@sixzjd/dsh-workbuddy-connect 0.0.0-stage → 0.3.1

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