dsh-connect-workbuddy 1.3.0 → 2.0.0

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.
@@ -5,998 +5,1306 @@ import { dirname, join } from "node:path";
5
5
  import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
6
6
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
7
7
  import { execFileSync } from "node:child_process";
8
- //#region src/auth.ts
8
+ //#region src/upstream.ts
9
+ const CN_CHAT_BASE = "https://copilot.tencent.com";
10
+ const CN_BILLING_BASE = "https://www.codebuddy.cn";
11
+ const GLOBAL_BASE = "https://www.workbuddy.ai";
9
12
  /**
10
- * WorkBuddy credential resolution.
11
- *
12
- * 参考:corrinehu/dsh-workbuddy-connect(MIT,Copyright (c) 2026 Corrine Hu)
13
- * — 桌面端 auth 文件只读、刷新结果写入 $DSH_HOME 自有副本、双凭据取
14
- * 到期更晚者、按需刷新(5 分钟余量)与单飞去重、刷新失败但 token
15
- * 未过期则继续沿用旧 token。这些机制已在该项目验证,此处沿用。
16
- * 改动:原版只解析单个 `workbuddy-desktop.info`。WorkBuddy 桌面端在
17
- * 同一 auth 目录留下带时间戳的备份文件(`workbuddy-desktop.<stamp>.info`),
18
- * 实测这些文件各自持有不同账号的可用凭据(本机 6 个文件 → 2 个账号)。
19
- * 本实现改为扫描整个 auth 目录,按 uin 去重为多个可选账号。跟随 App
20
- * 当前登录(live 文件)仍是默认行为;用户显式选择的账号被严格绑定,
21
- * 不因积分多少而切换,失效时也不会静默改选其他账号。
22
- *
23
- * @module dsh-connect-workbuddy/auth
13
+ * Model-catalog path used by the CN region (and the global fallback). The CN
14
+ * gateway answers it with the same bytes as its legacy
15
+ * `/console/enterprises/personal/models` alias. See {@link GLOBAL_CONFIG_PATH}
16
+ * for why the international region reads a different document.
24
17
  */
25
- /** Basename of the plugin-owned credential copy inside the Harness home. */
26
- const WORKBUDDY_AUTH_FILENAME = ".workbuddy-auth.json";
27
- /** Env variable that overrides the desktop auth-file location. */
28
- const WORKBUDDY_AUTH_FILE_ENV = "WORKBUDDY_AUTH_FILE";
29
- /** Basename of the live WorkBuddy desktop auth file. */
30
- const WORKBUDDY_LIVE_FILENAME = "workbuddy-desktop.info";
31
- /** Current on-disk format of the plugin-owned copy; readers reject others. */
32
- const OWN_FORMAT_VERSION = 1;
33
- /** Plugin-owned copy path inside the Harness home. */
34
- function workbuddyOwnAuthPath() {
35
- return join(resolveDshHome(), WORKBUDDY_AUTH_FILENAME);
36
- }
18
+ const MODELS_CATALOG_PATH = "/v2/enterprises/personal/models";
37
19
  /**
38
- * Platform-default directories holding the WorkBuddy desktop app's auth file.
20
+ * Remote product-config path on the global gateway. This is the document the
21
+ * desktop channel receives; it is the only source that lists the account's
22
+ * full international chat roster (see {@link DESKTOP_UA}).
23
+ */
24
+ const GLOBAL_CONFIG_PATH = "/v3/config";
25
+ const CLIENT_UA = "CLI/2.63.2 CodeBuddy/2.63.2";
26
+ /**
27
+ * User agent of the WorkBuddy desktop app.
39
28
  *
40
- * Windows and Linux prefer the OS-issued env location and fall back to the
41
- * home-derived convention when it is unset, so a redirected profile (OneDrive
42
- * folder backup, enterprise policy) still resolves. macOS has no equivalent
43
- * env variable; the single Application Support path is used as-is.
29
+ * The config service serves a DIFFERENT product configuration per client
30
+ * channel, selected by this product token — the version suffix is ignored
31
+ * (`WorkBuddy/5.5.2`, `WorkBuddy/1.0.0` and a bare `WorkBuddy` answer
32
+ * identically). On the INTERNATIONAL gateway the split decides which models
33
+ * exist at all:
44
34
  *
45
- * `platform`, `home`, and `env` are injectable so the platform branches are
46
- * testable on any host without touching a real machine.
35
+ * - CLI channel (`CLI/… CodeBuddy/…`) → 35 models that OMIT
36
+ * `deepseek-v4.1-flash` and `gpt-6-astra`, even though both are perfectly
37
+ * chat-usable (verified: `deepseek-v4.1-flash` streams HTTP 200 and is
38
+ * billed `x0.00`);
39
+ * - desktop channel → the account's real 20-model chat roster including both.
40
+ *
41
+ * The plugin emulates the CLI channel for CHAT but reads the desktop channel's
42
+ * configuration to learn the account's actual model list. The CN gateway needs
43
+ * no such switch: its desktop config carries no `cli` agent roster at all, so
44
+ * CN keeps reading the shared `/v2/enterprises/personal/models` path.
47
45
  */
48
- function defaultDesktopAuthDirs(platform = process.platform, home = homedir(), env = process.env) {
49
- if (platform === "darwin") return [join(home, "Library", "Application Support", "CodeBuddyExtension", "Data", "Public", "auth")];
50
- if (platform === "win32") {
51
- const local = nonEmptyEnv(env["LOCALAPPDATA"]) ?? join(home, "AppData", "Local");
52
- const roaming = nonEmptyEnv(env["APPDATA"]) ?? join(home, "AppData", "Roaming");
53
- return [join(local, "CodeBuddyExtension", "Data", "Public", "auth"), join(roaming, "CodeBuddyExtension", "Data", "Public", "auth")];
54
- }
55
- if (platform === "linux") {
56
- const config = nonEmptyEnv(env["XDG_CONFIG_HOME"]) ?? join(home, ".config");
57
- return [join(config, "CodeBuddyExtension", "Data", "Public", "auth")];
58
- }
59
- return [];
46
+ const DESKTOP_UA = "WorkBuddy/5.5.2";
47
+ const JSON_TIMEOUT_MS = 3e4;
48
+ const ERROR_BODY_LIMIT = 4096;
49
+ /** Insufficient-credit markers, ASCII lowercase plus the original Chinese. */
50
+ const HARD_CREDIT_MARKERS = [
51
+ "insufficient credit",
52
+ "no credit",
53
+ "credit exhausted",
54
+ "out of credit",
55
+ "quota exceeded",
56
+ "quota exhaust",
57
+ "payment required",
58
+ "credit not enough",
59
+ "not enough credit",
60
+ "积分不足",
61
+ "额度不足",
62
+ "余额不足",
63
+ "积分用完",
64
+ "额度用尽",
65
+ "没有积分"
66
+ ];
67
+ /** Session-invalidation markers that mean "sign in again in the WorkBuddy app". */
68
+ const SESSION_DEAD_MARKERS = ["Offline user session not found", "12153"];
69
+ /** Classify an upstream failure from its HTTP status and body excerpt. */
70
+ function classifyUpstreamError(status, body) {
71
+ if (status === 402) return "hard_credit";
72
+ const lower = body.toLowerCase();
73
+ for (const marker of HARD_CREDIT_MARKERS) if (lower.includes(marker.toLowerCase()) || body.includes(marker)) return "hard_credit";
74
+ for (const marker of SESSION_DEAD_MARKERS) if (body.includes(marker)) return "session_dead";
75
+ if (status === 429) return "soft_rate";
76
+ if (status === 404) return "not_found";
77
+ if (status >= 500) return "server";
78
+ if (status >= 400) return "client";
79
+ return "client";
60
80
  }
61
- /** A non-empty, trimmed env value, or undefined when unset/blank. */
62
- function nonEmptyEnv(value) {
63
- return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
81
+ /** Region for a login domain; an empty domain means CN (matching upstream tooling). */
82
+ function regionOf(domain) {
83
+ const lowered = domain.trim().toLowerCase();
84
+ if (lowered === "workbuddy.ai" || lowered.endsWith(".workbuddy.ai")) return "global";
85
+ return "cn";
64
86
  }
65
- /** The live auth file's platform candidates, in probe order. */
66
- function defaultDesktopAuthCandidates() {
67
- return defaultDesktopAuthDirs().map((dir) => join(dir, WORKBUDDY_LIVE_FILENAME));
87
+ function chatBase(credential) {
88
+ return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_CHAT_BASE;
68
89
  }
69
- /** First platform-default candidate; see {@link defaultDesktopAuthCandidates}. */
70
- function defaultDesktopAuthPath() {
71
- return defaultDesktopAuthCandidates()[0];
90
+ function billingBase(credential) {
91
+ return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
72
92
  }
73
- /** Normalize an expiry that may arrive in seconds or milliseconds. */
74
- function expiryToMs(value) {
75
- if (value <= 0) return 0;
76
- return value > 0xe8d4a51000 ? value : value * 1e3;
93
+ function originReferer(credential) {
94
+ return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
77
95
  }
78
- function optionalString(value) {
79
- return typeof value === "string" && value !== "" ? value : void 0;
96
+ /** Headers every upstream request shares. */
97
+ function commonHeaders(credential) {
98
+ return {
99
+ "Accept": "application/json, text/plain, */*",
100
+ "X-Requested-With": "XMLHttpRequest",
101
+ "Origin": originReferer(credential),
102
+ "Referer": `${originReferer(credential)}/`,
103
+ "User-Agent": CLIENT_UA
104
+ };
105
+ }
106
+ /** Chat request headers, including the X-No-* conventions the official CLI uses. */
107
+ function chatHeaders(credential) {
108
+ return {
109
+ ...commonHeaders(credential),
110
+ "Content-Type": "application/json",
111
+ ...credential.uid === "" ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
112
+ ...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
113
+ ...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
114
+ "X-Product": "SaaS"
115
+ };
116
+ }
117
+ /** Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else. */
118
+ function refreshHeaders(credential) {
119
+ const headers = {
120
+ ...commonHeaders(credential),
121
+ "X-Refresh-Token": credential.refreshToken,
122
+ "X-Auth-Refresh-Source": "workbuddy"
123
+ };
124
+ if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") headers["X-Enterprise-Id"] = credential.enterpriseId;
125
+ return headers;
126
+ }
127
+ /** Billing request headers. */
128
+ function billingHeaders(credential) {
129
+ const headers = {
130
+ "Authorization": `Bearer ${credential.accessToken}`,
131
+ "Accept": "application/json",
132
+ "Content-Type": "application/json"
133
+ };
134
+ if (credential.uid !== "") headers["X-User-Id"] = credential.uid;
135
+ if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") {
136
+ headers["X-Enterprise-Id"] = credential.enterpriseId;
137
+ headers["X-Tenant-Id"] = credential.enterpriseId;
138
+ }
139
+ if (credential.domain !== "") headers["X-Domain"] = credential.domain;
140
+ return headers;
80
141
  }
81
142
  /**
82
- * Parse a WorkBuddy auth document in either on-disk shape: the plugin OAuth
83
- * nested form `{"auth":{...},"account":{...}}` and the flat panel form.
84
- * Returns undefined when the document carries no access token.
143
+ * Normalize an OpenAI chat-completions body for the WorkBuddy upstream:
144
+ * force `stream: true` (the upstream rejects non-streaming) and flatten
145
+ * `tool_choice` (the upstream's field is a string; object forms return 400).
85
146
  */
86
- function parseWorkBuddyAuth(text, filePath) {
147
+ function prepareChatBody(source) {
148
+ let body;
149
+ try {
150
+ body = JSON.parse(source);
151
+ } catch {
152
+ return source;
153
+ }
154
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return source;
155
+ const obj = body;
156
+ obj["stream"] = true;
157
+ if (Array.isArray(obj["messages"])) for (const value of obj["messages"]) {
158
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
159
+ const message = value;
160
+ if (message["role"] === "developer") message["role"] = "system";
161
+ }
162
+ normalizeToolChoice(obj);
163
+ return JSON.stringify(obj);
164
+ }
165
+ /** Rewrite OpenAI `tool_choice` spellings into the upstream's string form. */
166
+ function normalizeToolChoice(obj) {
167
+ const suppress = () => {
168
+ delete obj["tools"];
169
+ delete obj["functions"];
170
+ };
171
+ if (!("tool_choice" in obj)) return;
172
+ const choice = obj["tool_choice"];
173
+ if (typeof choice === "string") {
174
+ if (choice.trim().toLowerCase() === "none") {
175
+ delete obj["tool_choice"];
176
+ suppress();
177
+ }
178
+ return;
179
+ }
180
+ if (typeof choice === "object" && choice !== null && !Array.isArray(choice)) {
181
+ const wrapped = choice;
182
+ const type = typeof wrapped["type"] === "string" ? wrapped["type"].trim().toLowerCase() : "";
183
+ if (type === "none") {
184
+ delete obj["tool_choice"];
185
+ suppress();
186
+ } else if (type === "auto" || type === "required") obj["tool_choice"] = type;
187
+ else if (type === "function") {
188
+ const fn = typeof wrapped["function"] === "object" && wrapped["function"] !== null ? wrapped["function"] : void 0;
189
+ let name = typeof fn?.["name"] === "string" ? fn["name"] : "";
190
+ if (name === "" && typeof wrapped["name"] === "string") name = wrapped["name"];
191
+ name = name.trim();
192
+ obj["tool_choice"] = name !== "" ? name : "auto";
193
+ } else delete obj["tool_choice"];
194
+ return;
195
+ }
196
+ delete obj["tool_choice"];
197
+ }
198
+ async function readEnvelope(response) {
199
+ const text = await response.text();
87
200
  let parsed;
88
201
  try {
89
202
  parsed = JSON.parse(text);
90
203
  } catch {
91
- return;
204
+ throw new Error(`workbuddy upstream returned non-JSON (http ${response.status}): ${text.slice(0, 160)}`);
92
205
  }
93
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
206
+ if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
94
207
  const document = parsed;
95
- let auth;
96
- let identity;
97
- if (typeof document["auth"] === "object" && document["auth"] !== null) {
98
- auth = document["auth"];
99
- identity = typeof document["account"] === "object" && document["account"] !== null ? document["account"] : {};
100
- } else {
101
- auth = document;
102
- identity = document;
103
- }
104
- const accessToken = typeof auth["accessToken"] === "string" ? auth["accessToken"] : "";
105
- if (accessToken === "") return void 0;
106
- const expiresAtMs = typeof auth["expiresAt"] === "number" ? expiryToMs(auth["expiresAt"]) : 0;
107
- const refreshExpiresAtMs = typeof auth["refreshExpiresAt"] === "number" ? expiryToMs(auth["refreshExpiresAt"]) : void 0;
108
- const enterpriseId = optionalString(identity["enterpriseId"]);
109
- const nickname = optionalString(identity["nickname"]);
110
- const uin = optionalString(identity["uin"]);
111
208
  return {
112
- accessToken,
113
- refreshToken: typeof auth["refreshToken"] === "string" ? auth["refreshToken"] : "",
114
- expiresAtMs,
115
- ...refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs },
116
- domain: optionalString(auth["domain"]) ?? "",
117
- uid: optionalString(identity["uid"]) ?? "",
118
- ...enterpriseId === void 0 ? {} : { enterpriseId },
119
- ...nickname === void 0 ? {} : { nickname },
120
- ...uin === void 0 ? {} : { uin },
121
- source: "desktop",
122
- filePath
209
+ code: typeof document["code"] === "number" ? document["code"] : 0,
210
+ msg: typeof document["msg"] === "string" ? document["msg"] : "",
211
+ data: "data" in document ? document["data"] : void 0
123
212
  };
124
213
  }
214
+ /** Fail an envelope whose business code is non-zero, classified like HTTP errors. */
215
+ function envelopeError(status, envelope) {
216
+ const kind = classifyUpstreamError(status, envelope.msg);
217
+ return /* @__PURE__ */ new Error(`workbuddy upstream ${kind} (http ${status}): ${envelope.msg.slice(0, 160)}`);
218
+ }
125
219
  /**
126
- * Rank two candidate files for the same account.
220
+ * Parse the upstream's `credits` string into a multiplier.
127
221
  *
128
- * The live `workbuddy-desktop.info` always wins: it is the app's current
129
- * sign-in, and the upstream revokes the tokens in the timestamped backups
130
- * even though their stored `expiresAt` is still in the future (observed on a
131
- * real machine — every backup claimed a 2027 expiry while only the live
132
- * file's token was accepted). Expiry is therefore only a tie-breaker among
133
- * backups, never the primary ordering.
134
- */
135
- function fileRank(path) {
136
- return authFileName(path) === WORKBUDDY_LIVE_FILENAME ? 0 : 1;
137
- }
138
- /**
139
- * Filename of a path regardless of the host separator: Windows paths use `\`
140
- * and this helper must keep working when a Windows path is compared on a
141
- * POSIX host (e.g. tests injecting a Windows-style auth dir).
142
- */
143
- function authFileName(path) {
144
- const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
145
- return separator === -1 ? path : path.slice(separator + 1);
146
- }
147
- /**
148
- * Stable account id. `uin` is the billing identity the upstream keys on and
149
- * survives across re-login; `uid` is the fallback for documents without one.
222
+ * Observed forms: `"x0.79 credits"`, `"x0.05"`, `"x0.00 credits"`,
223
+ * and absent. Unparsable values yield undefined rather than a guess — the
224
+ * card simply omits the rate instead of displaying a fabricated one.
150
225
  */
151
- function workbuddyAccountId(credential) {
152
- const stable = credential.uin ?? credential.uid ?? credential.nickname ?? "unknown";
153
- return createHash("sha256").update(`workbuddy\0${stable}`).digest("hex").slice(0, 24);
226
+ function parseCreditMultiplier(value) {
227
+ if (typeof value !== "string") return void 0;
228
+ const match = /x\s*([0-9]*\.?[0-9]+)/iu.exec(value);
229
+ if (match === null) return void 0;
230
+ const parsed = Number(match[1]);
231
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
154
232
  }
155
- /** Serialize the plugin-owned copy. */
156
- function ownDocument(credential, accountId) {
233
+ /** Parse the upstream's `reasoning` object; unknown shapes degrade to `{}`. */
234
+ function parseReasoning(value) {
235
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
236
+ const raw = value;
237
+ const supportedEfforts = Array.isArray(raw["supportedEfforts"]) ? raw["supportedEfforts"].filter((effort) => typeof effort === "string") : void 0;
238
+ const defaultEffort = typeof raw["defaultEffort"] === "string" ? raw["defaultEffort"] : void 0;
239
+ const canDisableThinking = typeof raw["canDisableThinking"] === "boolean" ? raw["canDisableThinking"] : void 0;
240
+ if (supportedEfforts === void 0 && defaultEffort === void 0 && canDisableThinking === void 0) return;
157
241
  return {
158
- version: OWN_FORMAT_VERSION,
159
- ...accountId === void 0 ? {} : { accountId },
160
- credential
242
+ ...supportedEfforts === void 0 || supportedEfforts.length === 0 ? {} : { supportedEfforts },
243
+ ...defaultEffort === void 0 ? {} : { defaultEffort },
244
+ ...canDisableThinking === void 0 ? {} : { canDisableThinking }
161
245
  };
162
246
  }
163
- /** Parse the plugin-owned copy; other versions and shapes are rejected. */
164
- function parseOwnDocument(text) {
165
- let parsed;
166
- try {
167
- parsed = JSON.parse(text);
168
- } catch {
169
- return;
170
- }
171
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
172
- const document = parsed;
173
- if (document["version"] !== OWN_FORMAT_VERSION) return void 0;
174
- if (typeof document["credential"] !== "object" || document["credential"] === null) return void 0;
175
- const credential = parseWorkBuddyAuth(JSON.stringify({ auth: document["credential"] }), workbuddyOwnAuthPath());
176
- if (credential === void 0) return void 0;
247
+ /** Parse one catalog entry; entries without usable token limits are dropped. */
248
+ function parseUpstreamModel(value) {
249
+ if (typeof value !== "object" || value === null) return void 0;
250
+ const raw = value;
251
+ const id = typeof raw["id"] === "string" ? raw["id"] : "";
252
+ if (id === "" || raw["disabled"] === true) return void 0;
253
+ const input = typeof raw["maxInputTokens"] === "number" ? raw["maxInputTokens"] : 0;
254
+ const output = typeof raw["maxOutputTokens"] === "number" ? raw["maxOutputTokens"] : 0;
255
+ if (input <= 0 || output <= 0) return void 0;
256
+ const name = typeof raw["name"] === "string" && raw["name"] !== "" ? raw["name"] : id;
257
+ const descriptionZh = typeof raw["descriptionZh"] === "string" && raw["descriptionZh"] !== "" ? raw["descriptionZh"] : void 0;
258
+ const descriptionEn = typeof raw["descriptionEn"] === "string" && raw["descriptionEn"] !== "" ? raw["descriptionEn"] : void 0;
259
+ const creditMultiplier = parseCreditMultiplier(raw["credits"]);
260
+ const reasoning = parseReasoning(raw["reasoning"]);
261
+ const supportsToolCall = typeof raw["supportsToolCall"] === "boolean" ? raw["supportsToolCall"] : void 0;
177
262
  return {
178
- ...credential,
179
- source: "dsh"
263
+ id,
264
+ name,
265
+ contextWindow: input,
266
+ maxTokens: output,
267
+ ...creditMultiplier === void 0 ? {} : { creditMultiplier },
268
+ ...reasoning === void 0 ? {} : { reasoning },
269
+ ...descriptionZh === void 0 ? {} : { descriptionZh },
270
+ ...descriptionEn === void 0 ? {} : { descriptionEn },
271
+ ...supportsToolCall === void 0 ? {} : { supportsToolCall }
180
272
  };
181
273
  }
182
- /** Whether a filesystem error reports an absent path. */
183
- function isENOENT(error) {
184
- return error?.code === "ENOENT";
185
- }
186
- /** Read one auth file, tolerating absence and unparsable content. */
187
- async function readAuthFile(path) {
188
- try {
189
- return parseWorkBuddyAuth(await readFile(path, "utf8"), path);
190
- } catch (error) {
191
- if (isENOENT(error)) return void 0;
192
- return;
193
- }
194
- }
195
274
  /**
196
- * Read-only credential store with demand-driven refresh and multi-account
197
- * discovery.
275
+ * Select the chat-capable models from a catalog-shaped document: parse every
276
+ * entry, then keep the `cli` agent's roster in its declared order.
198
277
  *
199
- * Refresh policy: refresh only when the access token is inside the margin
200
- * (or already expired), keep the refreshed credential in the plugin-owned
201
- * copy, and never write the desktop app's files. A failed refresh still
202
- * returns a not-yet-expired token so an unreachable refresh endpoint does
203
- * not take down a working session.
278
+ * Both the CN personal-models document and the global `/v3/config` document
279
+ * carry `models` plus an `agents` roster with the same entry shape, so one
280
+ * selector serves them. Without a usable `cli` roster the whole parsed catalog
281
+ * is exposed rather than nothing: the roster is an upstream detail that may
282
+ * change, and an empty answer would silently disarm the provider.
204
283
  */
205
- var WorkBuddyCredentialStore = class {
206
- refresh;
207
- refreshMarginMs;
208
- ownPath;
209
- authDirs;
210
- desktopPathOverride;
211
- accountId;
212
- inflight;
213
- constructor(options) {
214
- this.refresh = options.refresh;
215
- this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
216
- this.ownPath = options.ownPath ?? workbuddyOwnAuthPath();
217
- this.authDirs = options.authDirs;
218
- this.desktopPathOverride = options.desktopPath;
219
- }
220
- /** Repoint the desktop file or directory; applies on the next read. */
221
- setDesktopPath(path) {
222
- this.desktopPathOverride = path;
223
- this.inflight = void 0;
224
- }
225
- /** Select an account by id; tokens stay outside settings. */
226
- selectAccount(accountId) {
227
- this.accountId = accountId;
228
- this.inflight = void 0;
229
- }
230
- /** Selected account id, for diagnostics and route assembly. */
231
- selectedAccountId() {
232
- return this.accountId;
233
- }
234
- /** The auth-file path candidates, in probe order. */
235
- resolveDesktopCandidates() {
236
- const fromEnv = process.env[WORKBUDDY_AUTH_FILE_ENV];
237
- const explicit = this.desktopPathOverride ?? (fromEnv !== void 0 && fromEnv.trim() !== "" ? fromEnv : void 0);
238
- if (explicit !== void 0) return [explicit];
239
- return defaultDesktopAuthCandidates();
240
- }
241
- /** The resolved desktop auth-file path, for diagnostics. */
242
- desktopAuthPath() {
243
- return this.resolveDesktopCandidates()[0];
244
- }
245
- /** The plugin-owned copy path, for diagnostics. */
246
- ownAuthPath() {
247
- return this.ownPath;
284
+ function selectCliModels(rawModels, agents) {
285
+ const byId = /* @__PURE__ */ new Map();
286
+ for (const model of Array.isArray(rawModels) ? rawModels : []) {
287
+ const parsed = parseUpstreamModel(model);
288
+ if (parsed !== void 0) byId.set(parsed.id, parsed);
248
289
  }
249
- /**
250
- * Every auth file to scan: the live file plus the timestamped backups
251
- * WorkBuddy leaves beside it.
252
- *
253
- * An explicitly configured path pins the *directory*: its siblings are
254
- * still scanned, because a user who points the plugin at their auth file
255
- * expects account switching to work the same way it does on the default
256
- * path. Only the file ordering changes.
257
- *
258
- * A corrupt or signed-out file must never hide the others, so each read is
259
- * independent and failures are skipped rather than propagated.
260
- */
261
- async candidateFiles() {
262
- const explicitPath = this.desktopPathOverride ?? ((process.env["WORKBUDDY_AUTH_FILE"] ?? "").trim() !== "" ? process.env["WORKBUDDY_AUTH_FILE"] : void 0);
263
- const files = [];
264
- if (explicitPath !== void 0) {
265
- files.push(explicitPath);
266
- for (const backup of await this.backupsBeside(explicitPath)) files.push(backup);
267
- return files;
268
- }
269
- const dirs = this.authDirs ?? defaultDesktopAuthDirs();
270
- for (const dir of dirs) {
271
- const live = join(dir, WORKBUDDY_LIVE_FILENAME);
272
- files.push(live);
273
- for (const backup of await this.backupsBeside(live)) files.push(backup);
290
+ let cliIds;
291
+ for (const agent of Array.isArray(agents) ? agents : []) if (typeof agent === "object" && agent !== null) {
292
+ const wrapped = agent;
293
+ if (wrapped["name"] === "cli" && Array.isArray(wrapped["models"])) {
294
+ cliIds = wrapped["models"].filter((id) => typeof id === "string");
295
+ break;
274
296
  }
275
- return files;
276
297
  }
277
- /** Timestamped siblings of one auth file, newest first by filename. */
278
- async backupsBeside(path) {
279
- const dir = dirname(path);
280
- const base = path.slice(dir.length + 1);
298
+ const models = (cliIds !== void 0 && cliIds.length > 0 ? cliIds : [...byId.keys()]).map((id) => byId.get(id)).filter((model) => model !== void 0);
299
+ if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
300
+ return models;
301
+ }
302
+ /**
303
+ * Upstream HTTP client. One instance serves the whole plugin; requests take
304
+ * the credential explicitly so token refreshes apply on the next call.
305
+ */
306
+ var WorkBuddyUpstreamClient = class {
307
+ /** POST the chat endpoint; a successful answer is the raw SSE response. */
308
+ async chatStream(credential, bodyJson, signal) {
309
+ let response;
281
310
  try {
282
- return (await readdir(dir)).filter((name) => name !== base && name.endsWith(".info")).sort().reverse().map((name) => join(dir, name));
283
- } catch {
284
- return [];
311
+ response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
312
+ method: "POST",
313
+ headers: {
314
+ ...chatHeaders(credential),
315
+ "Authorization": `Bearer ${credential.accessToken}`
316
+ },
317
+ body: bodyJson,
318
+ ...signal === void 0 ? {} : { signal }
319
+ });
320
+ } catch (error) {
321
+ return {
322
+ ok: false,
323
+ status: 0,
324
+ kind: "server",
325
+ message: `transport error: ${String(error)}`
326
+ };
285
327
  }
328
+ if (response.ok) return {
329
+ ok: true,
330
+ response
331
+ };
332
+ const text = (await response.text()).slice(0, ERROR_BODY_LIMIT);
333
+ return {
334
+ ok: false,
335
+ status: response.status,
336
+ kind: classifyUpstreamError(response.status, text),
337
+ message: text
338
+ };
339
+ }
340
+ /** POST the token-refresh endpoint; the caller merges the outcome. */
341
+ async refreshToken(credential) {
342
+ const response = await fetch(`${chatBase(credential)}/v2/plugin/auth/token/refresh`, {
343
+ method: "POST",
344
+ headers: refreshHeaders(credential),
345
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
346
+ });
347
+ const envelope = await readEnvelope(response);
348
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
349
+ const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
350
+ const accessToken = typeof data["accessToken"] === "string" ? data["accessToken"] : "";
351
+ if (accessToken === "") throw new Error("workbuddy token refresh returned no accessToken; sign in again in the WorkBuddy app");
352
+ const outcome = { accessToken };
353
+ if (typeof data["refreshToken"] === "string" && data["refreshToken"] !== "") outcome.refreshToken = data["refreshToken"];
354
+ if (typeof data["expiresIn"] === "number" && data["expiresIn"] > 0) outcome.expiresInSec = data["expiresIn"];
355
+ if (typeof data["domain"] === "string" && data["domain"] !== "") outcome.domain = data["domain"];
356
+ return outcome;
286
357
  }
287
358
  /**
288
- * Read every local credential, deduplicated by account id. Files are
289
- * probed newest-first, so the first entry for an account is its freshest.
359
+ * Read the model directory for the credential's region.
360
+ *
361
+ * The two regions expose their chat roster through different documents:
362
+ * CN answers `/v2/enterprises/personal/models`, while the global gateway's
363
+ * personal-models path returns HTTP 500 and the CLI channel's `/v3/config`
364
+ * omits chat-usable models — so global reads `/v3/config` as the desktop
365
+ * channel (see {@link DESKTOP_UA}). Both documents share the entry shape, so
366
+ * one parser serves them. No user-side toggle is involved: the region comes
367
+ * from the credential's `domain`.
290
368
  */
291
- async readAll() {
292
- const files = await this.candidateFiles();
293
- const byId = /* @__PURE__ */ new Map();
294
- for (const file of files) {
295
- const credential = await readAuthFile(file);
296
- if (credential === void 0) continue;
297
- const id = workbuddyAccountId(credential);
298
- const existing = byId.get(id);
299
- if (existing === void 0) {
300
- byId.set(id, credential);
301
- continue;
302
- }
303
- if (fileRank(credential.filePath) < fileRank(existing.filePath) || fileRank(credential.filePath) === fileRank(existing.filePath) && credential.expiresAtMs > existing.expiresAtMs) byId.set(id, credential);
369
+ async fetchModels(credential, signal) {
370
+ const timeout = signal ?? AbortSignal.timeout(JSON_TIMEOUT_MS);
371
+ if (regionOf(credential.domain) === "global") {
372
+ const response = await fetch(`${GLOBAL_BASE}${GLOBAL_CONFIG_PATH}`, {
373
+ headers: {
374
+ "Authorization": `Bearer ${credential.accessToken}`,
375
+ "Accept": "application/json",
376
+ ...credential.uid === "" ? {} : { "X-User-Id": credential.uid },
377
+ ...credential.domain === "" ? {} : { "X-Domain": credential.domain },
378
+ "X-Product": "SaaS",
379
+ "X-Requested-With": "XMLHttpRequest",
380
+ "Connection": "close",
381
+ "User-Agent": DESKTOP_UA
382
+ },
383
+ signal: timeout
384
+ });
385
+ const envelope = await readEnvelope(response);
386
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
387
+ const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
388
+ return selectCliModels(data["models"], data["agents"]);
304
389
  }
305
- const own = await this.readOwn();
306
- if (own !== void 0) {
307
- const id = workbuddyAccountId(own);
308
- const existing = byId.get(id);
309
- if (existing === void 0 || own.expiresAtMs > existing.expiresAtMs) byId.set(id, own);
310
- }
311
- return [...byId.values()];
312
- }
313
- /**
314
- * Default when no account is explicitly selected: the live sign-in, else the
315
- * freshest credential. Following the app's current sign-in is the documented
316
- * default behaviour; the backups exist so the user can switch explicitly.
317
- * This is NOT credit-seeking — it never reorders accounts to find one with
318
- * remaining credit.
319
- */
320
- preferred(credentials) {
321
- if (credentials.length === 0) return void 0;
322
- return credentials.reduce((best, credential) => {
323
- if (fileRank(credential.filePath) < fileRank(best.filePath)) return credential;
324
- if (fileRank(credential.filePath) === fileRank(best.filePath) && credential.expiresAtMs > best.expiresAtMs) return credential;
325
- return best;
390
+ const response = await fetch(`${chatBase(credential)}${MODELS_CATALOG_PATH}`, {
391
+ headers: {
392
+ "Authorization": `Bearer ${credential.accessToken}`,
393
+ "Accept": "application/json",
394
+ "Origin": originReferer(credential),
395
+ "Referer": `${originReferer(credential)}/`,
396
+ "User-Agent": CLIENT_UA
397
+ },
398
+ signal: timeout
326
399
  });
400
+ const envelope = await readEnvelope(response);
401
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
402
+ const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
403
+ return selectCliModels(data["models"], data["agents"]);
327
404
  }
328
- /** Token-free account list for the plugin card. */
329
- async accounts() {
330
- const credentials = await this.readAll();
331
- if (credentials.length === 0) return [];
332
- const selectedExists = this.accountId !== void 0 && credentials.some((credential) => workbuddyAccountId(credential) === this.accountId);
333
- const defaultSelected = this.preferred(credentials);
334
- return credentials.map((credential) => {
335
- const id = workbuddyAccountId(credential);
336
- return {
337
- id,
338
- accountName: credential.nickname ?? credential.uin ?? credential.uid,
339
- ...credential.uin === void 0 ? {} : { uin: credential.uin },
340
- domain: credential.domain,
341
- source: credential.source,
342
- tokenExpiresAtMs: credential.expiresAtMs,
343
- filePath: credential.filePath,
344
- selected: selectedExists ? id === this.accountId : credential === defaultSelected
345
- };
405
+ /** Query today's check-in status without changing account state. */
406
+ async fetchCheckinStatus(credential) {
407
+ const response = await fetch(`${billingBase(credential)}/v2/billing/meter/checkin-activity-status`, {
408
+ method: "POST",
409
+ headers: billingHeaders(credential),
410
+ body: "{}",
411
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
346
412
  });
413
+ const envelope = await readEnvelope(response);
414
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
415
+ const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
416
+ const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
417
+ return {
418
+ active: data["active"] === true,
419
+ todayCheckedIn: data["today_checked_in"] === true,
420
+ streakDays: numberField("streak_days"),
421
+ dailyCredit: numberField("daily_credit"),
422
+ todayCredit: numberField("today_credit"),
423
+ isStreakDay: data["is_streak_day"] === true,
424
+ nextStreakDay: numberField("next_streak_day"),
425
+ streakBonusDays: numberField("streak_bonus_days"),
426
+ streakBonusCredit: numberField("streak_bonus_credit"),
427
+ ...typeof data["claim_button_text"] === "string" && data["claim_button_text"] !== "" ? { claimButtonText: data["claim_button_text"] } : {}
428
+ };
347
429
  }
348
- /** The freshest stored credential for the current selection, no refresh. */
349
- async current() {
350
- const credentials = await this.readAll();
351
- if (this.accountId === void 0) return this.preferred(credentials);
352
- return credentials.find((credential) => workbuddyAccountId(credential) === this.accountId);
353
- }
354
- /** The credential to send upstream: {@link current}, refreshed on demand. */
355
- async resolve() {
356
- const credential = await this.current();
357
- if (credential === void 0) {
358
- const candidates = this.resolveDesktopCandidates();
359
- const desktop = candidates.length > 0 ? candidates.join(" or ") : "(no desktop path on this platform)";
360
- throw new Error(`workbuddy: no signed-in WorkBuddy account found; sign in once in the WorkBuddy desktop app (expected ${desktop} or ${WORKBUDDY_AUTH_FILE_ENV}), or refresh an existing session`);
361
- }
362
- if (!this.needsRefresh(credential)) return credential;
363
- this.inflight ??= this.refreshNow(credential).finally(() => {
364
- this.inflight = void 0;
430
+ /** Claim today's check-in reward. The browser route guards this mutation. */
431
+ async claimDailyCheckin(credential) {
432
+ const response = await fetch(`${billingBase(credential)}/v2/billing/meter/daily-checkin`, {
433
+ method: "POST",
434
+ headers: billingHeaders(credential),
435
+ body: "{}",
436
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
365
437
  });
366
- return this.inflight;
367
- }
368
- /** Read-only sign-in summary; never refreshes and never throws. */
369
- async status() {
370
- try {
371
- const credential = await this.current();
372
- if (credential === void 0) return { state: "signed-out" };
373
- return {
374
- state: "signed-in",
375
- expiresAtMs: credential.expiresAtMs,
376
- ...credential.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs: credential.refreshExpiresAtMs },
377
- ...credential.nickname === void 0 ? {} : { nickname: credential.nickname },
378
- ...credential.domain === "" ? {} : { domain: credential.domain },
379
- source: credential.source
380
- };
381
- } catch {
382
- return { state: "signed-out" };
383
- }
384
- }
385
- /** Remove the plugin-owned copy; the desktop files are untouched. */
386
- async logout() {
387
- await rm(this.ownPath, { force: true });
388
- await rm(`${this.ownPath}.lock`, { force: true });
389
- }
390
- needsRefresh(credential) {
391
- if (credential.expiresAtMs <= 0) return true;
392
- return Date.now() + this.refreshMarginMs >= credential.expiresAtMs;
393
- }
394
- async refreshNow(credential) {
395
- if (credential.refreshToken === "") {
396
- if (credential.expiresAtMs > Date.now() + 3e4) return credential;
397
- throw new Error("workbuddy: access token expired and no refresh token is stored; sign in again in the WorkBuddy desktop app");
398
- }
399
- try {
400
- const outcome = await this.refresh(credential);
401
- const refreshed = {
402
- ...credential,
403
- accessToken: outcome.accessToken,
404
- ...outcome.refreshToken === void 0 ? {} : { refreshToken: outcome.refreshToken },
405
- expiresAtMs: outcome.expiresInSec !== void 0 ? Date.now() + outcome.expiresInSec * 1e3 : credential.expiresAtMs,
406
- ...outcome.domain === void 0 || outcome.domain === "" ? {} : { domain: outcome.domain },
407
- source: "dsh"
408
- };
409
- await this.saveOwn(refreshed);
410
- return refreshed;
411
- } catch (error) {
412
- if (credential.expiresAtMs > Date.now() + 3e4) return credential;
413
- throw new Error(`workbuddy: token refresh failed and the access token is expired (${String(error)}); open the WorkBuddy desktop app once to sign in again`);
414
- }
438
+ const envelope = await readEnvelope(response);
439
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
440
+ const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
441
+ const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
442
+ return {
443
+ credit: numberField("credit"),
444
+ streakDays: numberField("streak_days"),
445
+ isStreakDay: data["is_streak_day"] === true
446
+ };
415
447
  }
416
- async saveOwn(credential) {
417
- const accountId = workbuddyAccountId(credential);
418
- await withFileLock(this.ownPath, async () => {
419
- await writeFileAtomic(this.ownPath, `${JSON.stringify(ownDocument(credential, accountId), null, 2)}\n`, {
420
- mode: 384,
421
- dirMode: 448
422
- });
448
+ /**
449
+ * POST the billing endpoint for the remaining credit, keeping every package
450
+ * separate: the card groups monthly-cycle packages itself and lists the
451
+ * nearest-expiring one-off packages, so aggregation here would lose the
452
+ * dates it needs.
453
+ */
454
+ async fetchCredits(credential) {
455
+ const now = /* @__PURE__ */ new Date();
456
+ const format = (date) => [
457
+ date.getFullYear().toString().padStart(4, "0"),
458
+ (date.getMonth() + 1).toString().padStart(2, "0"),
459
+ date.getDate().toString().padStart(2, "0")
460
+ ].join("-") + " " + [
461
+ date.getHours().toString().padStart(2, "0"),
462
+ date.getMinutes().toString().padStart(2, "0"),
463
+ date.getSeconds().toString().padStart(2, "0")
464
+ ].join(":");
465
+ const response = await fetch(`${billingBase(credential)}/v2/billing/meter/get-user-resource`, {
466
+ method: "POST",
467
+ headers: billingHeaders(credential),
468
+ body: JSON.stringify({
469
+ PageNumber: 1,
470
+ PageSize: 100,
471
+ ProductCode: "p_tcaca",
472
+ Status: [0, 3],
473
+ PackageEndTimeRangeBegin: format(now),
474
+ PackageEndTimeRangeEnd: format(new Date(now.getTime() + 3185136e6))
475
+ }),
476
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
423
477
  });
424
- }
425
- async readOwn() {
426
- try {
427
- return parseOwnDocument(await readFile(this.ownPath, "utf8"));
428
- } catch {
429
- return;
478
+ const envelope = await readEnvelope(response);
479
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
480
+ const responseWrapper = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
481
+ const data = typeof responseWrapper["Response"] === "object" && responseWrapper["Response"] !== null ? responseWrapper["Response"] : {};
482
+ const inner = typeof data["Data"] === "object" && data["Data"] !== null ? data["Data"] : {};
483
+ const rawAccounts = Array.isArray(inner["Accounts"]) ? inner["Accounts"] : [];
484
+ let total = 0;
485
+ let nearestExpiryMs;
486
+ let expiringSoon = 0;
487
+ const SOON_MS = 2592e5;
488
+ const parseDate = (raw) => {
489
+ if (typeof raw === "number" && raw > 0xe8d4a51000) return raw;
490
+ if (typeof raw === "string" && raw !== "") {
491
+ const parsed = Date.parse(raw);
492
+ if (!Number.isNaN(parsed)) return parsed;
493
+ }
494
+ };
495
+ const packages = [];
496
+ for (const raw of rawAccounts) {
497
+ if (typeof raw !== "object" || raw === null) continue;
498
+ const account = raw;
499
+ const numberField = (key) => typeof account[key] === "number" ? account[key] : 0;
500
+ const monthly = numberField("CapacityType") === 4;
501
+ const size = monthly ? numberField("CycleCapacitySize") : numberField("CapacitySize");
502
+ const remain = monthly ? numberField("CycleCapacityRemain") : numberField("CapacityRemain");
503
+ const cappedRemain = remain < 0 ? 0 : remain;
504
+ const cycleEndMs = parseDate(account["CycleEndTime"]);
505
+ const expiresAtMs = monthly ? void 0 : parseDate(account["ExpiredTime"]) ?? cycleEndMs;
506
+ const refreshAtMs = monthly ? cycleEndMs === void 0 ? void 0 : cycleEndMs + 1e3 : void 0;
507
+ if (!monthly && (cappedRemain <= 0 || expiresAtMs !== void 0 && expiresAtMs <= Date.now())) continue;
508
+ total += cappedRemain;
509
+ const expiryMs = expiresAtMs;
510
+ if (expiryMs !== void 0) {
511
+ if (nearestExpiryMs === void 0 || expiryMs < nearestExpiryMs) nearestExpiryMs = expiryMs;
512
+ if (expiryMs - Date.now() <= SOON_MS) expiringSoon += cappedRemain;
513
+ }
514
+ packages.push({
515
+ packageName: typeof account["PackageName"] === "string" ? account["PackageName"] : "(unnamed)",
516
+ remain: cappedRemain,
517
+ size,
518
+ monthly,
519
+ ...refreshAtMs === void 0 ? {} : { refreshAtMs },
520
+ ...expiresAtMs === void 0 ? {} : { expiresAtMs }
521
+ });
430
522
  }
431
- }
432
- /** Whether any candidate file exists as a regular file; diagnostics only. */
433
- async desktopFilePresent() {
434
- for (const path of this.resolveDesktopCandidates()) try {
435
- if ((await stat(path)).isFile()) return true;
436
- } catch {}
437
- return false;
523
+ return {
524
+ total,
525
+ packages,
526
+ expiringSoon,
527
+ ...nearestExpiryMs === void 0 ? {} : { nearestExpiryMs }
528
+ };
438
529
  }
439
530
  };
440
531
  //#endregion
441
- //#region src/catalog.ts
532
+ //#region src/auth.ts
442
533
  /**
443
- * Static CLI models captured from the CN endpoint (2026-08-30). The upstream
444
- * refresh replaces this list at startup; it exists so the provider registers
445
- * with a usable catalog even while the first fetch is in flight or offline.
446
- */
447
- const FALLBACK_WORKBUDDY_MODELS = [
448
- {
449
- id: "auto",
450
- name: "Auto",
451
- contextWindow: 168e3,
452
- maxTokens: 32e3
453
- },
454
- {
455
- id: "hy3",
456
- name: "Hy3",
457
- contextWindow: 192e3,
458
- maxTokens: 64e3
459
- },
460
- {
461
- id: "glm-5v-turbo",
462
- name: "GLM-5v-Turbo",
463
- contextWindow: 2e5,
464
- maxTokens: 64e3
465
- },
466
- {
467
- id: "glm-5.3",
468
- name: "GLM-5.3",
469
- contextWindow: 1e6,
470
- maxTokens: 48e3
471
- },
472
- {
473
- id: "glm-5.2",
474
- name: "GLM-5.2",
475
- contextWindow: 1e6,
476
- maxTokens: 48e3
477
- },
478
- {
479
- id: "glm-5.1",
480
- name: "GLM-5.1",
481
- contextWindow: 2e5,
482
- maxTokens: 48e3
483
- },
484
- {
485
- id: "minimax-m3",
486
- name: "MiniMax-M3",
487
- contextWindow: 512e3,
488
- maxTokens: 128e3
489
- },
490
- {
491
- id: "kimi-k3-1",
492
- name: "Kimi-K3",
493
- contextWindow: 1e6,
494
- maxTokens: 32e3
495
- },
496
- {
497
- id: "kimi-k2.7",
498
- name: "Kimi-K2.7-Code",
499
- contextWindow: 256e3,
500
- maxTokens: 32e3
501
- },
502
- {
503
- id: "kimi-k2.6",
504
- name: "Kimi-K2.6",
505
- contextWindow: 256e3,
506
- maxTokens: 32e3
507
- },
508
- {
509
- id: "deepseek-v4-flash",
510
- name: "Deepseek-V4-Flash",
511
- contextWindow: 1e6,
512
- maxTokens: 5e4
513
- },
514
- {
515
- id: "deepseek-v4-pro",
516
- name: "Deepseek-V4-Pro",
517
- contextWindow: 1e6,
518
- maxTokens: 5e4
519
- }
520
- ];
521
- /** Apply the saved local DSH budget; models above 200K default to 200K. */
522
- function applyContextBudgets(catalog, budgets = {}) {
523
- return catalog.map((model) => ({
524
- ...model,
525
- contextWindow: model.contextWindow > 2e5 ? Math.min(model.contextWindow, budgets[model.id] ?? 2e5) : model.contextWindow
526
- }));
534
+ * WorkBuddy credential resolution.
535
+ *
536
+ * 参考:corrinehu/dsh-workbuddy-connect(MIT,Copyright (c) 2026 Corrine Hu)
537
+ * — 桌面端 auth 文件只读、刷新结果写入 $DSH_HOME 自有副本、双凭据取
538
+ * 到期更晚者、按需刷新(5 分钟余量)与单飞去重、刷新失败但 token
539
+ * 未过期则继续沿用旧 token。这些机制已在该项目验证,此处沿用。
540
+ * 改动:原版只解析单个 `workbuddy-desktop.info`。WorkBuddy 桌面端在
541
+ * 同一 auth 目录留下带时间戳的备份文件(`workbuddy-desktop.<stamp>.info`),
542
+ * 实测这些文件各自持有不同账号的可用凭据(本机 6 个文件 → 2 个账号)。
543
+ * 本实现改为扫描整个 auth 目录,按 uin 去重为多个可选账号。跟随 App
544
+ * 当前登录(live 文件)仍是默认行为;用户显式选择的账号被严格绑定,
545
+ * 不因积分多少而切换,失效时也不会静默改选其他账号。
546
+ * 另:store 可按区域(cn | global)限定可见账号 —— 国内版与国际版各持
547
+ * 一个 store,账号、刷新、选择完全隔离;插件自有刷新副本也按区域分
548
+ * 文件(`.workbuddy-auth.<region>.json`),双账号同时在线互不覆盖,
549
+ * 旧的单文件 `.workbuddy-auth.json` 作为迁移源保留读取。
550
+ *
551
+ * @module dsh-connect-workbuddy/auth
552
+ */
553
+ /** Legacy single-copy basename (pre-dual-provider); kept as migration source. */
554
+ const WORKBUDDY_AUTH_FILENAME = ".workbuddy-auth.json";
555
+ /** Env variable that overrides the desktop auth-file location. */
556
+ const WORKBUDDY_AUTH_FILE_ENV = "WORKBUDDY_AUTH_FILE";
557
+ /** Basename of the live WorkBuddy desktop auth file. */
558
+ const WORKBUDDY_LIVE_FILENAME = "workbuddy-desktop.info";
559
+ /** Prefix of the plugin-owned per-region credential copies. */
560
+ const WORKBUDDY_OWN_PREFIX = ".workbuddy-auth";
561
+ /** Current on-disk format of the plugin-owned copy; readers reject others. */
562
+ const OWN_FORMAT_VERSION = 1;
563
+ /**
564
+ * Plugin-owned copy path for one region inside the Harness home. Each
565
+ * region's store refreshes into its own file so two simultaneously signed-in
566
+ * regions never overwrite each other's refreshed token.
567
+ */
568
+ function workbuddyOwnAuthPath(region) {
569
+ return join(resolveDshHome(), `${WORKBUDDY_OWN_PREFIX}.${region}.json`);
527
570
  }
528
- function deriveCatalog(catalog, enabled, budgets = {}) {
529
- return applyContextBudgets(enabled.size === 0 ? catalog : catalog.filter((model) => enabled.has(model.id)), budgets);
571
+ /**
572
+ * Pre-dual-provider single-copy path. Still read as a migration source (a
573
+ * legacy credential serves the region it belongs to until that region's own
574
+ * first refresh writes the per-region file), and removed by `logout`.
575
+ */
576
+ function legacyWorkbuddyOwnAuthPath() {
577
+ return join(resolveDshHome(), WORKBUDDY_AUTH_FILENAME);
530
578
  }
531
- /** Mutable catalog shared by the shim's `/v1/models` and the adapter. */
532
- var WorkBuddyCatalog = class {
533
- models = FALLBACK_WORKBUDDY_MODELS;
534
- /** Current entries; the fallback list until the upstream answer lands. */
535
- current() {
536
- return this.models;
579
+ /**
580
+ * Platform-default directories holding the WorkBuddy desktop app's auth file.
581
+ *
582
+ * Windows and Linux prefer the OS-issued env location and fall back to the
583
+ * home-derived convention when it is unset, so a redirected profile (OneDrive
584
+ * folder backup, enterprise policy) still resolves. macOS has no equivalent
585
+ * env variable; the single Application Support path is used as-is.
586
+ *
587
+ * `platform`, `home`, and `env` are injectable so the platform branches are
588
+ * testable on any host without touching a real machine.
589
+ */
590
+ function defaultDesktopAuthDirs(platform = process.platform, home = homedir(), env = process.env) {
591
+ if (platform === "darwin") return [join(home, "Library", "Application Support", "CodeBuddyExtension", "Data", "Public", "auth")];
592
+ if (platform === "win32") {
593
+ const local = nonEmptyEnv(env["LOCALAPPDATA"]) ?? join(home, "AppData", "Local");
594
+ const roaming = nonEmptyEnv(env["APPDATA"]) ?? join(home, "AppData", "Roaming");
595
+ return [join(local, "CodeBuddyExtension", "Data", "Public", "auth"), join(roaming, "CodeBuddyExtension", "Data", "Public", "auth")];
537
596
  }
538
- /** Replace the list; callers invalidate their adapter snapshot after this. */
539
- set(models) {
540
- if (models.length === 0) throw new Error("workbuddy model catalog cannot be empty");
541
- this.models = models.map((model) => ({ ...model }));
597
+ if (platform === "linux") {
598
+ const config = nonEmptyEnv(env["XDG_CONFIG_HOME"]) ?? join(home, ".config");
599
+ return [join(config, "CodeBuddyExtension", "Data", "Public", "auth")];
542
600
  }
543
- };
544
- //#endregion
545
- //#region src/upstream.ts
546
- const CN_CHAT_BASE = "https://copilot.tencent.com";
547
- const CN_BILLING_BASE = "https://www.codebuddy.cn";
548
- const GLOBAL_BASE = "https://www.workbuddy.ai";
549
- const CLIENT_UA = "CLI/2.63.2 CodeBuddy/2.63.2";
550
- const JSON_TIMEOUT_MS = 3e4;
551
- const ERROR_BODY_LIMIT = 4096;
552
- /** Insufficient-credit markers, ASCII lowercase plus the original Chinese. */
553
- const HARD_CREDIT_MARKERS = [
554
- "insufficient credit",
555
- "no credit",
556
- "credit exhausted",
557
- "out of credit",
558
- "quota exceeded",
559
- "quota exhaust",
560
- "payment required",
561
- "credit not enough",
562
- "not enough credit",
563
- "积分不足",
564
- "额度不足",
565
- "余额不足",
566
- "积分用完",
567
- "额度用尽",
568
- "没有积分"
569
- ];
570
- /** Session-invalidation markers that mean "sign in again in the WorkBuddy app". */
571
- const SESSION_DEAD_MARKERS = ["Offline user session not found", "12153"];
572
- /** Classify an upstream failure from its HTTP status and body excerpt. */
573
- function classifyUpstreamError(status, body) {
574
- if (status === 402) return "hard_credit";
575
- const lower = body.toLowerCase();
576
- for (const marker of HARD_CREDIT_MARKERS) if (lower.includes(marker.toLowerCase()) || body.includes(marker)) return "hard_credit";
577
- for (const marker of SESSION_DEAD_MARKERS) if (body.includes(marker)) return "session_dead";
578
- if (status === 429) return "soft_rate";
579
- if (status === 404) return "not_found";
580
- if (status >= 500) return "server";
581
- if (status >= 400) return "client";
582
- return "client";
583
- }
584
- /** Region for a login domain; an empty domain means CN (matching upstream tooling). */
585
- function regionOf(domain) {
586
- const lowered = domain.trim().toLowerCase();
587
- if (lowered === "workbuddy.ai" || lowered.endsWith(".workbuddy.ai")) return "global";
588
- return "cn";
589
- }
590
- function chatBase(credential) {
591
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_CHAT_BASE;
592
- }
593
- function billingBase(credential) {
594
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
601
+ return [];
595
602
  }
596
- function originReferer(credential) {
597
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
603
+ /** A non-empty, trimmed env value, or undefined when unset/blank. */
604
+ function nonEmptyEnv(value) {
605
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
598
606
  }
599
- /** Headers every upstream request shares. */
600
- function commonHeaders(credential) {
601
- return {
602
- "Accept": "application/json, text/plain, */*",
603
- "X-Requested-With": "XMLHttpRequest",
604
- "Origin": originReferer(credential),
605
- "Referer": `${originReferer(credential)}/`,
606
- "User-Agent": CLIENT_UA
607
- };
607
+ /** The live auth file's platform candidates, in probe order. */
608
+ function defaultDesktopAuthCandidates() {
609
+ return defaultDesktopAuthDirs().map((dir) => join(dir, WORKBUDDY_LIVE_FILENAME));
608
610
  }
609
- /** Chat request headers, including the X-No-* conventions the official CLI uses. */
610
- function chatHeaders(credential) {
611
- return {
612
- ...commonHeaders(credential),
613
- "Content-Type": "application/json",
614
- ...credential.uid === "" ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
615
- ...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
616
- ...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
617
- "X-Product": "SaaS"
618
- };
611
+ /** First platform-default candidate; see {@link defaultDesktopAuthCandidates}. */
612
+ function defaultDesktopAuthPath() {
613
+ return defaultDesktopAuthCandidates()[0];
619
614
  }
620
- /** Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else. */
621
- function refreshHeaders(credential) {
622
- const headers = {
623
- ...commonHeaders(credential),
624
- "X-Refresh-Token": credential.refreshToken,
625
- "X-Auth-Refresh-Source": "workbuddy"
626
- };
627
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") headers["X-Enterprise-Id"] = credential.enterpriseId;
628
- return headers;
615
+ /** Normalize an expiry that may arrive in seconds or milliseconds. */
616
+ function expiryToMs(value) {
617
+ if (value <= 0) return 0;
618
+ return value > 0xe8d4a51000 ? value : value * 1e3;
629
619
  }
630
- /** Billing request headers. */
631
- function billingHeaders(credential) {
632
- const headers = {
633
- "Authorization": `Bearer ${credential.accessToken}`,
634
- "Accept": "application/json",
635
- "Content-Type": "application/json"
636
- };
637
- if (credential.uid !== "") headers["X-User-Id"] = credential.uid;
638
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") {
639
- headers["X-Enterprise-Id"] = credential.enterpriseId;
640
- headers["X-Tenant-Id"] = credential.enterpriseId;
641
- }
642
- if (credential.domain !== "") headers["X-Domain"] = credential.domain;
643
- return headers;
620
+ function optionalString(value) {
621
+ return typeof value === "string" && value !== "" ? value : void 0;
644
622
  }
645
623
  /**
646
- * Normalize an OpenAI chat-completions body for the WorkBuddy upstream:
647
- * force `stream: true` (the upstream rejects non-streaming) and flatten
648
- * `tool_choice` (the upstream's field is a string; object forms return 400).
624
+ * Parse a WorkBuddy auth document in either on-disk shape: the plugin OAuth
625
+ * nested form `{"auth":{...},"account":{...}}` and the flat panel form.
626
+ * Returns undefined when the document carries no access token.
649
627
  */
650
- function prepareChatBody(source) {
651
- let body;
628
+ function parseWorkBuddyAuth(text, filePath) {
629
+ let parsed;
652
630
  try {
653
- body = JSON.parse(source);
631
+ parsed = JSON.parse(text);
654
632
  } catch {
655
- return source;
633
+ return;
656
634
  }
657
- if (typeof body !== "object" || body === null || Array.isArray(body)) return source;
658
- const obj = body;
659
- obj["stream"] = true;
660
- if (Array.isArray(obj["messages"])) for (const value of obj["messages"]) {
661
- if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
662
- const message = value;
663
- if (message["role"] === "developer") message["role"] = "system";
635
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
636
+ const document = parsed;
637
+ let auth;
638
+ let identity;
639
+ if (typeof document["auth"] === "object" && document["auth"] !== null) {
640
+ auth = document["auth"];
641
+ identity = typeof document["account"] === "object" && document["account"] !== null ? document["account"] : {};
642
+ } else {
643
+ auth = document;
644
+ identity = document;
664
645
  }
665
- normalizeToolChoice(obj);
666
- return JSON.stringify(obj);
646
+ const accessToken = typeof auth["accessToken"] === "string" ? auth["accessToken"] : "";
647
+ if (accessToken === "") return void 0;
648
+ const expiresAtMs = typeof auth["expiresAt"] === "number" ? expiryToMs(auth["expiresAt"]) : 0;
649
+ const refreshExpiresAtMs = typeof auth["refreshExpiresAt"] === "number" ? expiryToMs(auth["refreshExpiresAt"]) : void 0;
650
+ const enterpriseId = optionalString(identity["enterpriseId"]);
651
+ const nickname = optionalString(identity["nickname"]);
652
+ const uin = optionalString(identity["uin"]);
653
+ return {
654
+ accessToken,
655
+ refreshToken: typeof auth["refreshToken"] === "string" ? auth["refreshToken"] : "",
656
+ expiresAtMs,
657
+ ...refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs },
658
+ domain: optionalString(auth["domain"]) ?? "",
659
+ uid: optionalString(identity["uid"]) ?? "",
660
+ ...enterpriseId === void 0 ? {} : { enterpriseId },
661
+ ...nickname === void 0 ? {} : { nickname },
662
+ ...uin === void 0 ? {} : { uin },
663
+ source: "desktop",
664
+ filePath
665
+ };
667
666
  }
668
- /** Rewrite OpenAI `tool_choice` spellings into the upstream's string form. */
669
- function normalizeToolChoice(obj) {
670
- const suppress = () => {
671
- delete obj["tools"];
672
- delete obj["functions"];
667
+ /**
668
+ * Rank two candidate files for the same account.
669
+ *
670
+ * The live `workbuddy-desktop.info` always wins: it is the app's current
671
+ * sign-in, and the upstream revokes the tokens in the timestamped backups
672
+ * even though their stored `expiresAt` is still in the future (observed on a
673
+ * real machine — every backup claimed a 2027 expiry while only the live
674
+ * file's token was accepted). Expiry is therefore only a tie-breaker among
675
+ * backups, never the primary ordering.
676
+ */
677
+ function fileRank(path) {
678
+ return authFileName(path) === WORKBUDDY_LIVE_FILENAME ? 0 : 1;
679
+ }
680
+ /**
681
+ * Filename of a path regardless of the host separator: Windows paths use `\`
682
+ * and this helper must keep working when a Windows path is compared on a
683
+ * POSIX host (e.g. tests injecting a Windows-style auth dir).
684
+ */
685
+ function authFileName(path) {
686
+ const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
687
+ return separator === -1 ? path : path.slice(separator + 1);
688
+ }
689
+ /**
690
+ * Stable account id. `uin` is the billing identity the upstream keys on and
691
+ * survives across re-login; `uid` is the fallback for documents without one.
692
+ */
693
+ function workbuddyAccountId(credential) {
694
+ const stable = credential.uin ?? credential.uid ?? credential.nickname ?? "unknown";
695
+ return createHash("sha256").update(`workbuddy\0${stable}`).digest("hex").slice(0, 24);
696
+ }
697
+ /** Serialize the plugin-owned copy. */
698
+ function ownDocument(credential, accountId) {
699
+ return {
700
+ version: OWN_FORMAT_VERSION,
701
+ ...accountId === void 0 ? {} : { accountId },
702
+ credential
673
703
  };
674
- if (!("tool_choice" in obj)) return;
675
- const choice = obj["tool_choice"];
676
- if (typeof choice === "string") {
677
- if (choice.trim().toLowerCase() === "none") {
678
- delete obj["tool_choice"];
679
- suppress();
680
- }
681
- return;
682
- }
683
- if (typeof choice === "object" && choice !== null && !Array.isArray(choice)) {
684
- const wrapped = choice;
685
- const type = typeof wrapped["type"] === "string" ? wrapped["type"].trim().toLowerCase() : "";
686
- if (type === "none") {
687
- delete obj["tool_choice"];
688
- suppress();
689
- } else if (type === "auto" || type === "required") obj["tool_choice"] = type;
690
- else if (type === "function") {
691
- const fn = typeof wrapped["function"] === "object" && wrapped["function"] !== null ? wrapped["function"] : void 0;
692
- let name = typeof fn?.["name"] === "string" ? fn["name"] : "";
693
- if (name === "" && typeof wrapped["name"] === "string") name = wrapped["name"];
694
- name = name.trim();
695
- obj["tool_choice"] = name !== "" ? name : "auto";
696
- } else delete obj["tool_choice"];
697
- return;
698
- }
699
- delete obj["tool_choice"];
700
704
  }
701
- async function readEnvelope(response) {
702
- const text = await response.text();
705
+ /** Parse the plugin-owned copy; other versions and shapes are rejected. */
706
+ function parseOwnDocument(text, filePath) {
703
707
  let parsed;
704
708
  try {
705
709
  parsed = JSON.parse(text);
706
710
  } catch {
707
- throw new Error(`workbuddy upstream returned non-JSON (http ${response.status}): ${text.slice(0, 160)}`);
711
+ return;
708
712
  }
709
- if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
713
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
710
714
  const document = parsed;
715
+ if (document["version"] !== OWN_FORMAT_VERSION) return void 0;
716
+ if (typeof document["credential"] !== "object" || document["credential"] === null) return void 0;
717
+ const credential = parseWorkBuddyAuth(JSON.stringify({ auth: document["credential"] }), filePath);
718
+ if (credential === void 0) return void 0;
711
719
  return {
712
- code: typeof document["code"] === "number" ? document["code"] : 0,
713
- msg: typeof document["msg"] === "string" ? document["msg"] : "",
714
- data: "data" in document ? document["data"] : void 0
720
+ ...credential,
721
+ source: "dsh"
715
722
  };
716
723
  }
717
- /** Fail an envelope whose business code is non-zero, classified like HTTP errors. */
718
- function envelopeError(status, envelope) {
719
- const kind = classifyUpstreamError(status, envelope.msg);
720
- return /* @__PURE__ */ new Error(`workbuddy upstream ${kind} (http ${status}): ${envelope.msg.slice(0, 160)}`);
721
- }
722
- /**
723
- * Parse the upstream's `credits` string into a multiplier.
724
- *
725
- * Observed forms: `"x0.79 credits"`, `"x0.05"`, `"x0.00 credits"`,
726
- * and absent. Unparsable values yield undefined rather than a guess — the
727
- * card simply omits the rate instead of displaying a fabricated one.
728
- */
729
- function parseCreditMultiplier(value) {
730
- if (typeof value !== "string") return void 0;
731
- const match = /x\s*([0-9]*\.?[0-9]+)/iu.exec(value);
732
- if (match === null) return void 0;
733
- const parsed = Number(match[1]);
734
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
735
- }
736
- /** Parse the upstream's `reasoning` object; unknown shapes degrade to `{}`. */
737
- function parseReasoning(value) {
738
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
739
- const raw = value;
740
- const supportedEfforts = Array.isArray(raw["supportedEfforts"]) ? raw["supportedEfforts"].filter((effort) => typeof effort === "string") : void 0;
741
- const defaultEffort = typeof raw["defaultEffort"] === "string" ? raw["defaultEffort"] : void 0;
742
- const canDisableThinking = typeof raw["canDisableThinking"] === "boolean" ? raw["canDisableThinking"] : void 0;
743
- if (supportedEfforts === void 0 && defaultEffort === void 0 && canDisableThinking === void 0) return;
744
- return {
745
- ...supportedEfforts === void 0 || supportedEfforts.length === 0 ? {} : { supportedEfforts },
746
- ...defaultEffort === void 0 ? {} : { defaultEffort },
747
- ...canDisableThinking === void 0 ? {} : { canDisableThinking }
748
- };
724
+ /** Whether a filesystem error reports an absent path. */
725
+ function isENOENT(error) {
726
+ return error?.code === "ENOENT";
749
727
  }
750
- /** Parse one catalog entry; entries without usable token limits are dropped. */
751
- function parseUpstreamModel(value) {
752
- if (typeof value !== "object" || value === null) return void 0;
753
- const raw = value;
754
- const id = typeof raw["id"] === "string" ? raw["id"] : "";
755
- if (id === "" || raw["disabled"] === true) return void 0;
756
- const input = typeof raw["maxInputTokens"] === "number" ? raw["maxInputTokens"] : 0;
757
- const output = typeof raw["maxOutputTokens"] === "number" ? raw["maxOutputTokens"] : 0;
758
- if (input <= 0 || output <= 0) return void 0;
759
- const name = typeof raw["name"] === "string" && raw["name"] !== "" ? raw["name"] : id;
760
- const descriptionZh = typeof raw["descriptionZh"] === "string" && raw["descriptionZh"] !== "" ? raw["descriptionZh"] : void 0;
761
- const descriptionEn = typeof raw["descriptionEn"] === "string" && raw["descriptionEn"] !== "" ? raw["descriptionEn"] : void 0;
762
- const creditMultiplier = parseCreditMultiplier(raw["credits"]);
763
- const reasoning = parseReasoning(raw["reasoning"]);
764
- const supportsToolCall = typeof raw["supportsToolCall"] === "boolean" ? raw["supportsToolCall"] : void 0;
765
- return {
766
- id,
767
- name,
768
- contextWindow: input,
769
- maxTokens: output,
770
- ...creditMultiplier === void 0 ? {} : { creditMultiplier },
771
- ...reasoning === void 0 ? {} : { reasoning },
772
- ...descriptionZh === void 0 ? {} : { descriptionZh },
773
- ...descriptionEn === void 0 ? {} : { descriptionEn },
774
- ...supportsToolCall === void 0 ? {} : { supportsToolCall }
775
- };
728
+ /** Read one auth file, tolerating absence and unparsable content. */
729
+ async function readAuthFile(path) {
730
+ try {
731
+ return parseWorkBuddyAuth(await readFile(path, "utf8"), path);
732
+ } catch (error) {
733
+ if (isENOENT(error)) return void 0;
734
+ return;
735
+ }
776
736
  }
777
737
  /**
778
- * Upstream HTTP client. One instance serves the whole plugin; requests take
779
- * the credential explicitly so token refreshes apply on the next call.
738
+ * Read-only credential store with demand-driven refresh and multi-account
739
+ * discovery.
740
+ *
741
+ * Refresh policy: refresh only when the access token is inside the margin
742
+ * (or already expired), keep the refreshed credential in the plugin-owned
743
+ * copy, and never write the desktop app's files. A failed refresh still
744
+ * returns a not-yet-expired token so an unreachable refresh endpoint does
745
+ * not take down a working session.
780
746
  */
781
- var WorkBuddyUpstreamClient = class {
782
- /** POST the chat endpoint; a successful answer is the raw SSE response. */
783
- async chatStream(credential, bodyJson, signal) {
784
- let response;
785
- try {
786
- response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
787
- method: "POST",
788
- headers: {
789
- ...chatHeaders(credential),
790
- "Authorization": `Bearer ${credential.accessToken}`
791
- },
792
- body: bodyJson,
793
- ...signal === void 0 ? {} : { signal }
794
- });
795
- } catch (error) {
796
- return {
797
- ok: false,
798
- status: 0,
799
- kind: "server",
800
- message: `transport error: ${String(error)}`
801
- };
802
- }
803
- if (response.ok) return {
804
- ok: true,
805
- response
806
- };
807
- const text = (await response.text()).slice(0, ERROR_BODY_LIMIT);
808
- return {
809
- ok: false,
810
- status: response.status,
811
- kind: classifyUpstreamError(response.status, text),
812
- message: text
813
- };
747
+ var WorkBuddyCredentialStore = class {
748
+ refresh;
749
+ refreshMarginMs;
750
+ region;
751
+ ownPathExplicit;
752
+ legacyOwnPath;
753
+ legacyOwnPathExplicit;
754
+ authDirs;
755
+ desktopPathOverride;
756
+ accountId;
757
+ inflight;
758
+ constructor(options) {
759
+ this.refresh = options.refresh;
760
+ this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
761
+ this.region = options.region;
762
+ this.ownPathExplicit = options.ownPath;
763
+ this.legacyOwnPath = options.legacyOwnPath ?? legacyWorkbuddyOwnAuthPath();
764
+ this.legacyOwnPathExplicit = options.legacyOwnPath;
765
+ this.authDirs = options.authDirs;
766
+ this.desktopPathOverride = options.desktopPath;
814
767
  }
815
- /** POST the token-refresh endpoint; the caller merges the outcome. */
816
- async refreshToken(credential) {
817
- const response = await fetch(`${chatBase(credential)}/v2/plugin/auth/token/refresh`, {
818
- method: "POST",
819
- headers: refreshHeaders(credential),
820
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
821
- });
822
- const envelope = await readEnvelope(response);
823
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
824
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
825
- const accessToken = typeof data["accessToken"] === "string" ? data["accessToken"] : "";
826
- if (accessToken === "") throw new Error("workbuddy token refresh returned no accessToken; sign in again in the WorkBuddy app");
827
- const outcome = { accessToken };
828
- if (typeof data["refreshToken"] === "string" && data["refreshToken"] !== "") outcome.refreshToken = data["refreshToken"];
829
- if (typeof data["expiresIn"] === "number" && data["expiresIn"] > 0) outcome.expiresInSec = data["expiresIn"];
830
- if (typeof data["domain"] === "string" && data["domain"] !== "") outcome.domain = data["domain"];
831
- return outcome;
768
+ /** Whether a credential's login domain belongs to this store's region. */
769
+ matchesRegion(domain) {
770
+ return this.region === void 0 || regionOf(domain) === this.region;
832
771
  }
833
772
  /**
834
- * GET the personal model catalog and keep the `cli` agent's models only,
835
- * preserving the capability fields the plugin card displays.
773
+ * The path this store refreshes into: the per-region file for a
774
+ * region-scoped store, the legacy single file otherwise, or an explicitly
775
+ * injected path in tests.
836
776
  */
837
- async fetchModels(credential, signal) {
838
- const response = await fetch(`${chatBase(credential)}/console/enterprises/personal/models`, {
839
- headers: {
840
- "Authorization": `Bearer ${credential.accessToken}`,
841
- "Accept": "application/json",
842
- "Origin": originReferer(credential),
843
- "Referer": `${originReferer(credential)}/`,
844
- "User-Agent": CLIENT_UA
845
- },
846
- signal: signal ?? AbortSignal.timeout(JSON_TIMEOUT_MS)
847
- });
848
- const envelope = await readEnvelope(response);
849
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
850
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
851
- const rawModels = Array.isArray(data["models"]) ? data["models"] : [];
852
- const agents = Array.isArray(data["agents"]) ? data["agents"] : [];
853
- let cliIds;
854
- for (const agent of agents) if (typeof agent === "object" && agent !== null) {
855
- const wrapped = agent;
856
- if (wrapped["name"] === "cli" && Array.isArray(wrapped["models"])) {
857
- cliIds = wrapped["models"].filter((id) => typeof id === "string");
858
- break;
859
- }
777
+ ownAuthPath() {
778
+ if (this.ownPathExplicit !== void 0) return this.ownPathExplicit;
779
+ return this.region !== void 0 ? workbuddyOwnAuthPath(this.region) : this.legacyOwnPath;
780
+ }
781
+ /**
782
+ * Every plugin-owned copy to read, most preferred first. A region-scoped
783
+ * store reads the legacy single copy as its migration source (readAll's
784
+ * region filter drops it when it carries the other region's credential); an
785
+ * unscoped store reads everything so diagnostics see both regions.
786
+ *
787
+ * With an explicitly injected own path the legacy source is read ONLY when
788
+ * it was injected too — a test that pins one file must not accidentally see
789
+ * the real machine's legacy copy.
790
+ */
791
+ ownCandidates() {
792
+ if (this.ownPathExplicit !== void 0) return this.legacyOwnPathExplicit !== void 0 ? [this.ownPathExplicit, this.legacyOwnPathExplicit] : [this.ownPathExplicit];
793
+ if (this.region !== void 0) return [workbuddyOwnAuthPath(this.region), this.legacyOwnPath];
794
+ return [
795
+ this.legacyOwnPath,
796
+ workbuddyOwnAuthPath("cn"),
797
+ workbuddyOwnAuthPath("global")
798
+ ];
799
+ }
800
+ /** Repoint the desktop file or directory; applies on the next read. */
801
+ setDesktopPath(path) {
802
+ this.desktopPathOverride = path;
803
+ this.inflight = void 0;
804
+ }
805
+ /** Select an account by id; tokens stay outside settings. */
806
+ selectAccount(accountId) {
807
+ this.accountId = accountId;
808
+ this.inflight = void 0;
809
+ }
810
+ /** Selected account id, for diagnostics and route assembly. */
811
+ selectedAccountId() {
812
+ return this.accountId;
813
+ }
814
+ /** The auth-file path candidates, in probe order. */
815
+ resolveDesktopCandidates() {
816
+ const fromEnv = process.env[WORKBUDDY_AUTH_FILE_ENV];
817
+ const explicit = this.desktopPathOverride ?? (fromEnv !== void 0 && fromEnv.trim() !== "" ? fromEnv : void 0);
818
+ if (explicit !== void 0) return [explicit];
819
+ return defaultDesktopAuthCandidates();
820
+ }
821
+ /** The resolved desktop auth-file path, for diagnostics. */
822
+ desktopAuthPath() {
823
+ return this.resolveDesktopCandidates()[0];
824
+ }
825
+ /**
826
+ * Every auth file to scan: the live file plus the timestamped backups
827
+ * WorkBuddy leaves beside it.
828
+ *
829
+ * An explicitly configured path pins the *directory*: its siblings are
830
+ * still scanned, because a user who points the plugin at their auth file
831
+ * expects account switching to work the same way it does on the default
832
+ * path. Only the file ordering changes.
833
+ *
834
+ * A corrupt or signed-out file must never hide the others, so each read is
835
+ * independent and failures are skipped rather than propagated.
836
+ */
837
+ async candidateFiles() {
838
+ const explicitPath = this.desktopPathOverride ?? ((process.env["WORKBUDDY_AUTH_FILE"] ?? "").trim() !== "" ? process.env["WORKBUDDY_AUTH_FILE"] : void 0);
839
+ const files = [];
840
+ if (explicitPath !== void 0) {
841
+ files.push(explicitPath);
842
+ for (const backup of await this.backupsBeside(explicitPath)) files.push(backup);
843
+ return files;
844
+ }
845
+ const dirs = this.authDirs ?? defaultDesktopAuthDirs();
846
+ for (const dir of dirs) {
847
+ const live = join(dir, WORKBUDDY_LIVE_FILENAME);
848
+ files.push(live);
849
+ for (const backup of await this.backupsBeside(live)) files.push(backup);
850
+ }
851
+ return files;
852
+ }
853
+ /** Timestamped siblings of one auth file, newest first by filename. */
854
+ async backupsBeside(path) {
855
+ const dir = dirname(path);
856
+ const base = path.slice(dir.length + 1);
857
+ try {
858
+ return (await readdir(dir)).filter((name) => name !== base && name.endsWith(".info")).sort().reverse().map((name) => join(dir, name));
859
+ } catch {
860
+ return [];
860
861
  }
862
+ }
863
+ /**
864
+ * Read every local credential, deduplicated by account id. Files are
865
+ * probed newest-first, so the first entry for an account is its freshest.
866
+ *
867
+ * A region-scoped store sees only its own region's credentials: the other
868
+ * region's accounts are invisible to selection, refresh, and status alike,
869
+ * which is what keeps the two regions' providers from cross-billing.
870
+ */
871
+ async readAll() {
872
+ const files = await this.candidateFiles();
861
873
  const byId = /* @__PURE__ */ new Map();
862
- for (const model of rawModels) {
863
- const parsed = parseUpstreamModel(model);
864
- if (parsed !== void 0) byId.set(parsed.id, parsed);
874
+ for (const file of files) {
875
+ const credential = await readAuthFile(file);
876
+ if (credential === void 0 || !this.matchesRegion(credential.domain)) continue;
877
+ const id = workbuddyAccountId(credential);
878
+ const existing = byId.get(id);
879
+ if (existing === void 0) {
880
+ byId.set(id, credential);
881
+ continue;
882
+ }
883
+ if (fileRank(credential.filePath) < fileRank(existing.filePath) || fileRank(credential.filePath) === fileRank(existing.filePath) && credential.expiresAtMs > existing.expiresAtMs) byId.set(id, credential);
884
+ }
885
+ for (const own of await this.readOwns()) {
886
+ if (!this.matchesRegion(own.domain)) continue;
887
+ const id = workbuddyAccountId(own);
888
+ const existing = byId.get(id);
889
+ if (existing === void 0 || own.expiresAtMs > existing.expiresAtMs) byId.set(id, own);
865
890
  }
866
- const models = (cliIds !== void 0 && cliIds.length > 0 ? cliIds : [...byId.keys()]).map((id) => byId.get(id)).filter((model) => model !== void 0);
867
- if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
868
- return models;
891
+ return [...byId.values()];
869
892
  }
870
- /** Query today's check-in status without changing account state. */
871
- async fetchCheckinStatus(credential) {
872
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/checkin-activity-status`, {
873
- method: "POST",
874
- headers: billingHeaders(credential),
875
- body: "{}",
876
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
893
+ /**
894
+ * Default when no account is explicitly selected: the live sign-in, else the
895
+ * freshest credential. Following the app's current sign-in is the documented
896
+ * default behaviour; the backups exist so the user can switch explicitly.
897
+ * This is NOT credit-seeking — it never reorders accounts to find one with
898
+ * remaining credit.
899
+ */
900
+ preferred(credentials) {
901
+ if (credentials.length === 0) return void 0;
902
+ return credentials.reduce((best, credential) => {
903
+ if (fileRank(credential.filePath) < fileRank(best.filePath)) return credential;
904
+ if (fileRank(credential.filePath) === fileRank(best.filePath) && credential.expiresAtMs > best.expiresAtMs) return credential;
905
+ return best;
877
906
  });
878
- const envelope = await readEnvelope(response);
879
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
880
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
881
- const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
882
- return {
883
- active: data["active"] === true,
884
- todayCheckedIn: data["today_checked_in"] === true,
885
- streakDays: numberField("streak_days"),
886
- dailyCredit: numberField("daily_credit"),
887
- todayCredit: numberField("today_credit"),
888
- isStreakDay: data["is_streak_day"] === true,
889
- nextStreakDay: numberField("next_streak_day"),
890
- streakBonusDays: numberField("streak_bonus_days"),
891
- streakBonusCredit: numberField("streak_bonus_credit"),
892
- ...typeof data["claim_button_text"] === "string" && data["claim_button_text"] !== "" ? { claimButtonText: data["claim_button_text"] } : {}
893
- };
894
907
  }
895
- /** Claim today's check-in reward. The browser route guards this mutation. */
896
- async claimDailyCheckin(credential) {
897
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/daily-checkin`, {
898
- method: "POST",
899
- headers: billingHeaders(credential),
900
- body: "{}",
901
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
908
+ /** Token-free account list for the plugin card. */
909
+ async accounts() {
910
+ const credentials = await this.readAll();
911
+ if (credentials.length === 0) return [];
912
+ const selectedExists = this.accountId !== void 0 && credentials.some((credential) => workbuddyAccountId(credential) === this.accountId);
913
+ const defaultSelected = this.preferred(credentials);
914
+ return credentials.map((credential) => {
915
+ const id = workbuddyAccountId(credential);
916
+ return {
917
+ id,
918
+ accountName: credential.nickname ?? credential.uin ?? credential.uid,
919
+ ...credential.uin === void 0 ? {} : { uin: credential.uin },
920
+ domain: credential.domain,
921
+ source: credential.source,
922
+ tokenExpiresAtMs: credential.expiresAtMs,
923
+ filePath: credential.filePath,
924
+ selected: selectedExists ? id === this.accountId : credential === defaultSelected
925
+ };
902
926
  });
903
- const envelope = await readEnvelope(response);
904
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
905
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
906
- const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
907
- return {
908
- credit: numberField("credit"),
909
- streakDays: numberField("streak_days"),
910
- isStreakDay: data["is_streak_day"] === true
911
- };
927
+ }
928
+ /** The freshest stored credential for the current selection, no refresh. */
929
+ async current() {
930
+ const credentials = await this.readAll();
931
+ if (this.accountId === void 0) return this.preferred(credentials);
932
+ return credentials.find((credential) => workbuddyAccountId(credential) === this.accountId);
933
+ }
934
+ /** The credential to send upstream: {@link current}, refreshed on demand. */
935
+ async resolve() {
936
+ const credential = await this.current();
937
+ if (credential === void 0) {
938
+ const candidates = this.resolveDesktopCandidates();
939
+ const desktop = candidates.length > 0 ? candidates.join(" or ") : "(no desktop path on this platform)";
940
+ throw new Error(`workbuddy: no signed-in WorkBuddy account found; sign in once in the WorkBuddy desktop app (expected ${desktop} or ${WORKBUDDY_AUTH_FILE_ENV}), or refresh an existing session`);
941
+ }
942
+ if (!this.needsRefresh(credential)) return credential;
943
+ this.inflight ??= this.refreshNow(credential).finally(() => {
944
+ this.inflight = void 0;
945
+ });
946
+ return this.inflight;
947
+ }
948
+ /** Read-only sign-in summary; never refreshes and never throws. */
949
+ async status() {
950
+ try {
951
+ const credential = await this.current();
952
+ if (credential === void 0) return { state: "signed-out" };
953
+ return {
954
+ state: "signed-in",
955
+ expiresAtMs: credential.expiresAtMs,
956
+ ...credential.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs: credential.refreshExpiresAtMs },
957
+ ...credential.nickname === void 0 ? {} : { nickname: credential.nickname },
958
+ ...credential.domain === "" ? {} : { domain: credential.domain },
959
+ source: credential.source
960
+ };
961
+ } catch {
962
+ return { state: "signed-out" };
963
+ }
912
964
  }
913
965
  /**
914
- * POST the billing endpoint for the remaining credit, keeping every package
915
- * separate: the card groups monthly-cycle packages itself and lists the
916
- * nearest-expiring one-off packages, so aggregation here would lose the
917
- * dates it needs.
966
+ * Remove every plugin-owned copy this store could read (per-region file,
967
+ * legacy single file, and their lock siblings); the desktop files are
968
+ * untouched. A region store's logout therefore also clears the legacy
969
+ * migration source — deliberate: `logout` is the user's "forget what the
970
+ * plugin stored" action, not a per-account toggle.
918
971
  */
919
- async fetchCredits(credential) {
920
- const now = /* @__PURE__ */ new Date();
921
- const format = (date) => [
922
- date.getFullYear().toString().padStart(4, "0"),
923
- (date.getMonth() + 1).toString().padStart(2, "0"),
924
- date.getDate().toString().padStart(2, "0")
925
- ].join("-") + " " + [
926
- date.getHours().toString().padStart(2, "0"),
927
- date.getMinutes().toString().padStart(2, "0"),
928
- date.getSeconds().toString().padStart(2, "0")
929
- ].join(":");
930
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/get-user-resource`, {
931
- method: "POST",
932
- headers: billingHeaders(credential),
933
- body: JSON.stringify({
934
- PageNumber: 1,
935
- PageSize: 100,
936
- ProductCode: "p_tcaca",
937
- Status: [0, 3],
938
- PackageEndTimeRangeBegin: format(now),
939
- PackageEndTimeRangeEnd: format(new Date(now.getTime() + 3185136e6))
940
- }),
941
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
942
- });
943
- const envelope = await readEnvelope(response);
944
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
945
- const responseWrapper = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
946
- const data = typeof responseWrapper["Response"] === "object" && responseWrapper["Response"] !== null ? responseWrapper["Response"] : {};
947
- const inner = typeof data["Data"] === "object" && data["Data"] !== null ? data["Data"] : {};
948
- const rawAccounts = Array.isArray(inner["Accounts"]) ? inner["Accounts"] : [];
949
- let total = 0;
950
- let nearestExpiryMs;
951
- let expiringSoon = 0;
952
- const SOON_MS = 2592e5;
953
- const parseDate = (raw) => {
954
- if (typeof raw === "number" && raw > 0xe8d4a51000) return raw;
955
- if (typeof raw === "string" && raw !== "") {
956
- const parsed = Date.parse(raw);
957
- if (!Number.isNaN(parsed)) return parsed;
958
- }
959
- };
960
- const packages = [];
961
- for (const raw of rawAccounts) {
962
- if (typeof raw !== "object" || raw === null) continue;
963
- const account = raw;
964
- const numberField = (key) => typeof account[key] === "number" ? account[key] : 0;
965
- const monthly = numberField("CapacityType") === 4;
966
- const size = monthly ? numberField("CycleCapacitySize") : numberField("CapacitySize");
967
- const remain = monthly ? numberField("CycleCapacityRemain") : numberField("CapacityRemain");
968
- const cappedRemain = remain < 0 ? 0 : remain;
969
- const cycleEndMs = parseDate(account["CycleEndTime"]);
970
- const expiresAtMs = monthly ? void 0 : parseDate(account["ExpiredTime"]) ?? cycleEndMs;
971
- const refreshAtMs = monthly ? cycleEndMs === void 0 ? void 0 : cycleEndMs + 1e3 : void 0;
972
- if (!monthly && (cappedRemain <= 0 || expiresAtMs !== void 0 && expiresAtMs <= Date.now())) continue;
973
- total += cappedRemain;
974
- const expiryMs = expiresAtMs;
975
- if (expiryMs !== void 0) {
976
- if (nearestExpiryMs === void 0 || expiryMs < nearestExpiryMs) nearestExpiryMs = expiryMs;
977
- if (expiryMs - Date.now() <= SOON_MS) expiringSoon += cappedRemain;
978
- }
979
- packages.push({
980
- packageName: typeof account["PackageName"] === "string" ? account["PackageName"] : "(unnamed)",
981
- remain: cappedRemain,
982
- size,
983
- monthly,
984
- ...refreshAtMs === void 0 ? {} : { refreshAtMs },
985
- ...expiresAtMs === void 0 ? {} : { expiresAtMs }
986
- });
972
+ async logout() {
973
+ for (const path of this.ownCandidates()) {
974
+ await rm(path, { force: true });
975
+ await rm(`${path}.lock`, { force: true });
987
976
  }
988
- return {
989
- total,
990
- packages,
991
- expiringSoon,
992
- ...nearestExpiryMs === void 0 ? {} : { nearestExpiryMs }
993
- };
977
+ }
978
+ needsRefresh(credential) {
979
+ if (credential.expiresAtMs <= 0) return true;
980
+ return Date.now() + this.refreshMarginMs >= credential.expiresAtMs;
981
+ }
982
+ async refreshNow(credential) {
983
+ if (credential.refreshToken === "") {
984
+ if (credential.expiresAtMs > Date.now() + 3e4) return credential;
985
+ throw new Error("workbuddy: access token expired and no refresh token is stored; sign in again in the WorkBuddy desktop app");
986
+ }
987
+ try {
988
+ const outcome = await this.refresh(credential);
989
+ const refreshed = {
990
+ ...credential,
991
+ accessToken: outcome.accessToken,
992
+ ...outcome.refreshToken === void 0 ? {} : { refreshToken: outcome.refreshToken },
993
+ expiresAtMs: outcome.expiresInSec !== void 0 ? Date.now() + outcome.expiresInSec * 1e3 : credential.expiresAtMs,
994
+ ...outcome.domain === void 0 || outcome.domain === "" ? {} : { domain: outcome.domain },
995
+ source: "dsh"
996
+ };
997
+ await this.saveOwn(refreshed);
998
+ return refreshed;
999
+ } catch (error) {
1000
+ if (credential.expiresAtMs > Date.now() + 3e4) return credential;
1001
+ throw new Error(`workbuddy: token refresh failed and the access token is expired (${String(error)}); open the WorkBuddy desktop app once to sign in again`);
1002
+ }
1003
+ }
1004
+ async saveOwn(credential) {
1005
+ const accountId = workbuddyAccountId(credential);
1006
+ const path = this.ownAuthPath();
1007
+ await withFileLock(path, async () => {
1008
+ await writeFileAtomic(path, `${JSON.stringify(ownDocument(credential, accountId), null, 2)}\n`, {
1009
+ mode: 384,
1010
+ dirMode: 448
1011
+ });
1012
+ });
1013
+ }
1014
+ /**
1015
+ * Every readable plugin-owned copy, in candidate order; absent or corrupt
1016
+ * files are skipped rather than propagated.
1017
+ */
1018
+ async readOwns() {
1019
+ const copies = [];
1020
+ for (const path of this.ownCandidates()) try {
1021
+ const parsed = parseOwnDocument(await readFile(path, "utf8"), path);
1022
+ if (parsed !== void 0) copies.push(parsed);
1023
+ } catch {}
1024
+ return copies;
1025
+ }
1026
+ /** Whether any candidate file exists as a regular file; diagnostics only. */
1027
+ async desktopFilePresent() {
1028
+ for (const path of this.resolveDesktopCandidates()) try {
1029
+ if ((await stat(path)).isFile()) return true;
1030
+ } catch {}
1031
+ return false;
1032
+ }
1033
+ };
1034
+ //#endregion
1035
+ //#region src/catalog.ts
1036
+ /**
1037
+ * Static CLI models captured from the CN endpoint (2026-08-30). The upstream
1038
+ * refresh replaces this list at startup; it exists so the provider registers
1039
+ * with a usable catalog even while the first fetch is in flight or offline.
1040
+ */
1041
+ const FALLBACK_WORKBUDDY_MODELS = [
1042
+ {
1043
+ id: "auto",
1044
+ name: "Auto",
1045
+ contextWindow: 168e3,
1046
+ maxTokens: 32e3
1047
+ },
1048
+ {
1049
+ id: "hy3",
1050
+ name: "Hy3",
1051
+ contextWindow: 192e3,
1052
+ maxTokens: 64e3
1053
+ },
1054
+ {
1055
+ id: "glm-5v-turbo",
1056
+ name: "GLM-5v-Turbo",
1057
+ contextWindow: 2e5,
1058
+ maxTokens: 64e3
1059
+ },
1060
+ {
1061
+ id: "glm-5.3",
1062
+ name: "GLM-5.3",
1063
+ contextWindow: 1e6,
1064
+ maxTokens: 48e3
1065
+ },
1066
+ {
1067
+ id: "glm-5.2",
1068
+ name: "GLM-5.2",
1069
+ contextWindow: 1e6,
1070
+ maxTokens: 48e3
1071
+ },
1072
+ {
1073
+ id: "glm-5.1",
1074
+ name: "GLM-5.1",
1075
+ contextWindow: 2e5,
1076
+ maxTokens: 48e3
1077
+ },
1078
+ {
1079
+ id: "minimax-m3",
1080
+ name: "MiniMax-M3",
1081
+ contextWindow: 512e3,
1082
+ maxTokens: 128e3
1083
+ },
1084
+ {
1085
+ id: "kimi-k3-1",
1086
+ name: "Kimi-K3",
1087
+ contextWindow: 1e6,
1088
+ maxTokens: 32e3
1089
+ },
1090
+ {
1091
+ id: "kimi-k2.7",
1092
+ name: "Kimi-K2.7-Code",
1093
+ contextWindow: 256e3,
1094
+ maxTokens: 32e3
1095
+ },
1096
+ {
1097
+ id: "kimi-k2.6",
1098
+ name: "Kimi-K2.6",
1099
+ contextWindow: 256e3,
1100
+ maxTokens: 32e3
1101
+ },
1102
+ {
1103
+ id: "deepseek-v4-flash",
1104
+ name: "Deepseek-V4-Flash",
1105
+ contextWindow: 1e6,
1106
+ maxTokens: 5e4
1107
+ },
1108
+ {
1109
+ id: "deepseek-v4-pro",
1110
+ name: "Deepseek-V4-Pro",
1111
+ contextWindow: 1e6,
1112
+ maxTokens: 5e4
1113
+ }
1114
+ ];
1115
+ /**
1116
+ * Static CLI models captured from the INTERNATIONAL gateway's desktop-channel
1117
+ * product config (`www.workbuddy.ai/v3/config`, 2026-09-11). The two regions
1118
+ * expose different rosters — the CN list has no `gpt-*`/`gemini-*` entries —
1119
+ * so a global account must never be seeded with the CN list. Like the CN
1120
+ * fallback this is replaced by the live refresh; it only keeps the provider
1121
+ * usable before the first fetch lands. Order and rates mirror the upstream.
1122
+ */
1123
+ const FALLBACK_WORKBUDDY_MODELS_GLOBAL = [
1124
+ {
1125
+ id: "default-model",
1126
+ name: "Auto",
1127
+ contextWindow: 176e3,
1128
+ maxTokens: 24e3,
1129
+ creditMultiplier: .79
1130
+ },
1131
+ {
1132
+ id: "fast-model",
1133
+ name: "Fast",
1134
+ contextWindow: 2e5,
1135
+ maxTokens: 32e3,
1136
+ creditMultiplier: .34
1137
+ },
1138
+ {
1139
+ id: "balanced-model",
1140
+ name: "Balanced",
1141
+ contextWindow: 256e3,
1142
+ maxTokens: 32e3,
1143
+ creditMultiplier: .59
1144
+ },
1145
+ {
1146
+ id: "primary-model",
1147
+ name: "Primary",
1148
+ contextWindow: 272e3,
1149
+ maxTokens: 72e3,
1150
+ creditMultiplier: 3.31
1151
+ },
1152
+ {
1153
+ id: "deep-model",
1154
+ name: "Deep",
1155
+ contextWindow: 176e3,
1156
+ maxTokens: 24e3,
1157
+ creditMultiplier: 3.33
1158
+ },
1159
+ {
1160
+ id: "deepseek-v4.1-flash",
1161
+ name: "Deepseek-V4.1-Flash",
1162
+ contextWindow: 1e6,
1163
+ maxTokens: 128e3,
1164
+ creditMultiplier: 0
1165
+ },
1166
+ {
1167
+ id: "gpt-6-astra",
1168
+ name: "GPT-6-Astra",
1169
+ contextWindow: 1e6,
1170
+ maxTokens: 128e3,
1171
+ creditMultiplier: 6.67
1172
+ },
1173
+ {
1174
+ id: "hy4-preview",
1175
+ name: "Hy4 preview",
1176
+ contextWindow: 1e6,
1177
+ maxTokens: 64e3,
1178
+ creditMultiplier: 0
1179
+ },
1180
+ {
1181
+ id: "hy3",
1182
+ name: "Hy3",
1183
+ contextWindow: 192e3,
1184
+ maxTokens: 64e3,
1185
+ creditMultiplier: 0
1186
+ },
1187
+ {
1188
+ id: "gpt-5.6-sol",
1189
+ name: "GPT-5.6-Sol",
1190
+ contextWindow: 1e6,
1191
+ maxTokens: 128e3,
1192
+ creditMultiplier: 3.47
1193
+ },
1194
+ {
1195
+ id: "gpt-5.6-terra",
1196
+ name: "GPT-5.6-Terra",
1197
+ contextWindow: 1e6,
1198
+ maxTokens: 128e3,
1199
+ creditMultiplier: 1.39
1200
+ },
1201
+ {
1202
+ id: "gpt-5.6-luna",
1203
+ name: "GPT-5.6-Luna",
1204
+ contextWindow: 1e6,
1205
+ maxTokens: 128e3,
1206
+ creditMultiplier: .14
1207
+ },
1208
+ {
1209
+ id: "gpt-5.5",
1210
+ name: "GPT-5.5",
1211
+ contextWindow: 1e6,
1212
+ maxTokens: 128e3,
1213
+ creditMultiplier: 3.31
1214
+ },
1215
+ {
1216
+ id: "gpt-5.4",
1217
+ name: "GPT-5.4",
1218
+ contextWindow: 272e3,
1219
+ maxTokens: 72e3,
1220
+ creditMultiplier: 1.65
1221
+ },
1222
+ {
1223
+ id: "gpt-5.3-codex",
1224
+ name: "GPT-5.3-Codex",
1225
+ contextWindow: 272e3,
1226
+ maxTokens: 72e3,
1227
+ creditMultiplier: 1.25
1228
+ },
1229
+ {
1230
+ id: "gemini-3.5-flash",
1231
+ name: "Gemini-3.5-Flash",
1232
+ contextWindow: 1e6,
1233
+ maxTokens: 65536,
1234
+ creditMultiplier: .99
1235
+ },
1236
+ {
1237
+ id: "glm-5.3",
1238
+ name: "GLM-5.3",
1239
+ contextWindow: 1e6,
1240
+ maxTokens: 48e3,
1241
+ creditMultiplier: .79
1242
+ },
1243
+ {
1244
+ id: "glm-5.2",
1245
+ name: "GLM-5.2",
1246
+ contextWindow: 1e6,
1247
+ maxTokens: 48e3,
1248
+ creditMultiplier: .79
1249
+ },
1250
+ {
1251
+ id: "kimi-k3",
1252
+ name: "Kimi-K3",
1253
+ contextWindow: 1e6,
1254
+ maxTokens: 32e3,
1255
+ creditMultiplier: 1.62
1256
+ },
1257
+ {
1258
+ id: "kimi-k2.6",
1259
+ name: "Kimi-K2.6",
1260
+ contextWindow: 256e3,
1261
+ maxTokens: 32e3,
1262
+ creditMultiplier: .52
1263
+ }
1264
+ ];
1265
+ /**
1266
+ * Static fallback directory for a region. Each region keeps its own model
1267
+ * slot in settings; the fallback must match the region so an account never
1268
+ * shows the other region's roster.
1269
+ */
1270
+ function fallbackModelsFor(region) {
1271
+ return region === "global" ? FALLBACK_WORKBUDDY_MODELS_GLOBAL : FALLBACK_WORKBUDDY_MODELS;
1272
+ }
1273
+ /** Apply the saved local DSH budget; models above 200K default to 200K. */
1274
+ function applyContextBudgets(catalog, budgets = {}) {
1275
+ return catalog.map((model) => ({
1276
+ ...model,
1277
+ contextWindow: model.contextWindow > 2e5 ? Math.min(model.contextWindow, budgets[model.id] ?? 2e5) : model.contextWindow
1278
+ }));
1279
+ }
1280
+ function deriveCatalog(catalog, enabled, budgets = {}) {
1281
+ return applyContextBudgets(enabled.size === 0 ? catalog : catalog.filter((model) => enabled.has(model.id)), budgets);
1282
+ }
1283
+ /** Mutable catalog shared by the shim's `/v1/models` and the adapter. */
1284
+ var WorkBuddyCatalog = class {
1285
+ models;
1286
+ /**
1287
+ * @param region Seeds the static fallback for this region; each region's
1288
+ * provider must never serve the other region's roster before its first
1289
+ * live refresh lands.
1290
+ */
1291
+ constructor(region = "cn") {
1292
+ this.models = fallbackModelsFor(region);
1293
+ }
1294
+ /** Current entries; the fallback list until the upstream answer lands. */
1295
+ current() {
1296
+ return this.models;
1297
+ }
1298
+ /** Replace the list; callers invalidate their adapter snapshot after this. */
1299
+ set(models) {
1300
+ if (models.length === 0) throw new Error("workbuddy model catalog cannot be empty");
1301
+ this.models = models.map((model) => ({ ...model }));
994
1302
  }
995
1303
  };
996
1304
  //#endregion
997
1305
  //#region src/version.ts
998
1306
  /** The npm package version this build was produced from. */
999
- const WORKBUDDY_CONNECT_VERSION = "1.3.0";
1307
+ const WORKBUDDY_CONNECT_VERSION = "2.0.0";
1000
1308
  //#endregion
1001
1309
  //#region src/host-heartbeat.ts
1002
1310
  /**
@@ -1102,4 +1410,4 @@ async function clearHostHeartbeat() {
1102
1410
  await rm(workbuddyHostHeartbeatPath(), { force: true });
1103
1411
  }
1104
1412
  //#endregion
1105
- export { defaultDesktopAuthCandidates as C, workbuddyAccountId as D, parseWorkBuddyAuth as E, workbuddyOwnAuthPath as O, authFileName as S, defaultDesktopAuthPath as T, WorkBuddyCatalog as _, readHostHeartbeat as a, WORKBUDDY_AUTH_FILE_ENV as b, WORKBUDDY_CONNECT_VERSION as c, parseCreditMultiplier as d, parseReasoning as f, FALLBACK_WORKBUDDY_MODELS as g, regionOf as h, processStartTimeMs as i, WorkBuddyUpstreamClient as l, prepareChatBody as m, clearHostHeartbeat as n, workbuddyHostHeartbeatPath as o, parseUpstreamModel as p, isHeartbeatProcessAlive as r, writeHostHeartbeat as s, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, classifyUpstreamError as u, deriveCatalog as v, defaultDesktopAuthDirs as w, WorkBuddyCredentialStore as x, WORKBUDDY_AUTH_FILENAME as y };
1413
+ export { prepareChatBody as A, workbuddyAccountId as C, parseCreditMultiplier as D, classifyUpstreamError as E, parseReasoning as O, parseWorkBuddyAuth as S, WorkBuddyUpstreamClient as T, authFileName as _, readHostHeartbeat as a, defaultDesktopAuthPath as b, WORKBUDDY_CONNECT_VERSION as c, WorkBuddyCatalog as d, deriveCatalog as f, WorkBuddyCredentialStore as g, WORKBUDDY_AUTH_FILE_ENV as h, processStartTimeMs as i, regionOf as j, parseUpstreamModel as k, FALLBACK_WORKBUDDY_MODELS as l, WORKBUDDY_AUTH_FILENAME as m, clearHostHeartbeat as n, workbuddyHostHeartbeatPath as o, fallbackModelsFor as p, isHeartbeatProcessAlive as r, writeHostHeartbeat as s, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, FALLBACK_WORKBUDDY_MODELS_GLOBAL as u, defaultDesktopAuthCandidates as v, workbuddyOwnAuthPath as w, legacyWorkbuddyOwnAuthPath as x, defaultDesktopAuthDirs as y };