dsh-browser-firefox 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/protocol.js CHANGED
@@ -22,12 +22,62 @@
22
22
  const BRIDGE_PATH = "/ext/bridge";
23
23
  /** Zero-config discovery endpoint: returns `{ wsUrl }` for the extension. */
24
24
  const BRIDGE_CONFIG_PATH = "/ext/bridge-config";
25
+ /**
26
+ * Fixed discovery beacons. A dsh Desktop host may bind its real webserver on
27
+ * an ephemeral port (`--port 0`); the bridge binds the first free port in this
28
+ * range and answers {@link BRIDGE_CONFIG_PATH} with the real ws URL. This
29
+ * borrows the approach used by `natgurlain/dsh-browser-agent` (MIT).
30
+ *
31
+ * The extension already lists 43189 as a legacy probe; 43190–43198 extend it.
32
+ */
33
+ const BEACON_PORTS = [
34
+ 43189,
35
+ 43190,
36
+ 43191,
37
+ 43192,
38
+ 43193,
39
+ 43194,
40
+ 43195,
41
+ 43196,
42
+ 43197,
43
+ 43198
44
+ ];
45
+ /** Parse one bridge-config response body. */
46
+ function parseBridgeConfigPayload(value) {
47
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
48
+ const wsUrl = value.wsUrl;
49
+ return typeof wsUrl === "string" && wsUrl.length > 0 ? { wsUrl } : void 0;
50
+ }
25
51
  /** Seconds a fresh socket may take to present `hello` before it is closed. */
26
52
  const HELLO_TIMEOUT_MS = 5e3;
53
+ /**
54
+ * Wire-protocol generation. Bumped only for a change an older peer cannot
55
+ * ignore safely: a client that does not understand a new frame type fails to
56
+ * parse it, and the bridge closes the socket as `unparseable frame`.
57
+ *
58
+ * - 1: 0.4.x/0.5.x — hello/rpc/stream/tool/question/approval frames.
59
+ * - 2: 0.5.2 — adds the `ui.attached` client frame (panel presence).
60
+ *
61
+ * Both ends stay on one generation: the plugin ignores the frame from an older
62
+ * client (which never sends it), and the client only sends it after `hello.ok`
63
+ * names a generation that understands it.
64
+ */
65
+ const BRIDGE_PROTOCOL_VERSION = 2;
66
+ /** Close codes the bridge uses, so a client can tell why a socket ended. */
67
+ const BRIDGE_CLOSE_CODES = {
68
+ /** A newer authenticated connection replaced this one (do not reconnect). */
69
+ replaced: 4e3,
70
+ /** No `hello` arrived inside {@link HELLO_TIMEOUT_MS}. */
71
+ helloTimeout: 4001,
72
+ /** The bearer token was missing or wrong. */
73
+ badToken: 4002
74
+ };
27
75
  /** Server-side ping cadence; the client answers `pong` to prove liveness. */
28
76
  const PING_INTERVAL_MS = 3e4;
29
77
  /** Default bytes of the generated bearer token (256-bit). */
30
78
  const DEFAULT_TOKEN_BYTES = 32;
79
+ /** Most questions one card may carry (the host never asks more in practice; this bounds a hostile frame). */
80
+ const MAX_QUESTIONS_PER_CARD = 50;
31
81
  /**
32
82
  * Type guard: is this frame one the SERVER may send? Client-only shapes
33
83
  * (hello/rpc/stream.open/stream.close/tool.result/pong) narrow out, so
@@ -45,7 +95,7 @@ function isServerFrame(frame) {
45
95
  * @returns true for client-sendable frames.
46
96
  */
47
97
  function isClientFrame(frame) {
48
- return frame.t === "hello" || frame.t === "rpc" || frame.t === "stream.open" || frame.t === "stream.close" || frame.t === "tool.result" || frame.t === "pong";
98
+ return frame.t === "hello" || frame.t === "ui.attached" || frame.t === "rpc" || frame.t === "stream.open" || frame.t === "stream.close" || frame.t === "tool.result" || frame.t === "pong";
49
99
  }
50
100
  /** Wire args must be a plain object (the Remote descriptor's named arguments). */
51
101
  function isArgs(value) {
@@ -76,6 +126,10 @@ function parseBridgeFrame(text) {
76
126
  caps: frame.caps,
77
127
  ...frame.version === void 0 ? {} : { version: frame.version }
78
128
  };
129
+ case "ui.attached": return typeof frame.attached === "boolean" ? {
130
+ t: "ui.attached",
131
+ attached: frame.attached
132
+ } : void 0;
79
133
  case "rpc": return typeof frame.id === "string" && typeof frame.method === "string" && isArgs(frame.args) ? {
80
134
  t: "rpc",
81
135
  id: frame.id,
@@ -110,9 +164,11 @@ function parseBridgeFrame(text) {
110
164
  case "hello.ok":
111
165
  if (!isCaps(frame.caps)) return void 0;
112
166
  if (frame.version !== void 0 && typeof frame.version !== "string") return void 0;
167
+ if (frame.protocolVersion !== void 0 && (typeof frame.protocolVersion !== "number" || !Number.isInteger(frame.protocolVersion) || frame.protocolVersion < 1)) return void 0;
113
168
  return {
114
169
  t: "hello.ok",
115
170
  caps: frame.caps,
171
+ ...typeof frame.protocolVersion === "number" ? { protocolVersion: frame.protocolVersion } : {},
116
172
  ...frame.version === void 0 ? {} : { version: frame.version }
117
173
  };
118
174
  case "rpc.result":
@@ -156,7 +212,7 @@ function parseBridgeFrame(text) {
156
212
  t: "tool.cancel",
157
213
  id: frame.id
158
214
  } : void 0;
159
- case "question.requested": return typeof frame.id === "string" && typeof frame.sessionId === "string" && Array.isArray(frame.questions) && frame.questions.length > 0 && frame.questions.every(isQuestionItem) ? {
215
+ case "question.requested": return typeof frame.id === "string" && typeof frame.sessionId === "string" && Array.isArray(frame.questions) && frame.questions.length > 0 && frame.questions.length <= 50 && frame.questions.every(isQuestionItem) ? {
160
216
  t: "question.requested",
161
217
  id: frame.id,
162
218
  sessionId: frame.sessionId,
@@ -196,7 +252,7 @@ function parseBridgeFrame(text) {
196
252
  function isCaps(value) {
197
253
  if (typeof value !== "object" || value === null) return false;
198
254
  const caps = value;
199
- return typeof caps.snapshotMaxChars === "number" && caps.snapshotMaxChars > 0 && typeof caps.maxInteractiveItems === "number" && caps.maxInteractiveItems > 0 && (caps.questions === void 0 || typeof caps.questions === "boolean") && (caps.approvals === void 0 || typeof caps.approvals === "boolean");
255
+ return typeof caps.snapshotMaxChars === "number" && caps.snapshotMaxChars > 0 && typeof caps.maxInteractiveItems === "number" && caps.maxInteractiveItems > 0 && (caps.questions === void 0 || typeof caps.questions === "boolean") && (caps.approvals === void 0 || typeof caps.approvals === "boolean") && (caps.panelPresence === void 0 || typeof caps.panelPresence === "boolean");
200
256
  }
201
257
  /** Narrow one question item; unknown extra keys (e.g. host `intent`) pass through. */
202
258
  function isQuestionItem(value) {
@@ -211,4 +267,4 @@ function isWireFailure(value) {
211
267
  return typeof value === "object" && value !== null && typeof value.code === "string" && typeof value.message === "string";
212
268
  }
213
269
  //#endregion
214
- export { BRIDGE_CONFIG_PATH, BRIDGE_PATH, DEFAULT_TOKEN_BYTES, HELLO_TIMEOUT_MS, PING_INTERVAL_MS, isClientFrame, isServerFrame, parseBridgeFrame };
270
+ export { BEACON_PORTS, BRIDGE_CLOSE_CODES, BRIDGE_CONFIG_PATH, BRIDGE_PATH, BRIDGE_PROTOCOL_VERSION, DEFAULT_TOKEN_BYTES, HELLO_TIMEOUT_MS, MAX_QUESTIONS_PER_CARD, PING_INTERVAL_MS, isClientFrame, isServerFrame, parseBridgeConfigPayload, parseBridgeFrame };
@@ -8,6 +8,9 @@
8
8
  * - the host aborts `request.signal` (turn cancelled, session disposed) →
9
9
  * the extension is sent `approval.resolved` and the waterfall resolves
10
10
  * with `'cancelled'` (the host vocabulary has no rejection channel here);
11
+ * - nobody decides inside {@link answerTimeoutMs} → the extension is sent
12
+ * `approval.resolved` and the waterfall resolves `'cancelled'`, the
13
+ * fail-closed outcome for an abandoned card;
11
14
  * - the bridge connection drops ({@link delegateAll}) → the waterfall is
12
15
  * delegated to `next()` so another answerer (dsh web) can still decide;
13
16
  * - plugin unload ({@link dispose}) → `'unavailable'`, the fail-closed
@@ -48,6 +51,8 @@ export declare class ApprovalBridge {
48
51
  constructor(deps: {
49
52
  /** Push one server frame to the connected extension (must tolerate a dead socket). */
50
53
  push: (frame: ServerFrame) => void;
54
+ /** How long a card may sit undecided before it settles as cancelled; 0/undefined disables the budget. */
55
+ answerTimeoutMs?: number;
51
56
  });
52
57
  /**
53
58
  * Own one host waterfall request: push `approval.requested` to the
@@ -67,6 +72,8 @@ export declare class ApprovalBridge {
67
72
  decide(args: ApprovalDecisionArgs): ApprovalReceipt;
68
73
  /** Bridge connection replaced/closed: delegate every unsettled approval. */
69
74
  delegateAll(): void;
75
+ /** A new connection took over: re-push pending approvals to the fresh panel. */
76
+ replay(): void;
70
77
  /** Plugin unload: answer everything fail-closed so no tool call outlives the plugin. */
71
78
  dispose(): void;
72
79
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Fixed-port discovery beacon for dsh Desktop hosts that bind an ephemeral
3
+ * webserver port (`--port 0`). The beacon binds the first free port of
4
+ * {@link BEACON_PORTS}, answers `/ext/bridge-config` with the real bridge URL,
5
+ * and lets the extension find this instance with a bounded probe list.
6
+ *
7
+ * Hardening (mirrors `natgurlain/dsh-browser-agent`, MIT):
8
+ * - binds loopback only;
9
+ * - sends no CORS headers, so a web page cannot read the answer;
10
+ * - rejects a foreign `Host` header (DNS rebinding);
11
+ * - carries no secret — the WebSocket itself authenticates every client.
12
+ *
13
+ * @module
14
+ */
15
+ /** One bound discovery beacon. */
16
+ export interface DiscoveryBeacon {
17
+ /** The port actually bound. */
18
+ port: number;
19
+ /** Stop listening and release the port. */
20
+ close(): Promise<void>;
21
+ }
22
+ /**
23
+ * Bind the first free beacon port.
24
+ *
25
+ * @param hostPort - the real webserver port (or a getter, for late binding).
26
+ * @param ports - candidate ports, tried in order.
27
+ * @param warn - diagnostics sink, silent by default.
28
+ * @returns the bound beacon, or undefined when every candidate is busy.
29
+ */
30
+ export declare function startDiscoveryBeacon(hostPort: number | (() => number | undefined), ports?: readonly number[], warn?: (message: string) => void): Promise<DiscoveryBeacon | undefined>;
31
+ //# sourceMappingURL=discovery-beacon.d.ts.map
@@ -6,22 +6,40 @@
6
6
  *
7
7
  * Ownership has three sources, all revocable:
8
8
  * - **driven**: the extension created or prompted the session (kept until the
9
- * plugin unloads);
9
+ * session disappears or the plugin unloads);
10
10
  * - **followed**: an open `session/follow` stream means the sidebar is
11
11
  * displaying that session right now (released when the stream closes);
12
12
  * - **inherited**: an ask from a subagent child session belongs to the
13
13
  * nearest extension-owned ancestor, so child questions/approvals surface in
14
14
  * the parent conversation the user is actually watching.
15
15
  *
16
+ * Inheritance only ever matters for **approvals**: the host's `ask()` rejects a
17
+ * delegated caller outright (`DELEGATED_CALLER`) before the questions waterfall
18
+ * runs, so a subagent never reaches the user-questions event.
19
+ *
16
20
  * @module
17
21
  */
18
22
  /** Mutable registry of extension-owned session ids. */
19
23
  export declare class ExtensionSessionRegistry {
20
24
  private readonly ids;
25
+ /** Sessions that disappeared from the store are dropped on the next read. */
26
+ private readonly missing;
27
+ /** Whether a session the registry tracks has since been disposed. */
28
+ private exists;
21
29
  /** Remember a session the extension successfully created or prompted. */
22
30
  note(sessionId: string | undefined): void;
23
31
  /** Forget a session (a failed dispatch revoked an optimistic note). */
24
32
  forget(sessionId: string | undefined): void;
33
+ /**
34
+ * Install the store lookup that lets a disposed session release its
35
+ * ownership. Called lazily by the plugin so a Session store registered after
36
+ * this plugin still takes effect.
37
+ *
38
+ * @param exists - session-id → whether the store still holds it.
39
+ */
40
+ watchStore(exists: (sessionId: string) => boolean): void;
41
+ /** Record that a session was disposed; the next {@link has} drops it. */
42
+ dispose(sessionId: string | undefined): void;
25
43
  /** Whether the extension has touched this session over the bridge. */
26
44
  has(sessionId: string | undefined): boolean;
27
45
  /** Test helper: drop all tracked ids. */
@@ -64,8 +82,53 @@ export declare function isOwnedSession(sessionId: string | undefined, sources: O
64
82
  * @returns the owned session id to route to, or undefined when nothing owns it.
65
83
  */
66
84
  export declare function owningSessionId(sessionId: string | undefined, sources: OwnershipSources, parentOf?: (sessionId: string) => string | undefined): string | undefined;
85
+ /** Which UI most recently spoke in a session. */
86
+ export type InteractionSource = 'sidebar' | 'web' | 'unknown';
87
+ /**
88
+ * Last-active-UI tracking, per session.
89
+ *
90
+ * The host exposes no focus or visibility signal (its `TypertGateway` surface
91
+ * has none), so "which window is the user looking at" cannot be asked
92
+ * directly. What CAN be observed exactly is **which path the session's last
93
+ * prompt came through**:
94
+ *
95
+ * - a prompt the extension sends crosses the bridge, so the plugin sees it in
96
+ * its RPC dispatch and knows the sidebar spoke;
97
+ * - a prompt typed in dsh web never crosses the bridge, so it reaches this
98
+ * plugin only as a durable `user/message` whose source carries the prompt's
99
+ * `rpcId`. Anything not minted by the bridge came from another UI.
100
+ *
101
+ * That makes "who spoke last" the routing rule: the card follows the UI the
102
+ * user is actually driving, which is the closest reliable proxy for attention.
103
+ */
104
+ export declare class SessionActivity {
105
+ private readonly last;
106
+ /** Prompt identities this bridge minted, in arrival order (bounded). */
107
+ private readonly sidebarRequests;
108
+ /** Record that the sidebar sent a prompt (called from the bridge's RPC dispatch). */
109
+ noteSidebarPrompt(sessionId: string | undefined, requestId: string | undefined): void;
110
+ /** Record that another UI (dsh web) sent a prompt. */
111
+ noteWebPrompt(sessionId: string | undefined): void;
112
+ /** Whether this prompt identity was minted by the bridge (i.e. the sidebar). */
113
+ isSidebarRequest(requestId: string | undefined): boolean;
114
+ /** Which UI last spoke in this session; `unknown` before any prompt. */
115
+ sourceOf(sessionId: string | undefined): InteractionSource;
116
+ /** Test helper / bridge generation reset. */
117
+ clear(): void;
118
+ }
67
119
  /** Why a host interaction was delegated to the next answerer. */
68
- export type DelegateReason = 'no-connection' | 'unsupported-client' | 'not-owned';
120
+ export type DelegateReason =
121
+ /** No extension is connected, so only the native answerer remains. */
122
+ 'no-connection'
123
+ /** The connected extension predates this card kind. */
124
+ | 'unsupported-client'
125
+ /** Connected, capable, but no side panel is open: a card would be invisible. */
126
+ | 'no-panel'
127
+ /**
128
+ * A dsh web client is live and the session's most recent prompt did NOT come
129
+ * from the sidebar — so the user is driving that UI and the card belongs there.
130
+ */
131
+ | 'recently-web' | 'not-owned';
69
132
  /** One interaction-ownership decision, kept inspectable for logging and tests. */
70
133
  export type InteractionOwnership = {
71
134
  owned: true;
@@ -76,14 +139,33 @@ export type InteractionOwnership = {
76
139
  };
77
140
  /**
78
141
  * Decide whether the bridge should own one host interaction (question or
79
- * approval). All gates must pass: an extension is connected, it advertised
80
- * the matching card capability in its hello caps, and the asking session is
81
- * extension-owned (directly or through an owned ancestor). Everything else
82
- * falls through to `next()` so the native answerer waterfall keeps working.
142
+ * approval). All gates must pass: an extension is connected, it advertised the
143
+ * matching card capability in its hello caps, a panel is attached to show the
144
+ * card, the sidebar (not dsh web) drove the session most recently, and the
145
+ * asking session is extension-owned (directly or through an owned ancestor).
146
+ * Everything else falls through to `next()` so the native answerer waterfall
147
+ * keeps working.
148
+ *
149
+ * Gate order matters for diagnostics: the connection/capability/presence gates
150
+ * are about the extension alone and are answered first, so a log line names the
151
+ * real obstacle instead of blaming the web client for a missing socket.
83
152
  */
84
153
  export declare function resolveInteractionOwnership(input: {
85
154
  hasExtensionConnection: boolean;
86
155
  clientSupports: boolean;
156
+ /**
157
+ * Whether a side panel is attached. A socket without a panel cannot show a
158
+ * card, and claiming the waterfall anyway would strand the turn.
159
+ */
160
+ uiAttached: boolean;
161
+ /**
162
+ * Whether another answerer (the dsh web client) is live right now. On its own
163
+ * this says nothing about whether the user is looking at that UI, so it only
164
+ * decides the card when the sidebar did not speak last.
165
+ */
166
+ webAnswersInteractions: boolean;
167
+ /** Which UI most recently sent a prompt for this session. */
168
+ activeSource: InteractionSource;
87
169
  sessionId: string | undefined;
88
170
  sources: OwnershipSources;
89
171
  parentOf?: (sessionId: string) => string | undefined;
@@ -45,6 +45,12 @@ export interface Config {
45
45
  sessionWorkspacePath?: string;
46
46
  /** Defer real session creation until the first prompt. Defaults to true. */
47
47
  deferSessionCreate?: boolean;
48
+ /** Prefer the dsh web client as the interaction answerer. Defaults to true. */
49
+ preferWebAnswerer?: boolean;
50
+ /** How long one pushed question/approval may wait for an answer before it settles; 0 disables. Defaults to 600000. */
51
+ answerTimeoutMs?: number;
52
+ /** Bind a fixed-port discovery beacon so an ephemeral-port host is still findable. Defaults to true. */
53
+ discoveryBeacon?: boolean;
48
54
  }
49
55
  export declare const Config: z<Config>;
50
56
  /** The shape after schemastery applies its defaults to every field. */
@@ -21,8 +21,45 @@
21
21
  export declare const BRIDGE_PATH = "/ext/bridge";
22
22
  /** Zero-config discovery endpoint: returns `{ wsUrl }` for the extension. */
23
23
  export declare const BRIDGE_CONFIG_PATH = "/ext/bridge-config";
24
+ /**
25
+ * Fixed discovery beacons. A dsh Desktop host may bind its real webserver on
26
+ * an ephemeral port (`--port 0`); the bridge binds the first free port in this
27
+ * range and answers {@link BRIDGE_CONFIG_PATH} with the real ws URL. This
28
+ * borrows the approach used by `natgurlain/dsh-browser-agent` (MIT).
29
+ *
30
+ * The extension already lists 43189 as a legacy probe; 43190–43198 extend it.
31
+ */
32
+ export declare const BEACON_PORTS: readonly [43189, 43190, 43191, 43192, 43193, 43194, 43195, 43196, 43197, 43198];
33
+ /** Payload the config endpoint (real bridge and discovery beacon) returns. */
34
+ export interface BridgeConfigPayload {
35
+ wsUrl: string;
36
+ }
37
+ /** Parse one bridge-config response body. */
38
+ export declare function parseBridgeConfigPayload(value: unknown): BridgeConfigPayload | undefined;
24
39
  /** Seconds a fresh socket may take to present `hello` before it is closed. */
25
40
  export declare const HELLO_TIMEOUT_MS = 5000;
41
+ /**
42
+ * Wire-protocol generation. Bumped only for a change an older peer cannot
43
+ * ignore safely: a client that does not understand a new frame type fails to
44
+ * parse it, and the bridge closes the socket as `unparseable frame`.
45
+ *
46
+ * - 1: 0.4.x/0.5.x — hello/rpc/stream/tool/question/approval frames.
47
+ * - 2: 0.5.2 — adds the `ui.attached` client frame (panel presence).
48
+ *
49
+ * Both ends stay on one generation: the plugin ignores the frame from an older
50
+ * client (which never sends it), and the client only sends it after `hello.ok`
51
+ * names a generation that understands it.
52
+ */
53
+ export declare const BRIDGE_PROTOCOL_VERSION = 2;
54
+ /** Close codes the bridge uses, so a client can tell why a socket ended. */
55
+ export declare const BRIDGE_CLOSE_CODES: {
56
+ /** A newer authenticated connection replaced this one (do not reconnect). */
57
+ readonly replaced: 4000;
58
+ /** No `hello` arrived inside {@link HELLO_TIMEOUT_MS}. */
59
+ readonly helloTimeout: 4001;
60
+ /** The bearer token was missing or wrong. */
61
+ readonly badToken: 4002;
62
+ };
26
63
  /** Server-side ping cadence; the client answers `pong` to prove liveness. */
27
64
  export declare const PING_INTERVAL_MS = 30000;
28
65
  /** Default bytes of the generated bearer token (256-bit). */
@@ -53,6 +90,8 @@ export interface BridgeCaps {
53
90
  questions?: boolean;
54
91
  /** Client advertises it can render host approval (permission) cards; the plugin only claims the approval waterfall for extension-owned sessions when set. */
55
92
  approvals?: boolean;
93
+ /** Client advertises it understands the `ui.attached` frame (0.5.2+); absent means the bridge cannot tell whether a panel is open. */
94
+ panelPresence?: boolean;
56
95
  }
57
96
  /** One Remote failure as plain wire data (RemoteError's message is non-enumerable, so it is restated explicitly). */
58
97
  export interface RemoteWireFailure {
@@ -73,6 +112,8 @@ export interface QuestionOption {
73
112
  label: string;
74
113
  description?: string;
75
114
  }
115
+ /** Most questions one card may carry (the host never asks more in practice; this bounds a hostile frame). */
116
+ export declare const MAX_QUESTIONS_PER_CARD = 50;
76
117
  /**
77
118
  * One ask_user_question item as it crosses the bridge (the host
78
119
  * AskUserQuestionItem wire form, minus the host-internal `intent`).
@@ -94,6 +135,17 @@ export type ClientFrame =
94
135
  caps: BridgeCaps;
95
136
  version?: string;
96
137
  }
138
+ /**
139
+ * A side panel opened (`attached: true`) or the last one closed
140
+ * (`attached: false`). The bridge claims a host interaction waterfall only
141
+ * while a panel is attached, so a closed sidebar can never leave a card that
142
+ * nobody can see. Sent only to a plugin that advertises
143
+ * {@link BridgeCaps.panelPresence}.
144
+ */
145
+ | {
146
+ t: 'ui.attached';
147
+ attached: boolean;
148
+ }
97
149
  /** Unary Remote call: slash-joined endpoint plus the descriptor's native args object. */
98
150
  | {
99
151
  t: 'rpc';
@@ -136,6 +188,7 @@ export type ServerFrame =
136
188
  t: 'hello.ok';
137
189
  caps: BridgeCaps;
138
190
  version?: string;
191
+ protocolVersion?: number;
139
192
  }
140
193
  /** Reply to an `rpc` frame: the RemoteResult wire form, flattened onto the frame. */
141
194
  | {
@@ -9,10 +9,19 @@
9
9
  * model is told the user refused);
10
10
  * - the host aborts `request.signal` (turn cancelled, session disposed) →
11
11
  * the extension is sent `question.resolved` and the waterfall rejects;
12
+ * - nobody answers inside the configured budget ({@link answerTimeoutMs}) →
13
+ * the extension is sent `question.resolved` and the waterfall rejects with
14
+ * the host's `ASK_TIMED_OUT` code, so a forgotten card can never hold a
15
+ * turn forever;
12
16
  * - the bridge connection drops ({@link delegateAll}) → the waterfall is
13
17
  * delegated to `next()` so another answerer (dsh web) can still serve it;
14
18
  * - plugin unload ({@link dispose}) → everything rejects promptly.
15
19
  *
20
+ * A **timed** ask (`request.wait`) additionally holds the host's foreground
21
+ * wait through `userQuestions/attachWait` for as long as the card lives: the
22
+ * host only pauses its own countdown while some answer UI claims the wait, so
23
+ * without the claim the sidebar's card would be withdrawn mid-typing.
24
+ *
16
25
  * @module
17
26
  */
18
27
  import type { QuestionItem, ServerFrame } from './protocol.ts';
@@ -40,7 +49,11 @@ export interface QuestionAnswerArgs {
40
49
  answer?: unknown;
41
50
  decline?: boolean;
42
51
  }
43
- /** Structural validation of the extension's answer payload. */
52
+ /**
53
+ * Structural validation of the extension's answer payload. The host promises
54
+ * one item per question, so a partial or duplicated batch is refused here
55
+ * rather than handed to the model as a half answer.
56
+ */
44
57
  export declare function asAnswerPayload(value: unknown, questionIds: ReadonlySet<string>): QuestionAnswerPayload | undefined;
45
58
  /** Parse the extension's `bridge/questionAnswer` rpc args (light: ids only). */
46
59
  export declare function asQuestionAnswerArgs(value: unknown): QuestionAnswerArgs | undefined;
@@ -51,6 +64,15 @@ export declare class QuestionBridge {
51
64
  constructor(deps: {
52
65
  /** Push one server frame to the connected extension (must tolerate a dead socket). */
53
66
  push: (frame: ServerFrame) => void;
67
+ /**
68
+ * Hold the host's foreground wait for one timed ask while the sidebar owns
69
+ * the card. Returns the release function, or undefined when the host offers
70
+ * no such stream. The bridge never throws when this fails: losing the claim
71
+ * only means the host's own countdown keeps running.
72
+ */
73
+ attachWait?: (agentId: string, callId: string, signal: AbortSignal) => (() => void) | undefined;
74
+ /** How long a card may sit unanswered before it settles as timed out; 0/undefined disables the budget. */
75
+ answerTimeoutMs?: number;
54
76
  });
55
77
  /**
56
78
  * Own one host waterfall request: push `question.requested` to the
@@ -60,9 +82,16 @@ export declare class QuestionBridge {
60
82
  * @param questions - host question items (forwarded verbatim).
61
83
  * @param next - waterfall delegation, used when the bridge connection drops.
62
84
  * @param signal - host cancellation lifetime for this request.
85
+ * @param options - timed-ask bookkeeping (`request.wait`) and the asking agent.
63
86
  * @returns the user's answer.
64
87
  */
65
- ask(sessionId: string, questions: QuestionItem[], next: () => Promise<QuestionAnswerPayload>, signal?: AbortSignal): Promise<QuestionAnswerPayload>;
88
+ ask(sessionId: string, questions: QuestionItem[], next: () => Promise<QuestionAnswerPayload>, signal?: AbortSignal, options?: {
89
+ agentId?: string | undefined;
90
+ wait?: {
91
+ callId: string;
92
+ timed?: boolean;
93
+ };
94
+ }): Promise<QuestionAnswerPayload>;
66
95
  /**
67
96
  * Settle one pending question from the extension's `bridge/questionAnswer`
68
97
  * rpc. The server replies with this receipt.
@@ -70,6 +99,12 @@ export declare class QuestionBridge {
70
99
  answer(args: QuestionAnswerArgs): QuestionAnswerReceipt;
71
100
  /** Bridge connection replaced/closed: delegate every unsettled question. */
72
101
  delegateAll(): void;
102
+ /**
103
+ * A new authenticated connection is taking over: re-push every still-pending
104
+ * card so the fresh panel can answer it. The extension clears its replay
105
+ * cache on `connecting`, so without this the card would simply vanish.
106
+ */
107
+ replay(): void;
73
108
  /** Plugin unload: reject everything so no tool call outlives the plugin. */
74
109
  dispose(): void;
75
110
  }
@@ -22,13 +22,29 @@ import type { IncomingMessage } from 'node:http';
22
22
  import type { Duplex } from 'node:stream';
23
23
  import { type BridgeCaps, type RemoteWireResult, type ServerFrame, type ToolErrorCode } from './protocol.ts';
24
24
  /**
25
- * Gateway endpoints the bridge pins to loopback (the rc line's
26
- * PRIVILEGED_METHODS, restated against the alpha Remote endpoint names:
27
- * settings/credentials mutation and host-desktop/filesystem actions). The
28
- * bridge rejects these for non-loopback remotes even with a valid token.
29
- * Exported so tests can tripwire the list against accidental shrinkage —
30
- * when the host line adds new privileged endpoints, extend this set in the
31
- * same commit.
25
+ * Remote namespaces the extension is actually allowed to reach when it is NOT
26
+ * a loopback client. The bridge speaks to the host as the `owner` principal
27
+ * (`principal: { kind: 'owner' }`), and the host's gateway skips
28
+ * `remoteAccess.decide` for owners — so this allowlist is the only gate.
29
+ *
30
+ * Default-deny by namespace means a newly added host endpoint (terminal/*,
31
+ * dynamicCordisRunner/*, pluginManager/*, workspaceFiles/*, ...) is refused
32
+ * automatically instead of silently widening the bridge's authority. Adding a
33
+ * namespace here is a security decision; keep it to what the extension calls.
34
+ *
35
+ * Exported so tests can tripwire it against accidental widening.
36
+ */
37
+ export declare const ALLOWED_NAMESPACES: Set<string>;
38
+ /**
39
+ * Individual methods refused even inside an allowed namespace: opening a
40
+ * host workspace path can reveal arbitrary directories to the browser.
41
+ */
42
+ export declare const DENIED_METHODS: Set<string>;
43
+ /**
44
+ * Kept as a named export for backwards compatibility with earlier tests that
45
+ * tripwired the old blacklist. Non-loopback clients are now gated by
46
+ * {@link ALLOWED_NAMESPACES}; this set only names the explicitly denied
47
+ * methods (a caller must not treat membership here as permission).
32
48
  */
33
49
  export declare const PRIVILEGED_METHODS: Set<string>;
34
50
  /**
@@ -67,6 +83,8 @@ export interface BridgeServerDeps {
67
83
  version?: string | undefined;
68
84
  /** An authenticated client arrived with a version different from ours. */
69
85
  onVersionMismatch?: (clientVersion: string) => void;
86
+ /** Whether this server should accept the `ui.attached` panel-presence frame. 0.5.2+: true. */
87
+ panelPresence?: boolean;
70
88
  /**
71
89
  * Plugin-local endpoint `bridge/questionAnswer`: settle one pending
72
90
  * ask_user_question the bridge pushed to this extension. Answered as the
@@ -87,6 +105,12 @@ export interface BridgeServerDeps {
87
105
  onFollowChanged?: (sessionId: string, open: boolean) => void;
88
106
  /** The active connection was replaced or closed (settle pushed questions). */
89
107
  onConnectionLost?: () => void;
108
+ /**
109
+ * A new authenticated connection replaced the old one and is about to be
110
+ * promoted. Pending interaction cards should be re-pushed to the new panel
111
+ * rather than delegated away.
112
+ */
113
+ onConnectionReplaced?: () => void;
90
114
  /**
91
115
  * Test seam: force the remote address seen by the privilege gate. The
92
116
  * sandbox cannot bind arbitrary loopback literals, so the non-loopback
@@ -152,6 +176,8 @@ export declare class BridgeServer {
152
176
  close(): Promise<void>;
153
177
  /** @returns whether an authenticated extension is currently connected. */
154
178
  hasConnection(): boolean;
179
+ /** @returns whether a side panel is attached to the connected extension. */
180
+ uiAttached(): boolean;
155
181
  /** @returns whether the connected extension advertised question-card support. */
156
182
  clientSupportsQuestions(): boolean;
157
183
  /** @returns whether the connected extension advertised approval-card support. */
@@ -172,7 +198,12 @@ export declare class BridgeServer {
172
198
  * must not reach the gateway until that admission has completed.
173
199
  */
174
200
  private routeRpc;
175
- /** Whether the connection owning this frame may call the endpoint at all. */
201
+ /**
202
+ * Whether the connection owning this frame may call the endpoint at all.
203
+ * Loopback clients keep the historical full authority (the extension runs
204
+ * on the user's own machine); non-loopback clients are confined to the
205
+ * extension's actual method surface by a default-deny namespace allowlist.
206
+ */
176
207
  private forbidden;
177
208
  private handleRpc;
178
209
  /** Open one Remote stream and pump its frames until closed, failed, or replaced. */
@@ -185,7 +216,14 @@ export declare class BridgeServer {
185
216
  /** Abort one open stream (client `stream.close`). */
186
217
  private closeStream;
187
218
  private settleTool;
188
- /** Close the current connection (if any) and settle its in-flight calls and streams. */
219
+ /**
220
+ * Close the current connection (if any) and settle its in-flight calls and
221
+ * streams.
222
+ *
223
+ * @param replaced - true when a NEW authenticated connection is about to
224
+ * take the slot. In that case pending interaction cards are kept alive and
225
+ * asked to re-push themselves; only a final loss delegates them away.
226
+ */
189
227
  private replaceConnection;
190
228
  }
191
229
  /**
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Model-facing trust boundary for text extracted from browser pages.
3
+ *
4
+ * A page controls every byte of a snapshot, and a snapshot lands in the model's
5
+ * context as ordinary tool output — so a page can write "ignore your previous
6
+ * instructions" and be read as if the user had said it. Wrapping the text in a
7
+ * boundary whose closing tag carries a fresh random nonce makes forging that
8
+ * boundary impractical, and the notice states the rule explicitly.
9
+ *
10
+ * This is defense in depth only: the enforcement boundary for *actions* is the
11
+ * host's approval path plus the extension's permission level, never this text.
12
+ *
13
+ * Ported from `omdsh-dev/dsh-browser` (MIT), `src/security/untrusted.ts`.
14
+ *
15
+ * @module
16
+ */
17
+ /** The rule restated on both sides of the boundary. */
18
+ export declare const UNTRUSTED_NOTICE: string;
19
+ /** Element name of the boundary, kept stable so a model learns it once. */
20
+ export declare const UNTRUSTED_TAG = "UNTRUSTED_PAGE_CONTENT";
21
+ /**
22
+ * Wrap page-derived text in a nonce-tagged untrusted boundary.
23
+ *
24
+ * @param content - text the page (or a page-derived tool) produced.
25
+ * @param maxChars - hard ceiling for the whole wrapped result; the body is
26
+ * truncated first so the boundary always survives intact.
27
+ * @param nonce - boundary nonce; defaults to a fresh random UUID.
28
+ * @returns the wrapped text, never longer than `maxChars`.
29
+ */
30
+ export declare function wrapUntrustedContent(content: string, maxChars: number, nonce?: string): string;
31
+ //# sourceMappingURL=untrusted.d.ts.map
@@ -27,6 +27,8 @@ export declare class PendingWaterfalls<TOutcome, TPayload = undefined> {
27
27
  signal: AbortSignal | undefined;
28
28
  payload: TPayload;
29
29
  complete: (outcome: TOutcome) => void;
30
+ /** Settlement of a `complete` that threw; must reject the caller's promise. */
31
+ fail: (error: unknown) => void;
30
32
  onAbort: () => void;
31
33
  }): void;
32
34
  /**
@@ -36,6 +38,8 @@ export declare class PendingWaterfalls<TOutcome, TPayload = undefined> {
36
38
  matches(id: string, sessionId: string): boolean;
37
39
  /** Domain payload registered with one unsettled entry (undefined once settled). */
38
40
  payloadOf(id: string): TPayload | undefined;
41
+ /** Asking session registered with one unsettled entry (undefined once settled). */
42
+ sessionOf(id: string): string | undefined;
39
43
  /**
40
44
  * Settle one request. Later settlements for the same id are no-ops, and the
41
45
  * entry is dropped together with its abort listener.