dsh-browser-firefox 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/cordis.patch.yml +29 -0
- package/lib/index.js +1182 -0
- package/lib/invariant.js +26 -0
- package/lib/protocol.js +134 -0
- package/lib/types/index.d.ts +59 -0
- package/lib/types/invariant.d.ts +16 -0
- package/lib/types/protocol.d.ts +144 -0
- package/lib/types/server.d.ts +127 -0
- package/lib/types/session-deferral.d.ts +25 -0
- package/lib/types/session-workspace.d.ts +22 -0
- package/lib/types/token.d.ts +57 -0
- package/lib/types/tools.d.ts +39 -0
- package/package.json +98 -0
- package/src/index.ts +194 -0
- package/src/invariant.ts +33 -0
- package/src/protocol.ts +199 -0
- package/src/server.ts +438 -0
- package/src/session-deferral.ts +99 -0
- package/src/session-workspace.ts +81 -0
- package/src/token.ts +100 -0
- package/src/tools.ts +396 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge WebSocket carrier: token-authenticated connection registry, gateway
|
|
3
|
+
* RPC passthrough, per-connection event pump, and tool-call dispatch to the
|
|
4
|
+
* connected browser extension.
|
|
5
|
+
*
|
|
6
|
+
* The route this server mounts (`/ext/bridge`) lives OUTSIDE the /api trust
|
|
7
|
+
* fence (which only guards the client-connection routes), so the bridge brings
|
|
8
|
+
* its own authentication: a bearer token presented in the `hello` frame within
|
|
9
|
+
* HELLO_TIMEOUT_MS. Gateway RPCs are dispatched through the same fetch-shaped
|
|
10
|
+
* handler the /api carrier uses (`toFetchHandler`), so schema validation and
|
|
11
|
+
* error envelopes are identical to the GUI path. Methods the /api carrier
|
|
12
|
+
* pins to loopback (`PRIVILEGED_METHODS`) stay loopback-only here regardless
|
|
13
|
+
* of the token, defense in depth for `--host 0.0.0.0` deployments.
|
|
14
|
+
*
|
|
15
|
+
* One active connection at a time: a new authenticated socket replaces the
|
|
16
|
+
* previous one (the old socket is closed and its in-flight tool calls settle
|
|
17
|
+
* as `bridge-closed`).
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { randomUUID } from 'node:crypto'
|
|
23
|
+
import type { IncomingMessage } from 'node:http'
|
|
24
|
+
import type { Duplex } from 'node:stream'
|
|
25
|
+
import { WebSocket, WebSocketServer } from 'ws'
|
|
26
|
+
import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
|
|
27
|
+
import {
|
|
28
|
+
HELLO_TIMEOUT_MS,
|
|
29
|
+
PING_INTERVAL_MS,
|
|
30
|
+
parseBridgeFrame,
|
|
31
|
+
type BridgeFrame,
|
|
32
|
+
type BridgeCaps,
|
|
33
|
+
type ClientFrame,
|
|
34
|
+
type ToolErrorCode,
|
|
35
|
+
} from './protocol.ts'
|
|
36
|
+
import { verifyToken } from './token.ts'
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Gateway methods the /api carrier pins to loopback (mirror of
|
|
40
|
+
* client-connection's PRIVILEGED_METHODS; kept verbatim so the two fences
|
|
41
|
+
* cannot drift). The bridge rejects these for non-loopback remotes even with
|
|
42
|
+
* a valid token.
|
|
43
|
+
*/
|
|
44
|
+
const PRIVILEGED_METHODS = new Set([
|
|
45
|
+
'host.pickDirectory',
|
|
46
|
+
'host.openPath',
|
|
47
|
+
'settings.describe',
|
|
48
|
+
'settings.openDocument',
|
|
49
|
+
'settings.update',
|
|
50
|
+
'settings.replace',
|
|
51
|
+
'settings.mutate',
|
|
52
|
+
'credentials.describe',
|
|
53
|
+
'credentials.set',
|
|
54
|
+
'credentials.unset',
|
|
55
|
+
])
|
|
56
|
+
|
|
57
|
+
/** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
|
|
58
|
+
export function isLoopbackAddress(address: string | undefined): boolean {
|
|
59
|
+
return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Error thrown by requestTool; the tool registry turns it into an isError result. */
|
|
63
|
+
export class BridgeToolError extends Error {
|
|
64
|
+
constructor(
|
|
65
|
+
readonly code: ToolErrorCode,
|
|
66
|
+
message: string,
|
|
67
|
+
) {
|
|
68
|
+
super(message)
|
|
69
|
+
this.name = 'BridgeToolError'
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Dependencies the bridge needs from the host. */
|
|
74
|
+
export interface BridgeServerDeps {
|
|
75
|
+
/** Bearer token the extension must present in `hello`. */
|
|
76
|
+
token: string
|
|
77
|
+
/** Fetch-shaped gateway carrier (from `toFetchHandler(ctx.apiProxy)`). */
|
|
78
|
+
apiHandler: { fetch: (request: Request) => Promise<Response> }
|
|
79
|
+
/** Per-connection event stream (usually `ctx.apiProxy.events.mux`). */
|
|
80
|
+
openEvents: (signal: AbortSignal) => AsyncIterable<RpcRequest<MuxFrame>>
|
|
81
|
+
/** Default per-tool-call timeout in ms. */
|
|
82
|
+
toolTimeoutMs: number
|
|
83
|
+
/** Capabilities to echo in `hello.ok` (negotiated snapshot budgets). */
|
|
84
|
+
caps: BridgeCaps
|
|
85
|
+
/**
|
|
86
|
+
* Test seam: force the remote address seen by the privilege gate. The
|
|
87
|
+
* sandbox cannot bind arbitrary loopback literals, so the non-loopback
|
|
88
|
+
* branch is exercised through this override; production never sets it.
|
|
89
|
+
*/
|
|
90
|
+
remoteAddressOverride?: string
|
|
91
|
+
/** Seconds a fresh socket may present `hello`; defaults to HELLO_TIMEOUT_MS. */
|
|
92
|
+
helloTimeoutMs?: number
|
|
93
|
+
/** Server ping cadence; defaults to PING_INTERVAL_MS. */
|
|
94
|
+
pingIntervalMs?: number
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** One in-flight tool call awaiting the extension's `tool.result`. */
|
|
98
|
+
interface PendingTool {
|
|
99
|
+
resolve: (result: unknown) => void
|
|
100
|
+
reject: (error: BridgeToolError) => void
|
|
101
|
+
timer: NodeJS.Timeout
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A socket that passed authentication and owns the single active slot. */
|
|
105
|
+
interface ReadyConnection {
|
|
106
|
+
ws: WebSocket
|
|
107
|
+
/** Remote address captured at upgrade time (loopback gate for privileged methods). */
|
|
108
|
+
remoteAddress: string | undefined
|
|
109
|
+
abort: AbortController
|
|
110
|
+
pump: Promise<void>
|
|
111
|
+
ping: NodeJS.Timeout
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function sendFrame(ws: WebSocket, frame: BridgeFrame): void {
|
|
115
|
+
/* v8 ignore next -- teardown race: the socket can die between a pump's
|
|
116
|
+
readiness check and this write; the guard refuses writes on dead sockets */
|
|
117
|
+
if (ws.readyState !== WebSocket.OPEN) return
|
|
118
|
+
ws.send(JSON.stringify(frame))
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Decode one ws message payload to text. Exported so all three delivery
|
|
123
|
+
* shapes (fragmented buffer list, Buffer, ArrayBuffer) are unit-testable
|
|
124
|
+
* directly — node ws only ever delivers Buffers in practice.
|
|
125
|
+
* @param data - ws message payload.
|
|
126
|
+
* @returns the decoded UTF-8 text.
|
|
127
|
+
*/
|
|
128
|
+
export function messageToText(data: Buffer | ArrayBuffer | Buffer[]): string {
|
|
129
|
+
if (Array.isArray(data)) return Buffer.concat(data).toString('utf8')
|
|
130
|
+
if (Buffer.isBuffer(data)) return data.toString('utf8')
|
|
131
|
+
return Buffer.from(data).toString('utf8')
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Token-authenticated bridge server. Construct once per plugin instance;
|
|
136
|
+
* dispose with {@link close}.
|
|
137
|
+
*/
|
|
138
|
+
export class BridgeServer {
|
|
139
|
+
private readonly wss = new WebSocketServer({ noServer: true })
|
|
140
|
+
private current: ReadyConnection | null = null
|
|
141
|
+
private readonly pendingTools = new Map<string, PendingTool>()
|
|
142
|
+
private closed = false
|
|
143
|
+
|
|
144
|
+
constructor(private readonly deps: BridgeServerDeps) {}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Handle one HTTP upgrade for the bridge path.
|
|
148
|
+
* @param req - upgrade request (carries the client's remote address).
|
|
149
|
+
* @param socket - raw socket transferred by the HTTP server.
|
|
150
|
+
* @param head - bytes already read after the upgrade headers.
|
|
151
|
+
*/
|
|
152
|
+
handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void {
|
|
153
|
+
const remote = this.deps.remoteAddressOverride ?? req.socket.remoteAddress
|
|
154
|
+
const origin = req.headers.origin
|
|
155
|
+
this.wss.handleUpgrade(req, socket, head, (ws) => { this.attach(ws, remote, origin) })
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Request one browser action from the connected extension.
|
|
160
|
+
* @param name - tool name (also the wire action name).
|
|
161
|
+
* @param args - validated tool arguments.
|
|
162
|
+
* @param signal - caller cancellation (abort settles the call as cancelled).
|
|
163
|
+
* @param timeoutMs - per-call budget; defaults to the plugin config value.
|
|
164
|
+
* @returns the extension's action result.
|
|
165
|
+
* @throws BridgeToolError when no extension is connected, the call times
|
|
166
|
+
* out, is cancelled, or the extension reports a failure.
|
|
167
|
+
*/
|
|
168
|
+
requestTool(
|
|
169
|
+
name: string,
|
|
170
|
+
args: Record<string, unknown>,
|
|
171
|
+
signal: AbortSignal,
|
|
172
|
+
timeoutMs: number = this.deps.toolTimeoutMs,
|
|
173
|
+
sessionId?: string,
|
|
174
|
+
title?: string,
|
|
175
|
+
): Promise<unknown> {
|
|
176
|
+
const conn = this.current
|
|
177
|
+
if (conn === null) {
|
|
178
|
+
throw new BridgeToolError('bridge-closed', 'no browser extension is connected to the bridge')
|
|
179
|
+
}
|
|
180
|
+
// A caller that already aborted must not dispatch: the abort listener
|
|
181
|
+
// below does not replay for pre-aborted signals, so the call would be
|
|
182
|
+
// sent to the extension and executed despite the cancellation.
|
|
183
|
+
if (signal.aborted) {
|
|
184
|
+
throw new BridgeToolError('bridge-closed', 'tool call cancelled before dispatch')
|
|
185
|
+
}
|
|
186
|
+
const id = randomUUID()
|
|
187
|
+
return new Promise<unknown>((resolve, reject) => {
|
|
188
|
+
let timer: NodeJS.Timeout
|
|
189
|
+
const settle = (error: BridgeToolError): void => {
|
|
190
|
+
clearTimeout(timer)
|
|
191
|
+
this.pendingTools.delete(id)
|
|
192
|
+
signal.removeEventListener('abort', onAbort)
|
|
193
|
+
reject(error)
|
|
194
|
+
}
|
|
195
|
+
const onAbort = (): void => {
|
|
196
|
+
settle(new BridgeToolError('bridge-closed', 'tool call cancelled before the extension answered'))
|
|
197
|
+
}
|
|
198
|
+
timer = setTimeout(() => {
|
|
199
|
+
settle(new BridgeToolError('timeout', `browser action "${name}" timed out after ${timeoutMs}ms`))
|
|
200
|
+
}, timeoutMs)
|
|
201
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
202
|
+
this.pendingTools.set(id, { resolve, reject, timer })
|
|
203
|
+
const callFrame: BridgeFrame = { t: 'tool.call', id, name, args, ...(sessionId !== undefined ? { sessionId } : {}), ...(title !== undefined ? { title } : {}) }
|
|
204
|
+
conn.ws.send(JSON.stringify(callFrame), (error) => {
|
|
205
|
+
/* v8 ignore next -- teardown race: when the write fails, the socket's
|
|
206
|
+
close handler settles the same call with the same code; the callback
|
|
207
|
+
path is a defensive second settle, covered via the close path */
|
|
208
|
+
if (error != null) {
|
|
209
|
+
settle(new BridgeToolError('bridge-closed', `bridge socket failed before delivery: ${error.message}`))
|
|
210
|
+
}
|
|
211
|
+
})
|
|
212
|
+
})
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Terminate the server: close the acceptor, drop all sockets, reject all
|
|
217
|
+
* in-flight tool calls.
|
|
218
|
+
* @returns a promise resolving after the acceptor and all pumps stop.
|
|
219
|
+
*/
|
|
220
|
+
async close(): Promise<void> {
|
|
221
|
+
// Idempotent: a second close must not touch the acceptor (ws throws
|
|
222
|
+
// "The server is not running" when closing an already-closed server).
|
|
223
|
+
if (this.closed) return
|
|
224
|
+
this.closed = true
|
|
225
|
+
// Capture the live pump BEFORE replaceConnection nulls the connection.
|
|
226
|
+
const pumps = this.current === null ? [] : [this.current.pump]
|
|
227
|
+
this.replaceConnection()
|
|
228
|
+
for (const socket of this.wss.clients) socket.terminate()
|
|
229
|
+
this.current = null
|
|
230
|
+
await new Promise<void>((resolve, reject) => {
|
|
231
|
+
this.wss.close((error) => {
|
|
232
|
+
/* v8 ignore next -- acceptor close cannot fail: close() is idempotent
|
|
233
|
+
and the noServer acceptor only reports teardown of already-terminated clients */
|
|
234
|
+
if (error === undefined) resolve()
|
|
235
|
+
/* v8 ignore next -- same unreachable arm */
|
|
236
|
+
else reject(error)
|
|
237
|
+
})
|
|
238
|
+
})
|
|
239
|
+
await Promise.all(pumps)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** @returns whether an authenticated extension is currently connected. */
|
|
243
|
+
hasConnection(): boolean {
|
|
244
|
+
return this.current !== null
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
private attach(ws: WebSocket, remoteAddress: string | undefined, origin: string | undefined): void {
|
|
248
|
+
let helloTimer: NodeJS.Timeout | undefined = setTimeout(() => {
|
|
249
|
+
ws.close(4001, 'hello timeout')
|
|
250
|
+
}, this.deps.helloTimeoutMs ?? HELLO_TIMEOUT_MS)
|
|
251
|
+
|
|
252
|
+
const onMessage = (data: Buffer | ArrayBuffer | Buffer[]): void => {
|
|
253
|
+
const text = messageToText(data)
|
|
254
|
+
const frame = parseBridgeFrame(text)
|
|
255
|
+
if (frame === undefined) {
|
|
256
|
+
ws.close(1008, 'unparseable frame')
|
|
257
|
+
return
|
|
258
|
+
}
|
|
259
|
+
if (helloTimer !== undefined) {
|
|
260
|
+
// Pending state: only `hello` is legal.
|
|
261
|
+
if (frame.t !== 'hello') {
|
|
262
|
+
ws.close(1008, 'hello first')
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
// Zero-config local mode: loopback sockets skip the token (the
|
|
266
|
+
// extension auto-discovers the bridge and connects without setup).
|
|
267
|
+
// WebSockets have no same-origin policy, so a malicious page could
|
|
268
|
+
// open a cross-origin socket to 127.0.0.1 with a loopback remote —
|
|
269
|
+
// the loopback shortcut therefore requires a chrome-extension://
|
|
270
|
+
// Origin (only extension contexts can present one; pages cannot
|
|
271
|
+
// forge the header). Non-loopback remotes must still present the
|
|
272
|
+
// bearer token.
|
|
273
|
+
const loopbackNoToken = isLoopbackAddress(remoteAddress)
|
|
274
|
+
&& typeof origin === 'string'
|
|
275
|
+
&& (origin.startsWith('chrome-extension://') || origin.startsWith('moz-extension://'))
|
|
276
|
+
if (!loopbackNoToken && !verifyToken(this.deps.token, frame.token)) {
|
|
277
|
+
ws.close(4002, 'bad token')
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
clearTimeout(helloTimer)
|
|
281
|
+
helloTimer = undefined
|
|
282
|
+
this.promote(ws, remoteAddress)
|
|
283
|
+
return
|
|
284
|
+
}
|
|
285
|
+
this.handleReadyFrame(frame)
|
|
286
|
+
}
|
|
287
|
+
const onClose = (): void => {
|
|
288
|
+
if (helloTimer !== undefined) clearTimeout(helloTimer)
|
|
289
|
+
if (this.current !== null && this.current.ws === ws) this.replaceConnection()
|
|
290
|
+
}
|
|
291
|
+
ws.on('message', onMessage)
|
|
292
|
+
ws.once('close', onClose)
|
|
293
|
+
ws.once('error', onClose)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Promote an authenticated socket to the single active slot. */
|
|
297
|
+
private promote(ws: WebSocket, remoteAddress: string | undefined): void {
|
|
298
|
+
this.replaceConnection()
|
|
299
|
+
const abort = new AbortController()
|
|
300
|
+
const ping = setInterval(() => { sendFrame(ws, { t: 'ping' }) }, this.deps.pingIntervalMs ?? PING_INTERVAL_MS)
|
|
301
|
+
const pump = (async () => {
|
|
302
|
+
try {
|
|
303
|
+
for await (const envelope of this.deps.openEvents(abort.signal)) {
|
|
304
|
+
if (ws.readyState !== WebSocket.OPEN) break
|
|
305
|
+
sendFrame(ws, {
|
|
306
|
+
t: 'event',
|
|
307
|
+
frame: { rpcId: envelope.rpcId, method: envelope.payload.type, payload: envelope.payload },
|
|
308
|
+
})
|
|
309
|
+
}
|
|
310
|
+
} catch (error: unknown) {
|
|
311
|
+
if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) {
|
|
312
|
+
sendFrame(ws, { t: 'error', code: 'stream-failed', message: String(error) })
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
})()
|
|
316
|
+
this.current = { ws, remoteAddress, abort, pump, ping }
|
|
317
|
+
sendFrame(ws, { t: 'hello.ok', caps: this.deps.caps })
|
|
318
|
+
ws.once('close', () => {
|
|
319
|
+
clearInterval(ping)
|
|
320
|
+
abort.abort()
|
|
321
|
+
})
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
private handleReadyFrame(frame: BridgeFrame): void {
|
|
325
|
+
switch (frame.t) {
|
|
326
|
+
case 'rpc':
|
|
327
|
+
void this.handleRpc(frame)
|
|
328
|
+
break
|
|
329
|
+
case 'tool.result':
|
|
330
|
+
this.settleTool(frame.id, frame.ok, frame.ok ? frame.result : frame.error)
|
|
331
|
+
break
|
|
332
|
+
case 'pong':
|
|
333
|
+
case 'hello':
|
|
334
|
+
case 'hello.ok':
|
|
335
|
+
case 'rpc.result':
|
|
336
|
+
case 'event':
|
|
337
|
+
case 'tool.call':
|
|
338
|
+
case 'ping':
|
|
339
|
+
case 'error':
|
|
340
|
+
// Protocol violations and unsolicited server-side shapes are ignored;
|
|
341
|
+
// the extension is the only sender on this channel.
|
|
342
|
+
break
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
private async handleRpc(frame: Extract<ClientFrame, { t: 'rpc' }>): Promise<void> {
|
|
347
|
+
const conn = this.current
|
|
348
|
+
/* v8 ignore next -- replacement race: a frame can land between a socket
|
|
349
|
+
replacement and the next promotion; the re-check keeps the handler total */
|
|
350
|
+
if (conn === null) return
|
|
351
|
+
const forbidden = PRIVILEGED_METHODS.has(frame.method) && !isLoopbackAddress(conn.remoteAddress)
|
|
352
|
+
if (forbidden) {
|
|
353
|
+
sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'forbidden', message: 'method is loopback-only' } })
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
const body = JSON.stringify({ type: 'client-request', rpcId: frame.id, method: frame.method, payload: frame.payload })
|
|
357
|
+
const request = new Request(new URL(`/api/${frame.method}`, 'http://dsh.internal'), {
|
|
358
|
+
method: 'POST',
|
|
359
|
+
headers: { 'content-type': 'application/json' },
|
|
360
|
+
body,
|
|
361
|
+
})
|
|
362
|
+
try {
|
|
363
|
+
const response = await this.deps.apiHandler.fetch(request)
|
|
364
|
+
const text = await response.text()
|
|
365
|
+
if (!response.ok) {
|
|
366
|
+
sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'http', message: text } })
|
|
367
|
+
return
|
|
368
|
+
}
|
|
369
|
+
let result: unknown
|
|
370
|
+
try {
|
|
371
|
+
result = JSON.parse(text)
|
|
372
|
+
} catch {
|
|
373
|
+
result = text
|
|
374
|
+
}
|
|
375
|
+
sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, result })
|
|
376
|
+
} catch (error: unknown) {
|
|
377
|
+
sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'internal', message: String(error) } })
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
private settleTool(id: string, ok: boolean, payload: unknown): void {
|
|
382
|
+
const pending = this.pendingTools.get(id)
|
|
383
|
+
if (pending === undefined) return
|
|
384
|
+
clearTimeout(pending.timer)
|
|
385
|
+
this.pendingTools.delete(id)
|
|
386
|
+
if (ok) pending.resolve(payload)
|
|
387
|
+
else pending.reject(new BridgeToolError(payloadCode(payload), payloadMessage(payload)))
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Close the current connection (if any) and settle its in-flight calls. */
|
|
391
|
+
private replaceConnection(): void {
|
|
392
|
+
const conn = this.current
|
|
393
|
+
if (conn === null) return
|
|
394
|
+
this.current = null
|
|
395
|
+
clearInterval(conn.ping)
|
|
396
|
+
conn.abort.abort()
|
|
397
|
+
if (conn.ws.readyState === WebSocket.OPEN || conn.ws.readyState === WebSocket.CONNECTING) {
|
|
398
|
+
conn.ws.close(4000, 'replaced')
|
|
399
|
+
}
|
|
400
|
+
for (const [id, pending] of this.pendingTools) {
|
|
401
|
+
clearTimeout(pending.timer)
|
|
402
|
+
this.pendingTools.delete(id)
|
|
403
|
+
pending.reject(new BridgeToolError('bridge-closed', 'the extension connection was replaced'))
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Tool error payload → stable code. The wire parser enforces string fields,
|
|
410
|
+
* so the fallback branches are parser-gated; exported so the fallback
|
|
411
|
+
* contract is unit-testable directly.
|
|
412
|
+
* @param payload - extension-reported error payload.
|
|
413
|
+
* @returns the stable error code.
|
|
414
|
+
*/
|
|
415
|
+
export function payloadCode(payload: unknown): ToolErrorCode {
|
|
416
|
+
if (typeof payload === 'object' && payload !== null) {
|
|
417
|
+
const code = (payload as { code?: unknown }).code
|
|
418
|
+
if (typeof code === 'string') return code as ToolErrorCode
|
|
419
|
+
return 'internal'
|
|
420
|
+
}
|
|
421
|
+
return 'internal'
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Tool error payload → message. The wire parser enforces string fields, so
|
|
426
|
+
* the fallback branches are parser-gated; exported so the fallback contract
|
|
427
|
+
* is unit-testable directly.
|
|
428
|
+
* @param payload - extension-reported error payload.
|
|
429
|
+
* @returns the human-readable message.
|
|
430
|
+
*/
|
|
431
|
+
export function payloadMessage(payload: unknown): string {
|
|
432
|
+
if (typeof payload === 'object' && payload !== null) {
|
|
433
|
+
const message = (payload as { message?: unknown }).message
|
|
434
|
+
if (typeof message === 'string' && message.length > 0) return message
|
|
435
|
+
return 'browser action failed'
|
|
436
|
+
}
|
|
437
|
+
return 'browser action failed'
|
|
438
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Defer real session creation until the first prompt.
|
|
3
|
+
*
|
|
4
|
+
* The panel calls `session.create` as soon as it connects, but a session that
|
|
5
|
+
* is opened and never used should leave zero trace in the store/GUI. This
|
|
6
|
+
* wrapper answers `session.create` with a provisional id (minted locally,
|
|
7
|
+
* nothing persisted), serves `session.history` for provisional ids as empty,
|
|
8
|
+
* and materializes the real session — same id, original create payload — on
|
|
9
|
+
* the first `session.prompt` for that id. Abandoned provisional ids are
|
|
10
|
+
* pruned after {@link PROVISIONAL_TTL_MS}.
|
|
11
|
+
*
|
|
12
|
+
* @module @deepseek-ai/dsh-bridge-browser/src/session-deferral
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { randomUUID } from 'node:crypto'
|
|
16
|
+
import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api'
|
|
17
|
+
import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api'
|
|
18
|
+
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
|
19
|
+
|
|
20
|
+
/** Provisional entries older than this are dropped on the next create. */
|
|
21
|
+
const PROVISIONAL_TTL_MS = 30 * 60_000
|
|
22
|
+
|
|
23
|
+
type CreateRequest = Parameters<ApiProxy['sessions']['create']>[0]
|
|
24
|
+
type HistoryRequest = Parameters<ApiProxy['sessions']['history']>[0]
|
|
25
|
+
type PromptRequest = Parameters<ApiProxy['sessions']['prompt']>[0]
|
|
26
|
+
|
|
27
|
+
interface ProvisionalEntry {
|
|
28
|
+
/** The original create payload, replayed at materialization (keeps cwd/workspaceId). */
|
|
29
|
+
payload: CreateRequest['payload']
|
|
30
|
+
createdAt: number
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Wrap the gateway sessions API so `session.create` returns a provisional id
|
|
35
|
+
* without creating anything; the real session materializes on the first
|
|
36
|
+
* `session.prompt` for that id.
|
|
37
|
+
*
|
|
38
|
+
* @param api - Gateway API implementation.
|
|
39
|
+
* @param enabled - Whether deferral is active; false returns the API untouched.
|
|
40
|
+
* @returns the original API when disabled, otherwise the wrapped API.
|
|
41
|
+
*/
|
|
42
|
+
export function withSessionDeferral(api: ApiProxy, enabled: boolean): ApiProxy {
|
|
43
|
+
if (!enabled) return api
|
|
44
|
+
|
|
45
|
+
const provisional = new Map<SessionId, ProvisionalEntry>()
|
|
46
|
+
const materializing = new Map<SessionId, ReturnType<ApiProxy['sessions']['create']>>()
|
|
47
|
+
|
|
48
|
+
const prune = (): void => {
|
|
49
|
+
const cutoff = Date.now() - PROVISIONAL_TTL_MS
|
|
50
|
+
for (const [id, entry] of provisional) {
|
|
51
|
+
if (entry.createdAt < cutoff) provisional.delete(id)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const mintedId = (payload: CreateRequest['payload']): SessionId =>
|
|
56
|
+
payload.sessionId ?? `session-${randomUUID()}` as SessionId
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
...api,
|
|
60
|
+
sessions: {
|
|
61
|
+
...api.sessions,
|
|
62
|
+
async create(request: CreateRequest) {
|
|
63
|
+
prune()
|
|
64
|
+
const sessionId = mintedId(request.payload)
|
|
65
|
+
provisional.set(sessionId, { payload: { ...request.payload }, createdAt: Date.now() })
|
|
66
|
+
return { rpcId: request.rpcId, result: { ok: true, value: { sessionId } } }
|
|
67
|
+
},
|
|
68
|
+
async history(request: HistoryRequest) {
|
|
69
|
+
if (!provisional.has(request.payload.sessionId)) return api.sessions.history(request)
|
|
70
|
+
return { rpcId: request.rpcId, result: { ok: true, value: { events: [], hasMore: false } } }
|
|
71
|
+
},
|
|
72
|
+
async prompt(request: PromptRequest) {
|
|
73
|
+
const entry = provisional.get(request.payload.sessionId)
|
|
74
|
+
if (entry === undefined) return api.sessions.prompt(request)
|
|
75
|
+
const existing = materializing.get(request.payload.sessionId)
|
|
76
|
+
const pending = existing ?? api.sessions.create({
|
|
77
|
+
rpcId: RpcId(randomUUID()),
|
|
78
|
+
payload: { ...entry.payload, sessionId: request.payload.sessionId },
|
|
79
|
+
})
|
|
80
|
+
if (existing === undefined) {
|
|
81
|
+
materializing.set(request.payload.sessionId, pending)
|
|
82
|
+
void pending.then(
|
|
83
|
+
() => { materializing.delete(request.payload.sessionId) },
|
|
84
|
+
() => { materializing.delete(request.payload.sessionId) },
|
|
85
|
+
)
|
|
86
|
+
}
|
|
87
|
+
const created = await pending
|
|
88
|
+
if (!created.result.ok) {
|
|
89
|
+
// The create failure value shape differs from prompt's success
|
|
90
|
+
// shape; the carrier relays only result.ok/error, so the value
|
|
91
|
+
// side is irrelevant here.
|
|
92
|
+
return created as unknown as Awaited<ReturnType<ApiProxy['sessions']['prompt']>>
|
|
93
|
+
}
|
|
94
|
+
provisional.delete(request.payload.sessionId)
|
|
95
|
+
return api.sessions.prompt(request)
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Best-effort workspace grouping for sessions created through the browser
|
|
3
|
+
* bridge. The wrapper changes only implicit `session.create` requests;
|
|
4
|
+
* explicit workspace choices and every other gateway method pass through.
|
|
5
|
+
* @module @deepseek-ai/dsh-bridge-browser/src/session-workspace
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
import { mkdir } from 'node:fs/promises'
|
|
10
|
+
import type { ApiProxy, WorkspaceId } from '@deepseek-ai/dsh-host-apiproxy/api'
|
|
11
|
+
import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api'
|
|
12
|
+
|
|
13
|
+
type Warn = (message: string) => void
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Add a dedicated Workspace to implicit session creation without making
|
|
17
|
+
* grouping a session-creation dependency. The first implicit create mkdirs
|
|
18
|
+
* and registers the configured path; that result, including failure, is
|
|
19
|
+
* cached for the wrapper lifetime.
|
|
20
|
+
*
|
|
21
|
+
* @param api - Injected gateway API implementation.
|
|
22
|
+
* @param workspacePath - Dedicated directory, or an empty string to opt out.
|
|
23
|
+
* @param warn - Logger called once when grouping cannot be established.
|
|
24
|
+
* @returns the original API for opt-out, otherwise an API with wrapped session creation.
|
|
25
|
+
*/
|
|
26
|
+
export function withSessionWorkspace(
|
|
27
|
+
api: ApiProxy,
|
|
28
|
+
workspacePath: string,
|
|
29
|
+
warn: Warn,
|
|
30
|
+
): ApiProxy {
|
|
31
|
+
if (workspacePath === '') return api
|
|
32
|
+
|
|
33
|
+
let workspacePromise: Promise<WorkspaceId | undefined> | undefined
|
|
34
|
+
const ensureWorkspace = (): Promise<WorkspaceId | undefined> => {
|
|
35
|
+
if (workspacePromise !== undefined) return workspacePromise
|
|
36
|
+
workspacePromise = (async () => {
|
|
37
|
+
try {
|
|
38
|
+
await mkdir(workspacePath, { recursive: true })
|
|
39
|
+
const workspaceApi = (api as { workspace?: ApiProxy['workspace'] }).workspace
|
|
40
|
+
if (workspaceApi === undefined) {
|
|
41
|
+
warn(`browser bridge: workspace API is unavailable; sessions will remain ungrouped`)
|
|
42
|
+
return undefined
|
|
43
|
+
}
|
|
44
|
+
const response = await workspaceApi.create({
|
|
45
|
+
rpcId: RpcId(randomUUID()),
|
|
46
|
+
payload: { path: workspacePath },
|
|
47
|
+
})
|
|
48
|
+
if (!response.result.ok) {
|
|
49
|
+
warn(
|
|
50
|
+
`browser bridge: workspace.create failed for "${workspacePath}" `
|
|
51
|
+
+ `(${response.result.error.code}: ${response.result.error.message}); sessions will remain ungrouped`,
|
|
52
|
+
)
|
|
53
|
+
return undefined
|
|
54
|
+
}
|
|
55
|
+
return response.result.value.workspace.workspaceId
|
|
56
|
+
} catch (error: unknown) {
|
|
57
|
+
warn(
|
|
58
|
+
`browser bridge: could not prepare session workspace "${workspacePath}": `
|
|
59
|
+
+ `${String(error)}; sessions will remain ungrouped`,
|
|
60
|
+
)
|
|
61
|
+
return undefined
|
|
62
|
+
}
|
|
63
|
+
})()
|
|
64
|
+
return workspacePromise
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
...api,
|
|
69
|
+
sessions: {
|
|
70
|
+
...api.sessions,
|
|
71
|
+
async create(request) {
|
|
72
|
+
if (request.payload.workspaceId !== undefined) return api.sessions.create(request)
|
|
73
|
+
const workspaceId = await ensureWorkspace()
|
|
74
|
+
if (workspaceId === undefined) return api.sessions.create(request)
|
|
75
|
+
const payload = { ...request.payload, workspaceId }
|
|
76
|
+
delete payload.cwd
|
|
77
|
+
return api.sessions.create({ ...request, payload })
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
}
|
|
81
|
+
}
|