@sixzjd/dsh-workbuddy-connect 0.0.0-stage → 0.3.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/lib/index.js ADDED
@@ -0,0 +1,879 @@
1
+ /**
2
+ * dsh-workbuddy-connect — host half.
3
+ *
4
+ * Registers a `workbuddy` and a `workbuddy-ai` LLM provider whose models are
5
+ * served by the WorkBuddy desktop products (CN: `copilot.tencent.com`;
6
+ * international: `www.workbuddy.ai`).
7
+ *
8
+ * The upstream is a closed, client-shaped API: it gates on the User-Agent, it
9
+ * refuses a body whose first message is not a system prompt, it rejects the
10
+ * OpenAI-only `store` field, it accepts `tool_choice` only in its string form,
11
+ * it answers `stream: true` only, and it wants a whole family of attribution
12
+ * headers. None of that can live in the profile config, so the plugin owns the
13
+ * wire format through a loopback shim: pi-ai speaks plain OpenAI-completions
14
+ * to the shim, and the shim speaks WorkBuddy to the gateway.
15
+ *
16
+ * The credential is the plugin's own: a device-authorization login, obtained
17
+ * by the settings card, refreshed on demand. Nothing is read out of the
18
+ * desktop app's own state, so the plugin works whether or not that app is
19
+ * installed.
20
+ *
21
+ * @module dsh-workbuddy-connect
22
+ */
23
+ import { randomBytes, timingSafeEqual } from 'node:crypto'
24
+ import { readFileSync } from 'node:fs'
25
+ import { join } from 'node:path'
26
+ import { WorkBuddyCredentialStore, WorkBuddyLoginClient, readJsonFile, writeJsonAtomic } from './auth.js'
27
+ import { WorkBuddyCatalog, fallbackFor } from './catalog.js'
28
+ import { createWorkBuddyAdapter } from './adapter.js'
29
+ import { createWorkBuddyShim } from './shim.js'
30
+ import { WorkBuddyUpstreamClient, modelWithCurrentPromotion, prepareChatBody, prepareInternationalChatBody, realmOf, regionOf } from './upstream.js'
31
+ import { readDesktopCredential, findDesktopExecutable } from './atrest.js'
32
+ import { discoverProfileDir, workbuddyPluginDataDir, workbuddyStateDir } from './paths.js'
33
+ import { checkForUpdate, updateSpecFrom } from './updates.js'
34
+ import { WORKBUDDY_VARIANTS, variantFor } from './variants.js'
35
+
36
+ export const name = 'llm-workbuddy'
37
+ export const inject = ['llm']
38
+
39
+ /**
40
+ * The version the card shows, read from the package manifest.
41
+ *
42
+ * A second literal beside `package.json` drifts the moment one is bumped and
43
+ * the other is not, and the card then reports a version the installed files do
44
+ * not have. Reading the manifest keeps the two the same by construction; the
45
+ * fallback covers a host that loads this module from outside a package.
46
+ */
47
+ const PLUGIN_VERSION = (() => {
48
+ try {
49
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
50
+ } catch {
51
+ return '0.0.0'
52
+ }
53
+ })()
54
+
55
+ /** How often the model catalog is refreshed from the upstream. */
56
+ const CATALOG_REFRESH_MS = 30 * 60_000
57
+
58
+ /** How often the credit balance is refreshed for the card. */
59
+ const CREDITS_REFRESH_MS = 5 * 60_000
60
+
61
+ /** Base path of this plugin's same-origin card routes. */
62
+ const ROUTE_BASE = '/plugins/dsh-workbuddy-connect'
63
+
64
+ /**
65
+ * Per-process control keys, minted once so a fiber hot-reload does not 403 the
66
+ * open card.
67
+ */
68
+ let processKeys
69
+ function controlKeys() {
70
+ processKeys ??= {
71
+ login: randomBytes(24).toString('hex'),
72
+ models: randomBytes(24).toString('hex'),
73
+ auth: randomBytes(24).toString('hex'),
74
+ update: randomBytes(24).toString('hex'),
75
+ }
76
+ return processKeys
77
+ }
78
+
79
+ /**
80
+ * The guard every state-changing card route shares: a loopback Host and
81
+ * Origin, plus the in-process key the card receives with its status document.
82
+ *
83
+ * Loopback alone is *not* authentication — any local process can address
84
+ * `127.0.0.1`, and these routes write a credential to disk.
85
+ */
86
+ function routeGuard(req, key) {
87
+ const host = req.headers.host
88
+ if (typeof host !== 'string' || !/^(localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d+)?$/i.test(host)) return false
89
+ const origin = req.headers.origin
90
+ if (origin !== undefined && !/^https?:\/\/(localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d+)?$/i.test(String(origin))) return false
91
+ const presented = req.headers['x-dsh-workbuddy-connect-key']
92
+ if (typeof presented !== 'string') return false
93
+ const a = Buffer.from(presented)
94
+ const b = Buffer.from(key)
95
+ return a.length === b.length && timingSafeEqual(a, b)
96
+ }
97
+
98
+ /** Read a route body with a hard ceiling. */
99
+ async function readRouteBody(req, limit = 65536) {
100
+ const chunks = []
101
+ let total = 0
102
+ for await (const chunk of req) {
103
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
104
+ total += buffer.length
105
+ if (total > limit) return undefined
106
+ chunks.push(buffer)
107
+ }
108
+ return Buffer.concat(chunks).toString('utf8')
109
+ }
110
+
111
+ /** Strip token-like content from a message before it reaches the browser. */
112
+ function safeMessage(error) {
113
+ return (error instanceof Error ? error.message : String(error))
114
+ .replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu, '[redacted token]')
115
+ .replace(/(\b(?:code|token|pat)=)[^&\s]+/giu, '$1[redacted]')
116
+ .slice(0, 500)
117
+ }
118
+
119
+ /**
120
+ * One variant's whole runtime: credential store, catalog, upstream client,
121
+ * shim, and adapter.
122
+ *
123
+ * The pieces are per variant rather than per plugin because the two products
124
+ * disagree about almost everything: which upstream realm a credential belongs
125
+ * to, which catalog document answers, which chat path is served, and which
126
+ * credential file is written. Sharing one instance would mean every one of
127
+ * those decisions carried a variant parameter.
128
+ */
129
+ class VariantRuntime {
130
+ /**
131
+ * @param {object} variant The variant descriptor.
132
+ * @param {object} options Constructor dependencies.
133
+ */
134
+ constructor(variant, options) {
135
+ this.variant = variant
136
+ this.logger = options.logger
137
+ this.dataDir = options.dataDir
138
+ this.stateDir = options.stateDir
139
+ this.client = options.client
140
+ this.login = options.login
141
+ this.onChange = options.onChange
142
+ /** Pending login attempts, keyed by the upstream's state string. */
143
+ this.attempts = new Map()
144
+
145
+ this.catalog = new WorkBuddyCatalog({ region: variant.region, initial: fallbackFor(variant.region) })
146
+ this.store = new WorkBuddyCredentialStore({
147
+ variant,
148
+ refresh: credential => this.client.refreshToken(credential),
149
+ })
150
+ this.settings = readJsonFile(join(this.dataDir, variant.settingsFilename)) ?? {}
151
+ if (Array.isArray(this.settings.disabledModels)) this.catalog.setDisabledModels(this.settings.disabledModels)
152
+ if (this.settings.useMaximumContextWindow === true) this.catalog.setUseMaximumContextWindow(true)
153
+ this.credits = undefined
154
+ this.creditsError = undefined
155
+ /**
156
+ * Whether the upstream has refused this credential since the last
157
+ * successful call.
158
+ *
159
+ * The desktop app rotates its own session behind the plugin's back, so a
160
+ * stored token can go stale while the card still reads "signed in". The
161
+ * upstream saying so is the only reliable signal, and the card needs it:
162
+ * without it the user sees a stale badge and an unexplained 401.
163
+ */
164
+ this.sessionStale = false
165
+ /**
166
+ * The upstream's own explanation while it has this account restricted.
167
+ *
168
+ * A restriction is not a dead session: the credential is valid and
169
+ * re-authenticating changes nothing (measured 2026-11-08 — a token minted
170
+ * seconds earlier was refused, and the official desktop app was refused on
171
+ * the same account). Only an appeal lifts it, so the card says that
172
+ * instead of offering the "import the desktop session" fix.
173
+ */
174
+ this.accountRestricted = undefined
175
+ }
176
+
177
+ /** Record that the upstream refused the stored credential. */
178
+ markSessionStale() {
179
+ if (this.sessionStale) return
180
+ this.sessionStale = true
181
+ this.onChange?.()
182
+ }
183
+
184
+ /** Forget a stale-session mark, after a call the upstream accepted. */
185
+ markSessionFresh() {
186
+ if (!this.sessionStale) return
187
+ this.sessionStale = false
188
+ this.onChange?.()
189
+ }
190
+
191
+ /** Record that the upstream restricted this account, keeping its own words. */
192
+ markAccountRestricted(reason) {
193
+ if (this.accountRestricted === reason) return
194
+ this.accountRestricted = reason
195
+ this.onChange?.()
196
+ }
197
+
198
+ /** Forget a restriction mark, after a call the upstream accepted. */
199
+ markAccountFresh() {
200
+ if (this.accountRestricted === undefined) return
201
+ this.accountRestricted = undefined
202
+ this.onChange?.()
203
+ }
204
+
205
+ /** The saved-catalog path for this variant. */
206
+ catalogPath() {
207
+ return join(this.stateDir, this.variant.catalogFilename)
208
+ }
209
+
210
+ /** The settings path for this variant. */
211
+ settingsPath() {
212
+ return join(this.dataDir, this.variant.settingsFilename)
213
+ }
214
+
215
+ /** Persist the settings this variant owns. */
216
+ saveSettings() {
217
+ writeJsonAtomic(this.settingsPath(), {
218
+ version: 1,
219
+ disabledModels: this.catalog.disabledModels(),
220
+ useMaximumContextWindow: this.catalog.useMaximumContextWindow === true,
221
+ })
222
+ }
223
+
224
+ /**
225
+ * Seed the catalog from the account's last successful live list, so a
226
+ * restart serves the same roster the account actually had.
227
+ */
228
+ seedFromSavedCatalog() {
229
+ const saved = readJsonFile(this.catalogPath())
230
+ if (!Array.isArray(saved?.models) || saved.models.length === 0) return
231
+ this.catalog.set(saved.models, 'saved', saved.fetchedAtMs)
232
+ }
233
+
234
+ /**
235
+ * Refresh the model catalog from the upstream.
236
+ *
237
+ * The three-level degradation is explicit: a successful fetch becomes
238
+ * `live`, a failure leaves whatever was in force (saved or fallback) and
239
+ * records the reason, so the card can say which one the user is looking at.
240
+ */
241
+ async refreshCatalog() {
242
+ try {
243
+ const credential = await this.store.resolve()
244
+ const models = await this.client.fetchModels(credential)
245
+ // The rows are stored RAW: a promotion is re-derived on every read
246
+ // (it is time-boxed, so a cached "Free now" must stop claiming itself
247
+ // when the window closes). Applying it here as well would layer the
248
+ // badge on twice — once by the fetch and once by every read.
249
+ this.catalog.set(models, 'live', Date.now())
250
+ this.catalog.lastError = undefined
251
+ writeJsonAtomic(this.catalogPath(), {
252
+ version: 1,
253
+ fetchedAtMs: this.catalog.fetchedAtMs,
254
+ models,
255
+ })
256
+ this.onChange?.()
257
+ return true
258
+ } catch (error) {
259
+ this.catalog.lastError = safeMessage(error)
260
+ this.logger?.warn?.(`dsh-workbuddy-connect: ${this.variant.displayName} catalog refresh failed`, error)
261
+ return false
262
+ }
263
+ }
264
+
265
+ /** Refresh the credit balance for the card. */
266
+ async refreshCredits() {
267
+ try {
268
+ const credential = await this.store.resolve()
269
+ this.credits = await this.client.fetchCredits(credential)
270
+ this.creditsError = undefined
271
+ } catch (error) {
272
+ this.creditsError = safeMessage(error)
273
+ }
274
+ }
275
+
276
+ /**
277
+ * The status document this variant contributes to the card.
278
+ *
279
+ * Never throws: a status read must never be the thing that breaks the card.
280
+ */
281
+ async status() {
282
+ const auth = await this.store.status()
283
+ // `catalog.all()` already re-derives the current promotion; applying it a
284
+ // second time here would repeat its badge.
285
+ const disabled = this.catalog.disabledModels()
286
+ const models = this.catalog.all().map(current => ({
287
+ id: current.id,
288
+ name: current.name,
289
+ contextWindow: current.contextWindow,
290
+ maxTokens: current.maxTokens,
291
+ defaultContextWindow: current.defaultContextWindow,
292
+ supportedContextWindows: current.supportedContextWindows,
293
+ supportsImages: current.supportsImages === true,
294
+ free: current.billing?.free === true,
295
+ rate: current.billing?.rateUnknown === true ? null : current.billing?.credits,
296
+ rateUnknown: current.billing?.rateUnknown === true,
297
+ badges: current.billing?.badges ?? [],
298
+ efforts: current.reasoning?.supportedEfforts ?? [],
299
+ enabled: !disabled.includes(current.id),
300
+ }))
301
+ return {
302
+ provider: this.variant.id,
303
+ displayName: this.variant.displayName,
304
+ appName: this.variant.appName,
305
+ region: this.variant.region,
306
+ signInUrl: this.variant.signInUrl,
307
+ // Whether the desktop app is installed, so the card can offer the
308
+ // one-click import. The check is a few `existsSync` calls — it never
309
+ // spawns the app, so it is cheap enough for a status poll.
310
+ desktopAvailable: findDesktopExecutable() !== undefined,
311
+ auth: { ...auth, sessionStale: this.sessionStale, accountRestricted: this.accountRestricted },
312
+ catalog: {
313
+ source: this.catalog.source,
314
+ fetchedAt: this.catalog.fetchedAtMs,
315
+ error: this.catalog.lastError,
316
+ models,
317
+ },
318
+ credits: this.credits ?? null,
319
+ creditsError: this.creditsError ?? null,
320
+ useMaximumContextWindow: this.catalog.useMaximumContextWindow === true,
321
+ }
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Start the providers: one runtime, one shim and one adapter per variant.
327
+ *
328
+ * An empty catalog hides the model group in DSH's picker, which is how a
329
+ * provider with nothing to serve disappears without touching registration.
330
+ */
331
+ export async function apply(ctx, config = {}) {
332
+ const dataDir = workbuddyPluginDataDir()
333
+ const stateDir = workbuddyStateDir()
334
+ // The profile whose lockfile records this installed copy. Discovered once at
335
+ // startup: it is the manifest-and-link resolution `paths.js` already performs
336
+ // for the data directory, and it cannot change while this process runs.
337
+ const profileDir = discoverProfileDir()
338
+ const client = new WorkBuddyUpstreamClient()
339
+ const login = new WorkBuddyLoginClient()
340
+ const { login: loginKey, models: modelsKey, auth: authKey, update: updateKey } = controlKeys()
341
+
342
+ const runtimes = new Map()
343
+ const adapters = new Map()
344
+ const shims = new Map()
345
+ const disposers = []
346
+
347
+ /** Re-snapshot every adapter after a catalog change. */
348
+ const refresh = () => {
349
+ for (const built of adapters.values()) built.invalidate()
350
+ ctx.emit('llm/adapters-updated')
351
+ }
352
+
353
+ for (const variant of WORKBUDDY_VARIANTS) {
354
+ const runtime = new VariantRuntime(variant, {
355
+ logger: ctx.logger,
356
+ dataDir,
357
+ stateDir,
358
+ client,
359
+ login,
360
+ onChange: refresh,
361
+ })
362
+ runtime.seedFromSavedCatalog()
363
+ // A variant with no credential shows no models at all: offering the
364
+ // compiled-in roster to a signed-out user would advertise models that can
365
+ // only fail.
366
+ const auth = await runtime.store.status()
367
+ runtime.catalog.setVisible(auth.state === 'signed-in')
368
+ runtimes.set(variant.id, runtime)
369
+
370
+ // The shim speaks to the upstream; the adapter speaks to the shim.
371
+ const shim = createWorkBuddyShim({
372
+ store: runtime.store,
373
+ client,
374
+ catalog: runtime.catalog,
375
+ logger: ctx.logger,
376
+ prepareBody: (raw, options) => (variant.region === 'global'
377
+ ? prepareInternationalChatBody(raw, options)
378
+ : prepareChatBody(raw, options)),
379
+ defaultEffortFor: id => runtime.catalog.current().find(entry => entry.id === id)?.reasoning?.defaultEffort,
380
+ // The upstream refusing the stored credential is the only trustworthy
381
+ // signal that the session was rotated away; the card turns it into a
382
+ // visible hint instead of a stale "signed in" badge.
383
+ onSessionDead: () => runtime.markSessionStale(),
384
+ // A restriction is a different failure with a different fix, so it gets
385
+ // its own mark rather than sharing the stale-session one.
386
+ onAccountRestricted: reason => runtime.markAccountRestricted(reason),
387
+ onSessionFresh: () => {
388
+ runtime.markSessionFresh()
389
+ // An accepted call also proves a restriction is gone (an appeal, or a
390
+ // restriction the upstream lifted on its own), so the warning must not
391
+ // outlive the condition it describes.
392
+ runtime.markAccountFresh()
393
+ },
394
+ // `DSH_WORKBUDDY_DUMP_BODY=/tmp/wb-body.json` records the exact request
395
+ // this process sends, which is the only way to tell a body-shape refusal
396
+ // from a credential one.
397
+ ...process.env['DSH_WORKBUDDY_DUMP_BODY'] === undefined
398
+ ? {}
399
+ : { dumpBodyPath: process.env['DSH_WORKBUDDY_DUMP_BODY'] },
400
+ })
401
+ shims.set(variant.id, shim)
402
+
403
+ const built = createWorkBuddyAdapter({
404
+ shim,
405
+ catalog: runtime.catalog,
406
+ providerId: variant.id,
407
+ displayName: variant.displayName,
408
+ // The identity every model of this route advertises. It is shared across
409
+ // the two regions on purpose — see `modelIdentityKeysOf`.
410
+ modelIdentity: variant.modelIdentity,
411
+ // Lazy service lookup: the adapter asks for the host's attachment
412
+ // service only when a request actually carries an image.
413
+ resolveAttachments: () => ctx.get('attachments'),
414
+ })
415
+ adapters.set(variant.id, built)
416
+ }
417
+
418
+ // Register synchronously, before any await: the headless host starts its
419
+ // first turn the moment the fiber is ready and does not await an async setup
420
+ // continuation, so an adapter registered after an `await` loses the race.
421
+ for (const [id, built] of adapters) {
422
+ try {
423
+ const releaseAdapter = ctx.llm.registerAdapter([id], built.adapter)
424
+ disposers.push(releaseAdapter)
425
+ } catch (error) {
426
+ ctx.logger?.error?.(`dsh-workbuddy-connect: registerAdapter failed for ${id}`, error)
427
+ }
428
+ }
429
+ try {
430
+ const releaseDirectory = ctx.llm.registerConfigurableProviders(WORKBUDDY_VARIANTS.map(variant => ({
431
+ provider: variant.id,
432
+ displayName: variant.displayName,
433
+ settingsNs: ctx.fiber?.entry?.options?.id ?? variant.id,
434
+ settingsPath: [],
435
+ declared: false,
436
+ })))
437
+ disposers.push(releaseDirectory)
438
+ } catch (error) {
439
+ ctx.logger?.error?.('dsh-workbuddy-connect: registerConfigurableProviders failed', error)
440
+ }
441
+ ctx.effect(() => () => {
442
+ for (const dispose of disposers) {
443
+ try {
444
+ dispose()
445
+ } catch {
446
+ // A disposer that throws must not stop the others.
447
+ }
448
+ }
449
+ })
450
+
451
+ // The first catalog fetch runs in the background: serving starts on the
452
+ // saved/built-in roster and upgrades to the live list when it lands.
453
+ for (const runtime of runtimes.values()) {
454
+ void runtime.refreshCatalog().then(() => refresh())
455
+ void runtime.refreshCredits()
456
+ }
457
+ // When the listen event lands (including the ephemeral-port fallback), the
458
+ // descriptors' embedded baseUrl may have changed — re-snapshot them.
459
+ for (const shim of shims.values()) {
460
+ void shim.ready.then(up => {
461
+ if (up) refresh()
462
+ })
463
+ }
464
+
465
+ ctx.effect(() => {
466
+ const timer = setInterval(() => {
467
+ for (const runtime of runtimes.values()) {
468
+ void runtime.refreshCatalog().then(() => refresh())
469
+ void runtime.refreshCredits()
470
+ }
471
+ }, CATALOG_REFRESH_MS)
472
+ timer.unref?.()
473
+ return () => clearInterval(timer)
474
+ })
475
+
476
+ //#region card routes
477
+ /**
478
+ * The last update report plus when it was taken.
479
+ *
480
+ * A `git ls-remote` costs a round trip, and the card polls its status for
481
+ * unrelated reasons (credits, catalog), so the answer is cached for a while
482
+ * and refreshed only when the user asks or the cache ages out. Both callers
483
+ * share one in-flight promise: two panels opening at once must not launch two
484
+ * checks.
485
+ */
486
+ const updateCache = { report: undefined, at: 0, inFlight: undefined }
487
+ const UPDATE_TTL_MS = 6 * 60 * 60 * 1000
488
+
489
+ async function updateReport(profileDir, force) {
490
+ const fresh = updateCache.report !== undefined && Date.now() - updateCache.at < UPDATE_TTL_MS
491
+ if (fresh && force !== true) return updateCache.report
492
+ if (updateCache.inFlight !== undefined) return updateCache.inFlight
493
+ updateCache.inFlight = (async () => {
494
+ try {
495
+ // The profile that hosts this plugin, not the one the card happens to
496
+ // be drawn in: the two are the same for a normal install, and the
497
+ // discovered directory is the one whose lockfile records this copy.
498
+ const report = await checkForUpdate(profileDir)
499
+ updateCache.report = report
500
+ updateCache.at = Date.now()
501
+ return report
502
+ } finally {
503
+ updateCache.inFlight = undefined
504
+ }
505
+ })()
506
+ return updateCache.inFlight
507
+ }
508
+
509
+ const updateHandler = async (req, res) => {
510
+ if (req.method !== 'GET' || !routeGuard(req, updateKey)) {
511
+ res.statusCode = req.method === 'GET' ? 403 : 405
512
+ res.end()
513
+ return
514
+ }
515
+ let report
516
+ try {
517
+ report = await updateReport(profileDir, new URL(req.url ?? '/', 'http://127.0.0.1').searchParams.get('refresh') === '1')
518
+ } catch (error) {
519
+ report = { state: 'unknown', reason: safeMessage(error) }
520
+ }
521
+ // No key is echoed here: this route only *reads*, and the install it
522
+ // enables goes through the plugin manager's own remote service, which
523
+ // carries its own authorization. Returning a control key would hand any
524
+ // reader of the card a credential it does not need.
525
+ const spec = updateSpecFrom(report)
526
+ const body = JSON.stringify({
527
+ ...report,
528
+ ...spec === undefined ? {} : { targetSpec: spec },
529
+ })
530
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
531
+ res.end(body)
532
+ }
533
+
534
+ const statusHandler = (req, res) => {
535
+ if (req.method !== 'GET') {
536
+ res.statusCode = 405
537
+ res.end()
538
+ return
539
+ }
540
+ const host = req.headers.host
541
+ if (typeof host !== 'string' || !/^(localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d+)?$/i.test(host)) {
542
+ res.statusCode = 403
543
+ res.end()
544
+ return
545
+ }
546
+ const origin = req.headers.origin
547
+ if (origin !== undefined && !/^https?:\/\/(localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d+)?$/i.test(String(origin))) {
548
+ res.statusCode = 403
549
+ res.end()
550
+ return
551
+ }
552
+ void (async () => {
553
+ const variants = {}
554
+ for (const [id, runtime] of runtimes) variants[id] = await runtime.status()
555
+ const payload = JSON.stringify({
556
+ status: 'ok',
557
+ version: PLUGIN_VERSION,
558
+ variants,
559
+ loginKey,
560
+ modelsKey,
561
+ authKey,
562
+ // The update route reads only, but it is still guarded like every
563
+ // other card route: the key travels with the status document the card
564
+ // already fetches, which is how `loginKey`/`modelsKey` reach it too.
565
+ updateKey,
566
+ })
567
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
568
+ res.end(payload)
569
+ })().catch(error => {
570
+ ctx.logger?.warn?.('dsh-workbuddy-connect: status route failed', error)
571
+ if (!res.headersSent) {
572
+ res.statusCode = 500
573
+ res.end()
574
+ }
575
+ })
576
+ }
577
+
578
+ const loginHandler = async (req, res) => {
579
+ if (req.method !== 'POST' || !routeGuard(req, loginKey)) {
580
+ res.statusCode = req.method === 'POST' ? 403 : 405
581
+ res.end()
582
+ return
583
+ }
584
+ const text = await readRouteBody(req)
585
+ let action
586
+ try {
587
+ action = JSON.parse(text ?? '')
588
+ } catch {
589
+ res.statusCode = 400
590
+ res.end()
591
+ return
592
+ }
593
+ const provider = typeof action?.provider === 'string' ? action.provider : ''
594
+ const runtime = runtimes.get(provider)
595
+ if (runtime === undefined) {
596
+ res.statusCode = 400
597
+ res.end()
598
+ return
599
+ }
600
+ try {
601
+ if (action?.action === 'begin') {
602
+ const attempt = await login.begin(runtime.variant.region)
603
+ runtime.attempts.set(attempt.state, { startedAtMs: Date.now() })
604
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
605
+ res.end(JSON.stringify({ status: 'pending', authUrl: attempt.authUrl, state: attempt.state }))
606
+ return
607
+ }
608
+ if (action?.action === 'poll') {
609
+ const state = typeof action.state === 'string' ? action.state : ''
610
+ const attempt = runtime.attempts.get(state)
611
+ if (attempt === undefined) {
612
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
613
+ res.end(JSON.stringify({ status: 'pending' }))
614
+ return
615
+ }
616
+ const outcome = await login.poll({ state, authUrl: '', region: runtime.variant.region })
617
+ if (outcome.status !== 'complete') {
618
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
619
+ res.end(JSON.stringify({ status: 'pending' }))
620
+ return
621
+ }
622
+ login.forget(state)
623
+ runtime.attempts.delete(state)
624
+ const { tokens, account } = outcome
625
+ const region = tokens.domain === '' ? runtime.variant.region : (tokens.domain.endsWith('workbuddy.ai') ? 'global' : 'cn')
626
+ const credential = {
627
+ accessToken: tokens.accessToken,
628
+ refreshToken: tokens.refreshToken,
629
+ expiresAtMs: Date.now() + (tokens.expiresInSec > 0 ? tokens.expiresInSec * 1000 : 0),
630
+ domain: tokens.domain,
631
+ region,
632
+ uid: account.uid,
633
+ ...account.enterpriseId === undefined ? {} : { enterpriseId: account.enterpriseId },
634
+ ...account.nickname === undefined ? {} : { nickname: account.nickname },
635
+ source: 'login',
636
+ }
637
+ await runtime.store.save(credential)
638
+ // A fresh sign-in is a new credential. The stale mark described the
639
+ // OLD one, so it must not survive the replacement — otherwise the card
640
+ // keeps advising a re-import the user just performed, and only a
641
+ // successful generation clears it. (An account restriction is
642
+ // deliberately kept: it belongs to the account, not the credential.)
643
+ runtime.markSessionFresh()
644
+ runtime.catalog.setVisible(true)
645
+ await runtime.refreshCatalog()
646
+ await runtime.refreshCredits()
647
+ refresh()
648
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
649
+ res.end(JSON.stringify({ status: 'complete' }))
650
+ return
651
+ }
652
+ if (action?.action === 'cancel') {
653
+ const state = typeof action.state === 'string' ? action.state : ''
654
+ login.forget(state)
655
+ runtime.attempts.delete(state)
656
+ res.statusCode = 204
657
+ res.end()
658
+ return
659
+ }
660
+ res.statusCode = 400
661
+ res.end()
662
+ } catch (error) {
663
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
664
+ res.end(JSON.stringify({ status: 'error', error: safeMessage(error) }))
665
+ }
666
+ }
667
+
668
+ const modelsHandler = async (req, res) => {
669
+ if (req.method !== 'POST' || !routeGuard(req, modelsKey)) {
670
+ res.statusCode = req.method === 'POST' ? 403 : 405
671
+ res.end()
672
+ return
673
+ }
674
+ const text = await readRouteBody(req)
675
+ let action
676
+ try {
677
+ action = JSON.parse(text ?? '')
678
+ } catch {
679
+ res.statusCode = 400
680
+ res.end()
681
+ return
682
+ }
683
+ const provider = typeof action?.provider === 'string' ? action.provider : ''
684
+ const runtime = runtimes.get(provider)
685
+ if (runtime === undefined) {
686
+ res.statusCode = 400
687
+ res.end()
688
+ return
689
+ }
690
+ if (action?.action === 'set-model' && typeof action.model === 'string' && typeof action.enabled === 'boolean') {
691
+ // One model, one new state. The card never sends a list derived from a
692
+ // snapshot of the page: a snapshot is stale the moment the catalog
693
+ // refreshes, and a complement computed from a stale one can disable
694
+ // every model but the one that was clicked.
695
+ const known = new Set(runtime.catalog.all().map(model => model.id))
696
+ if (!known.has(action.model)) {
697
+ res.statusCode = 400
698
+ res.end()
699
+ return
700
+ }
701
+ const next = new Set(runtime.catalog.disabledModels())
702
+ if (action.enabled) next.delete(action.model)
703
+ else next.add(action.model)
704
+ const list = [...next]
705
+ runtime.catalog.setDisabledModels(list)
706
+ runtime.settings.disabledModels = list
707
+ runtime.saveSettings()
708
+ refresh()
709
+ res.statusCode = 204
710
+ res.end()
711
+ return
712
+ }
713
+ if (action?.action === 'set-all' && typeof action.enabled === 'boolean') {
714
+ const list = action.enabled ? [] : runtime.catalog.all().map(model => model.id)
715
+ runtime.catalog.setDisabledModels(list)
716
+ runtime.settings.disabledModels = list
717
+ runtime.saveSettings()
718
+ refresh()
719
+ res.statusCode = 204
720
+ res.end()
721
+ return
722
+ }
723
+ if (action?.action === 'set-disabled' && Array.isArray(action.models)) {
724
+ // Kept for compatibility with an older card. The list is the set of
725
+ // models to KEEP, and the server turns it into the disabled set — the
726
+ // card never gets to name a list of things to remove.
727
+ const known = new Set(runtime.catalog.all().map(model => model.id))
728
+ const keep = new Set(action.models.filter(id => typeof id === 'string' && known.has(id)))
729
+ const next = [...known].filter(id => !keep.has(id))
730
+ runtime.catalog.setDisabledModels(next)
731
+ runtime.settings.disabledModels = next
732
+ runtime.saveSettings()
733
+ refresh()
734
+ res.statusCode = 204
735
+ res.end()
736
+ return
737
+ }
738
+ if (action?.action === 'set-max-window' && typeof action.enabled === 'boolean') {
739
+ runtime.catalog.setUseMaximumContextWindow(action.enabled)
740
+ runtime.settings.useMaximumContextWindow = action.enabled
741
+ runtime.saveSettings()
742
+ refresh()
743
+ res.statusCode = 204
744
+ res.end()
745
+ return
746
+ }
747
+ if (action?.action === 'refresh') {
748
+ await runtime.refreshCatalog()
749
+ await runtime.refreshCredits()
750
+ refresh()
751
+ res.statusCode = 204
752
+ res.end()
753
+ return
754
+ }
755
+ res.statusCode = 400
756
+ res.end()
757
+ }
758
+
759
+ const authHandler = async (req, res) => {
760
+ if (req.method !== 'POST' || !routeGuard(req, authKey)) {
761
+ res.statusCode = req.method === 'POST' ? 403 : 405
762
+ res.end()
763
+ return
764
+ }
765
+ const text = await readRouteBody(req)
766
+ let action
767
+ try {
768
+ action = JSON.parse(text ?? '')
769
+ } catch {
770
+ res.statusCode = 400
771
+ res.end()
772
+ return
773
+ }
774
+ const provider = typeof action?.provider === 'string' ? action.provider : ''
775
+ const runtime = runtimes.get(provider)
776
+ if (runtime === undefined) {
777
+ res.statusCode = 400
778
+ res.end()
779
+ return
780
+ }
781
+ if (action?.action === 'logout') {
782
+ await runtime.store.logout()
783
+ runtime.catalog.setVisible(false)
784
+ runtime.credits = undefined
785
+ refresh()
786
+ res.statusCode = 204
787
+ res.end()
788
+ return
789
+ }
790
+ if (action?.action === 'import-desktop') {
791
+ // Adopt the session the WorkBuddy desktop app is already signed in to.
792
+ // A convenience, not a dependency: the plugin's own device-authorization
793
+ // login stays the primary path and works without the app installed.
794
+ try {
795
+ const credential = await readDesktopCredential()
796
+ if (credential === undefined) {
797
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
798
+ res.end(JSON.stringify({ ok: false, error: 'no desktop session found' }))
799
+ return
800
+ }
801
+ const region = regionOf(credential.domain)
802
+ if (region !== runtime.variant.region) {
803
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
804
+ res.end(JSON.stringify({
805
+ ok: false,
806
+ error: `the desktop app is signed in to ${region === 'global' ? 'WorkBuddy AI' : 'WorkBuddy (CN)'}, not ${runtime.variant.appName}`,
807
+ }))
808
+ return
809
+ }
810
+ await runtime.store.save({ ...credential, region })
811
+ // The import replaced the credential, so the stale mark no longer
812
+ // describes what is stored. Without this the card keeps showing "the
813
+ // desktop app rotated its session" immediately after the user did
814
+ // exactly what that message asked for. (The account-restriction mark
815
+ // stays: re-importing cannot lift a restriction.)
816
+ runtime.markSessionFresh()
817
+ runtime.catalog.setVisible(true)
818
+ await runtime.refreshCatalog()
819
+ await runtime.refreshCredits()
820
+ refresh()
821
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
822
+ res.end(JSON.stringify({ ok: true }))
823
+ return
824
+ } catch (error) {
825
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
826
+ res.end(JSON.stringify({ ok: false, error: safeMessage(error) }))
827
+ return
828
+ }
829
+ }
830
+ res.statusCode = 400
831
+ res.end()
832
+ }
833
+ //#endregion
834
+
835
+ // Card routes on the host web server (same-origin for the browser half).
836
+ // Deferred injection: a headless host without the webServer service simply
837
+ // never runs this callback, and the model channel keeps working.
838
+ ctx.inject(['webServer'], (webCtx) => {
839
+ webCtx.effect(() => {
840
+ const a = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/status`, handler: statusHandler })
841
+ const b = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/login`, handler: loginHandler })
842
+ const c = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/models`, handler: modelsHandler })
843
+ const d = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/auth`, handler: authHandler })
844
+ const e = webCtx.webServer.register({ kind: 'exact', path: `${ROUTE_BASE}/update`, handler: updateHandler })
845
+ return () => {
846
+ a()
847
+ b()
848
+ c()
849
+ d()
850
+ e()
851
+ }
852
+ }, 'dsh-workbuddy-connect: web routes')
853
+ })
854
+
855
+ ctx.effect(() => async () => {
856
+ for (const shim of shims.values()) {
857
+ try {
858
+ await shim.close()
859
+ } catch {
860
+ // A shim that fails to close cleanly must not block the teardown.
861
+ }
862
+ }
863
+ })
864
+ }
865
+
866
+ export default { name, inject, apply }
867
+
868
+ // Internal surfaces exported for tests and CLI use.
869
+ export {
870
+ VariantRuntime,
871
+ WORKBUDDY_VARIANTS,
872
+ controlKeys,
873
+ fallbackFor,
874
+ prepareChatBody,
875
+ prepareInternationalChatBody,
876
+ realmOf,
877
+ safeMessage,
878
+ variantFor,
879
+ }