@linxin666/dsh-remote-bridge 0.4.7 → 0.4.8

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.
@@ -32,6 +32,19 @@ export interface ApprovalPrompt {
32
32
  /** Settles exactly once, with a decision or `undefined` to delegate. */
33
33
  readonly answer: Promise<ApprovalAnswer>;
34
34
  }
35
+ /**
36
+ * One live question as a second delivery publishes it.
37
+ *
38
+ * The same four fields the first broadcast carries, so a card a phone was shown
39
+ * and the same card handed to it again after a reconnect cannot be spelled
40
+ * differently.
41
+ */
42
+ export interface PendingPromptView {
43
+ readonly id: string;
44
+ readonly sessionId: string;
45
+ readonly toolName: string;
46
+ readonly summary: string;
47
+ }
35
48
  export interface ApprovalRegistryOptions {
36
49
  readonly timeoutMs?: number;
37
50
  /** Id source, injectable so a test can answer the exact id it was given. */
@@ -49,6 +62,17 @@ export declare class ApprovalRegistry {
49
62
  constructor(options?: ApprovalRegistryOptions);
50
63
  /** @returns how many questions are currently waiting for a phone. */
51
64
  get size(): number;
65
+ /**
66
+ * Every question still waiting for a phone, in claim order.
67
+ *
68
+ * Only a live claim can be named here: {@link #settle} is the single path out
69
+ * of the pending map, and an answer, the bridge's own timeout, the agent's
70
+ * cancellation and every withdrawal all pass through it before this reads the
71
+ * map again. A question this bridge released therefore cannot come back to a
72
+ * client that reconnects.
73
+ * @returns the fields a second delivery republishes, oldest claim first.
74
+ */
75
+ openPrompts(): readonly PendingPromptView[];
52
76
  /**
53
77
  * Claim one question.
54
78
  * @param input - session identity, tool name, presentation summary, and the agent's own lifetime.
@@ -17,6 +17,8 @@
17
17
  */
18
18
  import type { ApprovalRegistry } from './approvals.ts';
19
19
  import type { DeviceRoster } from './devices.ts';
20
+ import type { RemoteBridgeRegistry } from './extension.ts';
21
+ import { type JobRoster } from './jobs.ts';
20
22
  import type { PairingService } from './pairing.ts';
21
23
  import type { QuestionClaims } from './questions.ts';
22
24
  import { type SessionMeta } from './session-meta.ts';
@@ -24,12 +26,40 @@ import type { SessionPermissions } from './session-permissions.ts';
24
26
  import type { BridgeGateway, GatewayPeer } from './wire.ts';
25
27
  /** Protocol-level heartbeat period: a frame is sent after this long without one. */
26
28
  export declare const IDLE_PING_MS = 20000;
29
+ /**
30
+ * Deadline behind one liveness ping: a peer that sends no frame at all within
31
+ * this long of the ping is torn down.
32
+ *
33
+ * It only ever exists because a ping was sent — a connection the host has not
34
+ * pinged has no deadline — so a quiet client is never closed for being quiet,
35
+ * only for failing to answer. The measured one-way path over the relay is about
36
+ * 410 ms (2026-10-19), so this is more than an order of magnitude of slack.
37
+ */
38
+ export declare const LIVENESS_TIMEOUT_MS = 10000;
27
39
  /** How long `session.snapshot` waits for its follow stream's opening frame. */
28
40
  export declare const SNAPSHOT_OPEN_TIMEOUT_MS = 10000;
29
41
  /** Largest turn window one snapshot asks DSH for. */
30
42
  export declare const SNAPSHOT_MAX_MESSAGES = 200;
31
43
  /** Default byte budget of one `session.history` page: 512 KiB. */
32
44
  export declare const HISTORY_PAGE_BYTES: number;
45
+ /**
46
+ * Window one `session.history.deep` read asks DSH for: at least 50 user or
47
+ * assistant messages across at least 2 turns, and never more than 500 messages.
48
+ *
49
+ * It is the window the harness's own Web client pages history with, and it is
50
+ * deliberately wider than one answer: a byte budget is the caller's, so the
51
+ * store is asked for a whole span once and the bridge then cuts that span to
52
+ * `maxBytes` by entry. Nothing in the answer depends on where the store cut:
53
+ * the host's `hasMore` is folded into the answer's own `hasMore`, and the
54
+ * cursor is always the oldest entry the answer carries.
55
+ */
56
+ export declare const DEEP_HISTORY_WINDOW: {
57
+ readonly maxMessages: 500;
58
+ readonly turnWindow: {
59
+ readonly minMessages: 50;
60
+ readonly minTurns: 2;
61
+ };
62
+ };
33
63
  /** Highest number of prompt receipts one connection remembers for idempotency. */
34
64
  export declare const PROMPT_RECEIPT_LIMIT = 512;
35
65
  /** Largest base64 text one prompt attachment may carry: 6 MiB (protocol §10.2). */
@@ -38,6 +68,14 @@ export declare const PROMPT_ATTACHMENT_MAX_BYTES: number;
38
68
  export interface BridgeTransport {
39
69
  send(text: string): void;
40
70
  close(code: number, reason: string): void;
71
+ /**
72
+ * Optional: whether the peer declared `frame.deflate.v1`, reported once the
73
+ * `hello` that declares it has been recorded. The capability is the client's
74
+ * declaration and the wire form is the carrier's, so this is the one fact that
75
+ * has to cross between them. A carrier with no socket to compress — a
76
+ * recording double, for one — omits the member and keeps writing text.
77
+ */
78
+ frameDeflate?(declared: boolean): void;
41
79
  }
42
80
  export interface BridgeConnectionOptions {
43
81
  readonly gateway: BridgeGateway;
@@ -46,6 +84,8 @@ export interface BridgeConnectionOptions {
46
84
  readonly approvals: ApprovalRegistry;
47
85
  /** Pending user questions: the claims this bridge holds and the answer path back to the host. */
48
86
  readonly questions: QuestionClaims;
87
+ /** The host's background jobs: the read-only projection and the scopes this connection watches. */
88
+ readonly jobs: JobRoster;
49
89
  /** Process-local session metadata: live titles and the host's archive set. */
50
90
  readonly sessionMeta: SessionMeta;
51
91
  /** Host-process permission presets, read and switched through their real service objects. */
@@ -68,18 +108,17 @@ export interface BridgeConnectionOptions {
68
108
  */
69
109
  readonly onDeclare?: (connection: BridgeConnection) => void;
70
110
  readonly heartbeatMs?: number;
111
+ /**
112
+ * Methods plugins registered on the bridge's extension seam. Absent is the
113
+ * protocol exactly as this package defines it: every name outside
114
+ * `KNOWN_METHODS` answers `unknown-method`.
115
+ */
116
+ readonly extensions?: RemoteBridgeRegistry;
71
117
  }
72
118
  /** A device the connection proved itself to be, resolved from the upgrade request. */
73
119
  export interface ConnectionAuth {
74
120
  readonly deviceId: string;
75
121
  }
76
- /**
77
- * Everything one connected device may do.
78
- *
79
- * Not thread-safe by construction but safe by awaiting: handlers are invoked
80
- * one frame at a time by the carrier's reader, and the only background work is
81
- * a subscription's own drain loop.
82
- */
83
122
  export declare class BridgeConnection {
84
123
  #private;
85
124
  constructor(options: BridgeConnectionOptions, transport: BridgeTransport, auth?: ConnectionAuth);
@@ -89,6 +128,11 @@ export declare class BridgeConnection {
89
128
  get deviceId(): string | undefined;
90
129
  /** @returns whether the connection has been torn down. */
91
130
  get disposed(): boolean;
131
+ /**
132
+ * @returns this connection's identity for the extension seam. Stable for the
133
+ * life of the socket and never reused by a later one.
134
+ */
135
+ get id(): string;
92
136
  /**
93
137
  * @param capability - one capability name this protocol defines.
94
138
  * @returns whether this connection announced it in `hello`.
@@ -114,6 +158,13 @@ export declare class BridgeConnection {
114
158
  * Tear the connection down: stop the heartbeat, abort every follow stream it
115
159
  * owns, and tell the carrier to go away. Idempotent, and safe to call from a
116
160
  * socket error handler — a carrier whose socket already closed ignores it.
161
+ * @param close - the close frame to send instead of the bridge-unloading one.
162
+ * Only the liveness deadline passes it, so a client can tell a peer that
163
+ * stopped answering from an ordinary teardown; every other caller leaves it
164
+ * out and keeps the same code and reason as before.
117
165
  */
118
- dispose(): void;
166
+ dispose(close?: {
167
+ readonly code: number;
168
+ readonly reason: string;
169
+ }): void;
119
170
  }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Per-connection delta windows: what a client that already holds a copy of a
3
+ * whole set is sent instead of the whole set again.
4
+ *
5
+ * The difference is computed here, in the bridge, because the bridge is the
6
+ * only place that holds what the host said last — the host itself is asked for
7
+ * its complete answer every time and never learns that a client is caching one.
8
+ * That is the whole point of this module: the saving is bytes on the wire
9
+ * between the bridge and the phone, not a change to any host API.
10
+ *
11
+ * Three rules live in this file and nowhere else, so the roster and the board
12
+ * cannot disagree about them:
13
+ *
14
+ * - a delta is only diffed against the exact set this window last sent, and
15
+ * only for a token this window itself issued; anything else answers a reset,
16
+ * because a wrong base is a wrong answer;
17
+ * - a change is a change of the serialised row, not of a timestamp — the host's
18
+ * `updatedAt` is not a change signal for every field, and a row whose body is
19
+ * byte-identical has not changed;
20
+ * - a delta that is not clearly smaller than the reset body is not worth
21
+ * sending: past {@link DELTA_CHANGED_RATIO} of the rows, the answer is a reset.
22
+ * @module dsh-remote-bridge/core/delta
23
+ */
24
+ /** Largest roster one connection's delta window retains. */
25
+ export declare const ROSTER_DELTA_MAX_ROWS = 5000;
26
+ /** Largest board one connection's delta window retains. */
27
+ export declare const BOARD_DELTA_MAX_ROWS = 2000;
28
+ /**
29
+ * Share of the current set that may change before a reset is the cheaper
30
+ * answer. Bytes, not cleverness: past this point the delta carries most of the
31
+ * body already and the extra keys only make it bigger.
32
+ */
33
+ export declare const DELTA_CHANGED_RATIO = 0.6;
34
+ /** The one row field every set this module diffs is keyed by. */
35
+ export interface DeltaRow {
36
+ readonly id: string;
37
+ }
38
+ /** One window's answer, before a method wraps it in its own wire shape. */
39
+ export type DeltaAnswer<T> = {
40
+ readonly mode: 'reset';
41
+ /** Opaque token to send back as `since`; `""` when nothing was retained. */
42
+ readonly token: string;
43
+ /** The whole set, exactly as the method always published it. */
44
+ readonly rows: readonly T[];
45
+ } | {
46
+ readonly mode: 'delta';
47
+ readonly token: string;
48
+ /** Every row that is new or whose body differs from the last one sent. */
49
+ readonly changed: readonly T[];
50
+ /** Every id this window sent before and the host no longer names. */
51
+ readonly removed: readonly string[];
52
+ };
53
+ /** Cap on the set one window may retain. */
54
+ export interface DeltaLimits {
55
+ readonly maxRows: number;
56
+ }
57
+ /**
58
+ * One connection's view of one set: the rows it last sent, and the token that
59
+ * set was announced under.
60
+ *
61
+ * A window is created lazily by whoever needs it and lives exactly as long as
62
+ * the connection that owns it (see {@link RemoteBridgeDeltas}), so two
63
+ * connections never share a base and a dropped connection leaks nothing.
64
+ */
65
+ export declare class DeltaWindow<T extends DeltaRow> {
66
+ #private;
67
+ constructor(limits: DeltaLimits);
68
+ /**
69
+ * Answer one call over the current full set.
70
+ * @param rows - the complete set, exactly as the host answered it this time.
71
+ * @param since - the opaque token the client sent, if it sent one.
72
+ * @returns a reset carrying every row, or a delta against the last set sent.
73
+ */
74
+ answer(rows: readonly T[], since: string | undefined): DeltaAnswer<T>;
75
+ }
76
+ /**
77
+ * The delta windows one connection owns, by the name its owner keys them with.
78
+ *
79
+ * Held on the connection, so the state is released exactly when the connection
80
+ * is: there is no second registry to expire, and no connection's window can be
81
+ * read by another.
82
+ */
83
+ export declare class RemoteBridgeDeltas {
84
+ #private;
85
+ /**
86
+ * @param key - the window's name within this connection; one set, one key.
87
+ * @param limits - the cap this window retains.
88
+ * @returns the window, created on first use.
89
+ */
90
+ window<T extends DeltaRow>(key: string, limits: DeltaLimits): DeltaWindow<T>;
91
+ /**
92
+ * @param key - one window's name.
93
+ *
94
+ * Drops that window and the set it retained, so its token names nothing and
95
+ * the next call answers a reset. Used when a connection stops being served
96
+ * increments at all, which must cost it no memory either.
97
+ */
98
+ drop(key: string): void;
99
+ /** Drop every window: called when the owning connection is torn down. */
100
+ clear(): void;
101
+ }
@@ -23,6 +23,24 @@ export interface MessageUsage {
23
23
  readonly cacheWriteTokens?: number;
24
24
  readonly reasoningTokens?: number;
25
25
  }
26
+ /**
27
+ * Where one user message came from, as the host's durable `source` says.
28
+ *
29
+ * The three kinds are the only classification this protocol makes, and they are
30
+ * read off `source.kind` mechanically: `user` and `user-approval` are a human,
31
+ * `agent-message` and `subagent-settled` are an agent, and every other kind —
32
+ * including one this bridge has never seen — is the system. `sourceKind` is the
33
+ * host's own string, verbatim, so a client can tell "the system" apart without
34
+ * the bridge inventing a taxonomy it cannot keep current.
35
+ */
36
+ export interface MessageActor {
37
+ readonly kind: 'human' | 'agent' | 'system';
38
+ readonly sourceKind: string;
39
+ /** Durable id of the session that sent the message; only known for an agent. */
40
+ readonly sessionId?: string;
41
+ /** The host's own display label for the source, when it wrote one. */
42
+ readonly label?: string;
43
+ }
26
44
  /** One protocol v1 delta, before the session id and event sequence are attached. */
27
45
  export type SessionDelta = {
28
46
  readonly kind: 'text';
@@ -50,6 +68,13 @@ export type SessionDelta = {
50
68
  readonly text: string;
51
69
  readonly messageId?: string;
52
70
  readonly attachments?: readonly UserMessageAttachment[];
71
+ readonly actor?: MessageActor;
72
+ } | {
73
+ readonly kind: 'subagent';
74
+ readonly childId: string;
75
+ readonly label?: string;
76
+ readonly mode?: string;
77
+ readonly callId?: string;
53
78
  } | {
54
79
  readonly kind: 'usage';
55
80
  readonly usage: MessageUsage;
@@ -62,9 +87,16 @@ export declare const TOOL_CALL_MEMORY = 512;
62
87
  export declare const USER_MESSAGE_MEMORY = 512;
63
88
  /**
64
89
  * The durable entry types a protocol v1 client renders — `user/message`,
65
- * `assistant/message`, `tool/call` and `tool/result`. Everything else in a
66
- * turn's entries is the harness's own bookkeeping, which the client can only
67
- * count as unknown, so a client that asks for a trimmed baseline is not sent it.
90
+ * `assistant/message`, `tool/call`, `tool/result` and `subagent/catalog`.
91
+ * Everything else in a turn's entries is the harness's own bookkeeping, which
92
+ * the client can only count as unknown, so a client that asks for a trimmed
93
+ * baseline is not sent it.
94
+ *
95
+ * The catalog entry is here because it is the baseline half of the subagent
96
+ * thread: a phone that opens a session after children were spawned has no other
97
+ * way to learn that they exist, their labels, their modes or the call that
98
+ * spawned them. Without it the thread header can only be inferred from agent
99
+ * messages, and every field the catalog carries is lost.
68
100
  */
69
101
  export declare const RENDERED_ENTRY_TYPES: ReadonlySet<string>;
70
102
  /** One raw durable event inside a snapshot turn. */
@@ -73,6 +105,8 @@ export interface SnapshotEntry {
73
105
  readonly time: number;
74
106
  readonly type: string;
75
107
  readonly data: unknown;
108
+ /** Where a `user/message` came from; absent on every other entry type. */
109
+ readonly actor?: MessageActor;
76
110
  }
77
111
  /** One turn of a session snapshot: the durable events from `turn/start` to `turn/end`. */
78
112
  export interface SnapshotTurn {
@@ -122,21 +156,117 @@ export declare class MessageIndex {
122
156
  /** Remember one message, evicting the oldest entry past {@link USER_MESSAGE_MEMORY}. */
123
157
  remember(id: string): void;
124
158
  }
159
+ /**
160
+ * The child sessions one `tool/result` payload names as spawned.
161
+ *
162
+ * A spawn answers with a handle, and the handle is the only place a durable
163
+ * record ties a child id to the call that made it: the catalog event names the
164
+ * child but not the call. Two shapes are written by this harness and both are
165
+ * read here, verbatim from a real session log —
166
+ *
167
+ * - the activation handle the `subagent` tool returns, alone or nested in the
168
+ * object a `run_code` program returns:
169
+ * `{"a":{"kind":"activation","subagentId":"b0a3a569-…"}}`;
170
+ * - the plain notice the same tool prints when it runs without PTC:
171
+ * `started subagent d605390b-66f6-474b-956d-0824ec2103e0`.
172
+ *
173
+ * Nothing else is accepted: a `list_agents` answer that happens to list a child
174
+ * (`[{"kind":"child","id":"…"}]`) carries neither signature, so it can never
175
+ * lend its own call id to a thread it did not spawn.
176
+ * @param data - one durable `tool/result` payload.
177
+ * @returns the child ids the payload names, in the order it names them.
178
+ */
179
+ export declare function spawnedChildIdsOf(data: unknown): string[];
180
+ /**
181
+ * The child-to-call evidence one session's records already carry.
182
+ *
183
+ * A spawn's result can be projected after the catalog it belongs to, so a
184
+ * baseline reads the whole record list for this evidence before it resolves any
185
+ * catalog entry: the snapshot is a session that has already happened, and the
186
+ * answer it gives a client must not depend on where in the list it stopped
187
+ * looking. The live subscription feeds the same evidence in as it arrives.
188
+ * @param records - durable follow records, oldest first.
189
+ * @returns every child id a `tool/result` names, with the call that produced it.
190
+ */
191
+ export declare function spawnCallEvidence(records: readonly unknown[]): Map<string, string>;
192
+ /**
193
+ * Correlates one `subagent/catalog` event to the tool call that spawned the
194
+ * child it registers.
195
+ *
196
+ * The catalog event names the child but not the call, so the call is read from
197
+ * two places, in this order:
198
+ *
199
+ * 1. the spawn's own `tool/result`, which names the child it started
200
+ * ({@link spawnedChildIdsOf}). This is the decisive one: it survives a step
201
+ * that issued several calls, and a step whose one call started a whole team
202
+ * of children, because the payload says which child it is about.
203
+ * 2. the nearest preceding `tool/call` of the same turn and step, which is
204
+ * decidable only while one call is the whole story. A step with several
205
+ * calls leaves two candidates, and a call that already produced a child
206
+ * leaves one call behind two children; a guessed id would point a thread at
207
+ * the wrong card.
208
+ *
209
+ * Neither holds: undefined, and the wire carries no call id at all. The same
210
+ * index answers both paths — a subscription as it watches, and a baseline after
211
+ * reading the session's records — so the two can never disagree about which rule
212
+ * decides a given catalog.
213
+ */
214
+ export declare class SpawnCallIndex {
215
+ #private;
216
+ /**
217
+ * @param evidence - child-to-call pairs already read from the session's
218
+ * results, for the baseline path; empty for a live subscription.
219
+ */
220
+ constructor(evidence?: ReadonlyMap<string, string>);
221
+ /**
222
+ * Read one durable event into the correlation state.
223
+ *
224
+ * A turn boundary or a new step is the only reset: a call belongs to the step
225
+ * that issued it, so a call from an earlier step can never be the nearest
226
+ * preceding one.
227
+ */
228
+ observe(type: string, data: unknown): void;
229
+ /**
230
+ * The call that spawned the child a catalog event registered.
231
+ * @param childId - the child that catalog event carries.
232
+ * @returns its call id, or undefined when nothing on the wire decides it.
233
+ */
234
+ spawnCallId(childId: string): string | undefined;
235
+ }
125
236
  /**
126
237
  * Read the opening frame of a follow stream.
127
238
  * @returns the cursor and records, or undefined when this frame is not a snapshot.
128
239
  */
129
240
  export declare function readFollowBaseline(frame: unknown): FollowBaseline | undefined;
241
+ /** What one follow stream remembers beyond its two bounded message indexes. */
242
+ export interface FollowMemory {
243
+ /** Whether this connection declared `subagent.thread.v1`. */
244
+ readonly subagentThread?: boolean;
245
+ /** This stream's spawning-call correlation state; absent when the kind is off. */
246
+ readonly spawnCalls?: SpawnCallIndex;
247
+ }
130
248
  /**
131
249
  * Map one DSH follow frame to a delta, or undefined when the frame carries no
132
250
  * increment this protocol publishes.
133
251
  * @param frame - one `SessionFollowFrame`.
134
252
  * @param toolCalls - this connection's tool-call memory.
135
253
  * @param messages - this connection's published-user-message memory.
254
+ * @param memory - the stream's own correlation state, and which optional kinds it declared.
255
+ */
256
+ export declare function deltaOfFollowFrame(frame: unknown, toolCalls: ToolCallIndex, messages: MessageIndex, memory?: FollowMemory): SessionDelta | undefined;
257
+ /**
258
+ * Derive one message's actor from the host's own `source` record, mechanically.
259
+ * @param source - the `source` member of a durable `user/message`.
260
+ * @returns the actor, or undefined when the source carries no kind.
136
261
  */
137
- export declare function deltaOfFollowFrame(frame: unknown, toolCalls: ToolCallIndex, messages: MessageIndex): SessionDelta | undefined;
262
+ export declare function actorOfSource(source: unknown): MessageActor | undefined;
138
263
  /**
139
264
  * Project a follow baseline's records into turns.
265
+ *
266
+ * A `subagent/catalog` entry leaves here carrying the call that spawned its
267
+ * child in `data.callId`, decided by the same {@link SpawnCallIndex} a live
268
+ * subscription uses — so the baseline half and the live half of the thread
269
+ * cannot answer differently about one catalog.
140
270
  * @param records - the baseline's durable records, oldest first.
141
271
  * @returns one turn per `turn/start`, plus a lead-in turn when records precede the first one.
142
272
  */
@@ -179,3 +309,24 @@ export interface SnapshotPage {
179
309
  * @param measure - exact encoded size of one page shape, owned by the caller.
180
310
  */
181
311
  export declare function pageTurns(turns: readonly SnapshotTurn[], before: number | undefined, maxBytes: number, measure: (turns: readonly SnapshotTurn[], nextBefore: number | undefined, hasMore: boolean) => number): SnapshotPage;
312
+ /**
313
+ * Durable seq of a projection's oldest entry, or undefined when it carries none.
314
+ *
315
+ * The oldest entry is the first entry of the first turn that has one: a trimmed
316
+ * turn may keep no entry at all, so the scan skips those rather than reading
317
+ * `turns[0].entries[0]` and calling an empty-leading view an empty window.
318
+ * @param turns - the projection to read, in order.
319
+ */
320
+ export declare function oldestEntrySeq(turns: readonly SnapshotTurn[]): number | undefined;
321
+ /**
322
+ * Cut a projection at a durable watermark, keeping what is strictly above it.
323
+ *
324
+ * This is the forward twin of {@link pageTurns}' own slice: the same
325
+ * entry-level rule (`seq` is a durable watermark, not an index), the same
326
+ * turn rebuild, so an incremental snapshot carries turns shaped exactly like
327
+ * the baseline it continues — a turn whose remaining entries are fewer keeps
328
+ * its own `seq`, `endSeq`, `reason` and `time`.
329
+ * @param turns - the projection to cut, in order.
330
+ * @param watermark - exclusive durable watermark; entries at or below it are dropped.
331
+ */
332
+ export declare function turnsAbove(turns: readonly SnapshotTurn[], watermark: number): SnapshotTurn[];
@@ -21,6 +21,11 @@
21
21
  */
22
22
  /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
23
23
  export declare const MAX_FRAME_BYTES: number;
24
+ /**
25
+ * Smallest frame the host compresses, in UTF-8 bytes. Below it the DEFLATE
26
+ * header alone can outweigh a small object, so such a frame is never even tried.
27
+ */
28
+ export declare const FRAME_DEFLATE_MIN_BYTES = 1024;
24
29
  /** Reserved response id for a frame whose own id could not be recovered. */
25
30
  export declare const UNIDENTIFIED_FRAME_ID = 0;
26
31
  export interface ReqFrame {
@@ -80,6 +85,35 @@ export declare const DIRECTION_VIOLATION = "direction-violation";
80
85
  export declare function decodeClientFrame(text: string): DecodeOutcome;
81
86
  /** Encode one outgoing frame. */
82
87
  export declare function encodeFrame(frame: ServerFrame): string;
88
+ /**
89
+ * How one encoded frame crosses the wire: as the text the codec produced, or as
90
+ * raw DEFLATE of exactly that text.
91
+ */
92
+ export type OutboundPayload = {
93
+ readonly binary: false;
94
+ readonly text: string;
95
+ } | {
96
+ readonly binary: true;
97
+ readonly deflated: Buffer;
98
+ };
99
+ /**
100
+ * Decide the wire form of one encoded frame.
101
+ *
102
+ * The decision is a byte-level question only, asked after the frame has been
103
+ * measured against {@link MAX_FRAME_BYTES}: the text is deflated exactly as it
104
+ * stands, so a peer that inflates gets back the frame the text path would have
105
+ * written. A frame below {@link FRAME_DEFLATE_MIN_BYTES}, and a frame DEFLATE
106
+ * does not shrink (zlib's default level), both stay text — a binary frame that
107
+ * is larger than the text it replaces would pay for itself in neither direction.
108
+ * @param text - the frame as {@link encodeFrame} produced it.
109
+ * @param compress - whether the peer declared the capability that permits this.
110
+ * @param deflate - the compressor: zlib's raw DEFLATE at its default level, unless
111
+ * a caller injects one. Real deflate shrinks every frame that reaches the
112
+ * threshold, so an injected compressor is the only way to exercise the no-gain
113
+ * rule with content that truly cannot be compressed.
114
+ * @returns the text, or raw DEFLATE of it.
115
+ */
116
+ export declare function outboundPayloadOf(text: string, compress: boolean, deflate?: (source: Buffer) => Buffer): OutboundPayload;
83
117
  /** One successful response frame. */
84
118
  export declare function responseFrame(id: number, result: unknown): ResFrame;
85
119
  /** One failed response frame. */
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The bridge's extension seam: the one place another plugin adds methods and
3
+ * events to protocol v1 without the bridge learning what they mean.
4
+ *
5
+ * The bridge publishes this seam as the cordis service
6
+ * {@link REMOTE_BRIDGE_SERVICE}. A plugin registers a table of methods plus the
7
+ * capability a client must declare before those methods exist for it, and
8
+ * publishes events to the clients that declared the capability it names.
9
+ * Nothing here carries protocol vocabulary of its own: method names, payloads,
10
+ * topics and refusal codes belong to the registering plugin, which is why this
11
+ * module never appears in `KNOWN_METHODS` and never reads a payload.
12
+ *
13
+ * A connection dispatches an extension method only after the protocol's own
14
+ * gates: an unregistered name, a plugin that is not mounted, and a client that
15
+ * never declared the capability all answer `unknown-method` — the method is
16
+ * absent from that client's protocol, not refused by it.
17
+ * @module dsh-remote-bridge/core/extension
18
+ */
19
+ import type { RemoteBridgeDeltas } from './delta.ts';
20
+ /** Cordis service this seam is published under. */
21
+ export declare const REMOTE_BRIDGE_SERVICE = "remoteBridge";
22
+ /**
23
+ * Who is calling one extension method.
24
+ *
25
+ * The bridge exposes no device or session identity here on purpose: what an
26
+ * extension keys by connection is its own decision.
27
+ */
28
+ export interface RemoteBridgeCall {
29
+ /**
30
+ * Stable identity of the calling connection, unique within this bridge
31
+ * process. Two calls from one socket carry the same id; a reconnected socket
32
+ * carries a new one, because nothing proves it is the same peer.
33
+ */
34
+ readonly connectionId: string;
35
+ /**
36
+ * @param capability - one capability name of this protocol or of the calling
37
+ * extension.
38
+ * @returns whether this connection announced it in `hello`.
39
+ *
40
+ * The seam hands handlers the same predicate the bridge itself gates on, so
41
+ * an extension can gate behind a bridge capability (§15's `delta.v1`) without
42
+ * holding a copy of the client's declaration.
43
+ */
44
+ declares(capability: string): boolean;
45
+ /**
46
+ * This connection's delta windows, released with the connection.
47
+ *
48
+ * The mechanism of §15 lives once, in this bridge, and an extension borrows it
49
+ * per connection: the difference is always computed where the last answer is
50
+ * already held, and a dropped connection takes its base with it instead of
51
+ * leaving one to be expired by a second registry.
52
+ */
53
+ readonly deltas: RemoteBridgeDeltas;
54
+ }
55
+ /**
56
+ * What one extension method answers: the response body, or a refusal stated in
57
+ * the extension's own code vocabulary. The bridge forwards either verbatim —
58
+ * it holds no table of extension codes and invents none.
59
+ */
60
+ export type RemoteBridgeMethodResult = {
61
+ readonly ok: true;
62
+ readonly r?: unknown;
63
+ } | {
64
+ readonly ok: false;
65
+ readonly code: string;
66
+ readonly msg: string;
67
+ };
68
+ /** One client-callable method an extension owns. */
69
+ export type RemoteBridgeMethodHandler = (payload: Readonly<Record<string, unknown>>, call: RemoteBridgeCall) => RemoteBridgeMethodResult | Promise<RemoteBridgeMethodResult>;
70
+ /** A table of methods and the capability that admits a client to them. */
71
+ export interface RemoteBridgeMethods {
72
+ /**
73
+ * Capability a client declares in `hello`'s `cap` array before these methods
74
+ * are part of its protocol. Absent means every paired connection may call
75
+ * them; an unpaired connection never may, whatever it declared.
76
+ */
77
+ readonly capability?: string;
78
+ /** Method name to handler; the name is the extension's, not the bridge's. */
79
+ readonly methods: Readonly<Record<string, RemoteBridgeMethodHandler>>;
80
+ }
81
+ /** The seam, exactly as published on {@link REMOTE_BRIDGE_SERVICE}. */
82
+ export interface RemoteBridgeFace {
83
+ /**
84
+ * Add methods to the protocol surface.
85
+ * @returns the disposer withdrawing them; afterwards they answer `unknown-method` again.
86
+ */
87
+ registerMethods(table: RemoteBridgeMethods): () => void;
88
+ /**
89
+ * Publish one event to the connections that are paired — and, when a
90
+ * capability is named, have declared it.
91
+ * @returns how many connections took the frame.
92
+ */
93
+ broadcast(topic: string, payload: unknown, capability?: string): number;
94
+ }
95
+ /** The fan-out the seam publishes through; `BridgeHub` satisfies it. */
96
+ export interface RemoteBridgeFanout {
97
+ broadcast(topic: string, payload: unknown): number;
98
+ broadcastTo(capability: string, topic: string, payload: unknown): number;
99
+ }
100
+ /**
101
+ * The methods extensions registered, and the capability each one needs.
102
+ *
103
+ * Every connection consults this registry; nothing else holds extension state,
104
+ * so unmounting one plugin withdraws exactly its own methods.
105
+ */
106
+ export declare class RemoteBridgeRegistry {
107
+ #private;
108
+ /**
109
+ * Register one table of methods, all or nothing: a table naming a protocol
110
+ * method, an empty name or a name already taken is refused before any of its
111
+ * methods becomes callable.
112
+ * @param table - the methods and the capability they require.
113
+ * @returns the disposer withdrawing this table; idempotent.
114
+ */
115
+ registerMethods(table: RemoteBridgeMethods): () => void;
116
+ /**
117
+ * @param method - the method name a client asked for.
118
+ * @returns whether any plugin registered it, whatever capability it requires.
119
+ */
120
+ has(method: string): boolean;
121
+ /**
122
+ * @param method - the method name a client asked for.
123
+ * @param declares - whether the calling connection declared a capability.
124
+ * @returns the handler when the caller may use the method, else undefined.
125
+ */
126
+ handlerFor(method: string, declares: (capability: string) => boolean): RemoteBridgeMethodHandler | undefined;
127
+ }
128
+ /**
129
+ * Compose the published seam over a registry and a fan-out.
130
+ * @param methods - the registry this bridge owns.
131
+ * @param fanout - the hub's broadcast pair.
132
+ * @returns the face a plugin resolves from {@link REMOTE_BRIDGE_SERVICE}.
133
+ */
134
+ export declare function createRemoteBridgeFace(methods: RemoteBridgeRegistry, fanout: RemoteBridgeFanout): RemoteBridgeFace;
135
+ declare module '@deepseek-ai/cordis' {
136
+ interface Context {
137
+ /**
138
+ * The bridge's extension seam, while this package serves protocol v1. A
139
+ * plugin resolves it structurally at use time: requiring it would let the
140
+ * bridge's absence take the registering plugin's start down with it.
141
+ */
142
+ remoteBridge: RemoteBridgeFace;
143
+ }
144
+ }