dsh-browser-firefox 0.3.3 → 0.4.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/src/server.ts CHANGED
@@ -1,20 +1,20 @@
1
1
  /**
2
- * Bridge WebSocket carrier: token-authenticated connection registry, gateway
3
- * RPC passthrough, per-connection event pump, and tool-call dispatch to the
2
+ * Bridge WebSocket carrier: token-authenticated connection registry, Typert
3
+ * Remote passthrough (unary + streams), and tool-call dispatch to the
4
4
  * connected browser extension.
5
5
  *
6
6
  * The route this server mounts (`/ext/bridge`) lives OUTSIDE the /api trust
7
7
  * fence (which only guards the client-connection routes), so the bridge brings
8
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.
9
+ * HELLO_TIMEOUT_MS. RPC and stream frames speak the alpha Typert dialect
10
+ * verbatim: slash-joined endpoints, native `args` objects, and unmodified
11
+ * follow frames. Methods the bridge pins to loopback (`PRIVILEGED_METHODS`)
12
+ * stay loopback-only here regardless of the token, defense in depth for
13
+ * `--host 0.0.0.0` deployments.
14
14
  *
15
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`).
16
+ * previous one (the old socket is closed, its in-flight tool calls settle as
17
+ * `bridge-closed`, and its streams are aborted).
18
18
  *
19
19
  * @module
20
20
  */
@@ -23,7 +23,6 @@ import { randomUUID } from 'node:crypto'
23
23
  import type { IncomingMessage } from 'node:http'
24
24
  import type { Duplex } from 'node:stream'
25
25
  import { WebSocket, WebSocketServer } from 'ws'
26
- import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
27
26
  import {
28
27
  HELLO_TIMEOUT_MS,
29
28
  PING_INTERVAL_MS,
@@ -31,43 +30,91 @@ import {
31
30
  type BridgeFrame,
32
31
  type BridgeCaps,
33
32
  type ClientFrame,
33
+ type RemoteWireResult,
34
34
  type ToolErrorCode,
35
35
  } from './protocol.ts'
36
36
  import { verifyToken } from './token.ts'
37
37
 
38
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.
39
+ * Gateway endpoints the bridge pins to loopback (the rc line's
40
+ * PRIVILEGED_METHODS, restated against the alpha Remote endpoint names:
41
+ * settings/credentials mutation and host-desktop/filesystem actions). The
42
+ * bridge rejects these for non-loopback remotes even with a valid token.
43
+ * Exported so tests can tripwire the list against accidental shrinkage —
44
+ * when the host line adds new privileged endpoints, extend this set in the
45
+ * same commit.
43
46
  */
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',
47
+ export const PRIVILEGED_METHODS = new Set([
48
+ 'settings/describe',
49
+ 'settings/openSettingsDocument',
50
+ 'settings/openAgentPresetDirectory',
51
+ 'settings/update',
52
+ 'settings/replace',
53
+ 'settings/mutate',
54
+ 'credentials/describe',
55
+ 'credentials/set',
56
+ 'credentials/unset',
57
+ 'directoryPicker/pick',
58
+ 'directoryPicker/createDirectory',
59
+ 'directoryPicker/list',
60
+ 'session/openWorkspacePath',
55
61
  ])
56
62
 
57
63
  /** Session mutations whose WebSocket arrival order is behaviorally significant. */
58
64
  const ORDERED_SESSION_METHODS = new Set([
59
- 'session.prompt',
60
- 'session.cancel',
65
+ 'session/prompt',
66
+ 'session/cancel',
61
67
  ])
62
68
 
69
+ /** Default cap on one incoming WebSocket message (the ws library default of 100MiB is an unauthenticated DoS surface). */
70
+ const DEFAULT_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024
71
+
72
+ /** Default pump backpressure threshold: pause forwarding when the socket buffer grows past this. */
73
+ const DEFAULT_MAX_BUFFERED_BYTES = 4 * 1024 * 1024
74
+
75
+ /** Default grace period for stream pumps during close(); a wedged gateway iterator must not stall teardown forever. */
76
+ const DEFAULT_CLOSE_PUMP_TIMEOUT_MS = 5_000
77
+
78
+ /** Default pong budget: a connection missing this many consecutive ping cycles is terminated as a zombie. */
79
+ const DEFAULT_MISSED_PONGS_ALLOWED = 3
80
+
81
+ /** Poll cadence while a flooded socket drains. */
82
+ const DRAIN_POLL_MS = 50
83
+
84
+ /** Millisecond delay whose timer never keeps the process alive. */
85
+ function delay(ms: number): Promise<void> {
86
+ return new Promise((resolve) => {
87
+ const timer = setTimeout(resolve, ms)
88
+ timer.unref()
89
+ })
90
+ }
91
+
92
+ /**
93
+ * Race one promise against an abort signal. Resolves `undefined` when the
94
+ * signal wins; the loser's handlers are always attached, so a late rejection
95
+ * cannot surface as an unhandled rejection.
96
+ */
97
+ function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
98
+ if (signal.aborted) return Promise.resolve(undefined)
99
+ return new Promise<T | undefined>((resolve, reject) => {
100
+ const onAbort = (): void => { resolve(undefined) }
101
+ signal.addEventListener('abort', onAbort, { once: true })
102
+ promise.then(
103
+ (value) => { signal.removeEventListener('abort', onAbort); resolve(value) },
104
+ (error: unknown) => { signal.removeEventListener('abort', onAbort); reject(error) },
105
+ )
106
+ })
107
+ }
108
+
63
109
  /**
64
110
  * Extract the session id ordering key from an rpc frame, or undefined when
65
111
  * the method does not mutate a specific session (those dispatch freely).
66
112
  */
67
113
  function orderedSessionId(frame: Extract<ClientFrame, { t: 'rpc' }>): string | undefined {
68
114
  if (!ORDERED_SESSION_METHODS.has(frame.method)) return undefined
69
- if (typeof frame.payload !== 'object' || frame.payload === null || Array.isArray(frame.payload)) return undefined
70
- const sessionId = (frame.payload as Record<string, unknown>).sessionId
115
+ const request = frame.args.request
116
+ if (typeof request !== 'object' || request === null || Array.isArray(request)) return undefined
117
+ const sessionId = (request as Record<string, unknown>).sessionId
71
118
  return typeof sessionId === 'string' ? sessionId : undefined
72
119
  }
73
120
 
@@ -91,10 +138,14 @@ export class BridgeToolError extends Error {
91
138
  export interface BridgeServerDeps {
92
139
  /** Bearer token the extension must present in `hello`. */
93
140
  token: string
94
- /** Fetch-shaped gateway carrier (from `toFetchHandler(ctx.apiProxy)`). */
95
- apiHandler: { fetch: (request: Request) => Promise<Response> }
96
- /** Per-connection event stream (usually `ctx.apiProxy.events.mux`). */
97
- openEvents: (signal: AbortSignal) => AsyncIterable<RpcRequest<MuxFrame>>
141
+ /**
142
+ * Unary Remote dispatch (slash endpoint + native args), answering the
143
+ * RemoteResult wire form. Plugin-side interceptors (workspace grouping,
144
+ * session deferral) sit on this seam.
145
+ */
146
+ dispatchRpc: (method: string, args: Record<string, unknown>, signal: AbortSignal) => Promise<RemoteWireResult>
147
+ /** Open one Remote stream (slash endpoint + native args). */
148
+ openStream: (method: string, args: Record<string, unknown>, signal: AbortSignal) => Promise<AsyncIterable<unknown>>
98
149
  /** Default per-tool-call timeout in ms. */
99
150
  toolTimeoutMs: number
100
151
  /** Capabilities to echo in `hello.ok` (negotiated snapshot budgets). */
@@ -109,6 +160,14 @@ export interface BridgeServerDeps {
109
160
  helloTimeoutMs?: number
110
161
  /** Server ping cadence; defaults to PING_INTERVAL_MS. */
111
162
  pingIntervalMs?: number
163
+ /** Cap on one incoming message in bytes; defaults to 4MiB. */
164
+ maxPayloadBytes?: number
165
+ /** Pump backpressure threshold (ws bufferedAmount) in bytes; defaults to 4MiB. */
166
+ maxBufferedBytes?: number
167
+ /** Grace period for stream pumps during close(); defaults to 5000. */
168
+ closePumpTimeoutMs?: number
169
+ /** Consecutive missed ping cycles before a zombie connection is terminated; defaults to 3. */
170
+ missedPongsAllowed?: number
112
171
  }
113
172
 
114
173
  /** One in-flight tool call awaiting the extension's `tool.result`. */
@@ -118,14 +177,23 @@ interface PendingTool {
118
177
  timer: NodeJS.Timeout
119
178
  }
120
179
 
180
+ /** One open Remote stream owned by the current connection. */
181
+ interface OpenStream {
182
+ abort: AbortController
183
+ pump: Promise<void>
184
+ }
185
+
121
186
  /** A socket that passed authentication and owns the single active slot. */
122
187
  interface ReadyConnection {
123
188
  ws: WebSocket
124
189
  /** Remote address captured at upgrade time (loopback gate for privileged methods). */
125
190
  remoteAddress: string | undefined
126
191
  abort: AbortController
127
- pump: Promise<void>
128
192
  ping: NodeJS.Timeout
193
+ /** Last protocol pong timestamp (ms); refreshed by the client's answer to each ping. */
194
+ lastPong: number
195
+ /** Streams opened by this connection, keyed by the client-minted stream id. */
196
+ streams: Map<string, OpenStream>
129
197
  }
130
198
 
131
199
  function sendFrame(ws: WebSocket, frame: BridgeFrame): void {
@@ -153,13 +221,20 @@ export function messageToText(data: Buffer | ArrayBuffer | Buffer[]): string {
153
221
  * dispose with {@link close}.
154
222
  */
155
223
  export class BridgeServer {
156
- private readonly wss = new WebSocketServer({ noServer: true })
224
+ private readonly wss: WebSocketServer
157
225
  private current: ReadyConnection | null = null
158
226
  private readonly pendingTools = new Map<string, PendingTool>()
159
227
  private readonly orderedSessionRpcs = new Map<string, Promise<void>>()
160
228
  private closed = false
161
229
 
162
- constructor(private readonly deps: BridgeServerDeps) {}
230
+ constructor(private readonly deps: BridgeServerDeps) {
231
+ // Cap incoming frames: the default 100MiB ws payload limit lets any
232
+ // socket (pre-auth included) force a full JSON.parse of a huge body.
233
+ this.wss = new WebSocketServer({
234
+ noServer: true,
235
+ maxPayload: this.deps.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES,
236
+ })
237
+ }
163
238
 
164
239
  /**
165
240
  * Handle one HTTP upgrade for the bridge path.
@@ -240,7 +315,7 @@ export class BridgeServer {
240
315
 
241
316
  /**
242
317
  * Terminate the server: close the acceptor, drop all sockets, reject all
243
- * in-flight tool calls.
318
+ * in-flight tool calls, abort all streams.
244
319
  * @returns a promise resolving after the acceptor and all pumps stop.
245
320
  */
246
321
  async close(): Promise<void> {
@@ -248,8 +323,8 @@ export class BridgeServer {
248
323
  // "The server is not running" when closing an already-closed server).
249
324
  if (this.closed) return
250
325
  this.closed = true
251
- // Capture the live pump BEFORE replaceConnection nulls the connection.
252
- const pumps = this.current === null ? [] : [this.current.pump]
326
+ // Capture the live stream pumps BEFORE replaceConnection clears the map.
327
+ const pumps = this.current === null ? [] : [...this.current.streams.values()].map((stream) => stream.pump)
253
328
  this.replaceConnection()
254
329
  for (const socket of this.wss.clients) socket.terminate()
255
330
  this.current = null
@@ -262,7 +337,13 @@ export class BridgeServer {
262
337
  else reject(error)
263
338
  })
264
339
  })
265
- await Promise.all(pumps)
340
+ // Pumps should settle on abort promptly, but a wedged gateway iterator
341
+ // (one that never answers its pending next()) must not stall HMR/unload
342
+ // forever — bound the wait and leave the leak to the host process.
343
+ await Promise.race([
344
+ Promise.allSettled(pumps),
345
+ delay(this.deps.closePumpTimeoutMs ?? DEFAULT_CLOSE_PUMP_TIMEOUT_MS),
346
+ ])
266
347
  }
267
348
 
268
349
  /** @returns whether an authenticated extension is currently connected. */
@@ -325,23 +406,21 @@ export class BridgeServer {
325
406
  private promote(ws: WebSocket, remoteAddress: string | undefined): void {
326
407
  this.replaceConnection()
327
408
  const abort = new AbortController()
328
- const ping = setInterval(() => { sendFrame(ws, { t: 'ping' }) }, this.deps.pingIntervalMs ?? PING_INTERVAL_MS)
329
- const pump = (async () => {
330
- try {
331
- for await (const envelope of this.deps.openEvents(abort.signal)) {
332
- if (ws.readyState !== WebSocket.OPEN) break
333
- sendFrame(ws, {
334
- t: 'event',
335
- frame: { rpcId: envelope.rpcId, method: envelope.payload.type, payload: envelope.payload },
336
- })
337
- }
338
- } catch (error: unknown) {
339
- if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) {
340
- sendFrame(ws, { t: 'error', code: 'stream-failed', message: String(error) })
341
- }
409
+ const intervalMs = this.deps.pingIntervalMs ?? PING_INTERVAL_MS
410
+ const allowed = this.deps.missedPongsAllowed ?? DEFAULT_MISSED_PONGS_ALLOWED
411
+ const conn: ReadyConnection = { ws, remoteAddress, abort, ping: undefined as unknown as NodeJS.Timeout, lastPong: Date.now(), streams: new Map() }
412
+ const ping = setInterval(() => {
413
+ // Zombie guard: a client whose event loop is wedged keeps the TCP
414
+ // socket open but never answers pings; terminate it so a healthy
415
+ // reconnect can take the single active slot.
416
+ if (Date.now() - conn.lastPong > allowed * intervalMs) {
417
+ ws.terminate()
418
+ return
342
419
  }
343
- })()
344
- this.current = { ws, remoteAddress, abort, pump, ping }
420
+ sendFrame(ws, { t: 'ping' })
421
+ }, intervalMs)
422
+ conn.ping = ping
423
+ this.current = conn
345
424
  sendFrame(ws, { t: 'hello.ok', caps: this.deps.caps })
346
425
  ws.once('close', () => {
347
426
  clearInterval(ping)
@@ -354,14 +433,26 @@ export class BridgeServer {
354
433
  case 'rpc':
355
434
  this.routeRpc(frame)
356
435
  break
436
+ case 'stream.open':
437
+ this.openStream(frame)
438
+ break
439
+ case 'stream.close':
440
+ this.closeStream(frame.id)
441
+ break
357
442
  case 'tool.result':
358
443
  this.settleTool(frame.id, frame.ok, frame.ok ? frame.result : frame.error)
359
444
  break
360
- case 'pong':
445
+ case 'pong': {
446
+ // Liveness bookkeeping for the zombie-connection guard in promote().
447
+ const conn = this.current
448
+ if (conn !== null) conn.lastPong = Date.now()
449
+ break
450
+ }
361
451
  case 'hello':
362
452
  case 'hello.ok':
363
453
  case 'rpc.result':
364
- case 'event':
454
+ case 'stream.frame':
455
+ case 'stream.error':
365
456
  case 'tool.call':
366
457
  case 'ping':
367
458
  case 'error':
@@ -394,41 +485,108 @@ export class BridgeServer {
394
485
  void task.then(clear, clear)
395
486
  }
396
487
 
488
+ /** Whether the connection owning this frame may call the endpoint at all. */
489
+ private forbidden(method: string): boolean {
490
+ const conn = this.current
491
+ return conn !== null && PRIVILEGED_METHODS.has(method) && !isLoopbackAddress(conn.remoteAddress)
492
+ }
493
+
397
494
  private async handleRpc(frame: Extract<ClientFrame, { t: 'rpc' }>): Promise<void> {
398
495
  const conn = this.current
399
496
  /* v8 ignore next -- replacement race: a frame can land between a socket
400
497
  replacement and the next promotion; the re-check keeps the handler total */
401
498
  if (conn === null) return
402
- const forbidden = PRIVILEGED_METHODS.has(frame.method) && !isLoopbackAddress(conn.remoteAddress)
403
- if (forbidden) {
499
+ if (this.forbidden(frame.method)) {
404
500
  sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'forbidden', message: 'method is loopback-only' } })
405
501
  return
406
502
  }
407
- const body = JSON.stringify({ type: 'client-request', rpcId: frame.id, method: frame.method, payload: frame.payload })
408
- const request = new Request(new URL(`/api/${frame.method}`, 'http://dsh.internal'), {
409
- method: 'POST',
410
- headers: { 'content-type': 'application/json' },
411
- body,
412
- })
413
503
  try {
414
- const response = await this.deps.apiHandler.fetch(request)
415
- const text = await response.text()
416
- if (!response.ok) {
417
- sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'http', message: text } })
418
- return
504
+ const result = await this.deps.dispatchRpc(frame.method, frame.args, conn.abort.signal)
505
+ if (result.ok) {
506
+ sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, value: result.value })
507
+ } else {
508
+ sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: result.error })
419
509
  }
420
- let result: unknown
421
- try {
422
- result = JSON.parse(text)
423
- } catch {
424
- result = text
425
- }
426
- sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, result })
427
510
  } catch (error: unknown) {
428
511
  sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'internal', message: String(error) } })
429
512
  }
430
513
  }
431
514
 
515
+ /** Open one Remote stream and pump its frames until closed, failed, or replaced. */
516
+ private openStream(frame: Extract<ClientFrame, { t: 'stream.open' }>): void {
517
+ const conn = this.current
518
+ if (conn === null) return
519
+ if (this.forbidden(frame.method)) {
520
+ sendFrame(conn.ws, { t: 'stream.error', id: frame.id, message: 'method is loopback-only' })
521
+ return
522
+ }
523
+ // A repeated stream id replaces the old subscription (protocol violation,
524
+ // but closing beats leaking).
525
+ this.closeStream(frame.id)
526
+ const ws = conn.ws
527
+ const abort = new AbortController()
528
+ conn.abort.signal.addEventListener('abort', () => { abort.abort() }, { once: true })
529
+ let pump!: Promise<void>
530
+ pump = (async () => {
531
+ let iterator: AsyncIterator<unknown> | undefined
532
+ try {
533
+ const iterable = await this.deps.openStream(frame.method, frame.args, abort.signal)
534
+ iterator = iterable[Symbol.asyncIterator]()
535
+ for (;;) {
536
+ // Race every next() against abort: an idle follow stream can sit in
537
+ // next() for hours, and abort-as-advice alone would leave the pump
538
+ // (and close()) hanging until the gateway feels like answering.
539
+ const next = await raceAbort(iterator.next(), abort.signal)
540
+ if (next === undefined || next.done === true) break
541
+ if (ws.readyState !== WebSocket.OPEN) break
542
+ if (!await this.waitForDrain(ws, abort.signal)) break
543
+ sendFrame(ws, { t: 'stream.frame', id: frame.id, frame: next.value })
544
+ }
545
+ } catch (error: unknown) {
546
+ if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) {
547
+ sendFrame(ws, { t: 'stream.error', id: frame.id, message: String(error) })
548
+ }
549
+ } finally {
550
+ // Withdraw the subscription explicitly: for-await's implicit return()
551
+ // never runs when we broke out of the raw-iterator loop above, and a
552
+ // gateway iterator left open keeps the follow registration alive.
553
+ if (iterator !== undefined) {
554
+ try { await iterator.return?.() } catch { /* teardown best effort */ }
555
+ }
556
+ const current = this.current
557
+ if (current !== null && current.streams.get(frame.id)?.pump === pump) {
558
+ current.streams.delete(frame.id)
559
+ }
560
+ }
561
+ })()
562
+ conn.streams.set(frame.id, { abort, pump })
563
+ }
564
+
565
+ /**
566
+ * Backpressure gate for stream pumps. Returns false when the wait ended
567
+ * because the socket died or the pump was aborted (the caller then stops).
568
+ */
569
+ private async waitForDrain(ws: WebSocket, signal: AbortSignal): Promise<boolean> {
570
+ const limit = this.deps.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES
571
+ for (;;) {
572
+ if (signal.aborted || ws.readyState !== WebSocket.OPEN) return false
573
+ if (ws.bufferedAmount <= limit) return true
574
+ // ws exposes no 'drain' event; poll on a short cadence instead.
575
+ const elapsed = await raceAbort(delay(DRAIN_POLL_MS), signal)
576
+ if (elapsed === undefined) return false
577
+ }
578
+ }
579
+
580
+ /** Abort one open stream (client `stream.close`). */
581
+ private closeStream(id: string): void {
582
+ const conn = this.current
583
+ if (conn === null) return
584
+ const stream = conn.streams.get(id)
585
+ if (stream === undefined) return
586
+ conn.streams.delete(id)
587
+ stream.abort.abort()
588
+ }
589
+
432
590
  private settleTool(id: string, ok: boolean, payload: unknown): void {
433
591
  const pending = this.pendingTools.get(id)
434
592
  if (pending === undefined) return
@@ -438,13 +596,15 @@ export class BridgeServer {
438
596
  else pending.reject(new BridgeToolError(payloadCode(payload), payloadMessage(payload)))
439
597
  }
440
598
 
441
- /** Close the current connection (if any) and settle its in-flight calls. */
599
+ /** Close the current connection (if any) and settle its in-flight calls and streams. */
442
600
  private replaceConnection(): void {
443
601
  const conn = this.current
444
602
  if (conn === null) return
445
603
  this.current = null
446
604
  clearInterval(conn.ping)
447
605
  conn.abort.abort()
606
+ for (const stream of conn.streams.values()) stream.abort.abort()
607
+ conn.streams.clear()
448
608
  if (conn.ws.readyState === WebSocket.OPEN || conn.ws.readyState === WebSocket.CONNECTING) {
449
609
  conn.ws.close(4000, 'replaced')
450
610
  }
@@ -1,49 +1,52 @@
1
1
  /**
2
2
  * Defer real session creation until the first prompt.
3
3
  *
4
- * The panel calls `session.create` as soon as it connects, but a session that
4
+ * The panel calls `session/create` as soon as it connects, but a session that
5
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}.
6
+ * interceptor answers `session/create` with a provisional id (minted locally,
7
+ * nothing persisted) and materializes the real session — same id, original
8
+ * create request — on the first `session/prompt` for that id. Abandoned
9
+ * provisional ids are pruned after {@link PROVISIONAL_TTL_MS}.
11
10
  *
12
11
  * @module @deepseek-ai/dsh-bridge-browser/src/session-deferral
13
12
  */
14
13
 
15
14
  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
15
  import type { SessionId } from '@deepseek-ai/dsh-session/types'
16
+ import type { RemoteWireResult } from './protocol.ts'
17
+ import type { RpcDispatch } from './session-workspace.ts'
19
18
 
20
19
  /** Provisional entries older than this are dropped on the next create. */
21
20
  const PROVISIONAL_TTL_MS = 30 * 60_000
22
21
 
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
22
  interface ProvisionalEntry {
28
- /** The original create payload, replayed at materialization (keeps cwd/workspaceId). */
29
- payload: CreateRequest['payload']
23
+ /** The original create request, replayed at materialization (keeps cwd/workspaceId). */
24
+ request: Record<string, unknown>
30
25
  createdAt: number
31
26
  }
32
27
 
28
+ /** Extract the `request` arg object from one dispatch's native args, when present. */
29
+ function requestArg(args: Record<string, unknown>): Record<string, unknown> {
30
+ const request = args.request
31
+ return typeof request === 'object' && request !== null && !Array.isArray(request)
32
+ ? request as Record<string, unknown>
33
+ : {}
34
+ }
35
+
33
36
  /**
34
- * Wrap the gateway sessions API so `session.create` returns a provisional id
37
+ * Intercept the Remote dispatch so `session/create` returns a provisional id
35
38
  * without creating anything; the real session materializes on the first
36
- * `session.prompt` for that id.
39
+ * `session/prompt` for that id.
37
40
  *
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
+ * @param dispatch - Inner Remote dispatch.
42
+ * @param enabled - Whether deferral is active; false returns the dispatch untouched.
43
+ * @returns the original dispatch when disabled, otherwise the intercepting dispatch.
41
44
  */
42
- export function withSessionDeferral(api: ApiProxy, enabled: boolean): ApiProxy {
43
- if (!enabled) return api
45
+ export function withSessionDeferral(dispatch: RpcDispatch, enabled: boolean): RpcDispatch {
46
+ if (!enabled) return dispatch
44
47
 
45
- const provisional = new Map<SessionId, ProvisionalEntry>()
46
- const materializing = new Map<SessionId, ReturnType<ApiProxy['sessions']['create']>>()
48
+ const provisional = new Map<string, ProvisionalEntry>()
49
+ const materializing = new Map<string, Promise<RemoteWireResult>>()
47
50
 
48
51
  const prune = (): void => {
49
52
  const cutoff = Date.now() - PROVISIONAL_TTL_MS
@@ -52,48 +55,40 @@ export function withSessionDeferral(api: ApiProxy, enabled: boolean): ApiProxy {
52
55
  }
53
56
  }
54
57
 
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
- },
58
+ return async (method, args, signal): Promise<RemoteWireResult> => {
59
+ if (method === 'session/create') {
60
+ prune()
61
+ const request = requestArg(args)
62
+ const sessionId = typeof request.sessionId === 'string' ? request.sessionId : `session-${randomUUID()}`
63
+ provisional.set(sessionId, { request: { ...request }, createdAt: Date.now() })
64
+ return { ok: true, value: { sessionId: sessionId as SessionId } }
65
+ }
66
+ if (method === 'session/prompt') {
67
+ // prune 也挂在 prompt 路径:长期没有新建会话时,过期条目同样要清理。
68
+ prune()
69
+ const request = requestArg(args)
70
+ const sessionId = typeof request.sessionId === 'string' ? request.sessionId : undefined
71
+ const entry = sessionId === undefined ? undefined : provisional.get(sessionId)
72
+ if (sessionId === undefined || entry === undefined) return dispatch(method, args, signal)
73
+ const existing = materializing.get(sessionId)
74
+ const pending = existing ?? dispatch('session/create', { request: { ...entry.request, sessionId } }, signal)
75
+ if (existing === undefined) {
76
+ materializing.set(sessionId, pending)
77
+ void pending.then(
78
+ () => { materializing.delete(sessionId) },
79
+ () => { materializing.delete(sessionId) },
80
+ )
81
+ }
82
+ const created = await pending
83
+ if (!created.ok) {
84
+ // Materialization failed: relay the failure as the prompt answer so
85
+ // the extension surfaces the real reason; the provisional entry
86
+ // survives and the next prompt retries.
87
+ return { ok: false, error: created.error }
88
+ }
89
+ provisional.delete(sessionId)
90
+ return dispatch(method, args, signal)
91
+ }
92
+ return dispatch(method, args, signal)
98
93
  }
99
94
  }