dsh-browser-firefox 0.3.0

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 ADDED
@@ -0,0 +1,1182 @@
1
+ import { BRIDGE_CONFIG_PATH, BRIDGE_PATH, parseBridgeFrame } from "./protocol.js";
2
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { RpcId } from "@deepseek-ai/dsh-host-apiproxy/api";
5
+ import { toFetchHandler } from "@deepseek-ai/dsh-host-apiproxy";
6
+ import { dshHomePath } from "@deepseek-ai/dsh-home-paths";
7
+ import { WebSocket, WebSocketServer } from "ws";
8
+ import { chmod, mkdir, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
9
+ import { dirname, join } from "node:path";
10
+ //#region lib/types/token.js
11
+ /**
12
+ * Bridge bearer-token lifecycle: generation, constant-time verification, and
13
+ * file persistence under the dsh home directory.
14
+ *
15
+ * The token authenticates the browser extension against the bridge WebSocket.
16
+ * It is NOT the /api trust fence (that stays untouched); it is the bridge
17
+ * path's own auth because the bridge route lives outside the fence by design.
18
+ *
19
+ * @module
20
+ */
21
+ /** File name of the persisted token inside the dsh home. */
22
+ const TOKEN_FILE_NAME = "ext-bridge-token";
23
+ /**
24
+ * Generate a fresh token as lowercase hex.
25
+ * @param bytes - entropy bytes; defaults to DEFAULT_TOKEN_BYTES (256-bit).
26
+ * @returns the hex token string.
27
+ */
28
+ function generateToken(bytes = 32) {
29
+ return randomBytes(bytes).toString("hex");
30
+ }
31
+ /**
32
+ * Constant-time token comparison. Length mismatch fails fast (still constant
33
+ * time on the compared prefix) — a wrong-length token can never verify.
34
+ * @param expected - the configured token.
35
+ * @param actual - the token presented by the client.
36
+ * @returns true only when both are equal-length hex and byte-equal.
37
+ */
38
+ function verifyToken(expected, actual) {
39
+ const expectedBuf = Buffer.from(expected, "utf8");
40
+ const actualBuf = Buffer.from(actual, "utf8");
41
+ if (expectedBuf.length === 0 || expectedBuf.length !== actualBuf.length) return false;
42
+ return timingSafeEqual(expectedBuf, actualBuf);
43
+ }
44
+ /**
45
+ * Path of the persisted token file under the dsh home.
46
+ * @returns absolute path like `~/.dsh/ext-bridge-token`.
47
+ */
48
+ function tokenFilePath() {
49
+ return dshHomePath(TOKEN_FILE_NAME);
50
+ }
51
+ /**
52
+ * Read the persisted token; returns undefined when absent or unreadable.
53
+ * @param file - token file path.
54
+ * @returns the stored hex token, trimmed.
55
+ */
56
+ async function readTokenFile(file = tokenFilePath()) {
57
+ try {
58
+ return (await readFile(file, "utf8")).trim();
59
+ } catch {
60
+ return;
61
+ }
62
+ }
63
+ /**
64
+ * Persist a token atomically (temp file + rename) with 0600 permissions.
65
+ * @param token - hex token to persist.
66
+ * @param file - token file path.
67
+ */
68
+ async function writeTokenFile(token, file = tokenFilePath()) {
69
+ await mkdir(dirname(file), { recursive: true });
70
+ const temp = `${file}.tmp-${process.pid}`;
71
+ await writeFile(temp, `${token}\n`, { mode: 384 });
72
+ await chmod(temp, 384);
73
+ await rename(temp, file);
74
+ }
75
+ /**
76
+ * Resolve the bridge token: an explicitly configured token wins; otherwise the
77
+ * persisted file is reused when present, and a fresh token is generated and
78
+ * persisted otherwise.
79
+ * @param configured - token from plugin config, or undefined.
80
+ * @param file - token file path (injectable for tests).
81
+ * @returns `{ token, file, generated }` where `generated` records whether a new token was minted.
82
+ */
83
+ async function resolveToken(configured, file = tokenFilePath()) {
84
+ if (configured !== void 0 && configured.length > 0) return {
85
+ token: configured,
86
+ file,
87
+ generated: false
88
+ };
89
+ const persisted = await readTokenFile(file);
90
+ if (persisted !== void 0 && persisted.length > 0) return {
91
+ token: persisted,
92
+ file,
93
+ generated: false
94
+ };
95
+ const token = generateToken();
96
+ await writeTokenFile(token, file);
97
+ return {
98
+ token,
99
+ file,
100
+ generated: true
101
+ };
102
+ }
103
+ //#endregion
104
+ //#region lib/types/server.js
105
+ /**
106
+ * Bridge WebSocket carrier: token-authenticated connection registry, gateway
107
+ * RPC passthrough, per-connection event pump, and tool-call dispatch to the
108
+ * connected browser extension.
109
+ *
110
+ * The route this server mounts (`/ext/bridge`) lives OUTSIDE the /api trust
111
+ * fence (which only guards the client-connection routes), so the bridge brings
112
+ * its own authentication: a bearer token presented in the `hello` frame within
113
+ * HELLO_TIMEOUT_MS. Gateway RPCs are dispatched through the same fetch-shaped
114
+ * handler the /api carrier uses (`toFetchHandler`), so schema validation and
115
+ * error envelopes are identical to the GUI path. Methods the /api carrier
116
+ * pins to loopback (`PRIVILEGED_METHODS`) stay loopback-only here regardless
117
+ * of the token, defense in depth for `--host 0.0.0.0` deployments.
118
+ *
119
+ * One active connection at a time: a new authenticated socket replaces the
120
+ * previous one (the old socket is closed and its in-flight tool calls settle
121
+ * as `bridge-closed`).
122
+ *
123
+ * @module
124
+ */
125
+ /**
126
+ * Gateway methods the /api carrier pins to loopback (mirror of
127
+ * client-connection's PRIVILEGED_METHODS; kept verbatim so the two fences
128
+ * cannot drift). The bridge rejects these for non-loopback remotes even with
129
+ * a valid token.
130
+ */
131
+ const PRIVILEGED_METHODS = /* @__PURE__ */ new Set([
132
+ "host.pickDirectory",
133
+ "host.openPath",
134
+ "settings.describe",
135
+ "settings.openDocument",
136
+ "settings.update",
137
+ "settings.replace",
138
+ "settings.mutate",
139
+ "credentials.describe",
140
+ "credentials.set",
141
+ "credentials.unset"
142
+ ]);
143
+ /** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
144
+ function isLoopbackAddress(address) {
145
+ return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
146
+ }
147
+ /** Error thrown by requestTool; the tool registry turns it into an isError result. */
148
+ var BridgeToolError = class extends Error {
149
+ code;
150
+ constructor(code, message) {
151
+ super(message);
152
+ this.code = code;
153
+ this.name = "BridgeToolError";
154
+ }
155
+ };
156
+ function sendFrame(ws, frame) {
157
+ /* v8 ignore next -- teardown race: the socket can die between a pump's
158
+ readiness check and this write; the guard refuses writes on dead sockets */
159
+ if (ws.readyState !== WebSocket.OPEN) return;
160
+ ws.send(JSON.stringify(frame));
161
+ }
162
+ /**
163
+ * Decode one ws message payload to text. Exported so all three delivery
164
+ * shapes (fragmented buffer list, Buffer, ArrayBuffer) are unit-testable
165
+ * directly — node ws only ever delivers Buffers in practice.
166
+ * @param data - ws message payload.
167
+ * @returns the decoded UTF-8 text.
168
+ */
169
+ function messageToText(data) {
170
+ if (Array.isArray(data)) return Buffer.concat(data).toString("utf8");
171
+ if (Buffer.isBuffer(data)) return data.toString("utf8");
172
+ return Buffer.from(data).toString("utf8");
173
+ }
174
+ /**
175
+ * Token-authenticated bridge server. Construct once per plugin instance;
176
+ * dispose with {@link close}.
177
+ */
178
+ var BridgeServer = class {
179
+ deps;
180
+ wss = new WebSocketServer({ noServer: true });
181
+ current = null;
182
+ pendingTools = /* @__PURE__ */ new Map();
183
+ closed = false;
184
+ constructor(deps) {
185
+ this.deps = deps;
186
+ }
187
+ /**
188
+ * Handle one HTTP upgrade for the bridge path.
189
+ * @param req - upgrade request (carries the client's remote address).
190
+ * @param socket - raw socket transferred by the HTTP server.
191
+ * @param head - bytes already read after the upgrade headers.
192
+ */
193
+ handleUpgrade(req, socket, head) {
194
+ const remote = this.deps.remoteAddressOverride ?? req.socket.remoteAddress;
195
+ const origin = req.headers.origin;
196
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
197
+ this.attach(ws, remote, origin);
198
+ });
199
+ }
200
+ /**
201
+ * Request one browser action from the connected extension.
202
+ * @param name - tool name (also the wire action name).
203
+ * @param args - validated tool arguments.
204
+ * @param signal - caller cancellation (abort settles the call as cancelled).
205
+ * @param timeoutMs - per-call budget; defaults to the plugin config value.
206
+ * @returns the extension's action result.
207
+ * @throws BridgeToolError when no extension is connected, the call times
208
+ * out, is cancelled, or the extension reports a failure.
209
+ */
210
+ requestTool(name, args, signal, timeoutMs = this.deps.toolTimeoutMs, sessionId, title) {
211
+ const conn = this.current;
212
+ if (conn === null) throw new BridgeToolError("bridge-closed", "no browser extension is connected to the bridge");
213
+ if (signal.aborted) throw new BridgeToolError("bridge-closed", "tool call cancelled before dispatch");
214
+ const id = randomUUID();
215
+ return new Promise((resolve, reject) => {
216
+ let timer;
217
+ const settle = (error) => {
218
+ clearTimeout(timer);
219
+ this.pendingTools.delete(id);
220
+ signal.removeEventListener("abort", onAbort);
221
+ reject(error);
222
+ };
223
+ const onAbort = () => {
224
+ settle(new BridgeToolError("bridge-closed", "tool call cancelled before the extension answered"));
225
+ };
226
+ timer = setTimeout(() => {
227
+ settle(new BridgeToolError("timeout", `browser action "${name}" timed out after ${timeoutMs}ms`));
228
+ }, timeoutMs);
229
+ signal.addEventListener("abort", onAbort, { once: true });
230
+ this.pendingTools.set(id, {
231
+ resolve,
232
+ reject,
233
+ timer
234
+ });
235
+ const callFrame = {
236
+ t: "tool.call",
237
+ id,
238
+ name,
239
+ args,
240
+ ...sessionId !== void 0 ? { sessionId } : {},
241
+ ...title !== void 0 ? { title } : {}
242
+ };
243
+ conn.ws.send(JSON.stringify(callFrame), (error) => {
244
+ /* v8 ignore next -- teardown race: when the write fails, the socket's
245
+ close handler settles the same call with the same code; the callback
246
+ path is a defensive second settle, covered via the close path */
247
+ if (error != null) settle(new BridgeToolError("bridge-closed", `bridge socket failed before delivery: ${error.message}`));
248
+ });
249
+ });
250
+ }
251
+ /**
252
+ * Terminate the server: close the acceptor, drop all sockets, reject all
253
+ * in-flight tool calls.
254
+ * @returns a promise resolving after the acceptor and all pumps stop.
255
+ */
256
+ async close() {
257
+ if (this.closed) return;
258
+ this.closed = true;
259
+ const pumps = this.current === null ? [] : [this.current.pump];
260
+ this.replaceConnection();
261
+ for (const socket of this.wss.clients) socket.terminate();
262
+ this.current = null;
263
+ await new Promise((resolve, reject) => {
264
+ this.wss.close((error) => {
265
+ /* v8 ignore next -- acceptor close cannot fail: close() is idempotent
266
+ and the noServer acceptor only reports teardown of already-terminated clients */
267
+ if (error === void 0) resolve();
268
+ else reject(error);
269
+ });
270
+ });
271
+ await Promise.all(pumps);
272
+ }
273
+ /** @returns whether an authenticated extension is currently connected. */
274
+ hasConnection() {
275
+ return this.current !== null;
276
+ }
277
+ attach(ws, remoteAddress, origin) {
278
+ let helloTimer = setTimeout(() => {
279
+ ws.close(4001, "hello timeout");
280
+ }, this.deps.helloTimeoutMs ?? 5e3);
281
+ const onMessage = (data) => {
282
+ const frame = parseBridgeFrame(messageToText(data));
283
+ if (frame === void 0) {
284
+ ws.close(1008, "unparseable frame");
285
+ return;
286
+ }
287
+ if (helloTimer !== void 0) {
288
+ if (frame.t !== "hello") {
289
+ ws.close(1008, "hello first");
290
+ return;
291
+ }
292
+ if (!(isLoopbackAddress(remoteAddress) && typeof origin === "string" && (origin.startsWith("chrome-extension://") || origin.startsWith("moz-extension://"))) && !verifyToken(this.deps.token, frame.token)) {
293
+ ws.close(4002, "bad token");
294
+ return;
295
+ }
296
+ clearTimeout(helloTimer);
297
+ helloTimer = void 0;
298
+ this.promote(ws, remoteAddress);
299
+ return;
300
+ }
301
+ this.handleReadyFrame(frame);
302
+ };
303
+ const onClose = () => {
304
+ if (helloTimer !== void 0) clearTimeout(helloTimer);
305
+ if (this.current !== null && this.current.ws === ws) this.replaceConnection();
306
+ };
307
+ ws.on("message", onMessage);
308
+ ws.once("close", onClose);
309
+ ws.once("error", onClose);
310
+ }
311
+ /** Promote an authenticated socket to the single active slot. */
312
+ promote(ws, remoteAddress) {
313
+ this.replaceConnection();
314
+ const abort = new AbortController();
315
+ const ping = setInterval(() => {
316
+ sendFrame(ws, { t: "ping" });
317
+ }, this.deps.pingIntervalMs ?? 3e4);
318
+ const pump = (async () => {
319
+ try {
320
+ for await (const envelope of this.deps.openEvents(abort.signal)) {
321
+ if (ws.readyState !== WebSocket.OPEN) break;
322
+ sendFrame(ws, {
323
+ t: "event",
324
+ frame: {
325
+ rpcId: envelope.rpcId,
326
+ method: envelope.payload.type,
327
+ payload: envelope.payload
328
+ }
329
+ });
330
+ }
331
+ } catch (error) {
332
+ if (!abort.signal.aborted && ws.readyState === WebSocket.OPEN) sendFrame(ws, {
333
+ t: "error",
334
+ code: "stream-failed",
335
+ message: String(error)
336
+ });
337
+ }
338
+ })();
339
+ this.current = {
340
+ ws,
341
+ remoteAddress,
342
+ abort,
343
+ pump,
344
+ ping
345
+ };
346
+ sendFrame(ws, {
347
+ t: "hello.ok",
348
+ caps: this.deps.caps
349
+ });
350
+ ws.once("close", () => {
351
+ clearInterval(ping);
352
+ abort.abort();
353
+ });
354
+ }
355
+ handleReadyFrame(frame) {
356
+ switch (frame.t) {
357
+ case "rpc":
358
+ this.handleRpc(frame);
359
+ break;
360
+ case "tool.result":
361
+ this.settleTool(frame.id, frame.ok, frame.ok ? frame.result : frame.error);
362
+ break;
363
+ case "pong":
364
+ case "hello":
365
+ case "hello.ok":
366
+ case "rpc.result":
367
+ case "event":
368
+ case "tool.call":
369
+ case "ping":
370
+ case "error": break;
371
+ }
372
+ }
373
+ async handleRpc(frame) {
374
+ const conn = this.current;
375
+ /* v8 ignore next -- replacement race: a frame can land between a socket
376
+ replacement and the next promotion; the re-check keeps the handler total */
377
+ if (conn === null) return;
378
+ if (PRIVILEGED_METHODS.has(frame.method) && !isLoopbackAddress(conn.remoteAddress)) {
379
+ sendFrame(conn.ws, {
380
+ t: "rpc.result",
381
+ id: frame.id,
382
+ ok: false,
383
+ error: {
384
+ code: "forbidden",
385
+ message: "method is loopback-only"
386
+ }
387
+ });
388
+ return;
389
+ }
390
+ const body = JSON.stringify({
391
+ type: "client-request",
392
+ rpcId: frame.id,
393
+ method: frame.method,
394
+ payload: frame.payload
395
+ });
396
+ const request = new Request(new URL(`/api/${frame.method}`, "http://dsh.internal"), {
397
+ method: "POST",
398
+ headers: { "content-type": "application/json" },
399
+ body
400
+ });
401
+ try {
402
+ const response = await this.deps.apiHandler.fetch(request);
403
+ const text = await response.text();
404
+ if (!response.ok) {
405
+ sendFrame(conn.ws, {
406
+ t: "rpc.result",
407
+ id: frame.id,
408
+ ok: false,
409
+ error: {
410
+ code: "http",
411
+ message: text
412
+ }
413
+ });
414
+ return;
415
+ }
416
+ let result;
417
+ try {
418
+ result = JSON.parse(text);
419
+ } catch {
420
+ result = text;
421
+ }
422
+ sendFrame(conn.ws, {
423
+ t: "rpc.result",
424
+ id: frame.id,
425
+ ok: true,
426
+ result
427
+ });
428
+ } catch (error) {
429
+ sendFrame(conn.ws, {
430
+ t: "rpc.result",
431
+ id: frame.id,
432
+ ok: false,
433
+ error: {
434
+ code: "internal",
435
+ message: String(error)
436
+ }
437
+ });
438
+ }
439
+ }
440
+ settleTool(id, ok, payload) {
441
+ const pending = this.pendingTools.get(id);
442
+ if (pending === void 0) return;
443
+ clearTimeout(pending.timer);
444
+ this.pendingTools.delete(id);
445
+ if (ok) pending.resolve(payload);
446
+ else pending.reject(new BridgeToolError(payloadCode(payload), payloadMessage(payload)));
447
+ }
448
+ /** Close the current connection (if any) and settle its in-flight calls. */
449
+ replaceConnection() {
450
+ const conn = this.current;
451
+ if (conn === null) return;
452
+ this.current = null;
453
+ clearInterval(conn.ping);
454
+ conn.abort.abort();
455
+ if (conn.ws.readyState === WebSocket.OPEN || conn.ws.readyState === WebSocket.CONNECTING) conn.ws.close(4e3, "replaced");
456
+ for (const [id, pending] of this.pendingTools) {
457
+ clearTimeout(pending.timer);
458
+ this.pendingTools.delete(id);
459
+ pending.reject(new BridgeToolError("bridge-closed", "the extension connection was replaced"));
460
+ }
461
+ }
462
+ };
463
+ /**
464
+ * Tool error payload → stable code. The wire parser enforces string fields,
465
+ * so the fallback branches are parser-gated; exported so the fallback
466
+ * contract is unit-testable directly.
467
+ * @param payload - extension-reported error payload.
468
+ * @returns the stable error code.
469
+ */
470
+ function payloadCode(payload) {
471
+ if (typeof payload === "object" && payload !== null) {
472
+ const code = payload.code;
473
+ if (typeof code === "string") return code;
474
+ return "internal";
475
+ }
476
+ return "internal";
477
+ }
478
+ /**
479
+ * Tool error payload → message. The wire parser enforces string fields, so
480
+ * the fallback branches are parser-gated; exported so the fallback contract
481
+ * is unit-testable directly.
482
+ * @param payload - extension-reported error payload.
483
+ * @returns the human-readable message.
484
+ */
485
+ function payloadMessage(payload) {
486
+ if (typeof payload === "object" && payload !== null) {
487
+ const message = payload.message;
488
+ if (typeof message === "string" && message.length > 0) return message;
489
+ return "browser action failed";
490
+ }
491
+ return "browser action failed";
492
+ }
493
+ //#endregion
494
+ //#region lib/types/tools.js
495
+ /**
496
+ * Model-facing browser tools. Every tool executes by dispatching a `tool.call`
497
+ * over the bridge to the connected extension, which performs the action in the
498
+ * user's active tab and returns a pure-text result.
499
+ *
500
+ * The whole surface is text-only by design (DeepSeek models have no vision):
501
+ * `browser_snapshot` renders the page as structured text with a numbered
502
+ * interactive inventory, and every other tool addresses elements by that
503
+ * inventory's stable index. Results are single `{ text }` objects rendered as
504
+ * one text ContentBlock.
505
+ *
506
+ * @module
507
+ */
508
+ /** 截图临时目录名(位于 session workspace 下)。 */
509
+ const SCREENSHOT_DIR_NAME = ".dsh-browser-tmp";
510
+ /** 截图目录最多保留的张数,超出自动删最旧(不留垃圾)。 */
511
+ const MAX_SCREENSHOTS = 20;
512
+ /** 截图目录:保存在 session workspace 下(视觉工具能读),失败回退 dshHomePath。 */
513
+ function screenshotDir(workspacePath) {
514
+ return join(workspacePath, SCREENSHOT_DIR_NAME);
515
+ }
516
+ /** 解析 session workspace:优先 exec.agent.session.header.cwd,回退 process.cwd / dshHomePath。 */
517
+ function resolveWorkspace(exec) {
518
+ const cwd = exec.agent?.session?.header?.cwd;
519
+ if (cwd !== void 0 && cwd !== "") return cwd;
520
+ try {
521
+ return process.cwd();
522
+ } catch {
523
+ return dshHomePath("browser-screenshots");
524
+ }
525
+ }
526
+ /** 保存一张截图(data URL → PNG 文件),返回绝对路径;超上限删最旧。 */
527
+ async function saveScreenshot(dataUrl, workspacePath) {
528
+ const match = /^data:image\/(?:png|jpeg);base64,(.+)$/.exec(dataUrl);
529
+ if (match === null) throw new Error("扩展返回的不是图片 data URL");
530
+ const encoded = match[1];
531
+ if (encoded === void 0) throw new Error("data URL 缺少 base64 内容");
532
+ const dir = screenshotDir(workspacePath);
533
+ await mkdir(dir, { recursive: true });
534
+ const file = join(dir, `screenshot-${Date.now()}.png`);
535
+ await writeFile(file, Buffer.from(encoded, "base64"));
536
+ await pruneScreenshots(dir);
537
+ return file;
538
+ }
539
+ /** 删除截图目录里最旧的截图,直到数量 <= MAX_SCREENSHOTS。 */
540
+ async function pruneScreenshots(dir) {
541
+ let files;
542
+ try {
543
+ files = (await readdir(dir)).filter((f) => /^screenshot-\d+\.png$/.test(f)).sort();
544
+ } catch {
545
+ return;
546
+ }
547
+ while (files.length > MAX_SCREENSHOTS) {
548
+ const oldest = files.shift();
549
+ if (oldest !== void 0) await unlink(join(dir, oldest)).catch(() => {});
550
+ }
551
+ }
552
+ /** 清理全部截图,返回删除数量。 */
553
+ async function clearScreenshots(workspacePath) {
554
+ const dir = screenshotDir(workspacePath);
555
+ let count = 0;
556
+ try {
557
+ const files = (await readdir(dir)).filter((f) => /\.png$/.test(f));
558
+ for (const f of files) {
559
+ await unlink(join(dir, f)).catch(() => {});
560
+ count += 1;
561
+ }
562
+ } catch {}
563
+ return count;
564
+ }
565
+ /** Output contract shared by every browser tool. */
566
+ const TEXT_OUTPUT = {
567
+ schema: {
568
+ type: "object",
569
+ additionalProperties: false,
570
+ properties: { text: { type: "string" } },
571
+ required: ["text"]
572
+ },
573
+ render: (_args, value) => {
574
+ return [{
575
+ type: "text",
576
+ text: value.text
577
+ }];
578
+ }
579
+ };
580
+ /** 显式 JSON Schema object 顶层:空 parameters 对象会被 DeepSeek 适配器序列化成
581
+ * `{ type: null }` 并遭 API 拒绝(400 INVALID_REQUEST),所以每个工具的参数
582
+ * schema 都必须显式声明 `type: 'object'`。 */
583
+ const OBJECT_SCHEMA = {
584
+ type: "object",
585
+ additionalProperties: false
586
+ };
587
+ /**
588
+ * Register the browser tools on `ctx.tools`. Disposers are returned for the
589
+ * caller's effect to own; each tool's cooperative timeout budget is declared
590
+ * so `@deepseek-ai/dsh-timeout-policy` can enforce it, and every execute
591
+ * forwards `exec.signal` into the bridge call (abort settles it).
592
+ *
593
+ * @param ctx - Cordis context with the tools service.
594
+ * @param bridge - the authenticated bridge server.
595
+ * @param options - resolved tool budgets.
596
+ * @returns disposers keyed by tool name.
597
+ */
598
+ function registerBrowserTools(ctx, bridge, options) {
599
+ const disposers = /* @__PURE__ */ new Map();
600
+ const call = async (exec, name, args) => {
601
+ const sessionId = exec.agent?.id;
602
+ return normalizeTextResult(await bridge.requestTool(name, args, exec.signal, options.toolTimeoutMs, sessionId), name);
603
+ };
604
+ for (const tool of defineTools(call, options)) disposers.set(tool.name, ctx.tools.register(tool));
605
+ const screenshot = {
606
+ name: "browser_screenshot",
607
+ description: "对当前浏览器页面截图,保存为 PNG 文件并返回绝对路径。仅在页面内容是图片/公式/验证码等无法用文本表达时才调用(视觉兜底)。截图保存在 session workspace 的 .dsh-browser-tmp/ 目录,最多保留 20 张(超出自动删最旧);看完后可用 browser_clear_screenshots 清理。",
608
+ parameters: {
609
+ ...OBJECT_SCHEMA,
610
+ fullPage: {
611
+ type: "boolean",
612
+ description: "整页滚动截图(暂未实现,预留)。"
613
+ },
614
+ region: {
615
+ type: "string",
616
+ description: "区域截图 CSS 选择器(暂未实现,预留)。"
617
+ }
618
+ },
619
+ timeoutMs: options.toolTimeoutMs,
620
+ output: TEXT_OUTPUT,
621
+ execute: async (args, exec) => {
622
+ const sessionId = exec.agent?.id;
623
+ const workspace = resolveWorkspace(exec);
624
+ const dataUrl = await bridge.requestTool("browser_screenshot", args, exec.signal, options.toolTimeoutMs, sessionId);
625
+ if (typeof dataUrl !== "string") return { text: "browser_screenshot 返回了非字符串结果" };
626
+ try {
627
+ return { text: `截图已保存: ${await saveScreenshot(dataUrl, workspace)}` };
628
+ } catch (error) {
629
+ return { text: `截图保存失败: ${error instanceof Error ? error.message : String(error)}` };
630
+ }
631
+ }
632
+ };
633
+ disposers.set(screenshot.name, ctx.tools.register(screenshot));
634
+ const clearScreenshotsTool = {
635
+ name: "browser_clear_screenshots",
636
+ description: "删除 browser_screenshot 产生的全部临时截图文件,避免残留垃圾。看完截图后可调用。",
637
+ parameters: {
638
+ ...OBJECT_SCHEMA,
639
+ properties: {}
640
+ },
641
+ timeoutMs: options.toolTimeoutMs,
642
+ output: TEXT_OUTPUT,
643
+ execute: async (_args, exec) => {
644
+ return { text: `已清理 ${await clearScreenshots(resolveWorkspace(exec))} 张截图` };
645
+ }
646
+ };
647
+ disposers.set(clearScreenshotsTool.name, ctx.tools.register(clearScreenshotsTool));
648
+ return disposers;
649
+ }
650
+ /** Normalize the extension's result payload to the canonical `{ text }` shape. */
651
+ function normalizeTextResult(result, name) {
652
+ if (typeof result === "object" && result !== null && typeof result.text === "string") return { text: result.text };
653
+ return { text: `${name} returned no text: ${JSON.stringify(result)}` };
654
+ }
655
+ /** The v1 tool set, model-perspective contracts only (no transport vocabulary). */
656
+ function defineTools(call, options) {
657
+ const snapshot = () => ({
658
+ name: "browser_snapshot",
659
+ description: "读取当前浏览器页面的结构化文本快照(无截图):标题、URL、正文摘要、带编号的可交互元素清单、表单字段。编号是后续 browser_click/browser_type 等操作的定位依据。页面未变化时设置 delta=true 只返回变化部分,节省上下文。",
660
+ parameters: {
661
+ ...OBJECT_SCHEMA,
662
+ delta: {
663
+ type: "boolean",
664
+ description: "true 时只返回相对上次快照的变化(编号、URL、标题)。默认 false 返回完整快照。"
665
+ },
666
+ region: {
667
+ type: "string",
668
+ description: "可选:只读取页面某个区域(CSS 选择器或 \"main\"),用于懒加载内容。"
669
+ }
670
+ },
671
+ timeoutMs: options.toolTimeoutMs,
672
+ output: TEXT_OUTPUT,
673
+ execute: (args, exec) => {
674
+ const a = args;
675
+ return call(exec, "browser_snapshot", {
676
+ ...a.delta !== void 0 ? { delta: a.delta } : {},
677
+ ...a.region !== void 0 ? { region: a.region } : {}
678
+ });
679
+ }
680
+ });
681
+ const click = () => ({
682
+ name: "browser_click",
683
+ description: "点击页面元素。用编号 index(来自 browser_snapshot)或 CSS 选择器 selector(配 index 指定第几个匹配)定位。",
684
+ parameters: {
685
+ ...OBJECT_SCHEMA,
686
+ index: {
687
+ type: "number",
688
+ description: "browser_snapshot 清单中的元素编号(与 selector 二选一)。"
689
+ },
690
+ selector: {
691
+ type: "string",
692
+ description: "CSS 选择器(与 index 二选一)。"
693
+ }
694
+ },
695
+ timeoutMs: options.toolTimeoutMs,
696
+ output: TEXT_OUTPUT,
697
+ execute: (args, exec) => call(exec, "browser_click", args)
698
+ });
699
+ const type = () => ({
700
+ name: "browser_type",
701
+ description: "向当前页面编号为 index 的输入框输入文本。默认追加到现有值之后;replace=true 时先清空再输入。敏感字段(密码/卡号)的值不会回传,输入后立即清空本地记录。",
702
+ parameters: {
703
+ ...OBJECT_SCHEMA,
704
+ index: {
705
+ type: "number",
706
+ required: true,
707
+ description: "表单字段编号(来自 browser_snapshot 的 forms 清单)。"
708
+ },
709
+ text: {
710
+ type: "string",
711
+ required: true,
712
+ description: "要输入的文本。"
713
+ },
714
+ replace: {
715
+ type: "boolean",
716
+ description: "true 时清空现有值后输入。默认追加。"
717
+ }
718
+ },
719
+ timeoutMs: options.toolTimeoutMs,
720
+ output: TEXT_OUTPUT,
721
+ execute: (args, exec) => {
722
+ const a = args;
723
+ return call(exec, "browser_type", {
724
+ index: a.index,
725
+ text: a.text,
726
+ ...a.replace !== void 0 ? { replace: a.replace } : {}
727
+ });
728
+ }
729
+ });
730
+ const press = () => ({
731
+ name: "browser_press",
732
+ description: "向当前页面发送一个按键。常用值:Enter、Tab、Escape、ArrowUp、ArrowDown、ArrowLeft、ArrowRight、Backspace、Delete。",
733
+ parameters: {
734
+ ...OBJECT_SCHEMA,
735
+ key: {
736
+ type: "string",
737
+ required: true,
738
+ description: "按键名(KeyboardEvent.key 语义)。"
739
+ }
740
+ },
741
+ timeoutMs: options.toolTimeoutMs,
742
+ output: TEXT_OUTPUT,
743
+ execute: (args, exec) => call(exec, "browser_press", args)
744
+ });
745
+ const scroll = () => ({
746
+ name: "browser_scroll",
747
+ description: "滚动当前页面。direction 为 up/down/top/bottom;amount 为像素数(默认一屏)。",
748
+ parameters: {
749
+ ...OBJECT_SCHEMA,
750
+ direction: {
751
+ type: "string",
752
+ required: true,
753
+ enum: [
754
+ "up",
755
+ "down",
756
+ "top",
757
+ "bottom"
758
+ ],
759
+ description: "滚动方向。"
760
+ },
761
+ amount: {
762
+ type: "number",
763
+ description: "滚动像素数;top/bottom 时忽略。"
764
+ }
765
+ },
766
+ timeoutMs: options.toolTimeoutMs,
767
+ output: TEXT_OUTPUT,
768
+ execute: (args, exec) => {
769
+ const a = args;
770
+ return call(exec, "browser_scroll", {
771
+ direction: a.direction,
772
+ ...a.amount !== void 0 ? { amount: a.amount } : {}
773
+ });
774
+ }
775
+ });
776
+ const navigate = () => ({
777
+ name: "browser_navigate",
778
+ description: "在当前标签页导航到指定 URL。保留当前登录状态(cookie/会话)。",
779
+ parameters: {
780
+ ...OBJECT_SCHEMA,
781
+ url: {
782
+ type: "string",
783
+ required: true,
784
+ description: "完整 URL(http/https)。"
785
+ }
786
+ },
787
+ timeoutMs: options.toolTimeoutMs,
788
+ output: TEXT_OUTPUT,
789
+ execute: (args, exec) => call(exec, "browser_navigate", args)
790
+ });
791
+ const simple = (name, description) => ({
792
+ name,
793
+ description,
794
+ parameters: {
795
+ ...OBJECT_SCHEMA,
796
+ properties: {}
797
+ },
798
+ timeoutMs: options.toolTimeoutMs,
799
+ output: TEXT_OUTPUT,
800
+ execute: (_args, exec) => call(exec, name, {})
801
+ });
802
+ const getText = () => ({
803
+ name: "browser_get_text",
804
+ description: "读取当前页面指定区域的文本(用于懒加载内容或局部更新)。不带 selector 时返回整个页面的纯文本。",
805
+ parameters: {
806
+ ...OBJECT_SCHEMA,
807
+ selector: {
808
+ type: "string",
809
+ description: "CSS 选择器;缺省为整个页面。"
810
+ }
811
+ },
812
+ timeoutMs: options.toolTimeoutMs,
813
+ output: TEXT_OUTPUT,
814
+ execute: (args, exec) => {
815
+ const a = args;
816
+ return call(exec, "browser_get_text", { ...a.selector !== void 0 ? { selector: a.selector } : {} });
817
+ }
818
+ });
819
+ const wait = () => ({
820
+ name: "browser_wait",
821
+ description: "等待页面稳定(加载完成且无 DOM 变化)。在点击或导航后需要等结果渲染时使用。",
822
+ parameters: {
823
+ ...OBJECT_SCHEMA,
824
+ ms: {
825
+ type: "number",
826
+ description: "额外等待毫秒数;缺省只做稳定性检测。"
827
+ }
828
+ },
829
+ timeoutMs: options.toolTimeoutMs,
830
+ output: TEXT_OUTPUT,
831
+ execute: (args, exec) => {
832
+ const a = args;
833
+ return call(exec, "browser_wait", { ...a.ms !== void 0 ? { ms: a.ms } : {} });
834
+ }
835
+ });
836
+ const evaluate = () => ({
837
+ name: "browser_evaluate",
838
+ description: "在页面上下文执行受限的 DOM 操作(Firefox 禁止任意 JS,故用预编译操作)。action 支持:count(计数匹配元素)、getText(读文本)、click(点击第 index 个匹配)、setValue(设置值)、querySelectorAll(列出匹配元素)。用 CSS 选择器 selector 定位,index 指定第几个匹配(默认 0)。用于 snapshot/click 覆盖不到的 DOM 操作。",
839
+ parameters: {
840
+ ...OBJECT_SCHEMA,
841
+ action: {
842
+ type: "string",
843
+ required: true,
844
+ enum: [
845
+ "count",
846
+ "getText",
847
+ "click",
848
+ "setValue",
849
+ "querySelectorAll"
850
+ ],
851
+ description: "操作类型。"
852
+ },
853
+ selector: {
854
+ type: "string",
855
+ required: true,
856
+ description: "CSS 选择器。"
857
+ },
858
+ index: {
859
+ type: "number",
860
+ description: "匹配元素的序号(默认 0)。"
861
+ },
862
+ value: {
863
+ type: "string",
864
+ description: "setValue 时设置的值。"
865
+ }
866
+ },
867
+ timeoutMs: options.toolTimeoutMs,
868
+ output: TEXT_OUTPUT,
869
+ execute: (args, exec) => call(exec, "browser_evaluate", args)
870
+ });
871
+ return [
872
+ snapshot(),
873
+ click(),
874
+ type(),
875
+ press(),
876
+ scroll(),
877
+ navigate(),
878
+ simple("browser_back", "返回上一页。"),
879
+ simple("browser_forward", "前进到下一页。"),
880
+ simple("browser_reload", "重新加载当前页面。"),
881
+ getText(),
882
+ wait(),
883
+ evaluate(),
884
+ simple("browser_list_tabs", "列出当前会话标签页组中的所有标签页(id、标题、URL,当前工作的用 * 标记)。")
885
+ ];
886
+ }
887
+ //#endregion
888
+ //#region lib/types/session-deferral.js
889
+ /**
890
+ * Defer real session creation until the first prompt.
891
+ *
892
+ * The panel calls `session.create` as soon as it connects, but a session that
893
+ * is opened and never used should leave zero trace in the store/GUI. This
894
+ * wrapper answers `session.create` with a provisional id (minted locally,
895
+ * nothing persisted), serves `session.history` for provisional ids as empty,
896
+ * and materializes the real session — same id, original create payload — on
897
+ * the first `session.prompt` for that id. Abandoned provisional ids are
898
+ * pruned after {@link PROVISIONAL_TTL_MS}.
899
+ *
900
+ * @module @deepseek-ai/dsh-bridge-browser/src/session-deferral
901
+ */
902
+ /** Provisional entries older than this are dropped on the next create. */
903
+ const PROVISIONAL_TTL_MS = 30 * 6e4;
904
+ /**
905
+ * Wrap the gateway sessions API so `session.create` returns a provisional id
906
+ * without creating anything; the real session materializes on the first
907
+ * `session.prompt` for that id.
908
+ *
909
+ * @param api - Gateway API implementation.
910
+ * @param enabled - Whether deferral is active; false returns the API untouched.
911
+ * @returns the original API when disabled, otherwise the wrapped API.
912
+ */
913
+ function withSessionDeferral(api, enabled) {
914
+ if (!enabled) return api;
915
+ const provisional = /* @__PURE__ */ new Map();
916
+ const materializing = /* @__PURE__ */ new Map();
917
+ const prune = () => {
918
+ const cutoff = Date.now() - PROVISIONAL_TTL_MS;
919
+ for (const [id, entry] of provisional) if (entry.createdAt < cutoff) provisional.delete(id);
920
+ };
921
+ const mintedId = (payload) => payload.sessionId ?? `session-${randomUUID()}`;
922
+ return {
923
+ ...api,
924
+ sessions: {
925
+ ...api.sessions,
926
+ async create(request) {
927
+ prune();
928
+ const sessionId = mintedId(request.payload);
929
+ provisional.set(sessionId, {
930
+ payload: { ...request.payload },
931
+ createdAt: Date.now()
932
+ });
933
+ return {
934
+ rpcId: request.rpcId,
935
+ result: {
936
+ ok: true,
937
+ value: { sessionId }
938
+ }
939
+ };
940
+ },
941
+ async history(request) {
942
+ if (!provisional.has(request.payload.sessionId)) return api.sessions.history(request);
943
+ return {
944
+ rpcId: request.rpcId,
945
+ result: {
946
+ ok: true,
947
+ value: {
948
+ events: [],
949
+ hasMore: false
950
+ }
951
+ }
952
+ };
953
+ },
954
+ async prompt(request) {
955
+ const entry = provisional.get(request.payload.sessionId);
956
+ if (entry === void 0) return api.sessions.prompt(request);
957
+ const existing = materializing.get(request.payload.sessionId);
958
+ const pending = existing ?? api.sessions.create({
959
+ rpcId: RpcId(randomUUID()),
960
+ payload: {
961
+ ...entry.payload,
962
+ sessionId: request.payload.sessionId
963
+ }
964
+ });
965
+ if (existing === void 0) {
966
+ materializing.set(request.payload.sessionId, pending);
967
+ pending.then(() => {
968
+ materializing.delete(request.payload.sessionId);
969
+ }, () => {
970
+ materializing.delete(request.payload.sessionId);
971
+ });
972
+ }
973
+ const created = await pending;
974
+ if (!created.result.ok) return created;
975
+ provisional.delete(request.payload.sessionId);
976
+ return api.sessions.prompt(request);
977
+ }
978
+ }
979
+ };
980
+ }
981
+ //#endregion
982
+ //#region lib/types/session-workspace.js
983
+ /**
984
+ * Best-effort workspace grouping for sessions created through the browser
985
+ * bridge. The wrapper changes only implicit `session.create` requests;
986
+ * explicit workspace choices and every other gateway method pass through.
987
+ * @module @deepseek-ai/dsh-bridge-browser/src/session-workspace
988
+ */
989
+ /**
990
+ * Add a dedicated Workspace to implicit session creation without making
991
+ * grouping a session-creation dependency. The first implicit create mkdirs
992
+ * and registers the configured path; that result, including failure, is
993
+ * cached for the wrapper lifetime.
994
+ *
995
+ * @param api - Injected gateway API implementation.
996
+ * @param workspacePath - Dedicated directory, or an empty string to opt out.
997
+ * @param warn - Logger called once when grouping cannot be established.
998
+ * @returns the original API for opt-out, otherwise an API with wrapped session creation.
999
+ */
1000
+ function withSessionWorkspace(api, workspacePath, warn) {
1001
+ if (workspacePath === "") return api;
1002
+ let workspacePromise;
1003
+ const ensureWorkspace = () => {
1004
+ if (workspacePromise !== void 0) return workspacePromise;
1005
+ workspacePromise = (async () => {
1006
+ try {
1007
+ await mkdir(workspacePath, { recursive: true });
1008
+ const workspaceApi = api.workspace;
1009
+ if (workspaceApi === void 0) {
1010
+ warn(`browser bridge: workspace API is unavailable; sessions will remain ungrouped`);
1011
+ return;
1012
+ }
1013
+ const response = await workspaceApi.create({
1014
+ rpcId: RpcId(randomUUID()),
1015
+ payload: { path: workspacePath }
1016
+ });
1017
+ if (!response.result.ok) {
1018
+ warn(`browser bridge: workspace.create failed for "${workspacePath}" (${response.result.error.code}: ${response.result.error.message}); sessions will remain ungrouped`);
1019
+ return;
1020
+ }
1021
+ return response.result.value.workspace.workspaceId;
1022
+ } catch (error) {
1023
+ warn(`browser bridge: could not prepare session workspace "${workspacePath}": ${String(error)}; sessions will remain ungrouped`);
1024
+ return;
1025
+ }
1026
+ })();
1027
+ return workspacePromise;
1028
+ };
1029
+ return {
1030
+ ...api,
1031
+ sessions: {
1032
+ ...api.sessions,
1033
+ async create(request) {
1034
+ if (request.payload.workspaceId !== void 0) return api.sessions.create(request);
1035
+ const workspaceId = await ensureWorkspace();
1036
+ if (workspaceId === void 0) return api.sessions.create(request);
1037
+ const payload = {
1038
+ ...request.payload,
1039
+ workspaceId
1040
+ };
1041
+ delete payload.cwd;
1042
+ return api.sessions.create({
1043
+ ...request,
1044
+ payload
1045
+ });
1046
+ }
1047
+ }
1048
+ };
1049
+ }
1050
+ //#endregion
1051
+ //#region lib/types/index.js
1052
+ /**
1053
+ * `@deepseek-ai/dsh-bridge-browser`: token-authenticated WebSocket bridge for
1054
+ * the browser extension plus the text-only `browser_*` tool set.
1055
+ *
1056
+ * The bridge mounts its own upgrade route (`/ext/bridge`) on the host
1057
+ * webserver, OUTSIDE the /api trust fence — so it brings its own bearer-token
1058
+ * authentication (first frame `hello` within HELLO_TIMEOUT_MS). Gateway RPCs
1059
+ * from the extension are dispatched through the same fetch-shaped handler the
1060
+ * /api carrier uses, and session events are pumped per connection. Tools
1061
+ * execute by dispatching `tool.call` frames to the connected extension, which
1062
+ * performs the action in the user's active tab.
1063
+ *
1064
+ * Opt-in by design: nothing is registered unless this plugin appears in the
1065
+ * composition. No dsh core code is touched.
1066
+ *
1067
+ * @module @deepseek-ai/dsh-bridge-browser
1068
+ */
1069
+ /** Cordis plugin name used by loader diagnostics. */
1070
+ const name = "bridge-browser";
1071
+ /** Services required by this plugin. */
1072
+ const inject = [
1073
+ "webServer",
1074
+ "apiProxy",
1075
+ "tools"
1076
+ ];
1077
+ /** Default per-tool-call budget (ms). */
1078
+ const DEFAULT_TOOL_TIMEOUT_MS = 6e4;
1079
+ /** Default rendered-snapshot character budget (protects model context). */
1080
+ const DEFAULT_SNAPSHOT_MAX_CHARS = 12e3;
1081
+ /** Default cap on interactive inventory items per snapshot. */
1082
+ const DEFAULT_MAX_INTERACTIVE_ITEMS = 120;
1083
+ /** Default directory backing the browser extension's session group. */
1084
+ const DEFAULT_SESSION_WORKSPACE_PATH = dshHomePath("browser-sessions");
1085
+ /** Default: sessions materialize only on the first message (open-and-close leaves no trace). */
1086
+ const DEFAULT_DEFER_SESSION_CREATE = true;
1087
+ const Config = z.object({
1088
+ token: z.string(),
1089
+ toolTimeoutMs: z.number().step(1).min(1).default(DEFAULT_TOOL_TIMEOUT_MS),
1090
+ snapshotMaxChars: z.number().step(1).min(1).default(DEFAULT_SNAPSHOT_MAX_CHARS),
1091
+ maxInteractiveItems: z.number().step(1).min(1).default(DEFAULT_MAX_INTERACTIVE_ITEMS),
1092
+ sessionWorkspacePath: z.string().default(DEFAULT_SESSION_WORKSPACE_PATH),
1093
+ deferSessionCreate: z.boolean().default(DEFAULT_DEFER_SESSION_CREATE)
1094
+ });
1095
+ /** Configured budgets must be positive integers. Exported for validation tests. */
1096
+ function assertPositiveInteger(name, value) {
1097
+ if (!Number.isInteger(value) || value < 1) throw new Error(`bridge-browser: ${name} must be a positive integer`);
1098
+ }
1099
+ /**
1100
+ * Apply defaults and direct-call validation at the plugin boundary.
1101
+ * @param config - Loader-resolved or directly supplied plugin configuration.
1102
+ * @returns a complete configuration ready for runtime use.
1103
+ */
1104
+ function resolveConfig(config) {
1105
+ const resolved = {
1106
+ ...config.token === void 0 ? {} : { token: config.token },
1107
+ toolTimeoutMs: config.toolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS,
1108
+ snapshotMaxChars: config.snapshotMaxChars ?? DEFAULT_SNAPSHOT_MAX_CHARS,
1109
+ maxInteractiveItems: config.maxInteractiveItems ?? DEFAULT_MAX_INTERACTIVE_ITEMS,
1110
+ sessionWorkspacePath: config.sessionWorkspacePath ?? DEFAULT_SESSION_WORKSPACE_PATH,
1111
+ deferSessionCreate: config.deferSessionCreate ?? DEFAULT_DEFER_SESSION_CREATE
1112
+ };
1113
+ assertPositiveInteger("toolTimeoutMs", resolved.toolTimeoutMs);
1114
+ assertPositiveInteger("snapshotMaxChars", resolved.snapshotMaxChars);
1115
+ assertPositiveInteger("maxInteractiveItems", resolved.maxInteractiveItems);
1116
+ return resolved;
1117
+ }
1118
+ /**
1119
+ * Mount the bridge: resolve the token, register the upgrade route, the tool
1120
+ * set, and an optional system-prompt section, all effect-scoped for HMR.
1121
+ *
1122
+ * @param ctx - Cordis context.
1123
+ * @param config - plugin config (schema defaults applied).
1124
+ */
1125
+ async function apply(ctx, config) {
1126
+ const resolved = resolveConfig(config);
1127
+ const tokenRes = await resolveToken(resolved.token);
1128
+ const api = withSessionDeferral(withSessionWorkspace(ctx.apiProxy, resolved.sessionWorkspacePath, (message) => {
1129
+ ctx.logger.warn(message);
1130
+ }), resolved.deferSessionCreate);
1131
+ const server = new BridgeServer({
1132
+ token: tokenRes.token,
1133
+ apiHandler: toFetchHandler(api),
1134
+ openEvents: (signal) => api.events.mux({
1135
+ rpcId: RpcId(randomUUID()),
1136
+ payload: {}
1137
+ }, signal),
1138
+ toolTimeoutMs: resolved.toolTimeoutMs,
1139
+ caps: {
1140
+ textOnly: true,
1141
+ snapshotMaxChars: resolved.snapshotMaxChars,
1142
+ maxInteractiveItems: resolved.maxInteractiveItems
1143
+ }
1144
+ });
1145
+ const route = {
1146
+ path: BRIDGE_PATH,
1147
+ handler: (req, socket, head) => {
1148
+ server.handleUpgrade(req, socket, head);
1149
+ }
1150
+ };
1151
+ ctx.effect(() => ctx.webServer.registerUpgrade(route), "bridge-browser: /ext/bridge upgrade route");
1152
+ ctx.effect(() => () => server.close(), "bridge-browser: bridge server");
1153
+ const configRoute = {
1154
+ kind: "exact",
1155
+ path: BRIDGE_CONFIG_PATH,
1156
+ handler: (_req, res) => {
1157
+ res.writeHead(200, { "content-type": "application/json" });
1158
+ res.end(JSON.stringify({ wsUrl: `ws://127.0.0.1:${ctx.webServer.port}${BRIDGE_PATH}` }));
1159
+ }
1160
+ };
1161
+ ctx.effect(() => ctx.webServer.register(configRoute), "bridge-browser: /ext/bridge-config route");
1162
+ ctx.effect(() => {
1163
+ const disposers = registerBrowserTools(ctx, server, {
1164
+ toolTimeoutMs: resolved.toolTimeoutMs,
1165
+ snapshotMaxChars: resolved.snapshotMaxChars,
1166
+ maxInteractiveItems: resolved.maxInteractiveItems
1167
+ });
1168
+ return () => {
1169
+ for (const dispose of disposers.values()) dispose();
1170
+ };
1171
+ }, "bridge-browser: browser tools");
1172
+ const systemPrompt = ctx.get("systemPrompt");
1173
+ if (systemPrompt !== void 0) ctx.effect(() => systemPrompt.section({
1174
+ name: "tool:bridge-browser",
1175
+ order: 107,
1176
+ 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."
1177
+ }), "bridge-browser: system prompt section");
1178
+ 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}`);
1179
+ ctx.logger.info(`browser bridge: listening on ${BRIDGE_PATH}`);
1180
+ }
1181
+ //#endregion
1182
+ export { Config, apply, assertPositiveInteger, inject, name, resolveConfig };