dsh-connect-workbuddy 1.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.
- package/CHANGELOG.md +33 -0
- package/LICENSE +21 -0
- package/README.en.md +141 -0
- package/README.md +143 -0
- package/THIRD_PARTY_NOTICES.md +57 -0
- package/cordis.patch.yml +6 -0
- package/docs/assets/dsh-connect-workbuddy-usage-card.png +0 -0
- package/lib/bin.d.ts +19 -0
- package/lib/bin.js +202 -0
- package/lib/client.js +872 -0
- package/lib/host-heartbeat-DHfQtrSf.js +1118 -0
- package/lib/index.d.ts +651 -0
- package/lib/index.js +792 -0
- package/package.json +114 -0
- package/screenshots.json +3 -0
|
@@ -0,0 +1,1118 @@
|
|
|
1
|
+
import { readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
|
|
6
|
+
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
7
|
+
import { execFileSync } from "node:child_process";
|
|
8
|
+
//#region src/auth.ts
|
|
9
|
+
/**
|
|
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
|
+
* 均能通过上游鉴权,但积分分别为 1875 与 0)。本实现改为扫描整个
|
|
20
|
+
* auth 目录,按 uin 去重为多个可选账号,并默认优先有可用积分的账号。
|
|
21
|
+
* 跟随 App 当前登录仍是默认行为,切换账号是显式选项。
|
|
22
|
+
*
|
|
23
|
+
* @module dsh-connect-workbuddy/auth
|
|
24
|
+
*/
|
|
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
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Platform-default directories holding the WorkBuddy desktop app's auth file.
|
|
39
|
+
*
|
|
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.
|
|
44
|
+
*
|
|
45
|
+
* `platform`, `home`, and `env` are injectable so the platform branches are
|
|
46
|
+
* testable on any host without touching a real machine.
|
|
47
|
+
*/
|
|
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 [];
|
|
60
|
+
}
|
|
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;
|
|
64
|
+
}
|
|
65
|
+
/** The live auth file's platform candidates, in probe order. */
|
|
66
|
+
function defaultDesktopAuthCandidates() {
|
|
67
|
+
return defaultDesktopAuthDirs().map((dir) => join(dir, WORKBUDDY_LIVE_FILENAME));
|
|
68
|
+
}
|
|
69
|
+
/** First platform-default candidate; see {@link defaultDesktopAuthCandidates}. */
|
|
70
|
+
function defaultDesktopAuthPath() {
|
|
71
|
+
return defaultDesktopAuthCandidates()[0];
|
|
72
|
+
}
|
|
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;
|
|
77
|
+
}
|
|
78
|
+
function optionalString(value) {
|
|
79
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
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.
|
|
85
|
+
*/
|
|
86
|
+
function parseWorkBuddyAuth(text, filePath) {
|
|
87
|
+
let parsed;
|
|
88
|
+
try {
|
|
89
|
+
parsed = JSON.parse(text);
|
|
90
|
+
} catch {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
|
|
94
|
+
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
|
+
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
|
|
123
|
+
};
|
|
124
|
+
}
|
|
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);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Stable account id. `uin` is the billing identity the upstream keys on and
|
|
149
|
+
* survives across re-login; `uid` is the fallback for documents without one.
|
|
150
|
+
*/
|
|
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);
|
|
154
|
+
}
|
|
155
|
+
/** Serialize the plugin-owned copy. */
|
|
156
|
+
function ownDocument(credential, accountId) {
|
|
157
|
+
return {
|
|
158
|
+
version: OWN_FORMAT_VERSION,
|
|
159
|
+
...accountId === void 0 ? {} : { accountId },
|
|
160
|
+
credential
|
|
161
|
+
};
|
|
162
|
+
}
|
|
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;
|
|
177
|
+
return {
|
|
178
|
+
...credential,
|
|
179
|
+
source: "dsh"
|
|
180
|
+
};
|
|
181
|
+
}
|
|
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
|
+
/**
|
|
196
|
+
* Read-only credential store with demand-driven refresh and multi-account
|
|
197
|
+
* discovery.
|
|
198
|
+
*
|
|
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.
|
|
204
|
+
*/
|
|
205
|
+
var WorkBuddyCredentialStore = class {
|
|
206
|
+
refresh;
|
|
207
|
+
refreshMarginMs;
|
|
208
|
+
ownPath;
|
|
209
|
+
authDirs;
|
|
210
|
+
desktopPathOverride;
|
|
211
|
+
accountId;
|
|
212
|
+
/** Account ids with usable credit, tried first when nothing is selected. */
|
|
213
|
+
preferIds = [];
|
|
214
|
+
inflight;
|
|
215
|
+
constructor(options) {
|
|
216
|
+
this.refresh = options.refresh;
|
|
217
|
+
this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
|
|
218
|
+
this.ownPath = options.ownPath ?? workbuddyOwnAuthPath();
|
|
219
|
+
this.authDirs = options.authDirs;
|
|
220
|
+
this.desktopPathOverride = options.desktopPath;
|
|
221
|
+
}
|
|
222
|
+
/** Repoint the desktop file or directory; applies on the next read. */
|
|
223
|
+
setDesktopPath(path) {
|
|
224
|
+
this.desktopPathOverride = path;
|
|
225
|
+
this.inflight = void 0;
|
|
226
|
+
}
|
|
227
|
+
/** Select an account by id; tokens stay outside settings. */
|
|
228
|
+
selectAccount(accountId) {
|
|
229
|
+
this.accountId = accountId;
|
|
230
|
+
this.inflight = void 0;
|
|
231
|
+
}
|
|
232
|
+
/** Selected account id, for diagnostics and route assembly. */
|
|
233
|
+
selectedAccountId() {
|
|
234
|
+
return this.accountId;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Preferred account ordering used when no account is explicitly selected.
|
|
238
|
+
* An account with zero credit fails every chat request, so accounts with
|
|
239
|
+
* usable credit must win the default.
|
|
240
|
+
*/
|
|
241
|
+
setPreferAccountIds(ids) {
|
|
242
|
+
this.preferIds = [...ids];
|
|
243
|
+
this.inflight = void 0;
|
|
244
|
+
}
|
|
245
|
+
/** The auth-file path candidates, in probe order. */
|
|
246
|
+
resolveDesktopCandidates() {
|
|
247
|
+
const fromEnv = process.env[WORKBUDDY_AUTH_FILE_ENV];
|
|
248
|
+
const explicit = this.desktopPathOverride ?? (fromEnv !== void 0 && fromEnv.trim() !== "" ? fromEnv : void 0);
|
|
249
|
+
if (explicit !== void 0) return [explicit];
|
|
250
|
+
return defaultDesktopAuthCandidates();
|
|
251
|
+
}
|
|
252
|
+
/** The resolved desktop auth-file path, for diagnostics. */
|
|
253
|
+
desktopAuthPath() {
|
|
254
|
+
return this.resolveDesktopCandidates()[0];
|
|
255
|
+
}
|
|
256
|
+
/** The plugin-owned copy path, for diagnostics. */
|
|
257
|
+
ownAuthPath() {
|
|
258
|
+
return this.ownPath;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Every auth file to scan: the live file plus the timestamped backups
|
|
262
|
+
* WorkBuddy leaves beside it.
|
|
263
|
+
*
|
|
264
|
+
* An explicitly configured path pins the *directory*: its siblings are
|
|
265
|
+
* still scanned, because a user who points the plugin at their auth file
|
|
266
|
+
* expects account switching to work the same way it does on the default
|
|
267
|
+
* path. Only the file ordering changes.
|
|
268
|
+
*
|
|
269
|
+
* A corrupt or signed-out file must never hide the others, so each read is
|
|
270
|
+
* independent and failures are skipped rather than propagated.
|
|
271
|
+
*/
|
|
272
|
+
async candidateFiles() {
|
|
273
|
+
const explicitPath = this.desktopPathOverride ?? ((process.env["WORKBUDDY_AUTH_FILE"] ?? "").trim() !== "" ? process.env["WORKBUDDY_AUTH_FILE"] : void 0);
|
|
274
|
+
const files = [];
|
|
275
|
+
if (explicitPath !== void 0) {
|
|
276
|
+
files.push(explicitPath);
|
|
277
|
+
for (const backup of await this.backupsBeside(explicitPath)) files.push(backup);
|
|
278
|
+
return files;
|
|
279
|
+
}
|
|
280
|
+
const dirs = this.authDirs ?? defaultDesktopAuthDirs();
|
|
281
|
+
for (const dir of dirs) {
|
|
282
|
+
const live = join(dir, WORKBUDDY_LIVE_FILENAME);
|
|
283
|
+
files.push(live);
|
|
284
|
+
for (const backup of await this.backupsBeside(live)) files.push(backup);
|
|
285
|
+
}
|
|
286
|
+
return files;
|
|
287
|
+
}
|
|
288
|
+
/** Timestamped siblings of one auth file, newest first by filename. */
|
|
289
|
+
async backupsBeside(path) {
|
|
290
|
+
const dir = dirname(path);
|
|
291
|
+
const base = path.slice(dir.length + 1);
|
|
292
|
+
try {
|
|
293
|
+
return (await readdir(dir)).filter((name) => name !== base && name.endsWith(".info")).sort().reverse().map((name) => join(dir, name));
|
|
294
|
+
} catch {
|
|
295
|
+
return [];
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Read every local credential, deduplicated by account id. Files are
|
|
300
|
+
* probed newest-first, so the first entry for an account is its freshest.
|
|
301
|
+
*/
|
|
302
|
+
async readAll() {
|
|
303
|
+
const files = await this.candidateFiles();
|
|
304
|
+
const byId = /* @__PURE__ */ new Map();
|
|
305
|
+
for (const file of files) {
|
|
306
|
+
const credential = await readAuthFile(file);
|
|
307
|
+
if (credential === void 0) continue;
|
|
308
|
+
const id = workbuddyAccountId(credential);
|
|
309
|
+
const existing = byId.get(id);
|
|
310
|
+
if (existing === void 0) {
|
|
311
|
+
byId.set(id, credential);
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
if (fileRank(credential.filePath) < fileRank(existing.filePath) || fileRank(credential.filePath) === fileRank(existing.filePath) && credential.expiresAtMs > existing.expiresAtMs) byId.set(id, credential);
|
|
315
|
+
}
|
|
316
|
+
const own = await this.readOwn();
|
|
317
|
+
if (own !== void 0) {
|
|
318
|
+
const id = workbuddyAccountId(own);
|
|
319
|
+
const existing = byId.get(id);
|
|
320
|
+
if (existing === void 0 || own.expiresAtMs > existing.expiresAtMs) byId.set(id, own);
|
|
321
|
+
}
|
|
322
|
+
return [...byId.values()];
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Preferred account first, else the live sign-in, else the freshest
|
|
326
|
+
* credential. Following the app's current sign-in is the documented default
|
|
327
|
+
* behaviour; the backups exist so the user can switch explicitly.
|
|
328
|
+
*/
|
|
329
|
+
preferred(credentials) {
|
|
330
|
+
if (credentials.length === 0) return void 0;
|
|
331
|
+
for (const id of this.preferIds) {
|
|
332
|
+
const match = credentials.find((credential) => workbuddyAccountId(credential) === id);
|
|
333
|
+
if (match !== void 0) return match;
|
|
334
|
+
}
|
|
335
|
+
return credentials.reduce((best, credential) => {
|
|
336
|
+
if (fileRank(credential.filePath) < fileRank(best.filePath)) return credential;
|
|
337
|
+
if (fileRank(credential.filePath) === fileRank(best.filePath) && credential.expiresAtMs > best.expiresAtMs) return credential;
|
|
338
|
+
return best;
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
/** Token-free account list for the plugin card. */
|
|
342
|
+
async accounts() {
|
|
343
|
+
const credentials = await this.readAll();
|
|
344
|
+
if (credentials.length === 0) return [];
|
|
345
|
+
const selectedExists = this.accountId !== void 0 && credentials.some((credential) => workbuddyAccountId(credential) === this.accountId);
|
|
346
|
+
const defaultSelected = this.preferred(credentials);
|
|
347
|
+
return credentials.map((credential) => {
|
|
348
|
+
const id = workbuddyAccountId(credential);
|
|
349
|
+
return {
|
|
350
|
+
id,
|
|
351
|
+
accountName: credential.nickname ?? credential.uin ?? credential.uid,
|
|
352
|
+
...credential.uin === void 0 ? {} : { uin: credential.uin },
|
|
353
|
+
domain: credential.domain,
|
|
354
|
+
source: credential.source,
|
|
355
|
+
tokenExpiresAtMs: credential.expiresAtMs,
|
|
356
|
+
filePath: credential.filePath,
|
|
357
|
+
selected: selectedExists ? id === this.accountId : credential === defaultSelected
|
|
358
|
+
};
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
/** The freshest stored credential for the current selection, no refresh. */
|
|
362
|
+
async current() {
|
|
363
|
+
const credentials = await this.readAll();
|
|
364
|
+
if (this.accountId === void 0) return this.preferred(credentials);
|
|
365
|
+
return credentials.find((credential) => workbuddyAccountId(credential) === this.accountId) ?? this.preferred(credentials);
|
|
366
|
+
}
|
|
367
|
+
/** The credential to send upstream: {@link current}, refreshed on demand. */
|
|
368
|
+
async resolve() {
|
|
369
|
+
const credential = await this.current();
|
|
370
|
+
if (credential === void 0) {
|
|
371
|
+
const candidates = this.resolveDesktopCandidates();
|
|
372
|
+
const desktop = candidates.length > 0 ? candidates.join(" or ") : "(no desktop path on this platform)";
|
|
373
|
+
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`);
|
|
374
|
+
}
|
|
375
|
+
if (!this.needsRefresh(credential)) return credential;
|
|
376
|
+
this.inflight ??= this.refreshNow(credential).finally(() => {
|
|
377
|
+
this.inflight = void 0;
|
|
378
|
+
});
|
|
379
|
+
return this.inflight;
|
|
380
|
+
}
|
|
381
|
+
/** Read-only sign-in summary; never refreshes and never throws. */
|
|
382
|
+
async status() {
|
|
383
|
+
try {
|
|
384
|
+
const credential = await this.current();
|
|
385
|
+
if (credential === void 0) return { state: "signed-out" };
|
|
386
|
+
return {
|
|
387
|
+
state: "signed-in",
|
|
388
|
+
expiresAtMs: credential.expiresAtMs,
|
|
389
|
+
...credential.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs: credential.refreshExpiresAtMs },
|
|
390
|
+
...credential.nickname === void 0 ? {} : { nickname: credential.nickname },
|
|
391
|
+
...credential.domain === "" ? {} : { domain: credential.domain },
|
|
392
|
+
source: credential.source
|
|
393
|
+
};
|
|
394
|
+
} catch {
|
|
395
|
+
return { state: "signed-out" };
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
/** Remove the plugin-owned copy; the desktop files are untouched. */
|
|
399
|
+
async logout() {
|
|
400
|
+
await rm(this.ownPath, { force: true });
|
|
401
|
+
await rm(`${this.ownPath}.lock`, { force: true });
|
|
402
|
+
}
|
|
403
|
+
needsRefresh(credential) {
|
|
404
|
+
if (credential.expiresAtMs <= 0) return true;
|
|
405
|
+
return Date.now() + this.refreshMarginMs >= credential.expiresAtMs;
|
|
406
|
+
}
|
|
407
|
+
async refreshNow(credential) {
|
|
408
|
+
if (credential.refreshToken === "") {
|
|
409
|
+
if (credential.expiresAtMs > Date.now() + 3e4) return credential;
|
|
410
|
+
throw new Error("workbuddy: access token expired and no refresh token is stored; sign in again in the WorkBuddy desktop app");
|
|
411
|
+
}
|
|
412
|
+
try {
|
|
413
|
+
const outcome = await this.refresh(credential);
|
|
414
|
+
const refreshed = {
|
|
415
|
+
...credential,
|
|
416
|
+
accessToken: outcome.accessToken,
|
|
417
|
+
...outcome.refreshToken === void 0 ? {} : { refreshToken: outcome.refreshToken },
|
|
418
|
+
expiresAtMs: outcome.expiresInSec !== void 0 ? Date.now() + outcome.expiresInSec * 1e3 : credential.expiresAtMs,
|
|
419
|
+
...outcome.domain === void 0 || outcome.domain === "" ? {} : { domain: outcome.domain },
|
|
420
|
+
source: "dsh"
|
|
421
|
+
};
|
|
422
|
+
await this.saveOwn(refreshed);
|
|
423
|
+
return refreshed;
|
|
424
|
+
} catch (error) {
|
|
425
|
+
if (credential.expiresAtMs > Date.now() + 3e4) return credential;
|
|
426
|
+
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`);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
async saveOwn(credential) {
|
|
430
|
+
const accountId = workbuddyAccountId(credential);
|
|
431
|
+
await withFileLock(this.ownPath, async () => {
|
|
432
|
+
await writeFileAtomic(this.ownPath, `${JSON.stringify(ownDocument(credential, accountId), null, 2)}\n`, {
|
|
433
|
+
mode: 384,
|
|
434
|
+
dirMode: 448
|
|
435
|
+
});
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
async readOwn() {
|
|
439
|
+
try {
|
|
440
|
+
return parseOwnDocument(await readFile(this.ownPath, "utf8"));
|
|
441
|
+
} catch {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
/** Whether any candidate file exists as a regular file; diagnostics only. */
|
|
446
|
+
async desktopFilePresent() {
|
|
447
|
+
for (const path of this.resolveDesktopCandidates()) try {
|
|
448
|
+
if ((await stat(path)).isFile()) return true;
|
|
449
|
+
} catch {}
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
//#endregion
|
|
454
|
+
//#region src/catalog.ts
|
|
455
|
+
/**
|
|
456
|
+
* Static CLI models captured from the CN endpoint (2026-08-30). The upstream
|
|
457
|
+
* refresh replaces this list at startup; it exists so the provider registers
|
|
458
|
+
* with a usable catalog even while the first fetch is in flight or offline.
|
|
459
|
+
*/
|
|
460
|
+
const FALLBACK_WORKBUDDY_MODELS = [
|
|
461
|
+
{
|
|
462
|
+
id: "auto",
|
|
463
|
+
name: "Auto",
|
|
464
|
+
contextWindow: 168e3,
|
|
465
|
+
maxTokens: 32e3
|
|
466
|
+
},
|
|
467
|
+
{
|
|
468
|
+
id: "hy3",
|
|
469
|
+
name: "Hy3",
|
|
470
|
+
contextWindow: 192e3,
|
|
471
|
+
maxTokens: 64e3
|
|
472
|
+
},
|
|
473
|
+
{
|
|
474
|
+
id: "glm-5v-turbo",
|
|
475
|
+
name: "GLM-5v-Turbo",
|
|
476
|
+
contextWindow: 2e5,
|
|
477
|
+
maxTokens: 64e3
|
|
478
|
+
},
|
|
479
|
+
{
|
|
480
|
+
id: "glm-5.3",
|
|
481
|
+
name: "GLM-5.3",
|
|
482
|
+
contextWindow: 1e6,
|
|
483
|
+
maxTokens: 48e3
|
|
484
|
+
},
|
|
485
|
+
{
|
|
486
|
+
id: "glm-5.2",
|
|
487
|
+
name: "GLM-5.2",
|
|
488
|
+
contextWindow: 1e6,
|
|
489
|
+
maxTokens: 48e3
|
|
490
|
+
},
|
|
491
|
+
{
|
|
492
|
+
id: "glm-5.1",
|
|
493
|
+
name: "GLM-5.1",
|
|
494
|
+
contextWindow: 2e5,
|
|
495
|
+
maxTokens: 48e3
|
|
496
|
+
},
|
|
497
|
+
{
|
|
498
|
+
id: "minimax-m3",
|
|
499
|
+
name: "MiniMax-M3",
|
|
500
|
+
contextWindow: 512e3,
|
|
501
|
+
maxTokens: 128e3
|
|
502
|
+
},
|
|
503
|
+
{
|
|
504
|
+
id: "kimi-k3-1",
|
|
505
|
+
name: "Kimi-K3",
|
|
506
|
+
contextWindow: 1e6,
|
|
507
|
+
maxTokens: 32e3
|
|
508
|
+
},
|
|
509
|
+
{
|
|
510
|
+
id: "kimi-k2.7",
|
|
511
|
+
name: "Kimi-K2.7-Code",
|
|
512
|
+
contextWindow: 256e3,
|
|
513
|
+
maxTokens: 32e3
|
|
514
|
+
},
|
|
515
|
+
{
|
|
516
|
+
id: "kimi-k2.6",
|
|
517
|
+
name: "Kimi-K2.6",
|
|
518
|
+
contextWindow: 256e3,
|
|
519
|
+
maxTokens: 32e3
|
|
520
|
+
},
|
|
521
|
+
{
|
|
522
|
+
id: "deepseek-v4-flash",
|
|
523
|
+
name: "Deepseek-V4-Flash",
|
|
524
|
+
contextWindow: 1e6,
|
|
525
|
+
maxTokens: 5e4
|
|
526
|
+
},
|
|
527
|
+
{
|
|
528
|
+
id: "deepseek-v4-pro",
|
|
529
|
+
name: "Deepseek-V4-Pro",
|
|
530
|
+
contextWindow: 1e6,
|
|
531
|
+
maxTokens: 5e4
|
|
532
|
+
}
|
|
533
|
+
];
|
|
534
|
+
/** Apply the saved local DSH budget; models above 200K default to 200K. */
|
|
535
|
+
function applyContextBudgets(catalog, budgets = {}) {
|
|
536
|
+
return catalog.map((model) => ({
|
|
537
|
+
...model,
|
|
538
|
+
contextWindow: model.contextWindow > 2e5 ? Math.min(model.contextWindow, budgets[model.id] ?? 2e5) : model.contextWindow
|
|
539
|
+
}));
|
|
540
|
+
}
|
|
541
|
+
function deriveCatalog(catalog, enabled, budgets = {}) {
|
|
542
|
+
return applyContextBudgets(enabled.size === 0 ? catalog : catalog.filter((model) => enabled.has(model.id)), budgets);
|
|
543
|
+
}
|
|
544
|
+
/** Mutable catalog shared by the shim's `/v1/models` and the adapter. */
|
|
545
|
+
var WorkBuddyCatalog = class {
|
|
546
|
+
models = FALLBACK_WORKBUDDY_MODELS;
|
|
547
|
+
/** Current entries; the fallback list until the upstream answer lands. */
|
|
548
|
+
current() {
|
|
549
|
+
return this.models;
|
|
550
|
+
}
|
|
551
|
+
/** Replace the list; callers invalidate their adapter snapshot after this. */
|
|
552
|
+
set(models) {
|
|
553
|
+
if (models.length === 0) throw new Error("workbuddy model catalog cannot be empty");
|
|
554
|
+
this.models = models.map((model) => ({ ...model }));
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
//#endregion
|
|
558
|
+
//#region src/upstream.ts
|
|
559
|
+
const CN_CHAT_BASE = "https://copilot.tencent.com";
|
|
560
|
+
const CN_BILLING_BASE = "https://www.codebuddy.cn";
|
|
561
|
+
const GLOBAL_BASE = "https://www.workbuddy.ai";
|
|
562
|
+
const CLIENT_UA = "CLI/2.63.2 CodeBuddy/2.63.2";
|
|
563
|
+
const JSON_TIMEOUT_MS = 3e4;
|
|
564
|
+
const ERROR_BODY_LIMIT = 4096;
|
|
565
|
+
/** Insufficient-credit markers, ASCII lowercase plus the original Chinese. */
|
|
566
|
+
const HARD_CREDIT_MARKERS = [
|
|
567
|
+
"insufficient credit",
|
|
568
|
+
"no credit",
|
|
569
|
+
"credit exhausted",
|
|
570
|
+
"out of credit",
|
|
571
|
+
"quota exceeded",
|
|
572
|
+
"quota exhaust",
|
|
573
|
+
"payment required",
|
|
574
|
+
"credit not enough",
|
|
575
|
+
"not enough credit",
|
|
576
|
+
"积分不足",
|
|
577
|
+
"额度不足",
|
|
578
|
+
"余额不足",
|
|
579
|
+
"积分用完",
|
|
580
|
+
"额度用尽",
|
|
581
|
+
"没有积分"
|
|
582
|
+
];
|
|
583
|
+
/** Session-invalidation markers that mean "sign in again in the WorkBuddy app". */
|
|
584
|
+
const SESSION_DEAD_MARKERS = ["Offline user session not found", "12153"];
|
|
585
|
+
/** Classify an upstream failure from its HTTP status and body excerpt. */
|
|
586
|
+
function classifyUpstreamError(status, body) {
|
|
587
|
+
if (status === 402) return "hard_credit";
|
|
588
|
+
const lower = body.toLowerCase();
|
|
589
|
+
for (const marker of HARD_CREDIT_MARKERS) if (lower.includes(marker.toLowerCase()) || body.includes(marker)) return "hard_credit";
|
|
590
|
+
for (const marker of SESSION_DEAD_MARKERS) if (body.includes(marker)) return "session_dead";
|
|
591
|
+
if (status === 429) return "soft_rate";
|
|
592
|
+
if (status === 404) return "not_found";
|
|
593
|
+
if (status >= 500) return "server";
|
|
594
|
+
if (status >= 400) return "client";
|
|
595
|
+
return "client";
|
|
596
|
+
}
|
|
597
|
+
/** Region for a login domain; an empty domain means CN (matching upstream tooling). */
|
|
598
|
+
function regionOf(domain) {
|
|
599
|
+
const lowered = domain.trim().toLowerCase();
|
|
600
|
+
if (lowered === "workbuddy.ai" || lowered.endsWith(".workbuddy.ai")) return "global";
|
|
601
|
+
return "cn";
|
|
602
|
+
}
|
|
603
|
+
function chatBase(credential) {
|
|
604
|
+
return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_CHAT_BASE;
|
|
605
|
+
}
|
|
606
|
+
function billingBase(credential) {
|
|
607
|
+
return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
|
|
608
|
+
}
|
|
609
|
+
function originReferer(credential) {
|
|
610
|
+
return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
|
|
611
|
+
}
|
|
612
|
+
/** Headers every upstream request shares. */
|
|
613
|
+
function commonHeaders(credential) {
|
|
614
|
+
return {
|
|
615
|
+
"Accept": "application/json, text/plain, */*",
|
|
616
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
617
|
+
"Origin": originReferer(credential),
|
|
618
|
+
"Referer": `${originReferer(credential)}/`,
|
|
619
|
+
"User-Agent": CLIENT_UA
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
/** Chat request headers, including the X-No-* conventions the official CLI uses. */
|
|
623
|
+
function chatHeaders(credential) {
|
|
624
|
+
return {
|
|
625
|
+
...commonHeaders(credential),
|
|
626
|
+
"Content-Type": "application/json",
|
|
627
|
+
...credential.uid === "" ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
|
|
628
|
+
...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
|
|
629
|
+
...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
|
|
630
|
+
"X-Product": "SaaS"
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
/** Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else. */
|
|
634
|
+
function refreshHeaders(credential) {
|
|
635
|
+
const headers = {
|
|
636
|
+
...commonHeaders(credential),
|
|
637
|
+
"X-Refresh-Token": credential.refreshToken,
|
|
638
|
+
"X-Auth-Refresh-Source": "workbuddy"
|
|
639
|
+
};
|
|
640
|
+
if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") headers["X-Enterprise-Id"] = credential.enterpriseId;
|
|
641
|
+
return headers;
|
|
642
|
+
}
|
|
643
|
+
/** Billing request headers. */
|
|
644
|
+
function billingHeaders(credential) {
|
|
645
|
+
const headers = {
|
|
646
|
+
"Authorization": `Bearer ${credential.accessToken}`,
|
|
647
|
+
"Accept": "application/json",
|
|
648
|
+
"Content-Type": "application/json"
|
|
649
|
+
};
|
|
650
|
+
if (credential.uid !== "") headers["X-User-Id"] = credential.uid;
|
|
651
|
+
if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") {
|
|
652
|
+
headers["X-Enterprise-Id"] = credential.enterpriseId;
|
|
653
|
+
headers["X-Tenant-Id"] = credential.enterpriseId;
|
|
654
|
+
}
|
|
655
|
+
if (credential.domain !== "") headers["X-Domain"] = credential.domain;
|
|
656
|
+
return headers;
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Normalize an OpenAI chat-completions body for the WorkBuddy upstream:
|
|
660
|
+
* force `stream: true` (the upstream rejects non-streaming) and flatten
|
|
661
|
+
* `tool_choice` (the upstream's field is a string; object forms return 400).
|
|
662
|
+
*/
|
|
663
|
+
function prepareChatBody(source) {
|
|
664
|
+
let body;
|
|
665
|
+
try {
|
|
666
|
+
body = JSON.parse(source);
|
|
667
|
+
} catch {
|
|
668
|
+
return source;
|
|
669
|
+
}
|
|
670
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) return source;
|
|
671
|
+
const obj = body;
|
|
672
|
+
obj["stream"] = true;
|
|
673
|
+
if (Array.isArray(obj["messages"])) for (const value of obj["messages"]) {
|
|
674
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
|
|
675
|
+
const message = value;
|
|
676
|
+
if (message["role"] === "developer") message["role"] = "system";
|
|
677
|
+
}
|
|
678
|
+
normalizeToolChoice(obj);
|
|
679
|
+
return JSON.stringify(obj);
|
|
680
|
+
}
|
|
681
|
+
/** Rewrite OpenAI `tool_choice` spellings into the upstream's string form. */
|
|
682
|
+
function normalizeToolChoice(obj) {
|
|
683
|
+
const suppress = () => {
|
|
684
|
+
delete obj["tools"];
|
|
685
|
+
delete obj["functions"];
|
|
686
|
+
};
|
|
687
|
+
if (!("tool_choice" in obj)) return;
|
|
688
|
+
const choice = obj["tool_choice"];
|
|
689
|
+
if (typeof choice === "string") {
|
|
690
|
+
if (choice.trim().toLowerCase() === "none") {
|
|
691
|
+
delete obj["tool_choice"];
|
|
692
|
+
suppress();
|
|
693
|
+
}
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
if (typeof choice === "object" && choice !== null && !Array.isArray(choice)) {
|
|
697
|
+
const wrapped = choice;
|
|
698
|
+
const type = typeof wrapped["type"] === "string" ? wrapped["type"].trim().toLowerCase() : "";
|
|
699
|
+
if (type === "none") {
|
|
700
|
+
delete obj["tool_choice"];
|
|
701
|
+
suppress();
|
|
702
|
+
} else if (type === "auto" || type === "required") obj["tool_choice"] = type;
|
|
703
|
+
else if (type === "function") {
|
|
704
|
+
const fn = typeof wrapped["function"] === "object" && wrapped["function"] !== null ? wrapped["function"] : void 0;
|
|
705
|
+
let name = typeof fn?.["name"] === "string" ? fn["name"] : "";
|
|
706
|
+
if (name === "" && typeof wrapped["name"] === "string") name = wrapped["name"];
|
|
707
|
+
name = name.trim();
|
|
708
|
+
obj["tool_choice"] = name !== "" ? name : "auto";
|
|
709
|
+
} else delete obj["tool_choice"];
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
delete obj["tool_choice"];
|
|
713
|
+
}
|
|
714
|
+
async function readEnvelope(response) {
|
|
715
|
+
const text = await response.text();
|
|
716
|
+
let parsed;
|
|
717
|
+
try {
|
|
718
|
+
parsed = JSON.parse(text);
|
|
719
|
+
} catch {
|
|
720
|
+
throw new Error(`workbuddy upstream returned non-JSON (http ${response.status}): ${text.slice(0, 160)}`);
|
|
721
|
+
}
|
|
722
|
+
if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
|
|
723
|
+
const document = parsed;
|
|
724
|
+
return {
|
|
725
|
+
code: typeof document["code"] === "number" ? document["code"] : 0,
|
|
726
|
+
msg: typeof document["msg"] === "string" ? document["msg"] : "",
|
|
727
|
+
data: "data" in document ? document["data"] : void 0
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
/** Fail an envelope whose business code is non-zero, classified like HTTP errors. */
|
|
731
|
+
function envelopeError(status, envelope) {
|
|
732
|
+
const kind = classifyUpstreamError(status, envelope.msg);
|
|
733
|
+
return /* @__PURE__ */ new Error(`workbuddy upstream ${kind} (http ${status}): ${envelope.msg.slice(0, 160)}`);
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Parse the upstream's `credits` string into a multiplier.
|
|
737
|
+
*
|
|
738
|
+
* Observed forms: `"x0.79 credits"`, `"x0.05"`, `"x0.00 credits"`,
|
|
739
|
+
* and absent. Unparsable values yield undefined rather than a guess — the
|
|
740
|
+
* card simply omits the rate instead of displaying a fabricated one.
|
|
741
|
+
*/
|
|
742
|
+
function parseCreditMultiplier(value) {
|
|
743
|
+
if (typeof value !== "string") return void 0;
|
|
744
|
+
const match = /x\s*([0-9]*\.?[0-9]+)/iu.exec(value);
|
|
745
|
+
if (match === null) return void 0;
|
|
746
|
+
const parsed = Number(match[1]);
|
|
747
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
|
|
748
|
+
}
|
|
749
|
+
/** Parse the upstream's `reasoning` object; unknown shapes degrade to `{}`. */
|
|
750
|
+
function parseReasoning(value) {
|
|
751
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
752
|
+
const raw = value;
|
|
753
|
+
const supportedEfforts = Array.isArray(raw["supportedEfforts"]) ? raw["supportedEfforts"].filter((effort) => typeof effort === "string") : void 0;
|
|
754
|
+
const defaultEffort = typeof raw["defaultEffort"] === "string" ? raw["defaultEffort"] : void 0;
|
|
755
|
+
const canDisableThinking = typeof raw["canDisableThinking"] === "boolean" ? raw["canDisableThinking"] : void 0;
|
|
756
|
+
if (supportedEfforts === void 0 && defaultEffort === void 0 && canDisableThinking === void 0) return;
|
|
757
|
+
return {
|
|
758
|
+
...supportedEfforts === void 0 || supportedEfforts.length === 0 ? {} : { supportedEfforts },
|
|
759
|
+
...defaultEffort === void 0 ? {} : { defaultEffort },
|
|
760
|
+
...canDisableThinking === void 0 ? {} : { canDisableThinking }
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
/** Parse one catalog entry; entries without usable token limits are dropped. */
|
|
764
|
+
function parseUpstreamModel(value) {
|
|
765
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
766
|
+
const raw = value;
|
|
767
|
+
const id = typeof raw["id"] === "string" ? raw["id"] : "";
|
|
768
|
+
if (id === "" || raw["disabled"] === true) return void 0;
|
|
769
|
+
const input = typeof raw["maxInputTokens"] === "number" ? raw["maxInputTokens"] : 0;
|
|
770
|
+
const output = typeof raw["maxOutputTokens"] === "number" ? raw["maxOutputTokens"] : 0;
|
|
771
|
+
if (input <= 0 || output <= 0) return void 0;
|
|
772
|
+
const name = typeof raw["name"] === "string" && raw["name"] !== "" ? raw["name"] : id;
|
|
773
|
+
const descriptionZh = typeof raw["descriptionZh"] === "string" && raw["descriptionZh"] !== "" ? raw["descriptionZh"] : void 0;
|
|
774
|
+
const descriptionEn = typeof raw["descriptionEn"] === "string" && raw["descriptionEn"] !== "" ? raw["descriptionEn"] : void 0;
|
|
775
|
+
const creditMultiplier = parseCreditMultiplier(raw["credits"]);
|
|
776
|
+
const reasoning = parseReasoning(raw["reasoning"]);
|
|
777
|
+
const supportsToolCall = typeof raw["supportsToolCall"] === "boolean" ? raw["supportsToolCall"] : void 0;
|
|
778
|
+
return {
|
|
779
|
+
id,
|
|
780
|
+
name,
|
|
781
|
+
contextWindow: input,
|
|
782
|
+
maxTokens: output,
|
|
783
|
+
...creditMultiplier === void 0 ? {} : { creditMultiplier },
|
|
784
|
+
...reasoning === void 0 ? {} : { reasoning },
|
|
785
|
+
...descriptionZh === void 0 ? {} : { descriptionZh },
|
|
786
|
+
...descriptionEn === void 0 ? {} : { descriptionEn },
|
|
787
|
+
...supportsToolCall === void 0 ? {} : { supportsToolCall }
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Upstream HTTP client. One instance serves the whole plugin; requests take
|
|
792
|
+
* the credential explicitly so token refreshes apply on the next call.
|
|
793
|
+
*/
|
|
794
|
+
var WorkBuddyUpstreamClient = class {
|
|
795
|
+
/** POST the chat endpoint; a successful answer is the raw SSE response. */
|
|
796
|
+
async chatStream(credential, bodyJson, signal) {
|
|
797
|
+
let response;
|
|
798
|
+
try {
|
|
799
|
+
response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
|
|
800
|
+
method: "POST",
|
|
801
|
+
headers: {
|
|
802
|
+
...chatHeaders(credential),
|
|
803
|
+
"Authorization": `Bearer ${credential.accessToken}`
|
|
804
|
+
},
|
|
805
|
+
body: bodyJson,
|
|
806
|
+
...signal === void 0 ? {} : { signal }
|
|
807
|
+
});
|
|
808
|
+
} catch (error) {
|
|
809
|
+
return {
|
|
810
|
+
ok: false,
|
|
811
|
+
status: 0,
|
|
812
|
+
kind: "server",
|
|
813
|
+
message: `transport error: ${String(error)}`
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
if (response.ok) return {
|
|
817
|
+
ok: true,
|
|
818
|
+
response
|
|
819
|
+
};
|
|
820
|
+
const text = (await response.text()).slice(0, ERROR_BODY_LIMIT);
|
|
821
|
+
return {
|
|
822
|
+
ok: false,
|
|
823
|
+
status: response.status,
|
|
824
|
+
kind: classifyUpstreamError(response.status, text),
|
|
825
|
+
message: text
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
/** POST the token-refresh endpoint; the caller merges the outcome. */
|
|
829
|
+
async refreshToken(credential) {
|
|
830
|
+
const response = await fetch(`${chatBase(credential)}/v2/plugin/auth/token/refresh`, {
|
|
831
|
+
method: "POST",
|
|
832
|
+
headers: refreshHeaders(credential),
|
|
833
|
+
signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
|
|
834
|
+
});
|
|
835
|
+
const envelope = await readEnvelope(response);
|
|
836
|
+
if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
|
|
837
|
+
const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
|
|
838
|
+
const accessToken = typeof data["accessToken"] === "string" ? data["accessToken"] : "";
|
|
839
|
+
if (accessToken === "") throw new Error("workbuddy token refresh returned no accessToken; sign in again in the WorkBuddy app");
|
|
840
|
+
const outcome = { accessToken };
|
|
841
|
+
if (typeof data["refreshToken"] === "string" && data["refreshToken"] !== "") outcome.refreshToken = data["refreshToken"];
|
|
842
|
+
if (typeof data["expiresIn"] === "number" && data["expiresIn"] > 0) outcome.expiresInSec = data["expiresIn"];
|
|
843
|
+
if (typeof data["domain"] === "string" && data["domain"] !== "") outcome.domain = data["domain"];
|
|
844
|
+
return outcome;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* GET the personal model catalog and keep the `cli` agent's models only,
|
|
848
|
+
* preserving the capability fields the plugin card displays.
|
|
849
|
+
*/
|
|
850
|
+
async fetchModels(credential, signal) {
|
|
851
|
+
const response = await fetch(`${chatBase(credential)}/console/enterprises/personal/models`, {
|
|
852
|
+
headers: {
|
|
853
|
+
"Authorization": `Bearer ${credential.accessToken}`,
|
|
854
|
+
"Accept": "application/json",
|
|
855
|
+
"Origin": originReferer(credential),
|
|
856
|
+
"Referer": `${originReferer(credential)}/`,
|
|
857
|
+
"User-Agent": CLIENT_UA
|
|
858
|
+
},
|
|
859
|
+
signal: signal ?? AbortSignal.timeout(JSON_TIMEOUT_MS)
|
|
860
|
+
});
|
|
861
|
+
const envelope = await readEnvelope(response);
|
|
862
|
+
if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
|
|
863
|
+
const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
|
|
864
|
+
const rawModels = Array.isArray(data["models"]) ? data["models"] : [];
|
|
865
|
+
const agents = Array.isArray(data["agents"]) ? data["agents"] : [];
|
|
866
|
+
let cliIds;
|
|
867
|
+
for (const agent of agents) if (typeof agent === "object" && agent !== null) {
|
|
868
|
+
const wrapped = agent;
|
|
869
|
+
if (wrapped["name"] === "cli" && Array.isArray(wrapped["models"])) {
|
|
870
|
+
cliIds = wrapped["models"].filter((id) => typeof id === "string");
|
|
871
|
+
break;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
const byId = /* @__PURE__ */ new Map();
|
|
875
|
+
for (const model of rawModels) {
|
|
876
|
+
const parsed = parseUpstreamModel(model);
|
|
877
|
+
if (parsed !== void 0) byId.set(parsed.id, parsed);
|
|
878
|
+
}
|
|
879
|
+
const models = (cliIds !== void 0 && cliIds.length > 0 ? cliIds : [...byId.keys()]).map((id) => byId.get(id)).filter((model) => model !== void 0);
|
|
880
|
+
if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
|
|
881
|
+
return models;
|
|
882
|
+
}
|
|
883
|
+
/** Query today's check-in status without changing account state. */
|
|
884
|
+
async fetchCheckinStatus(credential) {
|
|
885
|
+
const response = await fetch(`${billingBase(credential)}/v2/billing/meter/checkin-activity-status`, {
|
|
886
|
+
method: "POST",
|
|
887
|
+
headers: billingHeaders(credential),
|
|
888
|
+
body: "{}",
|
|
889
|
+
signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
|
|
890
|
+
});
|
|
891
|
+
const envelope = await readEnvelope(response);
|
|
892
|
+
if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
|
|
893
|
+
const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
|
|
894
|
+
const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
|
|
895
|
+
return {
|
|
896
|
+
active: data["active"] === true,
|
|
897
|
+
todayCheckedIn: data["today_checked_in"] === true,
|
|
898
|
+
streakDays: numberField("streak_days"),
|
|
899
|
+
dailyCredit: numberField("daily_credit"),
|
|
900
|
+
todayCredit: numberField("today_credit"),
|
|
901
|
+
isStreakDay: data["is_streak_day"] === true,
|
|
902
|
+
nextStreakDay: numberField("next_streak_day"),
|
|
903
|
+
streakBonusDays: numberField("streak_bonus_days"),
|
|
904
|
+
streakBonusCredit: numberField("streak_bonus_credit"),
|
|
905
|
+
...typeof data["claim_button_text"] === "string" && data["claim_button_text"] !== "" ? { claimButtonText: data["claim_button_text"] } : {}
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
/** Claim today's check-in reward. The browser route guards this mutation. */
|
|
909
|
+
async claimDailyCheckin(credential) {
|
|
910
|
+
const response = await fetch(`${billingBase(credential)}/v2/billing/meter/daily-checkin`, {
|
|
911
|
+
method: "POST",
|
|
912
|
+
headers: billingHeaders(credential),
|
|
913
|
+
body: "{}",
|
|
914
|
+
signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
|
|
915
|
+
});
|
|
916
|
+
const envelope = await readEnvelope(response);
|
|
917
|
+
if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
|
|
918
|
+
const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
|
|
919
|
+
const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
|
|
920
|
+
return {
|
|
921
|
+
credit: numberField("credit"),
|
|
922
|
+
streakDays: numberField("streak_days"),
|
|
923
|
+
isStreakDay: data["is_streak_day"] === true
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* POST the billing endpoint for the remaining credit, keeping every package
|
|
928
|
+
* separate: the card groups monthly-cycle packages itself and lists the
|
|
929
|
+
* nearest-expiring one-off packages, so aggregation here would lose the
|
|
930
|
+
* dates it needs.
|
|
931
|
+
*/
|
|
932
|
+
async fetchCredits(credential) {
|
|
933
|
+
const now = /* @__PURE__ */ new Date();
|
|
934
|
+
const format = (date) => [
|
|
935
|
+
date.getFullYear().toString().padStart(4, "0"),
|
|
936
|
+
(date.getMonth() + 1).toString().padStart(2, "0"),
|
|
937
|
+
date.getDate().toString().padStart(2, "0")
|
|
938
|
+
].join("-") + " " + [
|
|
939
|
+
date.getHours().toString().padStart(2, "0"),
|
|
940
|
+
date.getMinutes().toString().padStart(2, "0"),
|
|
941
|
+
date.getSeconds().toString().padStart(2, "0")
|
|
942
|
+
].join(":");
|
|
943
|
+
const response = await fetch(`${billingBase(credential)}/v2/billing/meter/get-user-resource`, {
|
|
944
|
+
method: "POST",
|
|
945
|
+
headers: billingHeaders(credential),
|
|
946
|
+
body: JSON.stringify({
|
|
947
|
+
PageNumber: 1,
|
|
948
|
+
PageSize: 100,
|
|
949
|
+
ProductCode: "p_tcaca",
|
|
950
|
+
Status: [0, 3],
|
|
951
|
+
PackageEndTimeRangeBegin: format(now),
|
|
952
|
+
PackageEndTimeRangeEnd: format(new Date(now.getTime() + 3185136e6))
|
|
953
|
+
}),
|
|
954
|
+
signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
|
|
955
|
+
});
|
|
956
|
+
const envelope = await readEnvelope(response);
|
|
957
|
+
if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
|
|
958
|
+
const responseWrapper = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
|
|
959
|
+
const data = typeof responseWrapper["Response"] === "object" && responseWrapper["Response"] !== null ? responseWrapper["Response"] : {};
|
|
960
|
+
const inner = typeof data["Data"] === "object" && data["Data"] !== null ? data["Data"] : {};
|
|
961
|
+
const rawAccounts = Array.isArray(inner["Accounts"]) ? inner["Accounts"] : [];
|
|
962
|
+
let total = 0;
|
|
963
|
+
let nearestExpiryMs;
|
|
964
|
+
let expiringSoon = 0;
|
|
965
|
+
const SOON_MS = 2592e5;
|
|
966
|
+
const parseDate = (raw) => {
|
|
967
|
+
if (typeof raw === "number" && raw > 0xe8d4a51000) return raw;
|
|
968
|
+
if (typeof raw === "string" && raw !== "") {
|
|
969
|
+
const parsed = Date.parse(raw);
|
|
970
|
+
if (!Number.isNaN(parsed)) return parsed;
|
|
971
|
+
}
|
|
972
|
+
};
|
|
973
|
+
const packages = [];
|
|
974
|
+
for (const raw of rawAccounts) {
|
|
975
|
+
if (typeof raw !== "object" || raw === null) continue;
|
|
976
|
+
const account = raw;
|
|
977
|
+
const numberField = (key) => typeof account[key] === "number" ? account[key] : 0;
|
|
978
|
+
const monthly = numberField("CapacityType") === 4;
|
|
979
|
+
const size = monthly ? numberField("CycleCapacitySize") : numberField("CapacitySize");
|
|
980
|
+
const remain = monthly ? numberField("CycleCapacityRemain") : numberField("CapacityRemain");
|
|
981
|
+
const cappedRemain = remain < 0 ? 0 : remain;
|
|
982
|
+
const cycleEndMs = parseDate(account["CycleEndTime"]);
|
|
983
|
+
const expiresAtMs = monthly ? void 0 : parseDate(account["ExpiredTime"]) ?? cycleEndMs;
|
|
984
|
+
const refreshAtMs = monthly ? cycleEndMs === void 0 ? void 0 : cycleEndMs + 1e3 : void 0;
|
|
985
|
+
if (!monthly && (cappedRemain <= 0 || expiresAtMs !== void 0 && expiresAtMs <= Date.now())) continue;
|
|
986
|
+
total += cappedRemain;
|
|
987
|
+
const expiryMs = expiresAtMs;
|
|
988
|
+
if (expiryMs !== void 0) {
|
|
989
|
+
if (nearestExpiryMs === void 0 || expiryMs < nearestExpiryMs) nearestExpiryMs = expiryMs;
|
|
990
|
+
if (expiryMs - Date.now() <= SOON_MS) expiringSoon += cappedRemain;
|
|
991
|
+
}
|
|
992
|
+
packages.push({
|
|
993
|
+
packageName: typeof account["PackageName"] === "string" ? account["PackageName"] : "(unnamed)",
|
|
994
|
+
remain: cappedRemain,
|
|
995
|
+
size,
|
|
996
|
+
monthly,
|
|
997
|
+
...refreshAtMs === void 0 ? {} : { refreshAtMs },
|
|
998
|
+
...expiresAtMs === void 0 ? {} : { expiresAtMs }
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
return {
|
|
1002
|
+
total,
|
|
1003
|
+
packages,
|
|
1004
|
+
expiringSoon,
|
|
1005
|
+
...nearestExpiryMs === void 0 ? {} : { nearestExpiryMs }
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
};
|
|
1009
|
+
//#endregion
|
|
1010
|
+
//#region src/version.ts
|
|
1011
|
+
/** The npm package version this build was produced from. */
|
|
1012
|
+
const WORKBUDDY_CONNECT_VERSION = "1.0.0";
|
|
1013
|
+
//#endregion
|
|
1014
|
+
//#region src/host-heartbeat.ts
|
|
1015
|
+
/**
|
|
1016
|
+
* Host-side heartbeat: a small JSON file written under `$DSH_HOME` once the
|
|
1017
|
+
* `workbuddy` provider is registered. The status CLI reads it to report
|
|
1018
|
+
* whether the host bundle is alive, independent of the browser card.
|
|
1019
|
+
*
|
|
1020
|
+
* 参考:corrinehu/dsh-workbuddy-connect(MIT,Copyright (c) 2026 Corrine Hu)
|
|
1021
|
+
* — 该机制由其设计:浏览器端无法写文件,其健康只能靠 console.error 上报,
|
|
1022
|
+
* 因此由宿主写心跳文件,缺失即代表宿主从未启动;崩溃后的陈旧心跳
|
|
1023
|
+
* 通过 PID 存活检查识别。
|
|
1024
|
+
* 改动:无。机制本身已完备,原样沿用。
|
|
1025
|
+
*
|
|
1026
|
+
* @module dsh-connect-workbuddy/host-heartbeat
|
|
1027
|
+
*/
|
|
1028
|
+
/** Basename of the host heartbeat file inside the Harness home. */
|
|
1029
|
+
const WORKBUDDY_HOST_HEARTBEAT_FILENAME = ".workbuddy-host-heartbeat.json";
|
|
1030
|
+
/** Current on-disk heartbeat format; readers reject others. */
|
|
1031
|
+
const HEARTBEAT_FORMAT_VERSION = 1;
|
|
1032
|
+
/** Absolute path of the host heartbeat file. */
|
|
1033
|
+
function workbuddyHostHeartbeatPath() {
|
|
1034
|
+
return join(resolveDshHome(), WORKBUDDY_HOST_HEARTBEAT_FILENAME);
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Process start time in epoch milliseconds; undefined when unavailable.
|
|
1038
|
+
*
|
|
1039
|
+
* POSIX reads `ps -o lstart=`; Windows has no such command, so the creation
|
|
1040
|
+
* time is taken from PowerShell's `Get-Process` StartTime, emitted as UTC ISO
|
|
1041
|
+
* 8601 so `Date.parse` understands it without locale assumptions. Absent or
|
|
1042
|
+
* unqueryable processes (other users' processes) degrade to undefined.
|
|
1043
|
+
*/
|
|
1044
|
+
function processStartTimeMs(pid) {
|
|
1045
|
+
try {
|
|
1046
|
+
const output = process.platform === "win32" ? execFileSync("powershell", [
|
|
1047
|
+
"-NoProfile",
|
|
1048
|
+
"-NonInteractive",
|
|
1049
|
+
"-Command",
|
|
1050
|
+
`(Get-Process -Id ${pid} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`
|
|
1051
|
+
], { encoding: "utf8" }) : execFileSync("ps", [
|
|
1052
|
+
"-o",
|
|
1053
|
+
"lstart=",
|
|
1054
|
+
"-p",
|
|
1055
|
+
String(pid)
|
|
1056
|
+
], { encoding: "utf8" });
|
|
1057
|
+
const parsed = Date.parse(output.trim());
|
|
1058
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1059
|
+
} catch {
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Whether the recorded host process still matches the heartbeat's PID.
|
|
1065
|
+
*
|
|
1066
|
+
* A PID can be reused after a crash, so the recorded start time is compared
|
|
1067
|
+
* against the live process: a different start time means a different process.
|
|
1068
|
+
*/
|
|
1069
|
+
function isHeartbeatProcessAlive(heartbeat) {
|
|
1070
|
+
if (!Number.isInteger(heartbeat.pid) || heartbeat.pid <= 0) return false;
|
|
1071
|
+
try {
|
|
1072
|
+
process.kill(heartbeat.pid, 0);
|
|
1073
|
+
} catch {
|
|
1074
|
+
return false;
|
|
1075
|
+
}
|
|
1076
|
+
const startedAt = processStartTimeMs(heartbeat.pid);
|
|
1077
|
+
if (startedAt === void 0) return true;
|
|
1078
|
+
return Math.abs(startedAt - heartbeat.registeredAt) < 6e4;
|
|
1079
|
+
}
|
|
1080
|
+
/** Read the heartbeat; absent or unparsable files report undefined. */
|
|
1081
|
+
async function readHostHeartbeat() {
|
|
1082
|
+
try {
|
|
1083
|
+
const parsed = JSON.parse(await readFile(workbuddyHostHeartbeatPath(), "utf8"));
|
|
1084
|
+
if (typeof parsed !== "object" || parsed === null) return void 0;
|
|
1085
|
+
const document = parsed;
|
|
1086
|
+
if (document["version"] !== HEARTBEAT_FORMAT_VERSION) return void 0;
|
|
1087
|
+
if (document["package"] !== "dsh-connect-workbuddy") return void 0;
|
|
1088
|
+
const pid = document["pid"];
|
|
1089
|
+
const registeredAt = document["registeredAt"];
|
|
1090
|
+
if (typeof pid !== "number" || typeof registeredAt !== "number") return void 0;
|
|
1091
|
+
return {
|
|
1092
|
+
version: HEARTBEAT_FORMAT_VERSION,
|
|
1093
|
+
package: "dsh-connect-workbuddy",
|
|
1094
|
+
pluginVersion: typeof document["pluginVersion"] === "string" ? document["pluginVersion"] : WORKBUDDY_CONNECT_VERSION,
|
|
1095
|
+
registeredAt,
|
|
1096
|
+
pid
|
|
1097
|
+
};
|
|
1098
|
+
} catch {
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
/** Write the heartbeat for the current process. */
|
|
1103
|
+
async function writeHostHeartbeat() {
|
|
1104
|
+
const heartbeat = {
|
|
1105
|
+
version: HEARTBEAT_FORMAT_VERSION,
|
|
1106
|
+
package: "dsh-connect-workbuddy",
|
|
1107
|
+
pluginVersion: WORKBUDDY_CONNECT_VERSION,
|
|
1108
|
+
registeredAt: Date.now(),
|
|
1109
|
+
pid: process.pid
|
|
1110
|
+
};
|
|
1111
|
+
await writeFile(workbuddyHostHeartbeatPath(), `${JSON.stringify(heartbeat, null, 2)}\n`, { mode: 384 });
|
|
1112
|
+
}
|
|
1113
|
+
/** Remove the heartbeat; called when the plugin is disposed. */
|
|
1114
|
+
async function clearHostHeartbeat() {
|
|
1115
|
+
await rm(workbuddyHostHeartbeatPath(), { force: true });
|
|
1116
|
+
}
|
|
1117
|
+
//#endregion
|
|
1118
|
+
export { defaultDesktopAuthCandidates as C, workbuddyAccountId as D, parseWorkBuddyAuth as E, workbuddyOwnAuthPath as O, authFileName as S, defaultDesktopAuthPath as T, WorkBuddyCatalog as _, readHostHeartbeat as a, WORKBUDDY_AUTH_FILE_ENV as b, WORKBUDDY_CONNECT_VERSION as c, parseCreditMultiplier as d, parseReasoning as f, FALLBACK_WORKBUDDY_MODELS as g, regionOf as h, processStartTimeMs as i, WorkBuddyUpstreamClient as l, prepareChatBody as m, clearHostHeartbeat as n, workbuddyHostHeartbeatPath as o, parseUpstreamModel as p, isHeartbeatProcessAlive as r, writeHostHeartbeat as s, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, classifyUpstreamError as u, deriveCatalog as v, defaultDesktopAuthDirs as w, WorkBuddyCredentialStore as x, WORKBUDDY_AUTH_FILENAME as y };
|