@linxin666/dsh-remote-bridge 0.0.0-stage → 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.
Files changed (81) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +277 -2
  4. package/README.zh.md +276 -0
  5. package/cordis.patch.yml +17 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +1830 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +5789 -0
  10. package/lib/types/client/PairEntry.d.ts +16 -0
  11. package/lib/types/client/PairPanel.d.ts +55 -0
  12. package/lib/types/client/icons.d.ts +18 -0
  13. package/lib/types/client/index.d.ts +35 -0
  14. package/lib/types/client/locales.d.ts +42 -0
  15. package/lib/types/client/pair-token.d.ts +73 -0
  16. package/lib/types/client/semantic.d.ts +28 -0
  17. package/lib/types/core/approvals.d.ts +99 -0
  18. package/lib/types/core/connection.d.ts +170 -0
  19. package/lib/types/core/crypto.d.ts +48 -0
  20. package/lib/types/core/delta.d.ts +101 -0
  21. package/lib/types/core/devices.d.ts +72 -0
  22. package/lib/types/core/dsh-frames.d.ts +332 -0
  23. package/lib/types/core/envelope.d.ts +132 -0
  24. package/lib/types/core/extension.d.ts +144 -0
  25. package/lib/types/core/gateway-errors.d.ts +49 -0
  26. package/lib/types/core/hub.d.ts +127 -0
  27. package/lib/types/core/jobs.d.ts +204 -0
  28. package/lib/types/core/loopback.d.ts +35 -0
  29. package/lib/types/core/owner-peer.d.ts +49 -0
  30. package/lib/types/core/pairing.d.ts +61 -0
  31. package/lib/types/core/protocol.d.ts +319 -0
  32. package/lib/types/core/questions.d.ts +294 -0
  33. package/lib/types/core/session-meta.d.ts +105 -0
  34. package/lib/types/core/session-permissions.d.ts +134 -0
  35. package/lib/types/core/wire.d.ts +115 -0
  36. package/lib/types/core/ws-frames.d.ts +72 -0
  37. package/lib/types/host/dsh-home.d.ts +16 -0
  38. package/lib/types/host/pair-origin.d.ts +44 -0
  39. package/lib/types/host/routes.d.ts +27 -0
  40. package/lib/types/host/websocket.d.ts +111 -0
  41. package/lib/types/index.d.ts +55 -0
  42. package/lib/types/mount-once.d.ts +55 -0
  43. package/locale/en.json +6 -0
  44. package/locale/ru.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +93 -3
  47. package/src/client/PairEntry.tsx +151 -0
  48. package/src/client/PairPanel.tsx +183 -0
  49. package/src/client/icons.tsx +72 -0
  50. package/src/client/index.ts +81 -0
  51. package/src/client/locales.ts +72 -0
  52. package/src/client/pair-token.ts +104 -0
  53. package/src/client/panel.module.css +344 -0
  54. package/src/client/semantic.ts +37 -0
  55. package/src/core/approvals.ts +173 -0
  56. package/src/core/connection.ts +1906 -0
  57. package/src/core/crypto.ts +113 -0
  58. package/src/core/delta.ts +204 -0
  59. package/src/core/devices.ts +209 -0
  60. package/src/core/dsh-frames.ts +843 -0
  61. package/src/core/envelope.ts +219 -0
  62. package/src/core/extension.ts +197 -0
  63. package/src/core/gateway-errors.ts +92 -0
  64. package/src/core/hub.ts +310 -0
  65. package/src/core/jobs.ts +372 -0
  66. package/src/core/loopback.ts +60 -0
  67. package/src/core/owner-peer.ts +70 -0
  68. package/src/core/pairing.ts +113 -0
  69. package/src/core/protocol.ts +381 -0
  70. package/src/core/questions.ts +630 -0
  71. package/src/core/session-meta.ts +176 -0
  72. package/src/core/session-permissions.ts +266 -0
  73. package/src/core/wire.ts +159 -0
  74. package/src/core/ws-frames.ts +139 -0
  75. package/src/css-modules.d.ts +6 -0
  76. package/src/host/dsh-home.ts +42 -0
  77. package/src/host/pair-origin.ts +77 -0
  78. package/src/host/routes.ts +85 -0
  79. package/src/host/websocket.ts +359 -0
  80. package/src/index.ts +257 -0
  81. package/src/mount-once.ts +142 -0
@@ -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
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The paired-device roster: `$DSH_HOME/remote-bridge/devices.json`.
3
+ *
4
+ * What is stored is deliberately not a credential. Each row keeps the device's
5
+ * public key, its fingerprint, and the SHA-256 of the bearer token it was
6
+ * issued — never the token itself, so a leaked roster file grants nothing. The
7
+ * directory is 0700 and the file 0600, written through a temporary file plus
8
+ * rename, and a file that cannot be parsed is moved aside instead of being
9
+ * silently treated as an empty roster (which would quietly un-pair every phone
10
+ * and then overwrite the evidence on the next write).
11
+ * @module dsh-remote-bridge/core/devices
12
+ */
13
+ /** Entropy of one device bearer token. */
14
+ export declare const DEVICE_TOKEN_BYTES = 32;
15
+ /** Entropy of one device id. */
16
+ export declare const DEVICE_ID_BYTES = 12;
17
+ /** On-disk schema version of the roster file. */
18
+ export declare const ROSTER_VERSION = 1;
19
+ /** One paired device as the bridge keeps it. */
20
+ export interface DeviceRecord {
21
+ readonly deviceId: string;
22
+ /** base64url SPKI of the device's P-256 key. */
23
+ readonly pubKey: string;
24
+ /** SHA-256 hex of the SPKI DER: the human-comparable identity of the device. */
25
+ readonly fingerprint: string;
26
+ readonly createdAt: number;
27
+ readonly lastSeenAt: number;
28
+ }
29
+ /** What one successful enrollment hands back to the caller exactly once. */
30
+ export interface EnrollmentResult {
31
+ readonly deviceId: string;
32
+ /** The bearer token: returned to the enrolling connection and never persisted again. */
33
+ readonly deviceToken: string;
34
+ }
35
+ export interface DeviceRosterOptions {
36
+ /** Absolute path of the roster file. */
37
+ readonly file: string;
38
+ readonly now?: () => number;
39
+ readonly log?: (message: string) => void;
40
+ }
41
+ /**
42
+ * The persisted, revocable device roster.
43
+ *
44
+ * Revocation is a file edit: protocol v1 has no revoke method, so an operator
45
+ * removes the row (or deletes the file) and restarts. The in-memory copy is
46
+ * loaded once per process.
47
+ */
48
+ export declare class DeviceRoster {
49
+ #private;
50
+ constructor(options: DeviceRosterOptions);
51
+ /**
52
+ * Read the roster once. A missing file is an empty roster; an unreadable or
53
+ * malformed one is moved aside and reported, never silently zeroed.
54
+ * @returns when the in-memory roster reflects the file.
55
+ */
56
+ load(): Promise<void>;
57
+ /** @returns every paired device, without the token hash. */
58
+ devices(): readonly DeviceRecord[];
59
+ /**
60
+ * Resolve a bearer token to its device.
61
+ * @returns the device, or undefined when the token is unknown.
62
+ */
63
+ authenticate(token: string): DeviceRecord | undefined;
64
+ /**
65
+ * Admit one device for a public key it has already proven possession of.
66
+ * @param pubKey - base64url SPKI of the device's P-256 key.
67
+ * @returns the enrollment, or undefined when the key is not an acceptable P-256 SPKI.
68
+ */
69
+ enroll(pubKey: string): Promise<EnrollmentResult | undefined>;
70
+ /** Record that a device just reconnected; the file is refreshed at most once per call. */
71
+ touch(deviceId: string): Promise<void>;
72
+ }
@@ -0,0 +1,332 @@
1
+ /**
2
+ * DSH session frames to protocol v1 `session.delta` payloads, plus the reverse
3
+ * projection of a follow baseline into `session.snapshot` turns.
4
+ *
5
+ * Only frame SHAPES are read here, never DSH classes: the frame argument is
6
+ * `unknown` and every field is narrowed structurally, so a cohort that adds a
7
+ * field to a chunk cannot break the bridge and a cohort that renames one fails
8
+ * loudly at the mapping instead of emitting a half-filled delta.
9
+ * @module dsh-remote-bridge/core/dsh-frames
10
+ */
11
+ /** One image a durable `user/message` carried, as far as a client renders it. */
12
+ export interface UserMessageAttachment {
13
+ readonly attachmentId: string;
14
+ readonly mediaType: string;
15
+ readonly name?: string;
16
+ }
17
+ /** Token usage one finished `assistant/message` reported, passed through unconverted. */
18
+ export interface MessageUsage {
19
+ readonly inputTokens: number;
20
+ readonly outputTokens: number;
21
+ readonly totalTokens?: number;
22
+ readonly cacheReadTokens?: number;
23
+ readonly cacheWriteTokens?: number;
24
+ readonly reasoningTokens?: number;
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
+ }
44
+ /** One protocol v1 delta, before the session id and event sequence are attached. */
45
+ export type SessionDelta = {
46
+ readonly kind: 'text';
47
+ readonly text: string;
48
+ readonly blockIndex: number;
49
+ } | {
50
+ readonly kind: 'reasoning';
51
+ readonly text: string;
52
+ readonly blockIndex: number;
53
+ } | {
54
+ readonly kind: 'tool-call';
55
+ readonly callId: string;
56
+ readonly name: string;
57
+ readonly argumentsDelta: string;
58
+ } | {
59
+ readonly kind: 'tool-result';
60
+ readonly callId: string;
61
+ readonly output: string;
62
+ readonly isError: boolean;
63
+ } | {
64
+ readonly kind: 'turn-end';
65
+ readonly reason: string;
66
+ } | {
67
+ readonly kind: 'user-message';
68
+ readonly text: string;
69
+ readonly messageId?: string;
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;
78
+ } | {
79
+ readonly kind: 'usage';
80
+ readonly usage: MessageUsage;
81
+ readonly turn?: number;
82
+ readonly step?: number;
83
+ };
84
+ /** Highest number of tool calls one connection remembers by id. */
85
+ export declare const TOOL_CALL_MEMORY = 512;
86
+ /** Highest number of published user messages one connection remembers by id. */
87
+ export declare const USER_MESSAGE_MEMORY = 512;
88
+ /**
89
+ * The durable entry types a protocol v1 client renders — `user/message`,
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.
100
+ */
101
+ export declare const RENDERED_ENTRY_TYPES: ReadonlySet<string>;
102
+ /** One raw durable event inside a snapshot turn. */
103
+ export interface SnapshotEntry {
104
+ readonly seq: number;
105
+ readonly time: number;
106
+ readonly type: string;
107
+ readonly data: unknown;
108
+ /** Where a `user/message` came from; absent on every other entry type. */
109
+ readonly actor?: MessageActor;
110
+ }
111
+ /** One turn of a session snapshot: the durable events from `turn/start` to `turn/end`. */
112
+ export interface SnapshotTurn {
113
+ /** Seq of the `turn/start` event, or 0 for the lead-in before the first turn. */
114
+ readonly seq: number;
115
+ readonly time: number;
116
+ /** Seq of the `turn/end` event, or 0 while the turn is still open. */
117
+ readonly endSeq: number;
118
+ readonly endTime: number;
119
+ /** `turn/end` reason kind, or the empty string while the turn is open. */
120
+ readonly reason: string;
121
+ readonly entries: readonly SnapshotEntry[];
122
+ }
123
+ /** The opening frame of a `session/follow` stream. */
124
+ export interface FollowBaseline {
125
+ readonly cursor: number;
126
+ readonly records: readonly unknown[];
127
+ readonly hasMore: boolean;
128
+ }
129
+ /**
130
+ * Remembers which tool calls have already streamed their arguments, so the
131
+ * durable `tool/call` event that follows the stream is not replayed as a second
132
+ * copy of the same arguments. Bounded: a long-lived connection must not grow
133
+ * with every call it ever saw.
134
+ */
135
+ export declare class ToolCallIndex {
136
+ #private;
137
+ /** @returns whether this call already contributed a delta. */
138
+ has(callId: string): boolean;
139
+ /** @returns the last name seen for this call, if any. */
140
+ nameOf(callId: string): string | undefined;
141
+ /** Remember one call, evicting the oldest entry past {@link TOOL_CALL_MEMORY}. */
142
+ remember(callId: string, name: string): void;
143
+ }
144
+ /**
145
+ * Remembers which durable user messages this connection already published.
146
+ *
147
+ * A client only ever appends a transcript, so one durable `user/message` must
148
+ * reach the wire once: a replayed event would draw the same prompt a second
149
+ * time. Bounded for the same reason {@link ToolCallIndex} is — a long-lived
150
+ * connection must not grow with every message it ever saw.
151
+ */
152
+ export declare class MessageIndex {
153
+ #private;
154
+ /** @returns whether this message already contributed a delta. */
155
+ has(id: string): boolean;
156
+ /** Remember one message, evicting the oldest entry past {@link USER_MESSAGE_MEMORY}. */
157
+ remember(id: string): void;
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
+ }
236
+ /**
237
+ * Read the opening frame of a follow stream.
238
+ * @returns the cursor and records, or undefined when this frame is not a snapshot.
239
+ */
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
+ }
248
+ /**
249
+ * Map one DSH follow frame to a delta, or undefined when the frame carries no
250
+ * increment this protocol publishes.
251
+ * @param frame - one `SessionFollowFrame`.
252
+ * @param toolCalls - this connection's tool-call memory.
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.
261
+ */
262
+ export declare function actorOfSource(source: unknown): MessageActor | undefined;
263
+ /**
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.
270
+ * @param records - the baseline's durable records, oldest first.
271
+ * @returns one turn per `turn/start`, plus a lead-in turn when records precede the first one.
272
+ */
273
+ export declare function turnsOfRecords(records: readonly unknown[]): SnapshotTurn[];
274
+ /**
275
+ * Drop the entries of each turn that a protocol v1 client would not render.
276
+ *
277
+ * Only the inside of a turn changes: which turns survive, their order, their
278
+ * `seq`/`endSeq` metadata and every kept entry's `type` and `data` are the
279
+ * projection's own output. A turn whose entries are all unrenderable stays as a
280
+ * turn with an empty `entries` array, so the client never sees a shape it does
281
+ * not know how to read.
282
+ * @param turns - the projection of a follow baseline, in order.
283
+ * @returns the same turns, each carrying only its rendered entries.
284
+ */
285
+ export declare function trimUnrenderedEntries(turns: readonly SnapshotTurn[]): SnapshotTurn[];
286
+ /** One contiguous backwards page of a snapshot projection. */
287
+ export interface SnapshotPage {
288
+ /** The turns this page carries, oldest first; each keeps its own turn-level fields. */
289
+ readonly turns: SnapshotTurn[];
290
+ /** Durable seq of this page's oldest entry: the cursor for the next, older page. */
291
+ readonly nextBefore?: number;
292
+ readonly hasMore: boolean;
293
+ }
294
+ /**
295
+ * Slice one backwards page out of a projection, BY ENTRY rather than by turn.
296
+ *
297
+ * `before` is a durable watermark, not an index: the page carries the newest
298
+ * entries whose `seq` is strictly below it, so a cursor stays meaningful across
299
+ * connections and a projection that changed shape under it (a trimmed entry
300
+ * that never reaches the client) cannot make a page skip or repeat data. The
301
+ * turn list is rebuilt around exactly the entries in the page, each turn
302
+ * keeping its own `seq`/`endSeq`/`reason`, so a turn may be split across pages.
303
+ *
304
+ * A single entry that exceeds the budget on its own is a page of its own: the
305
+ * size rule never removes an entry, it only ends the page.
306
+ * @param turns - the projection to page, in order.
307
+ * @param before - exclusive durable watermark, or undefined for the newest page.
308
+ * @param maxBytes - byte budget of the encoded page.
309
+ * @param measure - exact encoded size of one page shape, owned by the caller.
310
+ */
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[];
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Protocol v1 frame envelope: the one JSON-object-per-text-frame codec both
3
+ * ends of the bridge speak. Shapes are frozen by the parent card and are not
4
+ * ours to extend:
5
+ *
6
+ * request {"t":"req","id":<uint>,"m":"<method>","p":{...}}
7
+ * response {"t":"res","id":<uint>,"ok":true,"r":{...}}
8
+ * {"t":"res","id":<uint>,"ok":false,"e":{"code":"<str>","msg":"<str>"}}
9
+ * event {"t":"ev","seq":<uint>,"m":"<topic>","p":{...}}
10
+ * heartbeat {"t":"ping","ts":<ms>} / {"t":"pong","ts":<ms>}
11
+ *
12
+ * Decisions this module owns (not restated by the frozen design):
13
+ * - the 10 MiB cap is measured in UTF-8 bytes of the received text, before
14
+ * parsing, so an oversized frame never allocates a parsed object graph;
15
+ * - direction violations (a `res` or `ev` arriving FROM the client) are their
16
+ * own failure code instead of `malformed`, because "the peer is speaking the
17
+ * wrong half of the protocol" is an actionable diagnostic;
18
+ * - a frame whose identity cannot be recovered is answered with the reserved
19
+ * id 0, since the envelope has no way to decline answering.
20
+ * @module dsh-remote-bridge/core/envelope
21
+ */
22
+ /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
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;
29
+ /** Reserved response id for a frame whose own id could not be recovered. */
30
+ export declare const UNIDENTIFIED_FRAME_ID = 0;
31
+ export interface ReqFrame {
32
+ readonly t: 'req';
33
+ readonly id: number;
34
+ readonly m: string;
35
+ readonly p: Readonly<Record<string, unknown>>;
36
+ }
37
+ export interface PingFrame {
38
+ readonly t: 'ping';
39
+ readonly ts: number;
40
+ }
41
+ export interface PongFrame {
42
+ readonly t: 'pong';
43
+ readonly ts: number;
44
+ }
45
+ /** Every frame a client may legitimately send. */
46
+ export type ClientFrame = ReqFrame | PingFrame | PongFrame;
47
+ export interface ResFrame {
48
+ readonly t: 'res';
49
+ readonly id: number;
50
+ readonly ok: boolean;
51
+ readonly r?: unknown;
52
+ readonly e?: {
53
+ readonly code: string;
54
+ readonly msg: string;
55
+ };
56
+ }
57
+ export interface EvFrame {
58
+ readonly t: 'ev';
59
+ readonly seq: number;
60
+ readonly m: string;
61
+ readonly p: unknown;
62
+ }
63
+ export type ServerFrame = ResFrame | EvFrame | PingFrame | PongFrame;
64
+ /** One refusal the decoder can state about the bytes it was handed. */
65
+ export interface FrameFailure {
66
+ readonly ok: false;
67
+ /** Response id to answer on: the recovered request id, else {@link UNIDENTIFIED_FRAME_ID}. */
68
+ readonly id: number;
69
+ readonly code: string;
70
+ readonly msg: string;
71
+ }
72
+ export type DecodeOutcome = {
73
+ readonly ok: true;
74
+ readonly frame: ClientFrame;
75
+ } | FrameFailure;
76
+ /** Failure codes the codec itself raises. */
77
+ export declare const FRAME_TOO_LARGE = "frame-too-large";
78
+ export declare const MALFORMED_FRAME = "malformed";
79
+ export declare const DIRECTION_VIOLATION = "direction-violation";
80
+ /**
81
+ * Decode one received text frame.
82
+ * @param text - the frame body exactly as it crossed the wire.
83
+ * @returns the frame, or the refusal to answer with.
84
+ */
85
+ export declare function decodeClientFrame(text: string): DecodeOutcome;
86
+ /** Encode one outgoing frame. */
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;
117
+ /** One successful response frame. */
118
+ export declare function responseFrame(id: number, result: unknown): ResFrame;
119
+ /** One failed response frame. */
120
+ export declare function errorFrame(id: number, code: string, msg: string): ResFrame;
121
+ /**
122
+ * Per-connection event sequence. The frozen design gives each connection its
123
+ * own counter starting at 1; it is deliberately NOT the DSH session cursor
124
+ * (§3.4), so the two numbers are never compared.
125
+ */
126
+ export declare class EventSequence {
127
+ #private;
128
+ /** @returns the next sequence number, advancing the counter. */
129
+ take(): number;
130
+ /** @returns the value {@link take} will return next, without advancing. */
131
+ peek(): number;
132
+ }