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/index.js +371 -91
- package/lib/protocol.js +36 -11
- package/lib/types/extension-sessions.d.ts +31 -0
- package/lib/types/index.d.ts +10 -2
- package/lib/types/protocol.d.ts +53 -5
- package/lib/types/questions.d.ts +76 -0
- package/lib/types/server.d.ts +21 -1
- package/lib/types/tools.d.ts +19 -5
- package/package.json +6 -3
- package/src/extension-sessions.ts +46 -0
- package/src/index.ts +86 -5
- package/src/protocol.ts +86 -16
- package/src/questions.ts +192 -0
- package/src/server.ts +55 -6
- package/src/tools.ts +85 -99
package/lib/index.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, parseBridgeFrame } from "./protocol.js";
|
|
2
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
3
4
|
import { dshHomePath } from "@deepseek-ai/dsh-home-paths";
|
|
4
5
|
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
5
6
|
import { WebSocket, WebSocketServer } from "ws";
|
|
6
|
-
import { chmod, mkdir, readFile,
|
|
7
|
-
import { dirname
|
|
7
|
+
import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname } from "node:path";
|
|
8
9
|
//#region lib/types/token.js
|
|
9
10
|
/**
|
|
10
11
|
* Bridge bearer-token lifecycle: generation, constant-time verification, and
|
|
@@ -146,8 +147,8 @@ const PRIVILEGED_METHODS = /* @__PURE__ */ new Set([
|
|
|
146
147
|
]);
|
|
147
148
|
/** Session mutations whose WebSocket arrival order is behaviorally significant. */
|
|
148
149
|
const ORDERED_SESSION_METHODS = /* @__PURE__ */ new Set(["session/prompt", "session/cancel"]);
|
|
149
|
-
/** Default cap on one incoming WebSocket message (the ws library default of 100MiB is an unauthenticated DoS surface). */
|
|
150
|
-
const DEFAULT_MAX_PAYLOAD_BYTES =
|
|
150
|
+
/** Default cap on one incoming WebSocket message (the ws library default of 100MiB is an unauthenticated DoS surface). 32MiB leaves room for base64 screenshots and image-carrying prompts, which routinely exceed 4MiB. */
|
|
151
|
+
const DEFAULT_MAX_PAYLOAD_BYTES = 32 * 1024 * 1024;
|
|
151
152
|
/** Default pump backpressure threshold: pause forwarding when the socket buffer grows past this. */
|
|
152
153
|
const DEFAULT_MAX_BUFFERED_BYTES = 4 * 1024 * 1024;
|
|
153
154
|
/** Default grace period for stream pumps during close(); a wedged gateway iterator must not stall teardown forever. */
|
|
@@ -342,6 +343,20 @@ var BridgeServer = class {
|
|
|
342
343
|
hasConnection() {
|
|
343
344
|
return this.current !== null;
|
|
344
345
|
}
|
|
346
|
+
/** @returns whether the connected extension advertised question-card support. */
|
|
347
|
+
clientSupportsQuestions() {
|
|
348
|
+
return this.current?.clientCaps.questions === true;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Push one unsolicited server frame (question.requested/question.resolved)
|
|
352
|
+
* to the connected extension. No-op when no extension is connected or the
|
|
353
|
+
* socket is already dead.
|
|
354
|
+
*/
|
|
355
|
+
push(frame) {
|
|
356
|
+
const conn = this.current;
|
|
357
|
+
if (conn === null) return;
|
|
358
|
+
sendFrame(conn.ws, frame);
|
|
359
|
+
}
|
|
345
360
|
attach(ws, remoteAddress, origin) {
|
|
346
361
|
let helloTimer = setTimeout(() => {
|
|
347
362
|
ws.close(4001, "hello timeout");
|
|
@@ -363,7 +378,7 @@ var BridgeServer = class {
|
|
|
363
378
|
}
|
|
364
379
|
clearTimeout(helloTimer);
|
|
365
380
|
helloTimer = void 0;
|
|
366
|
-
this.promote(ws, remoteAddress);
|
|
381
|
+
this.promote(ws, remoteAddress, frame.caps, frame.version);
|
|
367
382
|
return;
|
|
368
383
|
}
|
|
369
384
|
this.handleReadyFrame(frame);
|
|
@@ -377,14 +392,16 @@ var BridgeServer = class {
|
|
|
377
392
|
ws.once("error", onClose);
|
|
378
393
|
}
|
|
379
394
|
/** Promote an authenticated socket to the single active slot. */
|
|
380
|
-
promote(ws, remoteAddress) {
|
|
395
|
+
promote(ws, remoteAddress, clientCaps, clientVersion) {
|
|
381
396
|
this.replaceConnection();
|
|
397
|
+
if (clientVersion !== void 0 && this.deps.version !== void 0 && clientVersion !== this.deps.version) this.deps.onVersionMismatch?.(clientVersion);
|
|
382
398
|
const abort = new AbortController();
|
|
383
399
|
const intervalMs = this.deps.pingIntervalMs ?? 3e4;
|
|
384
400
|
const allowed = this.deps.missedPongsAllowed ?? DEFAULT_MISSED_PONGS_ALLOWED;
|
|
385
401
|
const conn = {
|
|
386
402
|
ws,
|
|
387
403
|
remoteAddress,
|
|
404
|
+
clientCaps,
|
|
388
405
|
abort,
|
|
389
406
|
ping: void 0,
|
|
390
407
|
lastPong: Date.now(),
|
|
@@ -401,7 +418,8 @@ var BridgeServer = class {
|
|
|
401
418
|
this.current = conn;
|
|
402
419
|
sendFrame(ws, {
|
|
403
420
|
t: "hello.ok",
|
|
404
|
-
caps: this.deps.caps
|
|
421
|
+
caps: this.deps.caps,
|
|
422
|
+
...this.deps.version === void 0 ? {} : { version: this.deps.version }
|
|
405
423
|
});
|
|
406
424
|
ws.once("close", () => {
|
|
407
425
|
clearInterval(ping);
|
|
@@ -433,6 +451,8 @@ var BridgeServer = class {
|
|
|
433
451
|
case "stream.frame":
|
|
434
452
|
case "stream.error":
|
|
435
453
|
case "tool.call":
|
|
454
|
+
case "question.requested":
|
|
455
|
+
case "question.resolved":
|
|
436
456
|
case "ping":
|
|
437
457
|
case "error": break;
|
|
438
458
|
}
|
|
@@ -477,6 +497,15 @@ var BridgeServer = class {
|
|
|
477
497
|
});
|
|
478
498
|
return;
|
|
479
499
|
}
|
|
500
|
+
if (frame.method === "bridge/questionAnswer") {
|
|
501
|
+
sendFrame(conn.ws, {
|
|
502
|
+
t: "rpc.result",
|
|
503
|
+
id: frame.id,
|
|
504
|
+
ok: true,
|
|
505
|
+
value: this.deps.answerQuestion(frame.args)
|
|
506
|
+
});
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
480
509
|
try {
|
|
481
510
|
const result = await this.deps.dispatchRpc(frame.method, frame.args, conn.abort.signal);
|
|
482
511
|
if (result.ok) sendFrame(conn.ws, {
|
|
@@ -600,6 +629,7 @@ var BridgeServer = class {
|
|
|
600
629
|
this.pendingTools.delete(id);
|
|
601
630
|
pending.reject(new BridgeToolError("bridge-closed", "the extension connection was replaced"));
|
|
602
631
|
}
|
|
632
|
+
this.deps.onConnectionLost?.();
|
|
603
633
|
}
|
|
604
634
|
};
|
|
605
635
|
/**
|
|
@@ -637,73 +667,19 @@ function payloadMessage(payload) {
|
|
|
637
667
|
/**
|
|
638
668
|
* Model-facing browser tools. Every tool executes by dispatching a `tool.call`
|
|
639
669
|
* over the bridge to the connected extension, which performs the action in the
|
|
640
|
-
* user's active tab and returns
|
|
670
|
+
* user's active tab and returns the result.
|
|
641
671
|
*
|
|
642
|
-
* The whole surface is text-only by design (DeepSeek models have no vision):
|
|
643
672
|
* `browser_snapshot` renders the page as structured text with a numbered
|
|
644
|
-
* interactive inventory, and every
|
|
645
|
-
* inventory's stable index
|
|
646
|
-
*
|
|
673
|
+
* interactive inventory, and every action tool addresses elements by that
|
|
674
|
+
* inventory's stable index — text is the addressing scheme, not a vision
|
|
675
|
+
* limitation. `browser_screenshot` is the exception: its capture is saved to
|
|
676
|
+
* the host attachment store and rendered as a native image ContentBlock, so
|
|
677
|
+
* the model sees the page directly (DeepSeek routes on the 0.1.2 line read
|
|
678
|
+
* images natively; text-only routes get the host's automatic placeholder
|
|
679
|
+
* downgrade).
|
|
647
680
|
*
|
|
648
681
|
* @module
|
|
649
682
|
*/
|
|
650
|
-
/** 截图临时目录名(位于 session workspace 下)。 */
|
|
651
|
-
const SCREENSHOT_DIR_NAME = ".dsh-browser-tmp";
|
|
652
|
-
/** 截图目录最多保留的张数,超出自动删最旧(不留垃圾)。 */
|
|
653
|
-
const MAX_SCREENSHOTS = 20;
|
|
654
|
-
/** 截图目录:保存在 session workspace 下(视觉工具能读),失败回退 dshHomePath。 */
|
|
655
|
-
function screenshotDir(workspacePath) {
|
|
656
|
-
return join(workspacePath, SCREENSHOT_DIR_NAME);
|
|
657
|
-
}
|
|
658
|
-
/** 解析 session workspace:优先 exec.agent.session.header.cwd,回退 process.cwd / dshHomePath。 */
|
|
659
|
-
function resolveWorkspace(exec) {
|
|
660
|
-
const cwd = exec.agent?.session?.header?.cwd;
|
|
661
|
-
if (cwd !== void 0 && cwd !== "") return cwd;
|
|
662
|
-
try {
|
|
663
|
-
return process.cwd();
|
|
664
|
-
} catch {
|
|
665
|
-
return dshHomePath("browser-screenshots");
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
/** 保存一张截图(data URL → PNG 文件),返回绝对路径;超上限删最旧。 */
|
|
669
|
-
async function saveScreenshot(dataUrl, workspacePath) {
|
|
670
|
-
const match = /^data:image\/(?:png|jpeg);base64,(.+)$/.exec(dataUrl);
|
|
671
|
-
if (match === null) throw new Error("扩展返回的不是图片 data URL");
|
|
672
|
-
const encoded = match[1];
|
|
673
|
-
if (encoded === void 0) throw new Error("data URL 缺少 base64 内容");
|
|
674
|
-
const dir = screenshotDir(workspacePath);
|
|
675
|
-
await mkdir(dir, { recursive: true });
|
|
676
|
-
const file = join(dir, `screenshot-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`);
|
|
677
|
-
await writeFile(file, Buffer.from(encoded, "base64"));
|
|
678
|
-
await pruneScreenshots(dir);
|
|
679
|
-
return file;
|
|
680
|
-
}
|
|
681
|
-
/** 删除截图目录里最旧的截图,直到数量 <= MAX_SCREENSHOTS。 */
|
|
682
|
-
async function pruneScreenshots(dir) {
|
|
683
|
-
let files;
|
|
684
|
-
try {
|
|
685
|
-
files = (await readdir(dir)).filter((f) => /^screenshot-\d+(?:-[a-z0-9]+)?\.png$/.test(f)).sort();
|
|
686
|
-
} catch {
|
|
687
|
-
return;
|
|
688
|
-
}
|
|
689
|
-
while (files.length > MAX_SCREENSHOTS) {
|
|
690
|
-
const oldest = files.shift();
|
|
691
|
-
if (oldest !== void 0) await unlink(join(dir, oldest)).catch(() => {});
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
/** 清理全部截图,返回删除数量。 */
|
|
695
|
-
async function clearScreenshots(workspacePath) {
|
|
696
|
-
const dir = screenshotDir(workspacePath);
|
|
697
|
-
let count = 0;
|
|
698
|
-
try {
|
|
699
|
-
const files = (await readdir(dir)).filter((f) => /\.png$/.test(f));
|
|
700
|
-
for (const f of files) {
|
|
701
|
-
await unlink(join(dir, f)).catch(() => {});
|
|
702
|
-
count += 1;
|
|
703
|
-
}
|
|
704
|
-
} catch {}
|
|
705
|
-
return count;
|
|
706
|
-
}
|
|
707
683
|
/** Output contract shared by every browser tool. */
|
|
708
684
|
const TEXT_OUTPUT = {
|
|
709
685
|
schema: {
|
|
@@ -719,6 +695,63 @@ const TEXT_OUTPUT = {
|
|
|
719
695
|
}];
|
|
720
696
|
}
|
|
721
697
|
};
|
|
698
|
+
/** Media types the host attachment store accepts (mirrors ImageMediaType). */
|
|
699
|
+
const IMAGE_MEDIA_TYPES = [
|
|
700
|
+
"image/png",
|
|
701
|
+
"image/jpeg",
|
|
702
|
+
"image/webp",
|
|
703
|
+
"image/gif"
|
|
704
|
+
];
|
|
705
|
+
/**
|
|
706
|
+
* Output contract for `browser_screenshot`: the durable image block comes
|
|
707
|
+
* first so the model sees the capture before the caption.
|
|
708
|
+
*/
|
|
709
|
+
const SCREENSHOT_OUTPUT = {
|
|
710
|
+
schema: {
|
|
711
|
+
type: "object",
|
|
712
|
+
additionalProperties: false,
|
|
713
|
+
properties: {
|
|
714
|
+
text: { type: "string" },
|
|
715
|
+
attachment: { type: "object" }
|
|
716
|
+
},
|
|
717
|
+
required: ["text"]
|
|
718
|
+
},
|
|
719
|
+
render: (_args, value) => {
|
|
720
|
+
const result = value;
|
|
721
|
+
return result.attachment === void 0 ? [{
|
|
722
|
+
type: "text",
|
|
723
|
+
text: result.text
|
|
724
|
+
}] : [{
|
|
725
|
+
type: "image",
|
|
726
|
+
attachment: result.attachment
|
|
727
|
+
}, {
|
|
728
|
+
type: "text",
|
|
729
|
+
text: result.text
|
|
730
|
+
}];
|
|
731
|
+
}
|
|
732
|
+
};
|
|
733
|
+
/**
|
|
734
|
+
* Normalize the extension's screenshot payload. Current extensions answer a
|
|
735
|
+
* structured `{ mediaType, data }` (base64 without the data: prefix); 0.4.x
|
|
736
|
+
* extensions answered a raw data URL — kept as the legacy path so a stale
|
|
737
|
+
* extension degrades instead of breaking.
|
|
738
|
+
*/
|
|
739
|
+
function parseScreenshotPayload(result) {
|
|
740
|
+
if (typeof result === "string") {
|
|
741
|
+
const match = /^data:(image\/(?:png|jpeg|webp|gif));base64,(.+)$/.exec(result);
|
|
742
|
+
return match !== null && match[1] !== void 0 && match[2] !== void 0 ? {
|
|
743
|
+
mediaType: match[1],
|
|
744
|
+
data: match[2]
|
|
745
|
+
} : void 0;
|
|
746
|
+
}
|
|
747
|
+
if (typeof result === "object" && result !== null && !Array.isArray(result)) {
|
|
748
|
+
const payload = result;
|
|
749
|
+
if (typeof payload.mediaType === "string" && IMAGE_MEDIA_TYPES.includes(payload.mediaType) && typeof payload.data === "string" && payload.data.length > 0) return {
|
|
750
|
+
mediaType: payload.mediaType,
|
|
751
|
+
data: payload.data
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
}
|
|
722
755
|
/**
|
|
723
756
|
* Register the browser tools on `ctx.tools`. Disposers are returned for the
|
|
724
757
|
* caller's effect to own; each tool's cooperative timeout budget is declared
|
|
@@ -739,7 +772,7 @@ function registerBrowserTools(ctx, bridge, options) {
|
|
|
739
772
|
for (const tool of defineTools(call, options)) disposers.set(tool.name, ctx.tools.register(tool));
|
|
740
773
|
const screenshot = {
|
|
741
774
|
name: "browser_screenshot",
|
|
742
|
-
description: "
|
|
775
|
+
description: "对当前浏览器页面截图,图像直接返回给你查看(原生图像块)。仅在页面内容是图片/公式/验证码等无法用文本表达时才调用(视觉兜底)。",
|
|
743
776
|
parameters: argsSchema({
|
|
744
777
|
fullPage: {
|
|
745
778
|
type: "boolean",
|
|
@@ -751,31 +784,29 @@ function registerBrowserTools(ctx, bridge, options) {
|
|
|
751
784
|
}
|
|
752
785
|
}),
|
|
753
786
|
timeoutMs: options.toolTimeoutMs,
|
|
754
|
-
output:
|
|
787
|
+
output: SCREENSHOT_OUTPUT,
|
|
755
788
|
execute: async (args, exec) => {
|
|
756
789
|
const sessionId = exec.agent?.id;
|
|
757
|
-
const
|
|
758
|
-
|
|
759
|
-
|
|
790
|
+
const payload = parseScreenshotPayload(await bridge.requestTool("browser_screenshot", args, exec.signal, options.toolTimeoutMs, sessionId));
|
|
791
|
+
if (payload === void 0) return { text: "browser_screenshot 返回了无法识别的结果(扩展版本过旧?)" };
|
|
792
|
+
const attachments = ctx.get("attachments");
|
|
793
|
+
if (attachments === void 0) return { text: "宿主未提供图像附件服务(attachments),无法把截图送入模型上下文" };
|
|
760
794
|
try {
|
|
761
|
-
|
|
795
|
+
const attachment = await attachments.saveImage({
|
|
796
|
+
data: Buffer.from(payload.data, "base64"),
|
|
797
|
+
mediaType: payload.mediaType,
|
|
798
|
+
name: `browser-screenshot-${Date.now()}.png`
|
|
799
|
+
});
|
|
800
|
+
return {
|
|
801
|
+
text: `页面截图(${payload.mediaType},${attachment.width}×${attachment.height})`,
|
|
802
|
+
attachment
|
|
803
|
+
};
|
|
762
804
|
} catch (error) {
|
|
763
805
|
return { text: `截图保存失败: ${error instanceof Error ? error.message : String(error)}` };
|
|
764
806
|
}
|
|
765
807
|
}
|
|
766
808
|
};
|
|
767
809
|
disposers.set(screenshot.name, ctx.tools.register(screenshot));
|
|
768
|
-
const clearScreenshotsTool = {
|
|
769
|
-
name: "browser_clear_screenshots",
|
|
770
|
-
description: "删除 browser_screenshot 产生的全部临时截图文件,避免残留垃圾。看完截图后可调用。",
|
|
771
|
-
parameters: argsSchema({}),
|
|
772
|
-
timeoutMs: options.toolTimeoutMs,
|
|
773
|
-
output: TEXT_OUTPUT,
|
|
774
|
-
execute: async (_args, exec) => {
|
|
775
|
-
return { text: `已清理 ${await clearScreenshots(resolveWorkspace(exec))} 张截图` };
|
|
776
|
-
}
|
|
777
|
-
};
|
|
778
|
-
disposers.set(clearScreenshotsTool.name, ctx.tools.register(clearScreenshotsTool));
|
|
779
810
|
return disposers;
|
|
780
811
|
}
|
|
781
812
|
/** Normalize the extension's result payload to the canonical `{ text }` shape. */
|
|
@@ -1209,10 +1240,197 @@ function withSessionWorkspace(dispatch, workspacePath, warn) {
|
|
|
1209
1240
|
};
|
|
1210
1241
|
}
|
|
1211
1242
|
//#endregion
|
|
1243
|
+
//#region lib/types/extension-sessions.js
|
|
1244
|
+
/**
|
|
1245
|
+
* Track session ids that the browser extension has driven through the bridge.
|
|
1246
|
+
* Sessions the extension never touched must keep the host userQuestions
|
|
1247
|
+
* waterfall so the dsh web UI (or any other answerer) renders
|
|
1248
|
+
* ask_user_question cards.
|
|
1249
|
+
* @module
|
|
1250
|
+
*/
|
|
1251
|
+
/** Mutable registry of extension-owned session ids. */
|
|
1252
|
+
var ExtensionSessionRegistry = class {
|
|
1253
|
+
ids = /* @__PURE__ */ new Set();
|
|
1254
|
+
/** Remember a session the extension successfully created or prompted. */
|
|
1255
|
+
note(sessionId) {
|
|
1256
|
+
if (typeof sessionId === "string" && sessionId.length > 0) this.ids.add(sessionId);
|
|
1257
|
+
}
|
|
1258
|
+
/** Whether the extension has touched this session over the bridge. */
|
|
1259
|
+
has(sessionId) {
|
|
1260
|
+
return typeof sessionId === "string" && this.ids.has(sessionId);
|
|
1261
|
+
}
|
|
1262
|
+
/** Test helper: drop all tracked ids. */
|
|
1263
|
+
clear() {
|
|
1264
|
+
this.ids.clear();
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
/**
|
|
1268
|
+
* Decide whether the bridge should own ask_user_question for this request.
|
|
1269
|
+
* All three gates must pass: an extension is connected, that extension
|
|
1270
|
+
* advertised question-card support in its hello caps, and the asking session
|
|
1271
|
+
* was driven over the bridge. Everything else falls through to `next()` so
|
|
1272
|
+
* the native answerer waterfall (dsh web) keeps working.
|
|
1273
|
+
*/
|
|
1274
|
+
function shouldBridgeOwnQuestion(input) {
|
|
1275
|
+
return input.hasExtensionConnection && input.clientSupportsQuestions && input.sessionId !== void 0 && input.extensionSessions.has(input.sessionId);
|
|
1276
|
+
}
|
|
1277
|
+
//#endregion
|
|
1278
|
+
//#region lib/types/questions.js
|
|
1279
|
+
/**
|
|
1280
|
+
* ask_user_question ownership: claim the host `user-questions/request`
|
|
1281
|
+
* waterfall for extension-owned sessions, push the question to the connected
|
|
1282
|
+
* extension, and settle the waterfall with the sidebar's answer.
|
|
1283
|
+
*
|
|
1284
|
+
* Settlement races (first wins, later ones see `settled` and no-op):
|
|
1285
|
+
* - the extension answers ({@link answer}) → waterfall resolves;
|
|
1286
|
+
* - the extension declines → waterfall rejects (the tool call fails, the
|
|
1287
|
+
* model is told the user refused);
|
|
1288
|
+
* - the host aborts `request.signal` (turn cancelled, session disposed) →
|
|
1289
|
+
* the extension is sent `question.resolved` and the waterfall rejects;
|
|
1290
|
+
* - the bridge connection drops ({@link delegateAll}) → the waterfall is
|
|
1291
|
+
* delegated to `next()` so another answerer (dsh web) can still serve it;
|
|
1292
|
+
* - plugin unload ({@link dispose}) → everything rejects promptly.
|
|
1293
|
+
*
|
|
1294
|
+
* @module
|
|
1295
|
+
*/
|
|
1296
|
+
/** Error matching the host's ASK_ABORTED semantics (the service remaps it). */
|
|
1297
|
+
function abortedError() {
|
|
1298
|
+
return /* @__PURE__ */ new Error("ask_user_question was aborted before the user answered");
|
|
1299
|
+
}
|
|
1300
|
+
function declinedError() {
|
|
1301
|
+
return /* @__PURE__ */ new Error("ask_user_question was declined by the user in the browser sidebar");
|
|
1302
|
+
}
|
|
1303
|
+
/** Structural validation of the extension's answer payload. */
|
|
1304
|
+
function asAnswerPayload(value, questionIds) {
|
|
1305
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
1306
|
+
const answers = value.answers;
|
|
1307
|
+
if (!Array.isArray(answers)) return void 0;
|
|
1308
|
+
const items = [];
|
|
1309
|
+
for (const entry of answers) {
|
|
1310
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return void 0;
|
|
1311
|
+
const item = entry;
|
|
1312
|
+
if (typeof item.id !== "string" || !questionIds.has(item.id)) return void 0;
|
|
1313
|
+
if (!Array.isArray(item.selected) || item.selected.some((option) => typeof option !== "string")) return void 0;
|
|
1314
|
+
if (item.custom !== void 0 && typeof item.custom !== "string") return void 0;
|
|
1315
|
+
items.push({
|
|
1316
|
+
id: item.id,
|
|
1317
|
+
selected: item.selected,
|
|
1318
|
+
...typeof item.custom === "string" ? { custom: item.custom } : {}
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
return { answers: items };
|
|
1322
|
+
}
|
|
1323
|
+
/** Parse the extension's `bridge/questionAnswer` rpc args (light: ids only). */
|
|
1324
|
+
function asQuestionAnswerArgs(value) {
|
|
1325
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
1326
|
+
const args = value;
|
|
1327
|
+
return typeof args.questionId === "string" && typeof args.sessionId === "string" ? value : void 0;
|
|
1328
|
+
}
|
|
1329
|
+
/** Owns the user-questions waterfall for extension-driven sessions. */
|
|
1330
|
+
var QuestionBridge = class {
|
|
1331
|
+
deps;
|
|
1332
|
+
pending = /* @__PURE__ */ new Map();
|
|
1333
|
+
constructor(deps) {
|
|
1334
|
+
this.deps = deps;
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* Own one host waterfall request: push `question.requested` to the
|
|
1338
|
+
* extension and suspend until one of the settlement races wins.
|
|
1339
|
+
*
|
|
1340
|
+
* @param sessionId - asking session (already ownership-checked by the caller).
|
|
1341
|
+
* @param questions - host question items (forwarded verbatim).
|
|
1342
|
+
* @param next - waterfall delegation, used when the bridge connection drops.
|
|
1343
|
+
* @param signal - host cancellation lifetime for this request.
|
|
1344
|
+
* @returns the user's answer.
|
|
1345
|
+
*/
|
|
1346
|
+
ask(sessionId, questions, next, signal) {
|
|
1347
|
+
if (signal?.aborted) return Promise.reject(abortedError());
|
|
1348
|
+
const questionId = randomUUID();
|
|
1349
|
+
return new Promise((resolve, reject) => {
|
|
1350
|
+
const entry = {
|
|
1351
|
+
sessionId,
|
|
1352
|
+
questionIds: new Set(questions.map((question) => question.id)),
|
|
1353
|
+
settled: false,
|
|
1354
|
+
signal,
|
|
1355
|
+
complete: (outcome) => {
|
|
1356
|
+
if (entry.settled) return;
|
|
1357
|
+
entry.settled = true;
|
|
1358
|
+
this.pending.delete(questionId);
|
|
1359
|
+
if (entry.onAbort !== void 0) entry.signal?.removeEventListener("abort", entry.onAbort);
|
|
1360
|
+
if (outcome.kind === "answer") resolve(outcome.answer);
|
|
1361
|
+
else if (outcome.kind === "reject") reject(outcome.error);
|
|
1362
|
+
else next().then(resolve, reject);
|
|
1363
|
+
},
|
|
1364
|
+
onAbort: void 0
|
|
1365
|
+
};
|
|
1366
|
+
if (signal !== void 0) {
|
|
1367
|
+
entry.onAbort = () => {
|
|
1368
|
+
this.deps.push({
|
|
1369
|
+
t: "question.resolved",
|
|
1370
|
+
id: questionId,
|
|
1371
|
+
sessionId
|
|
1372
|
+
});
|
|
1373
|
+
entry.complete({
|
|
1374
|
+
kind: "reject",
|
|
1375
|
+
error: abortedError()
|
|
1376
|
+
});
|
|
1377
|
+
};
|
|
1378
|
+
signal.addEventListener("abort", entry.onAbort, { once: true });
|
|
1379
|
+
}
|
|
1380
|
+
this.pending.set(questionId, entry);
|
|
1381
|
+
this.deps.push({
|
|
1382
|
+
t: "question.requested",
|
|
1383
|
+
id: questionId,
|
|
1384
|
+
sessionId,
|
|
1385
|
+
questions
|
|
1386
|
+
});
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Settle one pending question from the extension's `bridge/questionAnswer`
|
|
1391
|
+
* rpc. The server replies with this receipt.
|
|
1392
|
+
*/
|
|
1393
|
+
answer(args) {
|
|
1394
|
+
const entry = this.pending.get(args.questionId);
|
|
1395
|
+
if (entry === void 0 || entry.settled || entry.sessionId !== args.sessionId) return {
|
|
1396
|
+
accepted: false,
|
|
1397
|
+
reason: "not-pending"
|
|
1398
|
+
};
|
|
1399
|
+
if (args.decline === true) {
|
|
1400
|
+
entry.complete({
|
|
1401
|
+
kind: "reject",
|
|
1402
|
+
error: declinedError()
|
|
1403
|
+
});
|
|
1404
|
+
return { accepted: true };
|
|
1405
|
+
}
|
|
1406
|
+
const answer = asAnswerPayload(args.answer, entry.questionIds);
|
|
1407
|
+
if (answer === void 0) return {
|
|
1408
|
+
accepted: false,
|
|
1409
|
+
reason: "bad-answer"
|
|
1410
|
+
};
|
|
1411
|
+
entry.complete({
|
|
1412
|
+
kind: "answer",
|
|
1413
|
+
answer
|
|
1414
|
+
});
|
|
1415
|
+
return { accepted: true };
|
|
1416
|
+
}
|
|
1417
|
+
/** Bridge connection replaced/closed: delegate every unsettled question. */
|
|
1418
|
+
delegateAll() {
|
|
1419
|
+
for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({ kind: "delegate" });
|
|
1420
|
+
}
|
|
1421
|
+
/** Plugin unload: reject everything so no tool call outlives the plugin. */
|
|
1422
|
+
dispose() {
|
|
1423
|
+
for (const entry of [...this.pending.values()]) if (!entry.settled) entry.complete({
|
|
1424
|
+
kind: "reject",
|
|
1425
|
+
error: /* @__PURE__ */ new Error("browser bridge plugin was unloaded")
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
};
|
|
1429
|
+
//#endregion
|
|
1212
1430
|
//#region lib/types/index.js
|
|
1213
1431
|
/**
|
|
1214
1432
|
* `@deepseek-ai/dsh-bridge-browser`: token-authenticated WebSocket bridge for
|
|
1215
|
-
* the browser extension plus the
|
|
1433
|
+
* the browser extension plus the `browser_*` tool set.
|
|
1216
1434
|
*
|
|
1217
1435
|
* The bridge mounts its own upgrade route (`/ext/bridge`) on the host
|
|
1218
1436
|
* webserver, OUTSIDE the /api trust fence — so it brings its own bearer-token
|
|
@@ -1222,7 +1440,15 @@ function withSessionWorkspace(dispatch, workspacePath, warn) {
|
|
|
1222
1440
|
* `ctx.typertGateway.invoke`, and `stream.open` frames open
|
|
1223
1441
|
* `ctx.typertGateway.stream` subscriptions whose native follow frames flow
|
|
1224
1442
|
* back unmodified. Tools execute by dispatching `tool.call` frames to the
|
|
1225
|
-
* connected extension, which performs the action in the user's active tab
|
|
1443
|
+
* connected extension, which performs the action in the user's active tab;
|
|
1444
|
+
* `browser_screenshot` returns a native image block (the host attachment
|
|
1445
|
+
* store owns the bytes), so the model sees the page directly.
|
|
1446
|
+
*
|
|
1447
|
+
* For sessions the extension has created or prompted, the plugin also claims
|
|
1448
|
+
* the host `user-questions/request` waterfall (prepended listener) and pushes
|
|
1449
|
+
* `question.requested` to the extension, so the user answers
|
|
1450
|
+
* ask_user_question in the sidebar instead of the dsh web UI. Every other
|
|
1451
|
+
* session delegates to `next()`.
|
|
1226
1452
|
*
|
|
1227
1453
|
* Opt-in by design: nothing is registered unless this plugin appears in the
|
|
1228
1454
|
* composition. No dsh core code is touched.
|
|
@@ -1259,6 +1485,12 @@ const Config = z.object({
|
|
|
1259
1485
|
function assertPositiveInteger(name, value) {
|
|
1260
1486
|
if (!Number.isInteger(value) || value < 1) throw new Error(`bridge-browser: ${name} must be a positive integer`);
|
|
1261
1487
|
}
|
|
1488
|
+
/** Extract the session id from an rpc args/result object, when present. */
|
|
1489
|
+
function sessionIdOf(value) {
|
|
1490
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
1491
|
+
const sessionId = value.sessionId;
|
|
1492
|
+
return typeof sessionId === "string" && sessionId.length > 0 ? sessionId : void 0;
|
|
1493
|
+
}
|
|
1262
1494
|
/**
|
|
1263
1495
|
* Apply defaults and direct-call validation at the plugin boundary.
|
|
1264
1496
|
* @param config - Loader-resolved or directly supplied plugin configuration.
|
|
@@ -1312,9 +1544,28 @@ async function apply(ctx, config) {
|
|
|
1312
1544
|
const dispatchRpc = withSessionDeferral(withSessionWorkspace(invoke, resolved.sessionWorkspacePath, (message) => {
|
|
1313
1545
|
ctx.logger.warn(message);
|
|
1314
1546
|
}), resolved.deferSessionCreate);
|
|
1547
|
+
const extensionSessions = new ExtensionSessionRegistry();
|
|
1548
|
+
const notingDispatchRpc = async (method, args, signal) => {
|
|
1549
|
+
const result = await dispatchRpc(method, args, signal);
|
|
1550
|
+
if (result.ok && (method === "session/create" || method === "session/prompt")) {
|
|
1551
|
+
extensionSessions.note(sessionIdOf(args.request));
|
|
1552
|
+
extensionSessions.note(sessionIdOf(result.value));
|
|
1553
|
+
}
|
|
1554
|
+
return result;
|
|
1555
|
+
};
|
|
1556
|
+
let pluginVersion;
|
|
1557
|
+
try {
|
|
1558
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
1559
|
+
pluginVersion = typeof pkg.version === "string" ? pkg.version : void 0;
|
|
1560
|
+
} catch {
|
|
1561
|
+
pluginVersion = void 0;
|
|
1562
|
+
}
|
|
1563
|
+
const questions = new QuestionBridge({ push: (frame) => {
|
|
1564
|
+
server.push(frame);
|
|
1565
|
+
} });
|
|
1315
1566
|
const server = new BridgeServer({
|
|
1316
1567
|
token: tokenRes.token,
|
|
1317
|
-
dispatchRpc,
|
|
1568
|
+
dispatchRpc: notingDispatchRpc,
|
|
1318
1569
|
openStream: (method, args, signal) => {
|
|
1319
1570
|
const slash = method.indexOf("/");
|
|
1320
1571
|
const namespace = slash === -1 ? method : method.slice(0, slash);
|
|
@@ -1326,13 +1577,42 @@ async function apply(ctx, config) {
|
|
|
1326
1577
|
signal
|
|
1327
1578
|
});
|
|
1328
1579
|
},
|
|
1580
|
+
answerQuestion: (args) => {
|
|
1581
|
+
const parsed = asQuestionAnswerArgs(args);
|
|
1582
|
+
return parsed === void 0 ? {
|
|
1583
|
+
accepted: false,
|
|
1584
|
+
reason: "bad-answer"
|
|
1585
|
+
} : questions.answer(parsed);
|
|
1586
|
+
},
|
|
1587
|
+
onConnectionLost: () => {
|
|
1588
|
+
questions.delegateAll();
|
|
1589
|
+
},
|
|
1590
|
+
version: pluginVersion,
|
|
1591
|
+
onVersionMismatch: (clientVersion) => {
|
|
1592
|
+
ctx.logger.warn(`browser extension version ${clientVersion} != plugin version ${pluginVersion ?? "?"}; both components must be updated together`);
|
|
1593
|
+
},
|
|
1329
1594
|
toolTimeoutMs: resolved.toolTimeoutMs,
|
|
1330
1595
|
caps: {
|
|
1331
|
-
textOnly: true,
|
|
1332
1596
|
snapshotMaxChars: resolved.snapshotMaxChars,
|
|
1333
1597
|
maxInteractiveItems: resolved.maxInteractiveItems
|
|
1334
1598
|
}
|
|
1335
1599
|
});
|
|
1600
|
+
ctx.effect(() => {
|
|
1601
|
+
const disposeListener = ctx.on("user-questions/request", (request, next) => {
|
|
1602
|
+
const sessionId = request.agent?.id;
|
|
1603
|
+
if (sessionId === void 0 || !shouldBridgeOwnQuestion({
|
|
1604
|
+
hasExtensionConnection: server.hasConnection(),
|
|
1605
|
+
clientSupportsQuestions: server.clientSupportsQuestions(),
|
|
1606
|
+
sessionId,
|
|
1607
|
+
extensionSessions
|
|
1608
|
+
})) return next();
|
|
1609
|
+
return questions.ask(sessionId, request.questions, next, request.signal);
|
|
1610
|
+
}, { prepend: true });
|
|
1611
|
+
return () => {
|
|
1612
|
+
disposeListener();
|
|
1613
|
+
questions.dispose();
|
|
1614
|
+
};
|
|
1615
|
+
}, "bridge-browser: user-questions answerer");
|
|
1336
1616
|
const route = {
|
|
1337
1617
|
path: BRIDGE_PATH,
|
|
1338
1618
|
handler: (req, socket, head) => {
|
|
@@ -1376,7 +1656,7 @@ async function apply(ctx, config) {
|
|
|
1376
1656
|
if (systemPrompt !== void 0) ctx.effect(() => systemPrompt.section({
|
|
1377
1657
|
name: "tool:bridge-browser",
|
|
1378
1658
|
order: 107,
|
|
1379
|
-
text: "A browser bridge may be connected. To read or operate the user's active browser page, call browser_snapshot (text-only; numbered items are the click/type targets). Never assume page content you have not snapshot."
|
|
1659
|
+
text: "A browser bridge may be connected. To read or operate the user's active browser page, call browser_snapshot (text-only; numbered items are the click/type targets). For content that defies text (images, charts, captchas), call browser_screenshot: the image is returned to you directly. Never assume page content you have not snapshot."
|
|
1380
1660
|
}), "bridge-browser: system prompt section");
|
|
1381
1661
|
ctx.logger.info(tokenRes.generated ? `browser bridge: new token generated and persisted at ${tokenRes.file} (chmod 0600); connect the extension and paste it in its settings` : `browser bridge: using token from ${tokenRes.file}`);
|
|
1382
1662
|
ctx.logger.info(`browser bridge: listening on ${BRIDGE_PATH}`);
|