@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.7

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 (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +243 -2
  4. package/README.zh.md +244 -0
  5. package/cordis.patch.yml +17 -0
  6. package/lib/client.js +1830 -0
  7. package/lib/client.js.map +1 -0
  8. package/lib/index.js +3744 -0
  9. package/lib/types/client/PairEntry.d.ts +16 -0
  10. package/lib/types/client/PairPanel.d.ts +55 -0
  11. package/lib/types/client/icons.d.ts +18 -0
  12. package/lib/types/client/index.d.ts +35 -0
  13. package/lib/types/client/locales.d.ts +42 -0
  14. package/lib/types/client/pair-token.d.ts +73 -0
  15. package/lib/types/client/semantic.d.ts +28 -0
  16. package/lib/types/core/approvals.d.ts +75 -0
  17. package/lib/types/core/connection.d.ts +119 -0
  18. package/lib/types/core/crypto.d.ts +48 -0
  19. package/lib/types/core/devices.d.ts +72 -0
  20. package/lib/types/core/dsh-frames.d.ts +181 -0
  21. package/lib/types/core/envelope.d.ts +98 -0
  22. package/lib/types/core/gateway-errors.d.ts +49 -0
  23. package/lib/types/core/hub.d.ts +101 -0
  24. package/lib/types/core/loopback.d.ts +35 -0
  25. package/lib/types/core/owner-peer.d.ts +49 -0
  26. package/lib/types/core/pairing.d.ts +61 -0
  27. package/lib/types/core/protocol.d.ts +89 -0
  28. package/lib/types/core/questions.d.ts +246 -0
  29. package/lib/types/core/session-meta.d.ts +105 -0
  30. package/lib/types/core/session-permissions.d.ts +134 -0
  31. package/lib/types/core/wire.d.ts +115 -0
  32. package/lib/types/core/ws-frames.d.ts +61 -0
  33. package/lib/types/host/dsh-home.d.ts +16 -0
  34. package/lib/types/host/pair-origin.d.ts +44 -0
  35. package/lib/types/host/routes.d.ts +27 -0
  36. package/lib/types/host/websocket.d.ts +104 -0
  37. package/lib/types/index.d.ts +40 -0
  38. package/package.json +87 -3
  39. package/src/client/PairEntry.tsx +151 -0
  40. package/src/client/PairPanel.tsx +183 -0
  41. package/src/client/icons.tsx +72 -0
  42. package/src/client/index.ts +81 -0
  43. package/src/client/locales.ts +72 -0
  44. package/src/client/pair-token.ts +104 -0
  45. package/src/client/panel.module.css +344 -0
  46. package/src/client/semantic.ts +37 -0
  47. package/src/core/approvals.ts +142 -0
  48. package/src/core/connection.ts +1090 -0
  49. package/src/core/crypto.ts +113 -0
  50. package/src/core/devices.ts +209 -0
  51. package/src/core/dsh-frames.ts +486 -0
  52. package/src/core/envelope.ts +173 -0
  53. package/src/core/gateway-errors.ts +92 -0
  54. package/src/core/hub.ts +238 -0
  55. package/src/core/loopback.ts +60 -0
  56. package/src/core/owner-peer.ts +70 -0
  57. package/src/core/pairing.ts +113 -0
  58. package/src/core/protocol.ts +120 -0
  59. package/src/core/questions.ts +454 -0
  60. package/src/core/session-meta.ts +176 -0
  61. package/src/core/session-permissions.ts +266 -0
  62. package/src/core/wire.ts +155 -0
  63. package/src/core/ws-frames.ts +125 -0
  64. package/src/css-modules.d.ts +6 -0
  65. package/src/host/dsh-home.ts +42 -0
  66. package/src/host/pair-origin.ts +77 -0
  67. package/src/host/routes.ts +85 -0
  68. package/src/host/websocket.ts +325 -0
  69. package/src/index.ts +205 -0
@@ -0,0 +1,486 @@
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
+
12
+ /** One image a durable `user/message` carried, as far as a client renders it. */
13
+ export interface UserMessageAttachment {
14
+ readonly attachmentId: string
15
+ readonly mediaType: string
16
+ readonly name?: string
17
+ }
18
+
19
+ /** Token usage one finished `assistant/message` reported, passed through unconverted. */
20
+ export interface MessageUsage {
21
+ readonly inputTokens: number
22
+ readonly outputTokens: number
23
+ readonly totalTokens?: number
24
+ readonly cacheReadTokens?: number
25
+ readonly cacheWriteTokens?: number
26
+ readonly reasoningTokens?: number
27
+ }
28
+
29
+ /** One protocol v1 delta, before the session id and event sequence are attached. */
30
+ export type SessionDelta =
31
+ | { readonly kind: 'text'; readonly text: string; readonly blockIndex: number }
32
+ | { readonly kind: 'reasoning'; readonly text: string; readonly blockIndex: number }
33
+ | { readonly kind: 'tool-call'; readonly callId: string; readonly name: string; readonly argumentsDelta: string }
34
+ | { readonly kind: 'tool-result'; readonly callId: string; readonly output: string; readonly isError: boolean }
35
+ | { readonly kind: 'turn-end'; readonly reason: string }
36
+ | { readonly kind: 'user-message'; readonly text: string; readonly messageId?: string; readonly attachments?: readonly UserMessageAttachment[] }
37
+ | { readonly kind: 'usage'; readonly usage: MessageUsage; readonly turn?: number; readonly step?: number }
38
+
39
+ /** Highest number of tool calls one connection remembers by id. */
40
+ export const TOOL_CALL_MEMORY = 512
41
+ /** Highest number of published user messages one connection remembers by id. */
42
+ export const USER_MESSAGE_MEMORY = 512
43
+
44
+ /**
45
+ * The durable entry types a protocol v1 client renders — `user/message`,
46
+ * `assistant/message`, `tool/call` and `tool/result`. Everything else in a
47
+ * turn's entries is the harness's own bookkeeping, which the client can only
48
+ * count as unknown, so a client that asks for a trimmed baseline is not sent it.
49
+ */
50
+ export const RENDERED_ENTRY_TYPES: ReadonlySet<string> = new Set([
51
+ 'user/message',
52
+ 'assistant/message',
53
+ 'tool/call',
54
+ 'tool/result',
55
+ ])
56
+
57
+ /** One raw durable event inside a snapshot turn. */
58
+ export interface SnapshotEntry {
59
+ readonly seq: number
60
+ readonly time: number
61
+ readonly type: string
62
+ readonly data: unknown
63
+ }
64
+
65
+ /** One turn of a session snapshot: the durable events from `turn/start` to `turn/end`. */
66
+ export interface SnapshotTurn {
67
+ /** Seq of the `turn/start` event, or 0 for the lead-in before the first turn. */
68
+ readonly seq: number
69
+ readonly time: number
70
+ /** Seq of the `turn/end` event, or 0 while the turn is still open. */
71
+ readonly endSeq: number
72
+ readonly endTime: number
73
+ /** `turn/end` reason kind, or the empty string while the turn is open. */
74
+ readonly reason: string
75
+ readonly entries: readonly SnapshotEntry[]
76
+ }
77
+
78
+ /** The opening frame of a `session/follow` stream. */
79
+ export interface FollowBaseline {
80
+ readonly cursor: number
81
+ readonly records: readonly unknown[]
82
+ readonly hasMore: boolean
83
+ }
84
+
85
+ function isRecord(value: unknown): value is Record<string, unknown> {
86
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
87
+ }
88
+
89
+ function stringField(value: unknown, key: string): string | undefined {
90
+ if (!isRecord(value)) return undefined
91
+ const field = value[key]
92
+ return typeof field === 'string' ? field : undefined
93
+ }
94
+
95
+ /**
96
+ * Remembers which tool calls have already streamed their arguments, so the
97
+ * durable `tool/call` event that follows the stream is not replayed as a second
98
+ * copy of the same arguments. Bounded: a long-lived connection must not grow
99
+ * with every call it ever saw.
100
+ */
101
+ export class ToolCallIndex {
102
+ readonly #names = new Map<string, string>()
103
+
104
+ /** @returns whether this call already contributed a delta. */
105
+ has(callId: string): boolean {
106
+ return this.#names.has(callId)
107
+ }
108
+
109
+ /** @returns the last name seen for this call, if any. */
110
+ nameOf(callId: string): string | undefined {
111
+ return this.#names.get(callId)
112
+ }
113
+
114
+ /** Remember one call, evicting the oldest entry past {@link TOOL_CALL_MEMORY}. */
115
+ remember(callId: string, name: string): void {
116
+ if (name !== '') this.#names.set(callId, name)
117
+ else if (!this.#names.has(callId)) this.#names.set(callId, '')
118
+ while (this.#names.size > TOOL_CALL_MEMORY) {
119
+ const oldest = this.#names.keys().next()
120
+ if (oldest.done === true) break
121
+ this.#names.delete(oldest.value)
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Remembers which durable user messages this connection already published.
128
+ *
129
+ * A client only ever appends a transcript, so one durable `user/message` must
130
+ * reach the wire once: a replayed event would draw the same prompt a second
131
+ * time. Bounded for the same reason {@link ToolCallIndex} is — a long-lived
132
+ * connection must not grow with every message it ever saw.
133
+ */
134
+ export class MessageIndex {
135
+ readonly #ids = new Set<string>()
136
+
137
+ /** @returns whether this message already contributed a delta. */
138
+ has(id: string): boolean {
139
+ return this.#ids.has(id)
140
+ }
141
+
142
+ /** Remember one message, evicting the oldest entry past {@link USER_MESSAGE_MEMORY}. */
143
+ remember(id: string): void {
144
+ this.#ids.add(id)
145
+ while (this.#ids.size > USER_MESSAGE_MEMORY) {
146
+ const oldest = this.#ids.values().next()
147
+ if (oldest.done === true) break
148
+ this.#ids.delete(oldest.value)
149
+ }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Read the opening frame of a follow stream.
155
+ * @returns the cursor and records, or undefined when this frame is not a snapshot.
156
+ */
157
+ export function readFollowBaseline(frame: unknown): FollowBaseline | undefined {
158
+ if (!isRecord(frame) || frame.type !== 'snapshot') return undefined
159
+ const cursor = frame.cursor
160
+ const records = frame.records
161
+ if (typeof cursor !== 'number' || !Array.isArray(records)) return undefined
162
+ return { cursor, records, hasMore: frame.hasMore === true }
163
+ }
164
+
165
+ /**
166
+ * Map one DSH follow frame to a delta, or undefined when the frame carries no
167
+ * increment this protocol publishes.
168
+ * @param frame - one `SessionFollowFrame`.
169
+ * @param toolCalls - this connection's tool-call memory.
170
+ * @param messages - this connection's published-user-message memory.
171
+ */
172
+ export function deltaOfFollowFrame(frame: unknown, toolCalls: ToolCallIndex, messages: MessageIndex): SessionDelta | undefined {
173
+ if (!isRecord(frame)) return undefined
174
+ if (frame.type === 'assistant-stream') return deltaOfAssistantStream(frame.frame, toolCalls)
175
+ if (frame.type !== 'event') return undefined
176
+ const event = frame.event
177
+ if (!isRecord(event)) return undefined
178
+ const type = event.type
179
+ const data = event.data
180
+ if (type === 'tool/result') return toolResultDelta(data)
181
+ if (type === 'turn/end') return turnEndDelta(data)
182
+ if (type === 'tool/call') return assembledToolCallDelta(data, toolCalls)
183
+ if (type === 'user/message') return userMessageDelta(data, messages)
184
+ if (type === 'assistant/message') return usageDelta(data)
185
+ return undefined
186
+ }
187
+
188
+ function deltaOfAssistantStream(frame: unknown, toolCalls: ToolCallIndex): SessionDelta | undefined {
189
+ if (!isRecord(frame) || frame.type !== 'chunk') return undefined
190
+ const chunk = frame.chunk
191
+ if (!isRecord(chunk)) return undefined
192
+ const index = typeof chunk.index === 'number' ? chunk.index : 0
193
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
194
+ return { kind: 'text', text: chunk.text, blockIndex: index }
195
+ }
196
+ if (chunk.type === 'reasoning-delta' && typeof chunk.text === 'string') {
197
+ return { kind: 'reasoning', text: chunk.text, blockIndex: index }
198
+ }
199
+ if (chunk.type === 'tool-call-delta' && typeof chunk.id === 'string' && chunk.id !== '') {
200
+ const callId = chunk.id
201
+ const announced = typeof chunk.name === 'string' && chunk.name !== '' ? chunk.name : undefined
202
+ const name = announced ?? toolCalls.nameOf(callId) ?? ''
203
+ toolCalls.remember(callId, name)
204
+ return { kind: 'tool-call', callId, name, argumentsDelta: typeof chunk.argumentsDelta === 'string' ? chunk.argumentsDelta : '' }
205
+ }
206
+ return undefined
207
+ }
208
+
209
+ function toolResultDelta(data: unknown): SessionDelta | undefined {
210
+ const message = isRecord(data) ? data.message : undefined
211
+ if (!isRecord(message)) return undefined
212
+ const callId = message.toolCallId
213
+ if (typeof callId !== 'string' || callId === '') return undefined
214
+ return { kind: 'tool-result', callId, output: textOfBlocks(message.content), isError: message.isError === true }
215
+ }
216
+
217
+ function turnEndDelta(data: unknown): SessionDelta | undefined {
218
+ const reason = isRecord(data) ? data.reason : undefined
219
+ const kind = isRecord(reason) ? reason.kind : undefined
220
+ // An unreadable reason is reported as such: the client treats every non-
221
+ // `completed` value as an abnormal end, and `unknown` is the truth here.
222
+ return { kind: 'turn-end', reason: typeof kind === 'string' ? kind : 'unknown' }
223
+ }
224
+
225
+ /**
226
+ * The durable `tool/call` event carries the WHOLE argument string, not an
227
+ * increment, so it is published as a delta only when the connection never saw
228
+ * this call's increments — otherwise the client would append the arguments a
229
+ * second time.
230
+ */
231
+ function assembledToolCallDelta(data: unknown, toolCalls: ToolCallIndex): SessionDelta | undefined {
232
+ const callId = stringField(data, 'callId')
233
+ if (callId === undefined || callId === '') return undefined
234
+ if (toolCalls.has(callId)) return undefined
235
+ const name = stringField(data, 'name') ?? ''
236
+ toolCalls.remember(callId, name)
237
+ return { kind: 'tool-call', callId, name, argumentsDelta: stringField(data, 'arguments') ?? '' }
238
+ }
239
+
240
+ /** Flatten a message's model-facing blocks to display text; non-text blocks are dropped. */
241
+ function textOfBlocks(content: unknown): string {
242
+ if (!Array.isArray(content)) return ''
243
+ const parts: string[] = []
244
+ for (const block of content) {
245
+ if (!isRecord(block)) continue
246
+ if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
247
+ }
248
+ return parts.join('\n')
249
+ }
250
+
251
+ /**
252
+ * Map one durable `user/message` to the increment that shows it on a subscribed
253
+ * phone, so a prompt typed on the desktop appears without a baseline reload.
254
+ *
255
+ * Published once per message id: a replayed event must not draw the message a
256
+ * second time. The text is the message's text blocks and nothing else — image
257
+ * and file blocks travel in `attachments`, never inside it.
258
+ */
259
+ function userMessageDelta(data: unknown, messages: MessageIndex): SessionDelta | undefined {
260
+ if (!isRecord(data)) return undefined
261
+ const messageId = stringField(data, 'id')
262
+ if (messageId !== undefined) {
263
+ if (messages.has(messageId)) return undefined
264
+ messages.remember(messageId)
265
+ }
266
+ const attachments = imageAttachmentsOf(data.content)
267
+ return {
268
+ kind: 'user-message',
269
+ text: textOfBlocks(data.content),
270
+ ...(messageId === undefined ? {} : { messageId }),
271
+ ...(attachments.length === 0 ? {} : { attachments }),
272
+ }
273
+ }
274
+
275
+ /**
276
+ * The image references of one message's blocks, in content order.
277
+ *
278
+ * A durable image block nests its immutable reference under the block's own
279
+ * `attachment` key, so the id and media type are read from the reference — the
280
+ * block itself carries only its type and, once offloaded, that flag.
281
+ */
282
+ function imageAttachmentsOf(content: unknown): UserMessageAttachment[] {
283
+ if (!Array.isArray(content)) return []
284
+ const attachments: UserMessageAttachment[] = []
285
+ for (const block of content) {
286
+ if (!isRecord(block) || block.type !== 'image') continue
287
+ const ref = block.attachment
288
+ if (!isRecord(ref)) continue
289
+ const attachmentId = stringField(ref, 'attachmentId')
290
+ const mediaType = stringField(ref, 'mediaType')
291
+ if (attachmentId === undefined || mediaType === undefined) continue
292
+ const name = stringField(ref, 'name')
293
+ attachments.push({ attachmentId, mediaType, ...(name === undefined || name === '' ? {} : { name }) })
294
+ }
295
+ return attachments
296
+ }
297
+
298
+ /**
299
+ * Map one finished `assistant/message` to its usage increment, or to nothing.
300
+ *
301
+ * An event without `usage` publishes NO delta: absent is not zero, and a client
302
+ * must never record a token count the harness did not report.
303
+ */
304
+ function usageDelta(data: unknown): SessionDelta | undefined {
305
+ if (!isRecord(data)) return undefined
306
+ const usage = usageOf(data.usage)
307
+ if (usage === undefined) return undefined
308
+ const turn = numberOf(data.turn)
309
+ const step = numberOf(data.step)
310
+ return { kind: 'usage', usage, ...(turn === undefined ? {} : { turn }), ...(step === undefined ? {} : { step }) }
311
+ }
312
+
313
+ /** Read one `TokenUsage` verbatim; undefined when its two mandatory counters are not numbers. */
314
+ function usageOf(value: unknown): MessageUsage | undefined {
315
+ if (!isRecord(value)) return undefined
316
+ const inputTokens = numberOf(value.inputTokens)
317
+ const outputTokens = numberOf(value.outputTokens)
318
+ if (inputTokens === undefined || outputTokens === undefined) return undefined
319
+ const totalTokens = numberOf(value.totalTokens)
320
+ const cacheReadTokens = numberOf(value.cacheReadTokens)
321
+ const cacheWriteTokens = numberOf(value.cacheWriteTokens)
322
+ const reasoningTokens = numberOf(value.reasoningTokens)
323
+ return {
324
+ inputTokens,
325
+ outputTokens,
326
+ ...(totalTokens === undefined ? {} : { totalTokens }),
327
+ ...(cacheReadTokens === undefined ? {} : { cacheReadTokens }),
328
+ ...(cacheWriteTokens === undefined ? {} : { cacheWriteTokens }),
329
+ ...(reasoningTokens === undefined ? {} : { reasoningTokens }),
330
+ }
331
+ }
332
+
333
+ /** @returns a finite number field, or undefined. */
334
+ function numberOf(value: unknown): number | undefined {
335
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
336
+ }
337
+
338
+ /**
339
+ * Project a follow baseline's records into turns.
340
+ * @param records - the baseline's durable records, oldest first.
341
+ * @returns one turn per `turn/start`, plus a lead-in turn when records precede the first one.
342
+ */
343
+ export function turnsOfRecords(records: readonly unknown[]): SnapshotTurn[] {
344
+ const turns: SnapshotTurn[] = []
345
+ let current: { seq: number; time: number; endSeq: number; endTime: number; reason: string; entries: SnapshotEntry[] } | undefined
346
+ for (const record of records) {
347
+ const entry = snapshotEntryOf(record)
348
+ if (entry === undefined) continue
349
+ if (entry.type === 'turn/start' && current !== undefined && current.endSeq === 0) {
350
+ // A previous turn never ended (an aborted resume): its tail stays with it.
351
+ turns.push(current)
352
+ current = undefined
353
+ }
354
+ if (current === undefined) {
355
+ current = { seq: entry.type === 'turn/start' ? entry.seq : 0, time: entry.time, endSeq: 0, endTime: 0, reason: '', entries: [] }
356
+ }
357
+ current.entries.push(entry)
358
+ if (entry.type === 'turn/end') {
359
+ current.endSeq = entry.seq
360
+ current.endTime = entry.time
361
+ current.reason = isRecord(entry.data) && isRecord(entry.data.reason) && typeof entry.data.reason.kind === 'string'
362
+ ? entry.data.reason.kind
363
+ : 'unknown'
364
+ turns.push(current)
365
+ current = undefined
366
+ }
367
+ }
368
+ if (current !== undefined && current.entries.length > 0) turns.push(current)
369
+ return turns
370
+ }
371
+
372
+ /**
373
+ * Drop the entries of each turn that a protocol v1 client would not render.
374
+ *
375
+ * Only the inside of a turn changes: which turns survive, their order, their
376
+ * `seq`/`endSeq` metadata and every kept entry's `type` and `data` are the
377
+ * projection's own output. A turn whose entries are all unrenderable stays as a
378
+ * turn with an empty `entries` array, so the client never sees a shape it does
379
+ * not know how to read.
380
+ * @param turns - the projection of a follow baseline, in order.
381
+ * @returns the same turns, each carrying only its rendered entries.
382
+ */
383
+ export function trimUnrenderedEntries(turns: readonly SnapshotTurn[]): SnapshotTurn[] {
384
+ return turns.map(turn => {
385
+ const entries = turn.entries.filter(entry => RENDERED_ENTRY_TYPES.has(entry.type))
386
+ return entries.length === turn.entries.length ? turn : { ...turn, entries }
387
+ })
388
+ }
389
+
390
+ /** One contiguous backwards page of a snapshot projection. */
391
+ export interface SnapshotPage {
392
+ /** The turns this page carries, oldest first; each keeps its own turn-level fields. */
393
+ readonly turns: SnapshotTurn[]
394
+ /** Durable seq of this page's oldest entry: the cursor for the next, older page. */
395
+ readonly nextBefore?: number
396
+ readonly hasMore: boolean
397
+ }
398
+
399
+ /**
400
+ * Slice one backwards page out of a projection, BY ENTRY rather than by turn.
401
+ *
402
+ * `before` is a durable watermark, not an index: the page carries the newest
403
+ * entries whose `seq` is strictly below it, so a cursor stays meaningful across
404
+ * connections and a projection that changed shape under it (a trimmed entry
405
+ * that never reaches the client) cannot make a page skip or repeat data. The
406
+ * turn list is rebuilt around exactly the entries in the page, each turn
407
+ * keeping its own `seq`/`endSeq`/`reason`, so a turn may be split across pages.
408
+ *
409
+ * A single entry that exceeds the budget on its own is a page of its own: the
410
+ * size rule never removes an entry, it only ends the page.
411
+ * @param turns - the projection to page, in order.
412
+ * @param before - exclusive durable watermark, or undefined for the newest page.
413
+ * @param maxBytes - byte budget of the encoded page.
414
+ * @param measure - exact encoded size of one page shape, owned by the caller.
415
+ */
416
+ export function pageTurns(
417
+ turns: readonly SnapshotTurn[],
418
+ before: number | undefined,
419
+ maxBytes: number,
420
+ measure: (turns: readonly SnapshotTurn[], nextBefore: number | undefined, hasMore: boolean) => number,
421
+ ): SnapshotPage {
422
+ const flat: { readonly turn: SnapshotTurn; readonly entry: SnapshotEntry }[] = []
423
+ for (const turn of turns) {
424
+ for (const entry of turn.entries) {
425
+ if (before === undefined || entry.seq < before) flat.push({ turn, entry })
426
+ }
427
+ }
428
+ if (flat.length === 0) return { turns: [], hasMore: false }
429
+
430
+ const shells = new Map<SnapshotTurn, number>()
431
+ for (const item of flat) {
432
+ if (!shells.has(item.turn)) shells.set(item.turn, Buffer.byteLength(JSON.stringify({ ...item.turn, entries: [] }), 'utf8'))
433
+ }
434
+ // Greedy from the newest entry on a conservative running estimate — every
435
+ // entry and every contributing turn shell counted once — and then verified
436
+ // against the real encoding, shrinking from the oldest side until it fits.
437
+ let start = flat.length
438
+ let estimate = 0
439
+ const counted = new Set<SnapshotTurn>()
440
+ for (let index = flat.length - 1; index >= 0; index -= 1) {
441
+ const item = flat[index]
442
+ if (item === undefined) break
443
+ let cost = Buffer.byteLength(JSON.stringify(item.entry), 'utf8') + 1
444
+ if (!counted.has(item.turn)) {
445
+ counted.add(item.turn)
446
+ cost += shells.get(item.turn) ?? 0
447
+ }
448
+ if (start < flat.length && estimate + cost > maxBytes) break
449
+ estimate += cost
450
+ start = index
451
+ }
452
+ for (;;) {
453
+ const oldest = flat[start]?.entry.seq
454
+ if (oldest === undefined) return { turns: [], hasMore: false }
455
+ const page = groupEntries(flat.slice(start))
456
+ const hasMore = start > 0
457
+ if (flat.length - start === 1 || measure(page, hasMore ? oldest : undefined, hasMore) <= maxBytes) {
458
+ return hasMore ? { turns: page, nextBefore: oldest, hasMore } : { turns: page, hasMore }
459
+ }
460
+ start += 1
461
+ }
462
+ }
463
+
464
+ /** Rebuild the turn list around one contiguous run of entries. */
465
+ function groupEntries(items: readonly { readonly turn: SnapshotTurn; readonly entry: SnapshotEntry }[]): SnapshotTurn[] {
466
+ const page: SnapshotTurn[] = []
467
+ let current: SnapshotTurn | undefined
468
+ let entries: SnapshotEntry[] = []
469
+ for (const item of items) {
470
+ if (current !== item.turn) {
471
+ if (current !== undefined) page.push({ ...current, entries })
472
+ current = item.turn
473
+ entries = []
474
+ }
475
+ entries.push(item.entry)
476
+ }
477
+ if (current !== undefined) page.push({ ...current, entries })
478
+ return page
479
+ }
480
+
481
+ function snapshotEntryOf(record: unknown): SnapshotEntry | undefined {
482
+ const event = isRecord(record) ? record.event : undefined
483
+ if (!isRecord(event)) return undefined
484
+ if (typeof event.type !== 'string' || typeof event.seq !== 'number') return undefined
485
+ return { seq: event.seq, time: typeof event.time === 'number' ? event.time : 0, type: event.type, data: event.data }
486
+ }
@@ -0,0 +1,173 @@
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
+
23
+ /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
24
+ export const MAX_FRAME_BYTES = 10 * 1024 * 1024
25
+
26
+ /** Reserved response id for a frame whose own id could not be recovered. */
27
+ export const UNIDENTIFIED_FRAME_ID = 0
28
+
29
+ export interface ReqFrame {
30
+ readonly t: 'req'
31
+ readonly id: number
32
+ readonly m: string
33
+ readonly p: Readonly<Record<string, unknown>>
34
+ }
35
+
36
+ export interface PingFrame {
37
+ readonly t: 'ping'
38
+ readonly ts: number
39
+ }
40
+
41
+ export interface PongFrame {
42
+ readonly t: 'pong'
43
+ readonly ts: number
44
+ }
45
+
46
+ /** Every frame a client may legitimately send. */
47
+ export type ClientFrame = ReqFrame | PingFrame | PongFrame
48
+
49
+ export interface ResFrame {
50
+ readonly t: 'res'
51
+ readonly id: number
52
+ readonly ok: boolean
53
+ readonly r?: unknown
54
+ readonly e?: { readonly code: string; 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
+
64
+ export type ServerFrame = ResFrame | EvFrame | PingFrame | PongFrame
65
+
66
+ /** One refusal the decoder can state about the bytes it was handed. */
67
+ export interface FrameFailure {
68
+ readonly ok: false
69
+ /** Response id to answer on: the recovered request id, else {@link UNIDENTIFIED_FRAME_ID}. */
70
+ readonly id: number
71
+ readonly code: string
72
+ readonly msg: string
73
+ }
74
+
75
+ export type DecodeOutcome = { readonly ok: true; readonly frame: ClientFrame } | FrameFailure
76
+
77
+ /** Failure codes the codec itself raises. */
78
+ export const FRAME_TOO_LARGE = 'frame-too-large'
79
+ export const MALFORMED_FRAME = 'malformed'
80
+ export const DIRECTION_VIOLATION = 'direction-violation'
81
+
82
+ function isRecord(value: unknown): value is Record<string, unknown> {
83
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
84
+ }
85
+
86
+ /** An envelope id is a non-negative safe integer. */
87
+ function isFrameId(value: unknown): value is number {
88
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
89
+ }
90
+
91
+ /**
92
+ * Decode one received text frame.
93
+ * @param text - the frame body exactly as it crossed the wire.
94
+ * @returns the frame, or the refusal to answer with.
95
+ */
96
+ export function decodeClientFrame(text: string): DecodeOutcome {
97
+ if (Buffer.byteLength(text, 'utf8') > MAX_FRAME_BYTES) {
98
+ return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: FRAME_TOO_LARGE, msg: `frame exceeds ${MAX_FRAME_BYTES} bytes` }
99
+ }
100
+ let parsed: unknown
101
+ try {
102
+ parsed = JSON.parse(text)
103
+ } catch {
104
+ return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: 'frame is not JSON' }
105
+ }
106
+ if (!isRecord(parsed)) {
107
+ return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: 'frame is not a JSON object' }
108
+ }
109
+ const kind = parsed.t
110
+ if (kind === 'ping' || kind === 'pong') {
111
+ if (typeof parsed.ts !== 'number' || !Number.isFinite(parsed.ts)) {
112
+ return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: `${kind} requires a numeric ts` }
113
+ }
114
+ return { ok: true, frame: { t: kind, ts: parsed.ts } }
115
+ }
116
+ if (kind === 'res' || kind === 'ev') {
117
+ return {
118
+ ok: false,
119
+ id: isFrameId(parsed.id) ? parsed.id : UNIDENTIFIED_FRAME_ID,
120
+ code: DIRECTION_VIOLATION,
121
+ msg: `a client must not send a ${kind} frame`,
122
+ }
123
+ }
124
+ if (kind !== 'req') {
125
+ return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: 'frame has no known t discriminator' }
126
+ }
127
+ if (!isFrameId(parsed.id)) {
128
+ return { ok: false, id: UNIDENTIFIED_FRAME_ID, code: MALFORMED_FRAME, msg: 'req requires a non-negative integer id' }
129
+ }
130
+ if (typeof parsed.m !== 'string' || parsed.m === '') {
131
+ return { ok: false, id: parsed.id, code: MALFORMED_FRAME, msg: 'req requires a method name' }
132
+ }
133
+ if (parsed.p !== undefined && !isRecord(parsed.p)) {
134
+ return { ok: false, id: parsed.id, code: MALFORMED_FRAME, msg: 'req payload must be a JSON object' }
135
+ }
136
+ return { ok: true, frame: { t: 'req', id: parsed.id, m: parsed.m, p: parsed.p ?? {} } }
137
+ }
138
+
139
+ /** Encode one outgoing frame. */
140
+ export function encodeFrame(frame: ServerFrame): string {
141
+ return JSON.stringify(frame)
142
+ }
143
+
144
+ /** One successful response frame. */
145
+ export function responseFrame(id: number, result: unknown): ResFrame {
146
+ return { t: 'res', id, ok: true, r: result }
147
+ }
148
+
149
+ /** One failed response frame. */
150
+ export function errorFrame(id: number, code: string, msg: string): ResFrame {
151
+ return { t: 'res', id, ok: false, e: { code, msg } }
152
+ }
153
+
154
+ /**
155
+ * Per-connection event sequence. The frozen design gives each connection its
156
+ * own counter starting at 1; it is deliberately NOT the DSH session cursor
157
+ * (§3.4), so the two numbers are never compared.
158
+ */
159
+ export class EventSequence {
160
+ #next = 1
161
+
162
+ /** @returns the next sequence number, advancing the counter. */
163
+ take(): number {
164
+ const value = this.#next
165
+ this.#next += 1
166
+ return value
167
+ }
168
+
169
+ /** @returns the value {@link take} will return next, without advancing. */
170
+ peek(): number {
171
+ return this.#next
172
+ }
173
+ }