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