dsh-browser-firefox 0.4.1 → 0.4.6
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 +371 -91
- package/lib/protocol.js +36 -11
- package/lib/types/extension-sessions.d.ts +31 -0
- package/lib/types/index.d.ts +10 -2
- package/lib/types/protocol.d.ts +53 -5
- package/lib/types/questions.d.ts +76 -0
- package/lib/types/server.d.ts +21 -1
- package/lib/types/tools.d.ts +19 -5
- package/package.json +6 -3
- package/src/extension-sessions.ts +46 -0
- package/src/index.ts +86 -5
- package/src/protocol.ts +86 -16
- package/src/questions.ts +192 -0
- package/src/server.ts +55 -6
- package/src/tools.ts +85 -99
package/src/protocol.ts
CHANGED
|
@@ -51,14 +51,23 @@ export interface ToolError {
|
|
|
51
51
|
message: string
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
/**
|
|
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
|
+
*/
|
|
55
64
|
export interface BridgeCaps {
|
|
56
|
-
/** The extension renders page state as text only (no screenshots). */
|
|
57
|
-
textOnly: true
|
|
58
65
|
/** Upper bound on one rendered snapshot's characters (plugin config). */
|
|
59
66
|
snapshotMaxChars: number
|
|
60
67
|
/** Upper bound on interactive inventory items per snapshot (plugin config). */
|
|
61
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
|
|
62
71
|
}
|
|
63
72
|
|
|
64
73
|
/** One Remote failure as plain wire data (RemoteError's message is non-enumerable, so it is restated explicitly). */
|
|
@@ -73,10 +82,29 @@ export type RemoteWireResult =
|
|
|
73
82
|
| { ok: true; value: unknown }
|
|
74
83
|
| { ok: false; error: RemoteWireFailure }
|
|
75
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
|
+
|
|
76
104
|
/** Frames sent by the extension to the bridge plugin. */
|
|
77
105
|
export type ClientFrame =
|
|
78
|
-
/** First frame, within HELLO_TIMEOUT_MS of socket open. */
|
|
79
|
-
| { t: 'hello'; token: string; caps: BridgeCaps }
|
|
106
|
+
/** First frame, within HELLO_TIMEOUT_MS of socket open. `version` (extension version) lets the plugin detect a version mismatch; absent on pre-0.4.6 clients. */
|
|
107
|
+
| { t: 'hello'; token: string; caps: BridgeCaps; version?: string }
|
|
80
108
|
/** Unary Remote call: slash-joined endpoint plus the descriptor's native args object. */
|
|
81
109
|
| { t: 'rpc'; id: string; method: string; args: Record<string, unknown> }
|
|
82
110
|
/** Open one Remote stream (`session/follow`, `workspace/follow`); frames arrive as `stream.frame`. */
|
|
@@ -91,8 +119,8 @@ export type ClientFrame =
|
|
|
91
119
|
|
|
92
120
|
/** Frames sent by the bridge plugin to the extension. */
|
|
93
121
|
export type ServerFrame =
|
|
94
|
-
/** Accepted after a valid `hello`. */
|
|
95
|
-
| { t: 'hello.ok'; caps: BridgeCaps }
|
|
122
|
+
/** Accepted after a valid `hello`. `version` (plugin version) lets the extension detect a version mismatch; absent on pre-0.4.6 servers. */
|
|
123
|
+
| { t: 'hello.ok'; caps: BridgeCaps; version?: string }
|
|
96
124
|
/** Reply to an `rpc` frame: the RemoteResult wire form, flattened onto the frame. */
|
|
97
125
|
| { t: 'rpc.result'; id: string; ok: true; value: unknown }
|
|
98
126
|
| { t: 'rpc.result'; id: string; ok: false; error: RemoteWireFailure }
|
|
@@ -104,6 +132,17 @@ export type ServerFrame =
|
|
|
104
132
|
| { t: 'tool.call'; id: string; name: string; args: Record<string, unknown>; expiresAt?: number; sessionId?: string; title?: string }
|
|
105
133
|
/** Withdraw a tool call that timed out or whose caller was cancelled. */
|
|
106
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 }
|
|
107
146
|
/** Liveness probe. */
|
|
108
147
|
| { t: 'ping' }
|
|
109
148
|
/** Fatal connection error; the client should re-authenticate. */
|
|
@@ -126,6 +165,8 @@ export function isServerFrame(frame: BridgeFrame): frame is ServerFrame {
|
|
|
126
165
|
|| frame.t === 'stream.error'
|
|
127
166
|
|| frame.t === 'tool.call'
|
|
128
167
|
|| frame.t === 'tool.cancel'
|
|
168
|
+
|| frame.t === 'question.requested'
|
|
169
|
+
|| frame.t === 'question.resolved'
|
|
129
170
|
|| frame.t === 'ping'
|
|
130
171
|
|| frame.t === 'error'
|
|
131
172
|
}
|
|
@@ -167,10 +208,14 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
167
208
|
if (typeof frame.t !== 'string') return undefined
|
|
168
209
|
switch (frame.t) {
|
|
169
210
|
case 'hello':
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
:
|
|
211
|
+
if (typeof frame.token !== 'string' || !isCaps(frame.caps)) return undefined
|
|
212
|
+
if (frame.version !== undefined && typeof frame.version !== 'string') return undefined
|
|
213
|
+
return {
|
|
214
|
+
t: 'hello',
|
|
215
|
+
token: frame.token,
|
|
216
|
+
caps: frame.caps,
|
|
217
|
+
...(frame.version === undefined ? {} : { version: frame.version as string }),
|
|
218
|
+
}
|
|
174
219
|
case 'rpc':
|
|
175
220
|
return typeof frame.id === 'string' && typeof frame.method === 'string' && isArgs(frame.args)
|
|
176
221
|
? { t: 'rpc', id: frame.id, method: frame.method, args: frame.args }
|
|
@@ -192,9 +237,13 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
192
237
|
case 'pong':
|
|
193
238
|
return { t: 'pong' }
|
|
194
239
|
case 'hello.ok':
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
240
|
+
if (!isCaps(frame.caps)) return undefined
|
|
241
|
+
if (frame.version !== undefined && typeof frame.version !== 'string') return undefined
|
|
242
|
+
return {
|
|
243
|
+
t: 'hello.ok',
|
|
244
|
+
caps: frame.caps,
|
|
245
|
+
...(frame.version === undefined ? {} : { version: frame.version as string }),
|
|
246
|
+
}
|
|
198
247
|
case 'rpc.result':
|
|
199
248
|
if (typeof frame.id !== 'string') return undefined
|
|
200
249
|
if (frame.ok === true && 'value' in frame) {
|
|
@@ -229,6 +278,18 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
229
278
|
}
|
|
230
279
|
case 'tool.cancel':
|
|
231
280
|
return typeof frame.id === 'string' ? { t: 'tool.cancel', id: frame.id } : undefined
|
|
281
|
+
case 'question.requested':
|
|
282
|
+
return typeof frame.id === 'string'
|
|
283
|
+
&& typeof frame.sessionId === 'string'
|
|
284
|
+
&& Array.isArray(frame.questions)
|
|
285
|
+
&& frame.questions.length > 0
|
|
286
|
+
&& frame.questions.every(isQuestionItem)
|
|
287
|
+
? { t: 'question.requested', id: frame.id, sessionId: frame.sessionId, questions: frame.questions }
|
|
288
|
+
: undefined
|
|
289
|
+
case 'question.resolved':
|
|
290
|
+
return typeof frame.id === 'string' && typeof frame.sessionId === 'string'
|
|
291
|
+
? { t: 'question.resolved', id: frame.id, sessionId: frame.sessionId }
|
|
292
|
+
: undefined
|
|
232
293
|
case 'ping':
|
|
233
294
|
return { t: 'ping' }
|
|
234
295
|
case 'error':
|
|
@@ -243,9 +304,18 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
243
304
|
function isCaps(value: unknown): value is BridgeCaps {
|
|
244
305
|
if (typeof value !== 'object' || value === null) return false
|
|
245
306
|
const caps = value as Record<string, unknown>
|
|
246
|
-
|
|
247
|
-
|
|
307
|
+
// Unknown keys (legacy `textOnly`, future flags) are tolerated: each side
|
|
308
|
+
// only acts on the flags it understands.
|
|
309
|
+
return typeof caps.snapshotMaxChars === 'number' && caps.snapshotMaxChars > 0
|
|
248
310
|
&& typeof caps.maxInteractiveItems === 'number' && caps.maxInteractiveItems > 0
|
|
311
|
+
&& (caps.questions === undefined || typeof caps.questions === 'boolean')
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Narrow one question item; unknown extra keys (e.g. host `intent`) pass through. */
|
|
315
|
+
function isQuestionItem(value: unknown): value is QuestionItem {
|
|
316
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
317
|
+
const item = value as Record<string, unknown>
|
|
318
|
+
return typeof item.id === 'string' && typeof item.question === 'string'
|
|
249
319
|
}
|
|
250
320
|
|
|
251
321
|
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'
|
|
@@ -66,8 +67,8 @@ const ORDERED_SESSION_METHODS = new Set([
|
|
|
66
67
|
'session/cancel',
|
|
67
68
|
])
|
|
68
69
|
|
|
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 =
|
|
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
|
|
71
72
|
|
|
72
73
|
/** Default pump backpressure threshold: pause forwarding when the socket buffer grows past this. */
|
|
73
74
|
const DEFAULT_MAX_BUFFERED_BYTES = 4 * 1024 * 1024
|
|
@@ -150,6 +151,18 @@ export interface BridgeServerDeps {
|
|
|
150
151
|
toolTimeoutMs: number
|
|
151
152
|
/** Capabilities to echo in `hello.ok` (negotiated snapshot budgets). */
|
|
152
153
|
caps: BridgeCaps
|
|
154
|
+
/** Plugin version echoed in `hello.ok` so the extension can flag a mismatch (0.4.6+). */
|
|
155
|
+
version?: string | undefined
|
|
156
|
+
/** An authenticated client arrived with a version different from ours. */
|
|
157
|
+
onVersionMismatch?: (clientVersion: string) => void
|
|
158
|
+
/**
|
|
159
|
+
* Plugin-local endpoint `bridge/questionAnswer`: settle one pending
|
|
160
|
+
* ask_user_question the bridge pushed to this extension. Answered as the
|
|
161
|
+
* rpc result value `{accepted: true} | {accepted: false, reason}`.
|
|
162
|
+
*/
|
|
163
|
+
answerQuestion: (args: Record<string, unknown>) => unknown
|
|
164
|
+
/** The active connection was replaced or closed (settle pushed questions). */
|
|
165
|
+
onConnectionLost?: () => void
|
|
153
166
|
/**
|
|
154
167
|
* Test seam: force the remote address seen by the privilege gate. The
|
|
155
168
|
* sandbox cannot bind arbitrary loopback literals, so the non-loopback
|
|
@@ -188,6 +201,8 @@ interface ReadyConnection {
|
|
|
188
201
|
ws: WebSocket
|
|
189
202
|
/** Remote address captured at upgrade time (loopback gate for privileged methods). */
|
|
190
203
|
remoteAddress: string | undefined
|
|
204
|
+
/** Capabilities the client presented in `hello` (feature advertisements). */
|
|
205
|
+
clientCaps: BridgeCaps
|
|
191
206
|
abort: AbortController
|
|
192
207
|
ping: NodeJS.Timeout
|
|
193
208
|
/** Last protocol pong timestamp (ms); refreshed by the client's answer to each ping. */
|
|
@@ -351,6 +366,22 @@ export class BridgeServer {
|
|
|
351
366
|
return this.current !== null
|
|
352
367
|
}
|
|
353
368
|
|
|
369
|
+
/** @returns whether the connected extension advertised question-card support. */
|
|
370
|
+
clientSupportsQuestions(): boolean {
|
|
371
|
+
return this.current?.clientCaps.questions === true
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Push one unsolicited server frame (question.requested/question.resolved)
|
|
376
|
+
* to the connected extension. No-op when no extension is connected or the
|
|
377
|
+
* socket is already dead.
|
|
378
|
+
*/
|
|
379
|
+
push(frame: ServerFrame): void {
|
|
380
|
+
const conn = this.current
|
|
381
|
+
if (conn === null) return
|
|
382
|
+
sendFrame(conn.ws, frame)
|
|
383
|
+
}
|
|
384
|
+
|
|
354
385
|
private attach(ws: WebSocket, remoteAddress: string | undefined, origin: string | undefined): void {
|
|
355
386
|
let helloTimer: NodeJS.Timeout | undefined = setTimeout(() => {
|
|
356
387
|
ws.close(4001, 'hello timeout')
|
|
@@ -388,7 +419,7 @@ export class BridgeServer {
|
|
|
388
419
|
}
|
|
389
420
|
clearTimeout(helloTimer)
|
|
390
421
|
helloTimer = undefined
|
|
391
|
-
this.promote(ws, remoteAddress)
|
|
422
|
+
this.promote(ws, remoteAddress, frame.caps, frame.version)
|
|
392
423
|
return
|
|
393
424
|
}
|
|
394
425
|
this.handleReadyFrame(frame)
|
|
@@ -403,12 +434,15 @@ export class BridgeServer {
|
|
|
403
434
|
}
|
|
404
435
|
|
|
405
436
|
/** Promote an authenticated socket to the single active slot. */
|
|
406
|
-
private promote(ws: WebSocket, remoteAddress: string | undefined): void {
|
|
437
|
+
private promote(ws: WebSocket, remoteAddress: string | undefined, clientCaps: BridgeCaps, clientVersion?: string): void {
|
|
407
438
|
this.replaceConnection()
|
|
439
|
+
if (clientVersion !== undefined && this.deps.version !== undefined && clientVersion !== this.deps.version) {
|
|
440
|
+
this.deps.onVersionMismatch?.(clientVersion)
|
|
441
|
+
}
|
|
408
442
|
const abort = new AbortController()
|
|
409
443
|
const intervalMs = this.deps.pingIntervalMs ?? PING_INTERVAL_MS
|
|
410
444
|
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() }
|
|
445
|
+
const conn: ReadyConnection = { ws, remoteAddress, clientCaps, abort, ping: undefined as unknown as NodeJS.Timeout, lastPong: Date.now(), streams: new Map() }
|
|
412
446
|
const ping = setInterval(() => {
|
|
413
447
|
// Zombie guard: a client whose event loop is wedged keeps the TCP
|
|
414
448
|
// socket open but never answers pings; terminate it so a healthy
|
|
@@ -421,7 +455,11 @@ export class BridgeServer {
|
|
|
421
455
|
}, intervalMs)
|
|
422
456
|
conn.ping = ping
|
|
423
457
|
this.current = conn
|
|
424
|
-
sendFrame(ws, {
|
|
458
|
+
sendFrame(ws, {
|
|
459
|
+
t: 'hello.ok',
|
|
460
|
+
caps: this.deps.caps,
|
|
461
|
+
...(this.deps.version === undefined ? {} : { version: this.deps.version }),
|
|
462
|
+
})
|
|
425
463
|
ws.once('close', () => {
|
|
426
464
|
clearInterval(ping)
|
|
427
465
|
abort.abort()
|
|
@@ -454,6 +492,8 @@ export class BridgeServer {
|
|
|
454
492
|
case 'stream.frame':
|
|
455
493
|
case 'stream.error':
|
|
456
494
|
case 'tool.call':
|
|
495
|
+
case 'question.requested':
|
|
496
|
+
case 'question.resolved':
|
|
457
497
|
case 'ping':
|
|
458
498
|
case 'error':
|
|
459
499
|
// Protocol violations and unsolicited server-side shapes are ignored;
|
|
@@ -500,6 +540,12 @@ export class BridgeServer {
|
|
|
500
540
|
sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: false, error: { code: 'forbidden', message: 'method is loopback-only' } })
|
|
501
541
|
return
|
|
502
542
|
}
|
|
543
|
+
// Plugin-local endpoint: settle a pending ask_user_question. Intercepted
|
|
544
|
+
// before the Remote passthrough, like the privilege gate above.
|
|
545
|
+
if (frame.method === 'bridge/questionAnswer') {
|
|
546
|
+
sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, value: this.deps.answerQuestion(frame.args) })
|
|
547
|
+
return
|
|
548
|
+
}
|
|
503
549
|
try {
|
|
504
550
|
const result = await this.deps.dispatchRpc(frame.method, frame.args, conn.abort.signal)
|
|
505
551
|
if (result.ok) {
|
|
@@ -613,6 +659,9 @@ export class BridgeServer {
|
|
|
613
659
|
this.pendingTools.delete(id)
|
|
614
660
|
pending.reject(new BridgeToolError('bridge-closed', 'the extension connection was replaced'))
|
|
615
661
|
}
|
|
662
|
+
// Questions pushed to the old connection can never be answered now; the
|
|
663
|
+
// owner delegates their waterfalls to the next answerer.
|
|
664
|
+
this.deps.onConnectionLost?.()
|
|
616
665
|
}
|
|
617
666
|
}
|
|
618
667
|
|