dsh-browser-firefox 0.4.6 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -31,6 +31,7 @@ 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'
34
35
  import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
35
36
  import { readFileSync } from 'node:fs'
36
37
  import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
@@ -40,8 +41,9 @@ import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, type RemoteWireResult } from './protoc
40
41
  import { withSessionDeferral } from './session-deferral.ts'
41
42
  import { withSessionWorkspace, type RpcDispatch } from './session-workspace.ts'
42
43
  import { resolveToken } from './token.ts'
43
- import { ExtensionSessionRegistry, shouldBridgeOwnQuestion } from './extension-sessions.ts'
44
+ import { ExtensionSessionRegistry, FollowedSessions, resolveInteractionOwnership, type DelegateReason } from './extension-sessions.ts'
44
45
  import { asQuestionAnswerArgs, QuestionBridge } from './questions.ts'
46
+ import { ApprovalBridge, asApprovalDecisionArgs } from './approvals.ts'
45
47
 
46
48
  /** Cordis plugin name used by loader diagnostics. */
47
49
  export const name = 'bridge-browser'
@@ -106,6 +108,22 @@ function sessionIdOf(value: unknown): string | undefined {
106
108
  return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined
107
109
  }
108
110
 
111
+ /**
112
+ * Human-readable approval reason: the asker's localized text when present
113
+ * (zh first, then en), otherwise the raw reason string.
114
+ *
115
+ * @param request - pending host approval request.
116
+ * @returns display text, or undefined when the asker supplied none.
117
+ */
118
+ function approvalReasonText(request: ApprovalRequestEvent): string | undefined {
119
+ const display = request.displayReason
120
+ if (display !== undefined) {
121
+ const localized = display.zh ?? display['zh-Hans'] ?? display.en
122
+ if (typeof localized === 'string' && localized.length > 0) return localized
123
+ }
124
+ return typeof request.reason === 'string' && request.reason.length > 0 ? request.reason : undefined
125
+ }
126
+
109
127
  /**
110
128
  * Apply defaults and direct-call validation at the plugin boundary.
111
129
  * @param config - Loader-resolved or directly supplied plugin configuration.
@@ -163,17 +181,36 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
163
181
  ),
164
182
  resolved.deferSessionCreate,
165
183
  )
166
- // Ownership tracking for the user-questions waterfall: a session becomes
167
- // extension-owned only after a create/prompt SUCCEEDS — a failed prompt
168
- // against a desktop session must not steal its questions away from the
169
- // native answerer.
184
+ // Ownership tracking for the interaction waterfalls (ask_user_question and
185
+ // host approvals). A session becomes extension-owned when a create/prompt is
186
+ // DISPATCHED over the bridge (noted optimistically so a question asked
187
+ // during the very first turn still finds an owner) and is released again
188
+ // when the dispatch fails hard — a failed prompt against a desktop session
189
+ // must not steal its cards away from the native answerer.
170
190
  const extensionSessions = new ExtensionSessionRegistry()
191
+ const followedSessions = new FollowedSessions()
192
+ const ownershipSources = { driven: extensionSessions, followed: followedSessions }
193
+ // Subagent child sessions inherit their parent's ownership: a question asked
194
+ // by a delegated agent belongs in the conversation the user is watching.
195
+ const sessions = ctx.get('sessions')
196
+ const parentOf = sessions === undefined
197
+ ? undefined
198
+ : (sessionId: string): string | undefined => sessions.get(sessionId as never)?.header.parentSession
171
199
  const notingDispatchRpc: RpcDispatch = async (method, args, signal) => {
200
+ const tracksOwnership = method === 'session/create' || method === 'session/prompt'
201
+ const dispatched = tracksOwnership ? sessionIdOf(args.request) : undefined
202
+ if (dispatched !== undefined) extensionSessions.note(dispatched)
172
203
  const result = await dispatchRpc(method, args, signal)
173
- if (result.ok && (method === 'session/create' || method === 'session/prompt')) {
174
- extensionSessions.note(sessionIdOf(args.request))
175
- extensionSessions.note(sessionIdOf(result.value))
204
+ if (!result.ok) {
205
+ // Only a lookup failure disproves the optimistic note (the session does
206
+ // not exist); transient failures keep the session extension-owned.
207
+ const code = result.error.code
208
+ if (dispatched !== undefined && (code.includes('not-found') || code.includes('session-invalid'))) {
209
+ extensionSessions.forget(dispatched)
210
+ }
211
+ return result
176
212
  }
213
+ if (tracksOwnership) extensionSessions.note(sessionIdOf(result.value))
177
214
  return result
178
215
  }
179
216
  // Plugin version for the hello.ok handshake (extension flags a mismatch in
@@ -190,6 +227,9 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
190
227
  // Late-bound through the closure: server is constructed right below.
191
228
  push: (frame) => { server.push(frame) },
192
229
  })
230
+ const approvals = new ApprovalBridge({
231
+ push: (frame) => { server.push(frame) },
232
+ })
193
233
  const server = new BridgeServer({
194
234
  token: tokenRes.token,
195
235
  dispatchRpc: notingDispatchRpc,
@@ -205,7 +245,20 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
205
245
  ? { accepted: false, reason: 'bad-answer' }
206
246
  : questions.answer(parsed)
207
247
  },
208
- onConnectionLost: () => { questions.delegateAll() },
248
+ answerApproval: (args) => {
249
+ const parsed = asApprovalDecisionArgs(args)
250
+ return parsed === undefined
251
+ ? { accepted: false, reason: 'bad-decision' }
252
+ : approvals.decide(parsed)
253
+ },
254
+ onConnectionLost: () => {
255
+ questions.delegateAll()
256
+ approvals.delegateAll()
257
+ },
258
+ onFollowChanged: (sessionId, open) => {
259
+ if (open) followedSessions.open(sessionId)
260
+ else followedSessions.close(sessionId)
261
+ },
209
262
  version: pluginVersion,
210
263
  onVersionMismatch: (clientVersion) => {
211
264
  ctx.logger.warn(`browser extension version ${clientVersion} != plugin version ${pluginVersion ?? '?'}; both components must be updated together`)
@@ -218,22 +271,29 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
218
271
  })
219
272
 
220
273
  // Sidebar ask_user_question: claim the waterfall only for sessions the
221
- // extension owns (created or prompted over the bridge) while a
222
- // question-capable extension is connected; everything else keeps the
223
- // native answerer chain (dsh web). Prepended so the claim runs before the
224
- // Remote event forwarding listener in dsh-api-remotes.
274
+ // extension owns (driven over the bridge, currently followed, or a subagent
275
+ // child of an owned session) while a question-capable extension is
276
+ // connected; everything else keeps the native answerer chain (dsh web).
277
+ // Prepended so the claim runs before the Remote event forwarding listener
278
+ // in dsh-api-remotes. Delegations are logged with the failing gate so an
279
+ // "invisible card" report is diagnosable from the host log.
280
+ const logDelegation = (kind: 'user-questions' | 'approval', sessionId: string | undefined, reason: DelegateReason): void => {
281
+ ctx.logger.info(`browser bridge: delegated ${kind} for session ${sessionId ?? '<unknown>'} (${reason})`)
282
+ }
225
283
  ctx.effect(() => {
226
284
  const disposeListener = ctx.on('user-questions/request', (request, next) => {
227
- const sessionId = request.agent?.id
228
- if (sessionId === undefined || !shouldBridgeOwnQuestion({
285
+ const ownership = resolveInteractionOwnership({
229
286
  hasExtensionConnection: server.hasConnection(),
230
- clientSupportsQuestions: server.clientSupportsQuestions(),
231
- sessionId,
232
- extensionSessions,
233
- })) {
287
+ clientSupports: server.clientSupportsQuestions(),
288
+ sessionId: request.agent?.id,
289
+ sources: ownershipSources,
290
+ ...(parentOf === undefined ? {} : { parentOf }),
291
+ })
292
+ if (!ownership.owned) {
293
+ logDelegation('user-questions', request.agent?.id, ownership.reason)
234
294
  return next()
235
295
  }
236
- return questions.ask(sessionId, request.questions, next, request.signal)
296
+ return questions.ask(ownership.sessionId, request.questions, next, request.signal)
237
297
  }, { prepend: true })
238
298
  return () => {
239
299
  disposeListener()
@@ -241,6 +301,38 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
241
301
  }
242
302
  }, 'bridge-browser: user-questions answerer')
243
303
 
304
+ // Host approvals (a hooked tool call / permission ask): same ownership rule,
305
+ // same sidebar surface, so the user is not sent to dsh web for a decision.
306
+ ctx.effect(() => {
307
+ const disposeListener = ctx.on('approval/request', (request, next) => {
308
+ const ownership = resolveInteractionOwnership({
309
+ hasExtensionConnection: server.hasConnection(),
310
+ clientSupports: server.clientSupportsApprovals(),
311
+ sessionId: request.agent?.id,
312
+ sources: ownershipSources,
313
+ ...(parentOf === undefined ? {} : { parentOf }),
314
+ })
315
+ if (!ownership.owned) {
316
+ logDelegation('approval', request.agent?.id, ownership.reason)
317
+ return next()
318
+ }
319
+ return approvals.ask(
320
+ ownership.sessionId,
321
+ {
322
+ toolName: request.toolName,
323
+ ...(typeof request.callId === 'string' ? { callId: request.callId } : {}),
324
+ ...(approvalReasonText(request) === undefined ? {} : { reason: approvalReasonText(request) as string }),
325
+ },
326
+ next,
327
+ request.signal,
328
+ )
329
+ }, { prepend: true })
330
+ return () => {
331
+ disposeListener()
332
+ approvals.dispose()
333
+ }
334
+ }, 'bridge-browser: approval answerer')
335
+
244
336
  const route: WebUpgradeRoute = {
245
337
  path: BRIDGE_PATH,
246
338
  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/server.ts CHANGED
@@ -119,6 +119,14 @@ function orderedSessionId(frame: Extract<ClientFrame, { t: 'rpc' }>): string | u
119
119
  return typeof sessionId === 'string' ? sessionId : undefined
120
120
  }
121
121
 
122
+ /** Session id carried by a `session/follow` stream's native args. */
123
+ function followedSessionOf(args: Record<string, unknown>): string | undefined {
124
+ const request = args.request
125
+ if (typeof request !== 'object' || request === null || Array.isArray(request)) return undefined
126
+ const sessionId = (request as Record<string, unknown>).sessionId
127
+ return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined
128
+ }
129
+
122
130
  /** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
123
131
  export function isLoopbackAddress(address: string | undefined): boolean {
124
132
  return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
@@ -161,6 +169,18 @@ export interface BridgeServerDeps {
161
169
  * rpc result value `{accepted: true} | {accepted: false, reason}`.
162
170
  */
163
171
  answerQuestion: (args: Record<string, unknown>) => unknown
172
+ /**
173
+ * Plugin-local endpoint `bridge/approvalDecision`: settle one pending host
174
+ * approval the bridge pushed to this extension. Answered as the rpc result
175
+ * value `{accepted: true} | {accepted: false, reason}`.
176
+ */
177
+ answerApproval: (args: Record<string, unknown>) => unknown
178
+ /**
179
+ * A `session/follow` stream opened (`open: true`) or ended (`open: false`)
180
+ * for a session: the sidebar is displaying that session while the stream
181
+ * lives, so interaction ownership can follow the visible conversation.
182
+ */
183
+ onFollowChanged?: (sessionId: string, open: boolean) => void
164
184
  /** The active connection was replaced or closed (settle pushed questions). */
165
185
  onConnectionLost?: () => void
166
186
  /**
@@ -194,6 +214,8 @@ interface PendingTool {
194
214
  interface OpenStream {
195
215
  abort: AbortController
196
216
  pump: Promise<void>
217
+ /** Session a `session/follow` stream is displaying, for interaction ownership. */
218
+ followedSessionId?: string
197
219
  }
198
220
 
199
221
  /** A socket that passed authentication and owns the single active slot. */
@@ -371,6 +393,11 @@ export class BridgeServer {
371
393
  return this.current?.clientCaps.questions === true
372
394
  }
373
395
 
396
+ /** @returns whether the connected extension advertised approval-card support. */
397
+ clientSupportsApprovals(): boolean {
398
+ return this.current?.clientCaps.approvals === true
399
+ }
400
+
374
401
  /**
375
402
  * Push one unsolicited server frame (question.requested/question.resolved)
376
403
  * to the connected extension. No-op when no extension is connected or the
@@ -546,6 +573,10 @@ export class BridgeServer {
546
573
  sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, value: this.deps.answerQuestion(frame.args) })
547
574
  return
548
575
  }
576
+ if (frame.method === 'bridge/approvalDecision') {
577
+ sendFrame(conn.ws, { t: 'rpc.result', id: frame.id, ok: true, value: this.deps.answerApproval(frame.args) })
578
+ return
579
+ }
549
580
  try {
550
581
  const result = await this.deps.dispatchRpc(frame.method, frame.args, conn.abort.signal)
551
582
  if (result.ok) {
@@ -572,6 +603,10 @@ export class BridgeServer {
572
603
  const ws = conn.ws
573
604
  const abort = new AbortController()
574
605
  conn.abort.signal.addEventListener('abort', () => { abort.abort() }, { once: true })
606
+ // A session/follow stream means the sidebar is displaying this session:
607
+ // report the lifetime so interaction ownership can follow the visible
608
+ // conversation (released in the pump's finally below).
609
+ const followedSessionId = frame.method === 'session/follow' ? followedSessionOf(frame.args) : undefined
575
610
  let pump!: Promise<void>
576
611
  pump = (async () => {
577
612
  let iterator: AsyncIterator<unknown> | undefined
@@ -603,9 +638,15 @@ export class BridgeServer {
603
638
  if (current !== null && current.streams.get(frame.id)?.pump === pump) {
604
639
  current.streams.delete(frame.id)
605
640
  }
641
+ if (followedSessionId !== undefined) this.deps.onFollowChanged?.(followedSessionId, false)
606
642
  }
607
643
  })()
608
- conn.streams.set(frame.id, { abort, pump })
644
+ conn.streams.set(frame.id, {
645
+ abort,
646
+ pump,
647
+ ...(followedSessionId === undefined ? {} : { followedSessionId }),
648
+ })
649
+ if (followedSessionId !== undefined) this.deps.onFollowChanged?.(followedSessionId, true)
609
650
  }
610
651
 
611
652
  /**