dsh-browser-firefox 0.4.0 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/protocol.js CHANGED
@@ -36,7 +36,7 @@ const DEFAULT_TOKEN_BYTES = 32;
36
36
  * @returns true for server-sendable frames.
37
37
  */
38
38
  function isServerFrame(frame) {
39
- return frame.t === "hello.ok" || frame.t === "rpc.result" || frame.t === "stream.frame" || frame.t === "stream.error" || frame.t === "tool.call" || frame.t === "tool.cancel" || frame.t === "ping" || frame.t === "error";
39
+ return frame.t === "hello.ok" || frame.t === "rpc.result" || frame.t === "stream.frame" || frame.t === "stream.error" || frame.t === "tool.call" || frame.t === "tool.cancel" || frame.t === "question.requested" || frame.t === "question.resolved" || frame.t === "ping" || frame.t === "error";
40
40
  }
41
41
  /**
42
42
  * Type guard: is this frame one the CLIENT may send? Server-only shapes
@@ -148,6 +148,17 @@ function parseBridgeFrame(text) {
148
148
  t: "tool.cancel",
149
149
  id: frame.id
150
150
  } : void 0;
151
+ case "question.requested": return typeof frame.id === "string" && typeof frame.sessionId === "string" && Array.isArray(frame.questions) && frame.questions.length > 0 && frame.questions.every(isQuestionItem) ? {
152
+ t: "question.requested",
153
+ id: frame.id,
154
+ sessionId: frame.sessionId,
155
+ questions: frame.questions
156
+ } : void 0;
157
+ case "question.resolved": return typeof frame.id === "string" && typeof frame.sessionId === "string" ? {
158
+ t: "question.resolved",
159
+ id: frame.id,
160
+ sessionId: frame.sessionId
161
+ } : void 0;
151
162
  case "ping": return { t: "ping" };
152
163
  case "error": return typeof frame.code === "string" && typeof frame.message === "string" ? {
153
164
  t: "error",
@@ -160,7 +171,13 @@ function parseBridgeFrame(text) {
160
171
  function isCaps(value) {
161
172
  if (typeof value !== "object" || value === null) return false;
162
173
  const caps = value;
163
- return caps.textOnly === true && typeof caps.snapshotMaxChars === "number" && caps.snapshotMaxChars > 0 && typeof caps.maxInteractiveItems === "number" && caps.maxInteractiveItems > 0;
174
+ return typeof caps.snapshotMaxChars === "number" && caps.snapshotMaxChars > 0 && typeof caps.maxInteractiveItems === "number" && caps.maxInteractiveItems > 0 && (caps.questions === void 0 || typeof caps.questions === "boolean");
175
+ }
176
+ /** Narrow one question item; unknown extra keys (e.g. host `intent`) pass through. */
177
+ function isQuestionItem(value) {
178
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
179
+ const item = value;
180
+ return typeof item.id === "string" && typeof item.question === "string";
164
181
  }
165
182
  function isToolError(value) {
166
183
  return typeof value === "object" && value !== null && typeof value.code === "string" && typeof value.message === "string";
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Track session ids that the browser extension has driven through the bridge.
3
+ * Sessions the extension never touched must keep the host userQuestions
4
+ * waterfall so the dsh web UI (or any other answerer) renders
5
+ * ask_user_question cards.
6
+ * @module
7
+ */
8
+ /** Mutable registry of extension-owned session ids. */
9
+ export declare class ExtensionSessionRegistry {
10
+ private readonly ids;
11
+ /** Remember a session the extension successfully created or prompted. */
12
+ note(sessionId: string | undefined): void;
13
+ /** Whether the extension has touched this session over the bridge. */
14
+ has(sessionId: string | undefined): boolean;
15
+ /** Test helper: drop all tracked ids. */
16
+ clear(): void;
17
+ }
18
+ /**
19
+ * Decide whether the bridge should own ask_user_question for this request.
20
+ * All three gates must pass: an extension is connected, that extension
21
+ * advertised question-card support in its hello caps, and the asking session
22
+ * was driven over the bridge. Everything else falls through to `next()` so
23
+ * the native answerer waterfall (dsh web) keeps working.
24
+ */
25
+ export declare function shouldBridgeOwnQuestion(input: {
26
+ hasExtensionConnection: boolean;
27
+ clientSupportsQuestions: boolean;
28
+ sessionId: string | undefined;
29
+ extensionSessions: Pick<ExtensionSessionRegistry, 'has'>;
30
+ }): boolean;
31
+ //# sourceMappingURL=extension-sessions.d.ts.map
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `@deepseek-ai/dsh-bridge-browser`: token-authenticated WebSocket bridge for
3
- * the browser extension plus the text-only `browser_*` tool set.
3
+ * the browser extension plus the `browser_*` tool set.
4
4
  *
5
5
  * The bridge mounts its own upgrade route (`/ext/bridge`) on the host
6
6
  * webserver, OUTSIDE the /api trust fence — so it brings its own bearer-token
@@ -10,7 +10,15 @@
10
10
  * `ctx.typertGateway.invoke`, and `stream.open` frames open
11
11
  * `ctx.typertGateway.stream` subscriptions whose native follow frames flow
12
12
  * back unmodified. Tools execute by dispatching `tool.call` frames to the
13
- * connected extension, which performs the action in the user's active tab.
13
+ * connected extension, which performs the action in the user's active tab;
14
+ * `browser_screenshot` returns a native image block (the host attachment
15
+ * store owns the bytes), so the model sees the page directly.
16
+ *
17
+ * For sessions the extension has created or prompted, the plugin also claims
18
+ * the host `user-questions/request` waterfall (prepended listener) and pushes
19
+ * `question.requested` to the extension, so the user answers
20
+ * ask_user_question in the sidebar instead of the dsh web UI. Every other
21
+ * session delegates to `next()`.
14
22
  *
15
23
  * Opt-in by design: nothing is registered unless this plugin appears in the
16
24
  * composition. No dsh core code is touched.
@@ -28,20 +28,29 @@ export declare const PING_INTERVAL_MS = 30000;
28
28
  /** Default bytes of the generated bearer token (256-bit). */
29
29
  export declare const DEFAULT_TOKEN_BYTES = 32;
30
30
  /** Error codes a tool call may settle with. Open set: consumers must tolerate unknown codes. */
31
- export type ToolErrorCode = 'no-active-tab' | 'content-unavailable' | 'action-failed' | 'timeout' | 'bridge-closed' | 'bad-args' | 'internal';
31
+ export type ToolErrorCode = 'no-active-tab' | 'content-unavailable' | 'action-failed' | 'timeout' | 'bridge-closed' | 'bad-args' | 'approval-denied' | 'cancelled' | 'internal';
32
32
  /** One tool-call failure: stable machine code plus human text for the model. */
33
33
  export interface ToolError {
34
34
  code: ToolErrorCode;
35
35
  message: string;
36
36
  }
37
- /** Capabilities negotiated in `hello`/`hello.ok`. The extension performs its own actions; these bounds shape page snapshots. */
37
+ /**
38
+ * Capabilities negotiated in `hello`/`hello.ok`. The extension performs its
39
+ * own actions; the numeric bounds shape page snapshots. Optional booleans are
40
+ * feature advertisements: a peer that does not know a flag simply leaves it
41
+ * undefined, and the feature stays off for that pairing (graceful
42
+ * cross-version degradation; same-version pairing is still the support
43
+ * contract). Legacy 0.4.x `textOnly` is gone: DeepSeek routes on the 0.1.2
44
+ * line read images natively, so screenshots now cross the bridge as image
45
+ * blocks instead of file paths.
46
+ */
38
47
  export interface BridgeCaps {
39
- /** The extension renders page state as text only (no screenshots). */
40
- textOnly: true;
41
48
  /** Upper bound on one rendered snapshot's characters (plugin config). */
42
49
  snapshotMaxChars: number;
43
50
  /** Upper bound on interactive inventory items per snapshot (plugin config). */
44
51
  maxInteractiveItems: number;
52
+ /** Client advertises it can render ask_user_question cards; the plugin only claims the user-questions waterfall for extension-owned sessions when set. */
53
+ questions?: boolean;
45
54
  }
46
55
  /** One Remote failure as plain wire data (RemoteError's message is non-enumerable, so it is restated explicitly). */
47
56
  export interface RemoteWireFailure {
@@ -57,6 +66,23 @@ export type RemoteWireResult = {
57
66
  ok: false;
58
67
  error: RemoteWireFailure;
59
68
  };
69
+ /** One ask_user_question option (the host AskUserQuestionOption wire form). */
70
+ export interface QuestionOption {
71
+ label: string;
72
+ description?: string;
73
+ }
74
+ /**
75
+ * One ask_user_question item as it crosses the bridge (the host
76
+ * AskUserQuestionItem wire form, minus the host-internal `intent`).
77
+ */
78
+ export interface QuestionItem {
79
+ id: string;
80
+ question: string;
81
+ detail?: string;
82
+ header?: string;
83
+ options?: QuestionOption[];
84
+ multiSelect?: boolean;
85
+ }
60
86
  /** Frames sent by the extension to the bridge plugin. */
61
87
  export type ClientFrame =
62
88
  /** First frame, within HELLO_TIMEOUT_MS of socket open. */
@@ -146,6 +172,26 @@ export type ServerFrame =
146
172
  t: 'tool.cancel';
147
173
  id: string;
148
174
  }
175
+ /**
176
+ * The host asked the user (ask_user_question) in an extension-owned session
177
+ * and the bridge claimed the waterfall: the extension should render a
178
+ * question card. The answer rides a normal `rpc` frame with the
179
+ * plugin-local method `bridge/questionAnswer` (args `{questionId, sessionId,
180
+ * answer?} | {questionId, sessionId, decline: true}`), answered
181
+ * `{accepted: true} | {accepted: false, reason: 'not-pending'}`.
182
+ */
183
+ | {
184
+ t: 'question.requested';
185
+ id: string;
186
+ sessionId: string;
187
+ questions: QuestionItem[];
188
+ }
189
+ /** A previously pushed question is gone (host aborted it or the bridge delegated the waterfall elsewhere); dismiss the card without answering. */
190
+ | {
191
+ t: 'question.resolved';
192
+ id: string;
193
+ sessionId: string;
194
+ }
149
195
  /** Liveness probe. */
150
196
  | {
151
197
  t: 'ping';
@@ -0,0 +1,76 @@
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
+ import type { QuestionItem, ServerFrame } from './protocol.ts';
19
+ /** One answer item, mirroring the host AskUserQuestionAnswerItem wire form. */
20
+ export interface QuestionAnswerItem {
21
+ id: string;
22
+ selected: string[];
23
+ custom?: string;
24
+ }
25
+ /** The extension's answer payload, mirroring the host AskUserQuestionAnswer. */
26
+ export interface QuestionAnswerPayload {
27
+ answers: QuestionAnswerItem[];
28
+ }
29
+ /** Receipt answered to the extension's `bridge/questionAnswer` rpc. */
30
+ export type QuestionAnswerReceipt = {
31
+ accepted: true;
32
+ } | {
33
+ accepted: false;
34
+ reason: 'not-pending' | 'bad-answer';
35
+ };
36
+ /** Args of the plugin-local `bridge/questionAnswer` rpc method. */
37
+ export interface QuestionAnswerArgs {
38
+ questionId: string;
39
+ sessionId: string;
40
+ answer?: unknown;
41
+ decline?: boolean;
42
+ }
43
+ /** Structural validation of the extension's answer payload. */
44
+ export declare function asAnswerPayload(value: unknown, questionIds: ReadonlySet<string>): QuestionAnswerPayload | undefined;
45
+ /** Parse the extension's `bridge/questionAnswer` rpc args (light: ids only). */
46
+ export declare function asQuestionAnswerArgs(value: unknown): QuestionAnswerArgs | undefined;
47
+ /** Owns the user-questions waterfall for extension-driven sessions. */
48
+ export declare class QuestionBridge {
49
+ private readonly deps;
50
+ private readonly pending;
51
+ constructor(deps: {
52
+ /** Push one server frame to the connected extension (must tolerate a dead socket). */
53
+ push: (frame: ServerFrame) => void;
54
+ });
55
+ /**
56
+ * Own one host waterfall request: push `question.requested` to the
57
+ * extension and suspend until one of the settlement races wins.
58
+ *
59
+ * @param sessionId - asking session (already ownership-checked by the caller).
60
+ * @param questions - host question items (forwarded verbatim).
61
+ * @param next - waterfall delegation, used when the bridge connection drops.
62
+ * @param signal - host cancellation lifetime for this request.
63
+ * @returns the user's answer.
64
+ */
65
+ ask(sessionId: string, questions: QuestionItem[], next: () => Promise<QuestionAnswerPayload>, signal?: AbortSignal): Promise<QuestionAnswerPayload>;
66
+ /**
67
+ * Settle one pending question from the extension's `bridge/questionAnswer`
68
+ * rpc. The server replies with this receipt.
69
+ */
70
+ answer(args: QuestionAnswerArgs): QuestionAnswerReceipt;
71
+ /** Bridge connection replaced/closed: delegate every unsettled question. */
72
+ delegateAll(): void;
73
+ /** Plugin unload: reject everything so no tool call outlives the plugin. */
74
+ dispose(): void;
75
+ }
76
+ //# sourceMappingURL=questions.d.ts.map
@@ -20,7 +20,17 @@
20
20
  */
21
21
  import type { IncomingMessage } from 'node:http';
22
22
  import type { Duplex } from 'node:stream';
23
- import { type BridgeCaps, type RemoteWireResult, type ToolErrorCode } from './protocol.ts';
23
+ import { type BridgeCaps, type RemoteWireResult, type ServerFrame, type ToolErrorCode } from './protocol.ts';
24
+ /**
25
+ * Gateway endpoints the bridge pins to loopback (the rc line's
26
+ * PRIVILEGED_METHODS, restated against the alpha Remote endpoint names:
27
+ * settings/credentials mutation and host-desktop/filesystem actions). The
28
+ * bridge rejects these for non-loopback remotes even with a valid token.
29
+ * Exported so tests can tripwire the list against accidental shrinkage —
30
+ * when the host line adds new privileged endpoints, extend this set in the
31
+ * same commit.
32
+ */
33
+ export declare const PRIVILEGED_METHODS: Set<string>;
24
34
  /** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
25
35
  export declare function isLoopbackAddress(address: string | undefined): boolean;
26
36
  /** Error thrown by requestTool; the tool registry turns it into an isError result. */
@@ -44,6 +54,14 @@ export interface BridgeServerDeps {
44
54
  toolTimeoutMs: number;
45
55
  /** Capabilities to echo in `hello.ok` (negotiated snapshot budgets). */
46
56
  caps: BridgeCaps;
57
+ /**
58
+ * Plugin-local endpoint `bridge/questionAnswer`: settle one pending
59
+ * ask_user_question the bridge pushed to this extension. Answered as the
60
+ * rpc result value `{accepted: true} | {accepted: false, reason}`.
61
+ */
62
+ answerQuestion: (args: Record<string, unknown>) => unknown;
63
+ /** The active connection was replaced or closed (settle pushed questions). */
64
+ onConnectionLost?: () => void;
47
65
  /**
48
66
  * Test seam: force the remote address seen by the privilege gate. The
49
67
  * sandbox cannot bind arbitrary loopback literals, so the non-loopback
@@ -54,6 +72,14 @@ export interface BridgeServerDeps {
54
72
  helloTimeoutMs?: number;
55
73
  /** Server ping cadence; defaults to PING_INTERVAL_MS. */
56
74
  pingIntervalMs?: number;
75
+ /** Cap on one incoming message in bytes; defaults to 4MiB. */
76
+ maxPayloadBytes?: number;
77
+ /** Pump backpressure threshold (ws bufferedAmount) in bytes; defaults to 4MiB. */
78
+ maxBufferedBytes?: number;
79
+ /** Grace period for stream pumps during close(); defaults to 5000. */
80
+ closePumpTimeoutMs?: number;
81
+ /** Consecutive missed ping cycles before a zombie connection is terminated; defaults to 3. */
82
+ missedPongsAllowed?: number;
57
83
  }
58
84
  /**
59
85
  * Decode one ws message payload to text. Exported so all three delivery
@@ -101,6 +127,14 @@ export declare class BridgeServer {
101
127
  close(): Promise<void>;
102
128
  /** @returns whether an authenticated extension is currently connected. */
103
129
  hasConnection(): boolean;
130
+ /** @returns whether the connected extension advertised question-card support. */
131
+ clientSupportsQuestions(): boolean;
132
+ /**
133
+ * Push one unsolicited server frame (question.requested/question.resolved)
134
+ * to the connected extension. No-op when no extension is connected or the
135
+ * socket is already dead.
136
+ */
137
+ push(frame: ServerFrame): void;
104
138
  private attach;
105
139
  /** Promote an authenticated socket to the single active slot. */
106
140
  private promote;
@@ -116,6 +150,11 @@ export declare class BridgeServer {
116
150
  private handleRpc;
117
151
  /** Open one Remote stream and pump its frames until closed, failed, or replaced. */
118
152
  private openStream;
153
+ /**
154
+ * Backpressure gate for stream pumps. Returns false when the wait ended
155
+ * because the socket died or the pump was aborted (the caller then stops).
156
+ */
157
+ private waitForDrain;
119
158
  /** Abort one open stream (client `stream.close`). */
120
159
  private closeStream;
121
160
  private settleTool;
@@ -1,17 +1,21 @@
1
1
  /**
2
2
  * Model-facing browser tools. Every tool executes by dispatching a `tool.call`
3
3
  * over the bridge to the connected extension, which performs the action in the
4
- * user's active tab and returns a pure-text result.
4
+ * user's active tab and returns the result.
5
5
  *
6
- * The whole surface is text-only by design (DeepSeek models have no vision):
7
6
  * `browser_snapshot` renders the page as structured text with a numbered
8
- * interactive inventory, and every other tool addresses elements by that
9
- * inventory's stable index. Results are single `{ text }` objects rendered as
10
- * one text ContentBlock.
7
+ * interactive inventory, and every action tool addresses elements by that
8
+ * inventory's stable index — text is the addressing scheme, not a vision
9
+ * limitation. `browser_screenshot` is the exception: its capture is saved to
10
+ * the host attachment store and rendered as a native image ContentBlock, so
11
+ * the model sees the page directly (DeepSeek routes on the 0.1.2 line read
12
+ * images natively; text-only routes get the host's automatic placeholder
13
+ * downgrade).
11
14
  *
12
15
  * @module
13
16
  */
14
17
  import type { Context } from '@deepseek-ai/cordis';
18
+ import type { ImageMediaType } from '@deepseek-ai/dsh-attachment';
15
19
  import type { BridgeServer } from './server.ts';
16
20
  /** Options resolved from plugin config before tool registration. */
17
21
  export interface BrowserToolsOptions {
@@ -22,8 +26,18 @@ export interface BrowserToolsOptions {
22
26
  /** Upper bound on interactive inventory items per snapshot. */
23
27
  maxInteractiveItems: number;
24
28
  }
29
+ /**
30
+ * Normalize the extension's screenshot payload. Current extensions answer a
31
+ * structured `{ mediaType, data }` (base64 without the data: prefix); 0.4.x
32
+ * extensions answered a raw data URL — kept as the legacy path so a stale
33
+ * extension degrades instead of breaking.
34
+ */
35
+ export declare function parseScreenshotPayload(result: unknown): {
36
+ mediaType: ImageMediaType;
37
+ data: string;
38
+ } | undefined;
25
39
  /** The keys the extension accepts as wire action names (tool name == action name). */
26
- export declare const BROWSER_TOOL_NAMES: readonly ["browser_snapshot", "browser_click", "browser_type", "browser_press", "browser_scroll", "browser_navigate", "browser_back", "browser_forward", "browser_reload", "browser_get_text", "browser_wait", "browser_evaluate", "browser_screenshot", "browser_list_tabs"];
40
+ export declare const BROWSER_TOOL_NAMES: readonly ["browser_snapshot", "browser_click", "browser_type", "browser_press", "browser_scroll", "browser_navigate", "browser_back", "browser_forward", "browser_reload", "browser_get_text", "browser_wait", "browser_evaluate", "browser_screenshot", "browser_list_tabs", "browser_open_tab", "browser_follow_tab", "browser_close_tab"];
27
41
  /**
28
42
  * Register the browser tools on `ctx.tools`. Disposers are returned for the
29
43
  * caller's effect to own; each tool's cooperative timeout budget is declared
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-browser-firefox",
3
- "description": "Firefox browser control for DeepSeek Harness: token-authenticated WebSocket bridge + text-first browser_* tools driving the user's own Firefox via the companion AMO extension",
4
- "version": "0.4.0",
3
+ "description": "Firefox browser control for DeepSeek Harness: token-authenticated WebSocket bridge + browser_* tools (native-image screenshots) driving the user's own Firefox via the companion AMO extension, with sidebar ask_user_question answering",
4
+ "version": "0.4.5",
5
5
  "author": "tuojc",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -56,10 +56,12 @@
56
56
  "@deepseek-ai/dsh-api-gateway": "^0.1.2-alpha.2",
57
57
  "@deepseek-ai/dsh-api-session-controller": "^0.1.2-alpha.2",
58
58
  "@deepseek-ai/dsh-api-workspace-controller": "^0.1.2-alpha.2",
59
+ "@deepseek-ai/dsh-attachment": "^0.1.2-alpha.2",
59
60
  "@deepseek-ai/dsh-host-webserver": "^0.1.2-alpha.2",
60
61
  "@deepseek-ai/dsh-invariants": "^0.1.2-alpha.2",
61
62
  "@deepseek-ai/dsh-home-paths": "^0.1.2-alpha.2",
62
- "@deepseek-ai/dsh-tools": "^0.1.2-alpha.2"
63
+ "@deepseek-ai/dsh-tools": "^0.1.2-alpha.2",
64
+ "@deepseek-ai/dsh-user-questions": "^0.1.2-alpha.2"
63
65
  },
64
66
  "dependencies": {
65
67
  "@deepseek-ai/schemastery": "^3.18.1",
@@ -80,6 +82,7 @@
80
82
  "@deepseek-ai/dsh-api-gateway": "0.1.2-alpha.5",
81
83
  "@deepseek-ai/dsh-api-session-controller": "0.1.2-alpha.5",
82
84
  "@deepseek-ai/dsh-api-workspace-controller": "0.1.2-alpha.5",
85
+ "@deepseek-ai/dsh-attachment": "0.1.2-alpha.5",
83
86
  "@deepseek-ai/dsh-host-webserver": "0.1.2-alpha.5",
84
87
  "@deepseek-ai/dsh-invariants": "0.1.2-alpha.5",
85
88
  "@deepseek-ai/dsh-llm": "0.1.2-alpha.5",
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Track session ids that the browser extension has driven through the bridge.
3
+ * Sessions the extension never touched must keep the host userQuestions
4
+ * waterfall so the dsh web UI (or any other answerer) renders
5
+ * ask_user_question cards.
6
+ * @module
7
+ */
8
+
9
+ /** Mutable registry of extension-owned session ids. */
10
+ export class ExtensionSessionRegistry {
11
+ private readonly ids = new Set<string>()
12
+
13
+ /** Remember a session the extension successfully created or prompted. */
14
+ note(sessionId: string | undefined): void {
15
+ if (typeof sessionId === 'string' && sessionId.length > 0) this.ids.add(sessionId)
16
+ }
17
+
18
+ /** Whether the extension has touched this session over the bridge. */
19
+ has(sessionId: string | undefined): boolean {
20
+ return typeof sessionId === 'string' && this.ids.has(sessionId)
21
+ }
22
+
23
+ /** Test helper: drop all tracked ids. */
24
+ clear(): void {
25
+ this.ids.clear()
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Decide whether the bridge should own ask_user_question for this request.
31
+ * All three gates must pass: an extension is connected, that extension
32
+ * advertised question-card support in its hello caps, and the asking session
33
+ * was driven over the bridge. Everything else falls through to `next()` so
34
+ * the native answerer waterfall (dsh web) keeps working.
35
+ */
36
+ export function shouldBridgeOwnQuestion(input: {
37
+ hasExtensionConnection: boolean
38
+ clientSupportsQuestions: boolean
39
+ sessionId: string | undefined
40
+ extensionSessions: Pick<ExtensionSessionRegistry, 'has'>
41
+ }): boolean {
42
+ return input.hasExtensionConnection
43
+ && input.clientSupportsQuestions
44
+ && input.sessionId !== undefined
45
+ && input.extensionSessions.has(input.sessionId)
46
+ }
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `@deepseek-ai/dsh-bridge-browser`: token-authenticated WebSocket bridge for
3
- * the browser extension plus the text-only `browser_*` tool set.
3
+ * the browser extension plus the `browser_*` tool set.
4
4
  *
5
5
  * The bridge mounts its own upgrade route (`/ext/bridge`) on the host
6
6
  * webserver, OUTSIDE the /api trust fence — so it brings its own bearer-token
@@ -10,7 +10,15 @@
10
10
  * `ctx.typertGateway.invoke`, and `stream.open` frames open
11
11
  * `ctx.typertGateway.stream` subscriptions whose native follow frames flow
12
12
  * back unmodified. Tools execute by dispatching `tool.call` frames to the
13
- * connected extension, which performs the action in the user's active tab.
13
+ * connected extension, which performs the action in the user's active tab;
14
+ * `browser_screenshot` returns a native image block (the host attachment
15
+ * store owns the bytes), so the model sees the page directly.
16
+ *
17
+ * For sessions the extension has created or prompted, the plugin also claims
18
+ * the host `user-questions/request` waterfall (prepended listener) and pushes
19
+ * `question.requested` to the extension, so the user answers
20
+ * ask_user_question in the sidebar instead of the dsh web UI. Every other
21
+ * session delegates to `next()`.
14
22
  *
15
23
  * Opt-in by design: nothing is registered unless this plugin appears in the
16
24
  * composition. No dsh core code is touched.
@@ -22,6 +30,7 @@ import type { Context } from '@deepseek-ai/cordis'
22
30
  import z from '@deepseek-ai/schemastery'
23
31
  import type {} from '@deepseek-ai/dsh-tools'
24
32
  import type {} from '@deepseek-ai/dsh-api-gateway/types'
33
+ import type {} from '@deepseek-ai/dsh-user-questions/types'
25
34
  import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
26
35
  import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
27
36
  import { BridgeServer } from './server.ts'
@@ -30,6 +39,8 @@ import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, type RemoteWireResult } from './protoc
30
39
  import { withSessionDeferral } from './session-deferral.ts'
31
40
  import { withSessionWorkspace, type RpcDispatch } from './session-workspace.ts'
32
41
  import { resolveToken } from './token.ts'
42
+ import { ExtensionSessionRegistry, shouldBridgeOwnQuestion } from './extension-sessions.ts'
43
+ import { asQuestionAnswerArgs, QuestionBridge } from './questions.ts'
33
44
 
34
45
  /** Cordis plugin name used by loader diagnostics. */
35
46
  export const name = 'bridge-browser'
@@ -87,6 +98,13 @@ export function assertPositiveInteger(name: string, value: number): void {
87
98
  }
88
99
  }
89
100
 
101
+ /** Extract the session id from an rpc args/result object, when present. */
102
+ function sessionIdOf(value: unknown): string | undefined {
103
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
104
+ const sessionId = (value as Record<string, unknown>).sessionId
105
+ return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined
106
+ }
107
+
90
108
  /**
91
109
  * Apply defaults and direct-call validation at the plugin boundary.
92
110
  * @param config - Loader-resolved or directly supplied plugin configuration.
@@ -144,23 +162,70 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
144
162
  ),
145
163
  resolved.deferSessionCreate,
146
164
  )
165
+ // Ownership tracking for the user-questions waterfall: a session becomes
166
+ // extension-owned only after a create/prompt SUCCEEDS — a failed prompt
167
+ // against a desktop session must not steal its questions away from the
168
+ // native answerer.
169
+ const extensionSessions = new ExtensionSessionRegistry()
170
+ const notingDispatchRpc: RpcDispatch = async (method, args, signal) => {
171
+ const result = await dispatchRpc(method, args, signal)
172
+ if (result.ok && (method === 'session/create' || method === 'session/prompt')) {
173
+ extensionSessions.note(sessionIdOf(args.request))
174
+ extensionSessions.note(sessionIdOf(result.value))
175
+ }
176
+ return result
177
+ }
178
+ const questions = new QuestionBridge({
179
+ // Late-bound through the closure: server is constructed right below.
180
+ push: (frame) => { server.push(frame) },
181
+ })
147
182
  const server = new BridgeServer({
148
183
  token: tokenRes.token,
149
- dispatchRpc,
184
+ dispatchRpc: notingDispatchRpc,
150
185
  openStream: (method, args, signal) => {
151
186
  const slash = method.indexOf('/')
152
187
  const namespace = slash === -1 ? method : method.slice(0, slash)
153
188
  const remoteMethod = slash === -1 ? '' : method.slice(slash + 1)
154
189
  return ctx.typertGateway.stream({ namespace, method: remoteMethod, args, signal })
155
190
  },
191
+ answerQuestion: (args) => {
192
+ const parsed = asQuestionAnswerArgs(args)
193
+ return parsed === undefined
194
+ ? { accepted: false, reason: 'bad-answer' }
195
+ : questions.answer(parsed)
196
+ },
197
+ onConnectionLost: () => { questions.delegateAll() },
156
198
  toolTimeoutMs: resolved.toolTimeoutMs,
157
199
  caps: {
158
- textOnly: true,
159
200
  snapshotMaxChars: resolved.snapshotMaxChars,
160
201
  maxInteractiveItems: resolved.maxInteractiveItems,
161
202
  },
162
203
  })
163
204
 
205
+ // Sidebar ask_user_question: claim the waterfall only for sessions the
206
+ // extension owns (created or prompted over the bridge) while a
207
+ // question-capable extension is connected; everything else keeps the
208
+ // native answerer chain (dsh web). Prepended so the claim runs before the
209
+ // Remote event forwarding listener in dsh-api-remotes.
210
+ ctx.effect(() => {
211
+ const disposeListener = ctx.on('user-questions/request', (request, next) => {
212
+ const sessionId = request.agent?.id
213
+ if (sessionId === undefined || !shouldBridgeOwnQuestion({
214
+ hasExtensionConnection: server.hasConnection(),
215
+ clientSupportsQuestions: server.clientSupportsQuestions(),
216
+ sessionId,
217
+ extensionSessions,
218
+ })) {
219
+ return next()
220
+ }
221
+ return questions.ask(sessionId, request.questions, next, request.signal)
222
+ }, { prepend: true })
223
+ return () => {
224
+ disposeListener()
225
+ questions.dispose()
226
+ }
227
+ }, 'bridge-browser: user-questions answerer')
228
+
164
229
  const route: WebUpgradeRoute = {
165
230
  path: BRIDGE_PATH,
166
231
  handler: (req, socket, head) => { server.handleUpgrade(req, socket, head) },
@@ -210,7 +275,8 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
210
275
  name: 'tool:bridge-browser',
211
276
  order: 107,
212
277
  text: 'A browser bridge may be connected. To read or operate the user\'s active browser page, call browser_snapshot '
213
- + '(text-only; numbered items are the click/type targets). Never assume page content you have not snapshot.',
278
+ + '(text-only; numbered items are the click/type targets). For content that defies text (images, charts, captchas), '
279
+ + 'call browser_screenshot: the image is returned to you directly. Never assume page content you have not snapshot.',
214
280
  }), 'bridge-browser: system prompt section')
215
281
  }
216
282