dsh-connect-workbuddy 1.4.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,449 +5,1043 @@ 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
  }
125
- /**
126
- * Rank two candidate files for the same account.
127
- *
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);
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)}`);
146
218
  }
147
219
  /**
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.
220
+ * Parse the upstream's `credits` string into a multiplier.
221
+ *
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;
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);
233
289
  }
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();
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;
296
+ }
240
297
  }
241
- /** The resolved desktop auth-file path, for diagnostics. */
242
- desktopAuthPath() {
243
- return this.resolveDesktopCandidates()[0];
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;
310
+ try {
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
+ };
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
+ };
244
339
  }
245
- /** The plugin-owned copy path, for diagnostics. */
246
- ownAuthPath() {
247
- return this.ownPath;
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;
248
357
  }
249
358
  /**
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.
359
+ * Read the model directory for the credential's region.
257
360
  *
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.
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`.
260
368
  */
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);
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"]);
274
389
  }
275
- return files;
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
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"]);
276
404
  }
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);
281
- try {
282
- return (await readdir(dir)).filter((name) => name !== base && name.endsWith(".info")).sort().reverse().map((name) => join(dir, name));
283
- } catch {
284
- return [];
285
- }
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)
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
+ };
286
429
  }
287
- /**
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.
290
- */
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);
304
- }
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()];
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)
437
+ });
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
+ };
312
447
  }
313
448
  /**
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.
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.
319
453
  */
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;
326
- });
327
- }
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
- };
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)
346
477
  });
347
- }
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`);
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
+ });
361
522
  }
362
- if (!this.needsRefresh(credential)) return credential;
363
- this.inflight ??= this.refreshNow(credential).finally(() => {
364
- this.inflight = void 0;
365
- });
366
- return this.inflight;
523
+ return {
524
+ total,
525
+ packages,
526
+ expiringSoon,
527
+ ...nearestExpiryMs === void 0 ? {} : { nearestExpiryMs }
528
+ };
367
529
  }
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 });
530
+ };
531
+ //#endregion
532
+ //#region src/auth.ts
533
+ /**
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`);
570
+ }
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);
578
+ }
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")];
389
596
  }
390
- needsRefresh(credential) {
391
- if (credential.expiresAtMs <= 0) return true;
392
- return Date.now() + this.refreshMarginMs >= credential.expiresAtMs;
597
+ if (platform === "linux") {
598
+ const config = nonEmptyEnv(env["XDG_CONFIG_HOME"]) ?? join(home, ".config");
599
+ return [join(config, "CodeBuddyExtension", "Data", "Public", "auth")];
393
600
  }
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
- }
601
+ return [];
602
+ }
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;
606
+ }
607
+ /** The live auth file's platform candidates, in probe order. */
608
+ function defaultDesktopAuthCandidates() {
609
+ return defaultDesktopAuthDirs().map((dir) => join(dir, WORKBUDDY_LIVE_FILENAME));
610
+ }
611
+ /** First platform-default candidate; see {@link defaultDesktopAuthCandidates}. */
612
+ function defaultDesktopAuthPath() {
613
+ return defaultDesktopAuthCandidates()[0];
614
+ }
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;
619
+ }
620
+ function optionalString(value) {
621
+ return typeof value === "string" && value !== "" ? value : void 0;
622
+ }
623
+ /**
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.
627
+ */
628
+ function parseWorkBuddyAuth(text, filePath) {
629
+ let parsed;
630
+ try {
631
+ parsed = JSON.parse(text);
632
+ } catch {
633
+ return;
415
634
  }
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
- });
423
- });
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;
424
645
  }
425
- async readOwn() {
426
- try {
427
- return parseOwnDocument(await readFile(this.ownPath, "utf8"));
428
- } catch {
429
- return;
430
- }
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
+ };
666
+ }
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
703
+ };
704
+ }
705
+ /** Parse the plugin-owned copy; other versions and shapes are rejected. */
706
+ function parseOwnDocument(text, filePath) {
707
+ let parsed;
708
+ try {
709
+ parsed = JSON.parse(text);
710
+ } catch {
711
+ return;
431
712
  }
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;
713
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
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;
719
+ return {
720
+ ...credential,
721
+ source: "dsh"
722
+ };
723
+ }
724
+ /** Whether a filesystem error reports an absent path. */
725
+ function isENOENT(error) {
726
+ return error?.code === "ENOENT";
727
+ }
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;
438
735
  }
439
- };
440
- //#endregion
441
- //#region src/catalog.ts
736
+ }
442
737
  /**
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.
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.
446
746
  */
447
- const FALLBACK_WORKBUDDY_MODELS = [
448
- {
449
- id: "auto",
450
- name: "Auto",
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;
767
+ }
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;
771
+ }
772
+ /**
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.
776
+ */
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 [];
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();
873
+ const byId = /* @__PURE__ */ new Map();
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);
890
+ }
891
+ return [...byId.values()];
892
+ }
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;
906
+ });
907
+ }
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
+ };
926
+ });
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
+ }
964
+ }
965
+ /**
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.
971
+ */
972
+ async logout() {
973
+ for (const path of this.ownCandidates()) {
974
+ await rm(path, { force: true });
975
+ await rm(`${path}.lock`, { force: true });
976
+ }
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",
451
1045
  contextWindow: 168e3,
452
1046
  maxTokens: 32e3
453
1047
  },
@@ -688,7 +1282,15 @@ function deriveCatalog(catalog, enabled, budgets = {}) {
688
1282
  }
689
1283
  /** Mutable catalog shared by the shim's `/v1/models` and the adapter. */
690
1284
  var WorkBuddyCatalog = class {
691
- models = FALLBACK_WORKBUDDY_MODELS;
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
+ }
692
1294
  /** Current entries; the fallback list until the upstream answer lands. */
693
1295
  current() {
694
1296
  return this.models;
@@ -700,533 +1302,9 @@ var WorkBuddyCatalog = class {
700
1302
  }
701
1303
  };
702
1304
  //#endregion
703
- //#region src/upstream.ts
704
- const CN_CHAT_BASE = "https://copilot.tencent.com";
705
- const CN_BILLING_BASE = "https://www.codebuddy.cn";
706
- const GLOBAL_BASE = "https://www.workbuddy.ai";
707
- /**
708
- * Model-catalog path used by the CN region (and the global fallback). The CN
709
- * gateway answers it with the same bytes as its legacy
710
- * `/console/enterprises/personal/models` alias. See {@link GLOBAL_CONFIG_PATH}
711
- * for why the international region reads a different document.
712
- */
713
- const MODELS_CATALOG_PATH = "/v2/enterprises/personal/models";
714
- /**
715
- * Remote product-config path on the global gateway. This is the document the
716
- * desktop channel receives; it is the only source that lists the account's
717
- * full international chat roster (see {@link DESKTOP_UA}).
718
- */
719
- const GLOBAL_CONFIG_PATH = "/v3/config";
720
- const CLIENT_UA = "CLI/2.63.2 CodeBuddy/2.63.2";
721
- /**
722
- * User agent of the WorkBuddy desktop app.
723
- *
724
- * The config service serves a DIFFERENT product configuration per client
725
- * channel, selected by this product token — the version suffix is ignored
726
- * (`WorkBuddy/5.5.2`, `WorkBuddy/1.0.0` and a bare `WorkBuddy` answer
727
- * identically). On the INTERNATIONAL gateway the split decides which models
728
- * exist at all:
729
- *
730
- * - CLI channel (`CLI/… CodeBuddy/…`) → 35 models that OMIT
731
- * `deepseek-v4.1-flash` and `gpt-6-astra`, even though both are perfectly
732
- * chat-usable (verified: `deepseek-v4.1-flash` streams HTTP 200 and is
733
- * billed `x0.00`);
734
- * - desktop channel → the account's real 20-model chat roster including both.
735
- *
736
- * The plugin emulates the CLI channel for CHAT but reads the desktop channel's
737
- * configuration to learn the account's actual model list. The CN gateway needs
738
- * no such switch: its desktop config carries no `cli` agent roster at all, so
739
- * CN keeps reading the shared `/v2/enterprises/personal/models` path.
740
- */
741
- const DESKTOP_UA = "WorkBuddy/5.5.2";
742
- const JSON_TIMEOUT_MS = 3e4;
743
- const ERROR_BODY_LIMIT = 4096;
744
- /** Insufficient-credit markers, ASCII lowercase plus the original Chinese. */
745
- const HARD_CREDIT_MARKERS = [
746
- "insufficient credit",
747
- "no credit",
748
- "credit exhausted",
749
- "out of credit",
750
- "quota exceeded",
751
- "quota exhaust",
752
- "payment required",
753
- "credit not enough",
754
- "not enough credit",
755
- "积分不足",
756
- "额度不足",
757
- "余额不足",
758
- "积分用完",
759
- "额度用尽",
760
- "没有积分"
761
- ];
762
- /** Session-invalidation markers that mean "sign in again in the WorkBuddy app". */
763
- const SESSION_DEAD_MARKERS = ["Offline user session not found", "12153"];
764
- /** Classify an upstream failure from its HTTP status and body excerpt. */
765
- function classifyUpstreamError(status, body) {
766
- if (status === 402) return "hard_credit";
767
- const lower = body.toLowerCase();
768
- for (const marker of HARD_CREDIT_MARKERS) if (lower.includes(marker.toLowerCase()) || body.includes(marker)) return "hard_credit";
769
- for (const marker of SESSION_DEAD_MARKERS) if (body.includes(marker)) return "session_dead";
770
- if (status === 429) return "soft_rate";
771
- if (status === 404) return "not_found";
772
- if (status >= 500) return "server";
773
- if (status >= 400) return "client";
774
- return "client";
775
- }
776
- /** Region for a login domain; an empty domain means CN (matching upstream tooling). */
777
- function regionOf(domain) {
778
- const lowered = domain.trim().toLowerCase();
779
- if (lowered === "workbuddy.ai" || lowered.endsWith(".workbuddy.ai")) return "global";
780
- return "cn";
781
- }
782
- function chatBase(credential) {
783
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_CHAT_BASE;
784
- }
785
- function billingBase(credential) {
786
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
787
- }
788
- function originReferer(credential) {
789
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
790
- }
791
- /** Headers every upstream request shares. */
792
- function commonHeaders(credential) {
793
- return {
794
- "Accept": "application/json, text/plain, */*",
795
- "X-Requested-With": "XMLHttpRequest",
796
- "Origin": originReferer(credential),
797
- "Referer": `${originReferer(credential)}/`,
798
- "User-Agent": CLIENT_UA
799
- };
800
- }
801
- /** Chat request headers, including the X-No-* conventions the official CLI uses. */
802
- function chatHeaders(credential) {
803
- return {
804
- ...commonHeaders(credential),
805
- "Content-Type": "application/json",
806
- ...credential.uid === "" ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
807
- ...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
808
- ...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
809
- "X-Product": "SaaS"
810
- };
811
- }
812
- /** Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else. */
813
- function refreshHeaders(credential) {
814
- const headers = {
815
- ...commonHeaders(credential),
816
- "X-Refresh-Token": credential.refreshToken,
817
- "X-Auth-Refresh-Source": "workbuddy"
818
- };
819
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") headers["X-Enterprise-Id"] = credential.enterpriseId;
820
- return headers;
821
- }
822
- /** Billing request headers. */
823
- function billingHeaders(credential) {
824
- const headers = {
825
- "Authorization": `Bearer ${credential.accessToken}`,
826
- "Accept": "application/json",
827
- "Content-Type": "application/json"
828
- };
829
- if (credential.uid !== "") headers["X-User-Id"] = credential.uid;
830
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") {
831
- headers["X-Enterprise-Id"] = credential.enterpriseId;
832
- headers["X-Tenant-Id"] = credential.enterpriseId;
833
- }
834
- if (credential.domain !== "") headers["X-Domain"] = credential.domain;
835
- return headers;
836
- }
837
- /**
838
- * Normalize an OpenAI chat-completions body for the WorkBuddy upstream:
839
- * force `stream: true` (the upstream rejects non-streaming) and flatten
840
- * `tool_choice` (the upstream's field is a string; object forms return 400).
841
- */
842
- function prepareChatBody(source) {
843
- let body;
844
- try {
845
- body = JSON.parse(source);
846
- } catch {
847
- return source;
848
- }
849
- if (typeof body !== "object" || body === null || Array.isArray(body)) return source;
850
- const obj = body;
851
- obj["stream"] = true;
852
- if (Array.isArray(obj["messages"])) for (const value of obj["messages"]) {
853
- if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
854
- const message = value;
855
- if (message["role"] === "developer") message["role"] = "system";
856
- }
857
- normalizeToolChoice(obj);
858
- return JSON.stringify(obj);
859
- }
860
- /** Rewrite OpenAI `tool_choice` spellings into the upstream's string form. */
861
- function normalizeToolChoice(obj) {
862
- const suppress = () => {
863
- delete obj["tools"];
864
- delete obj["functions"];
865
- };
866
- if (!("tool_choice" in obj)) return;
867
- const choice = obj["tool_choice"];
868
- if (typeof choice === "string") {
869
- if (choice.trim().toLowerCase() === "none") {
870
- delete obj["tool_choice"];
871
- suppress();
872
- }
873
- return;
874
- }
875
- if (typeof choice === "object" && choice !== null && !Array.isArray(choice)) {
876
- const wrapped = choice;
877
- const type = typeof wrapped["type"] === "string" ? wrapped["type"].trim().toLowerCase() : "";
878
- if (type === "none") {
879
- delete obj["tool_choice"];
880
- suppress();
881
- } else if (type === "auto" || type === "required") obj["tool_choice"] = type;
882
- else if (type === "function") {
883
- const fn = typeof wrapped["function"] === "object" && wrapped["function"] !== null ? wrapped["function"] : void 0;
884
- let name = typeof fn?.["name"] === "string" ? fn["name"] : "";
885
- if (name === "" && typeof wrapped["name"] === "string") name = wrapped["name"];
886
- name = name.trim();
887
- obj["tool_choice"] = name !== "" ? name : "auto";
888
- } else delete obj["tool_choice"];
889
- return;
890
- }
891
- delete obj["tool_choice"];
892
- }
893
- async function readEnvelope(response) {
894
- const text = await response.text();
895
- let parsed;
896
- try {
897
- parsed = JSON.parse(text);
898
- } catch {
899
- throw new Error(`workbuddy upstream returned non-JSON (http ${response.status}): ${text.slice(0, 160)}`);
900
- }
901
- if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
902
- const document = parsed;
903
- return {
904
- code: typeof document["code"] === "number" ? document["code"] : 0,
905
- msg: typeof document["msg"] === "string" ? document["msg"] : "",
906
- data: "data" in document ? document["data"] : void 0
907
- };
908
- }
909
- /** Fail an envelope whose business code is non-zero, classified like HTTP errors. */
910
- function envelopeError(status, envelope) {
911
- const kind = classifyUpstreamError(status, envelope.msg);
912
- return /* @__PURE__ */ new Error(`workbuddy upstream ${kind} (http ${status}): ${envelope.msg.slice(0, 160)}`);
913
- }
914
- /**
915
- * Parse the upstream's `credits` string into a multiplier.
916
- *
917
- * Observed forms: `"x0.79 credits"`, `"x0.05"`, `"x0.00 credits"`,
918
- * and absent. Unparsable values yield undefined rather than a guess — the
919
- * card simply omits the rate instead of displaying a fabricated one.
920
- */
921
- function parseCreditMultiplier(value) {
922
- if (typeof value !== "string") return void 0;
923
- const match = /x\s*([0-9]*\.?[0-9]+)/iu.exec(value);
924
- if (match === null) return void 0;
925
- const parsed = Number(match[1]);
926
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
927
- }
928
- /** Parse the upstream's `reasoning` object; unknown shapes degrade to `{}`. */
929
- function parseReasoning(value) {
930
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
931
- const raw = value;
932
- const supportedEfforts = Array.isArray(raw["supportedEfforts"]) ? raw["supportedEfforts"].filter((effort) => typeof effort === "string") : void 0;
933
- const defaultEffort = typeof raw["defaultEffort"] === "string" ? raw["defaultEffort"] : void 0;
934
- const canDisableThinking = typeof raw["canDisableThinking"] === "boolean" ? raw["canDisableThinking"] : void 0;
935
- if (supportedEfforts === void 0 && defaultEffort === void 0 && canDisableThinking === void 0) return;
936
- return {
937
- ...supportedEfforts === void 0 || supportedEfforts.length === 0 ? {} : { supportedEfforts },
938
- ...defaultEffort === void 0 ? {} : { defaultEffort },
939
- ...canDisableThinking === void 0 ? {} : { canDisableThinking }
940
- };
941
- }
942
- /** Parse one catalog entry; entries without usable token limits are dropped. */
943
- function parseUpstreamModel(value) {
944
- if (typeof value !== "object" || value === null) return void 0;
945
- const raw = value;
946
- const id = typeof raw["id"] === "string" ? raw["id"] : "";
947
- if (id === "" || raw["disabled"] === true) return void 0;
948
- const input = typeof raw["maxInputTokens"] === "number" ? raw["maxInputTokens"] : 0;
949
- const output = typeof raw["maxOutputTokens"] === "number" ? raw["maxOutputTokens"] : 0;
950
- if (input <= 0 || output <= 0) return void 0;
951
- const name = typeof raw["name"] === "string" && raw["name"] !== "" ? raw["name"] : id;
952
- const descriptionZh = typeof raw["descriptionZh"] === "string" && raw["descriptionZh"] !== "" ? raw["descriptionZh"] : void 0;
953
- const descriptionEn = typeof raw["descriptionEn"] === "string" && raw["descriptionEn"] !== "" ? raw["descriptionEn"] : void 0;
954
- const creditMultiplier = parseCreditMultiplier(raw["credits"]);
955
- const reasoning = parseReasoning(raw["reasoning"]);
956
- const supportsToolCall = typeof raw["supportsToolCall"] === "boolean" ? raw["supportsToolCall"] : void 0;
957
- return {
958
- id,
959
- name,
960
- contextWindow: input,
961
- maxTokens: output,
962
- ...creditMultiplier === void 0 ? {} : { creditMultiplier },
963
- ...reasoning === void 0 ? {} : { reasoning },
964
- ...descriptionZh === void 0 ? {} : { descriptionZh },
965
- ...descriptionEn === void 0 ? {} : { descriptionEn },
966
- ...supportsToolCall === void 0 ? {} : { supportsToolCall }
967
- };
968
- }
969
- /**
970
- * Select the chat-capable models from a catalog-shaped document: parse every
971
- * entry, then keep the `cli` agent's roster in its declared order.
972
- *
973
- * Both the CN personal-models document and the global `/v3/config` document
974
- * carry `models` plus an `agents` roster with the same entry shape, so one
975
- * selector serves them. Without a usable `cli` roster the whole parsed catalog
976
- * is exposed rather than nothing: the roster is an upstream detail that may
977
- * change, and an empty answer would silently disarm the provider.
978
- */
979
- function selectCliModels(rawModels, agents) {
980
- const byId = /* @__PURE__ */ new Map();
981
- for (const model of Array.isArray(rawModels) ? rawModels : []) {
982
- const parsed = parseUpstreamModel(model);
983
- if (parsed !== void 0) byId.set(parsed.id, parsed);
984
- }
985
- let cliIds;
986
- for (const agent of Array.isArray(agents) ? agents : []) if (typeof agent === "object" && agent !== null) {
987
- const wrapped = agent;
988
- if (wrapped["name"] === "cli" && Array.isArray(wrapped["models"])) {
989
- cliIds = wrapped["models"].filter((id) => typeof id === "string");
990
- break;
991
- }
992
- }
993
- const models = (cliIds !== void 0 && cliIds.length > 0 ? cliIds : [...byId.keys()]).map((id) => byId.get(id)).filter((model) => model !== void 0);
994
- if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
995
- return models;
996
- }
997
- /**
998
- * Upstream HTTP client. One instance serves the whole plugin; requests take
999
- * the credential explicitly so token refreshes apply on the next call.
1000
- */
1001
- var WorkBuddyUpstreamClient = class {
1002
- /** POST the chat endpoint; a successful answer is the raw SSE response. */
1003
- async chatStream(credential, bodyJson, signal) {
1004
- let response;
1005
- try {
1006
- response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
1007
- method: "POST",
1008
- headers: {
1009
- ...chatHeaders(credential),
1010
- "Authorization": `Bearer ${credential.accessToken}`
1011
- },
1012
- body: bodyJson,
1013
- ...signal === void 0 ? {} : { signal }
1014
- });
1015
- } catch (error) {
1016
- return {
1017
- ok: false,
1018
- status: 0,
1019
- kind: "server",
1020
- message: `transport error: ${String(error)}`
1021
- };
1022
- }
1023
- if (response.ok) return {
1024
- ok: true,
1025
- response
1026
- };
1027
- const text = (await response.text()).slice(0, ERROR_BODY_LIMIT);
1028
- return {
1029
- ok: false,
1030
- status: response.status,
1031
- kind: classifyUpstreamError(response.status, text),
1032
- message: text
1033
- };
1034
- }
1035
- /** POST the token-refresh endpoint; the caller merges the outcome. */
1036
- async refreshToken(credential) {
1037
- const response = await fetch(`${chatBase(credential)}/v2/plugin/auth/token/refresh`, {
1038
- method: "POST",
1039
- headers: refreshHeaders(credential),
1040
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1041
- });
1042
- const envelope = await readEnvelope(response);
1043
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1044
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1045
- const accessToken = typeof data["accessToken"] === "string" ? data["accessToken"] : "";
1046
- if (accessToken === "") throw new Error("workbuddy token refresh returned no accessToken; sign in again in the WorkBuddy app");
1047
- const outcome = { accessToken };
1048
- if (typeof data["refreshToken"] === "string" && data["refreshToken"] !== "") outcome.refreshToken = data["refreshToken"];
1049
- if (typeof data["expiresIn"] === "number" && data["expiresIn"] > 0) outcome.expiresInSec = data["expiresIn"];
1050
- if (typeof data["domain"] === "string" && data["domain"] !== "") outcome.domain = data["domain"];
1051
- return outcome;
1052
- }
1053
- /**
1054
- * Read the model directory for the credential's region.
1055
- *
1056
- * The two regions expose their chat roster through different documents:
1057
- * CN answers `/v2/enterprises/personal/models`, while the global gateway's
1058
- * personal-models path returns HTTP 500 and the CLI channel's `/v3/config`
1059
- * omits chat-usable models — so global reads `/v3/config` as the desktop
1060
- * channel (see {@link DESKTOP_UA}). Both documents share the entry shape, so
1061
- * one parser serves them. No user-side toggle is involved: the region comes
1062
- * from the credential's `domain`.
1063
- */
1064
- async fetchModels(credential, signal) {
1065
- const timeout = signal ?? AbortSignal.timeout(JSON_TIMEOUT_MS);
1066
- if (regionOf(credential.domain) === "global") {
1067
- const response = await fetch(`${GLOBAL_BASE}${GLOBAL_CONFIG_PATH}`, {
1068
- headers: {
1069
- "Authorization": `Bearer ${credential.accessToken}`,
1070
- "Accept": "application/json",
1071
- ...credential.uid === "" ? {} : { "X-User-Id": credential.uid },
1072
- ...credential.domain === "" ? {} : { "X-Domain": credential.domain },
1073
- "X-Product": "SaaS",
1074
- "X-Requested-With": "XMLHttpRequest",
1075
- "Connection": "close",
1076
- "User-Agent": DESKTOP_UA
1077
- },
1078
- signal: timeout
1079
- });
1080
- const envelope = await readEnvelope(response);
1081
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1082
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1083
- return selectCliModels(data["models"], data["agents"]);
1084
- }
1085
- const response = await fetch(`${chatBase(credential)}${MODELS_CATALOG_PATH}`, {
1086
- headers: {
1087
- "Authorization": `Bearer ${credential.accessToken}`,
1088
- "Accept": "application/json",
1089
- "Origin": originReferer(credential),
1090
- "Referer": `${originReferer(credential)}/`,
1091
- "User-Agent": CLIENT_UA
1092
- },
1093
- signal: timeout
1094
- });
1095
- const envelope = await readEnvelope(response);
1096
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1097
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1098
- return selectCliModels(data["models"], data["agents"]);
1099
- }
1100
- /** Query today's check-in status without changing account state. */
1101
- async fetchCheckinStatus(credential) {
1102
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/checkin-activity-status`, {
1103
- method: "POST",
1104
- headers: billingHeaders(credential),
1105
- body: "{}",
1106
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1107
- });
1108
- const envelope = await readEnvelope(response);
1109
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1110
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1111
- const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
1112
- return {
1113
- active: data["active"] === true,
1114
- todayCheckedIn: data["today_checked_in"] === true,
1115
- streakDays: numberField("streak_days"),
1116
- dailyCredit: numberField("daily_credit"),
1117
- todayCredit: numberField("today_credit"),
1118
- isStreakDay: data["is_streak_day"] === true,
1119
- nextStreakDay: numberField("next_streak_day"),
1120
- streakBonusDays: numberField("streak_bonus_days"),
1121
- streakBonusCredit: numberField("streak_bonus_credit"),
1122
- ...typeof data["claim_button_text"] === "string" && data["claim_button_text"] !== "" ? { claimButtonText: data["claim_button_text"] } : {}
1123
- };
1124
- }
1125
- /** Claim today's check-in reward. The browser route guards this mutation. */
1126
- async claimDailyCheckin(credential) {
1127
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/daily-checkin`, {
1128
- method: "POST",
1129
- headers: billingHeaders(credential),
1130
- body: "{}",
1131
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1132
- });
1133
- const envelope = await readEnvelope(response);
1134
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1135
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1136
- const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
1137
- return {
1138
- credit: numberField("credit"),
1139
- streakDays: numberField("streak_days"),
1140
- isStreakDay: data["is_streak_day"] === true
1141
- };
1142
- }
1143
- /**
1144
- * POST the billing endpoint for the remaining credit, keeping every package
1145
- * separate: the card groups monthly-cycle packages itself and lists the
1146
- * nearest-expiring one-off packages, so aggregation here would lose the
1147
- * dates it needs.
1148
- */
1149
- async fetchCredits(credential) {
1150
- const now = /* @__PURE__ */ new Date();
1151
- const format = (date) => [
1152
- date.getFullYear().toString().padStart(4, "0"),
1153
- (date.getMonth() + 1).toString().padStart(2, "0"),
1154
- date.getDate().toString().padStart(2, "0")
1155
- ].join("-") + " " + [
1156
- date.getHours().toString().padStart(2, "0"),
1157
- date.getMinutes().toString().padStart(2, "0"),
1158
- date.getSeconds().toString().padStart(2, "0")
1159
- ].join(":");
1160
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/get-user-resource`, {
1161
- method: "POST",
1162
- headers: billingHeaders(credential),
1163
- body: JSON.stringify({
1164
- PageNumber: 1,
1165
- PageSize: 100,
1166
- ProductCode: "p_tcaca",
1167
- Status: [0, 3],
1168
- PackageEndTimeRangeBegin: format(now),
1169
- PackageEndTimeRangeEnd: format(new Date(now.getTime() + 3185136e6))
1170
- }),
1171
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1172
- });
1173
- const envelope = await readEnvelope(response);
1174
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1175
- const responseWrapper = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1176
- const data = typeof responseWrapper["Response"] === "object" && responseWrapper["Response"] !== null ? responseWrapper["Response"] : {};
1177
- const inner = typeof data["Data"] === "object" && data["Data"] !== null ? data["Data"] : {};
1178
- const rawAccounts = Array.isArray(inner["Accounts"]) ? inner["Accounts"] : [];
1179
- let total = 0;
1180
- let nearestExpiryMs;
1181
- let expiringSoon = 0;
1182
- const SOON_MS = 2592e5;
1183
- const parseDate = (raw) => {
1184
- if (typeof raw === "number" && raw > 0xe8d4a51000) return raw;
1185
- if (typeof raw === "string" && raw !== "") {
1186
- const parsed = Date.parse(raw);
1187
- if (!Number.isNaN(parsed)) return parsed;
1188
- }
1189
- };
1190
- const packages = [];
1191
- for (const raw of rawAccounts) {
1192
- if (typeof raw !== "object" || raw === null) continue;
1193
- const account = raw;
1194
- const numberField = (key) => typeof account[key] === "number" ? account[key] : 0;
1195
- const monthly = numberField("CapacityType") === 4;
1196
- const size = monthly ? numberField("CycleCapacitySize") : numberField("CapacitySize");
1197
- const remain = monthly ? numberField("CycleCapacityRemain") : numberField("CapacityRemain");
1198
- const cappedRemain = remain < 0 ? 0 : remain;
1199
- const cycleEndMs = parseDate(account["CycleEndTime"]);
1200
- const expiresAtMs = monthly ? void 0 : parseDate(account["ExpiredTime"]) ?? cycleEndMs;
1201
- const refreshAtMs = monthly ? cycleEndMs === void 0 ? void 0 : cycleEndMs + 1e3 : void 0;
1202
- if (!monthly && (cappedRemain <= 0 || expiresAtMs !== void 0 && expiresAtMs <= Date.now())) continue;
1203
- total += cappedRemain;
1204
- const expiryMs = expiresAtMs;
1205
- if (expiryMs !== void 0) {
1206
- if (nearestExpiryMs === void 0 || expiryMs < nearestExpiryMs) nearestExpiryMs = expiryMs;
1207
- if (expiryMs - Date.now() <= SOON_MS) expiringSoon += cappedRemain;
1208
- }
1209
- packages.push({
1210
- packageName: typeof account["PackageName"] === "string" ? account["PackageName"] : "(unnamed)",
1211
- remain: cappedRemain,
1212
- size,
1213
- monthly,
1214
- ...refreshAtMs === void 0 ? {} : { refreshAtMs },
1215
- ...expiresAtMs === void 0 ? {} : { expiresAtMs }
1216
- });
1217
- }
1218
- return {
1219
- total,
1220
- packages,
1221
- expiringSoon,
1222
- ...nearestExpiryMs === void 0 ? {} : { nearestExpiryMs }
1223
- };
1224
- }
1225
- };
1226
- //#endregion
1227
1305
  //#region src/version.ts
1228
1306
  /** The npm package version this build was produced from. */
1229
- const WORKBUDDY_CONNECT_VERSION = "1.4.0";
1307
+ const WORKBUDDY_CONNECT_VERSION = "2.0.0";
1230
1308
  //#endregion
1231
1309
  //#region src/host-heartbeat.ts
1232
1310
  /**
@@ -1332,4 +1410,4 @@ async function clearHostHeartbeat() {
1332
1410
  await rm(workbuddyHostHeartbeatPath(), { force: true });
1333
1411
  }
1334
1412
  //#endregion
1335
- export { workbuddyOwnAuthPath as A, WorkBuddyCredentialStore as C, defaultDesktopAuthPath as D, defaultDesktopAuthDirs as E, parseWorkBuddyAuth as O, WORKBUDDY_AUTH_FILE_ENV as S, defaultDesktopAuthCandidates as T, FALLBACK_WORKBUDDY_MODELS_GLOBAL as _, readHostHeartbeat as a, fallbackModelsFor as b, WORKBUDDY_CONNECT_VERSION as c, parseCreditMultiplier as d, parseReasoning as f, FALLBACK_WORKBUDDY_MODELS as g, regionOf as h, processStartTimeMs as i, workbuddyAccountId as k, 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, WorkBuddyCatalog as v, authFileName as w, WORKBUDDY_AUTH_FILENAME as x, deriveCatalog 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 };