dsh-browser-firefox 0.4.1 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/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
@@ -67,11 +67,15 @@ function parseBridgeFrame(text) {
67
67
  const frame = value;
68
68
  if (typeof frame.t !== "string") return void 0;
69
69
  switch (frame.t) {
70
- case "hello": return typeof frame.token === "string" && isCaps(frame.caps) ? {
71
- t: "hello",
72
- token: frame.token,
73
- caps: frame.caps
74
- } : void 0;
70
+ case "hello":
71
+ if (typeof frame.token !== "string" || !isCaps(frame.caps)) return void 0;
72
+ if (frame.version !== void 0 && typeof frame.version !== "string") return void 0;
73
+ return {
74
+ t: "hello",
75
+ token: frame.token,
76
+ caps: frame.caps,
77
+ ...frame.version === void 0 ? {} : { version: frame.version }
78
+ };
75
79
  case "rpc": return typeof frame.id === "string" && typeof frame.method === "string" && isArgs(frame.args) ? {
76
80
  t: "rpc",
77
81
  id: frame.id,
@@ -103,10 +107,14 @@ function parseBridgeFrame(text) {
103
107
  error: frame.error
104
108
  } : void 0;
105
109
  case "pong": return { t: "pong" };
106
- case "hello.ok": return isCaps(frame.caps) ? {
107
- t: "hello.ok",
108
- caps: frame.caps
109
- } : void 0;
110
+ case "hello.ok":
111
+ if (!isCaps(frame.caps)) return void 0;
112
+ if (frame.version !== void 0 && typeof frame.version !== "string") return void 0;
113
+ return {
114
+ t: "hello.ok",
115
+ caps: frame.caps,
116
+ ...frame.version === void 0 ? {} : { version: frame.version }
117
+ };
110
118
  case "rpc.result":
111
119
  if (typeof frame.id !== "string") return void 0;
112
120
  if (frame.ok === true && "value" in frame) return {
@@ -148,6 +156,17 @@ function parseBridgeFrame(text) {
148
156
  t: "tool.cancel",
149
157
  id: frame.id
150
158
  } : void 0;
159
+ case "question.requested": return typeof frame.id === "string" && typeof frame.sessionId === "string" && Array.isArray(frame.questions) && frame.questions.length > 0 && frame.questions.every(isQuestionItem) ? {
160
+ t: "question.requested",
161
+ id: frame.id,
162
+ sessionId: frame.sessionId,
163
+ questions: frame.questions
164
+ } : void 0;
165
+ case "question.resolved": return typeof frame.id === "string" && typeof frame.sessionId === "string" ? {
166
+ t: "question.resolved",
167
+ id: frame.id,
168
+ sessionId: frame.sessionId
169
+ } : void 0;
151
170
  case "ping": return { t: "ping" };
152
171
  case "error": return typeof frame.code === "string" && typeof frame.message === "string" ? {
153
172
  t: "error",
@@ -160,7 +179,13 @@ function parseBridgeFrame(text) {
160
179
  function isCaps(value) {
161
180
  if (typeof value !== "object" || value === null) return false;
162
181
  const caps = value;
163
- return caps.textOnly === true && typeof caps.snapshotMaxChars === "number" && caps.snapshotMaxChars > 0 && typeof caps.maxInteractiveItems === "number" && caps.maxInteractiveItems > 0;
182
+ return typeof caps.snapshotMaxChars === "number" && caps.snapshotMaxChars > 0 && typeof caps.maxInteractiveItems === "number" && caps.maxInteractiveItems > 0 && (caps.questions === void 0 || typeof caps.questions === "boolean");
183
+ }
184
+ /** Narrow one question item; unknown extra keys (e.g. host `intent`) pass through. */
185
+ function isQuestionItem(value) {
186
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
187
+ const item = value;
188
+ return typeof item.id === "string" && typeof item.question === "string";
164
189
  }
165
190
  function isToolError(value) {
166
191
  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.
@@ -34,14 +34,23 @@ 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,13 +66,31 @@ 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
- /** First frame, within HELLO_TIMEOUT_MS of socket open. */
88
+ /** 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. */
63
89
  {
64
90
  t: 'hello';
65
91
  token: string;
66
92
  caps: BridgeCaps;
93
+ version?: string;
67
94
  }
68
95
  /** Unary Remote call: slash-joined endpoint plus the descriptor's native args object. */
69
96
  | {
@@ -102,10 +129,11 @@ export type ClientFrame =
102
129
  };
103
130
  /** Frames sent by the bridge plugin to the extension. */
104
131
  export type ServerFrame =
105
- /** Accepted after a valid `hello`. */
132
+ /** Accepted after a valid `hello`. `version` (plugin version) lets the extension detect a version mismatch; absent on pre-0.4.6 servers. */
106
133
  {
107
134
  t: 'hello.ok';
108
135
  caps: BridgeCaps;
136
+ version?: string;
109
137
  }
110
138
  /** Reply to an `rpc` frame: the RemoteResult wire form, flattened onto the frame. */
111
139
  | {
@@ -146,6 +174,26 @@ export type ServerFrame =
146
174
  t: 'tool.cancel';
147
175
  id: string;
148
176
  }
177
+ /**
178
+ * The host asked the user (ask_user_question) in an extension-owned session
179
+ * and the bridge claimed the waterfall: the extension should render a
180
+ * question card. The answer rides a normal `rpc` frame with the
181
+ * plugin-local method `bridge/questionAnswer` (args `{questionId, sessionId,
182
+ * answer?} | {questionId, sessionId, decline: true}`), answered
183
+ * `{accepted: true} | {accepted: false, reason: 'not-pending'}`.
184
+ */
185
+ | {
186
+ t: 'question.requested';
187
+ id: string;
188
+ sessionId: string;
189
+ questions: QuestionItem[];
190
+ }
191
+ /** A previously pushed question is gone (host aborted it or the bridge delegated the waterfall elsewhere); dismiss the card without answering. */
192
+ | {
193
+ t: 'question.resolved';
194
+ id: string;
195
+ sessionId: string;
196
+ }
149
197
  /** Liveness probe. */
150
198
  | {
151
199
  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,7 @@
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
24
  /**
25
25
  * Gateway endpoints the bridge pins to loopback (the rc line's
26
26
  * PRIVILEGED_METHODS, restated against the alpha Remote endpoint names:
@@ -54,6 +54,18 @@ export interface BridgeServerDeps {
54
54
  toolTimeoutMs: number;
55
55
  /** Capabilities to echo in `hello.ok` (negotiated snapshot budgets). */
56
56
  caps: BridgeCaps;
57
+ /** Plugin version echoed in `hello.ok` so the extension can flag a mismatch (0.4.6+). */
58
+ version?: string | undefined;
59
+ /** An authenticated client arrived with a version different from ours. */
60
+ onVersionMismatch?: (clientVersion: string) => void;
61
+ /**
62
+ * Plugin-local endpoint `bridge/questionAnswer`: settle one pending
63
+ * ask_user_question the bridge pushed to this extension. Answered as the
64
+ * rpc result value `{accepted: true} | {accepted: false, reason}`.
65
+ */
66
+ answerQuestion: (args: Record<string, unknown>) => unknown;
67
+ /** The active connection was replaced or closed (settle pushed questions). */
68
+ onConnectionLost?: () => void;
57
69
  /**
58
70
  * Test seam: force the remote address seen by the privilege gate. The
59
71
  * sandbox cannot bind arbitrary loopback literals, so the non-loopback
@@ -119,6 +131,14 @@ export declare class BridgeServer {
119
131
  close(): Promise<void>;
120
132
  /** @returns whether an authenticated extension is currently connected. */
121
133
  hasConnection(): boolean;
134
+ /** @returns whether the connected extension advertised question-card support. */
135
+ clientSupportsQuestions(): boolean;
136
+ /**
137
+ * Push one unsolicited server frame (question.requested/question.resolved)
138
+ * to the connected extension. No-op when no extension is connected or the
139
+ * socket is already dead.
140
+ */
141
+ push(frame: ServerFrame): void;
122
142
  private attach;
123
143
  /** Promote an authenticated socket to the single active slot. */
124
144
  private promote;
@@ -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,6 +26,16 @@ 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
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
  /**
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.1",
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.6",
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,7 +30,9 @@ 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'
35
+ import { readFileSync } from 'node:fs'
26
36
  import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
27
37
  import { BridgeServer } from './server.ts'
28
38
  import { registerBrowserTools } from './tools.ts'
@@ -30,6 +40,8 @@ import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, type RemoteWireResult } from './protoc
30
40
  import { withSessionDeferral } from './session-deferral.ts'
31
41
  import { withSessionWorkspace, type RpcDispatch } from './session-workspace.ts'
32
42
  import { resolveToken } from './token.ts'
43
+ import { ExtensionSessionRegistry, shouldBridgeOwnQuestion } from './extension-sessions.ts'
44
+ import { asQuestionAnswerArgs, QuestionBridge } from './questions.ts'
33
45
 
34
46
  /** Cordis plugin name used by loader diagnostics. */
35
47
  export const name = 'bridge-browser'
@@ -87,6 +99,13 @@ export function assertPositiveInteger(name: string, value: number): void {
87
99
  }
88
100
  }
89
101
 
102
+ /** Extract the session id from an rpc args/result object, when present. */
103
+ function sessionIdOf(value: unknown): string | undefined {
104
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
105
+ const sessionId = (value as Record<string, unknown>).sessionId
106
+ return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined
107
+ }
108
+
90
109
  /**
91
110
  * Apply defaults and direct-call validation at the plugin boundary.
92
111
  * @param config - Loader-resolved or directly supplied plugin configuration.
@@ -144,23 +163,84 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
144
163
  ),
145
164
  resolved.deferSessionCreate,
146
165
  )
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.
170
+ const extensionSessions = new ExtensionSessionRegistry()
171
+ const notingDispatchRpc: RpcDispatch = async (method, args, signal) => {
172
+ 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))
176
+ }
177
+ return result
178
+ }
179
+ // Plugin version for the hello.ok handshake (extension flags a mismatch in
180
+ // the sidebar). src/ and lib/ layouts both resolve to the same package.json.
181
+ let pluginVersion: string | undefined
182
+ try {
183
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version?: unknown }
184
+ pluginVersion = typeof pkg.version === 'string' ? pkg.version : undefined
185
+ } catch {
186
+ pluginVersion = undefined
187
+ }
188
+
189
+ const questions = new QuestionBridge({
190
+ // Late-bound through the closure: server is constructed right below.
191
+ push: (frame) => { server.push(frame) },
192
+ })
147
193
  const server = new BridgeServer({
148
194
  token: tokenRes.token,
149
- dispatchRpc,
195
+ dispatchRpc: notingDispatchRpc,
150
196
  openStream: (method, args, signal) => {
151
197
  const slash = method.indexOf('/')
152
198
  const namespace = slash === -1 ? method : method.slice(0, slash)
153
199
  const remoteMethod = slash === -1 ? '' : method.slice(slash + 1)
154
200
  return ctx.typertGateway.stream({ namespace, method: remoteMethod, args, signal })
155
201
  },
202
+ answerQuestion: (args) => {
203
+ const parsed = asQuestionAnswerArgs(args)
204
+ return parsed === undefined
205
+ ? { accepted: false, reason: 'bad-answer' }
206
+ : questions.answer(parsed)
207
+ },
208
+ onConnectionLost: () => { questions.delegateAll() },
209
+ version: pluginVersion,
210
+ onVersionMismatch: (clientVersion) => {
211
+ ctx.logger.warn(`browser extension version ${clientVersion} != plugin version ${pluginVersion ?? '?'}; both components must be updated together`)
212
+ },
156
213
  toolTimeoutMs: resolved.toolTimeoutMs,
157
214
  caps: {
158
- textOnly: true,
159
215
  snapshotMaxChars: resolved.snapshotMaxChars,
160
216
  maxInteractiveItems: resolved.maxInteractiveItems,
161
217
  },
162
218
  })
163
219
 
220
+ // 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.
225
+ ctx.effect(() => {
226
+ const disposeListener = ctx.on('user-questions/request', (request, next) => {
227
+ const sessionId = request.agent?.id
228
+ if (sessionId === undefined || !shouldBridgeOwnQuestion({
229
+ hasExtensionConnection: server.hasConnection(),
230
+ clientSupportsQuestions: server.clientSupportsQuestions(),
231
+ sessionId,
232
+ extensionSessions,
233
+ })) {
234
+ return next()
235
+ }
236
+ return questions.ask(sessionId, request.questions, next, request.signal)
237
+ }, { prepend: true })
238
+ return () => {
239
+ disposeListener()
240
+ questions.dispose()
241
+ }
242
+ }, 'bridge-browser: user-questions answerer')
243
+
164
244
  const route: WebUpgradeRoute = {
165
245
  path: BRIDGE_PATH,
166
246
  handler: (req, socket, head) => { server.handleUpgrade(req, socket, head) },
@@ -210,7 +290,8 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
210
290
  name: 'tool:bridge-browser',
211
291
  order: 107,
212
292
  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.',
293
+ + '(text-only; numbered items are the click/type targets). For content that defies text (images, charts, captchas), '
294
+ + 'call browser_screenshot: the image is returned to you directly. Never assume page content you have not snapshot.',
214
295
  }), 'bridge-browser: system prompt section')
215
296
  }
216
297