dsh-browser-firefox 0.4.6 → 0.4.8
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 +450 -51
- package/lib/protocol.js +19 -2
- package/lib/types/approvals.d.ts +73 -0
- package/lib/types/extension-sessions.d.ts +72 -12
- package/lib/types/protocol.d.ts +25 -0
- package/lib/types/questions.d.ts +1 -1
- package/lib/types/server.d.ts +23 -0
- package/lib/types/session-follow.d.ts +46 -0
- package/lib/types/waterfall.d.ts +49 -0
- package/package.json +29 -33
- package/src/approvals.ts +143 -0
- package/src/extension-sessions.ts +123 -16
- package/src/index.ts +121 -20
- package/src/protocol.ts +35 -0
- package/src/questions.ts +20 -38
- package/src/server.ts +59 -4
- package/src/session-follow.ts +76 -0
- package/src/waterfall.ts +91 -0
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Track session ids that the browser extension has driven through the bridge.
|
|
3
|
-
* Sessions the extension never touched must keep the host
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* Sessions the extension never touched must keep the host waterfalls
|
|
4
|
+
* (user-questions, approvals) so the dsh web UI (or any other answerer)
|
|
5
|
+
* renders the cards.
|
|
6
|
+
*
|
|
7
|
+
* Ownership has three sources, all revocable:
|
|
8
|
+
* - **driven**: the extension created or prompted the session (kept until the
|
|
9
|
+
* plugin unloads);
|
|
10
|
+
* - **followed**: an open `session/follow` stream means the sidebar is
|
|
11
|
+
* displaying that session right now (released when the stream closes);
|
|
12
|
+
* - **inherited**: an ask from a subagent child session belongs to the
|
|
13
|
+
* nearest extension-owned ancestor, so child questions/approvals surface in
|
|
14
|
+
* the parent conversation the user is actually watching.
|
|
15
|
+
*
|
|
6
16
|
* @module
|
|
7
17
|
*/
|
|
8
18
|
|
|
@@ -15,6 +25,11 @@ export class ExtensionSessionRegistry {
|
|
|
15
25
|
if (typeof sessionId === 'string' && sessionId.length > 0) this.ids.add(sessionId)
|
|
16
26
|
}
|
|
17
27
|
|
|
28
|
+
/** Forget a session (a failed dispatch revoked an optimistic note). */
|
|
29
|
+
forget(sessionId: string | undefined): void {
|
|
30
|
+
if (typeof sessionId === 'string') this.ids.delete(sessionId)
|
|
31
|
+
}
|
|
32
|
+
|
|
18
33
|
/** Whether the extension has touched this session over the bridge. */
|
|
19
34
|
has(sessionId: string | undefined): boolean {
|
|
20
35
|
return typeof sessionId === 'string' && this.ids.has(sessionId)
|
|
@@ -27,20 +42,112 @@ export class ExtensionSessionRegistry {
|
|
|
27
42
|
}
|
|
28
43
|
|
|
29
44
|
/**
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
|
|
45
|
+
* Live `session/follow` subscriptions: the sidebar is displaying these
|
|
46
|
+
* sessions, so they count as extension-owned while the stream is open.
|
|
47
|
+
* Reference-counted per session because one session can be followed by more
|
|
48
|
+
* than one panel connection.
|
|
49
|
+
*/
|
|
50
|
+
export class FollowedSessions {
|
|
51
|
+
private readonly counts = new Map<string, number>()
|
|
52
|
+
|
|
53
|
+
/** Register one open follow stream for a session. */
|
|
54
|
+
open(sessionId: string | undefined): void {
|
|
55
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return
|
|
56
|
+
this.counts.set(sessionId, (this.counts.get(sessionId) ?? 0) + 1)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Release one follow stream; the last release drops the session. */
|
|
60
|
+
close(sessionId: string | undefined): void {
|
|
61
|
+
if (typeof sessionId !== 'string') return
|
|
62
|
+
const current = this.counts.get(sessionId)
|
|
63
|
+
if (current === undefined) return
|
|
64
|
+
if (current <= 1) this.counts.delete(sessionId)
|
|
65
|
+
else this.counts.set(sessionId, current - 1)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Whether any open follow stream is displaying this session. */
|
|
69
|
+
has(sessionId: string | undefined): boolean {
|
|
70
|
+
return typeof sessionId === 'string' && this.counts.has(sessionId)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Drop every subscription (bridge generation replacement, plugin unload). */
|
|
74
|
+
clear(): void {
|
|
75
|
+
this.counts.clear()
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Ownership sources consulted by {@link owningSessionId}. */
|
|
80
|
+
export interface OwnershipSources {
|
|
81
|
+
/** Sessions the extension created or prompted. */
|
|
82
|
+
driven: Pick<ExtensionSessionRegistry, 'has'>
|
|
83
|
+
/** Sessions an open follow stream is displaying. */
|
|
84
|
+
followed?: Pick<FollowedSessions, 'has'>
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Maximum ancestor hops when looking for an owned session. */
|
|
88
|
+
const MAX_OWNER_DEPTH = 8
|
|
89
|
+
|
|
90
|
+
/** Whether one exact session id is extension-owned by either source. */
|
|
91
|
+
export function isOwnedSession(sessionId: string | undefined, sources: OwnershipSources): boolean {
|
|
92
|
+
if (sessionId === undefined) return false
|
|
93
|
+
return sources.driven.has(sessionId) || sources.followed?.has(sessionId) === true
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Resolve which session id the sidebar card should be filed under: the asking
|
|
98
|
+
* session itself when it is owned, otherwise the nearest owned ancestor (a
|
|
99
|
+
* subagent child session inherits its parent's ownership).
|
|
100
|
+
*
|
|
101
|
+
* @param sessionId - the asking session (the host event's agent id).
|
|
102
|
+
* @param sources - ownership sources.
|
|
103
|
+
* @param parentOf - session-id → parent-session-id lookup; absent disables inheritance.
|
|
104
|
+
* @returns the owned session id to route to, or undefined when nothing owns it.
|
|
105
|
+
*/
|
|
106
|
+
export function owningSessionId(
|
|
107
|
+
sessionId: string | undefined,
|
|
108
|
+
sources: OwnershipSources,
|
|
109
|
+
parentOf?: (sessionId: string) => string | undefined,
|
|
110
|
+
): string | undefined {
|
|
111
|
+
if (sessionId === undefined) return undefined
|
|
112
|
+
if (isOwnedSession(sessionId, sources)) return sessionId
|
|
113
|
+
if (parentOf === undefined) return undefined
|
|
114
|
+
const seen = new Set<string>([sessionId])
|
|
115
|
+
let current = sessionId
|
|
116
|
+
for (let depth = 0; depth < MAX_OWNER_DEPTH; depth += 1) {
|
|
117
|
+
const parent = parentOf(current)
|
|
118
|
+
if (parent === undefined || parent.length === 0 || seen.has(parent)) return undefined
|
|
119
|
+
if (isOwnedSession(parent, sources)) return parent
|
|
120
|
+
seen.add(parent)
|
|
121
|
+
current = parent
|
|
122
|
+
}
|
|
123
|
+
return undefined
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Why a host interaction was delegated to the next answerer. */
|
|
127
|
+
export type DelegateReason = 'no-connection' | 'unsupported-client' | 'not-owned'
|
|
128
|
+
|
|
129
|
+
/** One interaction-ownership decision, kept inspectable for logging and tests. */
|
|
130
|
+
export type InteractionOwnership =
|
|
131
|
+
| { owned: true; sessionId: string }
|
|
132
|
+
| { owned: false; reason: DelegateReason }
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Decide whether the bridge should own one host interaction (question or
|
|
136
|
+
* approval). All gates must pass: an extension is connected, it advertised
|
|
137
|
+
* the matching card capability in its hello caps, and the asking session is
|
|
138
|
+
* extension-owned (directly or through an owned ancestor). Everything else
|
|
139
|
+
* falls through to `next()` so the native answerer waterfall keeps working.
|
|
35
140
|
*/
|
|
36
|
-
export function
|
|
141
|
+
export function resolveInteractionOwnership(input: {
|
|
37
142
|
hasExtensionConnection: boolean
|
|
38
|
-
|
|
143
|
+
clientSupports: boolean
|
|
39
144
|
sessionId: string | undefined
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
145
|
+
sources: OwnershipSources
|
|
146
|
+
parentOf?: (sessionId: string) => string | undefined
|
|
147
|
+
}): InteractionOwnership {
|
|
148
|
+
if (!input.hasExtensionConnection) return { owned: false, reason: 'no-connection' }
|
|
149
|
+
if (!input.clientSupports) return { owned: false, reason: 'unsupported-client' }
|
|
150
|
+
const sessionId = owningSessionId(input.sessionId, input.sources, input.parentOf)
|
|
151
|
+
if (sessionId === undefined) return { owned: false, reason: 'not-owned' }
|
|
152
|
+
return { owned: true, sessionId }
|
|
46
153
|
}
|
package/src/index.ts
CHANGED
|
@@ -31,6 +31,8 @@ import z from '@deepseek-ai/schemastery'
|
|
|
31
31
|
import type {} from '@deepseek-ai/dsh-tools'
|
|
32
32
|
import type {} from '@deepseek-ai/dsh-api-gateway/types'
|
|
33
33
|
import type {} from '@deepseek-ai/dsh-user-questions/types'
|
|
34
|
+
import type { ApprovalRequestEvent } from '@deepseek-ai/dsh-user-approval/types'
|
|
35
|
+
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
|
34
36
|
import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
|
|
35
37
|
import { readFileSync } from 'node:fs'
|
|
36
38
|
import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
|
|
@@ -40,8 +42,9 @@ import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, type RemoteWireResult } from './protoc
|
|
|
40
42
|
import { withSessionDeferral } from './session-deferral.ts'
|
|
41
43
|
import { withSessionWorkspace, type RpcDispatch } from './session-workspace.ts'
|
|
42
44
|
import { resolveToken } from './token.ts'
|
|
43
|
-
import { ExtensionSessionRegistry,
|
|
45
|
+
import { ExtensionSessionRegistry, FollowedSessions, resolveInteractionOwnership, type DelegateReason } from './extension-sessions.ts'
|
|
44
46
|
import { asQuestionAnswerArgs, QuestionBridge } from './questions.ts'
|
|
47
|
+
import { ApprovalBridge, asApprovalDecisionArgs } from './approvals.ts'
|
|
45
48
|
|
|
46
49
|
/** Cordis plugin name used by loader diagnostics. */
|
|
47
50
|
export const name = 'bridge-browser'
|
|
@@ -106,6 +109,22 @@ function sessionIdOf(value: unknown): string | undefined {
|
|
|
106
109
|
return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined
|
|
107
110
|
}
|
|
108
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Human-readable approval reason: the asker's localized text when present
|
|
114
|
+
* (zh first, then en), otherwise the raw reason string.
|
|
115
|
+
*
|
|
116
|
+
* @param request - pending host approval request.
|
|
117
|
+
* @returns display text, or undefined when the asker supplied none.
|
|
118
|
+
*/
|
|
119
|
+
function approvalReasonText(request: ApprovalRequestEvent): string | undefined {
|
|
120
|
+
const display = request.displayReason
|
|
121
|
+
if (display !== undefined) {
|
|
122
|
+
const localized = display.zh ?? display['zh-Hans'] ?? display.en
|
|
123
|
+
if (typeof localized === 'string' && localized.length > 0) return localized
|
|
124
|
+
}
|
|
125
|
+
return typeof request.reason === 'string' && request.reason.length > 0 ? request.reason : undefined
|
|
126
|
+
}
|
|
127
|
+
|
|
109
128
|
/**
|
|
110
129
|
* Apply defaults and direct-call validation at the plugin boundary.
|
|
111
130
|
* @param config - Loader-resolved or directly supplied plugin configuration.
|
|
@@ -163,17 +182,39 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
163
182
|
),
|
|
164
183
|
resolved.deferSessionCreate,
|
|
165
184
|
)
|
|
166
|
-
// Ownership tracking for the
|
|
167
|
-
// extension-owned
|
|
168
|
-
//
|
|
169
|
-
//
|
|
185
|
+
// Ownership tracking for the interaction waterfalls (ask_user_question and
|
|
186
|
+
// host approvals). A session becomes extension-owned when a create/prompt is
|
|
187
|
+
// DISPATCHED over the bridge (noted optimistically so a question asked
|
|
188
|
+
// during the very first turn still finds an owner) and is released again
|
|
189
|
+
// when the dispatch fails hard — a failed prompt against a desktop session
|
|
190
|
+
// must not steal its cards away from the native answerer.
|
|
170
191
|
const extensionSessions = new ExtensionSessionRegistry()
|
|
192
|
+
const followedSessions = new FollowedSessions()
|
|
193
|
+
const ownershipSources = { driven: extensionSessions, followed: followedSessions }
|
|
194
|
+
// Subagent child sessions inherit their parent's ownership: a question asked
|
|
195
|
+
// by a delegated agent belongs in the conversation the user is watching.
|
|
196
|
+
// The Session store is read lazily on every hop: capturing it once at mount
|
|
197
|
+
// would silently disable inheritance whenever it is registered after this
|
|
198
|
+
// plugin (or recreated by an HMR reload).
|
|
199
|
+
const parentOf = (sessionId: string): string | undefined => {
|
|
200
|
+
const sessions = ctx.get('sessions')
|
|
201
|
+
return sessions?.get(sessionId as SessionId)?.header.parentSession
|
|
202
|
+
}
|
|
171
203
|
const notingDispatchRpc: RpcDispatch = async (method, args, signal) => {
|
|
204
|
+
const tracksOwnership = method === 'session/create' || method === 'session/prompt'
|
|
205
|
+
const dispatched = tracksOwnership ? sessionIdOf(args.request) : undefined
|
|
206
|
+
if (dispatched !== undefined) extensionSessions.note(dispatched)
|
|
172
207
|
const result = await dispatchRpc(method, args, signal)
|
|
173
|
-
if (result.ok
|
|
174
|
-
|
|
175
|
-
|
|
208
|
+
if (!result.ok) {
|
|
209
|
+
// Only a lookup failure disproves the optimistic note (the session does
|
|
210
|
+
// not exist); transient failures keep the session extension-owned.
|
|
211
|
+
const code = result.error.code
|
|
212
|
+
if (dispatched !== undefined && (code.includes('not-found') || code.includes('session-invalid'))) {
|
|
213
|
+
extensionSessions.forget(dispatched)
|
|
214
|
+
}
|
|
215
|
+
return result
|
|
176
216
|
}
|
|
217
|
+
if (tracksOwnership) extensionSessions.note(sessionIdOf(result.value))
|
|
177
218
|
return result
|
|
178
219
|
}
|
|
179
220
|
// Plugin version for the hello.ok handshake (extension flags a mismatch in
|
|
@@ -190,6 +231,9 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
190
231
|
// Late-bound through the closure: server is constructed right below.
|
|
191
232
|
push: (frame) => { server.push(frame) },
|
|
192
233
|
})
|
|
234
|
+
const approvals = new ApprovalBridge({
|
|
235
|
+
push: (frame) => { server.push(frame) },
|
|
236
|
+
})
|
|
193
237
|
const server = new BridgeServer({
|
|
194
238
|
token: tokenRes.token,
|
|
195
239
|
dispatchRpc: notingDispatchRpc,
|
|
@@ -205,7 +249,20 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
205
249
|
? { accepted: false, reason: 'bad-answer' }
|
|
206
250
|
: questions.answer(parsed)
|
|
207
251
|
},
|
|
208
|
-
|
|
252
|
+
answerApproval: (args) => {
|
|
253
|
+
const parsed = asApprovalDecisionArgs(args)
|
|
254
|
+
return parsed === undefined
|
|
255
|
+
? { accepted: false, reason: 'bad-decision' }
|
|
256
|
+
: approvals.decide(parsed)
|
|
257
|
+
},
|
|
258
|
+
onConnectionLost: () => {
|
|
259
|
+
questions.delegateAll()
|
|
260
|
+
approvals.delegateAll()
|
|
261
|
+
},
|
|
262
|
+
onFollowChanged: (sessionId, open) => {
|
|
263
|
+
if (open) followedSessions.open(sessionId)
|
|
264
|
+
else followedSessions.close(sessionId)
|
|
265
|
+
},
|
|
209
266
|
version: pluginVersion,
|
|
210
267
|
onVersionMismatch: (clientVersion) => {
|
|
211
268
|
ctx.logger.warn(`browser extension version ${clientVersion} != plugin version ${pluginVersion ?? '?'}; both components must be updated together`)
|
|
@@ -218,22 +275,33 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
218
275
|
})
|
|
219
276
|
|
|
220
277
|
// Sidebar ask_user_question: claim the waterfall only for sessions the
|
|
221
|
-
// extension owns (
|
|
222
|
-
// question-capable extension is
|
|
223
|
-
// native answerer chain (dsh web).
|
|
224
|
-
// Remote event forwarding listener
|
|
278
|
+
// extension owns (driven over the bridge, currently followed, or a subagent
|
|
279
|
+
// child of an owned session) while a question-capable extension is
|
|
280
|
+
// connected; everything else keeps the native answerer chain (dsh web).
|
|
281
|
+
// Prepended so the claim runs before the Remote event forwarding listener
|
|
282
|
+
// in dsh-api-remotes. Delegations are logged with the failing gate so an
|
|
283
|
+
// "invisible card" report is diagnosable from the host log.
|
|
284
|
+
// 委托日志:只有「扩展在线但不支持该卡片」是用户可操作的(扩展版本旧),
|
|
285
|
+
// 其余(无连接、会话不归属)在 dsh web 会话里每次都发生,压到 debug 免得刷屏。
|
|
286
|
+
const logDelegation = (kind: 'user-questions' | 'approval', sessionId: string | undefined, reason: DelegateReason): void => {
|
|
287
|
+
const line = `browser bridge: delegated ${kind} for session ${sessionId ?? '<unknown>'} (${reason})`
|
|
288
|
+
if (reason === 'unsupported-client') ctx.logger.info(line)
|
|
289
|
+
else ctx.logger.debug(line)
|
|
290
|
+
}
|
|
225
291
|
ctx.effect(() => {
|
|
226
292
|
const disposeListener = ctx.on('user-questions/request', (request, next) => {
|
|
227
|
-
const
|
|
228
|
-
if (sessionId === undefined || !shouldBridgeOwnQuestion({
|
|
293
|
+
const ownership = resolveInteractionOwnership({
|
|
229
294
|
hasExtensionConnection: server.hasConnection(),
|
|
230
|
-
|
|
231
|
-
sessionId,
|
|
232
|
-
|
|
233
|
-
|
|
295
|
+
clientSupports: server.clientSupportsQuestions(),
|
|
296
|
+
sessionId: request.agent?.id,
|
|
297
|
+
sources: ownershipSources,
|
|
298
|
+
parentOf,
|
|
299
|
+
})
|
|
300
|
+
if (!ownership.owned) {
|
|
301
|
+
logDelegation('user-questions', request.agent?.id, ownership.reason)
|
|
234
302
|
return next()
|
|
235
303
|
}
|
|
236
|
-
return questions.ask(sessionId, request.questions, next, request.signal)
|
|
304
|
+
return questions.ask(ownership.sessionId, request.questions, next, request.signal)
|
|
237
305
|
}, { prepend: true })
|
|
238
306
|
return () => {
|
|
239
307
|
disposeListener()
|
|
@@ -241,6 +309,39 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
241
309
|
}
|
|
242
310
|
}, 'bridge-browser: user-questions answerer')
|
|
243
311
|
|
|
312
|
+
// Host approvals (a hooked tool call / permission ask): same ownership rule,
|
|
313
|
+
// same sidebar surface, so the user is not sent to dsh web for a decision.
|
|
314
|
+
ctx.effect(() => {
|
|
315
|
+
const disposeListener = ctx.on('approval/request', (request, next) => {
|
|
316
|
+
const ownership = resolveInteractionOwnership({
|
|
317
|
+
hasExtensionConnection: server.hasConnection(),
|
|
318
|
+
clientSupports: server.clientSupportsApprovals(),
|
|
319
|
+
sessionId: request.agent?.id,
|
|
320
|
+
sources: ownershipSources,
|
|
321
|
+
parentOf,
|
|
322
|
+
})
|
|
323
|
+
if (!ownership.owned) {
|
|
324
|
+
logDelegation('approval', request.agent?.id, ownership.reason)
|
|
325
|
+
return next()
|
|
326
|
+
}
|
|
327
|
+
const reason = approvalReasonText(request)
|
|
328
|
+
return approvals.ask(
|
|
329
|
+
ownership.sessionId,
|
|
330
|
+
{
|
|
331
|
+
toolName: request.toolName,
|
|
332
|
+
...(typeof request.callId === 'string' ? { callId: request.callId } : {}),
|
|
333
|
+
...(reason === undefined ? {} : { reason }),
|
|
334
|
+
},
|
|
335
|
+
next,
|
|
336
|
+
request.signal,
|
|
337
|
+
)
|
|
338
|
+
}, { prepend: true })
|
|
339
|
+
return () => {
|
|
340
|
+
disposeListener()
|
|
341
|
+
approvals.dispose()
|
|
342
|
+
}
|
|
343
|
+
}, 'bridge-browser: approval answerer')
|
|
344
|
+
|
|
244
345
|
const route: WebUpgradeRoute = {
|
|
245
346
|
path: BRIDGE_PATH,
|
|
246
347
|
handler: (req, socket, head) => { server.handleUpgrade(req, socket, head) },
|
package/src/protocol.ts
CHANGED
|
@@ -68,6 +68,8 @@ export interface BridgeCaps {
|
|
|
68
68
|
maxInteractiveItems: number
|
|
69
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
70
|
questions?: boolean
|
|
71
|
+
/** Client advertises it can render host approval (permission) cards; the plugin only claims the approval waterfall for extension-owned sessions when set. */
|
|
72
|
+
approvals?: boolean
|
|
71
73
|
}
|
|
72
74
|
|
|
73
75
|
/** One Remote failure as plain wire data (RemoteError's message is non-enumerable, so it is restated explicitly). */
|
|
@@ -143,6 +145,18 @@ export type ServerFrame =
|
|
|
143
145
|
| { t: 'question.requested'; id: string; sessionId: string; questions: QuestionItem[] }
|
|
144
146
|
/** A previously pushed question is gone (host aborted it or the bridge delegated the waterfall elsewhere); dismiss the card without answering. */
|
|
145
147
|
| { t: 'question.resolved'; id: string; sessionId: string }
|
|
148
|
+
/**
|
|
149
|
+
* The host needs one approval decision (a hooked tool call, a permission
|
|
150
|
+
* ask) in an extension-owned session and the bridge claimed the waterfall:
|
|
151
|
+
* the extension should render an approval card. The decision rides a normal
|
|
152
|
+
* `rpc` frame with the plugin-local method `bridge/approvalDecision` (args
|
|
153
|
+
* `{approvalId, sessionId, decision: 'allowed-once' | 'rejected'}`),
|
|
154
|
+
* answered `{accepted: true} | {accepted: false, reason: 'not-pending' |
|
|
155
|
+
* 'bad-decision'}`.
|
|
156
|
+
*/
|
|
157
|
+
| { t: 'approval.requested'; id: string; sessionId: string; toolName: string; callId?: string; reason?: string }
|
|
158
|
+
/** A previously pushed approval is gone (host cancelled it or the bridge delegated the waterfall elsewhere); dismiss the card without deciding. */
|
|
159
|
+
| { t: 'approval.resolved'; id: string; sessionId: string }
|
|
146
160
|
/** Liveness probe. */
|
|
147
161
|
| { t: 'ping' }
|
|
148
162
|
/** Fatal connection error; the client should re-authenticate. */
|
|
@@ -167,6 +181,8 @@ export function isServerFrame(frame: BridgeFrame): frame is ServerFrame {
|
|
|
167
181
|
|| frame.t === 'tool.cancel'
|
|
168
182
|
|| frame.t === 'question.requested'
|
|
169
183
|
|| frame.t === 'question.resolved'
|
|
184
|
+
|| frame.t === 'approval.requested'
|
|
185
|
+
|| frame.t === 'approval.resolved'
|
|
170
186
|
|| frame.t === 'ping'
|
|
171
187
|
|| frame.t === 'error'
|
|
172
188
|
}
|
|
@@ -290,6 +306,24 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
290
306
|
return typeof frame.id === 'string' && typeof frame.sessionId === 'string'
|
|
291
307
|
? { t: 'question.resolved', id: frame.id, sessionId: frame.sessionId }
|
|
292
308
|
: undefined
|
|
309
|
+
case 'approval.requested':
|
|
310
|
+
if (typeof frame.id !== 'string' || typeof frame.sessionId !== 'string' || typeof frame.toolName !== 'string') {
|
|
311
|
+
return undefined
|
|
312
|
+
}
|
|
313
|
+
if (frame.callId !== undefined && typeof frame.callId !== 'string') return undefined
|
|
314
|
+
if (frame.reason !== undefined && typeof frame.reason !== 'string') return undefined
|
|
315
|
+
return {
|
|
316
|
+
t: 'approval.requested',
|
|
317
|
+
id: frame.id,
|
|
318
|
+
sessionId: frame.sessionId,
|
|
319
|
+
toolName: frame.toolName,
|
|
320
|
+
...(typeof frame.callId === 'string' ? { callId: frame.callId } : {}),
|
|
321
|
+
...(typeof frame.reason === 'string' ? { reason: frame.reason } : {}),
|
|
322
|
+
}
|
|
323
|
+
case 'approval.resolved':
|
|
324
|
+
return typeof frame.id === 'string' && typeof frame.sessionId === 'string'
|
|
325
|
+
? { t: 'approval.resolved', id: frame.id, sessionId: frame.sessionId }
|
|
326
|
+
: undefined
|
|
293
327
|
case 'ping':
|
|
294
328
|
return { t: 'ping' }
|
|
295
329
|
case 'error':
|
|
@@ -309,6 +343,7 @@ function isCaps(value: unknown): value is BridgeCaps {
|
|
|
309
343
|
return typeof caps.snapshotMaxChars === 'number' && caps.snapshotMaxChars > 0
|
|
310
344
|
&& typeof caps.maxInteractiveItems === 'number' && caps.maxInteractiveItems > 0
|
|
311
345
|
&& (caps.questions === undefined || typeof caps.questions === 'boolean')
|
|
346
|
+
&& (caps.approvals === undefined || typeof caps.approvals === 'boolean')
|
|
312
347
|
}
|
|
313
348
|
|
|
314
349
|
/** Narrow one question item; unknown extra keys (e.g. host `intent`) pass through. */
|
package/src/questions.ts
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
import { randomUUID } from 'node:crypto'
|
|
20
20
|
import type { QuestionItem, ServerFrame } from './protocol.ts'
|
|
21
|
+
import { PendingWaterfalls } from './waterfall.ts'
|
|
21
22
|
|
|
22
23
|
/** One answer item, mirroring the host AskUserQuestionAnswerItem wire form. */
|
|
23
24
|
export interface QuestionAnswerItem {
|
|
@@ -49,15 +50,6 @@ type PendingOutcome =
|
|
|
49
50
|
| { kind: 'reject'; error: Error }
|
|
50
51
|
| { kind: 'delegate' }
|
|
51
52
|
|
|
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
53
|
/** Error matching the host's ASK_ABORTED semantics (the service remaps it). */
|
|
62
54
|
function abortedError(): Error {
|
|
63
55
|
return new Error('ask_user_question was aborted before the user answered')
|
|
@@ -99,7 +91,7 @@ export function asQuestionAnswerArgs(value: unknown): QuestionAnswerArgs | undef
|
|
|
99
91
|
|
|
100
92
|
/** Owns the user-questions waterfall for extension-driven sessions. */
|
|
101
93
|
export class QuestionBridge {
|
|
102
|
-
private readonly
|
|
94
|
+
private readonly waterfalls = new PendingWaterfalls<PendingOutcome, ReadonlySet<string>>()
|
|
103
95
|
|
|
104
96
|
constructor(private readonly deps: {
|
|
105
97
|
/** Push one server frame to the connected extension (must tolerate a dead socket). */
|
|
@@ -124,33 +116,28 @@ export class QuestionBridge {
|
|
|
124
116
|
): Promise<QuestionAnswerPayload> {
|
|
125
117
|
if (signal?.aborted) return Promise.reject(abortedError())
|
|
126
118
|
const questionId = randomUUID()
|
|
119
|
+
const questionIds = new Set(questions.map(question => question.id))
|
|
127
120
|
return new Promise<QuestionAnswerPayload>((resolve, reject) => {
|
|
128
|
-
const
|
|
121
|
+
const settle = (outcome: PendingOutcome): void => {
|
|
122
|
+
this.waterfalls.settle(questionId, outcome)
|
|
123
|
+
}
|
|
124
|
+
this.waterfalls.register({
|
|
125
|
+
id: questionId,
|
|
129
126
|
sessionId,
|
|
130
|
-
questionIds: new Set(questions.map(question => question.id)),
|
|
131
|
-
settled: false,
|
|
132
127
|
signal,
|
|
128
|
+
payload: questionIds,
|
|
133
129
|
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
130
|
if (outcome.kind === 'answer') resolve(outcome.answer)
|
|
139
131
|
else if (outcome.kind === 'reject') reject(outcome.error)
|
|
140
132
|
else next().then(resolve, reject)
|
|
141
133
|
},
|
|
142
|
-
onAbort:
|
|
143
|
-
}
|
|
144
|
-
if (signal !== undefined) {
|
|
145
|
-
entry.onAbort = () => {
|
|
134
|
+
onAbort: () => {
|
|
146
135
|
// Tell the extension to drop the card before settling so a late
|
|
147
136
|
// answer can never report acceptance for a dead request.
|
|
148
137
|
this.deps.push({ t: 'question.resolved', id: questionId, sessionId })
|
|
149
|
-
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
}
|
|
153
|
-
this.pending.set(questionId, entry)
|
|
138
|
+
settle({ kind: 'reject', error: abortedError() })
|
|
139
|
+
},
|
|
140
|
+
})
|
|
154
141
|
this.deps.push({ t: 'question.requested', id: questionId, sessionId, questions })
|
|
155
142
|
})
|
|
156
143
|
}
|
|
@@ -160,33 +147,28 @@ export class QuestionBridge {
|
|
|
160
147
|
* rpc. The server replies with this receipt.
|
|
161
148
|
*/
|
|
162
149
|
answer(args: QuestionAnswerArgs): QuestionAnswerReceipt {
|
|
163
|
-
|
|
164
|
-
if (entry === undefined || entry.settled || entry.sessionId !== args.sessionId) {
|
|
150
|
+
if (!this.waterfalls.matches(args.questionId, args.sessionId)) {
|
|
165
151
|
return { accepted: false, reason: 'not-pending' }
|
|
166
152
|
}
|
|
167
153
|
if (args.decline === true) {
|
|
168
|
-
|
|
154
|
+
this.waterfalls.settle(args.questionId, { kind: 'reject', error: declinedError() })
|
|
169
155
|
return { accepted: true }
|
|
170
156
|
}
|
|
171
|
-
const answer = asAnswerPayload(args.answer,
|
|
157
|
+
const answer = asAnswerPayload(args.answer, this.waterfalls.payloadOf(args.questionId) ?? new Set())
|
|
172
158
|
if (answer === undefined) return { accepted: false, reason: 'bad-answer' }
|
|
173
|
-
|
|
159
|
+
this.waterfalls.settle(args.questionId, { kind: 'answer', answer })
|
|
174
160
|
return { accepted: true }
|
|
175
161
|
}
|
|
176
162
|
|
|
177
163
|
/** Bridge connection replaced/closed: delegate every unsettled question. */
|
|
178
164
|
delegateAll(): void {
|
|
179
|
-
for (const
|
|
180
|
-
if (!entry.settled) entry.complete({ kind: 'delegate' })
|
|
181
|
-
}
|
|
165
|
+
for (const id of this.waterfalls.ids()) this.waterfalls.settle(id, { kind: 'delegate' })
|
|
182
166
|
}
|
|
183
167
|
|
|
184
168
|
/** Plugin unload: reject everything so no tool call outlives the plugin. */
|
|
185
169
|
dispose(): void {
|
|
186
|
-
for (const
|
|
187
|
-
|
|
188
|
-
entry.complete({ kind: 'reject', error: new Error('browser bridge plugin was unloaded') })
|
|
189
|
-
}
|
|
170
|
+
for (const id of this.waterfalls.ids()) {
|
|
171
|
+
this.waterfalls.settle(id, { kind: 'reject', error: new Error('browser bridge plugin was unloaded') })
|
|
190
172
|
}
|
|
191
173
|
}
|
|
192
174
|
}
|