dsh-browser-firefox 0.4.0 → 0.4.5
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 +503 -102
- package/lib/protocol.js +19 -2
- package/lib/types/extension-sessions.d.ts +31 -0
- package/lib/types/index.d.ts +10 -2
- package/lib/types/protocol.d.ts +50 -4
- package/lib/types/questions.d.ts +76 -0
- package/lib/types/server.d.ts +40 -1
- package/lib/types/tools.d.ts +20 -6
- package/package.json +6 -3
- package/src/extension-sessions.ts +46 -0
- package/src/index.ts +71 -5
- package/src/protocol.ts +69 -5
- package/src/questions.ts +192 -0
- package/src/server.ts +162 -11
- package/src/session-deferral.ts +2 -0
- package/src/tools.ts +135 -100
package/src/protocol.ts
CHANGED
|
@@ -41,6 +41,8 @@ export type ToolErrorCode =
|
|
|
41
41
|
| 'timeout'
|
|
42
42
|
| 'bridge-closed'
|
|
43
43
|
| 'bad-args'
|
|
44
|
+
| 'approval-denied'
|
|
45
|
+
| 'cancelled'
|
|
44
46
|
| 'internal'
|
|
45
47
|
|
|
46
48
|
/** One tool-call failure: stable machine code plus human text for the model. */
|
|
@@ -49,14 +51,23 @@ export interface ToolError {
|
|
|
49
51
|
message: string
|
|
50
52
|
}
|
|
51
53
|
|
|
52
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* Capabilities negotiated in `hello`/`hello.ok`. The extension performs its
|
|
56
|
+
* own actions; the numeric bounds shape page snapshots. Optional booleans are
|
|
57
|
+
* feature advertisements: a peer that does not know a flag simply leaves it
|
|
58
|
+
* undefined, and the feature stays off for that pairing (graceful
|
|
59
|
+
* cross-version degradation; same-version pairing is still the support
|
|
60
|
+
* contract). Legacy 0.4.x `textOnly` is gone: DeepSeek routes on the 0.1.2
|
|
61
|
+
* line read images natively, so screenshots now cross the bridge as image
|
|
62
|
+
* blocks instead of file paths.
|
|
63
|
+
*/
|
|
53
64
|
export interface BridgeCaps {
|
|
54
|
-
/** The extension renders page state as text only (no screenshots). */
|
|
55
|
-
textOnly: true
|
|
56
65
|
/** Upper bound on one rendered snapshot's characters (plugin config). */
|
|
57
66
|
snapshotMaxChars: number
|
|
58
67
|
/** Upper bound on interactive inventory items per snapshot (plugin config). */
|
|
59
68
|
maxInteractiveItems: number
|
|
69
|
+
/** Client advertises it can render ask_user_question cards; the plugin only claims the user-questions waterfall for extension-owned sessions when set. */
|
|
70
|
+
questions?: boolean
|
|
60
71
|
}
|
|
61
72
|
|
|
62
73
|
/** One Remote failure as plain wire data (RemoteError's message is non-enumerable, so it is restated explicitly). */
|
|
@@ -71,6 +82,25 @@ export type RemoteWireResult =
|
|
|
71
82
|
| { ok: true; value: unknown }
|
|
72
83
|
| { ok: false; error: RemoteWireFailure }
|
|
73
84
|
|
|
85
|
+
/** One ask_user_question option (the host AskUserQuestionOption wire form). */
|
|
86
|
+
export interface QuestionOption {
|
|
87
|
+
label: string
|
|
88
|
+
description?: string
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One ask_user_question item as it crosses the bridge (the host
|
|
93
|
+
* AskUserQuestionItem wire form, minus the host-internal `intent`).
|
|
94
|
+
*/
|
|
95
|
+
export interface QuestionItem {
|
|
96
|
+
id: string
|
|
97
|
+
question: string
|
|
98
|
+
detail?: string
|
|
99
|
+
header?: string
|
|
100
|
+
options?: QuestionOption[]
|
|
101
|
+
multiSelect?: boolean
|
|
102
|
+
}
|
|
103
|
+
|
|
74
104
|
/** Frames sent by the extension to the bridge plugin. */
|
|
75
105
|
export type ClientFrame =
|
|
76
106
|
/** First frame, within HELLO_TIMEOUT_MS of socket open. */
|
|
@@ -102,6 +132,17 @@ export type ServerFrame =
|
|
|
102
132
|
| { t: 'tool.call'; id: string; name: string; args: Record<string, unknown>; expiresAt?: number; sessionId?: string; title?: string }
|
|
103
133
|
/** Withdraw a tool call that timed out or whose caller was cancelled. */
|
|
104
134
|
| { t: 'tool.cancel'; id: string }
|
|
135
|
+
/**
|
|
136
|
+
* The host asked the user (ask_user_question) in an extension-owned session
|
|
137
|
+
* and the bridge claimed the waterfall: the extension should render a
|
|
138
|
+
* question card. The answer rides a normal `rpc` frame with the
|
|
139
|
+
* plugin-local method `bridge/questionAnswer` (args `{questionId, sessionId,
|
|
140
|
+
* answer?} | {questionId, sessionId, decline: true}`), answered
|
|
141
|
+
* `{accepted: true} | {accepted: false, reason: 'not-pending'}`.
|
|
142
|
+
*/
|
|
143
|
+
| { t: 'question.requested'; id: string; sessionId: string; questions: QuestionItem[] }
|
|
144
|
+
/** A previously pushed question is gone (host aborted it or the bridge delegated the waterfall elsewhere); dismiss the card without answering. */
|
|
145
|
+
| { t: 'question.resolved'; id: string; sessionId: string }
|
|
105
146
|
/** Liveness probe. */
|
|
106
147
|
| { t: 'ping' }
|
|
107
148
|
/** Fatal connection error; the client should re-authenticate. */
|
|
@@ -124,6 +165,8 @@ export function isServerFrame(frame: BridgeFrame): frame is ServerFrame {
|
|
|
124
165
|
|| frame.t === 'stream.error'
|
|
125
166
|
|| frame.t === 'tool.call'
|
|
126
167
|
|| frame.t === 'tool.cancel'
|
|
168
|
+
|| frame.t === 'question.requested'
|
|
169
|
+
|| frame.t === 'question.resolved'
|
|
127
170
|
|| frame.t === 'ping'
|
|
128
171
|
|| frame.t === 'error'
|
|
129
172
|
}
|
|
@@ -227,6 +270,18 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
227
270
|
}
|
|
228
271
|
case 'tool.cancel':
|
|
229
272
|
return typeof frame.id === 'string' ? { t: 'tool.cancel', id: frame.id } : undefined
|
|
273
|
+
case 'question.requested':
|
|
274
|
+
return typeof frame.id === 'string'
|
|
275
|
+
&& typeof frame.sessionId === 'string'
|
|
276
|
+
&& Array.isArray(frame.questions)
|
|
277
|
+
&& frame.questions.length > 0
|
|
278
|
+
&& frame.questions.every(isQuestionItem)
|
|
279
|
+
? { t: 'question.requested', id: frame.id, sessionId: frame.sessionId, questions: frame.questions }
|
|
280
|
+
: undefined
|
|
281
|
+
case 'question.resolved':
|
|
282
|
+
return typeof frame.id === 'string' && typeof frame.sessionId === 'string'
|
|
283
|
+
? { t: 'question.resolved', id: frame.id, sessionId: frame.sessionId }
|
|
284
|
+
: undefined
|
|
230
285
|
case 'ping':
|
|
231
286
|
return { t: 'ping' }
|
|
232
287
|
case 'error':
|
|
@@ -241,9 +296,18 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
241
296
|
function isCaps(value: unknown): value is BridgeCaps {
|
|
242
297
|
if (typeof value !== 'object' || value === null) return false
|
|
243
298
|
const caps = value as Record<string, unknown>
|
|
244
|
-
|
|
245
|
-
|
|
299
|
+
// Unknown keys (legacy `textOnly`, future flags) are tolerated: each side
|
|
300
|
+
// only acts on the flags it understands.
|
|
301
|
+
return typeof caps.snapshotMaxChars === 'number' && caps.snapshotMaxChars > 0
|
|
246
302
|
&& typeof caps.maxInteractiveItems === 'number' && caps.maxInteractiveItems > 0
|
|
303
|
+
&& (caps.questions === undefined || typeof caps.questions === 'boolean')
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Narrow one question item; unknown extra keys (e.g. host `intent`) pass through. */
|
|
307
|
+
function isQuestionItem(value: unknown): value is QuestionItem {
|
|
308
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
309
|
+
const item = value as Record<string, unknown>
|
|
310
|
+
return typeof item.id === 'string' && typeof item.question === 'string'
|
|
247
311
|
}
|
|
248
312
|
|
|
249
313
|
function isToolError(value: unknown): value is ToolError {
|
package/src/questions.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ask_user_question ownership: claim the host `user-questions/request`
|
|
3
|
+
* waterfall for extension-owned sessions, push the question to the connected
|
|
4
|
+
* extension, and settle the waterfall with the sidebar's answer.
|
|
5
|
+
*
|
|
6
|
+
* Settlement races (first wins, later ones see `settled` and no-op):
|
|
7
|
+
* - the extension answers ({@link answer}) → waterfall resolves;
|
|
8
|
+
* - the extension declines → waterfall rejects (the tool call fails, the
|
|
9
|
+
* model is told the user refused);
|
|
10
|
+
* - the host aborts `request.signal` (turn cancelled, session disposed) →
|
|
11
|
+
* the extension is sent `question.resolved` and the waterfall rejects;
|
|
12
|
+
* - the bridge connection drops ({@link delegateAll}) → the waterfall is
|
|
13
|
+
* delegated to `next()` so another answerer (dsh web) can still serve it;
|
|
14
|
+
* - plugin unload ({@link dispose}) → everything rejects promptly.
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { randomUUID } from 'node:crypto'
|
|
20
|
+
import type { QuestionItem, ServerFrame } from './protocol.ts'
|
|
21
|
+
|
|
22
|
+
/** One answer item, mirroring the host AskUserQuestionAnswerItem wire form. */
|
|
23
|
+
export interface QuestionAnswerItem {
|
|
24
|
+
id: string
|
|
25
|
+
selected: string[]
|
|
26
|
+
custom?: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The extension's answer payload, mirroring the host AskUserQuestionAnswer. */
|
|
30
|
+
export interface QuestionAnswerPayload {
|
|
31
|
+
answers: QuestionAnswerItem[]
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Receipt answered to the extension's `bridge/questionAnswer` rpc. */
|
|
35
|
+
export type QuestionAnswerReceipt =
|
|
36
|
+
| { accepted: true }
|
|
37
|
+
| { accepted: false; reason: 'not-pending' | 'bad-answer' }
|
|
38
|
+
|
|
39
|
+
/** Args of the plugin-local `bridge/questionAnswer` rpc method. */
|
|
40
|
+
export interface QuestionAnswerArgs {
|
|
41
|
+
questionId: string
|
|
42
|
+
sessionId: string
|
|
43
|
+
answer?: unknown
|
|
44
|
+
decline?: boolean
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type PendingOutcome =
|
|
48
|
+
| { kind: 'answer'; answer: QuestionAnswerPayload }
|
|
49
|
+
| { kind: 'reject'; error: Error }
|
|
50
|
+
| { kind: 'delegate' }
|
|
51
|
+
|
|
52
|
+
interface PendingQuestion {
|
|
53
|
+
readonly sessionId: string
|
|
54
|
+
readonly questionIds: ReadonlySet<string>
|
|
55
|
+
settled: boolean
|
|
56
|
+
readonly complete: (outcome: PendingOutcome) => void
|
|
57
|
+
readonly signal: AbortSignal | undefined
|
|
58
|
+
onAbort: (() => void) | undefined
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Error matching the host's ASK_ABORTED semantics (the service remaps it). */
|
|
62
|
+
function abortedError(): Error {
|
|
63
|
+
return new Error('ask_user_question was aborted before the user answered')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function declinedError(): Error {
|
|
67
|
+
return new Error('ask_user_question was declined by the user in the browser sidebar')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Structural validation of the extension's answer payload. */
|
|
71
|
+
export function asAnswerPayload(value: unknown, questionIds: ReadonlySet<string>): QuestionAnswerPayload | undefined {
|
|
72
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
|
|
73
|
+
const answers = (value as { answers?: unknown }).answers
|
|
74
|
+
if (!Array.isArray(answers)) return undefined
|
|
75
|
+
const items: QuestionAnswerItem[] = []
|
|
76
|
+
for (const entry of answers) {
|
|
77
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return undefined
|
|
78
|
+
const item = entry as Record<string, unknown>
|
|
79
|
+
if (typeof item.id !== 'string' || !questionIds.has(item.id)) return undefined
|
|
80
|
+
if (!Array.isArray(item.selected) || item.selected.some(option => typeof option !== 'string')) return undefined
|
|
81
|
+
if (item.custom !== undefined && typeof item.custom !== 'string') return undefined
|
|
82
|
+
items.push({
|
|
83
|
+
id: item.id,
|
|
84
|
+
selected: item.selected as string[],
|
|
85
|
+
...(typeof item.custom === 'string' ? { custom: item.custom } : {}),
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
return { answers: items }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Parse the extension's `bridge/questionAnswer` rpc args (light: ids only). */
|
|
92
|
+
export function asQuestionAnswerArgs(value: unknown): QuestionAnswerArgs | undefined {
|
|
93
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
|
|
94
|
+
const args = value as Record<string, unknown>
|
|
95
|
+
return typeof args.questionId === 'string' && typeof args.sessionId === 'string'
|
|
96
|
+
? value as QuestionAnswerArgs
|
|
97
|
+
: undefined
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Owns the user-questions waterfall for extension-driven sessions. */
|
|
101
|
+
export class QuestionBridge {
|
|
102
|
+
private readonly pending = new Map<string, PendingQuestion>()
|
|
103
|
+
|
|
104
|
+
constructor(private readonly deps: {
|
|
105
|
+
/** Push one server frame to the connected extension (must tolerate a dead socket). */
|
|
106
|
+
push: (frame: ServerFrame) => void
|
|
107
|
+
}) {}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Own one host waterfall request: push `question.requested` to the
|
|
111
|
+
* extension and suspend until one of the settlement races wins.
|
|
112
|
+
*
|
|
113
|
+
* @param sessionId - asking session (already ownership-checked by the caller).
|
|
114
|
+
* @param questions - host question items (forwarded verbatim).
|
|
115
|
+
* @param next - waterfall delegation, used when the bridge connection drops.
|
|
116
|
+
* @param signal - host cancellation lifetime for this request.
|
|
117
|
+
* @returns the user's answer.
|
|
118
|
+
*/
|
|
119
|
+
ask(
|
|
120
|
+
sessionId: string,
|
|
121
|
+
questions: QuestionItem[],
|
|
122
|
+
next: () => Promise<QuestionAnswerPayload>,
|
|
123
|
+
signal?: AbortSignal,
|
|
124
|
+
): Promise<QuestionAnswerPayload> {
|
|
125
|
+
if (signal?.aborted) return Promise.reject(abortedError())
|
|
126
|
+
const questionId = randomUUID()
|
|
127
|
+
return new Promise<QuestionAnswerPayload>((resolve, reject) => {
|
|
128
|
+
const entry: PendingQuestion = {
|
|
129
|
+
sessionId,
|
|
130
|
+
questionIds: new Set(questions.map(question => question.id)),
|
|
131
|
+
settled: false,
|
|
132
|
+
signal,
|
|
133
|
+
complete: (outcome) => {
|
|
134
|
+
if (entry.settled) return
|
|
135
|
+
entry.settled = true
|
|
136
|
+
this.pending.delete(questionId)
|
|
137
|
+
if (entry.onAbort !== undefined) entry.signal?.removeEventListener('abort', entry.onAbort)
|
|
138
|
+
if (outcome.kind === 'answer') resolve(outcome.answer)
|
|
139
|
+
else if (outcome.kind === 'reject') reject(outcome.error)
|
|
140
|
+
else next().then(resolve, reject)
|
|
141
|
+
},
|
|
142
|
+
onAbort: undefined,
|
|
143
|
+
}
|
|
144
|
+
if (signal !== undefined) {
|
|
145
|
+
entry.onAbort = () => {
|
|
146
|
+
// Tell the extension to drop the card before settling so a late
|
|
147
|
+
// answer can never report acceptance for a dead request.
|
|
148
|
+
this.deps.push({ t: 'question.resolved', id: questionId, sessionId })
|
|
149
|
+
entry.complete({ kind: 'reject', error: abortedError() })
|
|
150
|
+
}
|
|
151
|
+
signal.addEventListener('abort', entry.onAbort, { once: true })
|
|
152
|
+
}
|
|
153
|
+
this.pending.set(questionId, entry)
|
|
154
|
+
this.deps.push({ t: 'question.requested', id: questionId, sessionId, questions })
|
|
155
|
+
})
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Settle one pending question from the extension's `bridge/questionAnswer`
|
|
160
|
+
* rpc. The server replies with this receipt.
|
|
161
|
+
*/
|
|
162
|
+
answer(args: QuestionAnswerArgs): QuestionAnswerReceipt {
|
|
163
|
+
const entry = this.pending.get(args.questionId)
|
|
164
|
+
if (entry === undefined || entry.settled || entry.sessionId !== args.sessionId) {
|
|
165
|
+
return { accepted: false, reason: 'not-pending' }
|
|
166
|
+
}
|
|
167
|
+
if (args.decline === true) {
|
|
168
|
+
entry.complete({ kind: 'reject', error: declinedError() })
|
|
169
|
+
return { accepted: true }
|
|
170
|
+
}
|
|
171
|
+
const answer = asAnswerPayload(args.answer, entry.questionIds)
|
|
172
|
+
if (answer === undefined) return { accepted: false, reason: 'bad-answer' }
|
|
173
|
+
entry.complete({ kind: 'answer', answer })
|
|
174
|
+
return { accepted: true }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Bridge connection replaced/closed: delegate every unsettled question. */
|
|
178
|
+
delegateAll(): void {
|
|
179
|
+
for (const entry of [...this.pending.values()]) {
|
|
180
|
+
if (!entry.settled) entry.complete({ kind: 'delegate' })
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Plugin unload: reject everything so no tool call outlives the plugin. */
|
|
185
|
+
dispose(): void {
|
|
186
|
+
for (const entry of [...this.pending.values()]) {
|
|
187
|
+
if (!entry.settled) {
|
|
188
|
+
entry.complete({ kind: 'reject', error: new Error('browser bridge plugin was unloaded') })
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
package/src/server.ts
CHANGED
|
@@ -31,6 +31,7 @@ import {
|
|
|
31
31
|
type BridgeCaps,
|
|
32
32
|
type ClientFrame,
|
|
33
33
|
type RemoteWireResult,
|
|
34
|
+
type ServerFrame,
|
|
34
35
|
type ToolErrorCode,
|
|
35
36
|
} from './protocol.ts'
|
|
36
37
|
import { verifyToken } from './token.ts'
|
|
@@ -40,8 +41,11 @@ import { verifyToken } from './token.ts'
|
|
|
40
41
|
* PRIVILEGED_METHODS, restated against the alpha Remote endpoint names:
|
|
41
42
|
* settings/credentials mutation and host-desktop/filesystem actions). The
|
|
42
43
|
* bridge rejects these for non-loopback remotes even with a valid token.
|
|
44
|
+
* Exported so tests can tripwire the list against accidental shrinkage —
|
|
45
|
+
* when the host line adds new privileged endpoints, extend this set in the
|
|
46
|
+
* same commit.
|
|
43
47
|
*/
|
|
44
|
-
const PRIVILEGED_METHODS = new Set([
|
|
48
|
+
export const PRIVILEGED_METHODS = new Set([
|
|
45
49
|
'settings/describe',
|
|
46
50
|
'settings/openSettingsDocument',
|
|
47
51
|
'settings/openAgentPresetDirectory',
|
|
@@ -63,6 +67,46 @@ const ORDERED_SESSION_METHODS = new Set([
|
|
|
63
67
|
'session/cancel',
|
|
64
68
|
])
|
|
65
69
|
|
|
70
|
+
/** Default cap on one incoming WebSocket message (the ws library default of 100MiB is an unauthenticated DoS surface). 32MiB leaves room for base64 screenshots and image-carrying prompts, which routinely exceed 4MiB. */
|
|
71
|
+
const DEFAULT_MAX_PAYLOAD_BYTES = 32 * 1024 * 1024
|
|
72
|
+
|
|
73
|
+
/** Default pump backpressure threshold: pause forwarding when the socket buffer grows past this. */
|
|
74
|
+
const DEFAULT_MAX_BUFFERED_BYTES = 4 * 1024 * 1024
|
|
75
|
+
|
|
76
|
+
/** Default grace period for stream pumps during close(); a wedged gateway iterator must not stall teardown forever. */
|
|
77
|
+
const DEFAULT_CLOSE_PUMP_TIMEOUT_MS = 5_000
|
|
78
|
+
|
|
79
|
+
/** Default pong budget: a connection missing this many consecutive ping cycles is terminated as a zombie. */
|
|
80
|
+
const DEFAULT_MISSED_PONGS_ALLOWED = 3
|
|
81
|
+
|
|
82
|
+
/** Poll cadence while a flooded socket drains. */
|
|
83
|
+
const DRAIN_POLL_MS = 50
|
|
84
|
+
|
|
85
|
+
/** Millisecond delay whose timer never keeps the process alive. */
|
|
86
|
+
function delay(ms: number): Promise<void> {
|
|
87
|
+
return new Promise((resolve) => {
|
|
88
|
+
const timer = setTimeout(resolve, ms)
|
|
89
|
+
timer.unref()
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Race one promise against an abort signal. Resolves `undefined` when the
|
|
95
|
+
* signal wins; the loser's handlers are always attached, so a late rejection
|
|
96
|
+
* cannot surface as an unhandled rejection.
|
|
97
|
+
*/
|
|
98
|
+
function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
|
|
99
|
+
if (signal.aborted) return Promise.resolve(undefined)
|
|
100
|
+
return new Promise<T | undefined>((resolve, reject) => {
|
|
101
|
+
const onAbort = (): void => { resolve(undefined) }
|
|
102
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
103
|
+
promise.then(
|
|
104
|
+
(value) => { signal.removeEventListener('abort', onAbort); resolve(value) },
|
|
105
|
+
(error: unknown) => { signal.removeEventListener('abort', onAbort); reject(error) },
|
|
106
|
+
)
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
|
|
66
110
|
/**
|
|
67
111
|
* Extract the session id ordering key from an rpc frame, or undefined when
|
|
68
112
|
* the method does not mutate a specific session (those dispatch freely).
|
|
@@ -107,6 +151,14 @@ export interface BridgeServerDeps {
|
|
|
107
151
|
toolTimeoutMs: number
|
|
108
152
|
/** Capabilities to echo in `hello.ok` (negotiated snapshot budgets). */
|
|
109
153
|
caps: BridgeCaps
|
|
154
|
+
/**
|
|
155
|
+
* Plugin-local endpoint `bridge/questionAnswer`: settle one pending
|
|
156
|
+
* ask_user_question the bridge pushed to this extension. Answered as the
|
|
157
|
+
* rpc result value `{accepted: true} | {accepted: false, reason}`.
|
|
158
|
+
*/
|
|
159
|
+
answerQuestion: (args: Record<string, unknown>) => unknown
|
|
160
|
+
/** The active connection was replaced or closed (settle pushed questions). */
|
|
161
|
+
onConnectionLost?: () => void
|
|
110
162
|
/**
|
|
111
163
|
* Test seam: force the remote address seen by the privilege gate. The
|
|
112
164
|
* sandbox cannot bind arbitrary loopback literals, so the non-loopback
|
|
@@ -117,6 +169,14 @@ export interface BridgeServerDeps {
|
|
|
117
169
|
helloTimeoutMs?: number
|
|
118
170
|
/** Server ping cadence; defaults to PING_INTERVAL_MS. */
|
|
119
171
|
pingIntervalMs?: number
|
|
172
|
+
/** Cap on one incoming message in bytes; defaults to 4MiB. */
|
|
173
|
+
maxPayloadBytes?: number
|
|
174
|
+
/** Pump backpressure threshold (ws bufferedAmount) in bytes; defaults to 4MiB. */
|
|
175
|
+
maxBufferedBytes?: number
|
|
176
|
+
/** Grace period for stream pumps during close(); defaults to 5000. */
|
|
177
|
+
closePumpTimeoutMs?: number
|
|
178
|
+
/** Consecutive missed ping cycles before a zombie connection is terminated; defaults to 3. */
|
|
179
|
+
missedPongsAllowed?: number
|
|
120
180
|
}
|
|
121
181
|
|
|
122
182
|
/** One in-flight tool call awaiting the extension's `tool.result`. */
|
|
@@ -137,8 +197,12 @@ interface ReadyConnection {
|
|
|
137
197
|
ws: WebSocket
|
|
138
198
|
/** Remote address captured at upgrade time (loopback gate for privileged methods). */
|
|
139
199
|
remoteAddress: string | undefined
|
|
200
|
+
/** Capabilities the client presented in `hello` (feature advertisements). */
|
|
201
|
+
clientCaps: BridgeCaps
|
|
140
202
|
abort: AbortController
|
|
141
203
|
ping: NodeJS.Timeout
|
|
204
|
+
/** Last protocol pong timestamp (ms); refreshed by the client's answer to each ping. */
|
|
205
|
+
lastPong: number
|
|
142
206
|
/** Streams opened by this connection, keyed by the client-minted stream id. */
|
|
143
207
|
streams: Map<string, OpenStream>
|
|
144
208
|
}
|
|
@@ -168,13 +232,20 @@ export function messageToText(data: Buffer | ArrayBuffer | Buffer[]): string {
|
|
|
168
232
|
* dispose with {@link close}.
|
|
169
233
|
*/
|
|
170
234
|
export class BridgeServer {
|
|
171
|
-
private readonly wss
|
|
235
|
+
private readonly wss: WebSocketServer
|
|
172
236
|
private current: ReadyConnection | null = null
|
|
173
237
|
private readonly pendingTools = new Map<string, PendingTool>()
|
|
174
238
|
private readonly orderedSessionRpcs = new Map<string, Promise<void>>()
|
|
175
239
|
private closed = false
|
|
176
240
|
|
|
177
|
-
constructor(private readonly deps: BridgeServerDeps) {
|
|
241
|
+
constructor(private readonly deps: BridgeServerDeps) {
|
|
242
|
+
// Cap incoming frames: the default 100MiB ws payload limit lets any
|
|
243
|
+
// socket (pre-auth included) force a full JSON.parse of a huge body.
|
|
244
|
+
this.wss = new WebSocketServer({
|
|
245
|
+
noServer: true,
|
|
246
|
+
maxPayload: this.deps.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES,
|
|
247
|
+
})
|
|
248
|
+
}
|
|
178
249
|
|
|
179
250
|
/**
|
|
180
251
|
* Handle one HTTP upgrade for the bridge path.
|
|
@@ -277,7 +348,13 @@ export class BridgeServer {
|
|
|
277
348
|
else reject(error)
|
|
278
349
|
})
|
|
279
350
|
})
|
|
280
|
-
|
|
351
|
+
// Pumps should settle on abort promptly, but a wedged gateway iterator
|
|
352
|
+
// (one that never answers its pending next()) must not stall HMR/unload
|
|
353
|
+
// forever — bound the wait and leave the leak to the host process.
|
|
354
|
+
await Promise.race([
|
|
355
|
+
Promise.allSettled(pumps),
|
|
356
|
+
delay(this.deps.closePumpTimeoutMs ?? DEFAULT_CLOSE_PUMP_TIMEOUT_MS),
|
|
357
|
+
])
|
|
281
358
|
}
|
|
282
359
|
|
|
283
360
|
/** @returns whether an authenticated extension is currently connected. */
|
|
@@ -285,6 +362,22 @@ export class BridgeServer {
|
|
|
285
362
|
return this.current !== null
|
|
286
363
|
}
|
|
287
364
|
|
|
365
|
+
/** @returns whether the connected extension advertised question-card support. */
|
|
366
|
+
clientSupportsQuestions(): boolean {
|
|
367
|
+
return this.current?.clientCaps.questions === true
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Push one unsolicited server frame (question.requested/question.resolved)
|
|
372
|
+
* to the connected extension. No-op when no extension is connected or the
|
|
373
|
+
* socket is already dead.
|
|
374
|
+
*/
|
|
375
|
+
push(frame: ServerFrame): void {
|
|
376
|
+
const conn = this.current
|
|
377
|
+
if (conn === null) return
|
|
378
|
+
sendFrame(conn.ws, frame)
|
|
379
|
+
}
|
|
380
|
+
|
|
288
381
|
private attach(ws: WebSocket, remoteAddress: string | undefined, origin: string | undefined): void {
|
|
289
382
|
let helloTimer: NodeJS.Timeout | undefined = setTimeout(() => {
|
|
290
383
|
ws.close(4001, 'hello timeout')
|
|
@@ -322,7 +415,7 @@ export class BridgeServer {
|
|
|
322
415
|
}
|
|
323
416
|
clearTimeout(helloTimer)
|
|
324
417
|
helloTimer = undefined
|
|
325
|
-
this.promote(ws, remoteAddress)
|
|
418
|
+
this.promote(ws, remoteAddress, frame.caps)
|
|
326
419
|
return
|
|
327
420
|
}
|
|
328
421
|
this.handleReadyFrame(frame)
|
|
@@ -337,11 +430,24 @@ export class BridgeServer {
|
|
|
337
430
|
}
|
|
338
431
|
|
|
339
432
|
/** Promote an authenticated socket to the single active slot. */
|
|
340
|
-
private promote(ws: WebSocket, remoteAddress: string | undefined): void {
|
|
433
|
+
private promote(ws: WebSocket, remoteAddress: string | undefined, clientCaps: BridgeCaps): void {
|
|
341
434
|
this.replaceConnection()
|
|
342
435
|
const abort = new AbortController()
|
|
343
|
-
const
|
|
344
|
-
|
|
436
|
+
const intervalMs = this.deps.pingIntervalMs ?? PING_INTERVAL_MS
|
|
437
|
+
const allowed = this.deps.missedPongsAllowed ?? DEFAULT_MISSED_PONGS_ALLOWED
|
|
438
|
+
const conn: ReadyConnection = { ws, remoteAddress, clientCaps, abort, ping: undefined as unknown as NodeJS.Timeout, lastPong: Date.now(), streams: new Map() }
|
|
439
|
+
const ping = setInterval(() => {
|
|
440
|
+
// Zombie guard: a client whose event loop is wedged keeps the TCP
|
|
441
|
+
// socket open but never answers pings; terminate it so a healthy
|
|
442
|
+
// reconnect can take the single active slot.
|
|
443
|
+
if (Date.now() - conn.lastPong > allowed * intervalMs) {
|
|
444
|
+
ws.terminate()
|
|
445
|
+
return
|
|
446
|
+
}
|
|
447
|
+
sendFrame(ws, { t: 'ping' })
|
|
448
|
+
}, intervalMs)
|
|
449
|
+
conn.ping = ping
|
|
450
|
+
this.current = conn
|
|
345
451
|
sendFrame(ws, { t: 'hello.ok', caps: this.deps.caps })
|
|
346
452
|
ws.once('close', () => {
|
|
347
453
|
clearInterval(ping)
|
|
@@ -363,13 +469,20 @@ export class BridgeServer {
|
|
|
363
469
|
case 'tool.result':
|
|
364
470
|
this.settleTool(frame.id, frame.ok, frame.ok ? frame.result : frame.error)
|
|
365
471
|
break
|
|
366
|
-
case 'pong':
|
|
472
|
+
case 'pong': {
|
|
473
|
+
// Liveness bookkeeping for the zombie-connection guard in promote().
|
|
474
|
+
const conn = this.current
|
|
475
|
+
if (conn !== null) conn.lastPong = Date.now()
|
|
476
|
+
break
|
|
477
|
+
}
|
|
367
478
|
case 'hello':
|
|
368
479
|
case 'hello.ok':
|
|
369
480
|
case 'rpc.result':
|
|
370
481
|
case 'stream.frame':
|
|
371
482
|
case 'stream.error':
|
|
372
483
|
case 'tool.call':
|
|
484
|
+
case 'question.requested':
|
|
485
|
+
case 'question.resolved':
|
|
373
486
|
case 'ping':
|
|
374
487
|
case 'error':
|
|
375
488
|
// Protocol violations and unsolicited server-side shapes are ignored;
|
|
@@ -416,6 +529,12 @@ export class BridgeServer {
|
|
|
416
529
|
sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'forbidden', message: 'method is loopback-only' } })
|
|
417
530
|
return
|
|
418
531
|
}
|
|
532
|
+
// Plugin-local endpoint: settle a pending ask_user_question. Intercepted
|
|
533
|
+
// before the Remote passthrough, like the privilege gate above.
|
|
534
|
+
if (frame.method === 'bridge/questionAnswer') {
|
|
535
|
+
sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, value: this.deps.answerQuestion(frame.args) })
|
|
536
|
+
return
|
|
537
|
+
}
|
|
419
538
|
try {
|
|
420
539
|
const result = await this.deps.dispatchRpc(frame.method, frame.args, conn.abort.signal)
|
|
421
540
|
if (result.ok) {
|
|
@@ -444,17 +563,31 @@ export class BridgeServer {
|
|
|
444
563
|
conn.abort.signal.addEventListener('abort', () => { abort.abort() }, { once: true })
|
|
445
564
|
let pump!: Promise<void>
|
|
446
565
|
pump = (async () => {
|
|
566
|
+
let iterator: AsyncIterator<unknown> | undefined
|
|
447
567
|
try {
|
|
448
568
|
const iterable = await this.deps.openStream(frame.method, frame.args, abort.signal)
|
|
449
|
-
|
|
569
|
+
iterator = iterable[Symbol.asyncIterator]()
|
|
570
|
+
for (;;) {
|
|
571
|
+
// Race every next() against abort: an idle follow stream can sit in
|
|
572
|
+
// next() for hours, and abort-as-advice alone would leave the pump
|
|
573
|
+
// (and close()) hanging until the gateway feels like answering.
|
|
574
|
+
const next = await raceAbort(iterator.next(), abort.signal)
|
|
575
|
+
if (next === undefined || next.done === true) break
|
|
450
576
|
if (ws.readyState !== WebSocket.OPEN) break
|
|
451
|
-
|
|
577
|
+
if (!await this.waitForDrain(ws, abort.signal)) break
|
|
578
|
+
sendFrame(ws, { t: 'stream.frame', id: frame.id, frame: next.value })
|
|
452
579
|
}
|
|
453
580
|
} catch (error: unknown) {
|
|
454
581
|
if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) {
|
|
455
582
|
sendFrame(ws, { t: 'stream.error', id: frame.id, message: String(error) })
|
|
456
583
|
}
|
|
457
584
|
} finally {
|
|
585
|
+
// Withdraw the subscription explicitly: for-await's implicit return()
|
|
586
|
+
// never runs when we broke out of the raw-iterator loop above, and a
|
|
587
|
+
// gateway iterator left open keeps the follow registration alive.
|
|
588
|
+
if (iterator !== undefined) {
|
|
589
|
+
try { await iterator.return?.() } catch { /* teardown best effort */ }
|
|
590
|
+
}
|
|
458
591
|
const current = this.current
|
|
459
592
|
if (current !== null && current.streams.get(frame.id)?.pump === pump) {
|
|
460
593
|
current.streams.delete(frame.id)
|
|
@@ -464,6 +597,21 @@ export class BridgeServer {
|
|
|
464
597
|
conn.streams.set(frame.id, { abort, pump })
|
|
465
598
|
}
|
|
466
599
|
|
|
600
|
+
/**
|
|
601
|
+
* Backpressure gate for stream pumps. Returns false when the wait ended
|
|
602
|
+
* because the socket died or the pump was aborted (the caller then stops).
|
|
603
|
+
*/
|
|
604
|
+
private async waitForDrain(ws: WebSocket, signal: AbortSignal): Promise<boolean> {
|
|
605
|
+
const limit = this.deps.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES
|
|
606
|
+
for (;;) {
|
|
607
|
+
if (signal.aborted || ws.readyState !== WebSocket.OPEN) return false
|
|
608
|
+
if (ws.bufferedAmount <= limit) return true
|
|
609
|
+
// ws exposes no 'drain' event; poll on a short cadence instead.
|
|
610
|
+
const elapsed = await raceAbort(delay(DRAIN_POLL_MS), signal)
|
|
611
|
+
if (elapsed === undefined) return false
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
467
615
|
/** Abort one open stream (client `stream.close`). */
|
|
468
616
|
private closeStream(id: string): void {
|
|
469
617
|
const conn = this.current
|
|
@@ -500,6 +648,9 @@ export class BridgeServer {
|
|
|
500
648
|
this.pendingTools.delete(id)
|
|
501
649
|
pending.reject(new BridgeToolError('bridge-closed', 'the extension connection was replaced'))
|
|
502
650
|
}
|
|
651
|
+
// Questions pushed to the old connection can never be answered now; the
|
|
652
|
+
// owner delegates their waterfalls to the next answerer.
|
|
653
|
+
this.deps.onConnectionLost?.()
|
|
503
654
|
}
|
|
504
655
|
}
|
|
505
656
|
|
package/src/session-deferral.ts
CHANGED
|
@@ -64,6 +64,8 @@ export function withSessionDeferral(dispatch: RpcDispatch, enabled: boolean): Rp
|
|
|
64
64
|
return { ok: true, value: { sessionId: sessionId as SessionId } }
|
|
65
65
|
}
|
|
66
66
|
if (method === 'session/prompt') {
|
|
67
|
+
// prune 也挂在 prompt 路径:长期没有新建会话时,过期条目同样要清理。
|
|
68
|
+
prune()
|
|
67
69
|
const request = requestArg(args)
|
|
68
70
|
const sessionId = typeof request.sessionId === 'string' ? request.sessionId : undefined
|
|
69
71
|
const entry = sessionId === undefined ? undefined : provisional.get(sessionId)
|