dsh-workbuddy-connect 0.3.2 → 0.5.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.
@@ -1,1198 +0,0 @@
1
- import { readFile, rm, stat, writeFile } from "node:fs/promises";
2
- import { homedir, release } from "node:os";
3
- import { basename, join } from "node:path";
4
- import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
5
- import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
6
- import { execFileSync } from "node:child_process";
7
- //#region src/auth.ts
8
- /**
9
- * WorkBuddy credential resolution. The primary source is the WorkBuddy
10
- * desktop app's own auth file, read-only; a plugin-owned copy under
11
- * `$DSH_HOME` holds token refreshes so the desktop file is never written.
12
- * The effective credential is whichever of the two expires later, so a
13
- * refresh by either side wins.
14
- *
15
- * @module dsh-workbuddy-connect/auth
16
- */
17
- /** Basename of the plugin-owned credential copy inside the Harness home. */
18
- const WORKBUDDY_AUTH_FILENAME = ".workbuddy-auth.json";
19
- /** Env variable that overrides the desktop auth-file location. */
20
- const WORKBUDDY_AUTH_FILE_ENV = "WORKBUDDY_AUTH_FILE";
21
- /** Current on-disk format of the plugin-owned copy; readers reject others. */
22
- const OWN_FORMAT_VERSION = 1;
23
- /** Plugin-owned copy path inside the Harness home. */
24
- function workbuddyOwnAuthPath() {
25
- return join(resolveDshHome(), WORKBUDDY_AUTH_FILENAME);
26
- }
27
- const DESKTOP_AUTH_RELATIVE_PATH = [
28
- "CodeBuddyExtension",
29
- "Data",
30
- "Public",
31
- "auth",
32
- "workbuddy-desktop.info"
33
- ];
34
- /** Whether this Linux process is running inside Windows Subsystem for Linux. */
35
- function isWsl() {
36
- if (process.platform !== "linux") return false;
37
- if (process.env["WSL_DISTRO_NAME"] !== void 0 || process.env["WSL_INTEROP"] !== void 0) return true;
38
- return release().toLowerCase().includes("microsoft");
39
- }
40
- /** Convert a Windows drive path to WSL's conventional `/mnt/<drive>` form. */
41
- function windowsPathForWsl(value) {
42
- const path = value?.trim();
43
- if (!path) return void 0;
44
- if (path.startsWith("/")) return path;
45
- const drivePath = /^([a-z]):[\\/](.*)$/iu.exec(path);
46
- if (drivePath === null) return void 0;
47
- return join("/mnt", drivePath[1].toLowerCase(), ...drivePath[2].split(/[\\/]+/u));
48
- }
49
- /** Windows desktop credential candidates visible from a WSL process. */
50
- function wslDesktopAuthCandidates(home) {
51
- const profile = windowsPathForWsl(process.env["USERPROFILE"]) ?? join("/mnt/c/Users", basename(home));
52
- const localAppData = windowsPathForWsl(process.env["LOCALAPPDATA"]) ?? join(profile, "AppData", "Local");
53
- const roamingAppData = windowsPathForWsl(process.env["APPDATA"]) ?? join(profile, "AppData", "Roaming");
54
- return [join(localAppData, ...DESKTOP_AUTH_RELATIVE_PATH), join(roamingAppData, ...DESKTOP_AUTH_RELATIVE_PATH)];
55
- }
56
- /**
57
- * Platform-default candidates for the WorkBuddy desktop app's auth file, in
58
- * probe order. Windows probes both AppData roots: current builds write under
59
- * `%LOCALAPPDATA%` (Local), older ones under `%APPDATA%` (Roaming). WSL probes
60
- * those same Windows locations through its mounted Windows profile before the
61
- * native Linux location.
62
- */
63
- function defaultDesktopAuthCandidates() {
64
- const home = homedir();
65
- if (process.platform === "darwin") return [join(home, "Library", "Application Support", "CodeBuddyExtension", "Data", "Public", "auth", "workbuddy-desktop.info")];
66
- if (process.platform === "win32") return [join(home, "AppData", "Local", "CodeBuddyExtension", "Data", "Public", "auth", "workbuddy-desktop.info"), join(home, "AppData", "Roaming", "CodeBuddyExtension", "Data", "Public", "auth", "workbuddy-desktop.info")];
67
- if (process.platform === "linux") {
68
- const linux = join(home, ".config", ...DESKTOP_AUTH_RELATIVE_PATH);
69
- return isWsl() ? [...wslDesktopAuthCandidates(home), linux] : [linux];
70
- }
71
- return [];
72
- }
73
- /** First platform-default candidate; see {@link defaultDesktopAuthCandidates}. */
74
- function defaultDesktopAuthPath() {
75
- return defaultDesktopAuthCandidates()[0];
76
- }
77
- /** Normalize an expiry that may arrive in seconds or milliseconds. */
78
- function expiryToMs(value) {
79
- if (value <= 0) return 0;
80
- return value > 0xe8d4a51000 ? value : value * 1e3;
81
- }
82
- function optionalString(value) {
83
- return typeof value === "string" && value !== "" ? value : void 0;
84
- }
85
- /**
86
- * Parse a WorkBuddy auth document in either on-disk shape: the plugin OAuth
87
- * nested form `{"auth":{...},"account":{...}}` and the flat panel form.
88
- * Returns undefined when the document carries no access token.
89
- */
90
- function parseWorkBuddyAuth(text) {
91
- let parsed;
92
- try {
93
- parsed = JSON.parse(text);
94
- } catch {
95
- return;
96
- }
97
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
98
- const document = parsed;
99
- let auth;
100
- let identity;
101
- if (typeof document["auth"] === "object" && document["auth"] !== null) {
102
- auth = document["auth"];
103
- identity = typeof document["account"] === "object" && document["account"] !== null ? document["account"] : {};
104
- } else {
105
- auth = document;
106
- identity = document;
107
- }
108
- const accessToken = typeof auth["accessToken"] === "string" ? auth["accessToken"] : "";
109
- if (accessToken === "") return void 0;
110
- const expiresAtMs = typeof auth["expiresAt"] === "number" ? expiryToMs(auth["expiresAt"]) : 0;
111
- const refreshExpiresAtMs = typeof auth["refreshExpiresAt"] === "number" ? expiryToMs(auth["refreshExpiresAt"]) : void 0;
112
- const enterpriseId = optionalString(identity["enterpriseId"]);
113
- const nickname = optionalString(identity["nickname"]);
114
- return {
115
- accessToken,
116
- refreshToken: typeof auth["refreshToken"] === "string" ? auth["refreshToken"] : "",
117
- expiresAtMs,
118
- ...refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs },
119
- domain: optionalString(auth["domain"]) ?? "",
120
- uid: optionalString(identity["uid"]) ?? "",
121
- ...enterpriseId === void 0 ? {} : { enterpriseId },
122
- ...nickname === void 0 ? {} : { nickname },
123
- source: "desktop"
124
- };
125
- }
126
- /** Serialize the plugin-owned copy. */
127
- function ownDocument(credential) {
128
- return {
129
- version: OWN_FORMAT_VERSION,
130
- credential
131
- };
132
- }
133
- /** Parse the plugin-owned copy; other versions and shapes are rejected. */
134
- function parseOwnDocument(text) {
135
- let parsed;
136
- try {
137
- parsed = JSON.parse(text);
138
- } catch {
139
- return;
140
- }
141
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
142
- const document = parsed;
143
- if (document["version"] !== OWN_FORMAT_VERSION) return void 0;
144
- if (typeof document["credential"] !== "object" || document["credential"] === null) return void 0;
145
- const stored = document["credential"];
146
- const accessToken = typeof stored["accessToken"] === "string" ? stored["accessToken"] : "";
147
- if (accessToken === "") return void 0;
148
- const refreshExpiresAtMs = typeof stored["refreshExpiresAtMs"] === "number" ? stored["refreshExpiresAtMs"] : void 0;
149
- const enterpriseId = optionalString(stored["enterpriseId"]);
150
- const nickname = optionalString(stored["nickname"]);
151
- return {
152
- accessToken,
153
- refreshToken: typeof stored["refreshToken"] === "string" ? stored["refreshToken"] : "",
154
- expiresAtMs: typeof stored["expiresAtMs"] === "number" ? stored["expiresAtMs"] : 0,
155
- ...refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs },
156
- domain: optionalString(stored["domain"]) ?? "",
157
- uid: optionalString(stored["uid"]) ?? "",
158
- ...enterpriseId === void 0 ? {} : { enterpriseId },
159
- ...nickname === void 0 ? {} : { nickname },
160
- source: "dsh"
161
- };
162
- }
163
- /** Whether a filesystem error reports an absent path. */
164
- function isENOENT(error) {
165
- return error?.code === "ENOENT";
166
- }
167
- /**
168
- * Read-only credential store with demand-driven refresh.
169
- *
170
- * Refresh policy: refresh only when the access token is inside the margin
171
- * (or already expired), keep the refreshed credential in the plugin-owned
172
- * copy, and never write the desktop app's file. A failed refresh still
173
- * returns a not-yet-expired token so an unreachable refresh endpoint does
174
- * not take down a working session.
175
- */
176
- var WorkBuddyCredentialStore = class {
177
- refresh;
178
- refreshMarginMs;
179
- ownPath;
180
- desktopPathOverride;
181
- inflight;
182
- constructor(options) {
183
- this.refresh = options.refresh;
184
- this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
185
- this.ownPath = options.ownPath ?? workbuddyOwnAuthPath();
186
- this.desktopPathOverride = options.desktopPath;
187
- }
188
- /**
189
- * Configuration precedence for the desktop file: the plugin's configured
190
- * path, then the environment variable, then the platform defaults. An
191
- * explicit path is used verbatim; the defaults are a probe order.
192
- */
193
- resolveDesktopCandidates() {
194
- const fromEnv = process.env[WORKBUDDY_AUTH_FILE_ENV];
195
- const explicit = this.desktopPathOverride ?? (fromEnv !== void 0 && fromEnv.trim() !== "" ? fromEnv : void 0);
196
- if (explicit !== void 0) return [explicit];
197
- return defaultDesktopAuthCandidates();
198
- }
199
- resolveDesktopPath() {
200
- return this.resolveDesktopCandidates()[0];
201
- }
202
- /**
203
- * Repoint the desktop file; a settings change applies on the next read.
204
- */
205
- setDesktopPath(path) {
206
- this.desktopPathOverride = path;
207
- }
208
- /** The resolved desktop auth-file path, for diagnostics. */
209
- desktopAuthPath() {
210
- return this.resolveDesktopPath();
211
- }
212
- /** The plugin-owned copy path, for diagnostics. */
213
- ownAuthPath() {
214
- return this.ownPath;
215
- }
216
- /** Read the freshest stored credential without refreshing anything. */
217
- async current() {
218
- const [desktop, own] = await Promise.all([this.readDesktop(), this.readOwn()]);
219
- if (desktop === void 0) return own;
220
- if (own === void 0) return desktop;
221
- return own.expiresAtMs > desktop.expiresAtMs ? own : desktop;
222
- }
223
- /**
224
- * The credential to send upstream: {@link current}, refreshed on demand.
225
- * Single-flight, so parallel requests share one refresh.
226
- */
227
- async resolve() {
228
- const credential = await this.current();
229
- if (credential === void 0) {
230
- const candidates = this.resolveDesktopCandidates();
231
- const desktop = candidates.length > 0 ? candidates.join(" or ") : "(no desktop path on this platform)";
232
- throw new Error(`workbuddy: no signed-in WorkBuddy account found; sign in once in the WorkBuddy desktop app (expected ${desktop} or WORKBUDDY_AUTH_FILE), or refresh an existing session`);
233
- }
234
- if (!this.needsRefresh(credential)) return credential;
235
- this.inflight ??= this.refreshNow(credential).finally(() => {
236
- this.inflight = void 0;
237
- });
238
- return this.inflight;
239
- }
240
- /** Read-only sign-in summary; never refreshes and never throws. */
241
- async status() {
242
- try {
243
- const credential = await this.current();
244
- if (credential === void 0) return { state: "signed-out" };
245
- return {
246
- state: "signed-in",
247
- expiresAtMs: credential.expiresAtMs,
248
- ...credential.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs: credential.refreshExpiresAtMs },
249
- ...credential.nickname === void 0 ? {} : { nickname: credential.nickname },
250
- ...credential.domain === "" ? {} : { domain: credential.domain },
251
- source: credential.source
252
- };
253
- } catch {
254
- return { state: "signed-out" };
255
- }
256
- }
257
- /** Remove the plugin-owned copy; the desktop file is untouched. */
258
- async logout() {
259
- await rm(this.ownPath, { force: true });
260
- await rm(`${this.ownPath}.lock`, { force: true });
261
- }
262
- needsRefresh(credential) {
263
- if (credential.expiresAtMs <= 0) return true;
264
- return Date.now() + this.refreshMarginMs >= credential.expiresAtMs;
265
- }
266
- async refreshNow(credential) {
267
- if (credential.refreshToken === "") {
268
- if (credential.expiresAtMs > Date.now() + 3e4) return credential;
269
- throw new Error("workbuddy: access token expired and no refresh token is stored; sign in again in the WorkBuddy desktop app");
270
- }
271
- try {
272
- const outcome = await this.refresh(credential);
273
- const refreshed = {
274
- ...credential,
275
- accessToken: outcome.accessToken,
276
- ...outcome.refreshToken === void 0 ? {} : { refreshToken: outcome.refreshToken },
277
- expiresAtMs: outcome.expiresInSec !== void 0 ? Date.now() + outcome.expiresInSec * 1e3 : credential.expiresAtMs,
278
- ...outcome.domain === void 0 || outcome.domain === "" ? {} : { domain: outcome.domain },
279
- source: "dsh"
280
- };
281
- await this.saveOwn(refreshed);
282
- return refreshed;
283
- } catch (error) {
284
- if (credential.expiresAtMs > Date.now() + 3e4) return credential;
285
- 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`);
286
- }
287
- }
288
- async saveOwn(credential) {
289
- await withFileLock(this.ownPath, async () => {
290
- await writeFileAtomic(this.ownPath, `${JSON.stringify(ownDocument(credential), null, 2)}\n`, {
291
- mode: 384,
292
- dirMode: 448
293
- });
294
- });
295
- }
296
- /**
297
- * Read the first desktop candidate that exists. Only an absent file
298
- * (ENOENT) falls through to the next candidate; a file that is present
299
- * but unparsable is authoritative for its slot, so a stale older-version
300
- * file never silently wins over a broken newer one.
301
- */
302
- async readDesktop() {
303
- for (const desktopPath of this.resolveDesktopCandidates()) try {
304
- return parseWorkBuddyAuth(await readFile(desktopPath, "utf8"));
305
- } catch (error) {
306
- if (!isENOENT(error)) throw error;
307
- }
308
- }
309
- async readOwn() {
310
- try {
311
- return parseOwnDocument(await readFile(this.ownPath, "utf8"));
312
- } catch (error) {
313
- if (isENOENT(error)) return void 0;
314
- return;
315
- }
316
- }
317
- /** Whether any desktop-file candidate exists as a regular file; diagnostics only. */
318
- async desktopFilePresent() {
319
- for (const desktopPath of this.resolveDesktopCandidates()) try {
320
- if ((await stat(desktopPath)).isFile()) return true;
321
- } catch {}
322
- return false;
323
- }
324
- };
325
- //#endregion
326
- //#region src/catalog.ts
327
- /**
328
- * Static CLI models observed on the CN endpoint (re-verified against the live
329
- * catalog 2026-09-01, including the thinking-effort and billing metadata). The
330
- * upstream refresh replaces this list at startup; it exists so the provider
331
- * registers with a usable catalog even while the first fetch is in flight or
332
- * offline.
333
- *
334
- * The list tracks the `cli` agent's model roster exactly: the 15 models the
335
- * desktop CLI offers. Reasoning metadata is taken verbatim from the live
336
- * endpoint — each model's supported effort set and whether thinking can be
337
- * disabled — and the `free` flag follows the upstream `x0.00` credits marker.
338
- */
339
- const FALLBACK_WORKBUDDY_MODELS = [
340
- {
341
- id: "auto",
342
- name: "Auto",
343
- contextWindow: 168e3,
344
- maxTokens: 32e3,
345
- supportsImages: true,
346
- reasoning: {
347
- supports: true,
348
- onlyReasoning: true,
349
- defaultEffort: "high",
350
- canDisableThinking: false
351
- },
352
- billing: { free: false }
353
- },
354
- {
355
- id: "hy3",
356
- name: "Hy3",
357
- contextWindow: 192e3,
358
- maxTokens: 64e3,
359
- supportsImages: true,
360
- reasoning: {
361
- supports: true,
362
- onlyReasoning: true,
363
- defaultEffort: "high",
364
- canDisableThinking: false
365
- },
366
- billing: {
367
- credits: "x0.00",
368
- badges: ["限时免费"],
369
- free: true
370
- }
371
- },
372
- {
373
- id: "glm-5.2",
374
- name: "GLM-5.2",
375
- contextWindow: 1e6,
376
- maxTokens: 48e3,
377
- supportsImages: true,
378
- reasoning: {
379
- supports: true,
380
- onlyReasoning: true,
381
- defaultEffort: "medium",
382
- canDisableThinking: false
383
- },
384
- billing: {
385
- credits: "x0.79 credits",
386
- badges: ["夜间折扣"],
387
- free: false
388
- }
389
- },
390
- {
391
- id: "glm-5.1",
392
- name: "GLM-5.1",
393
- contextWindow: 2e5,
394
- maxTokens: 48e3,
395
- supportsImages: false,
396
- reasoning: {
397
- supports: true,
398
- onlyReasoning: true,
399
- defaultEffort: "medium",
400
- canDisableThinking: false
401
- },
402
- billing: {
403
- credits: "x0.79 credits",
404
- free: false
405
- }
406
- },
407
- {
408
- id: "glm-5v-turbo",
409
- name: "GLM-5v-Turbo",
410
- contextWindow: 2e5,
411
- maxTokens: 64e3,
412
- supportsImages: true,
413
- reasoning: {
414
- supports: true,
415
- onlyReasoning: true,
416
- defaultEffort: "medium",
417
- canDisableThinking: false
418
- },
419
- billing: {
420
- credits: "x0.71 credits",
421
- free: false
422
- }
423
- },
424
- {
425
- id: "kimi-k3-1",
426
- name: "Kimi-K3",
427
- contextWindow: 1e6,
428
- maxTokens: 32e3,
429
- supportsImages: true,
430
- reasoning: {
431
- supports: true,
432
- onlyReasoning: true,
433
- defaultEffort: "medium",
434
- canDisableThinking: false
435
- },
436
- billing: {
437
- credits: "x1.62 credits",
438
- free: false
439
- }
440
- },
441
- {
442
- id: "kimi-k2.7",
443
- name: "Kimi-K2.7-Code",
444
- contextWindow: 256e3,
445
- maxTokens: 32e3,
446
- supportsImages: true,
447
- reasoning: {
448
- supports: true,
449
- onlyReasoning: true,
450
- defaultEffort: "medium",
451
- canDisableThinking: false
452
- },
453
- billing: {
454
- credits: "x0.57 credits",
455
- free: false
456
- }
457
- },
458
- {
459
- id: "kimi-k2.6",
460
- name: "Kimi-K2.6",
461
- contextWindow: 256e3,
462
- maxTokens: 32e3,
463
- supportsImages: true,
464
- reasoning: {
465
- supports: true,
466
- onlyReasoning: true,
467
- defaultEffort: "medium",
468
- canDisableThinking: false
469
- },
470
- billing: {
471
- credits: "x0.52 credits",
472
- free: false
473
- }
474
- },
475
- {
476
- id: "minimax-m3",
477
- name: "MiniMax-M3",
478
- contextWindow: 512e3,
479
- maxTokens: 128e3,
480
- supportsImages: true,
481
- reasoning: {
482
- supports: true,
483
- onlyReasoning: true,
484
- defaultEffort: "medium",
485
- canDisableThinking: false
486
- },
487
- billing: {
488
- credits: "x0.25 credits",
489
- free: false
490
- }
491
- },
492
- {
493
- id: "deepseek-v4-flash",
494
- name: "Deepseek-V4-Flash",
495
- contextWindow: 1e6,
496
- maxTokens: 5e4,
497
- supportsImages: true,
498
- reasoning: {
499
- supports: true,
500
- onlyReasoning: true,
501
- defaultEffort: "high",
502
- canDisableThinking: false
503
- },
504
- billing: {
505
- credits: "x0.17 credits",
506
- free: false
507
- }
508
- },
509
- {
510
- id: "deepseek-v4-pro",
511
- name: "Deepseek-V4-Pro",
512
- contextWindow: 1e6,
513
- maxTokens: 5e4,
514
- supportsImages: true,
515
- reasoning: {
516
- supports: true,
517
- onlyReasoning: true,
518
- defaultEffort: "high",
519
- canDisableThinking: false
520
- },
521
- billing: {
522
- credits: "x0.51 credits",
523
- free: false
524
- }
525
- },
526
- {
527
- id: "hy4-preview",
528
- name: "Hy4 preview",
529
- contextWindow: 1e6,
530
- maxTokens: 64e3,
531
- supportsImages: true,
532
- reasoning: {
533
- supports: true,
534
- onlyReasoning: true,
535
- supportedEfforts: ["high"],
536
- defaultEffort: "high",
537
- canDisableThinking: false
538
- },
539
- billing: {
540
- credits: "x0.00",
541
- badges: ["限时免费"],
542
- free: true
543
- }
544
- },
545
- {
546
- id: "hy3-x",
547
- name: "Hy3",
548
- contextWindow: 192e3,
549
- maxTokens: 64e3,
550
- supportsImages: true,
551
- reasoning: {
552
- supports: true,
553
- onlyReasoning: true,
554
- supportedEfforts: ["low", "high"],
555
- defaultEffort: "high",
556
- canDisableThinking: false
557
- },
558
- billing: {
559
- credits: "x0.05",
560
- free: false
561
- }
562
- },
563
- {
564
- id: "glm-5.3",
565
- name: "GLM-5.3",
566
- contextWindow: 1e6,
567
- maxTokens: 48e3,
568
- supportsImages: true,
569
- reasoning: {
570
- supports: true,
571
- onlyReasoning: true,
572
- supportedEfforts: [
573
- "low",
574
- "high",
575
- "xhigh"
576
- ],
577
- defaultEffort: "high",
578
- canDisableThinking: true
579
- },
580
- billing: {
581
- credits: "x0.79",
582
- free: false
583
- }
584
- },
585
- {
586
- id: "glm-5.3-flash",
587
- name: "GLM-5.3-Flash",
588
- contextWindow: 1e6,
589
- maxTokens: 32e3,
590
- supportsImages: true,
591
- reasoning: {
592
- supports: true,
593
- onlyReasoning: true,
594
- supportedEfforts: [
595
- "low",
596
- "high",
597
- "max"
598
- ],
599
- defaultEffort: "high",
600
- canDisableThinking: true
601
- },
602
- billing: {
603
- credits: "x0.06",
604
- free: false
605
- }
606
- }
607
- ];
608
- /** Mutable catalog shared by the shim's `/v1/models` and the adapter. */
609
- var WorkBuddyCatalog = class {
610
- models = FALLBACK_WORKBUDDY_MODELS;
611
- /** Current entries; the fallback list until the upstream answer lands. */
612
- current() {
613
- return this.models;
614
- }
615
- /** Replace the list; callers invalidate their adapter snapshot after this. */
616
- set(models) {
617
- this.models = [...models];
618
- }
619
- };
620
- //#endregion
621
- //#region src/upstream.ts
622
- const CN_CHAT_BASE = "https://copilot.tencent.com";
623
- const CN_BILLING_BASE = "https://www.codebuddy.cn";
624
- const GLOBAL_BASE = "https://www.workbuddy.ai";
625
- const CLIENT_UA = "CLI/2.63.2 CodeBuddy/2.63.2";
626
- const JSON_TIMEOUT_MS = 3e4;
627
- const ERROR_BODY_LIMIT = 4096;
628
- /** Insufficient-credit markers, ASCII lowercase plus the original Chinese. */
629
- const HARD_CREDIT_MARKERS = [
630
- "insufficient credit",
631
- "no credit",
632
- "credit exhausted",
633
- "out of credit",
634
- "quota exceeded",
635
- "quota exhaust",
636
- "payment required",
637
- "credit not enough",
638
- "not enough credit",
639
- "积分不足",
640
- "额度不足",
641
- "余额不足",
642
- "积分用完",
643
- "额度用尽",
644
- "没有积分"
645
- ];
646
- /** The concrete effort spellings WorkBuddy exposes on the wire. */
647
- const EFFORT_VALUES = [
648
- "low",
649
- "medium",
650
- "high",
651
- "xhigh",
652
- "max"
653
- ];
654
- /** Promotional badge keys the upstream tags carry, minus their color suffix. */
655
- const BADGE_PREFIX = "badge:";
656
- /** Parse the upstream `reasoning` object into {@link WorkBuddyModelReasoning}. */
657
- function resolveUpstreamReasoning(wrapped) {
658
- const supports = wrapped["supportsReasoning"] === true;
659
- const onlyReasoning = wrapped["onlyReasoning"] === true;
660
- const rawReasoning = wrapped["reasoning"];
661
- let supportedEfforts;
662
- let defaultEffort;
663
- let canDisableThinking = true;
664
- if (typeof rawReasoning === "object" && rawReasoning !== null && !Array.isArray(rawReasoning)) {
665
- const reasoning = rawReasoning;
666
- const rawEfforts = reasoning["supportedEfforts"];
667
- if (Array.isArray(rawEfforts)) {
668
- const efforts = rawEfforts.filter((value) => typeof value === "string" && EFFORT_VALUES.includes(value));
669
- if (efforts.length > 0) supportedEfforts = efforts;
670
- }
671
- if (typeof reasoning["defaultEffort"] === "string" && EFFORT_VALUES.includes(reasoning["defaultEffort"])) defaultEffort = reasoning["defaultEffort"];
672
- else if (typeof reasoning["effort"] === "string" && EFFORT_VALUES.includes(reasoning["effort"])) defaultEffort = reasoning["effort"];
673
- canDisableThinking = reasoning["canDisableThinking"] === true;
674
- }
675
- return { reasoning: {
676
- supports,
677
- onlyReasoning,
678
- ...supportedEfforts === void 0 ? {} : { supportedEfforts },
679
- ...defaultEffort === void 0 ? {} : { defaultEffort },
680
- canDisableThinking
681
- } };
682
- }
683
- /**
684
- * Reduce an upstream credits string to its language-neutral display form.
685
- *
686
- * The host LLM seam carries this text to the browser, and the host has no
687
- * locale service — whatever string is produced here is shown verbatim in every
688
- * UI language. The upstream is inconsistent in a way that matters: some catalog
689
- * rows report a bare multiplier (`x0.79`) and others append a unit word
690
- * (`x0.79 credits`), and the unit word would pin the display to English.
691
- * Dropping a trailing `credits` (case-insensitive, singular or plural) yields
692
- * the one spelling that reads identically in every language.
693
- *
694
- * @param credits - raw upstream credits string, e.g. `"x0.79 credits"`.
695
- * @returns the bare multiplier, or undefined when nothing displayable remains.
696
- */
697
- function normalizeCredits(credits) {
698
- if (credits === void 0) return void 0;
699
- const trimmed = credits.trim();
700
- if (trimmed === "") return void 0;
701
- if (/^credits?$/iu.test(trimmed)) return void 0;
702
- const bare = trimmed.replace(/\s+credits?$/iu, "").trim();
703
- return bare === "" ? void 0 : bare;
704
- }
705
- /** Parse the upstream `tags` / `credits` fields into billing metadata. */
706
- function resolveUpstreamBilling(wrapped) {
707
- const rawCredits = wrapped["credits"];
708
- const credits = typeof rawCredits === "string" && rawCredits.trim() !== "" ? rawCredits.trim() : void 0;
709
- const badges = [];
710
- const rawTags = wrapped["tags"];
711
- if (Array.isArray(rawTags)) for (const tag of rawTags) {
712
- if (typeof tag !== "string") continue;
713
- if (!tag.toLowerCase().startsWith(BADGE_PREFIX)) continue;
714
- const label = tag.slice(6).split(":")[0] ?? tag.slice(6);
715
- if (label !== "") badges.push(label);
716
- }
717
- const free = credits !== void 0 && /^x?0\.0+$/u.test(credits);
718
- return { billing: {
719
- ...credits === void 0 ? {} : { credits },
720
- ...badges.length === 0 ? {} : { badges },
721
- free
722
- } };
723
- }
724
- /** Session-invalidation markers that mean "sign in again in the WorkBuddy app". */
725
- const SESSION_DEAD_MARKERS = ["Offline user session not found", "12153"];
726
- /** Classify an upstream failure from its HTTP status and body excerpt. */
727
- function classifyUpstreamError(status, body) {
728
- if (status === 402) return "hard_credit";
729
- const lower = body.toLowerCase();
730
- for (const marker of HARD_CREDIT_MARKERS) if (lower.includes(marker.toLowerCase()) || body.includes(marker)) return "hard_credit";
731
- for (const marker of SESSION_DEAD_MARKERS) if (body.includes(marker)) return "session_dead";
732
- if (status === 429) return "soft_rate";
733
- if (status === 404) return "not_found";
734
- if (status >= 500) return "server";
735
- if (status >= 400) return "client";
736
- return "client";
737
- }
738
- /** Region for a login domain; an empty domain means CN (matching upstream tooling). */
739
- function regionOf(domain) {
740
- const lowered = domain.trim().toLowerCase();
741
- if (lowered === "workbuddy.ai" || lowered.endsWith(".workbuddy.ai")) return "global";
742
- return "cn";
743
- }
744
- function chatBase(credential) {
745
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_CHAT_BASE;
746
- }
747
- function billingBase(credential) {
748
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
749
- }
750
- function originReferer(credential) {
751
- return regionOf(credential.domain) === "global" ? GLOBAL_BASE : CN_BILLING_BASE;
752
- }
753
- /** Headers every upstream request shares. */
754
- function commonHeaders(credential) {
755
- return {
756
- "Accept": "application/json, text/plain, */*",
757
- "X-Requested-With": "XMLHttpRequest",
758
- "Origin": originReferer(credential),
759
- "Referer": `${originReferer(credential)}/`,
760
- "User-Agent": CLIENT_UA
761
- };
762
- }
763
- /** Chat request headers, including the X-No-* conventions the official CLI uses. */
764
- function chatHeaders(credential) {
765
- return {
766
- ...commonHeaders(credential),
767
- "Content-Type": "application/json",
768
- ...credential.uid === "" ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
769
- ...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
770
- ...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
771
- "X-Product": "SaaS"
772
- };
773
- }
774
- /** Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else. */
775
- function refreshHeaders(credential) {
776
- const headers = {
777
- ...commonHeaders(credential),
778
- "X-Refresh-Token": credential.refreshToken,
779
- "X-Auth-Refresh-Source": "workbuddy"
780
- };
781
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") headers["X-Enterprise-Id"] = credential.enterpriseId;
782
- return headers;
783
- }
784
- /** Billing request headers. */
785
- function billingHeaders(credential) {
786
- const headers = {
787
- "Authorization": `Bearer ${credential.accessToken}`,
788
- "Accept": "application/json",
789
- "Content-Type": "application/json"
790
- };
791
- if (credential.uid !== "") headers["X-User-Id"] = credential.uid;
792
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") {
793
- headers["X-Enterprise-Id"] = credential.enterpriseId;
794
- headers["X-Tenant-Id"] = credential.enterpriseId;
795
- }
796
- if (credential.domain !== "") headers["X-Domain"] = credential.domain;
797
- return headers;
798
- }
799
- /**
800
- * Normalize an OpenAI chat-completions body for the WorkBuddy upstream:
801
- * force `stream: true` (the upstream rejects non-streaming), flatten
802
- * `tool_choice` (the upstream's field is a string; object forms return 400),
803
- * and rewrite `developer` messages as `system`.
804
- *
805
- * The `developer` rewrite is load-bearing: pi-ai emits the system prompt as
806
- * `role: "developer"` (the OpenAI convention it adopted), but the WorkBuddy
807
- * upstream rejects that role with HTTP 400 code 11128 ("Illegal API
808
- * invocation from an unapproved channel"). Rewriting to `system` is the
809
- * compatible spelling the upstream accepts.
810
- */
811
- function prepareChatBody(source) {
812
- let body;
813
- try {
814
- body = JSON.parse(source);
815
- } catch {
816
- return source;
817
- }
818
- if (typeof body !== "object" || body === null || Array.isArray(body)) return source;
819
- const obj = body;
820
- obj["stream"] = true;
821
- normalizeDeveloperRole(obj);
822
- normalizeToolChoice(obj);
823
- return JSON.stringify(obj);
824
- }
825
- /** Rewrite `role: "developer"` messages to `role: "system"` (upstream rejects developer). */
826
- function normalizeDeveloperRole(obj) {
827
- const messages = obj["messages"];
828
- if (!Array.isArray(messages)) return;
829
- for (const message of messages) {
830
- if (typeof message !== "object" || message === null || Array.isArray(message)) continue;
831
- const wrapped = message;
832
- if (wrapped["role"] === "developer") wrapped["role"] = "system";
833
- }
834
- }
835
- /** Rewrite OpenAI `tool_choice` spellings into the upstream's string form. */
836
- function normalizeToolChoice(obj) {
837
- const suppress = () => {
838
- delete obj["tools"];
839
- delete obj["functions"];
840
- };
841
- if (!("tool_choice" in obj)) return;
842
- const choice = obj["tool_choice"];
843
- if (typeof choice === "string") {
844
- if (choice.trim().toLowerCase() === "none") {
845
- delete obj["tool_choice"];
846
- suppress();
847
- }
848
- return;
849
- }
850
- if (typeof choice === "object" && choice !== null && !Array.isArray(choice)) {
851
- const wrapped = choice;
852
- const type = typeof wrapped["type"] === "string" ? wrapped["type"].trim().toLowerCase() : "";
853
- if (type === "none") {
854
- delete obj["tool_choice"];
855
- suppress();
856
- } else if (type === "auto" || type === "required") obj["tool_choice"] = type;
857
- else if (type === "function") {
858
- const fn = typeof wrapped["function"] === "object" && wrapped["function"] !== null ? wrapped["function"] : void 0;
859
- let name = typeof fn?.["name"] === "string" ? fn["name"] : "";
860
- if (name === "" && typeof wrapped["name"] === "string") name = wrapped["name"];
861
- name = name.trim();
862
- obj["tool_choice"] = name !== "" ? name : "auto";
863
- } else delete obj["tool_choice"];
864
- return;
865
- }
866
- delete obj["tool_choice"];
867
- }
868
- async function readEnvelope(response) {
869
- const text = await response.text();
870
- let parsed;
871
- try {
872
- parsed = JSON.parse(text);
873
- } catch {
874
- throw new Error(`workbuddy upstream returned non-JSON (http ${response.status}): ${text.slice(0, 160)}`);
875
- }
876
- if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
877
- const document = parsed;
878
- return {
879
- code: typeof document["code"] === "number" ? document["code"] : 0,
880
- msg: typeof document["msg"] === "string" ? document["msg"] : "",
881
- data: "data" in document ? document["data"] : void 0
882
- };
883
- }
884
- /** Fail an envelope whose business code is non-zero, classified like HTTP errors. */
885
- function envelopeError(status, envelope) {
886
- const kind = classifyUpstreamError(status, envelope.msg);
887
- return /* @__PURE__ */ new Error(`workbuddy upstream ${kind} (http ${status}): ${envelope.msg.slice(0, 160)}`);
888
- }
889
- /**
890
- * Upstream HTTP client. One instance serves the whole plugin; requests take
891
- * the credential explicitly so token refreshes apply on the next call.
892
- */
893
- var WorkBuddyUpstreamClient = class {
894
- /** POST the chat endpoint; a successful answer is the raw SSE response. */
895
- async chatStream(credential, bodyJson, signal) {
896
- let response;
897
- try {
898
- response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
899
- method: "POST",
900
- headers: {
901
- ...chatHeaders(credential),
902
- "Authorization": `Bearer ${credential.accessToken}`
903
- },
904
- body: bodyJson,
905
- ...signal === void 0 ? {} : { signal }
906
- });
907
- } catch (error) {
908
- return {
909
- ok: false,
910
- status: 0,
911
- kind: "server",
912
- message: `transport error: ${String(error)}`
913
- };
914
- }
915
- if (response.ok) return {
916
- ok: true,
917
- response
918
- };
919
- const text = (await response.text()).slice(0, ERROR_BODY_LIMIT);
920
- return {
921
- ok: false,
922
- status: response.status,
923
- kind: classifyUpstreamError(response.status, text),
924
- message: text
925
- };
926
- }
927
- /** POST the token-refresh endpoint; the caller merges the outcome. */
928
- async refreshToken(credential) {
929
- const response = await fetch(`${chatBase(credential)}/v2/plugin/auth/token/refresh`, {
930
- method: "POST",
931
- headers: refreshHeaders(credential),
932
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
933
- });
934
- const envelope = await readEnvelope(response);
935
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
936
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
937
- const accessToken = typeof data["accessToken"] === "string" ? data["accessToken"] : "";
938
- if (accessToken === "") throw new Error("workbuddy token refresh returned no accessToken; sign in again in the WorkBuddy app");
939
- const outcome = { accessToken };
940
- if (typeof data["refreshToken"] === "string" && data["refreshToken"] !== "") outcome.refreshToken = data["refreshToken"];
941
- if (typeof data["expiresIn"] === "number" && data["expiresIn"] > 0) outcome.expiresInSec = data["expiresIn"];
942
- if (typeof data["domain"] === "string" && data["domain"] !== "") outcome.domain = data["domain"];
943
- return outcome;
944
- }
945
- /** GET the personal model catalog and keep the `cli` agent's models only. */
946
- async fetchModels(credential) {
947
- const response = await fetch(`${chatBase(credential)}/console/enterprises/personal/models`, {
948
- headers: {
949
- "Authorization": `Bearer ${credential.accessToken}`,
950
- "Accept": "application/json",
951
- "Origin": originReferer(credential),
952
- "Referer": `${originReferer(credential)}/`,
953
- "User-Agent": CLIENT_UA
954
- },
955
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
956
- });
957
- const envelope = await readEnvelope(response);
958
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
959
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
960
- const rawModels = Array.isArray(data["models"]) ? data["models"] : [];
961
- const agents = Array.isArray(data["agents"]) ? data["agents"] : [];
962
- let cliIds;
963
- for (const agent of agents) if (typeof agent === "object" && agent !== null) {
964
- const wrapped = agent;
965
- if (wrapped["name"] === "cli" && Array.isArray(wrapped["models"])) {
966
- cliIds = wrapped["models"].filter((id) => typeof id === "string");
967
- break;
968
- }
969
- }
970
- if (cliIds === void 0 || cliIds.length === 0) throw new Error("workbuddy model catalog lists no cli agent models");
971
- const byId = /* @__PURE__ */ new Map();
972
- for (const model of rawModels) {
973
- if (typeof model !== "object" || model === null) continue;
974
- const wrapped = model;
975
- const id = typeof wrapped["id"] === "string" ? wrapped["id"] : "";
976
- if (id === "" || wrapped["disabled"] === true) continue;
977
- const input = typeof wrapped["maxInputTokens"] === "number" ? wrapped["maxInputTokens"] : 0;
978
- const output = typeof wrapped["maxOutputTokens"] === "number" ? wrapped["maxOutputTokens"] : 0;
979
- if (input <= 0 || output <= 0) continue;
980
- byId.set(id, {
981
- id,
982
- name: typeof wrapped["name"] === "string" && wrapped["name"] !== "" ? wrapped["name"] : id,
983
- contextWindow: input,
984
- maxTokens: output,
985
- supportsImages: wrapped["supportsImages"] === true && wrapped["disabledMultimodal"] !== true,
986
- ...resolveUpstreamReasoning(wrapped),
987
- ...resolveUpstreamBilling(wrapped)
988
- });
989
- }
990
- const models = cliIds.map((id) => byId.get(id)).filter((model) => model !== void 0);
991
- if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
992
- return models;
993
- }
994
- /** POST the billing endpoint for the aggregated remaining credit. */
995
- async fetchCredits(credential) {
996
- const now = /* @__PURE__ */ new Date();
997
- const format = (date) => [
998
- date.getFullYear().toString().padStart(4, "0"),
999
- (date.getMonth() + 1).toString().padStart(2, "0"),
1000
- date.getDate().toString().padStart(2, "0")
1001
- ].join("-") + " " + [
1002
- date.getHours().toString().padStart(2, "0"),
1003
- date.getMinutes().toString().padStart(2, "0"),
1004
- date.getSeconds().toString().padStart(2, "0")
1005
- ].join(":");
1006
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/get-user-resource`, {
1007
- method: "POST",
1008
- headers: billingHeaders(credential),
1009
- body: JSON.stringify({
1010
- PageNumber: 1,
1011
- PageSize: 100,
1012
- ProductCode: "p_tcaca",
1013
- Status: [0, 3],
1014
- PackageEndTimeRangeBegin: format(now),
1015
- PackageEndTimeRangeEnd: format(new Date(now.getTime() + 3185136e6))
1016
- }),
1017
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1018
- });
1019
- const envelope = await readEnvelope(response);
1020
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1021
- const responseWrapper = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1022
- const data = typeof responseWrapper["Response"] === "object" && responseWrapper["Response"] !== null ? responseWrapper["Response"] : {};
1023
- const inner = typeof data["Data"] === "object" && data["Data"] !== null ? data["Data"] : {};
1024
- const rawAccounts = Array.isArray(inner["Accounts"]) ? inner["Accounts"] : [];
1025
- const accounts = [];
1026
- let total = 0;
1027
- for (const raw of rawAccounts) {
1028
- if (typeof raw !== "object" || raw === null) continue;
1029
- const account = raw;
1030
- const numberField = (key) => typeof account[key] === "number" ? account[key] : 0;
1031
- const size = numberField("CycleCapacitySize");
1032
- const cycleRemain = numberField("CycleCapacityRemain");
1033
- const cycleUsed = numberField("CycleCapacityUsed");
1034
- const capacityRemain = numberField("CapacityRemain");
1035
- let remain;
1036
- if (size > 0) remain = cycleRemain;
1037
- else if (cycleRemain > 0 || cycleUsed > 0) remain = cycleRemain;
1038
- else remain = capacityRemain;
1039
- if (remain < 0) remain = 0;
1040
- total += remain;
1041
- accounts.push({
1042
- packageName: typeof account["PackageName"] === "string" ? account["PackageName"] : "(unnamed)",
1043
- remain,
1044
- size: size > 0 ? size : numberField("CapacitySize")
1045
- });
1046
- }
1047
- return {
1048
- total,
1049
- accounts
1050
- };
1051
- }
1052
- };
1053
- //#endregion
1054
- //#region src/version.ts
1055
- const WORKBUDDY_CONNECT_VERSION = "0.3.2";
1056
- //#endregion
1057
- //#region src/host-heartbeat.ts
1058
- /**
1059
- * Host-side heartbeat: a small JSON file written under `$DSH_HOME` once the
1060
- * `workbuddy` provider is registered. The status CLI reads it to report
1061
- * whether the host bundle is alive, independent of the browser card.
1062
- *
1063
- * The browser (client) bundle cannot write files; its health is reported
1064
- * only through `console.error` on failure (see `src/client/index.tsx`).
1065
- * This asymmetry is intentional: the host is the load-bearing half, and
1066
- * a missing heartbeat unambiguously means the host never started.
1067
- *
1068
- * @module dsh-workbuddy-connect/host-heartbeat
1069
- */
1070
- /** Basename of the host heartbeat file inside the Harness home. */
1071
- const WORKBUDDY_HOST_HEARTBEAT_FILENAME = ".workbuddy-host-heartbeat.json";
1072
- /** Current on-disk heartbeat format; readers reject others. */
1073
- const HEARTBEAT_FORMAT_VERSION = 1;
1074
- /** Absolute path of the host heartbeat file. */
1075
- function workbuddyHostHeartbeatPath() {
1076
- return join(resolveDshHome(), WORKBUDDY_HOST_HEARTBEAT_FILENAME);
1077
- }
1078
- /**
1079
- * Write (or overwrite) the heartbeat after the host bundle registered the
1080
- * provider. A failed write is non-fatal: the host is already running, and
1081
- * the status CLI will simply report "heartbeat missing" rather than failing.
1082
- */
1083
- async function writeHostHeartbeat() {
1084
- const document = {
1085
- version: HEARTBEAT_FORMAT_VERSION,
1086
- package: "dsh-workbuddy-connect",
1087
- pluginVersion: WORKBUDDY_CONNECT_VERSION,
1088
- registeredAt: Date.now(),
1089
- pid: process.pid
1090
- };
1091
- try {
1092
- await writeFile(workbuddyHostHeartbeatPath(), JSON.stringify(document), "utf8");
1093
- } catch {}
1094
- }
1095
- /** Remove the heartbeat on plugin disposal so a stale file does not linger. */
1096
- async function clearHostHeartbeat() {
1097
- try {
1098
- await rm(workbuddyHostHeartbeatPath(), { force: true });
1099
- } catch {}
1100
- }
1101
- /** Read and validate the heartbeat; returns `undefined` when absent or malformed. */
1102
- async function readHostHeartbeat() {
1103
- let raw;
1104
- try {
1105
- raw = await readFile(workbuddyHostHeartbeatPath(), "utf8");
1106
- } catch {
1107
- return;
1108
- }
1109
- try {
1110
- const parsed = JSON.parse(raw);
1111
- if (parsed.version === HEARTBEAT_FORMAT_VERSION && parsed.package === "dsh-workbuddy-connect" && typeof parsed.registeredAt === "number" && typeof parsed.pid === "number") return {
1112
- version: HEARTBEAT_FORMAT_VERSION,
1113
- package: "dsh-workbuddy-connect",
1114
- pluginVersion: typeof parsed.pluginVersion === "string" ? parsed.pluginVersion : "unknown",
1115
- registeredAt: parsed.registeredAt,
1116
- pid: parsed.pid
1117
- };
1118
- } catch {}
1119
- }
1120
- /**
1121
- * Absolute start time (epoch ms) of the process holding `pid`, or `undefined`
1122
- * when it cannot be determined (no such PID, platform lacks a readable source).
1123
- *
1124
- * - macOS / Linux: `ps -o lstart=` prints a local-time "EEE MMM DD HH:MM:SS YYYY";
1125
- * `Date.parse` resolves it against the local clock, which matches how
1126
- * `registeredAt` (a `Date.now()` absolute value) is expressed.
1127
- * - Windows: WMI `CreationDate` is UTC (`YYYYMMDDHHMMSS.mmm+zzzz`); parsed with
1128
- * `Date.UTC`, again comparable to `registeredAt`.
1129
- *
1130
- * Failures return `undefined` so callers can fall back to plain PID liveness
1131
- * rather than mis-report a running host as dead.
1132
- */
1133
- function processStartTimeMs(pid) {
1134
- try {
1135
- if (process.platform === "win32") {
1136
- const m = execFileSync("wmic", [
1137
- "process",
1138
- "where",
1139
- `processid=${pid}`,
1140
- "get",
1141
- "CreationDate"
1142
- ], {
1143
- encoding: "utf8",
1144
- windowsHide: true
1145
- }).match(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.\d+([+-]\d{4})/);
1146
- if (m === null) return void 0;
1147
- const [, y, mo, d, h, mi, s] = m;
1148
- const ms = Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s));
1149
- return Number.isFinite(ms) ? ms : void 0;
1150
- }
1151
- const out = execFileSync("ps", [
1152
- "-o",
1153
- "lstart=",
1154
- "-p",
1155
- String(pid)
1156
- ], {
1157
- encoding: "utf8",
1158
- env: {
1159
- ...process.env,
1160
- LC_ALL: "C",
1161
- LANG: "C"
1162
- }
1163
- }).trim();
1164
- if (out === "") return void 0;
1165
- const ms = Date.parse(out);
1166
- return Number.isFinite(ms) ? ms : void 0;
1167
- } catch {
1168
- return;
1169
- }
1170
- }
1171
- /**
1172
- * Whether the heartbeat's PID is still alive *and* still the same process that
1173
- * registered it. A stale heartbeat (host crashed without clearing the file)
1174
- * is distinguished from a live host by two checks:
1175
- *
1176
- * 1. `process.kill(pid, 0)` — the PID exists (signal 0 tests existence).
1177
- * 2. The process holding that PID started at or before `registeredAt`. A host
1178
- * that registered the heartbeat must have been started before writing it,
1179
- * so `start <= registeredAt`; a recycled PID belongs to an unrelated process
1180
- * started after the host died, so `start > registeredAt` correctly reads dead.
1181
- *
1182
- * PID-only detection is not enough: after a crash the OS may hand the same PID
1183
- * to an unrelated process, and the un-cleared stale heartbeat would otherwise
1184
- * produce a false "Host running". When the process start time cannot be read
1185
- * (e.g. unsupported platform) the check degrades to plain PID liveness.
1186
- */
1187
- function isHeartbeatProcessAlive(heartbeat) {
1188
- try {
1189
- process.kill(heartbeat.pid, 0);
1190
- } catch {
1191
- return false;
1192
- }
1193
- const startAtMs = processStartTimeMs(heartbeat.pid);
1194
- if (startAtMs === void 0) return true;
1195
- return startAtMs <= heartbeat.registeredAt;
1196
- }
1197
- //#endregion
1198
- export { workbuddyOwnAuthPath as S, WORKBUDDY_AUTH_FILE_ENV as _, readHostHeartbeat as a, defaultDesktopAuthPath as b, WORKBUDDY_CONNECT_VERSION as c, normalizeCredits as d, prepareChatBody as f, WORKBUDDY_AUTH_FILENAME as g, WorkBuddyCatalog as h, processStartTimeMs as i, WorkBuddyUpstreamClient as l, FALLBACK_WORKBUDDY_MODELS as m, clearHostHeartbeat as n, workbuddyHostHeartbeatPath as o, regionOf as p, isHeartbeatProcessAlive as r, writeHostHeartbeat as s, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, classifyUpstreamError as u, WorkBuddyCredentialStore as v, parseWorkBuddyAuth as x, defaultDesktopAuthCandidates as y };