@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/paths.js ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The plugin's data directory — the ONE place every file the plugin owns lives.
3
+ *
4
+ * Layout: `<profile>/.dsh-workbuddy-connect/` with the credential at the root
5
+ * and the rebuildable caches under `state/`. Everything the plugin writes —
6
+ * credentials, saved catalogs, the App-version cache, the settings file — lands
7
+ * here, so a profile directory never collects loose `.workbuddy-*` files and
8
+ * "clear the caches" can never be mistaken for "clear the credential".
9
+ *
10
+ * The profile is discovered the way the credential store always did: by asking
11
+ * the profiles tree which one *declares* this package in its manifest. A plugin
12
+ * is installed into a profile by link, so walking up from this module's own
13
+ * location would miss the profile for exactly the install shape a developer
14
+ * uses (`file:` / `link:` dependencies).
15
+ *
16
+ * Fallbacks, in order: `DSH_WORKBUDDY_DATA_DIR` env override → the discovered
17
+ * profile → the Harness home (a checkout running its own tests, or a host
18
+ * loading the plugin from outside any profile).
19
+ *
20
+ * @module dsh-workbuddy-connect/paths
21
+ */
22
+ import { readFileSync, readdirSync, realpathSync } from 'node:fs'
23
+ import { homedir } from 'node:os'
24
+ import { dirname, join } from 'node:path'
25
+ import { fileURLToPath } from 'node:url'
26
+
27
+ /** The per-profile directory the plugin's data folder lives under. */
28
+ export const WORKBUDDY_DATA_DIR_NAME = '.dsh-workbuddy-connect'
29
+
30
+ /** The directory inside the data dir where the rebuildable state files live. */
31
+ export const WORKBUDDY_STATE_DIR_NAME = 'state'
32
+
33
+ /** Environment override for the whole data directory. */
34
+ export const WORKBUDDY_DATA_DIR_ENV = 'DSH_WORKBUDDY_DATA_DIR'
35
+
36
+ const PROFILES_DIR_NAME = 'profiles'
37
+
38
+ /** The npm name of this package, as a profile's manifest declares it. */
39
+ const PLUGIN_PACKAGE_NAME = '@sixzjd/dsh-workbuddy-connect'
40
+
41
+ /**
42
+ * Names a profile may still declare from before the scoped rename.
43
+ *
44
+ * The unscoped name was this package's identity until it was published to a
45
+ * registry, where that name was already somebody else's. A profile installed
46
+ * earlier still names the old one, and refusing to recognise it would make the
47
+ * plugin unable to find its own data directory — the card would come up empty
48
+ * with a working installation behind it.
49
+ */
50
+ const LEGACY_PACKAGE_NAMES = ['dsh-workbuddy-connect']
51
+
52
+ /** The Harness home: `$DSH_HOME`, else `~/.dsh`. */
53
+ export function resolveDshHome() {
54
+ const override = process.env.DSH_HOME
55
+ if (override !== undefined && override.trim() !== '') return override
56
+ return join(homedir(), '.dsh')
57
+ }
58
+
59
+ function pluginPackageRoot() {
60
+ try {
61
+ // `<root>/lib/paths.js` — the package root is one level up.
62
+ return dirname(dirname(fileURLToPath(import.meta.url)))
63
+ } catch {
64
+ return undefined
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Whether a profile directory declares this plugin.
70
+ *
71
+ * Read from the profile's manifest rather than inferred from this module's own
72
+ * location, because DSH installs a plugin into a profile by *link*: the manifest
73
+ * carries `"dsh-workbuddy-connect": "file:…"` or `"link:/path"`, while Node
74
+ * resolves the module to that real path, which can lie outside `$DSH_HOME`.
75
+ */
76
+ function profileDeclaresPlugin(profileDir) {
77
+ try {
78
+ const manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8'))
79
+ return [PLUGIN_PACKAGE_NAME, ...LEGACY_PACKAGE_NAMES].some(name =>
80
+ typeof manifest.dependencies?.[name] === 'string'
81
+ || typeof manifest.devDependencies?.[name] === 'string')
82
+ } catch {
83
+ return false
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Whether a profile's installed copy of this plugin resolves to this package.
89
+ *
90
+ * This is what separates two profiles that both declare the plugin — a `web` and
91
+ * a `desktop` profile can each list it — so the data directory follows the
92
+ * profile whose copy is actually running rather than the first one found.
93
+ */
94
+ function profileLinksToThisPackage(profileDir) {
95
+ const own = pluginPackageRoot()
96
+ if (own === undefined) return false
97
+ try {
98
+ return [PLUGIN_PACKAGE_NAME, ...LEGACY_PACKAGE_NAMES].some(name => {
99
+ try {
100
+ return realpathSync(join(profileDir, 'node_modules', name)) === realpathSync(own)
101
+ } catch {
102
+ return false
103
+ }
104
+ })
105
+ } catch {
106
+ return false
107
+ }
108
+ }
109
+
110
+ /**
111
+ * The profile directory this plugin belongs to, or undefined when none can be
112
+ * determined.
113
+ *
114
+ * A single declaring profile is accepted without the link test, so a normal
115
+ * (non-linked) install still resolves.
116
+ */
117
+ export function discoverProfileDir() {
118
+ const profilesRoot = join(resolveDshHome(), PROFILES_DIR_NAME)
119
+ let entries
120
+ try {
121
+ entries = readdirSync(profilesRoot, { withFileTypes: true })
122
+ } catch {
123
+ return undefined
124
+ }
125
+ const candidates = []
126
+ for (const entry of entries) {
127
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
128
+ const dir = join(profilesRoot, entry.name)
129
+ if (profileDeclaresPlugin(dir)) candidates.push(dir)
130
+ }
131
+ if (candidates.length === 0) return undefined
132
+ if (candidates.length === 1) return candidates[0]
133
+ return candidates.find(candidate => profileLinksToThisPackage(candidate))
134
+ }
135
+
136
+ /**
137
+ * The plugin's data directory: `<profile>/.dsh-workbuddy-connect`.
138
+ *
139
+ * Falls back to the Harness home when no profile can be discovered, so the
140
+ * plugin always has somewhere to write; `DSH_WORKBUDDY_DATA_DIR` overrides
141
+ * either way.
142
+ */
143
+ export function workbuddyPluginDataDir() {
144
+ const override = process.env[WORKBUDDY_DATA_DIR_ENV]
145
+ if (override !== undefined && override.trim() !== '') return override
146
+ const base = discoverProfileDir() ?? resolveDshHome()
147
+ return join(base, WORKBUDDY_DATA_DIR_NAME)
148
+ }
149
+
150
+ /**
151
+ * The directory the rebuildable state files live in:
152
+ * `<data dir>/state/` (saved catalogs, App-version cache).
153
+ */
154
+ export function workbuddyStateDir() {
155
+ return join(workbuddyPluginDataDir(), WORKBUDDY_STATE_DIR_NAME)
156
+ }
package/lib/shim.js ADDED
@@ -0,0 +1,531 @@
1
+ /**
2
+ * Loopback OpenAI-compatible endpoint.
3
+ *
4
+ * The pi-ai provider points here; the shim applies the WorkBuddy wire quirks
5
+ * (forced streaming, string `tool_choice`, the client's own identity) and
6
+ * forwards to the real upstream. It binds 127.0.0.1 only and never serves
7
+ * another interface.
8
+ *
9
+ * Inbound hardening: the loopback bind alone is not a trust boundary (any
10
+ * local process or a DNS-rebinding page can reach 127.0.0.1), so every request
11
+ * must carry a loopback Host header, browser-sent Origins must be loopback,
12
+ * chat POSTs must be application/json, and the Authorization header must carry
13
+ * the shim's per-process shared secret. The plugin's own client satisfies all
14
+ * four by construction; a local attacker cannot read the secret out of the
15
+ * plugin process's memory.
16
+ *
17
+ * The upstream only speaks streaming (`stream: true`; a non-streaming request
18
+ * is refused with code 11101), so the shim always asks upstream for a stream
19
+ * and *reassembles* one into plain JSON when the client asked for none.
20
+ *
21
+ * @module dsh-workbuddy-connect/shim
22
+ */
23
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
24
+ import { createServer } from 'node:http'
25
+ import { writeFileSync } from 'node:fs'
26
+ import { describeAccountRestriction, describeUpstreamFailure } from './upstream.js'
27
+
28
+ /** The shim's preferred fixed loopback port (env-overridable; ephemeral on collision). */
29
+ const SHIM_PORT = Number(process.env.DSH_WORKBUDDY_CONNECT_PORT ?? 39319)
30
+
31
+ /** Chat-completion bodies in a long session are large; 32 MiB mirrors Anthropic's guidance. */
32
+ const MAX_BODY_BYTES = 32 * 1024 * 1024
33
+
34
+ /**
35
+ * The largest prepared body this shim will forward.
36
+ *
37
+ * Re-measured 2026-10-28 against both live gateways: body *size* is not what
38
+ * the upstream refuses on. A 1.2MB body streamed in 23s, a 2MB body was
39
+ * answered in 4.5s, and the only refusals were token-budget ones — a precise
40
+ * `11115 / "prompt is too long: N tokens > M maximum"` naming both the count
41
+ * and the ceiling.
42
+ *
43
+ * The earlier 350KB bound came from a session that was really tripping a
44
+ * model's *token* ceiling: `hy3` and `minimax-m3.1-flash` enforce 100000, not
45
+ * the 192000/300000 their catalog rows advertise. The bound therefore rejected
46
+ * bodies the gateway accepts and stranded sessions whose history sat between
47
+ * the two numbers — the harness could neither send nor compact.
48
+ *
49
+ * The token ceiling is enforced upstream and already arrives in the one
50
+ * spelling the harness recovers from by compacting, so this is a transport
51
+ * sanity limit rather than a model limit. Override it with
52
+ * DSH_WORKBUDDY_MAX_BODY_BYTES when a proxy in the path has its own cap.
53
+ */
54
+ export const MAX_DELIVERABLE_BODY_BYTES = (() => {
55
+ const configured = Number(process.env['DSH_WORKBUDDY_MAX_BODY_BYTES'])
56
+ // 16 MiB sits above any realistic token-equivalent of a 1048576-token window
57
+ // (16 bytes per token) and below the 32 MiB transport cap, so the upstream's
58
+ // token ceiling — not a local byte guess — is what bounds a request.
59
+ return Number.isFinite(configured) && configured > 0 ? configured : 16 * 1024 * 1024
60
+ })()
61
+
62
+ /** HTTP status each upstream failure class surfaces as. */
63
+ export const KIND_STATUS = {
64
+ hard_credit: 402,
65
+ soft_rate: 429,
66
+ session_dead: 401,
67
+ // Not 401/403: the harness turns those into its own "API key is invalid"
68
+ // notice, which is the one thing a restriction is *not*. 409 keeps the real
69
+ // message in front of the user and stops the retry policy from looping.
70
+ account_restricted: 409,
71
+ not_found: 502,
72
+ server: 502,
73
+ client: 400,
74
+ }
75
+
76
+ /** Loopback hostnames a local plugin surface may be addressed by. */
77
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]'])
78
+
79
+ /** Strip the optional :port from a Host header value, IPv6-bracket aware. */
80
+ function hostnameOfHost(host) {
81
+ const value = String(host ?? '').trim().toLowerCase()
82
+ if (value.startsWith('[')) {
83
+ const end = value.indexOf(']')
84
+ return end === -1 ? value : value.slice(0, end + 1)
85
+ }
86
+ const colon = value.lastIndexOf(':')
87
+ return colon !== -1 && !value.slice(0, colon).includes(':') && /^\d+$/.test(value.slice(colon + 1)) ? value.slice(0, colon) : value
88
+ }
89
+
90
+ /**
91
+ * The request's Host header must name the loopback interface.
92
+ *
93
+ * A DNS-rebinding page (attacker domain re-resolved to 127.0.0.1) sends its own
94
+ * domain in Host, so this check drops those before any routing happens.
95
+ */
96
+ function hostIsLoopback(host) {
97
+ if (typeof host !== 'string' || host.trim() === '') return false
98
+ return LOOPBACK_HOSTS.has(hostnameOfHost(host))
99
+ }
100
+
101
+ /**
102
+ * A browser-sent Origin (present header) must be loopback.
103
+ *
104
+ * Non-browser clients (the plugin's own fetch calls) send no Origin at all and
105
+ * pass.
106
+ */
107
+ function originIsLoopback(origin) {
108
+ if (typeof origin !== 'string' || origin.trim() === '') return true
109
+ return /^https?:\/\/(localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d+)?$/i.test(origin)
110
+ }
111
+
112
+ function writeJson(res, status, body) {
113
+ const payload = JSON.stringify(body)
114
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) })
115
+ res.end(payload)
116
+ }
117
+
118
+ function writeOpenAIError(res, status, kind, message) {
119
+ writeJson(res, status, { error: { message, type: kind, code: kind } })
120
+ }
121
+
122
+ /** Read a request body with a hard ceiling; over-limit bodies fail the request. */
123
+ async function readBody(req) {
124
+ const chunks = []
125
+ let total = 0
126
+ for await (const chunk of req) {
127
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
128
+ total += buffer.length
129
+ if (total > MAX_BODY_BYTES) {
130
+ const error = new Error('request body too large')
131
+ error.statusCode = 413
132
+ throw error
133
+ }
134
+ chunks.push(buffer)
135
+ }
136
+ return Buffer.concat(chunks).toString('utf8')
137
+ }
138
+
139
+ /**
140
+ * Reassemble an SSE stream into the plain chat.completion JSON a client that
141
+ * asked for no stream expects.
142
+ *
143
+ * The upstream only ever streams, so this is not a nicety: it is the only way
144
+ * a non-streaming client can be served at all.
145
+ */
146
+ async function collectCompletion(upstreamRes, signal) {
147
+ const message = { role: 'assistant', content: '' }
148
+ const out = {
149
+ id: `chatcmpl-${randomBytes(12).toString('hex')}`,
150
+ object: 'chat.completion',
151
+ created: Math.floor(Date.now() / 1000),
152
+ model: '',
153
+ choices: [{ index: 0, message, finish_reason: 'stop' }],
154
+ }
155
+ const toolCalls = []
156
+ let reader
157
+ try {
158
+ reader = upstreamRes.body.getReader()
159
+ } catch {
160
+ return out
161
+ }
162
+ const decoder = new TextDecoder()
163
+ let buf = ''
164
+ // Cancelling the reader resolves any in-flight read as done, so a stall
165
+ // mid-stream is broken by the abort rather than blocking the pump.
166
+ const onAbort = () => {
167
+ reader.cancel().catch(() => {})
168
+ }
169
+ if (signal) signal.addEventListener('abort', onAbort, { once: true })
170
+ try {
171
+ for (;;) {
172
+ let chunk
173
+ try {
174
+ chunk = await reader.read()
175
+ } catch {
176
+ break
177
+ }
178
+ if (chunk.done) break
179
+ buf += decoder.decode(chunk.value, { stream: true })
180
+ let index
181
+ while ((index = buf.indexOf('\n\n')) !== -1) {
182
+ const block = buf.slice(0, index + 2)
183
+ buf = buf.slice(index + 2)
184
+ let raw = ''
185
+ for (const line of block.split('\n')) if (line.startsWith('data:')) raw = line.slice(5).trim()
186
+ if (raw === '' || raw === '[DONE]') continue
187
+ let data
188
+ try {
189
+ data = JSON.parse(raw)
190
+ } catch {
191
+ continue
192
+ }
193
+ if (typeof data?.model === 'string' && data.model !== '') out.model = data.model
194
+ if (data?.usage !== undefined && data?.usage !== null) out.usage = data.usage
195
+ for (const choice of Array.isArray(data?.choices) ? data.choices : []) {
196
+ if (typeof choice?.delta?.content === 'string') message.content += choice.delta.content
197
+ if (typeof choice?.delta?.reasoning_content === 'string') {
198
+ message.reasoning_content = (message.reasoning_content ?? '') + choice.delta.reasoning_content
199
+ }
200
+ if (Array.isArray(choice?.delta?.tool_calls)) toolCalls.push(...choice.delta.tool_calls)
201
+ if (typeof choice?.finish_reason === 'string' && choice.finish_reason !== '') out.choices[0].finish_reason = choice.finish_reason
202
+ }
203
+ }
204
+ }
205
+ } finally {
206
+ if (signal) signal.removeEventListener('abort', onAbort)
207
+ }
208
+ if (toolCalls.length > 0) message.tool_calls = mergeToolCallDeltas(toolCalls)
209
+ return out
210
+ }
211
+
212
+ /** Merge the per-delta tool-call fragments into whole calls. */
213
+ function mergeToolCallDeltas(deltas) {
214
+ const merged = []
215
+ for (const delta of deltas) {
216
+ const index = Number.isInteger(delta?.index) ? delta.index : merged.length
217
+ let slot = merged.find(entry => entry.index === index)
218
+ if (slot === undefined) {
219
+ slot = { id: delta?.id ?? `call_${index}`, type: 'function', index, function: { name: delta?.function?.name ?? '', arguments: '' } }
220
+ merged.push(slot)
221
+ }
222
+ if (typeof delta?.function?.name === 'string' && delta.function.name !== '') slot.function.name = delta.function.name
223
+ if (typeof delta?.function?.arguments === 'string') slot.function.arguments += delta.function.arguments
224
+ }
225
+ return merged
226
+ }
227
+
228
+ /** Pump an upstream SSE stream straight through to the client. */
229
+ async function relayStream(res, upstreamRes, signal) {
230
+ res.writeHead(200, {
231
+ 'Content-Type': 'text/event-stream',
232
+ 'Cache-Control': 'no-cache',
233
+ Connection: 'keep-alive',
234
+ 'X-Accel-Buffering': 'no',
235
+ })
236
+ let reader
237
+ try {
238
+ reader = upstreamRes.body.getReader()
239
+ } catch {
240
+ res.end()
241
+ return
242
+ }
243
+ const onAbort = () => {
244
+ reader.cancel().catch(() => {})
245
+ }
246
+ if (signal) signal.addEventListener('abort', onAbort, { once: true })
247
+ const decoder = new TextDecoder()
248
+ let buf = ''
249
+ try {
250
+ for (;;) {
251
+ const chunk = await reader.read()
252
+ if (chunk.done) break
253
+ buf += decoder.decode(chunk.value, { stream: true })
254
+ // Hand over everything up to the last complete event boundary so a split
255
+ // block never gets rewritten wrongly.
256
+ const cut = buf.lastIndexOf('\n\n')
257
+ if (cut !== -1) {
258
+ res.write(buf.slice(0, cut + 2))
259
+ buf = buf.slice(cut + 2)
260
+ }
261
+ }
262
+ if (buf !== '') res.write(buf)
263
+ } catch (error) {
264
+ options.logger?.warn?.('dsh-workbuddy-connect: upstream stream failed mid-flight', error)
265
+ } finally {
266
+ if (signal) signal.removeEventListener('abort', onAbort)
267
+ if (res.writable && !res.writableEnded) res.end()
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Start the loopback endpoint.
273
+ *
274
+ * @param {object} options
275
+ * @param {object} options.store Credential store (resolves the real upstream token).
276
+ * @param {object} options.client Upstream client (`chatStream`).
277
+ * @param {object} options.catalog The live catalog (`current()`).
278
+ * @param {object} [options.logger] Host logger.
279
+ * @param {(body: string) => string} [options.prepareBody] Body preparation hook.
280
+ * @param {(id: string) => string|undefined} [options.defaultEffortFor] Per-model default reasoning effort.
281
+ * @param {() => void} [options.onSessionDead] Called when the upstream refuses the stored credential.
282
+ * @param {(reason: string) => void} [options.onAccountRestricted] Called when the upstream restricts the account.
283
+ * @param {() => void} [options.onSessionFresh] Called after a call the upstream accepted.
284
+ * @param {string} [options.dumpBodyPath] Write the exact outbound body here (diagnostics; off by default).
285
+ */
286
+ export function createWorkBuddyShim(options) {
287
+ const { store, client, catalog } = options
288
+ const logger = options.logger
289
+
290
+ // Per-process shared secret. Lives only in memory; the adapter resolves it
291
+ // as the OpenAI apiKey, which pi-ai sends as `Authorization: Bearer ...`.
292
+ // The shim never forwards it upstream — the real credential comes from the
293
+ // store. A local attacker who can hit the port still cannot forge this.
294
+ const SHARED_SECRET = randomBytes(32).toString('base64url')
295
+
296
+ /** Constant-time bearer check; absent or mismatched bearers are rejected. */
297
+ function bearerOk(req) {
298
+ const header = req.headers.authorization
299
+ if (typeof header !== 'string') return false
300
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim())
301
+ if (match === null) return false
302
+ const a = Buffer.from(match[1])
303
+ const b = Buffer.from(SHARED_SECRET)
304
+ return a.length === b.length && timingSafeEqual(a, b)
305
+ }
306
+
307
+ async function chatCompletions(req, res) {
308
+ const contentType = req.headers['content-type']
309
+ if (typeof contentType !== 'string' || !contentType.trim().toLowerCase().startsWith('application/json')) {
310
+ writeOpenAIError(res, 415, 'unsupported_media_type', 'Content-Type must be application/json')
311
+ return
312
+ }
313
+ let raw
314
+ try {
315
+ raw = await readBody(req)
316
+ } catch (error) {
317
+ writeOpenAIError(res, error?.statusCode === 413 ? 413 : 400, 'invalid_request_error', String(error?.message ?? error))
318
+ return
319
+ }
320
+ let credential
321
+ try {
322
+ credential = await store.resolve()
323
+ } catch (error) {
324
+ writeOpenAIError(res, 401, 'not_signed_in', String(error?.message ?? error))
325
+ return
326
+ }
327
+ // Resolve the model's own default reasoning level so the "Default" level
328
+ // (which pi-ai spells `off`) goes on the wire as that declared value, and
329
+ // so a model that refuses `off` is never asked for it.
330
+ let defaultEffort
331
+ let modelId
332
+ try {
333
+ const parsed = JSON.parse(raw)
334
+ modelId = typeof parsed?.model === 'string' ? parsed.model : undefined
335
+ if (modelId !== undefined) defaultEffort = options.defaultEffortFor?.(modelId)
336
+ } catch {
337
+ // Malformed body: the preparation hook reports it as-is.
338
+ }
339
+ const prepared = options.prepareBody
340
+ ? options.prepareBody(raw, {
341
+ ...defaultEffort === undefined ? {} : { defaultEffort },
342
+ ...modelId === undefined ? {} : { modelId },
343
+ })
344
+ : raw
345
+
346
+ // Opt-in transcript of the exact body that leaves this process, for
347
+ // diagnosing a gateway refusal that depends on the request content. Off
348
+ // unless the operator names a path, and the file is created 0600: a body
349
+ // carries the whole conversation.
350
+ if (options.dumpBodyPath !== undefined) {
351
+ try {
352
+ writeFileSync(options.dumpBodyPath, prepared, { mode: 0o600 })
353
+ } catch {
354
+ // A diagnostic write must never take down the request it describes.
355
+ }
356
+ }
357
+
358
+ // An over-bound body is answered locally, in the harness's own
359
+ // context-overflow spelling: that is the one failure it recovers from by
360
+ // compacting, and the upstream's own answers at this size — a hang, a cut
361
+ // connection, a bare 400 — give it nothing to act on.
362
+ if (prepared.length > MAX_DELIVERABLE_BODY_BYTES) {
363
+ writeOpenAIError(
364
+ res,
365
+ 400,
366
+ 'context_length_exceeded',
367
+ "This request exceeded the model's maximum context length (the prepared body is past what the WorkBuddy gateway reliably accepts). Please reduce the length of the messages or run compaction.",
368
+ )
369
+ return
370
+ }
371
+
372
+ const controller = new AbortController()
373
+ const onClientClose = () => controller.abort()
374
+ res.on('close', onClientClose)
375
+ try {
376
+ const result = await client.chatStream(credential, prepared, controller.signal)
377
+ if (!result.ok) {
378
+ // The upstream's own `extError` names the offending field and its
379
+ // value; without it a refusal reads as "model unavailable" and the fix
380
+ // lives nowhere in the message.
381
+ const detail = describeUpstreamFailure(result.message)
382
+ // A size refusal under the bound (a model whose real window is smaller
383
+ // than its row declares) is re-spelled into the same context-overflow
384
+ // error: measured 2026-10-25, the upstream answers it as a bare 400
385
+ // with business code 11115, which the harness would otherwise read as
386
+ // a plain invalid request and never compact from.
387
+ if (/11115|context length|maximum context|too long/i.test(String(result.message))) {
388
+ options.onSessionFresh?.()
389
+ writeOpenAIError(
390
+ res,
391
+ 400,
392
+ 'context_length_exceeded',
393
+ `This request exceeded the model's maximum context length. Please reduce the length of the messages or run compaction. (upstream: ${String(result.message).slice(0, 300)})`,
394
+ )
395
+ return
396
+ }
397
+ // A dead session is the one failure the card can act on: the stored
398
+ // credential was rotated away (the desktop app re-signs in behind the
399
+ // plugin's back), so the card has to say so instead of keeping a
400
+ // "signed in" badge over a token nobody can use.
401
+ if (result.kind === 'session_dead') options.onSessionDead?.()
402
+ // An account restriction is NOT a credential problem, and the text must
403
+ // not contain a bare 401/403: the harness adapter classifies any
404
+ // message mentioning one as its own AUTH failure and replaces this
405
+ // explanation with "API key is invalid" — the exact misdiagnosis this
406
+ // branch exists to prevent.
407
+ if (result.kind === 'account_restricted') {
408
+ const explanation = describeAccountRestriction(String(result.message)) ?? 'upstream restricted this account'
409
+ options.onAccountRestricted?.(explanation)
410
+ writeOpenAIError(
411
+ res,
412
+ KIND_STATUS.account_restricted,
413
+ 'account_restricted',
414
+ `WorkBuddy restricted this account, so no model will answer until the restriction is lifted. ${explanation}`,
415
+ )
416
+ return
417
+ }
418
+ writeOpenAIError(
419
+ res,
420
+ KIND_STATUS[result.kind] ?? 502,
421
+ result.kind,
422
+ `workbuddy upstream ${result.kind} (http ${result.status})${detail === '' ? '' : `; ${detail}`}: ${String(result.message).slice(0, 400)}`,
423
+ )
424
+ return
425
+ }
426
+ options.onSessionFresh?.()
427
+ const wantsStream = (() => {
428
+ try {
429
+ return JSON.parse(raw)?.stream === true
430
+ } catch {
431
+ return false
432
+ }
433
+ })()
434
+ if (wantsStream) {
435
+ await relayStream(res, result.response, controller.signal)
436
+ return
437
+ }
438
+ const content = await collectCompletion(result.response, controller.signal)
439
+ writeJson(res, 200, content)
440
+ } finally {
441
+ res.removeListener('close', onClientClose)
442
+ }
443
+ }
444
+
445
+ const server = createServer((req, res) => {
446
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1').pathname.replace(/\/+$/, '') || '/'
447
+ if (!hostIsLoopback(req.headers.host)) {
448
+ writeOpenAIError(res, 403, 'host_not_allowed', 'Host header must name the loopback interface')
449
+ return
450
+ }
451
+ if (!originIsLoopback(req.headers.origin)) {
452
+ writeOpenAIError(res, 403, 'origin_not_allowed', 'Origin must be a loopback origin')
453
+ return
454
+ }
455
+ if (!bearerOk(req)) {
456
+ writeOpenAIError(res, 401, 'unauthorized', 'missing or invalid Authorization bearer')
457
+ return
458
+ }
459
+ if (req.method === 'GET' && (url === '/healthz' || url === '/v1/models' || url === '/models')) {
460
+ if (url !== '/healthz') {
461
+ writeJson(res, 200, {
462
+ object: 'list',
463
+ data: catalog.current().map(model => ({
464
+ id: model.id,
465
+ object: 'model',
466
+ created: 0,
467
+ owned_by: 'workbuddy',
468
+ })),
469
+ })
470
+ return
471
+ }
472
+ writeJson(res, 200, { ok: true })
473
+ return
474
+ }
475
+ if (req.method === 'POST' && (url === '/v1/chat/completions' || url === '/chat/completions')) {
476
+ chatCompletions(req, res).catch(error => {
477
+ logger?.warn?.('dsh-workbuddy-connect: loopback request failed', error)
478
+ try {
479
+ if (!res.headersSent) writeOpenAIError(res, 500, 'internal', String(error))
480
+ else res.end()
481
+ } catch {
482
+ // The response is already gone; nothing left to say.
483
+ }
484
+ })
485
+ return
486
+ }
487
+ writeOpenAIError(res, 404, 'not_found', `no such route: ${req.method} ${url}`)
488
+ })
489
+ server.requestTimeout = 0
490
+ server.headersTimeout = 60_000
491
+ // The shim must never hold a finished CLI run open: an unref'd listener lets
492
+ // the process exit while the server is up.
493
+ server.unref()
494
+
495
+ // A fixed loopback port keeps baseUrl() usable synchronously: the adapter's
496
+ // model descriptors embed the shim origin at construction, and the headless
497
+ // host starts its first turn before an awaited setup continuation resolves.
498
+ // A collision falls back to an ephemeral port and the caller refreshes its
499
+ // descriptors when `ready` lands. The promise never rejects: an unawaited
500
+ // rejection would tear down the host process.
501
+ const ready = new Promise((resolve) => {
502
+ server.once('listening', () => resolve(true))
503
+ server.once('error', (error) => {
504
+ if (error?.code === 'EADDRINUSE') {
505
+ logger?.warn?.(`dsh-workbuddy-connect: port ${SHIM_PORT} is busy, falling back to an ephemeral loopback port`)
506
+ server.once('error', (retryError) => {
507
+ logger?.error?.('dsh-workbuddy-connect: loopback endpoint failed to start', retryError)
508
+ resolve(false)
509
+ })
510
+ server.listen(0, '127.0.0.1')
511
+ return
512
+ }
513
+ logger?.error?.('dsh-workbuddy-connect: loopback endpoint failed to start', error)
514
+ resolve(false)
515
+ })
516
+ })
517
+ server.listen(SHIM_PORT, '127.0.0.1')
518
+
519
+ return {
520
+ ready,
521
+ baseUrl: () => `http://127.0.0.1:${server.address()?.port ?? SHIM_PORT}`,
522
+ token: () => SHARED_SECRET,
523
+ close: () => new Promise((resolve, reject) => {
524
+ server.close(() => resolve())
525
+ server.closeAllConnections()
526
+ server.once('error', reject)
527
+ }),
528
+ }
529
+ }
530
+
531
+ export { createHash }