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.
@@ -0,0 +1,26 @@
1
+ //#region lib/types/invariant.js
2
+ /**
3
+ * Package-owned invariant companion for `@deepseek-ai/dsh-bridge-browser`.
4
+ * @module @deepseek-ai/dsh-bridge-browser/invariant
5
+ */
6
+ const PACKAGE_NAME = "@deepseek-ai/dsh-bridge-browser";
7
+ /** Cordis companion plugin name. */
8
+ const name = "bridge-browser-invariant";
9
+ /** Service required before the companion can reserve package ownership. */
10
+ const inject = ["invariants"];
11
+ /**
12
+ * No runtime invariant: the bridge's connection registry and pending tool map
13
+ * are instance-private (no published event stream to assert against), and the
14
+ * wire contract is pinned by protocol.ts and covered by its unit tests. The
15
+ * tools are plain ctx.tools registrations observed by dsh-tools' own
16
+ * invariant.
17
+ */
18
+ const install = () => {};
19
+ /**
20
+ * Register this package's invariant companion.
21
+ * @param ctx - Cordis context carrying the invariant service.
22
+ * @returns the installed registration's disposer after setup succeeds.
23
+ */
24
+ const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
25
+ //#endregion
26
+ export { apply, inject, name };
@@ -0,0 +1,134 @@
1
+ //#region lib/types/protocol.js
2
+ /**
3
+ * Wire contract between the dsh bridge plugin and the browser extension.
4
+ *
5
+ * Zero-dependency module (pure types, constants, and a parser): both the
6
+ * plugin (node) and the Chrome extension (browser bundle) import this file, so
7
+ * the frame shapes can never drift between the two halves.
8
+ *
9
+ * Frames are one JSON object per WebSocket message, discriminated by `t`.
10
+ * Correlation ids (`id`) are minted by the requestor and echoed by the
11
+ * responder; they are opaque strings, never parsed.
12
+ *
13
+ * @module
14
+ */
15
+ /** WebSocket pathname the bridge plugin registers on the host webserver. */
16
+ const BRIDGE_PATH = "/ext/bridge";
17
+ /** Zero-config discovery endpoint: returns `{ wsUrl }` for the extension. */
18
+ const BRIDGE_CONFIG_PATH = "/ext/bridge-config";
19
+ /** Seconds a fresh socket may take to present `hello` before it is closed. */
20
+ const HELLO_TIMEOUT_MS = 5e3;
21
+ /** Server-side ping cadence; the client answers `pong` to prove liveness. */
22
+ const PING_INTERVAL_MS = 3e4;
23
+ /** Default bytes of the generated bearer token (256-bit). */
24
+ const DEFAULT_TOKEN_BYTES = 32;
25
+ /**
26
+ * Type guard: is this frame one the SERVER may send? Client-only shapes
27
+ * (hello/tool.result/pong) narrow out, so server-side consumers never
28
+ * dispatch on their own request vocabulary.
29
+ * @param frame - parsed frame.
30
+ * @returns true for server-sendable frames.
31
+ */
32
+ function isServerFrame(frame) {
33
+ return frame.t === "hello.ok" || frame.t === "rpc.result" || frame.t === "event" || frame.t === "tool.call" || frame.t === "ping" || frame.t === "error";
34
+ }
35
+ /**
36
+ * Type guard: is this frame one the CLIENT may send? Server-only shapes
37
+ * narrow out, so client-side consumers never dispatch on server vocabulary.
38
+ * @param frame - parsed frame.
39
+ * @returns true for client-sendable frames.
40
+ */
41
+ function isClientFrame(frame) {
42
+ return frame.t === "hello" || frame.t === "rpc" || frame.t === "tool.result" || frame.t === "pong";
43
+ }
44
+ /**
45
+ * Parse one WebSocket message into a frame.
46
+ * @param text - raw message text.
47
+ * @returns the frame, or `undefined` when the message is not a valid frame.
48
+ */
49
+ function parseBridgeFrame(text) {
50
+ let value;
51
+ try {
52
+ value = JSON.parse(text);
53
+ } catch {
54
+ return;
55
+ }
56
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
57
+ const frame = value;
58
+ if (typeof frame.t !== "string") return void 0;
59
+ switch (frame.t) {
60
+ case "hello": return typeof frame.token === "string" && isCaps(frame.caps) ? {
61
+ t: "hello",
62
+ token: frame.token,
63
+ caps: frame.caps
64
+ } : void 0;
65
+ case "rpc": return typeof frame.id === "string" && typeof frame.method === "string" ? {
66
+ t: "rpc",
67
+ id: frame.id,
68
+ method: frame.method,
69
+ payload: frame.payload
70
+ } : void 0;
71
+ case "tool.result":
72
+ if (typeof frame.id !== "string") return void 0;
73
+ if (frame.ok === true && "result" in frame) return {
74
+ t: "tool.result",
75
+ id: frame.id,
76
+ ok: true,
77
+ result: frame.result
78
+ };
79
+ return isToolError(frame.error) ? {
80
+ t: "tool.result",
81
+ id: frame.id,
82
+ ok: false,
83
+ error: frame.error
84
+ } : void 0;
85
+ case "pong": return { t: "pong" };
86
+ case "hello.ok": return isCaps(frame.caps) ? {
87
+ t: "hello.ok",
88
+ caps: frame.caps
89
+ } : void 0;
90
+ case "rpc.result":
91
+ if (typeof frame.id !== "string") return void 0;
92
+ if (frame.ok === true && "result" in frame) return {
93
+ t: "rpc.result",
94
+ id: frame.id,
95
+ ok: true,
96
+ result: frame.result
97
+ };
98
+ return typeof frame.error === "object" && frame.error !== null ? {
99
+ t: "rpc.result",
100
+ id: frame.id,
101
+ ok: false,
102
+ error: frame.error
103
+ } : void 0;
104
+ case "event": return typeof frame.frame === "object" && frame.frame !== null ? {
105
+ t: "event",
106
+ frame: frame.frame
107
+ } : void 0;
108
+ case "tool.call": return typeof frame.id === "string" && typeof frame.name === "string" && typeof frame.args === "object" && frame.args !== null && !Array.isArray(frame.args) ? {
109
+ t: "tool.call",
110
+ id: frame.id,
111
+ name: frame.name,
112
+ args: frame.args,
113
+ ...typeof frame.sessionId === "string" ? { sessionId: frame.sessionId } : {},
114
+ ...typeof frame.title === "string" ? { title: frame.title } : {}
115
+ } : void 0;
116
+ case "ping": return { t: "ping" };
117
+ case "error": return typeof frame.code === "string" && typeof frame.message === "string" ? {
118
+ t: "error",
119
+ code: frame.code,
120
+ message: frame.message
121
+ } : void 0;
122
+ default: return;
123
+ }
124
+ }
125
+ function isCaps(value) {
126
+ if (typeof value !== "object" || value === null) return false;
127
+ const caps = value;
128
+ return caps.textOnly === true && typeof caps.snapshotMaxChars === "number" && caps.snapshotMaxChars > 0 && typeof caps.maxInteractiveItems === "number" && caps.maxInteractiveItems > 0;
129
+ }
130
+ function isToolError(value) {
131
+ return typeof value === "object" && value !== null && typeof value.code === "string" && typeof value.message === "string";
132
+ }
133
+ //#endregion
134
+ export { BRIDGE_CONFIG_PATH, BRIDGE_PATH, DEFAULT_TOKEN_BYTES, HELLO_TIMEOUT_MS, PING_INTERVAL_MS, isClientFrame, isServerFrame, parseBridgeFrame };
@@ -0,0 +1,59 @@
1
+ /**
2
+ * `@deepseek-ai/dsh-bridge-browser`: token-authenticated WebSocket bridge for
3
+ * the browser extension plus the text-only `browser_*` tool set.
4
+ *
5
+ * The bridge mounts its own upgrade route (`/ext/bridge`) on the host
6
+ * webserver, OUTSIDE the /api trust fence — so it brings its own bearer-token
7
+ * authentication (first frame `hello` within HELLO_TIMEOUT_MS). Gateway RPCs
8
+ * from the extension are dispatched through the same fetch-shaped handler the
9
+ * /api carrier uses, and session events are pumped per connection. Tools
10
+ * execute by dispatching `tool.call` frames to the connected extension, which
11
+ * performs the action in the user's active tab.
12
+ *
13
+ * Opt-in by design: nothing is registered unless this plugin appears in the
14
+ * composition. No dsh core code is touched.
15
+ *
16
+ * @module @deepseek-ai/dsh-bridge-browser
17
+ */
18
+ import type { Context } from '@deepseek-ai/cordis';
19
+ import z from '@deepseek-ai/schemastery';
20
+ /** Cordis plugin name used by loader diagnostics. */
21
+ export declare const name = "bridge-browser";
22
+ /** Services required by this plugin. */
23
+ export declare const inject: string[];
24
+ /** Plugin config: deployment-varying tunables only; the wire contract stays fixed. */
25
+ export interface Config {
26
+ /** Fixed bearer token. When absent, a token is generated on first boot and persisted under the dsh home (0600). */
27
+ token?: string;
28
+ /** Per-tool-call timeout in ms. Defaults to 60000. */
29
+ toolTimeoutMs?: number;
30
+ /** Upper bound on one snapshot's rendered characters. Defaults to 12000. */
31
+ snapshotMaxChars?: number;
32
+ /** Upper bound on interactive inventory items per snapshot. Defaults to 60. */
33
+ maxInteractiveItems?: number;
34
+ /** Dedicated workspace path for extension-created sessions. Empty disables grouping. */
35
+ sessionWorkspacePath?: string;
36
+ /** Defer real session creation until the first prompt. Defaults to true. */
37
+ deferSessionCreate?: boolean;
38
+ }
39
+ export declare const Config: z<Config>;
40
+ /** The shape after schemastery applies its defaults to every field. */
41
+ type ResolvedConfig = Required<Omit<Config, 'token'>> & Pick<Config, 'token'>;
42
+ /** Configured budgets must be positive integers. Exported for validation tests. */
43
+ export declare function assertPositiveInteger(name: string, value: number): void;
44
+ /**
45
+ * Apply defaults and direct-call validation at the plugin boundary.
46
+ * @param config - Loader-resolved or directly supplied plugin configuration.
47
+ * @returns a complete configuration ready for runtime use.
48
+ */
49
+ export declare function resolveConfig(config: Config): ResolvedConfig;
50
+ /**
51
+ * Mount the bridge: resolve the token, register the upgrade route, the tool
52
+ * set, and an optional system-prompt section, all effect-scoped for HMR.
53
+ *
54
+ * @param ctx - Cordis context.
55
+ * @param config - plugin config (schema defaults applied).
56
+ */
57
+ export declare function apply(ctx: Context, config: Config): Promise<void>;
58
+ export {};
59
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Package-owned invariant companion for `@deepseek-ai/dsh-bridge-browser`.
3
+ * @module @deepseek-ai/dsh-bridge-browser/invariant
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis';
6
+ /** Cordis companion plugin name. */
7
+ export declare const name = "bridge-browser-invariant";
8
+ /** Service required before the companion can reserve package ownership. */
9
+ export declare const inject: string[];
10
+ /**
11
+ * Register this package's invariant companion.
12
+ * @param ctx - Cordis context carrying the invariant service.
13
+ * @returns the installed registration's disposer after setup succeeds.
14
+ */
15
+ export declare const apply: (ctx: Context) => Promise<() => void>;
16
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Wire contract between the dsh bridge plugin and the browser extension.
3
+ *
4
+ * Zero-dependency module (pure types, constants, and a parser): both the
5
+ * plugin (node) and the Chrome extension (browser bundle) import this file, so
6
+ * the frame shapes can never drift between the two halves.
7
+ *
8
+ * Frames are one JSON object per WebSocket message, discriminated by `t`.
9
+ * Correlation ids (`id`) are minted by the requestor and echoed by the
10
+ * responder; they are opaque strings, never parsed.
11
+ *
12
+ * @module
13
+ */
14
+ /** WebSocket pathname the bridge plugin registers on the host webserver. */
15
+ export declare const BRIDGE_PATH = "/ext/bridge";
16
+ /** Zero-config discovery endpoint: returns `{ wsUrl }` for the extension. */
17
+ export declare const BRIDGE_CONFIG_PATH = "/ext/bridge-config";
18
+ /** Seconds a fresh socket may take to present `hello` before it is closed. */
19
+ export declare const HELLO_TIMEOUT_MS = 5000;
20
+ /** Server-side ping cadence; the client answers `pong` to prove liveness. */
21
+ export declare const PING_INTERVAL_MS = 30000;
22
+ /** Default bytes of the generated bearer token (256-bit). */
23
+ export declare const DEFAULT_TOKEN_BYTES = 32;
24
+ /** Error codes a tool call may settle with. Open set: consumers must tolerate unknown codes. */
25
+ export type ToolErrorCode = 'no-active-tab' | 'content-unavailable' | 'action-failed' | 'timeout' | 'bridge-closed' | 'bad-args' | 'internal';
26
+ /** One tool-call failure: stable machine code plus human text for the model. */
27
+ export interface ToolError {
28
+ code: ToolErrorCode;
29
+ message: string;
30
+ }
31
+ /** Capabilities negotiated in `hello`/`hello.ok`. The extension performs its own actions; these bounds shape page snapshots. */
32
+ export interface BridgeCaps {
33
+ /** The extension renders page state as text only (no screenshots). */
34
+ textOnly: true;
35
+ /** Upper bound on one rendered snapshot's characters (plugin config). */
36
+ snapshotMaxChars: number;
37
+ /** Upper bound on interactive inventory items per snapshot (plugin config). */
38
+ maxInteractiveItems: number;
39
+ }
40
+ /** Frames sent by the extension to the bridge plugin. */
41
+ export type ClientFrame =
42
+ /** First frame, within HELLO_TIMEOUT_MS of socket open. */
43
+ {
44
+ t: 'hello';
45
+ token: string;
46
+ caps: BridgeCaps;
47
+ }
48
+ /** Unary gateway RPC passthrough (method names from the apiproxy RpcMethodMap). */
49
+ | {
50
+ t: 'rpc';
51
+ id: string;
52
+ method: string;
53
+ payload: unknown;
54
+ }
55
+ /** Result of a previously dispatched tool call. */
56
+ | {
57
+ t: 'tool.result';
58
+ id: string;
59
+ ok: true;
60
+ result: unknown;
61
+ } | {
62
+ t: 'tool.result';
63
+ id: string;
64
+ ok: false;
65
+ error: ToolError;
66
+ }
67
+ /** Liveness reply. */
68
+ | {
69
+ t: 'pong';
70
+ };
71
+ /** Frames sent by the bridge plugin to the extension. */
72
+ export type ServerFrame =
73
+ /** Accepted after a valid `hello`. */
74
+ {
75
+ t: 'hello.ok';
76
+ caps: BridgeCaps;
77
+ }
78
+ /** Reply to an `rpc` frame; `result` is the apiproxy ServerResponse envelope. */
79
+ | {
80
+ t: 'rpc.result';
81
+ id: string;
82
+ ok: true;
83
+ result: unknown;
84
+ } | {
85
+ t: 'rpc.result';
86
+ id: string;
87
+ ok: false;
88
+ error: {
89
+ code: string;
90
+ message: string;
91
+ };
92
+ }
93
+ /** One gateway event envelope (the same server-request shape the GUI's /api/events.mux carries). */
94
+ | {
95
+ t: 'event';
96
+ frame: {
97
+ rpcId: string;
98
+ method: string;
99
+ payload: unknown;
100
+ };
101
+ }
102
+ /** A model-requested browser action to execute in the active tab. */
103
+ | {
104
+ t: 'tool.call';
105
+ id: string;
106
+ name: string;
107
+ args: Record<string, unknown>;
108
+ sessionId?: string;
109
+ title?: string;
110
+ }
111
+ /** Liveness probe. */
112
+ | {
113
+ t: 'ping';
114
+ }
115
+ /** Fatal connection error; the client should re-authenticate. */
116
+ | {
117
+ t: 'error';
118
+ code: string;
119
+ message: string;
120
+ };
121
+ /** Any frame on the wire. */
122
+ export type BridgeFrame = ClientFrame | ServerFrame;
123
+ /**
124
+ * Type guard: is this frame one the SERVER may send? Client-only shapes
125
+ * (hello/tool.result/pong) narrow out, so server-side consumers never
126
+ * dispatch on their own request vocabulary.
127
+ * @param frame - parsed frame.
128
+ * @returns true for server-sendable frames.
129
+ */
130
+ export declare function isServerFrame(frame: BridgeFrame): frame is ServerFrame;
131
+ /**
132
+ * Type guard: is this frame one the CLIENT may send? Server-only shapes
133
+ * narrow out, so client-side consumers never dispatch on server vocabulary.
134
+ * @param frame - parsed frame.
135
+ * @returns true for client-sendable frames.
136
+ */
137
+ export declare function isClientFrame(frame: BridgeFrame): frame is ClientFrame;
138
+ /**
139
+ * Parse one WebSocket message into a frame.
140
+ * @param text - raw message text.
141
+ * @returns the frame, or `undefined` when the message is not a valid frame.
142
+ */
143
+ export declare function parseBridgeFrame(text: string): BridgeFrame | undefined;
144
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Bridge WebSocket carrier: token-authenticated connection registry, gateway
3
+ * RPC passthrough, per-connection event pump, and tool-call dispatch to the
4
+ * connected browser extension.
5
+ *
6
+ * The route this server mounts (`/ext/bridge`) lives OUTSIDE the /api trust
7
+ * fence (which only guards the client-connection routes), so the bridge brings
8
+ * its own authentication: a bearer token presented in the `hello` frame within
9
+ * HELLO_TIMEOUT_MS. Gateway RPCs are dispatched through the same fetch-shaped
10
+ * handler the /api carrier uses (`toFetchHandler`), so schema validation and
11
+ * error envelopes are identical to the GUI path. Methods the /api carrier
12
+ * pins to loopback (`PRIVILEGED_METHODS`) stay loopback-only here regardless
13
+ * of the token, defense in depth for `--host 0.0.0.0` deployments.
14
+ *
15
+ * One active connection at a time: a new authenticated socket replaces the
16
+ * previous one (the old socket is closed and its in-flight tool calls settle
17
+ * as `bridge-closed`).
18
+ *
19
+ * @module
20
+ */
21
+ import type { IncomingMessage } from 'node:http';
22
+ import type { Duplex } from 'node:stream';
23
+ import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api';
24
+ import { type BridgeCaps, type ToolErrorCode } from './protocol.ts';
25
+ /** Loopback IPv4/IPv6 literals (IPv4-mapped included). Exported for tests and reuse. */
26
+ export declare function isLoopbackAddress(address: string | undefined): boolean;
27
+ /** Error thrown by requestTool; the tool registry turns it into an isError result. */
28
+ export declare class BridgeToolError extends Error {
29
+ readonly code: ToolErrorCode;
30
+ constructor(code: ToolErrorCode, message: string);
31
+ }
32
+ /** Dependencies the bridge needs from the host. */
33
+ export interface BridgeServerDeps {
34
+ /** Bearer token the extension must present in `hello`. */
35
+ token: string;
36
+ /** Fetch-shaped gateway carrier (from `toFetchHandler(ctx.apiProxy)`). */
37
+ apiHandler: {
38
+ fetch: (request: Request) => Promise<Response>;
39
+ };
40
+ /** Per-connection event stream (usually `ctx.apiProxy.events.mux`). */
41
+ openEvents: (signal: AbortSignal) => AsyncIterable<RpcRequest<MuxFrame>>;
42
+ /** Default per-tool-call timeout in ms. */
43
+ toolTimeoutMs: number;
44
+ /** Capabilities to echo in `hello.ok` (negotiated snapshot budgets). */
45
+ caps: BridgeCaps;
46
+ /**
47
+ * Test seam: force the remote address seen by the privilege gate. The
48
+ * sandbox cannot bind arbitrary loopback literals, so the non-loopback
49
+ * branch is exercised through this override; production never sets it.
50
+ */
51
+ remoteAddressOverride?: string;
52
+ /** Seconds a fresh socket may present `hello`; defaults to HELLO_TIMEOUT_MS. */
53
+ helloTimeoutMs?: number;
54
+ /** Server ping cadence; defaults to PING_INTERVAL_MS. */
55
+ pingIntervalMs?: number;
56
+ }
57
+ /**
58
+ * Decode one ws message payload to text. Exported so all three delivery
59
+ * shapes (fragmented buffer list, Buffer, ArrayBuffer) are unit-testable
60
+ * directly — node ws only ever delivers Buffers in practice.
61
+ * @param data - ws message payload.
62
+ * @returns the decoded UTF-8 text.
63
+ */
64
+ export declare function messageToText(data: Buffer | ArrayBuffer | Buffer[]): string;
65
+ /**
66
+ * Token-authenticated bridge server. Construct once per plugin instance;
67
+ * dispose with {@link close}.
68
+ */
69
+ export declare class BridgeServer {
70
+ private readonly deps;
71
+ private readonly wss;
72
+ private current;
73
+ private readonly pendingTools;
74
+ private closed;
75
+ constructor(deps: BridgeServerDeps);
76
+ /**
77
+ * Handle one HTTP upgrade for the bridge path.
78
+ * @param req - upgrade request (carries the client's remote address).
79
+ * @param socket - raw socket transferred by the HTTP server.
80
+ * @param head - bytes already read after the upgrade headers.
81
+ */
82
+ handleUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void;
83
+ /**
84
+ * Request one browser action from the connected extension.
85
+ * @param name - tool name (also the wire action name).
86
+ * @param args - validated tool arguments.
87
+ * @param signal - caller cancellation (abort settles the call as cancelled).
88
+ * @param timeoutMs - per-call budget; defaults to the plugin config value.
89
+ * @returns the extension's action result.
90
+ * @throws BridgeToolError when no extension is connected, the call times
91
+ * out, is cancelled, or the extension reports a failure.
92
+ */
93
+ requestTool(name: string, args: Record<string, unknown>, signal: AbortSignal, timeoutMs?: number, sessionId?: string, title?: string): Promise<unknown>;
94
+ /**
95
+ * Terminate the server: close the acceptor, drop all sockets, reject all
96
+ * in-flight tool calls.
97
+ * @returns a promise resolving after the acceptor and all pumps stop.
98
+ */
99
+ close(): Promise<void>;
100
+ /** @returns whether an authenticated extension is currently connected. */
101
+ hasConnection(): boolean;
102
+ private attach;
103
+ /** Promote an authenticated socket to the single active slot. */
104
+ private promote;
105
+ private handleReadyFrame;
106
+ private handleRpc;
107
+ private settleTool;
108
+ /** Close the current connection (if any) and settle its in-flight calls. */
109
+ private replaceConnection;
110
+ }
111
+ /**
112
+ * Tool error payload → stable code. The wire parser enforces string fields,
113
+ * so the fallback branches are parser-gated; exported so the fallback
114
+ * contract is unit-testable directly.
115
+ * @param payload - extension-reported error payload.
116
+ * @returns the stable error code.
117
+ */
118
+ export declare function payloadCode(payload: unknown): ToolErrorCode;
119
+ /**
120
+ * Tool error payload → message. The wire parser enforces string fields, so
121
+ * the fallback branches are parser-gated; exported so the fallback contract
122
+ * is unit-testable directly.
123
+ * @param payload - extension-reported error payload.
124
+ * @returns the human-readable message.
125
+ */
126
+ export declare function payloadMessage(payload: unknown): string;
127
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Defer real session creation until the first prompt.
3
+ *
4
+ * The panel calls `session.create` as soon as it connects, but a session that
5
+ * is opened and never used should leave zero trace in the store/GUI. This
6
+ * wrapper answers `session.create` with a provisional id (minted locally,
7
+ * nothing persisted), serves `session.history` for provisional ids as empty,
8
+ * and materializes the real session — same id, original create payload — on
9
+ * the first `session.prompt` for that id. Abandoned provisional ids are
10
+ * pruned after {@link PROVISIONAL_TTL_MS}.
11
+ *
12
+ * @module @deepseek-ai/dsh-bridge-browser/src/session-deferral
13
+ */
14
+ import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api';
15
+ /**
16
+ * Wrap the gateway sessions API so `session.create` returns a provisional id
17
+ * without creating anything; the real session materializes on the first
18
+ * `session.prompt` for that id.
19
+ *
20
+ * @param api - Gateway API implementation.
21
+ * @param enabled - Whether deferral is active; false returns the API untouched.
22
+ * @returns the original API when disabled, otherwise the wrapped API.
23
+ */
24
+ export declare function withSessionDeferral(api: ApiProxy, enabled: boolean): ApiProxy;
25
+ //# sourceMappingURL=session-deferral.d.ts.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Best-effort workspace grouping for sessions created through the browser
3
+ * bridge. The wrapper changes only implicit `session.create` requests;
4
+ * explicit workspace choices and every other gateway method pass through.
5
+ * @module @deepseek-ai/dsh-bridge-browser/src/session-workspace
6
+ */
7
+ import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api';
8
+ type Warn = (message: string) => void;
9
+ /**
10
+ * Add a dedicated Workspace to implicit session creation without making
11
+ * grouping a session-creation dependency. The first implicit create mkdirs
12
+ * and registers the configured path; that result, including failure, is
13
+ * cached for the wrapper lifetime.
14
+ *
15
+ * @param api - Injected gateway API implementation.
16
+ * @param workspacePath - Dedicated directory, or an empty string to opt out.
17
+ * @param warn - Logger called once when grouping cannot be established.
18
+ * @returns the original API for opt-out, otherwise an API with wrapped session creation.
19
+ */
20
+ export declare function withSessionWorkspace(api: ApiProxy, workspacePath: string, warn: Warn): ApiProxy;
21
+ export {};
22
+ //# sourceMappingURL=session-workspace.d.ts.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Bridge bearer-token lifecycle: generation, constant-time verification, and
3
+ * file persistence under the dsh home directory.
4
+ *
5
+ * The token authenticates the browser extension against the bridge WebSocket.
6
+ * It is NOT the /api trust fence (that stays untouched); it is the bridge
7
+ * path's own auth because the bridge route lives outside the fence by design.
8
+ *
9
+ * @module
10
+ */
11
+ /** File name of the persisted token inside the dsh home. */
12
+ export declare const TOKEN_FILE_NAME = "ext-bridge-token";
13
+ /**
14
+ * Generate a fresh token as lowercase hex.
15
+ * @param bytes - entropy bytes; defaults to DEFAULT_TOKEN_BYTES (256-bit).
16
+ * @returns the hex token string.
17
+ */
18
+ export declare function generateToken(bytes?: number): string;
19
+ /**
20
+ * Constant-time token comparison. Length mismatch fails fast (still constant
21
+ * time on the compared prefix) — a wrong-length token can never verify.
22
+ * @param expected - the configured token.
23
+ * @param actual - the token presented by the client.
24
+ * @returns true only when both are equal-length hex and byte-equal.
25
+ */
26
+ export declare function verifyToken(expected: string, actual: string): boolean;
27
+ /**
28
+ * Path of the persisted token file under the dsh home.
29
+ * @returns absolute path like `~/.dsh/ext-bridge-token`.
30
+ */
31
+ export declare function tokenFilePath(): string;
32
+ /**
33
+ * Read the persisted token; returns undefined when absent or unreadable.
34
+ * @param file - token file path.
35
+ * @returns the stored hex token, trimmed.
36
+ */
37
+ export declare function readTokenFile(file?: string): Promise<string | undefined>;
38
+ /**
39
+ * Persist a token atomically (temp file + rename) with 0600 permissions.
40
+ * @param token - hex token to persist.
41
+ * @param file - token file path.
42
+ */
43
+ export declare function writeTokenFile(token: string, file?: string): Promise<void>;
44
+ /**
45
+ * Resolve the bridge token: an explicitly configured token wins; otherwise the
46
+ * persisted file is reused when present, and a fresh token is generated and
47
+ * persisted otherwise.
48
+ * @param configured - token from plugin config, or undefined.
49
+ * @param file - token file path (injectable for tests).
50
+ * @returns `{ token, file, generated }` where `generated` records whether a new token was minted.
51
+ */
52
+ export declare function resolveToken(configured: string | undefined, file?: string): Promise<{
53
+ token: string;
54
+ file: string;
55
+ generated: boolean;
56
+ }>;
57
+ //# sourceMappingURL=token.d.ts.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Model-facing browser tools. Every tool executes by dispatching a `tool.call`
3
+ * over the bridge to the connected extension, which performs the action in the
4
+ * user's active tab and returns a pure-text result.
5
+ *
6
+ * The whole surface is text-only by design (DeepSeek models have no vision):
7
+ * `browser_snapshot` renders the page as structured text with a numbered
8
+ * interactive inventory, and every other tool addresses elements by that
9
+ * inventory's stable index. Results are single `{ text }` objects rendered as
10
+ * one text ContentBlock.
11
+ *
12
+ * @module
13
+ */
14
+ import type { Context } from '@deepseek-ai/cordis';
15
+ import type { BridgeServer } from './server.ts';
16
+ /** Options resolved from plugin config before tool registration. */
17
+ export interface BrowserToolsOptions {
18
+ /** Per-tool-call budget in ms (also the bridge's default). */
19
+ toolTimeoutMs: number;
20
+ /** Upper bound on one snapshot's rendered characters. */
21
+ snapshotMaxChars: number;
22
+ /** Upper bound on interactive inventory items per snapshot. */
23
+ maxInteractiveItems: number;
24
+ }
25
+ /** The keys the extension accepts as wire action names (tool name == action name). */
26
+ export declare const BROWSER_TOOL_NAMES: readonly ["browser_snapshot", "browser_click", "browser_type", "browser_press", "browser_scroll", "browser_navigate", "browser_back", "browser_forward", "browser_reload", "browser_get_text", "browser_wait", "browser_evaluate", "browser_screenshot", "browser_list_tabs"];
27
+ /**
28
+ * Register the browser tools on `ctx.tools`. Disposers are returned for the
29
+ * caller's effect to own; each tool's cooperative timeout budget is declared
30
+ * so `@deepseek-ai/dsh-timeout-policy` can enforce it, and every execute
31
+ * forwards `exec.signal` into the bridge call (abort settles it).
32
+ *
33
+ * @param ctx - Cordis context with the tools service.
34
+ * @param bridge - the authenticated bridge server.
35
+ * @param options - resolved tool budgets.
36
+ * @returns disposers keyed by tool name.
37
+ */
38
+ export declare function registerBrowserTools(ctx: Context, bridge: BridgeServer, options: BrowserToolsOptions): Map<string, () => void>;
39
+ //# sourceMappingURL=tools.d.ts.map