@robota-sdk/agent-transport 3.0.0-beta.100

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 (93) hide show
  1. package/CHANGELOG.md +1137 -0
  2. package/LICENSE +661 -0
  3. package/README.md +121 -0
  4. package/dist/browser/client.d.ts +2 -0
  5. package/dist/browser/client.js +1 -0
  6. package/dist/browser/index.d.ts +624 -0
  7. package/dist/browser/index.d.ts.map +1 -0
  8. package/dist/browser/index.js +2 -0
  9. package/dist/browser/index.js.map +1 -0
  10. package/dist/browser/observer-messages-4fRQZU2D.d.ts +499 -0
  11. package/dist/browser/observer-messages-4fRQZU2D.d.ts.map +1 -0
  12. package/dist/browser/observer-messages-O8jTPEQO.js +2 -0
  13. package/dist/browser/observer-messages-O8jTPEQO.js.map +1 -0
  14. package/dist/node/index.cjs +1 -0
  15. package/dist/node/index.d.cts +1115 -0
  16. package/dist/node/index.d.cts.map +1 -0
  17. package/dist/node/index.d.ts +1115 -0
  18. package/dist/node/index.d.ts.map +1 -0
  19. package/dist/node/index.js +2 -0
  20. package/dist/node/index.js.map +1 -0
  21. package/dist/node/node.cjs +1 -0
  22. package/dist/node/node.d.cts +317 -0
  23. package/dist/node/node.d.cts.map +1 -0
  24. package/dist/node/node.d.ts +317 -0
  25. package/dist/node/node.d.ts.map +1 -0
  26. package/dist/node/node.js +2 -0
  27. package/dist/node/node.js.map +1 -0
  28. package/package.json +122 -0
  29. package/src/__tests__/__fixtures__/korean-text.json +6 -0
  30. package/src/__tests__/access-token-verifier.test.ts +672 -0
  31. package/src/__tests__/admission.test.ts +130 -0
  32. package/src/__tests__/app-tool-messages.test.ts +463 -0
  33. package/src/__tests__/bearer-resource-gate.test.ts +120 -0
  34. package/src/__tests__/channel-frames.test.ts +215 -0
  35. package/src/__tests__/driver-attribution-capability.test.ts +83 -0
  36. package/src/__tests__/file-transfer.test.ts +281 -0
  37. package/src/__tests__/handoff-chunking.test.ts +261 -0
  38. package/src/__tests__/handoff-manifest.test.ts +52 -0
  39. package/src/__tests__/history-attached-budget.test.ts +216 -0
  40. package/src/__tests__/message-decoders.test.ts +870 -0
  41. package/src/__tests__/outbound-delivery.test.ts +558 -0
  42. package/src/__tests__/peer-message-ledger.test.ts +200 -0
  43. package/src/__tests__/permission-summary.test.ts +18 -0
  44. package/src/__tests__/personal-usage-report.test.ts +193 -0
  45. package/src/__tests__/project-read-messages.test.ts +118 -0
  46. package/src/__tests__/resume-buffer.test.ts +93 -0
  47. package/src/__tests__/session-detail-loop-status.test.ts +169 -0
  48. package/src/__tests__/session-directory-messages.test.ts +322 -0
  49. package/src/__tests__/session-error-classification.test.ts +113 -0
  50. package/src/__tests__/session-event-delivery.test.ts +101 -0
  51. package/src/__tests__/session-history-wire.test.ts +364 -0
  52. package/src/__tests__/session-message-handler-e5.test.ts +99 -0
  53. package/src/__tests__/session-message-handler-observe.test.ts +223 -0
  54. package/src/__tests__/session-message-handler.test.ts +726 -0
  55. package/src/__tests__/session-resume-bridge.test.ts +472 -0
  56. package/src/__tests__/settings-messages.test.ts +193 -0
  57. package/src/__tests__/stdio-carrier.test.ts +85 -0
  58. package/src/__tests__/submit-prompt-shape.test.ts +78 -0
  59. package/src/__tests__/usage-report-carrier.test.ts +98 -0
  60. package/src/__tests__/ws-broadcast-events.test.ts +94 -0
  61. package/src/app-tool-messages.ts +140 -0
  62. package/src/background-messages.ts +169 -0
  63. package/src/channel-frames.ts +182 -0
  64. package/src/client.ts +17 -0
  65. package/src/handoff-chunking.ts +275 -0
  66. package/src/index.ts +135 -0
  67. package/src/loop-control-messages.ts +34 -0
  68. package/src/message-decoders.ts +485 -0
  69. package/src/message-parser.ts +33 -0
  70. package/src/node/access-token-verifier.ts +363 -0
  71. package/src/node/admission.ts +153 -0
  72. package/src/node/bearer-resource-gate.ts +331 -0
  73. package/src/node/file-transfer.ts +530 -0
  74. package/src/node/handoff-manifest.ts +77 -0
  75. package/src/node/index.ts +45 -0
  76. package/src/node/stdio-carrier.ts +59 -0
  77. package/src/observer-messages.ts +47 -0
  78. package/src/open-prompts.ts +76 -0
  79. package/src/outbound-delivery.ts +240 -0
  80. package/src/peer-message-ledger.ts +193 -0
  81. package/src/permission-summary.ts +18 -0
  82. package/src/project-read-messages.ts +74 -0
  83. package/src/protocol-session.ts +56 -0
  84. package/src/resume-buffer.ts +123 -0
  85. package/src/session-directory-messages.ts +162 -0
  86. package/src/session-error-classification.ts +91 -0
  87. package/src/session-events.ts +290 -0
  88. package/src/session-message-handler.ts +413 -0
  89. package/src/session-query-messages.ts +160 -0
  90. package/src/session-resume-bridge.ts +275 -0
  91. package/src/settings-messages.ts +103 -0
  92. package/src/usage-messages.ts +195 -0
  93. package/src/wire-messages.ts +436 -0
@@ -0,0 +1,1115 @@
1
+ import { IToolAppView, IToolExecutionResult, TToolArgs, TToolParameters, TUniversalMessagePart } from "@robota-sdk/agent-core";
2
+ import { IPersonalUsageReport, IPersonalUsageRequest, IUsageBySourceReport, TUsageSurface } from "@robota-sdk/agent-interface-analytics";
3
+ import { ICommandListEntry, ICommandResult, ICommandSkillListEntry, TCommandSurfaceLocality } from "@robota-sdk/agent-interface-command";
4
+ import { IBackgroundJobGroupState, IBackgroundTaskInput, IBackgroundTaskListFilter, IBackgroundTaskLogCursor, IBackgroundTaskLogPage, IBackgroundTaskState, IExecutionDetailCursor, IExecutionDetailPage, IExecutionWorkspaceSnapshot, TBackgroundJobGroupEvent, TBackgroundTaskEvent } from "@robota-sdk/agent-interface-execution";
5
+ import { IAskRequestEvent, IBranchEvent, ICompactEvent, IContextFileRefreshedEvent, IExecutionResult, IModelListGroup, IPermissionRequestEvent, IPlanApprovalEvent, IPromptResolvedEvent, ISessionAgentJobs, ISessionBackgroundGroups, ISessionBackgroundTasks, ISessionCommands, ISessionConversationRead, ISessionDirectory, ISessionDriverAttribution, ISessionEvents, ISessionExecutionDetail, ISessionExecutionState, ISessionExecutionWorkspace, ISessionListing, ISessionProjectRead, ISessionPromptResolution, ISessionRenamedEvent, ISessionRuntimeTools, ISessionSelfPacedLoopControl, ISessionStatusRead, ISessionStatusSnapshot, ISessionSwitchedEvent, ISessionToolAppViews, ISessionTurnControl, ISessionTurnSubmission, ISettingsSnapshot, IToolState, IUiIntentEvent, TDriverId, TPermissionResultValue, TProjectDiffRead, TProjectMemoryRead, TProjectStatusRead, TSessionChangeRefusalCode, TSessionDeleteRefusalCode, TSettingsPatch, TTurnSource, TWaitingLoopStopOutcome } from "@robota-sdk/agent-interface-session";
6
+ import { IBinaryFrame, IChannelEventFrame, TActionResponse, TChannelReceiveResult } from "@robota-sdk/agent-interface-transport";
7
+ import { IHandoffIntegrity, IPeerMessage, IPeerMessageAck, TPeerDeliveryState } from "@robota-sdk/agent-interface-session-mobility";
8
+ //#region src/wire-messages.d.ts
9
+ type TBackgroundControlAction = 'cancel' | 'close' | 'send';
10
+ type THistoryEntry = ReturnType<ISessionConversationRead['getFullHistory']>[number];
11
+ /**
12
+ * #3282 §4: one agent the switcher can offer. `definedIn` is a plain-words location — a discovered
13
+ * file's path, or "Built-in" — never a raw internal id.
14
+ */
15
+ interface IWireAgentDefinitionSummary {
16
+ name: string;
17
+ description: string;
18
+ definedIn: string;
19
+ }
20
+ /**
21
+ * #3189: one entry of the session's full history as it crosses the wire. The same record the session
22
+ * keeps, except that `timestamp` is an ISO 8601 string: a `Date` does not survive JSON, and a
23
+ * declared `Date` that arrives as a string would let a client call `Date` methods on a string.
24
+ */
25
+ interface IWireHistoryEntry extends Omit<THistoryEntry, 'timestamp'> {
26
+ /** ISO 8601. */
27
+ timestamp: string;
28
+ }
29
+ /**
30
+ * #3189: a turn's result as it crosses the wire. The session's whole history stays behind: it only
31
+ * grows, so a client reads it in bounded pages with `get-history` instead.
32
+ */
33
+ type TWireExecutionResult = Omit<IExecutionResult, 'history'>;
34
+ /** Inbound message from client to server. */
35
+ type TClientMessage = {
36
+ type: 'submit';
37
+ prompt: string;
38
+ } | {
39
+ type: 'command';
40
+ name: string;
41
+ args?: string;
42
+ requestId?: string;
43
+ } | {
44
+ type: 'abort';
45
+ } | {
46
+ type: 'cancel-queue';
47
+ } | {
48
+ type: 'get-messages';
49
+ } | {
50
+ type: 'get-history';
51
+ fromIndex?: number;
52
+ } | {
53
+ type: 'get-prompts';
54
+ } | {
55
+ type: 'get-context';
56
+ } | {
57
+ type: 'get-commands';
58
+ } | {
59
+ type: 'get-status';
60
+ } | {
61
+ type: 'list-models';
62
+ requestId: string;
63
+ } | {
64
+ type: 'get-agent-definitions';
65
+ requestId: string;
66
+ } | {
67
+ type: 'list-sessions';
68
+ requestId: string;
69
+ } | {
70
+ type: 'new-session';
71
+ requestId?: string;
72
+ } | {
73
+ type: 'switch-session';
74
+ sessionId: string;
75
+ requestId?: string;
76
+ } | {
77
+ type: 'rename-session';
78
+ sessionId: string;
79
+ name: string;
80
+ requestId: string;
81
+ } | {
82
+ type: 'delete-session';
83
+ sessionId: string;
84
+ requestId: string;
85
+ } | {
86
+ type: 'get-usage-report';
87
+ } | {
88
+ type: 'get-personal-usage-report';
89
+ requestId: string;
90
+ period: IPersonalUsageRequest['period'];
91
+ timezone: string;
92
+ } | {
93
+ type: 'get-stored-session-usage-report';
94
+ requestId: string;
95
+ sessionId: string;
96
+ } | {
97
+ type: 'get-executing';
98
+ } | {
99
+ type: 'get-pending';
100
+ } | {
101
+ type: 'get-execution-workspace';
102
+ } | {
103
+ type: 'read-execution-detail';
104
+ requestId: string;
105
+ entryId: string;
106
+ cursor?: IExecutionDetailCursor;
107
+ } | {
108
+ type: 'stop-waiting-loop';
109
+ requestId: string;
110
+ } | {
111
+ type: 'project-status';
112
+ requestId: string;
113
+ } | {
114
+ type: 'project-diff';
115
+ requestId: string;
116
+ path: string;
117
+ } | {
118
+ type: 'project-memory';
119
+ requestId: string;
120
+ } | {
121
+ type: 'call-app-tool';
122
+ requestId: string;
123
+ viewId: string;
124
+ name: string;
125
+ arguments: TToolParameters;
126
+ } | {
127
+ type: 'read-app-view';
128
+ requestId: string;
129
+ viewId: string;
130
+ } | {
131
+ type: 'get-background-tasks';
132
+ filter?: IBackgroundTaskListFilter;
133
+ } | {
134
+ type: 'get-background-task';
135
+ taskId: string;
136
+ } | {
137
+ type: 'get-background-job-groups';
138
+ } | {
139
+ type: 'get-background-job-group';
140
+ groupId: string;
141
+ } | {
142
+ type: 'wait-background-job-group';
143
+ groupId: string;
144
+ } | {
145
+ type: 'cancel-background-task';
146
+ taskId: string;
147
+ reason?: string;
148
+ } | {
149
+ type: 'close-background-task';
150
+ taskId: string;
151
+ } | {
152
+ type: 'send-background-task';
153
+ taskId: string;
154
+ input: IBackgroundTaskInput;
155
+ } | {
156
+ type: 'read-background-task-log';
157
+ taskId: string;
158
+ cursor?: IBackgroundTaskLogCursor;
159
+ } | {
160
+ type: 'permission-response';
161
+ id: string;
162
+ result: TPermissionResultValue;
163
+ } | {
164
+ type: 'ask-response';
165
+ id: string;
166
+ response: TActionResponse;
167
+ } | {
168
+ type: 'resume';
169
+ lastSeq: number;
170
+ } | {
171
+ type: 'ack';
172
+ seq: number;
173
+ } | {
174
+ type: 'get-settings';
175
+ requestId: string;
176
+ } | {
177
+ type: 'update-settings';
178
+ requestId: string;
179
+ patch: TSettingsPatch;
180
+ };
181
+ /** Outbound message from server to client. */
182
+ type TServerMessage = {
183
+ type: 'text_delta';
184
+ delta: string;
185
+ driverId?: TDriverId;
186
+ } | {
187
+ type: 'user_message';
188
+ content: string;
189
+ driverId?: TDriverId;
190
+ } | {
191
+ type: 'tool_start';
192
+ state: IToolState;
193
+ driverId?: TDriverId;
194
+ } | {
195
+ type: 'tool_end';
196
+ state: IToolState;
197
+ driverId?: TDriverId;
198
+ } | {
199
+ type: 'thinking';
200
+ isThinking: boolean;
201
+ driverId?: TDriverId;
202
+ } | {
203
+ type: 'complete';
204
+ result: TWireExecutionResult;
205
+ driverId?: TDriverId;
206
+ } | {
207
+ type: 'interrupted';
208
+ result: TWireExecutionResult;
209
+ driverId?: TDriverId;
210
+ } | {
211
+ type: 'error';
212
+ /** The raw failure text — kept for a "Details" disclosure; never the whole story on its own. */
213
+ message: string;
214
+ /**
215
+ * What kind of failure this was, when it's known — so a renderer can say what happened and
216
+ * what to do next in plain words instead of showing `message` verbatim (#3289 §3). Additive:
217
+ * absent for a session error this classification does not recognize (unchanged behavior).
218
+ */
219
+ code?: 'auth' | 'rate_limit' | 'model_unavailable' | 'network' | 'provider';
220
+ /** The provider/profile name the failure came from, when `code` names one. */
221
+ provider?: string;
222
+ /** For `code: 'rate_limit'`, how long until a retry may succeed, when the provider said so. */
223
+ retryAfterSeconds?: number;
224
+ /**
225
+ * For `code: 'model_unavailable'`, the model the failed request tried — captured at the moment
226
+ * of failure so a renderer never has to fall back to whatever model is live by the time it
227
+ * draws this notice (which may already be a different one the person switched to).
228
+ */
229
+ model?: string;
230
+ driverId?: TDriverId;
231
+ } | {
232
+ type: 'command_result';
233
+ name: string;
234
+ message: string;
235
+ success: boolean;
236
+ data?: ICommandResult['data'];
237
+ /** The `requestId` of the `command` this answers, when it carried one. */
238
+ requestId?: string;
239
+ } | {
240
+ type: 'messages';
241
+ messages: ReturnType<ISessionConversationRead['getMessages']>;
242
+ /**
243
+ * #3288 §2: the SAME history, projected into display segments (text runs and finished tool
244
+ * calls, diffs included) — so a reload/reconnect/resume replay shows tool rows instead of bare
245
+ * text. Optional so an older host that has not grown `getMessagesDisplay()` yet still sends a
246
+ * valid frame; a client without this field falls back to `messages`-only (text bubbles), the
247
+ * same as before this existed.
248
+ */
249
+ display?: ReturnType<ISessionConversationRead['getMessagesDisplay']>;
250
+ /**
251
+ * #3289 §3: this connection's own server-assigned driver id, carried on the first frame every
252
+ * connection already gets — so a client can tell its OWN turns from a co-driver's instead of
253
+ * treating everything but the literal `'owner'` id as someone else (REMOTE-014 E5 display-only).
254
+ */
255
+ driverId?: TDriverId;
256
+ } | {
257
+ type: 'history';
258
+ startIndex: number;
259
+ total: number;
260
+ entries: IWireHistoryEntry[];
261
+ } | {
262
+ type: 'context';
263
+ state: ReturnType<ISessionConversationRead['getContextState']>;
264
+ } | {
265
+ type: 'history_changed';
266
+ /** A completed compaction, for clients that do not render the full system history. */
267
+ compact?: {
268
+ trigger: ICompactEvent['trigger'];
269
+ beforeUsedPercentage: number;
270
+ afterUsedPercentage: number;
271
+ };
272
+ } | {
273
+ type: 'turn_source';
274
+ source: TTurnSource;
275
+ } | {
276
+ type: 'commands';
277
+ commands: ICommandListEntry[];
278
+ skills: ICommandSkillListEntry[];
279
+ } | {
280
+ type: 'session_status';
281
+ status: ISessionStatusSnapshot;
282
+ } | {
283
+ type: 'model_list';
284
+ requestId: string;
285
+ groups: readonly IModelListGroup[];
286
+ currentProfile?: string;
287
+ currentModel: string;
288
+ } | {
289
+ type: 'agent_definitions';
290
+ requestId: string;
291
+ agents: readonly IWireAgentDefinitionSummary[];
292
+ current: string;
293
+ } | {
294
+ type: 'sessions';
295
+ requestId: string;
296
+ listing: ISessionListing;
297
+ } | {
298
+ type: 'sessions_error';
299
+ requestId: string;
300
+ code: 'not_available' | 'list_failed';
301
+ message: string;
302
+ } | {
303
+ type: 'session_switched';
304
+ event: ISessionSwitchedEvent;
305
+ } | {
306
+ type: 'session_change_failed';
307
+ code: TSessionChangeRefusalCode;
308
+ message: string;
309
+ requestId?: string;
310
+ } | {
311
+ type: 'session_renamed_in_list';
312
+ requestId: string;
313
+ sessionId: string;
314
+ name: string;
315
+ } | {
316
+ type: 'session_rename_failed';
317
+ requestId: string;
318
+ message: string;
319
+ } | {
320
+ type: 'session_deleted';
321
+ requestId: string;
322
+ sessionId: string;
323
+ } | {
324
+ type: 'session_delete_failed';
325
+ requestId: string;
326
+ code: TSessionDeleteRefusalCode;
327
+ message: string;
328
+ } | {
329
+ type: 'usage_report';
330
+ report: IUsageBySourceReport;
331
+ } | {
332
+ type: 'personal_usage_report';
333
+ requestId: string;
334
+ report: IPersonalUsageReport;
335
+ } | {
336
+ type: 'personal_usage_report_error';
337
+ requestId: string;
338
+ code: 'not_available' | 'report_failed';
339
+ message: string;
340
+ } | {
341
+ type: 'stored_session_usage_report';
342
+ requestId: string;
343
+ sessionId: string;
344
+ report: IUsageBySourceReport;
345
+ } | {
346
+ type: 'stored_session_usage_report_error';
347
+ requestId: string;
348
+ sessionId: string;
349
+ code: 'not_available' | 'report_failed';
350
+ message: string;
351
+ } | {
352
+ type: 'executing';
353
+ executing: boolean;
354
+ } | {
355
+ type: 'pending';
356
+ pending: string | null;
357
+ pendingCount?: number;
358
+ } | {
359
+ type: 'execution_workspace_event';
360
+ snapshot: IExecutionWorkspaceSnapshot;
361
+ } | {
362
+ type: 'execution_detail';
363
+ requestId: string;
364
+ page: IExecutionDetailPage;
365
+ } | {
366
+ type: 'execution_detail_error';
367
+ requestId: string;
368
+ message: string;
369
+ } | {
370
+ type: 'waiting_loop_stop';
371
+ requestId: string;
372
+ outcome: TWaitingLoopStopOutcome;
373
+ } | {
374
+ type: 'project_status';
375
+ requestId: string;
376
+ result: TProjectStatusRead;
377
+ } | {
378
+ type: 'project_diff';
379
+ requestId: string;
380
+ result: TProjectDiffRead;
381
+ } | {
382
+ type: 'project_memory';
383
+ requestId: string;
384
+ result: TProjectMemoryRead;
385
+ } | {
386
+ type: 'app_tool_result';
387
+ requestId: string;
388
+ success: boolean;
389
+ data?: IToolExecutionResult['result'];
390
+ parts?: TUniversalMessagePart[];
391
+ error?: string;
392
+ } | {
393
+ type: 'app_view';
394
+ requestId: string;
395
+ view: IToolAppView;
396
+ } | {
397
+ type: 'background_task_event';
398
+ event: TBackgroundTaskEvent;
399
+ } | {
400
+ type: 'background_job_group_event';
401
+ event: TBackgroundJobGroupEvent;
402
+ } | {
403
+ type: 'plan_event';
404
+ event: IPlanApprovalEvent;
405
+ } | {
406
+ type: 'context_file_refreshed';
407
+ event: IContextFileRefreshedEvent;
408
+ } | {
409
+ type: 'branch_event';
410
+ event: IBranchEvent;
411
+ } | {
412
+ type: 'background_tasks';
413
+ tasks: IBackgroundTaskState[];
414
+ } | {
415
+ type: 'background_task';
416
+ taskId: string;
417
+ task: IBackgroundTaskState | null;
418
+ } | {
419
+ type: 'background_job_groups';
420
+ groups: IBackgroundJobGroupState[];
421
+ } | {
422
+ type: 'background_job_group';
423
+ groupId: string;
424
+ group: IBackgroundJobGroupState | null;
425
+ } | {
426
+ type: 'background_task_log';
427
+ taskId: string;
428
+ page: IBackgroundTaskLogPage;
429
+ } | {
430
+ type: 'permission_request';
431
+ event: IPermissionRequestEvent;
432
+ } | {
433
+ type: 'ask_request';
434
+ event: IAskRequestEvent;
435
+ } | {
436
+ type: 'prompt_resolved';
437
+ event: IPromptResolvedEvent;
438
+ } | {
439
+ type: 'ui_intent';
440
+ event: IUiIntentEvent;
441
+ } | {
442
+ type: 'session_renamed';
443
+ event: ISessionRenamedEvent;
444
+ } | {
445
+ type: 'history_cleared';
446
+ } | {
447
+ type: 'background_task_control_result';
448
+ action: TBackgroundControlAction;
449
+ taskId: string;
450
+ success: boolean;
451
+ message?: string;
452
+ } | {
453
+ type: 'protocol_error';
454
+ message: string;
455
+ requestId?: string;
456
+ } | {
457
+ type: 'resume_gap';
458
+ } | {
459
+ type: 'settings';
460
+ requestId: string;
461
+ settings: ISettingsSnapshot;
462
+ } | {
463
+ type: 'settings_error';
464
+ requestId: string;
465
+ code: 'not_available' | 'invalid' | 'refused' | 'update_failed';
466
+ message: string;
467
+ };
468
+ /**
469
+ * REMOTE-013 E4: a server message stamped with its monotonic session sequence number (added by the
470
+ * {@link SessionResumeBridge} on the reconnectable WebRTC path). Intersecting over the union distributes the
471
+ * `seq` field onto every variant. The WS localhost path never stamps it (a `type`-dispatching client ignores
472
+ * an absent/extra `seq`).
473
+ */
474
+ type TSeqServerMessage = TServerMessage & {
475
+ seq: number;
476
+ };
477
+ //#endregion
478
+ //#region src/outbound-delivery.d.ts
479
+ declare const outboundDeliveryBrand: unique symbol;
480
+ /**
481
+ * Deliver one outbound frame on a connection. A carrier failure is REPORTED through the boundary's
482
+ * error handler, never thrown at the caller — so a reply resolving after a disconnect cannot escape as
483
+ * an unhandled rejection or out of the carrier's inbound listener.
484
+ *
485
+ * Only {@link createOutboundDelivery} produces one. The brand is the mechanism, not decoration: it is
486
+ * what makes a raw carrier `send` unusable where a boundary is required.
487
+ */
488
+ type TOutboundDeliver = ((message: TServerMessage) => void) & {
489
+ readonly [outboundDeliveryBrand]: true;
490
+ /**
491
+ * Bytes this carrier has ACCEPTED and not yet written to the peer — or `undefined` when it cannot
492
+ * say.
493
+ *
494
+ * `deliver` returning is not delivery. Both carriers hand this boundary a fire-and-forget sink, so
495
+ * a frame that has "been sent" may be sitting in a socket buffer the boundary cannot see. Anything
496
+ * this boundary counted itself would be a count of what it HANDED OVER, which is a different
497
+ * quantity from what the peer has not read — and a budget over the wrong quantity reports a
498
+ * healthy connection for a peer that stopped reading (ARCH-030 / issue #1734).
499
+ *
500
+ * `undefined` is deliberately not `0`. A carrier that cannot report backpressure and a carrier with
501
+ * nothing pending are different states, and collapsing them would let "unknown" satisfy any
502
+ * threshold placed on this number.
503
+ */
504
+ readonly pendingBytes: () => number | undefined;
505
+ };
506
+ /**
507
+ * Observe THIS connection's first outbound delivery failure. `event` is the `type` of the frame that
508
+ * could not be delivered — for the fan-out, the frame a session event was forwarded as (usually, not
509
+ * always, the event's own name), and the reply's type for a reply (`command_result`, `protocol_error`, …).
510
+ *
511
+ * Required, never optional: a carrier that could opt out of observing its own delivery failures is the
512
+ * silent-failure shape this boundary exists to remove.
513
+ */
514
+ type TDeliveryErrorHandler = (error: Error, event: TServerMessage['type']) => void;
515
+ declare const DEFAULT_MAX_PENDING_BYTES: number;
516
+ /**
517
+ * Backpressure budget for a terminal attached to a session on the same host, in either role.
518
+ *
519
+ * 1 MiB, tighter than the default: an attached terminal reads a local socket, so a backlog this large
520
+ * means it stopped reading rather than that a network is slow. Exceeding it closes that connection
521
+ * only; the session never waits for a reader, so other surfaces keep streaming.
522
+ */
523
+ declare const ATTACHED_SURFACE_MAX_PENDING_BYTES: number;
524
+ /**
525
+ * Is this carrier holding more than the budget allows?
526
+ *
527
+ * Exported because a WebSocket carries TWO kinds of outbound frame over one socket — the text
528
+ * protocol and TRANS-001's payload channels — and only one of them goes through
529
+ * {@link createOutboundDelivery}. A budget the binary path re-implemented would be a second opinion
530
+ * about one socket's backpressure; a budget it skipped would leave the same non-reading peer
531
+ * unbounded on the other half of the connection.
532
+ *
533
+ * `undefined` is unknown, not zero: a carrier that cannot report backpressure is never over budget.
534
+ */
535
+ declare function isOverPendingBudget(pending: number | undefined, limit?: number): boolean;
536
+ /**
537
+ * Default outbound DRAIN budget (issue #2306): how long a carrier may stay non-empty before the peer
538
+ * is treated as not reading.
539
+ *
540
+ * 120 seconds. The byte budget bounds HOW MUCH a peer holds; it cannot bound HOW LONG, because
541
+ * `bufferedAmount` is a quantity with no history — a peer draining just enough to stay under 8 MiB
542
+ * forever is never over it. The figure is generous on purpose: a legitimately slow link drains to
543
+ * zero between bursts, so the clock resets, whereas a peer that keeps SOMETHING pending for two
544
+ * minutes straight is holding a session, its resume buffer, and a socket it does not intend to read.
545
+ * A badly chosen figure here disconnects real users, which is why it is one named constant and an
546
+ * argument, never an inline number. `Infinity` disables the budget.
547
+ */
548
+ declare const DEFAULT_MAX_PENDING_MS: number;
549
+ /**
550
+ * The drain clock the boundary keeps for a carrier (issue #2306). One timestamp, not per-frame
551
+ * bookkeeping: it starts on the first reading that finds the carrier non-empty, RESETS only when a
552
+ * reading finds it empty (a peer that drains to one byte and stalls again has not drained), and is
553
+ * consulted synchronously at each send — the boundary has no timer and gains none here.
554
+ */
555
+ interface IPendingStallClock {
556
+ readonly maxPendingMs: number;
557
+ /**
558
+ * Record one reading of the carrier's pending bytes. Returns how long the carrier has been
559
+ * continuously non-empty when that exceeds the budget; `undefined` otherwise. An `undefined`
560
+ * reading is unknown, not zero: it neither starts nor resets the clock.
561
+ */
562
+ observe: (pending: number | undefined) => number | undefined;
563
+ }
564
+ declare function createPendingStallClock(maxPendingMs?: number, now?: () => number): IPendingStallClock;
565
+ declare function createOutboundDelivery(send: (message: TServerMessage) => void, onDeliveryError: TDeliveryErrorHandler, pendingBytes?: () => number | undefined, maxPendingBytes?: number, stallClock?: IPendingStallClock): TOutboundDeliver;
566
+ //#endregion
567
+ //#region src/protocol-session.d.ts
568
+ /** Session roles required by the shared WebSocket/WebRTC protocol. */
569
+ interface IProtocolSession extends ISessionTurnSubmission, ISessionTurnControl, ISessionCommands, ISessionStatusRead, ISessionEvents, ISessionPromptResolution, ISessionConversationRead, ISessionExecutionState, ISessionDriverAttribution, ISessionBackgroundTasks, ISessionBackgroundGroups, ISessionExecutionWorkspace, ISessionExecutionDetail, ISessionSelfPacedLoopControl, ISessionAgentJobs, ISessionRuntimeTools, ISessionToolAppViews {}
570
+ /**
571
+ * #3282 §4c: a protocol session that ALSO answers the Project panel's reads. `Partial` (not a fourth
572
+ * mandatory role on {@link IProtocolSession} itself) deliberately: every existing test double and
573
+ * every other host that builds an `IProtocolSession` keeps type-checking unchanged, and the panel's
574
+ * three methods are runtime-probed (`typeof session.readProjectStatus === 'function'`) rather than
575
+ * assumed — `InteractiveSession` (the one production implementation) provides all three, satisfying
576
+ * this type with no further wiring.
577
+ */
578
+ type TProjectReadCapableSession = IProtocolSession & Partial<ISessionProjectRead>;
579
+ //#endregion
580
+ //#region src/settings-messages.d.ts
581
+ type TSettingsMessage = Extract<TClientMessage, {
582
+ type: 'get-settings' | 'update-settings';
583
+ }>;
584
+ declare function isSettingsMessage(msg: TClientMessage): msg is TSettingsMessage;
585
+ /** What applying a patch did: the fresh snapshot, or why nothing was written. */
586
+ type TSettingsUpdateOutcome = {
587
+ readonly ok: true;
588
+ readonly settings: ISettingsSnapshot;
589
+ } | {
590
+ readonly ok: false;
591
+ readonly code: 'not_available' | 'invalid' | 'refused' | 'update_failed';
592
+ readonly message: string;
593
+ };
594
+ /**
595
+ * #3282 §4a: host-owned read/write for the Settings screen, supplied by the composition root the
596
+ * same way `IUsageQueryReporters` supplies usage reads — this package only correlates the request
597
+ * and carries the result. `updateSettings` applies through the SAME function the matching slash
598
+ * command uses (issue #3282 §4: "one code path, so the behavior matches the TUI"), so whatever a
599
+ * command would refuse on this surface is refused here too.
600
+ */
601
+ interface ISettingsReporter {
602
+ getSettings(session: IProtocolSession, locality?: TCommandSurfaceLocality): ISettingsSnapshot | Promise<ISettingsSnapshot>;
603
+ /**
604
+ * Applies through the SAME function the matching slash command uses. `locality` (#3282 §4 part
605
+ * b-2) is forwarded to that command exactly as the transport received it, so a command that
606
+ * refuses a remote surface (installing a plugin) refuses identically here.
607
+ */
608
+ updateSettings(session: IProtocolSession, patch: TSettingsPatch, locality?: TCommandSurfaceLocality): TSettingsUpdateOutcome | Promise<TSettingsUpdateOutcome>;
609
+ }
610
+ declare function handleSettingsMessage(session: IProtocolSession, deliver: TOutboundDeliver, msg: TSettingsMessage, reporter: ISettingsReporter | undefined, locality?: TCommandSurfaceLocality): void;
611
+ //#endregion
612
+ //#region src/usage-messages.d.ts
613
+ interface IUsageQueryReporters {
614
+ readonly personalUsageReporter: ((request: IPersonalUsageRequest) => IPersonalUsageReport | Promise<IPersonalUsageReport>) | undefined;
615
+ readonly usageReporter: ((session: IProtocolSession) => IUsageBySourceReport | Promise<IUsageBySourceReport>) | undefined;
616
+ readonly storedSessionUsageReporter: ((sessionId: string) => IUsageBySourceReport | Promise<IUsageBySourceReport>) | undefined;
617
+ }
618
+ //#endregion
619
+ //#region src/session-events.d.ts
620
+ type TProtocolSessionEventClassification = 'forwarded' | 'requester-routed' | 'non-surface';
621
+ /** Exhaustive protocol-owner policy over the shared session-event vocabulary. */
622
+ declare const PROTOCOL_SESSION_EVENT_CLASSIFICATION: {
623
+ readonly text_delta: "forwarded";
624
+ readonly tool_start: "forwarded";
625
+ readonly tool_end: "forwarded";
626
+ readonly thinking: "forwarded";
627
+ readonly thinking_delta: "non-surface";
628
+ readonly complete: "forwarded";
629
+ readonly error: "forwarded";
630
+ readonly context_update: "forwarded";
631
+ readonly compact: "forwarded";
632
+ readonly interrupted: "forwarded";
633
+ readonly skill_activation: "forwarded";
634
+ readonly background_task_event: "forwarded";
635
+ readonly background_job_group_event: "forwarded";
636
+ readonly execution_workspace_event: "forwarded";
637
+ readonly user_message: "forwarded";
638
+ readonly turn_source: "forwarded";
639
+ readonly context_file_refreshed: "forwarded";
640
+ readonly memory_event: "forwarded";
641
+ readonly goal_event: "non-surface";
642
+ readonly plan_event: "forwarded";
643
+ readonly branch_event: "forwarded";
644
+ readonly permission_request: "forwarded";
645
+ readonly ask_request: "forwarded";
646
+ readonly prompt_resolved: "forwarded";
647
+ readonly ui_intent: "requester-routed";
648
+ readonly session_renamed: "forwarded";
649
+ readonly history_cleared: "forwarded";
650
+ readonly session_switched: "forwarded";
651
+ readonly status_changed: "forwarded";
652
+ };
653
+ //#endregion
654
+ //#region src/session-message-handler.d.ts
655
+ /**
656
+ * What a connected surface may do. `drive` sends prompts, answers questions and controls the session.
657
+ * `observe` is read-only: it follows this session's conversation and state, but never submits, answers,
658
+ * controls, or reads another session's records, and it never counts as a surface that can answer.
659
+ */
660
+ type TSessionSurfaceRole = 'drive' | 'observe';
661
+ interface ISessionMessageHandlerOptions {
662
+ /** IProtocolSession to expose — `Partial<ISessionProjectRead>` is probed, not assumed (#3282 §4c). */
663
+ session: TProjectReadCapableSession;
664
+ /**
665
+ * ARCH-030: the CARRIER's connection-scoped outbound delivery boundary — not a raw `send`, and not a
666
+ * `send` plus an error callback for this handler to assemble into one. The carrier owns both the sink
667
+ * and the "what does a failed send mean for this connection" policy, so it builds the boundary and
668
+ * passes it down; the raw sink never crosses this parameter, which is what stops a future reply family
669
+ * from reaching the wire unguarded.
670
+ */
671
+ deliver: TOutboundDeliver;
672
+ /**
673
+ * REMOTE-014 E5: the SERVER-ASSIGNED driver id for THIS remote surface (the E3 `deviceId`). Injected into
674
+ * every inbound `submit`/`command`/prompt-response so a co-drive turn/answer is attributed to this driver —
675
+ * a client-supplied driver id is NEVER trusted. Absent → unattributed (the session defaults to the owner).
676
+ */
677
+ driverId?: TDriverId;
678
+ /** Trusted carrier-owned product surface, kept separate from driver identity. */
679
+ surface?: TUsageSurface;
680
+ /** Carrier-decided role of this connection; defaults to `drive`. The client never chooses it here. */
681
+ role?: TSessionSurfaceRole;
682
+ /** Host-owned cross-session read model. The protocol only correlates and carries its result. */
683
+ personalUsageReporter?: NonNullable<IUsageQueryReporters['personalUsageReporter']>;
684
+ /** Host-owned current-session trace/cost producer for the pre-existing message family. */
685
+ usageReporter?: NonNullable<IUsageQueryReporters['usageReporter']>;
686
+ /** Host-owned stored-session producer used by cross-session drill-down. */
687
+ storedSessionUsageReporter?: NonNullable<IUsageQueryReporters['storedSessionUsageReporter']>;
688
+ /** Host-owned session directory (#3189): list, start and switch the host's sessions. */
689
+ sessionDirectory?: ISessionDirectory;
690
+ /** #3282 §4a: host-owned read/write for the GUI Settings screen. */
691
+ settingsReporter?: ISettingsReporter;
692
+ /**
693
+ * #3282 §4 part b-2: carrier-decided, like `role` — whether THIS carrier's connections are
694
+ * provably on this machine. The loopback WS carrier is `'local'`; the device-mesh/WebRTC carrier
695
+ * sets `'remote'`. Absent → `'local'`, forwarded to `executeCommand` and the settings reporter so a
696
+ * command that runs code from outside the session (installing a plugin) can refuse a remote device.
697
+ */
698
+ commandSurfaceLocality?: TCommandSurfaceLocality;
699
+ /**
700
+ * The most bytes one frame answering an app tool call or view read may take, for a carrier whose
701
+ * channel carries less than the inbound limit (a WebRTC data channel). An answer over it is
702
+ * replaced by a `protocol_error` before it reaches any buffer. Defaults to the inbound limit less
703
+ * a margin for a carrier that stamps frames afterwards.
704
+ */
705
+ maxFrameBytes?: number;
706
+ }
707
+ /**
708
+ * Create a carrier-neutral message handler for an IProtocolSession.
709
+ *
710
+ * Returns:
711
+ * - `onMessage(data)`: call this when the WebSocket receives a message
712
+ * - `cleanup()`: call this when the WebSocket disconnects
713
+ *
714
+ * Usage:
715
+ * ```typescript
716
+ * const delivery = createOutboundDelivery(
717
+ * (msg) => ws.send(JSON.stringify(msg)),
718
+ * (error) => ws.close(1011, error.message),
719
+ * );
720
+ * const { onMessage, cleanup } = createSessionMessageHandler({ session: interactiveSession, deliver: delivery });
721
+ *
722
+ * ws.on('message', (data) => onMessage(String(data)));
723
+ * ws.on('close', cleanup);
724
+ * ```
725
+ */
726
+ declare function createSessionMessageHandler(options: ISessionMessageHandlerOptions): {
727
+ onMessage: (data: string) => void;
728
+ cleanup: () => void;
729
+ };
730
+ //#endregion
731
+ //#region src/observer-messages.d.ts
732
+ /** Whether an observer may send a message of this type. */
733
+ declare function isObserverMessageType(type: string): boolean;
734
+ //#endregion
735
+ //#region src/session-query-messages.d.ts
736
+ /**
737
+ * #3189: the most serialized history one `history` frame carries. Well under the tightest outbound
738
+ * budget (an attached terminal's, 1 MiB), so a client reading page after page is never mistaken for
739
+ * one that stopped reading.
740
+ */
741
+ declare const HISTORY_PAGE_MAX_BYTES: number;
742
+ //#endregion
743
+ //#region src/message-decoders.d.ts
744
+ type TMessageDecodeResult<TMessage> = {
745
+ readonly ok: true;
746
+ readonly message: TMessage;
747
+ } | {
748
+ readonly ok: false;
749
+ readonly reason: string;
750
+ };
751
+ /** Serialized frames larger than this are refused before any parse (a bounded inbound budget). */
752
+ declare const MAX_INBOUND_FRAME_BYTES: number;
753
+ /** Total decode of a parsed client frame. */
754
+ declare function decodeClientMessage(value: unknown): TMessageDecodeResult<TClientMessage>;
755
+ /** Variant-level decode of a parsed server frame (foreign-owned payloads as records, see header). */
756
+ declare function decodeServerMessage(value: unknown): TMessageDecodeResult<TServerMessage>;
757
+ /** `raw string → JSON → owner decoder`, the one path a carrier implements. */
758
+ declare function decodeFrame<TMessage>(data: string, decode: (value: unknown) => TMessageDecodeResult<TMessage>): TMessageDecodeResult<TMessage>;
759
+ //#endregion
760
+ //#region src/resume-buffer.d.ts
761
+ /** One retained frame: its sequence number and the message. */
762
+ interface IBufferedFrame {
763
+ readonly seq: number;
764
+ readonly message: TServerMessage;
765
+ }
766
+ /** The result of a `tailAfter` — either the ordered replay slice, or an overrun (client must full-refresh). */
767
+ type TResumeTail = {
768
+ readonly kind: 'tail';
769
+ readonly frames: readonly IBufferedFrame[];
770
+ } | {
771
+ readonly kind: 'overrun';
772
+ };
773
+ interface IResumeBufferOptions {
774
+ /** Max retained frames (drop-oldest beyond this). Default 512. */
775
+ readonly maxFrames?: number;
776
+ /** Max retained bytes across frames (drop-oldest beyond this). Default 4 MiB. */
777
+ readonly maxBytes?: number;
778
+ /** Serialized size of a message (for the byte budget). Default: JSON length. Injectable for tests. */
779
+ readonly sizeOf?: (message: TServerMessage) => number;
780
+ }
781
+ /**
782
+ * A monotonic, bounded ring of un-acked frames. Sequence numbers are assigned by {@link append} and never
783
+ * reused; `tailAfter` / `ackThrough` operate over the retained window.
784
+ */
785
+ declare class ResumeBuffer {
786
+ private readonly frames;
787
+ private readonly sizes;
788
+ private nextSeq;
789
+ private bytes;
790
+ private readonly maxFrames;
791
+ private readonly maxBytes;
792
+ private readonly sizeOf;
793
+ constructor(options?: IResumeBufferOptions);
794
+ /** Append a message, assign + return its monotonic seq, and evict oldest frames beyond the bounds. */
795
+ append(message: TServerMessage): number;
796
+ /** Drop all retained frames with `seq <= throughSeq` (the client confirmed receipt up to there). */
797
+ ackThrough(throughSeq: number): void;
798
+ /**
799
+ * The ordered frames with `seq > lastSeq`. Returns an `overrun` marker when `lastSeq` is older than the
800
+ * oldest retained frame (i.e. some frame after `lastSeq` was already evicted) — the client must full-refresh.
801
+ * `lastSeq` at or beyond the newest seq yields an empty tail (nothing to replay).
802
+ */
803
+ tailAfter(lastSeq: number): TResumeTail;
804
+ /** The last seq assigned (0 when nothing has been appended). */
805
+ get lastSeq(): number;
806
+ /** Retained frame count (diagnostics/tests). */
807
+ get size(): number;
808
+ private evict;
809
+ /** The single place that mutates `frames`/`sizes`/`bytes` for removal, so byte accounting can't drift. */
810
+ private removeOldest;
811
+ }
812
+ //#endregion
813
+ //#region src/channel-frames.d.ts
814
+ /** `R`, `B`, `F` — the shared prefix every channel frame starts with. */
815
+ declare const CHANNEL_FRAME_MAGIC: Uint8Array;
816
+ /** Envelope version. Bumped only on an incompatible layout change. */
817
+ declare const CHANNEL_FRAME_VERSION = 1;
818
+ /** Encode an opaque binary frame. The payload bytes are copied verbatim. */
819
+ declare function encodeBinaryFrame(frame: IBinaryFrame): Uint8Array;
820
+ /** Encode a structured, consumer-declared event frame (UTF-8 JSON body). */
821
+ declare function encodeChannelEventFrame(frame: IChannelEventFrame): Uint8Array;
822
+ /** True when `bytes` starts with the channel-frame magic — a cheap, non-parsing routing check. */
823
+ declare function isChannelFrame(bytes: Uint8Array): boolean;
824
+ /**
825
+ * Decode a channel frame. Returns an explicit result union — a non-channel, truncated, or malformed
826
+ * input is a stated error the carrier reports to the peer, never a thrown exception on the hot path
827
+ * and never a silently dropped frame.
828
+ */
829
+ declare function decodeChannelFrame(bytes: Uint8Array): TChannelReceiveResult;
830
+ //#endregion
831
+ //#region src/session-resume-bridge.d.ts
832
+ /** The current channel sink — receives a serialized JSON frame to put on the wire. */
833
+ type TResumeSink = (data: string) => void;
834
+ /** Options for {@link SessionResumeBridge.attach}. */
835
+ interface IAttachOptions {
836
+ /**
837
+ * REMOTE-013 E4: on a RECONNECT, HOLD live sink-forwarding until the client's `resume` has replayed the
838
+ * buffered tail — otherwise a live frame emitted between attach and the inbound `resume` would leapfrog the
839
+ * gap frames on the wire, and the client's seq-dedup would then discard the (older, lower-seq) gap. Every
840
+ * live event is already appended to the buffer, so holding loses nothing; `replay()` flushes in order and
841
+ * un-holds. First-pair attach does NOT hold (the client starts at seq 0, frames arrive in order).
842
+ */
843
+ readonly awaitResume?: boolean;
844
+ /** Sink/carrier-owned failure lifecycle for this attachment only. */
845
+ readonly onDeliveryError: (error: Error, event: string) => void;
846
+ /**
847
+ * ARCH-030: this attachment's carrier backpressure reading, if it has one.
848
+ *
849
+ * Threaded through because the replay path is the burst this budget exists for — a reconnecting
850
+ * peer is handed the whole retained tail at once, and without a reading the boundary here would
851
+ * have no budget at all while the per-channel boundary did.
852
+ */
853
+ readonly pendingBytes?: () => number | undefined;
854
+ }
855
+ interface ISessionResumeBridgeOptions {
856
+ readonly session: IProtocolSession;
857
+ readonly buffer?: IResumeBufferOptions;
858
+ /** REMOTE-014 E5: the SERVER-ASSIGNED driver id for this surface, injected into inbound submit/command/prompt-response. */
859
+ readonly driverId?: TDriverId;
860
+ readonly surface?: TUsageSurface;
861
+ readonly personalUsageReporter?: IUsageQueryReporters['personalUsageReporter'];
862
+ readonly usageReporter?: IUsageQueryReporters['usageReporter'];
863
+ readonly storedSessionUsageReporter?: IUsageQueryReporters['storedSessionUsageReporter'];
864
+ /** #3282 §4 part b-2: this bridge is the reconnectable WebRTC path, so it is always `'remote'`. */
865
+ readonly commandSurfaceLocality?: TCommandSurfaceLocality;
866
+ /** See {@link ISessionMessageHandlerOptions.maxFrameBytes}: the channel's limit, not the inbound one. */
867
+ readonly maxFrameBytes?: number;
868
+ }
869
+ declare class SessionResumeBridge {
870
+ private readonly session;
871
+ private readonly buffer;
872
+ private driverId?;
873
+ private readonly reporters;
874
+ private readonly surface?;
875
+ private readonly commandSurfaceLocality?;
876
+ private readonly maxFrameBytes?;
877
+ /**
878
+ * Ends with the bridge, not with a channel: a channel drop keeps the session reconnectable, so work
879
+ * started for a hosted app view (a call waiting on its prompt) survives it and is cancelled only when
880
+ * the host gives up on the session.
881
+ */
882
+ private readonly lifetime;
883
+ private readonly unsubscribe;
884
+ private onDeliveryError?;
885
+ /**
886
+ * ARCH-030: the attachment's outbound boundary — and the only reference this class keeps to the current
887
+ * channel, which is why `dispose()` goes through `detach()` rather than clearing a separate field.
888
+ * Built per `attach` because a boundary LATCHES on its first failure, so a fresh one is exactly what
889
+ * un-latches the session for the next channel. It holds the only try/catch on the frame path.
890
+ */
891
+ private outbound?;
892
+ /**
893
+ * The session-lifetime entry every frame takes — event fan-out AND every reply to an inbound frame —
894
+ * before it is seq-stamped and buffered by {@link emit}. Distinct from {@link outbound}, which is the
895
+ * per-attachment exit to the current channel; this one outlives channels because the subscription does.
896
+ *
897
+ * It guards the BUFFERING step, not a carrier, and it latches for the life of the session on purpose:
898
+ * the failure it is placed against is the buffer refusing a frame on capacity, and a resume buffer that
899
+ * cannot accept frames cannot honour a later `resume` either, so there is nothing a reconnect recovers.
900
+ * That is the opposite of {@link outbound}, where the next channel IS the recovery — the two scopes
901
+ * differ because the failures do. (A per-frame serialization failure would leave the buffer intact, but
902
+ * such a frame is undeliverable on every carrier, since each one stringifies it too; it is reported and
903
+ * the carrier torn down, never silently dropped.)
904
+ */
905
+ private readonly emitBoundary;
906
+ private disposed;
907
+ /** REMOTE-013 E4: while true, live emits are buffered but NOT forwarded — released by `replay()` on reconnect. */
908
+ private holding;
909
+ constructor(options: ISessionResumeBridgeOptions);
910
+ /** Set the current channel sink (on connect / reconnect). Live messages reach the client; replay is `resume`-driven. */
911
+ attach(sink: TResumeSink, options: IAttachOptions): void;
912
+ /** Clear the sink (channel drop). Buffering continues so gap output is retained for the next `resume`. */
913
+ detach(): void;
914
+ /**
915
+ * REMOTE-014 E5: bind the SERVER-ASSIGNED driver id (the E3 `deviceId`) once the peer pairs — the bridge
916
+ * injects it into every subsequent inbound submit/command/prompt-response for co-drive attribution.
917
+ */
918
+ setDriverId(driverId: TDriverId): void;
919
+ /** Route one inbound channel frame: `resume`/`ack` handled here; everything else → the session. */
920
+ onClientMessage(data: string): void;
921
+ /** Unsubscribe from the session (host reconnect-window ceiling / teardown). Idempotent. */
922
+ dispose(): void;
923
+ /** Diagnostics/tests: the last seq assigned. */
924
+ get lastSeq(): number;
925
+ /**
926
+ * Stamp a seq, retain in the buffer, and forward to the current sink — UNLESS holding for a reconnect replay.
927
+ *
928
+ * ARCH-030: the `buffer.append` happens BEFORE the boundary, deliberately. The boundary latches on its
929
+ * first failure and drops everything after it, so a frame appended afterwards would be lost — appending
930
+ * first means a dropped frame is still in the un-acked tail and still replays on the next `resume`.
931
+ */
932
+ private emit;
933
+ /**
934
+ * Replay the buffered tail after `lastSeq` (or `resume_gap` on overrun), then RELEASE the reconnect hold so
935
+ * subsequent live frames flow in order behind the flushed gap.
936
+ *
937
+ * A failing sink reports ONCE across the whole tail: the boundary latches on the first failure and every
938
+ * remaining frame is dropped silently. Those frames stay un-acked in the buffer and replay on the next
939
+ * attachment. Before ARCH-030 the single report was a side effect of `detach()` running mid-loop; now it
940
+ * is the boundary's stated contract.
941
+ */
942
+ private replay;
943
+ /** The ONE outbound exit from this class. No frame reaches the sink except through the attachment's boundary. */
944
+ private deliverFrame;
945
+ /** Detach the failed sink but retain the frame, then notify its attachment owner. */
946
+ private reportDeliveryError;
947
+ }
948
+ //#endregion
949
+ //#region src/peer-message-ledger.d.ts
950
+ /**
951
+ * What the receiver has seen from one origin.
952
+ *
953
+ * `delivered` is a SET, not just a high-water mark, and that distinction is the whole of review
954
+ * finding #1. A high-water mark cannot tell "sequence 2 was already used" from "sequence 2 is the
955
+ * gap we reported and it has just arrived" — and answering the second as if it were the first
956
+ * refuses a message that was never delivered, permanently. `highestSequence` is kept alongside it
957
+ * because reporting a gap needs the frontier, not the membership.
958
+ *
959
+ * Exported because it is reachable from `IPeerMessageLedger`. A public interface whose field type is
960
+ * unexported is a name a consumer cannot write down (review finding #2). Measured: `tsdown` inlines
961
+ * it into the bundled declaration so no TS4033 is raised today — the finding's build-breakage claim
962
+ * does not reproduce — but a type nobody can name is still a bad public surface.
963
+ */
964
+ interface IOriginRecord {
965
+ /** The highest sequence delivered from this origin — the frontier a gap is measured against. */
966
+ highestSequence: number;
967
+ /** Every sequence actually delivered. Membership, not a range: gaps get filled out of order. */
968
+ delivered: Set<number>;
969
+ /** Acks already issued, by message id, so a retry gets the original answer back. */
970
+ issued: Map<string, IPeerMessageAck>;
971
+ }
972
+ /** Per-connection receive state. Created empty; discarded when the connection ends. */
973
+ interface IPeerMessageLedger {
974
+ readonly origins: Map<string, IOriginRecord>;
975
+ }
976
+ declare function createPeerMessageLedger(): IPeerMessageLedger;
977
+ /** Why a message was not accepted, when it was not. */
978
+ interface IPeerMessageRejection {
979
+ readonly state: Extract<TPeerDeliveryState, 'refused' | 'failed'>;
980
+ readonly reason: string;
981
+ }
982
+ interface IPeerMessageVerdict {
983
+ readonly ack: IPeerMessageAck;
984
+ /**
985
+ * Should the session deliver this to the agent?
986
+ *
987
+ * False for a duplicate and for a refusal. Separate from `ack.state` because a caller that
988
+ * re-derived it from the state string would have to re-list which states mean "deliver", and that
989
+ * list is exactly what drifts.
990
+ */
991
+ readonly deliver: boolean;
992
+ /**
993
+ * Set when this message's sequence is ahead of the last one delivered from its origin.
994
+ *
995
+ * Reported, not resolved. The session layer decides whether a gap is worth waiting for; the
996
+ * ledger's job is to make sure it is never invisible.
997
+ */
998
+ readonly gapBefore?: number;
999
+ }
1000
+ /**
1001
+ * Record a message and say what should happen to it.
1002
+ *
1003
+ * Pure with respect to its inputs except for the ledger it is handed, which it updates in place —
1004
+ * the caller owns the ledger's lifetime, so a connection ending is a reference going away rather
1005
+ * than a cleanup step someone can forget.
1006
+ */
1007
+ declare function admitPeerMessage(ledger: IPeerMessageLedger, message: IPeerMessage, rejection?: IPeerMessageRejection): IPeerMessageVerdict;
1008
+ /**
1009
+ * Mark a delivered message as acknowledged by the agent side.
1010
+ *
1011
+ * Separate from `admitPeerMessage` because delivery and acknowledgement answer different questions —
1012
+ * "did the receiver take it" versus "did the agent act on it" — and a sender waiting for the second
1013
+ * must not be told the first.
1014
+ */
1015
+ declare function acknowledgePeerMessage(ledger: IPeerMessageLedger, originSessionId: string, id: string): IPeerMessageAck | undefined;
1016
+ /** Forget one origin — used when a peer disconnects and its sequence space is no longer meaningful. */
1017
+ declare function forgetPeerOrigin(ledger: IPeerMessageLedger, originSessionId: string): void;
1018
+ //#endregion
1019
+ //#region src/permission-summary.d.ts
1020
+ /** The call's identifying argument, or `undefined` when it has none worth showing. */
1021
+ declare function permissionSummaryArgument(toolArgs: TToolArgs): string | undefined;
1022
+ //#endregion
1023
+ //#region src/handoff-chunking.d.ts
1024
+ /**
1025
+ * One piece of a payload in flight.
1026
+ *
1027
+ * `total` travels on every chunk rather than in a separate header frame: a header can be the frame
1028
+ * that gets lost, and a receiver that learned the count from a message it never got would wait
1029
+ * forever for a number it cannot ask for again.
1030
+ */
1031
+ interface IHandoffChunk {
1032
+ readonly handoffId: string;
1033
+ /** 0-based position in the sequence. */
1034
+ readonly index: number;
1035
+ /** How many chunks make up the whole payload. */
1036
+ readonly total: number;
1037
+ /** base64 of this slice of the UTF-8 encoded payload. */
1038
+ readonly data: string;
1039
+ }
1040
+ /**
1041
+ * Default frame budget, in bytes of encoded chunk data.
1042
+ *
1043
+ * 16 KiB because that is the size every SCTP implementation carries without negotiation. Larger
1044
+ * works between two peers that both support it and fails between two that do not — and it fails at
1045
+ * transfer time, on the user's session, not in a test.
1046
+ */
1047
+ declare const DEFAULT_MAX_CHUNK_BYTES: number;
1048
+ /**
1049
+ * Cut a sealed payload into chunks.
1050
+ *
1051
+ * Takes the serialized string the seal produced, not the record — the digest is over those exact
1052
+ * bytes, and re-serializing here would let a chunked payload differ from the one the manifest
1053
+ * describes.
1054
+ */
1055
+ declare function chunkHandoffPayload(handoffId: string, serialized: string, maxChunkBytes?: number): readonly IHandoffChunk[];
1056
+ /** Why a chunk was not accepted. */
1057
+ type TChunkRejection =
1058
+ /** Belongs to a different transfer. */
1059
+ 'wrong-handoff' |
1060
+ /** `index` is negative, or beyond the declared `total`. */
1061
+ 'out-of-range' |
1062
+ /** Its `total` disagrees with what earlier chunks declared. */
1063
+ 'inconsistent-total' |
1064
+ /** Its `data` is not decodable base64. */
1065
+ 'undecodable';
1066
+ type TChunkOutcome =
1067
+ /** Stored; more are still needed. */
1068
+ 'accepted' |
1069
+ /** Already had this index, and it matched. A retry, not a problem. */
1070
+ 'duplicate' |
1071
+ /** Stored, and that was the last one missing. */
1072
+ 'complete' | 'refused';
1073
+ interface IChunkResult {
1074
+ readonly outcome: TChunkOutcome;
1075
+ readonly rejection?: TChunkRejection;
1076
+ /** Present when complete: the reassembled payload, ready for the integrity check. */
1077
+ readonly serialized?: string;
1078
+ /** How many distinct chunks are held. */
1079
+ readonly received: number;
1080
+ /** How many are expected, once anything has declared it. */
1081
+ readonly expected?: number;
1082
+ }
1083
+ /**
1084
+ * Collects the chunks of ONE transfer.
1085
+ *
1086
+ * One assembler per `handoffId`, because a shared one would have to key everything by transfer and
1087
+ * would then be a place where two transfers can be confused for each other. A chunk naming a
1088
+ * different transfer is refused rather than routed — routing is the caller's job and doing it here
1089
+ * would make this a dispatcher as well as a buffer.
1090
+ */
1091
+ declare class HandoffChunkAssembler {
1092
+ private readonly handoffId;
1093
+ private readonly chunks;
1094
+ private declaredTotal;
1095
+ constructor(handoffId: string);
1096
+ get received(): number;
1097
+ get expected(): number | undefined;
1098
+ /** Take one chunk. Reordering and retries are normal; inconsistency is not. */
1099
+ accept(chunk: IHandoffChunk): IChunkResult;
1100
+ /** Which indices are still missing, so a caller can ask for them rather than restarting. */
1101
+ missing(): readonly number[];
1102
+ /** Drop everything held. The transfer was abandoned, or its integrity check failed. */
1103
+ discard(): void;
1104
+ private reassemble;
1105
+ }
1106
+ /**
1107
+ * How many chunks a payload of this size will take, without building them.
1108
+ *
1109
+ * For a progress indicator at the sending end, and for a receiver deciding whether it is willing to
1110
+ * hold that much before the first chunk arrives.
1111
+ */
1112
+ declare function chunkCountFor(integrity: IHandoffIntegrity, maxChunkBytes?: number): number;
1113
+ //#endregion
1114
+ export { ATTACHED_SURFACE_MAX_PENDING_BYTES, CHANNEL_FRAME_MAGIC, CHANNEL_FRAME_VERSION, DEFAULT_MAX_CHUNK_BYTES, DEFAULT_MAX_PENDING_BYTES, DEFAULT_MAX_PENDING_MS, HISTORY_PAGE_MAX_BYTES, HandoffChunkAssembler, type IAttachOptions, type IBufferedFrame, type IChunkResult, type IHandoffChunk, type IPeerMessageLedger, type IPeerMessageRejection, type IPeerMessageVerdict, type IPendingStallClock, type IProtocolSession, type IResumeBufferOptions, type ISessionMessageHandlerOptions, type ISessionResumeBridgeOptions, type ISettingsReporter, type IWireAgentDefinitionSummary, type IWireHistoryEntry, MAX_INBOUND_FRAME_BYTES, PROTOCOL_SESSION_EVENT_CLASSIFICATION, ResumeBuffer, SessionResumeBridge, type TChunkOutcome, type TChunkRejection, type TClientMessage, type TDeliveryErrorHandler, type TMessageDecodeResult, type TOutboundDeliver, type TProtocolSessionEventClassification, type TResumeSink, type TResumeTail, type TSeqServerMessage, type TServerMessage, type TSessionSurfaceRole, type TSettingsUpdateOutcome, type TWireExecutionResult, acknowledgePeerMessage, admitPeerMessage, chunkCountFor, chunkHandoffPayload, createOutboundDelivery, createPeerMessageLedger, createPendingStallClock, createSessionMessageHandler, decodeChannelFrame, decodeClientMessage, decodeFrame, decodeServerMessage, encodeBinaryFrame, encodeChannelEventFrame, forgetPeerOrigin, handleSettingsMessage, isChannelFrame, isObserverMessageType, isOverPendingBudget, isSettingsMessage, permissionSummaryArgument };
1115
+ //# sourceMappingURL=index.d.cts.map