dsh-browser-firefox 0.5.1 → 0.5.3
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/README.md +13 -3
- package/icon.svg +10 -0
- package/lib/index.js +613 -69
- package/lib/protocol.js +60 -4
- package/lib/types/approvals.d.ts +7 -0
- package/lib/types/discovery-beacon.d.ts +31 -0
- package/lib/types/extension-sessions.d.ts +88 -6
- package/lib/types/index.d.ts +6 -0
- package/lib/types/protocol.d.ts +53 -0
- package/lib/types/questions.d.ts +37 -2
- package/lib/types/server.d.ts +47 -9
- package/lib/types/untrusted.d.ts +31 -0
- package/lib/types/waterfall.d.ts +4 -0
- package/package.json +7 -4
- package/src/approvals.ts +65 -4
- package/src/discovery-beacon.ts +77 -0
- package/src/extension-sessions.ts +147 -7
- package/src/index.ts +144 -3
- package/src/protocol.ts +68 -1
- package/src/questions.ts +128 -8
- package/src/server.ts +123 -31
- package/src/session-workspace.ts +18 -4
- package/src/tools.ts +20 -4
- package/src/untrusted.ts +50 -0
- package/src/waterfall.ts +24 -1
package/src/index.ts
CHANGED
|
@@ -43,9 +43,10 @@ import { withSessionDeferral } from './session-deferral.ts'
|
|
|
43
43
|
import { withSessionWorkspace, type RpcDispatch } from './session-workspace.ts'
|
|
44
44
|
import { resolveToken } from './token.ts'
|
|
45
45
|
import { createGatewayPeer } from './gateway-peer.ts'
|
|
46
|
-
import { ExtensionSessionRegistry, FollowedSessions, resolveInteractionOwnership, type DelegateReason } from './extension-sessions.ts'
|
|
46
|
+
import { ExtensionSessionRegistry, FollowedSessions, SessionActivity, resolveInteractionOwnership, type DelegateReason } from './extension-sessions.ts'
|
|
47
47
|
import { asQuestionAnswerArgs, QuestionBridge } from './questions.ts'
|
|
48
48
|
import { ApprovalBridge, asApprovalDecisionArgs } from './approvals.ts'
|
|
49
|
+
import { startDiscoveryBeacon } from './discovery-beacon.ts'
|
|
49
50
|
|
|
50
51
|
/** Cordis plugin name used by loader diagnostics. */
|
|
51
52
|
export const name = 'bridge-browser'
|
|
@@ -68,6 +69,20 @@ const DEFAULT_SESSION_WORKSPACE_PATH = dshHomePath('browser-sessions')
|
|
|
68
69
|
/** Default: sessions materialize only on the first message (open-and-close leaves no trace). */
|
|
69
70
|
const DEFAULT_DEFER_SESSION_CREATE = true
|
|
70
71
|
|
|
72
|
+
/**
|
|
73
|
+
* Default: a live dsh web client owns host interactions. The bridge claims a
|
|
74
|
+
* waterfall only when nothing else can answer it — otherwise the user would
|
|
75
|
+
* answer in the sidebar while the conversation they are watching stays silent.
|
|
76
|
+
*/
|
|
77
|
+
const DEFAULT_PREFER_WEB_ANSWERER = true
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Default budget for one pushed card (ms). An unanswered card would otherwise
|
|
81
|
+
* hold the agent turn open forever, because a connected-but-unattended bridge
|
|
82
|
+
* looks exactly like a user who is thinking.
|
|
83
|
+
*/
|
|
84
|
+
const DEFAULT_ANSWER_TIMEOUT_MS = 10 * 60_000
|
|
85
|
+
|
|
71
86
|
/** Plugin config: deployment-varying tunables only; the wire contract stays fixed. */
|
|
72
87
|
export interface Config {
|
|
73
88
|
/** Fixed bearer token. When absent, a token is generated on first boot and persisted under the dsh home (0600). */
|
|
@@ -82,6 +97,12 @@ export interface Config {
|
|
|
82
97
|
sessionWorkspacePath?: string
|
|
83
98
|
/** Defer real session creation until the first prompt. Defaults to true. */
|
|
84
99
|
deferSessionCreate?: boolean
|
|
100
|
+
/** Prefer the dsh web client as the interaction answerer. Defaults to true. */
|
|
101
|
+
preferWebAnswerer?: boolean
|
|
102
|
+
/** How long one pushed question/approval may wait for an answer before it settles; 0 disables. Defaults to 600000. */
|
|
103
|
+
answerTimeoutMs?: number
|
|
104
|
+
/** Bind a fixed-port discovery beacon so an ephemeral-port host is still findable. Defaults to true. */
|
|
105
|
+
discoveryBeacon?: boolean
|
|
85
106
|
}
|
|
86
107
|
|
|
87
108
|
export const Config: z<Config> = z.object({
|
|
@@ -91,6 +112,9 @@ export const Config: z<Config> = z.object({
|
|
|
91
112
|
maxInteractiveItems: z.number().step(1).min(1).default(DEFAULT_MAX_INTERACTIVE_ITEMS),
|
|
92
113
|
sessionWorkspacePath: z.string().default(DEFAULT_SESSION_WORKSPACE_PATH),
|
|
93
114
|
deferSessionCreate: z.boolean().default(DEFAULT_DEFER_SESSION_CREATE),
|
|
115
|
+
preferWebAnswerer: z.boolean().default(DEFAULT_PREFER_WEB_ANSWERER),
|
|
116
|
+
answerTimeoutMs: z.number().step(1).min(0).default(DEFAULT_ANSWER_TIMEOUT_MS),
|
|
117
|
+
discoveryBeacon: z.boolean().default(true),
|
|
94
118
|
})
|
|
95
119
|
|
|
96
120
|
/** The shape after schemastery applies its defaults to every field. */
|
|
@@ -110,6 +134,17 @@ function sessionIdOf(value: unknown): string | undefined {
|
|
|
110
134
|
return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined
|
|
111
135
|
}
|
|
112
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Extract the client-minted prompt identity from an rpc args/result object.
|
|
139
|
+
* The host echoes it onto the durable `user/message` as `source.rpcId`, which
|
|
140
|
+
* is how this plugin later tells a sidebar prompt from a dsh web one.
|
|
141
|
+
*/
|
|
142
|
+
function requestIdOf(value: unknown): string | undefined {
|
|
143
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
|
|
144
|
+
const requestId = (value as Record<string, unknown>).requestId
|
|
145
|
+
return typeof requestId === 'string' && requestId.length > 0 ? requestId : undefined
|
|
146
|
+
}
|
|
147
|
+
|
|
113
148
|
/**
|
|
114
149
|
* Human-readable approval reason: the asker's localized text when present
|
|
115
150
|
* (zh first, then en), otherwise the raw reason string.
|
|
@@ -139,10 +174,16 @@ export function resolveConfig(config: Config): ResolvedConfig {
|
|
|
139
174
|
maxInteractiveItems: config.maxInteractiveItems ?? DEFAULT_MAX_INTERACTIVE_ITEMS,
|
|
140
175
|
sessionWorkspacePath: config.sessionWorkspacePath ?? DEFAULT_SESSION_WORKSPACE_PATH,
|
|
141
176
|
deferSessionCreate: config.deferSessionCreate ?? DEFAULT_DEFER_SESSION_CREATE,
|
|
177
|
+
preferWebAnswerer: config.preferWebAnswerer ?? DEFAULT_PREFER_WEB_ANSWERER,
|
|
178
|
+
answerTimeoutMs: config.answerTimeoutMs ?? DEFAULT_ANSWER_TIMEOUT_MS,
|
|
179
|
+
discoveryBeacon: config.discoveryBeacon ?? true,
|
|
142
180
|
}
|
|
143
181
|
assertPositiveInteger('toolTimeoutMs', resolved.toolTimeoutMs)
|
|
144
182
|
assertPositiveInteger('snapshotMaxChars', resolved.snapshotMaxChars)
|
|
145
183
|
assertPositiveInteger('maxInteractiveItems', resolved.maxInteractiveItems)
|
|
184
|
+
if (!Number.isInteger(resolved.answerTimeoutMs) || resolved.answerTimeoutMs < 0) {
|
|
185
|
+
throw new Error('bridge-browser: answerTimeoutMs must be a non-negative integer')
|
|
186
|
+
}
|
|
146
187
|
return resolved
|
|
147
188
|
}
|
|
148
189
|
|
|
@@ -195,6 +236,12 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
195
236
|
const extensionSessions = new ExtensionSessionRegistry()
|
|
196
237
|
const followedSessions = new FollowedSessions()
|
|
197
238
|
const ownershipSources = { driven: extensionSessions, followed: followedSessions }
|
|
239
|
+
// Which UI spoke last, per session. The routing rule for pushed cards: the
|
|
240
|
+
// card follows the UI the user is actually driving (see SessionActivity).
|
|
241
|
+
const activity = new SessionActivity()
|
|
242
|
+
// A session that left the store can no longer ask, so it must stop counting
|
|
243
|
+
// as extension-owned; the lookup stays lazy for the same reason as parentOf.
|
|
244
|
+
extensionSessions.watchStore((sessionId) => ctx.get('sessions')?.get(sessionId as SessionId) !== undefined)
|
|
198
245
|
// Subagent child sessions inherit their parent's ownership: a question asked
|
|
199
246
|
// by a delegated agent belongs in the conversation the user is watching.
|
|
200
247
|
// The Session store is read lazily on every hop: capturing it once at mount
|
|
@@ -208,6 +255,11 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
208
255
|
const tracksOwnership = method === 'session/create' || method === 'session/prompt'
|
|
209
256
|
const dispatched = tracksOwnership ? sessionIdOf(args.request) : undefined
|
|
210
257
|
if (dispatched !== undefined) extensionSessions.note(dispatched)
|
|
258
|
+
// A prompt through the bridge means the SIDEBAR is the UI being driven, so
|
|
259
|
+
// the session's cards belong there until another UI speaks. The requestId is
|
|
260
|
+
// recorded too: the durable user/message echoes it, which lets the
|
|
261
|
+
// session/event listener below attribute later messages back to this path.
|
|
262
|
+
if (method === 'session/prompt') activity.noteSidebarPrompt(dispatched, requestIdOf(args.request))
|
|
211
263
|
const result = await dispatchRpc(method, args, signal)
|
|
212
264
|
if (!result.ok) {
|
|
213
265
|
// Only a lookup failure disproves the optimistic note (the session does
|
|
@@ -234,13 +286,47 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
234
286
|
const questions = new QuestionBridge({
|
|
235
287
|
// Late-bound through the closure: server is constructed right below.
|
|
236
288
|
push: (frame) => { server.push(frame) },
|
|
289
|
+
// A timed ask must hold the host's foreground wait while the sidebar owns
|
|
290
|
+
// the card, or the host's own countdown withdraws it mid-typing. The claim
|
|
291
|
+
// is a `userQuestions/attachWait` stream that lives exactly as long as the
|
|
292
|
+
// card; the frames it yields are irrelevant, holding it is the point.
|
|
293
|
+
attachWait: (agentId, callId, signal) => {
|
|
294
|
+
let released = false
|
|
295
|
+
const pump = (async () => {
|
|
296
|
+
const stream = await ctx.typertGateway.stream({
|
|
297
|
+
namespace: 'userQuestions',
|
|
298
|
+
method: 'attachWait',
|
|
299
|
+
args: { agentId, callId },
|
|
300
|
+
signal,
|
|
301
|
+
peer,
|
|
302
|
+
})
|
|
303
|
+
for await (const _frame of stream) {
|
|
304
|
+
// Frames only carry the remaining duration; holding the stream open
|
|
305
|
+
// is what pauses the host countdown.
|
|
306
|
+
if (signal.aborted) break
|
|
307
|
+
}
|
|
308
|
+
})()
|
|
309
|
+
// An escaping rejection would reach the host's fail-loud handler; the
|
|
310
|
+
// claim is best-effort, so absorb it here.
|
|
311
|
+
void pump.catch(() => undefined)
|
|
312
|
+
return () => {
|
|
313
|
+
if (released) return
|
|
314
|
+
released = true
|
|
315
|
+
void pump.catch(() => undefined)
|
|
316
|
+
}
|
|
317
|
+
},
|
|
318
|
+
answerTimeoutMs: resolved.answerTimeoutMs,
|
|
237
319
|
})
|
|
238
320
|
const approvals = new ApprovalBridge({
|
|
239
321
|
push: (frame) => { server.push(frame) },
|
|
322
|
+
answerTimeoutMs: resolved.answerTimeoutMs,
|
|
240
323
|
})
|
|
241
324
|
const server = new BridgeServer({
|
|
242
325
|
token: tokenRes.token,
|
|
243
326
|
dispatchRpc: notingDispatchRpc,
|
|
327
|
+
// The panel-presence frame is a protocol addition; a peer that predates it
|
|
328
|
+
// would close the socket on an unknown frame type.
|
|
329
|
+
panelPresence: true,
|
|
244
330
|
openStream: (method, args, signal) => {
|
|
245
331
|
const slash = method.indexOf('/')
|
|
246
332
|
const namespace = slash === -1 ? method : method.slice(0, slash)
|
|
@@ -263,6 +349,12 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
263
349
|
questions.delegateAll()
|
|
264
350
|
approvals.delegateAll()
|
|
265
351
|
},
|
|
352
|
+
onConnectionReplaced: () => {
|
|
353
|
+
// Keep pending cards alive across a transient reconnect: re-push them to
|
|
354
|
+
// the newly promoted panel instead of stranding the host turn.
|
|
355
|
+
questions.replay()
|
|
356
|
+
approvals.replay()
|
|
357
|
+
},
|
|
266
358
|
onFollowChanged: (sessionId, open) => {
|
|
267
359
|
if (open) followedSessions.open(sessionId)
|
|
268
360
|
else followedSessions.close(sessionId)
|
|
@@ -275,6 +367,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
275
367
|
caps: {
|
|
276
368
|
snapshotMaxChars: resolved.snapshotMaxChars,
|
|
277
369
|
maxInteractiveItems: resolved.maxInteractiveItems,
|
|
370
|
+
panelPresence: true,
|
|
278
371
|
},
|
|
279
372
|
})
|
|
280
373
|
|
|
@@ -292,11 +385,29 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
292
385
|
if (reason === 'unsupported-client') ctx.logger.info(line)
|
|
293
386
|
else ctx.logger.debug(line)
|
|
294
387
|
}
|
|
388
|
+
|
|
389
|
+
// Observe the other UI's prompts. A prompt typed in dsh web never crosses the
|
|
390
|
+
// bridge, so it surfaces only as a durable `user/message`; anything whose
|
|
391
|
+
// source.rpcId was NOT minted by the bridge came from another UI. That makes
|
|
392
|
+
// "who spoke last" observable without any host focus signal.
|
|
393
|
+
ctx.effect(() => ctx.on('session/event', (session, event) => {
|
|
394
|
+
if (event.type !== 'user/message') return
|
|
395
|
+
const source = (event.data as { source?: { kind?: string; rpcId?: unknown } }).source
|
|
396
|
+
// Only a real user submission counts; runtime context injections
|
|
397
|
+
// (`plugin`/`developer` sources) say nothing about where the user is looking.
|
|
398
|
+
if (source?.kind !== 'user') return
|
|
399
|
+
if (activity.isSidebarRequest(typeof source.rpcId === 'string' ? source.rpcId : undefined)) return
|
|
400
|
+
activity.noteWebPrompt(session.id)
|
|
401
|
+
}, { global: true }), 'bridge-browser: track last-active UI')
|
|
402
|
+
|
|
295
403
|
ctx.effect(() => {
|
|
296
404
|
const disposeListener = ctx.on('user-questions/request', (request, next) => {
|
|
297
405
|
const ownership = resolveInteractionOwnership({
|
|
406
|
+
webAnswersInteractions: resolved.preferWebAnswerer && ctx.typertGateway.hasLiveClient(),
|
|
298
407
|
hasExtensionConnection: server.hasConnection(),
|
|
299
408
|
clientSupports: server.clientSupportsQuestions(),
|
|
409
|
+
uiAttached: server.uiAttached(),
|
|
410
|
+
activeSource: activity.sourceOf(request.agent?.id),
|
|
300
411
|
sessionId: request.agent?.id,
|
|
301
412
|
sources: ownershipSources,
|
|
302
413
|
parentOf,
|
|
@@ -305,7 +416,16 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
305
416
|
logDelegation('user-questions', request.agent?.id, ownership.reason)
|
|
306
417
|
return next()
|
|
307
418
|
}
|
|
308
|
-
return questions.ask(
|
|
419
|
+
return questions.ask(
|
|
420
|
+
ownership.sessionId,
|
|
421
|
+
request.questions,
|
|
422
|
+
next,
|
|
423
|
+
request.signal,
|
|
424
|
+
{
|
|
425
|
+
agentId: request.agent?.id,
|
|
426
|
+
...(request.wait === undefined ? {} : { wait: request.wait }),
|
|
427
|
+
},
|
|
428
|
+
)
|
|
309
429
|
}, { prepend: true })
|
|
310
430
|
return () => {
|
|
311
431
|
disposeListener()
|
|
@@ -318,8 +438,11 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
318
438
|
ctx.effect(() => {
|
|
319
439
|
const disposeListener = ctx.on('approval/request', (request, next) => {
|
|
320
440
|
const ownership = resolveInteractionOwnership({
|
|
441
|
+
webAnswersInteractions: resolved.preferWebAnswerer && ctx.typertGateway.hasLiveClient(),
|
|
321
442
|
hasExtensionConnection: server.hasConnection(),
|
|
322
443
|
clientSupports: server.clientSupportsApprovals(),
|
|
444
|
+
uiAttached: server.uiAttached(),
|
|
445
|
+
activeSource: activity.sourceOf(request.agent?.id),
|
|
323
446
|
sessionId: request.agent?.id,
|
|
324
447
|
sources: ownershipSources,
|
|
325
448
|
parentOf,
|
|
@@ -352,7 +475,10 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
352
475
|
// token inside `hello`, so its two paths must bypass the web app's route/auth
|
|
353
476
|
// fence and stay reachable from a `moz-extension://` origin. The allow is
|
|
354
477
|
// scoped to exactly these paths; every other route keeps the host policy.
|
|
355
|
-
ctx.effect(() => ctx.on('webserver/authorize', (request) => {
|
|
478
|
+
ctx.effect(() => ctx.on('webserver/authorize', (request, policy) => {
|
|
479
|
+
// Never override an explicit deny from another listener: our allow is
|
|
480
|
+
// scoped to the bridge's own paths, not a blanket override.
|
|
481
|
+
if (policy === 'deny') return undefined
|
|
356
482
|
const path = request.url.pathname
|
|
357
483
|
return path === BRIDGE_PATH || path === BRIDGE_CONFIG_PATH
|
|
358
484
|
? { kind: 'allow' as const }
|
|
@@ -393,6 +519,21 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
|
|
393
519
|
}
|
|
394
520
|
ctx.effect(() => ctx.webServer.register(configRoute), 'bridge-browser: /ext/bridge-config route')
|
|
395
521
|
|
|
522
|
+
// Discovery beacon: a Desktop host on an ephemeral port still advertises a
|
|
523
|
+
// stable address (borrowed from natgurlain/dsh-browser-agent, MIT).
|
|
524
|
+
if (resolved.discoveryBeacon) {
|
|
525
|
+
ctx.effect(async () => {
|
|
526
|
+
const beacon = await startDiscoveryBeacon(
|
|
527
|
+
() => ctx.webServer.port,
|
|
528
|
+
undefined,
|
|
529
|
+
message => { ctx.logger.warn(message) },
|
|
530
|
+
)
|
|
531
|
+
if (beacon === undefined) return () => {}
|
|
532
|
+
ctx.logger.info(`browser bridge: discovery beacon listening on ${beacon.port}`)
|
|
533
|
+
return () => { void beacon.close() }
|
|
534
|
+
}, 'bridge-browser: discovery beacon')
|
|
535
|
+
}
|
|
536
|
+
|
|
396
537
|
ctx.effect(() => {
|
|
397
538
|
const disposers = registerBrowserTools(ctx, server, {
|
|
398
539
|
toolTimeoutMs: resolved.toolTimeoutMs,
|
package/src/protocol.ts
CHANGED
|
@@ -24,9 +24,55 @@ export const BRIDGE_PATH = '/ext/bridge'
|
|
|
24
24
|
/** Zero-config discovery endpoint: returns `{ wsUrl }` for the extension. */
|
|
25
25
|
export const BRIDGE_CONFIG_PATH = '/ext/bridge-config'
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Fixed discovery beacons. A dsh Desktop host may bind its real webserver on
|
|
29
|
+
* an ephemeral port (`--port 0`); the bridge binds the first free port in this
|
|
30
|
+
* range and answers {@link BRIDGE_CONFIG_PATH} with the real ws URL. This
|
|
31
|
+
* borrows the approach used by `natgurlain/dsh-browser-agent` (MIT).
|
|
32
|
+
*
|
|
33
|
+
* The extension already lists 43189 as a legacy probe; 43190–43198 extend it.
|
|
34
|
+
*/
|
|
35
|
+
export const BEACON_PORTS = [43189, 43190, 43191, 43192, 43193, 43194, 43195, 43196, 43197, 43198] as const
|
|
36
|
+
|
|
37
|
+
/** Payload the config endpoint (real bridge and discovery beacon) returns. */
|
|
38
|
+
export interface BridgeConfigPayload {
|
|
39
|
+
wsUrl: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Parse one bridge-config response body. */
|
|
43
|
+
export function parseBridgeConfigPayload(value: unknown): BridgeConfigPayload | undefined {
|
|
44
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
|
|
45
|
+
const wsUrl = (value as { wsUrl?: unknown }).wsUrl
|
|
46
|
+
return typeof wsUrl === 'string' && wsUrl.length > 0 ? { wsUrl } : undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
27
49
|
/** Seconds a fresh socket may take to present `hello` before it is closed. */
|
|
28
50
|
export const HELLO_TIMEOUT_MS = 5_000
|
|
29
51
|
|
|
52
|
+
/**
|
|
53
|
+
* Wire-protocol generation. Bumped only for a change an older peer cannot
|
|
54
|
+
* ignore safely: a client that does not understand a new frame type fails to
|
|
55
|
+
* parse it, and the bridge closes the socket as `unparseable frame`.
|
|
56
|
+
*
|
|
57
|
+
* - 1: 0.4.x/0.5.x — hello/rpc/stream/tool/question/approval frames.
|
|
58
|
+
* - 2: 0.5.2 — adds the `ui.attached` client frame (panel presence).
|
|
59
|
+
*
|
|
60
|
+
* Both ends stay on one generation: the plugin ignores the frame from an older
|
|
61
|
+
* client (which never sends it), and the client only sends it after `hello.ok`
|
|
62
|
+
* names a generation that understands it.
|
|
63
|
+
*/
|
|
64
|
+
export const BRIDGE_PROTOCOL_VERSION = 2
|
|
65
|
+
|
|
66
|
+
/** Close codes the bridge uses, so a client can tell why a socket ended. */
|
|
67
|
+
export const BRIDGE_CLOSE_CODES = {
|
|
68
|
+
/** A newer authenticated connection replaced this one (do not reconnect). */
|
|
69
|
+
replaced: 4000,
|
|
70
|
+
/** No `hello` arrived inside {@link HELLO_TIMEOUT_MS}. */
|
|
71
|
+
helloTimeout: 4001,
|
|
72
|
+
/** The bearer token was missing or wrong. */
|
|
73
|
+
badToken: 4002,
|
|
74
|
+
} as const
|
|
75
|
+
|
|
30
76
|
/** Server-side ping cadence; the client answers `pong` to prove liveness. */
|
|
31
77
|
export const PING_INTERVAL_MS = 30_000
|
|
32
78
|
|
|
@@ -70,6 +116,8 @@ export interface BridgeCaps {
|
|
|
70
116
|
questions?: boolean
|
|
71
117
|
/** Client advertises it can render host approval (permission) cards; the plugin only claims the approval waterfall for extension-owned sessions when set. */
|
|
72
118
|
approvals?: boolean
|
|
119
|
+
/** Client advertises it understands the `ui.attached` frame (0.5.2+); absent means the bridge cannot tell whether a panel is open. */
|
|
120
|
+
panelPresence?: boolean
|
|
73
121
|
}
|
|
74
122
|
|
|
75
123
|
/** One Remote failure as plain wire data (RemoteError's message is non-enumerable, so it is restated explicitly). */
|
|
@@ -90,6 +138,9 @@ export interface QuestionOption {
|
|
|
90
138
|
description?: string
|
|
91
139
|
}
|
|
92
140
|
|
|
141
|
+
/** Most questions one card may carry (the host never asks more in practice; this bounds a hostile frame). */
|
|
142
|
+
export const MAX_QUESTIONS_PER_CARD = 50
|
|
143
|
+
|
|
93
144
|
/**
|
|
94
145
|
* One ask_user_question item as it crosses the bridge (the host
|
|
95
146
|
* AskUserQuestionItem wire form, minus the host-internal `intent`).
|
|
@@ -107,6 +158,14 @@ export interface QuestionItem {
|
|
|
107
158
|
export type ClientFrame =
|
|
108
159
|
/** 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. */
|
|
109
160
|
| { t: 'hello'; token: string; caps: BridgeCaps; version?: string }
|
|
161
|
+
/**
|
|
162
|
+
* A side panel opened (`attached: true`) or the last one closed
|
|
163
|
+
* (`attached: false`). The bridge claims a host interaction waterfall only
|
|
164
|
+
* while a panel is attached, so a closed sidebar can never leave a card that
|
|
165
|
+
* nobody can see. Sent only to a plugin that advertises
|
|
166
|
+
* {@link BridgeCaps.panelPresence}.
|
|
167
|
+
*/
|
|
168
|
+
| { t: 'ui.attached'; attached: boolean }
|
|
110
169
|
/** Unary Remote call: slash-joined endpoint plus the descriptor's native args object. */
|
|
111
170
|
| { t: 'rpc'; id: string; method: string; args: Record<string, unknown> }
|
|
112
171
|
/** Open one Remote stream (`session/follow`, `workspace/follow`); frames arrive as `stream.frame`. */
|
|
@@ -122,7 +181,7 @@ export type ClientFrame =
|
|
|
122
181
|
/** Frames sent by the bridge plugin to the extension. */
|
|
123
182
|
export type ServerFrame =
|
|
124
183
|
/** Accepted after a valid `hello`. `version` (plugin version) lets the extension detect a version mismatch; absent on pre-0.4.6 servers. */
|
|
125
|
-
| { t: 'hello.ok'; caps: BridgeCaps; version?: string }
|
|
184
|
+
| { t: 'hello.ok'; caps: BridgeCaps; version?: string; protocolVersion?: number }
|
|
126
185
|
/** Reply to an `rpc` frame: the RemoteResult wire form, flattened onto the frame. */
|
|
127
186
|
| { t: 'rpc.result'; id: string; ok: true; value: unknown }
|
|
128
187
|
| { t: 'rpc.result'; id: string; ok: false; error: RemoteWireFailure }
|
|
@@ -195,6 +254,7 @@ export function isServerFrame(frame: BridgeFrame): frame is ServerFrame {
|
|
|
195
254
|
*/
|
|
196
255
|
export function isClientFrame(frame: BridgeFrame): frame is ClientFrame {
|
|
197
256
|
return frame.t === 'hello'
|
|
257
|
+
|| frame.t === 'ui.attached'
|
|
198
258
|
|| frame.t === 'rpc'
|
|
199
259
|
|| frame.t === 'stream.open'
|
|
200
260
|
|| frame.t === 'stream.close'
|
|
@@ -232,6 +292,8 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
232
292
|
caps: frame.caps,
|
|
233
293
|
...(frame.version === undefined ? {} : { version: frame.version as string }),
|
|
234
294
|
}
|
|
295
|
+
case 'ui.attached':
|
|
296
|
+
return typeof frame.attached === 'boolean' ? { t: 'ui.attached', attached: frame.attached } : undefined
|
|
235
297
|
case 'rpc':
|
|
236
298
|
return typeof frame.id === 'string' && typeof frame.method === 'string' && isArgs(frame.args)
|
|
237
299
|
? { t: 'rpc', id: frame.id, method: frame.method, args: frame.args }
|
|
@@ -255,9 +317,12 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
255
317
|
case 'hello.ok':
|
|
256
318
|
if (!isCaps(frame.caps)) return undefined
|
|
257
319
|
if (frame.version !== undefined && typeof frame.version !== 'string') return undefined
|
|
320
|
+
if (frame.protocolVersion !== undefined
|
|
321
|
+
&& (typeof frame.protocolVersion !== 'number' || !Number.isInteger(frame.protocolVersion) || frame.protocolVersion < 1)) return undefined
|
|
258
322
|
return {
|
|
259
323
|
t: 'hello.ok',
|
|
260
324
|
caps: frame.caps,
|
|
325
|
+
...(typeof frame.protocolVersion === 'number' ? { protocolVersion: frame.protocolVersion } : {}),
|
|
261
326
|
...(frame.version === undefined ? {} : { version: frame.version as string }),
|
|
262
327
|
}
|
|
263
328
|
case 'rpc.result':
|
|
@@ -299,6 +364,7 @@ export function parseBridgeFrame(text: string): BridgeFrame | undefined {
|
|
|
299
364
|
&& typeof frame.sessionId === 'string'
|
|
300
365
|
&& Array.isArray(frame.questions)
|
|
301
366
|
&& frame.questions.length > 0
|
|
367
|
+
&& frame.questions.length <= MAX_QUESTIONS_PER_CARD
|
|
302
368
|
&& frame.questions.every(isQuestionItem)
|
|
303
369
|
? { t: 'question.requested', id: frame.id, sessionId: frame.sessionId, questions: frame.questions }
|
|
304
370
|
: undefined
|
|
@@ -344,6 +410,7 @@ function isCaps(value: unknown): value is BridgeCaps {
|
|
|
344
410
|
&& typeof caps.maxInteractiveItems === 'number' && caps.maxInteractiveItems > 0
|
|
345
411
|
&& (caps.questions === undefined || typeof caps.questions === 'boolean')
|
|
346
412
|
&& (caps.approvals === undefined || typeof caps.approvals === 'boolean')
|
|
413
|
+
&& (caps.panelPresence === undefined || typeof caps.panelPresence === 'boolean')
|
|
347
414
|
}
|
|
348
415
|
|
|
349
416
|
/** Narrow one question item; unknown extra keys (e.g. host `intent`) pass through. */
|
package/src/questions.ts
CHANGED
|
@@ -9,10 +9,19 @@
|
|
|
9
9
|
* model is told the user refused);
|
|
10
10
|
* - the host aborts `request.signal` (turn cancelled, session disposed) →
|
|
11
11
|
* the extension is sent `question.resolved` and the waterfall rejects;
|
|
12
|
+
* - nobody answers inside the configured budget ({@link answerTimeoutMs}) →
|
|
13
|
+
* the extension is sent `question.resolved` and the waterfall rejects with
|
|
14
|
+
* the host's `ASK_TIMED_OUT` code, so a forgotten card can never hold a
|
|
15
|
+
* turn forever;
|
|
12
16
|
* - the bridge connection drops ({@link delegateAll}) → the waterfall is
|
|
13
17
|
* delegated to `next()` so another answerer (dsh web) can still serve it;
|
|
14
18
|
* - plugin unload ({@link dispose}) → everything rejects promptly.
|
|
15
19
|
*
|
|
20
|
+
* A **timed** ask (`request.wait`) additionally holds the host's foreground
|
|
21
|
+
* wait through `userQuestions/attachWait` for as long as the card lives: the
|
|
22
|
+
* host only pauses its own countdown while some answer UI claims the wait, so
|
|
23
|
+
* without the claim the sidebar's card would be withdrawn mid-typing.
|
|
24
|
+
*
|
|
16
25
|
* @module
|
|
17
26
|
*/
|
|
18
27
|
|
|
@@ -50,25 +59,51 @@ type PendingOutcome =
|
|
|
50
59
|
| { kind: 'reject'; error: Error }
|
|
51
60
|
| { kind: 'delegate' }
|
|
52
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Build an error the host's `restoreUserQuestionError` recognises (it
|
|
64
|
+
* duck-types on `name` + `code`, so no runtime import of the service package is
|
|
65
|
+
* needed). Without the name the host would fold our rejection into a generic
|
|
66
|
+
* `PROVIDER_ERROR`, and the model would read "the answerer failed" instead of
|
|
67
|
+
* what the user actually did.
|
|
68
|
+
*/
|
|
69
|
+
function questionError(message: string, code: string): Error {
|
|
70
|
+
const error = new Error(message)
|
|
71
|
+
error.name = 'UserQuestionError'
|
|
72
|
+
;(error as Error & { code?: string }).code = code
|
|
73
|
+
return error
|
|
74
|
+
}
|
|
75
|
+
|
|
53
76
|
/** Error matching the host's ASK_ABORTED semantics (the service remaps it). */
|
|
54
77
|
function abortedError(): Error {
|
|
55
|
-
return
|
|
78
|
+
return questionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED')
|
|
56
79
|
}
|
|
57
80
|
|
|
58
81
|
function declinedError(): Error {
|
|
59
|
-
return
|
|
82
|
+
return questionError('ask_user_question was declined by the user in the browser sidebar', 'ASK_DECLINED')
|
|
60
83
|
}
|
|
61
84
|
|
|
62
|
-
/**
|
|
85
|
+
/** The user never answered inside the bridge's budget (the host maps this to a pending result). */
|
|
86
|
+
function timedOutError(): Error {
|
|
87
|
+
return questionError('ask_user_question timed out before the user answered', 'ASK_TIMED_OUT')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Structural validation of the extension's answer payload. The host promises
|
|
92
|
+
* one item per question, so a partial or duplicated batch is refused here
|
|
93
|
+
* rather than handed to the model as a half answer.
|
|
94
|
+
*/
|
|
63
95
|
export function asAnswerPayload(value: unknown, questionIds: ReadonlySet<string>): QuestionAnswerPayload | undefined {
|
|
64
96
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
|
|
65
97
|
const answers = (value as { answers?: unknown }).answers
|
|
66
98
|
if (!Array.isArray(answers)) return undefined
|
|
67
99
|
const items: QuestionAnswerItem[] = []
|
|
100
|
+
const seen = new Set<string>()
|
|
68
101
|
for (const entry of answers) {
|
|
69
102
|
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return undefined
|
|
70
103
|
const item = entry as Record<string, unknown>
|
|
71
104
|
if (typeof item.id !== 'string' || !questionIds.has(item.id)) return undefined
|
|
105
|
+
if (seen.has(item.id)) return undefined
|
|
106
|
+
seen.add(item.id)
|
|
72
107
|
if (!Array.isArray(item.selected) || item.selected.some(option => typeof option !== 'string')) return undefined
|
|
73
108
|
if (item.custom !== undefined && typeof item.custom !== 'string') return undefined
|
|
74
109
|
items.push({
|
|
@@ -77,6 +112,7 @@ export function asAnswerPayload(value: unknown, questionIds: ReadonlySet<string>
|
|
|
77
112
|
...(typeof item.custom === 'string' ? { custom: item.custom } : {}),
|
|
78
113
|
})
|
|
79
114
|
}
|
|
115
|
+
if (items.length !== questionIds.size) return undefined
|
|
80
116
|
return { answers: items }
|
|
81
117
|
}
|
|
82
118
|
|
|
@@ -91,11 +127,20 @@ export function asQuestionAnswerArgs(value: unknown): QuestionAnswerArgs | undef
|
|
|
91
127
|
|
|
92
128
|
/** Owns the user-questions waterfall for extension-driven sessions. */
|
|
93
129
|
export class QuestionBridge {
|
|
94
|
-
private readonly waterfalls = new PendingWaterfalls<PendingOutcome, ReadonlySet<string
|
|
130
|
+
private readonly waterfalls = new PendingWaterfalls<PendingOutcome, { questionIds: ReadonlySet<string>; questions: QuestionItem[] }>()
|
|
95
131
|
|
|
96
132
|
constructor(private readonly deps: {
|
|
97
133
|
/** Push one server frame to the connected extension (must tolerate a dead socket). */
|
|
98
134
|
push: (frame: ServerFrame) => void
|
|
135
|
+
/**
|
|
136
|
+
* Hold the host's foreground wait for one timed ask while the sidebar owns
|
|
137
|
+
* the card. Returns the release function, or undefined when the host offers
|
|
138
|
+
* no such stream. The bridge never throws when this fails: losing the claim
|
|
139
|
+
* only means the host's own countdown keeps running.
|
|
140
|
+
*/
|
|
141
|
+
attachWait?: (agentId: string, callId: string, signal: AbortSignal) => (() => void) | undefined
|
|
142
|
+
/** How long a card may sit unanswered before it settles as timed out; 0/undefined disables the budget. */
|
|
143
|
+
answerTimeoutMs?: number
|
|
99
144
|
}) {}
|
|
100
145
|
|
|
101
146
|
/**
|
|
@@ -106,6 +151,7 @@ export class QuestionBridge {
|
|
|
106
151
|
* @param questions - host question items (forwarded verbatim).
|
|
107
152
|
* @param next - waterfall delegation, used when the bridge connection drops.
|
|
108
153
|
* @param signal - host cancellation lifetime for this request.
|
|
154
|
+
* @param options - timed-ask bookkeeping (`request.wait`) and the asking agent.
|
|
109
155
|
* @returns the user's answer.
|
|
110
156
|
*/
|
|
111
157
|
ask(
|
|
@@ -113,11 +159,26 @@ export class QuestionBridge {
|
|
|
113
159
|
questions: QuestionItem[],
|
|
114
160
|
next: () => Promise<QuestionAnswerPayload>,
|
|
115
161
|
signal?: AbortSignal,
|
|
162
|
+
options?: { agentId?: string | undefined; wait?: { callId: string; timed?: boolean } },
|
|
116
163
|
): Promise<QuestionAnswerPayload> {
|
|
117
164
|
if (signal?.aborted) return Promise.reject(abortedError())
|
|
118
165
|
const questionId = randomUUID()
|
|
119
166
|
const questionIds = new Set(questions.map(question => question.id))
|
|
167
|
+
const payload = { questionIds, questions }
|
|
120
168
|
return new Promise<QuestionAnswerPayload>((resolve, reject) => {
|
|
169
|
+
let timer: NodeJS.Timeout | undefined
|
|
170
|
+
let releaseWait: (() => void) | undefined
|
|
171
|
+
const cleanup = (): void => {
|
|
172
|
+
if (timer !== undefined) {
|
|
173
|
+
clearTimeout(timer)
|
|
174
|
+
timer = undefined
|
|
175
|
+
}
|
|
176
|
+
if (releaseWait !== undefined) {
|
|
177
|
+
const release = releaseWait
|
|
178
|
+
releaseWait = undefined
|
|
179
|
+
try { release() } catch { /* the host stream is already gone */ }
|
|
180
|
+
}
|
|
181
|
+
}
|
|
121
182
|
const settle = (outcome: PendingOutcome): void => {
|
|
122
183
|
this.waterfalls.settle(questionId, outcome)
|
|
123
184
|
}
|
|
@@ -125,11 +186,19 @@ export class QuestionBridge {
|
|
|
125
186
|
id: questionId,
|
|
126
187
|
sessionId,
|
|
127
188
|
signal,
|
|
128
|
-
payload
|
|
189
|
+
payload,
|
|
129
190
|
complete: (outcome) => {
|
|
191
|
+
cleanup()
|
|
130
192
|
if (outcome.kind === 'answer') resolve(outcome.answer)
|
|
131
193
|
else if (outcome.kind === 'reject') reject(outcome.error)
|
|
132
|
-
|
|
194
|
+
// `next()` may throw synchronously (a mis-scoped listener does); the
|
|
195
|
+
// promise chain keeps that inside the caller's rejection instead of
|
|
196
|
+
// letting it escape into the socket's close listener.
|
|
197
|
+
else Promise.resolve().then(next).then(resolve, reject)
|
|
198
|
+
},
|
|
199
|
+
fail: (error) => {
|
|
200
|
+
cleanup()
|
|
201
|
+
reject(error instanceof Error ? error : new Error(String(error)))
|
|
133
202
|
},
|
|
134
203
|
onAbort: () => {
|
|
135
204
|
// Tell the extension to drop the card before settling so a late
|
|
@@ -138,6 +207,36 @@ export class QuestionBridge {
|
|
|
138
207
|
settle({ kind: 'reject', error: abortedError() })
|
|
139
208
|
},
|
|
140
209
|
})
|
|
210
|
+
// Hold the host's timed foreground wait: while a claim exists the host
|
|
211
|
+
// pauses its countdown, so the card survives however long the user takes.
|
|
212
|
+
const wait = options?.wait
|
|
213
|
+
const agentId = options?.agentId
|
|
214
|
+
if (wait !== undefined && agentId !== undefined && this.deps.attachWait !== undefined) {
|
|
215
|
+
const claim = new AbortController()
|
|
216
|
+
try {
|
|
217
|
+
releaseWait = this.deps.attachWait(agentId, wait.callId, claim.signal)
|
|
218
|
+
} catch {
|
|
219
|
+
releaseWait = undefined
|
|
220
|
+
}
|
|
221
|
+
if (releaseWait !== undefined) {
|
|
222
|
+
const release = releaseWait
|
|
223
|
+
releaseWait = () => {
|
|
224
|
+
claim.abort()
|
|
225
|
+
release()
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const budget = this.deps.answerTimeoutMs
|
|
230
|
+
if (budget !== undefined && budget > 0) {
|
|
231
|
+
timer = setTimeout(() => {
|
|
232
|
+
// A card nobody answers must not hold the turn: withdraw it and let
|
|
233
|
+
// the host settle the tool call (a timed ask becomes a pending
|
|
234
|
+
// result, a blocking ask fails with the same code).
|
|
235
|
+
this.deps.push({ t: 'question.resolved', id: questionId, sessionId })
|
|
236
|
+
settle({ kind: 'reject', error: timedOutError() })
|
|
237
|
+
}, budget)
|
|
238
|
+
timer.unref?.()
|
|
239
|
+
}
|
|
141
240
|
this.deps.push({ t: 'question.requested', id: questionId, sessionId, questions })
|
|
142
241
|
})
|
|
143
242
|
}
|
|
@@ -154,7 +253,7 @@ export class QuestionBridge {
|
|
|
154
253
|
this.waterfalls.settle(args.questionId, { kind: 'reject', error: declinedError() })
|
|
155
254
|
return { accepted: true }
|
|
156
255
|
}
|
|
157
|
-
const answer = asAnswerPayload(args.answer, this.waterfalls.payloadOf(args.questionId) ?? new Set())
|
|
256
|
+
const answer = asAnswerPayload(args.answer, this.waterfalls.payloadOf(args.questionId)?.questionIds ?? new Set())
|
|
158
257
|
if (answer === undefined) return { accepted: false, reason: 'bad-answer' }
|
|
159
258
|
this.waterfalls.settle(args.questionId, { kind: 'answer', answer })
|
|
160
259
|
return { accepted: true }
|
|
@@ -162,7 +261,28 @@ export class QuestionBridge {
|
|
|
162
261
|
|
|
163
262
|
/** Bridge connection replaced/closed: delegate every unsettled question. */
|
|
164
263
|
delegateAll(): void {
|
|
165
|
-
for (const id of this.waterfalls.ids())
|
|
264
|
+
for (const id of this.waterfalls.ids()) {
|
|
265
|
+
// Withdraw the card first: the extension's replay cache keeps a push
|
|
266
|
+
// until it sees the matching resolution, so delegating silently would
|
|
267
|
+
// leave a card that can only answer `not-pending`.
|
|
268
|
+
const sessionId = this.waterfalls.sessionOf(id)
|
|
269
|
+
if (sessionId !== undefined) this.deps.push({ t: 'question.resolved', id, sessionId })
|
|
270
|
+
this.waterfalls.settle(id, { kind: 'delegate' })
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* A new authenticated connection is taking over: re-push every still-pending
|
|
276
|
+
* card so the fresh panel can answer it. The extension clears its replay
|
|
277
|
+
* cache on `connecting`, so without this the card would simply vanish.
|
|
278
|
+
*/
|
|
279
|
+
replay(): void {
|
|
280
|
+
for (const id of this.waterfalls.ids()) {
|
|
281
|
+
const entry = this.waterfalls.payloadOf(id)
|
|
282
|
+
const sessionId = this.waterfalls.sessionOf(id)
|
|
283
|
+
if (entry === undefined || sessionId === undefined) continue
|
|
284
|
+
this.deps.push({ t: 'question.requested', id, sessionId, questions: entry.questions })
|
|
285
|
+
}
|
|
166
286
|
}
|
|
167
287
|
|
|
168
288
|
/** Plugin unload: reject everything so no tool call outlives the plugin. */
|