@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.
- package/CHANGELOG.md +1137 -0
- package/LICENSE +661 -0
- package/README.md +121 -0
- package/dist/browser/client.d.ts +2 -0
- package/dist/browser/client.js +1 -0
- package/dist/browser/index.d.ts +624 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +2 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/observer-messages-4fRQZU2D.d.ts +499 -0
- package/dist/browser/observer-messages-4fRQZU2D.d.ts.map +1 -0
- package/dist/browser/observer-messages-O8jTPEQO.js +2 -0
- package/dist/browser/observer-messages-O8jTPEQO.js.map +1 -0
- package/dist/node/index.cjs +1 -0
- package/dist/node/index.d.cts +1115 -0
- package/dist/node/index.d.cts.map +1 -0
- package/dist/node/index.d.ts +1115 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/node.cjs +1 -0
- package/dist/node/node.d.cts +317 -0
- package/dist/node/node.d.cts.map +1 -0
- package/dist/node/node.d.ts +317 -0
- package/dist/node/node.d.ts.map +1 -0
- package/dist/node/node.js +2 -0
- package/dist/node/node.js.map +1 -0
- package/package.json +122 -0
- package/src/__tests__/__fixtures__/korean-text.json +6 -0
- package/src/__tests__/access-token-verifier.test.ts +672 -0
- package/src/__tests__/admission.test.ts +130 -0
- package/src/__tests__/app-tool-messages.test.ts +463 -0
- package/src/__tests__/bearer-resource-gate.test.ts +120 -0
- package/src/__tests__/channel-frames.test.ts +215 -0
- package/src/__tests__/driver-attribution-capability.test.ts +83 -0
- package/src/__tests__/file-transfer.test.ts +281 -0
- package/src/__tests__/handoff-chunking.test.ts +261 -0
- package/src/__tests__/handoff-manifest.test.ts +52 -0
- package/src/__tests__/history-attached-budget.test.ts +216 -0
- package/src/__tests__/message-decoders.test.ts +870 -0
- package/src/__tests__/outbound-delivery.test.ts +558 -0
- package/src/__tests__/peer-message-ledger.test.ts +200 -0
- package/src/__tests__/permission-summary.test.ts +18 -0
- package/src/__tests__/personal-usage-report.test.ts +193 -0
- package/src/__tests__/project-read-messages.test.ts +118 -0
- package/src/__tests__/resume-buffer.test.ts +93 -0
- package/src/__tests__/session-detail-loop-status.test.ts +169 -0
- package/src/__tests__/session-directory-messages.test.ts +322 -0
- package/src/__tests__/session-error-classification.test.ts +113 -0
- package/src/__tests__/session-event-delivery.test.ts +101 -0
- package/src/__tests__/session-history-wire.test.ts +364 -0
- package/src/__tests__/session-message-handler-e5.test.ts +99 -0
- package/src/__tests__/session-message-handler-observe.test.ts +223 -0
- package/src/__tests__/session-message-handler.test.ts +726 -0
- package/src/__tests__/session-resume-bridge.test.ts +472 -0
- package/src/__tests__/settings-messages.test.ts +193 -0
- package/src/__tests__/stdio-carrier.test.ts +85 -0
- package/src/__tests__/submit-prompt-shape.test.ts +78 -0
- package/src/__tests__/usage-report-carrier.test.ts +98 -0
- package/src/__tests__/ws-broadcast-events.test.ts +94 -0
- package/src/app-tool-messages.ts +140 -0
- package/src/background-messages.ts +169 -0
- package/src/channel-frames.ts +182 -0
- package/src/client.ts +17 -0
- package/src/handoff-chunking.ts +275 -0
- package/src/index.ts +135 -0
- package/src/loop-control-messages.ts +34 -0
- package/src/message-decoders.ts +485 -0
- package/src/message-parser.ts +33 -0
- package/src/node/access-token-verifier.ts +363 -0
- package/src/node/admission.ts +153 -0
- package/src/node/bearer-resource-gate.ts +331 -0
- package/src/node/file-transfer.ts +530 -0
- package/src/node/handoff-manifest.ts +77 -0
- package/src/node/index.ts +45 -0
- package/src/node/stdio-carrier.ts +59 -0
- package/src/observer-messages.ts +47 -0
- package/src/open-prompts.ts +76 -0
- package/src/outbound-delivery.ts +240 -0
- package/src/peer-message-ledger.ts +193 -0
- package/src/permission-summary.ts +18 -0
- package/src/project-read-messages.ts +74 -0
- package/src/protocol-session.ts +56 -0
- package/src/resume-buffer.ts +123 -0
- package/src/session-directory-messages.ts +162 -0
- package/src/session-error-classification.ts +91 -0
- package/src/session-events.ts +290 -0
- package/src/session-message-handler.ts +413 -0
- package/src/session-query-messages.ts +160 -0
- package/src/session-resume-bridge.ts +275 -0
- package/src/settings-messages.ts +103 -0
- package/src/usage-messages.ts +195 -0
- package/src/wire-messages.ts +436 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent session-resume bridge for the reconnectable WebRTC path (REMOTE-013 Stage E4).
|
|
3
|
+
*
|
|
4
|
+
* Created ONCE per remote session and OUTLIVES individual data channels. It subscribes to the session's
|
|
5
|
+
* events exactly once, stamps every outbound `TServerMessage` with a **monotonic `seq` that is continuous
|
|
6
|
+
* across channel drops**, and retains the un-acked tail in a {@link ResumeBuffer}. The data channel is a
|
|
7
|
+
* SWAPPABLE sink:
|
|
8
|
+
*
|
|
9
|
+
* - `attach(sink)` — set the current sink (a new channel after a reconnect). Does NOT auto-replay; replay is
|
|
10
|
+
* driven by the client's `resume`.
|
|
11
|
+
* - `detach()` — clear the sink but KEEP buffering, so output produced while no channel is attached (the gap)
|
|
12
|
+
* is captured and replayable.
|
|
13
|
+
* - `onClientMessage(data)` — `resume{lastSeq}` replays the buffered tail (or `resume_gap` on overrun); `ack{seq}`
|
|
14
|
+
* frees the buffer; everything else routes to the session (reusing the shared `handleClientMessage`).
|
|
15
|
+
* - `dispose()` — unsubscribe (host reconnect-window ceiling / teardown).
|
|
16
|
+
*
|
|
17
|
+
* This is the fix for the placement defect: because the seq counter + buffer live here (not in the per-channel
|
|
18
|
+
* `createSessionMessageHandler`), `seq` does not reset when a reconnect builds a new channel, and gap output is not lost.
|
|
19
|
+
* The WS localhost path does NOT use this bridge — it keeps `createSessionMessageHandler` unchanged.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { createOutboundDelivery } from './outbound-delivery.js';
|
|
23
|
+
import { ResumeBuffer, type IResumeBufferOptions } from './resume-buffer.js';
|
|
24
|
+
import { subscribeSessionEvents } from './session-events.js';
|
|
25
|
+
import { handleClientMessage, parseClientMessage } from './session-message-handler.js';
|
|
26
|
+
|
|
27
|
+
import type { TOutboundDeliver } from './outbound-delivery.js';
|
|
28
|
+
import type { IProtocolSession } from './protocol-session.js';
|
|
29
|
+
import type { IUsageQueryReporters } from './usage-messages.js';
|
|
30
|
+
import type { TSeqServerMessage, TServerMessage } from './wire-messages.js';
|
|
31
|
+
import type { TCommandSurfaceLocality } from '@robota-sdk/agent-interface-command';
|
|
32
|
+
import type { TUsageSurface } from '@robota-sdk/agent-interface-analytics';
|
|
33
|
+
import type { TDriverId } from '@robota-sdk/agent-interface-session';
|
|
34
|
+
|
|
35
|
+
/** The current channel sink — receives a serialized JSON frame to put on the wire. */
|
|
36
|
+
export type TResumeSink = (data: string) => void;
|
|
37
|
+
|
|
38
|
+
/** Options for {@link SessionResumeBridge.attach}. */
|
|
39
|
+
export interface IAttachOptions {
|
|
40
|
+
/**
|
|
41
|
+
* REMOTE-013 E4: on a RECONNECT, HOLD live sink-forwarding until the client's `resume` has replayed the
|
|
42
|
+
* buffered tail — otherwise a live frame emitted between attach and the inbound `resume` would leapfrog the
|
|
43
|
+
* gap frames on the wire, and the client's seq-dedup would then discard the (older, lower-seq) gap. Every
|
|
44
|
+
* live event is already appended to the buffer, so holding loses nothing; `replay()` flushes in order and
|
|
45
|
+
* un-holds. First-pair attach does NOT hold (the client starts at seq 0, frames arrive in order).
|
|
46
|
+
*/
|
|
47
|
+
readonly awaitResume?: boolean;
|
|
48
|
+
/** Sink/carrier-owned failure lifecycle for this attachment only. */
|
|
49
|
+
readonly onDeliveryError: (error: Error, event: string) => void;
|
|
50
|
+
/**
|
|
51
|
+
* ARCH-030: this attachment's carrier backpressure reading, if it has one.
|
|
52
|
+
*
|
|
53
|
+
* Threaded through because the replay path is the burst this budget exists for — a reconnecting
|
|
54
|
+
* peer is handed the whole retained tail at once, and without a reading the boundary here would
|
|
55
|
+
* have no budget at all while the per-channel boundary did.
|
|
56
|
+
*/
|
|
57
|
+
readonly pendingBytes?: () => number | undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface ISessionResumeBridgeOptions {
|
|
61
|
+
readonly session: IProtocolSession;
|
|
62
|
+
readonly buffer?: IResumeBufferOptions;
|
|
63
|
+
/** REMOTE-014 E5: the SERVER-ASSIGNED driver id for this surface, injected into inbound submit/command/prompt-response. */
|
|
64
|
+
readonly driverId?: TDriverId;
|
|
65
|
+
readonly surface?: TUsageSurface;
|
|
66
|
+
readonly personalUsageReporter?: IUsageQueryReporters['personalUsageReporter'];
|
|
67
|
+
readonly usageReporter?: IUsageQueryReporters['usageReporter'];
|
|
68
|
+
readonly storedSessionUsageReporter?: IUsageQueryReporters['storedSessionUsageReporter'];
|
|
69
|
+
/** #3282 §4 part b-2: this bridge is the reconnectable WebRTC path, so it is always `'remote'`. */
|
|
70
|
+
readonly commandSurfaceLocality?: TCommandSurfaceLocality;
|
|
71
|
+
/** See {@link ISessionMessageHandlerOptions.maxFrameBytes}: the channel's limit, not the inbound one. */
|
|
72
|
+
readonly maxFrameBytes?: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export class SessionResumeBridge {
|
|
76
|
+
private readonly session: IProtocolSession;
|
|
77
|
+
private readonly buffer: ResumeBuffer;
|
|
78
|
+
private driverId?: TDriverId;
|
|
79
|
+
private readonly reporters: IUsageQueryReporters;
|
|
80
|
+
private readonly surface?: TUsageSurface;
|
|
81
|
+
private readonly commandSurfaceLocality?: TCommandSurfaceLocality;
|
|
82
|
+
private readonly maxFrameBytes?: number;
|
|
83
|
+
/**
|
|
84
|
+
* Ends with the bridge, not with a channel: a channel drop keeps the session reconnectable, so work
|
|
85
|
+
* started for a hosted app view (a call waiting on its prompt) survives it and is cancelled only when
|
|
86
|
+
* the host gives up on the session.
|
|
87
|
+
*/
|
|
88
|
+
private readonly lifetime = new AbortController();
|
|
89
|
+
private readonly unsubscribe: () => void;
|
|
90
|
+
private onDeliveryError?: IAttachOptions['onDeliveryError'];
|
|
91
|
+
/**
|
|
92
|
+
* ARCH-030: the attachment's outbound boundary — and the only reference this class keeps to the current
|
|
93
|
+
* channel, which is why `dispose()` goes through `detach()` rather than clearing a separate field.
|
|
94
|
+
* Built per `attach` because a boundary LATCHES on its first failure, so a fresh one is exactly what
|
|
95
|
+
* un-latches the session for the next channel. It holds the only try/catch on the frame path.
|
|
96
|
+
*/
|
|
97
|
+
private outbound?: TOutboundDeliver;
|
|
98
|
+
/**
|
|
99
|
+
* The session-lifetime entry every frame takes — event fan-out AND every reply to an inbound frame —
|
|
100
|
+
* before it is seq-stamped and buffered by {@link emit}. Distinct from {@link outbound}, which is the
|
|
101
|
+
* per-attachment exit to the current channel; this one outlives channels because the subscription does.
|
|
102
|
+
*
|
|
103
|
+
* It guards the BUFFERING step, not a carrier, and it latches for the life of the session on purpose:
|
|
104
|
+
* the failure it is placed against is the buffer refusing a frame on capacity, and a resume buffer that
|
|
105
|
+
* cannot accept frames cannot honour a later `resume` either, so there is nothing a reconnect recovers.
|
|
106
|
+
* That is the opposite of {@link outbound}, where the next channel IS the recovery — the two scopes
|
|
107
|
+
* differ because the failures do. (A per-frame serialization failure would leave the buffer intact, but
|
|
108
|
+
* such a frame is undeliverable on every carrier, since each one stringifies it too; it is reported and
|
|
109
|
+
* the carrier torn down, never silently dropped.)
|
|
110
|
+
*/
|
|
111
|
+
private readonly emitBoundary: TOutboundDeliver;
|
|
112
|
+
private disposed = false;
|
|
113
|
+
/** REMOTE-013 E4: while true, live emits are buffered but NOT forwarded — released by `replay()` on reconnect. */
|
|
114
|
+
private holding = false;
|
|
115
|
+
|
|
116
|
+
public constructor(options: ISessionResumeBridgeOptions) {
|
|
117
|
+
this.session = options.session;
|
|
118
|
+
this.buffer = new ResumeBuffer(options.buffer);
|
|
119
|
+
this.driverId = options.driverId;
|
|
120
|
+
this.surface = options.surface;
|
|
121
|
+
this.commandSurfaceLocality = options.commandSurfaceLocality;
|
|
122
|
+
this.maxFrameBytes = options.maxFrameBytes;
|
|
123
|
+
this.reporters = {
|
|
124
|
+
personalUsageReporter: options.personalUsageReporter,
|
|
125
|
+
usageReporter: options.usageReporter,
|
|
126
|
+
storedSessionUsageReporter: options.storedSessionUsageReporter,
|
|
127
|
+
};
|
|
128
|
+
// ONE subscription for the whole session — outlives every channel. Every event → seq-stamped + buffered.
|
|
129
|
+
// CMD-004 Stage D: `ui_intent` is requester-routed against the LATE-BOUND driver id (bound by
|
|
130
|
+
// `setDriverId` after pairing) — routing happens BEFORE buffering, so a foreign surface's intent
|
|
131
|
+
// consumes no seq and can never leak through a later `resume` replay.
|
|
132
|
+
//
|
|
133
|
+
// ARCH-030: built through the factory, never cast — the brand is only worth having if this class
|
|
134
|
+
// does not spell its way around it. `emit` buffers and then hands the stamped frame to whatever
|
|
135
|
+
// boundary is currently ATTACHED, so it does not itself throw on a carrier failure; this boundary
|
|
136
|
+
// exists so that if it ever did, the failure would be reported rather than escaping the session's
|
|
137
|
+
// event listener.
|
|
138
|
+
this.emitBoundary = createOutboundDelivery(
|
|
139
|
+
(message) => this.emit(message),
|
|
140
|
+
(error, event) => this.reportDeliveryError(error, event),
|
|
141
|
+
);
|
|
142
|
+
this.unsubscribe = subscribeSessionEvents(this.session, this.emitBoundary, {
|
|
143
|
+
getSurfaceDriverId: () => this.driverId,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Set the current channel sink (on connect / reconnect). Live messages reach the client; replay is `resume`-driven. */
|
|
148
|
+
public attach(sink: TResumeSink, options: IAttachOptions): void {
|
|
149
|
+
if (this.disposed) return;
|
|
150
|
+
this.onDeliveryError = options.onDeliveryError;
|
|
151
|
+
this.outbound = createOutboundDelivery(
|
|
152
|
+
(message) => sink(JSON.stringify(message)),
|
|
153
|
+
(error, event) => this.reportDeliveryError(error, event),
|
|
154
|
+
options.pendingBytes,
|
|
155
|
+
);
|
|
156
|
+
// On a reconnect, hold live forwarding until `resume` flushes the buffered tail (avoids the live-vs-replay race).
|
|
157
|
+
this.holding = options.awaitResume === true;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Clear the sink (channel drop). Buffering continues so gap output is retained for the next `resume`. */
|
|
161
|
+
public detach(): void {
|
|
162
|
+
this.outbound = undefined;
|
|
163
|
+
this.onDeliveryError = undefined;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* REMOTE-014 E5: bind the SERVER-ASSIGNED driver id (the E3 `deviceId`) once the peer pairs — the bridge
|
|
168
|
+
* injects it into every subsequent inbound submit/command/prompt-response for co-drive attribution.
|
|
169
|
+
*/
|
|
170
|
+
public setDriverId(driverId: TDriverId): void {
|
|
171
|
+
this.driverId = driverId;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Route one inbound channel frame: `resume`/`ack` handled here; everything else → the session. */
|
|
175
|
+
public onClientMessage(data: string): void {
|
|
176
|
+
if (this.disposed) return;
|
|
177
|
+
const msg = parseClientMessage(data, this.emitBoundary);
|
|
178
|
+
if (!msg) return;
|
|
179
|
+
if (msg.type === 'resume') {
|
|
180
|
+
this.replay(msg.lastSeq);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (msg.type === 'ack') {
|
|
184
|
+
this.buffer.ackThrough(msg.seq);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
// Session control/query/background/prompt-response — responses funnel back through `emit` (seq'd + buffered).
|
|
188
|
+
// REMOTE-014 E5: inject the server-assigned driver id (submit/prompt-response attribution).
|
|
189
|
+
handleClientMessage(
|
|
190
|
+
this.session,
|
|
191
|
+
this.emitBoundary,
|
|
192
|
+
msg,
|
|
193
|
+
this.driverId,
|
|
194
|
+
this.reporters,
|
|
195
|
+
this.surface,
|
|
196
|
+
undefined,
|
|
197
|
+
undefined,
|
|
198
|
+
this.commandSurfaceLocality,
|
|
199
|
+
{
|
|
200
|
+
signal: this.lifetime.signal,
|
|
201
|
+
...(this.maxFrameBytes !== undefined ? { maxFrameBytes: this.maxFrameBytes } : {}),
|
|
202
|
+
},
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Unsubscribe from the session (host reconnect-window ceiling / teardown). Idempotent. */
|
|
207
|
+
public dispose(): void {
|
|
208
|
+
if (this.disposed) return;
|
|
209
|
+
this.disposed = true;
|
|
210
|
+
this.lifetime.abort();
|
|
211
|
+
// Through `detach`, not a field assignment: the boundary's closure is what holds the channel, so
|
|
212
|
+
// clearing anything else released nothing and left teardown documented but not performed.
|
|
213
|
+
this.detach();
|
|
214
|
+
this.unsubscribe();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Diagnostics/tests: the last seq assigned. */
|
|
218
|
+
public get lastSeq(): number {
|
|
219
|
+
return this.buffer.lastSeq;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Stamp a seq, retain in the buffer, and forward to the current sink — UNLESS holding for a reconnect replay.
|
|
224
|
+
*
|
|
225
|
+
* ARCH-030: the `buffer.append` happens BEFORE the boundary, deliberately. The boundary latches on its
|
|
226
|
+
* first failure and drops everything after it, so a frame appended afterwards would be lost — appending
|
|
227
|
+
* first means a dropped frame is still in the un-acked tail and still replays on the next `resume`.
|
|
228
|
+
*/
|
|
229
|
+
private emit(message: TServerMessage): void {
|
|
230
|
+
if (this.disposed) return;
|
|
231
|
+
const seq = this.buffer.append(message);
|
|
232
|
+
if (this.holding) return; // buffered only; `replay()` will flush it in order and release the hold
|
|
233
|
+
this.deliverFrame({ ...message, seq } as TSeqServerMessage);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Replay the buffered tail after `lastSeq` (or `resume_gap` on overrun), then RELEASE the reconnect hold so
|
|
238
|
+
* subsequent live frames flow in order behind the flushed gap.
|
|
239
|
+
*
|
|
240
|
+
* A failing sink reports ONCE across the whole tail: the boundary latches on the first failure and every
|
|
241
|
+
* remaining frame is dropped silently. Those frames stay un-acked in the buffer and replay on the next
|
|
242
|
+
* attachment. Before ARCH-030 the single report was a side effect of `detach()` running mid-loop; now it
|
|
243
|
+
* is the boundary's stated contract.
|
|
244
|
+
*/
|
|
245
|
+
private replay(lastSeq: number): void {
|
|
246
|
+
const tail = this.buffer.tailAfter(lastSeq);
|
|
247
|
+
if (tail.kind === 'overrun') {
|
|
248
|
+
// `resume_gap` is neither stamped nor buffered: the client answers it with a full `get-messages`
|
|
249
|
+
// refresh, so there is nothing for it to resume from.
|
|
250
|
+
this.deliverFrame({ type: 'resume_gap' });
|
|
251
|
+
this.holding = false; // client will full-refresh via get-messages; let live frames flow
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
for (const frame of tail.frames) {
|
|
255
|
+
this.deliverFrame({ ...frame.message, seq: frame.seq } as TSeqServerMessage);
|
|
256
|
+
}
|
|
257
|
+
this.holding = false; // gap flushed in order — resume live forwarding
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** The ONE outbound exit from this class. No frame reaches the sink except through the attachment's boundary. */
|
|
261
|
+
private deliverFrame(message: TServerMessage): void {
|
|
262
|
+
this.outbound?.(message);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Detach the failed sink but retain the frame, then notify its attachment owner. */
|
|
266
|
+
private reportDeliveryError(error: Error, event: string): void {
|
|
267
|
+
const onDeliveryError = this.onDeliveryError;
|
|
268
|
+
this.detach();
|
|
269
|
+
try {
|
|
270
|
+
onDeliveryError?.(error, event);
|
|
271
|
+
} catch {
|
|
272
|
+
// Carrier diagnostics cannot corrupt the retained buffer or the committed operation.
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { TOutboundDeliver } from './outbound-delivery.js';
|
|
2
|
+
import type { IProtocolSession } from './protocol-session.js';
|
|
3
|
+
import type { TClientMessage } from './wire-messages.js';
|
|
4
|
+
import type { TCommandSurfaceLocality } from '@robota-sdk/agent-interface-command';
|
|
5
|
+
import type { ISettingsSnapshot, TSettingsPatch } from '@robota-sdk/agent-interface-session';
|
|
6
|
+
|
|
7
|
+
type TSettingsMessage = Extract<TClientMessage, { type: 'get-settings' | 'update-settings' }>;
|
|
8
|
+
|
|
9
|
+
export function isSettingsMessage(msg: TClientMessage): msg is TSettingsMessage {
|
|
10
|
+
return msg.type === 'get-settings' || msg.type === 'update-settings';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** What applying a patch did: the fresh snapshot, or why nothing was written. */
|
|
14
|
+
export type TSettingsUpdateOutcome =
|
|
15
|
+
| { readonly ok: true; readonly settings: ISettingsSnapshot }
|
|
16
|
+
| {
|
|
17
|
+
readonly ok: false;
|
|
18
|
+
readonly code: 'not_available' | 'invalid' | 'refused' | 'update_failed';
|
|
19
|
+
readonly message: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* #3282 §4a: host-owned read/write for the Settings screen, supplied by the composition root the
|
|
24
|
+
* same way `IUsageQueryReporters` supplies usage reads — this package only correlates the request
|
|
25
|
+
* and carries the result. `updateSettings` applies through the SAME function the matching slash
|
|
26
|
+
* command uses (issue #3282 §4: "one code path, so the behavior matches the TUI"), so whatever a
|
|
27
|
+
* command would refuse on this surface is refused here too.
|
|
28
|
+
*/
|
|
29
|
+
export interface ISettingsReporter {
|
|
30
|
+
getSettings(
|
|
31
|
+
session: IProtocolSession,
|
|
32
|
+
locality?: TCommandSurfaceLocality,
|
|
33
|
+
): ISettingsSnapshot | Promise<ISettingsSnapshot>;
|
|
34
|
+
/**
|
|
35
|
+
* Applies through the SAME function the matching slash command uses. `locality` (#3282 §4 part
|
|
36
|
+
* b-2) is forwarded to that command exactly as the transport received it, so a command that
|
|
37
|
+
* refuses a remote surface (installing a plugin) refuses identically here.
|
|
38
|
+
*/
|
|
39
|
+
updateSettings(
|
|
40
|
+
session: IProtocolSession,
|
|
41
|
+
patch: TSettingsPatch,
|
|
42
|
+
locality?: TCommandSurfaceLocality,
|
|
43
|
+
): TSettingsUpdateOutcome | Promise<TSettingsUpdateOutcome>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function handleSettingsMessage(
|
|
47
|
+
session: IProtocolSession,
|
|
48
|
+
deliver: TOutboundDeliver,
|
|
49
|
+
msg: TSettingsMessage,
|
|
50
|
+
reporter: ISettingsReporter | undefined,
|
|
51
|
+
locality?: TCommandSurfaceLocality,
|
|
52
|
+
): void {
|
|
53
|
+
if (!reporter) {
|
|
54
|
+
deliverSettingsError(
|
|
55
|
+
deliver,
|
|
56
|
+
msg.requestId,
|
|
57
|
+
'not_available',
|
|
58
|
+
'Settings are not available on this host.',
|
|
59
|
+
);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
if (msg.type === 'get-settings') {
|
|
64
|
+
void Promise.resolve(reporter.getSettings(session, locality)).then(
|
|
65
|
+
(settings) => deliver({ type: 'settings', requestId: msg.requestId, settings }),
|
|
66
|
+
(error) =>
|
|
67
|
+
deliverSettingsError(deliver, msg.requestId, 'update_failed', failureMessage(error)),
|
|
68
|
+
);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
void Promise.resolve(reporter.updateSettings(session, msg.patch, locality)).then(
|
|
72
|
+
(outcome) => {
|
|
73
|
+
if (outcome.ok) {
|
|
74
|
+
deliver({ type: 'settings', requestId: msg.requestId, settings: outcome.settings });
|
|
75
|
+
} else {
|
|
76
|
+
deliverSettingsError(deliver, msg.requestId, outcome.code, outcome.message);
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
(error) =>
|
|
80
|
+
deliverSettingsError(deliver, msg.requestId, 'update_failed', failureMessage(error)),
|
|
81
|
+
);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
deliverSettingsError(
|
|
84
|
+
deliver,
|
|
85
|
+
msg.requestId,
|
|
86
|
+
'update_failed',
|
|
87
|
+
failureMessage(error instanceof Error ? error : String(error)),
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function deliverSettingsError(
|
|
93
|
+
deliver: TOutboundDeliver,
|
|
94
|
+
requestId: string,
|
|
95
|
+
code: 'not_available' | 'invalid' | 'refused' | 'update_failed',
|
|
96
|
+
message: string,
|
|
97
|
+
): void {
|
|
98
|
+
deliver({ type: 'settings_error', requestId, code, message });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function failureMessage(error: Error | string): string {
|
|
102
|
+
return error instanceof Error ? error.message : String(error);
|
|
103
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { MAX_INBOUND_FRAME_BYTES } from './message-decoders.js';
|
|
2
|
+
|
|
3
|
+
import type { TOutboundDeliver } from './outbound-delivery.js';
|
|
4
|
+
import type { IProtocolSession } from './protocol-session.js';
|
|
5
|
+
import type { TClientMessage } from './wire-messages.js';
|
|
6
|
+
import type {
|
|
7
|
+
IPersonalUsageReport,
|
|
8
|
+
IPersonalUsageRequest,
|
|
9
|
+
IUsageBySourceReport,
|
|
10
|
+
} from '@robota-sdk/agent-interface-analytics';
|
|
11
|
+
|
|
12
|
+
type TJsonValue =
|
|
13
|
+
string | number | boolean | null | readonly TJsonValue[] | { readonly [key: string]: TJsonValue };
|
|
14
|
+
|
|
15
|
+
export interface IUsageQueryReporters {
|
|
16
|
+
readonly personalUsageReporter:
|
|
17
|
+
| ((request: IPersonalUsageRequest) => IPersonalUsageReport | Promise<IPersonalUsageReport>)
|
|
18
|
+
| undefined;
|
|
19
|
+
readonly usageReporter:
|
|
20
|
+
| ((session: IProtocolSession) => IUsageBySourceReport | Promise<IUsageBySourceReport>)
|
|
21
|
+
| undefined;
|
|
22
|
+
readonly storedSessionUsageReporter:
|
|
23
|
+
((sessionId: string) => IUsageBySourceReport | Promise<IUsageBySourceReport>) | undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type TMalformedUsageRequest =
|
|
27
|
+
| { type: 'personal'; requestId: string }
|
|
28
|
+
| { type: 'stored-session'; requestId: string; sessionId: string };
|
|
29
|
+
|
|
30
|
+
function isJsonObject(value: TJsonValue): value is { readonly [key: string]: TJsonValue } {
|
|
31
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function optionalNonEmptyString(value: TJsonValue | undefined): string | undefined {
|
|
35
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function malformedUsageRequest(data: string): TMalformedUsageRequest | undefined {
|
|
39
|
+
if (new TextEncoder().encode(data).byteLength > MAX_INBOUND_FRAME_BYTES) return undefined;
|
|
40
|
+
try {
|
|
41
|
+
const value = JSON.parse(data) as TJsonValue;
|
|
42
|
+
if (!isJsonObject(value)) return undefined;
|
|
43
|
+
const requestId = optionalNonEmptyString(value['requestId']);
|
|
44
|
+
if (!requestId) return undefined;
|
|
45
|
+
if (value['type'] === 'get-personal-usage-report') return { type: 'personal', requestId };
|
|
46
|
+
const sessionId = optionalNonEmptyString(value['sessionId']);
|
|
47
|
+
return value['type'] === 'get-stored-session-usage-report' && sessionId
|
|
48
|
+
? { type: 'stored-session', requestId, sessionId }
|
|
49
|
+
: undefined;
|
|
50
|
+
} catch {
|
|
51
|
+
// allow-fallback: malformed JSON has no trustworthy request id to correlate, so the caller emits
|
|
52
|
+
// the protocol's uncorrelated decode error without echoing attacker-controlled content.
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function handleUsageQueryMessage(
|
|
58
|
+
session: IProtocolSession,
|
|
59
|
+
deliver: TOutboundDeliver,
|
|
60
|
+
msg: TClientMessage,
|
|
61
|
+
reporters: IUsageQueryReporters,
|
|
62
|
+
): boolean {
|
|
63
|
+
if (msg.type === 'get-personal-usage-report') {
|
|
64
|
+
handlePersonalUsageQuery(deliver, msg, reporters.personalUsageReporter);
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
if (msg.type === 'get-stored-session-usage-report') {
|
|
68
|
+
handleStoredSessionUsageQuery(deliver, msg, reporters.storedSessionUsageReporter);
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
if (msg.type === 'get-usage-report') {
|
|
72
|
+
handleCurrentUsageQuery(session, deliver, reporters.usageReporter);
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function handleCurrentUsageQuery(
|
|
79
|
+
session: IProtocolSession,
|
|
80
|
+
deliver: TOutboundDeliver,
|
|
81
|
+
reporter: IUsageQueryReporters['usageReporter'],
|
|
82
|
+
): void {
|
|
83
|
+
if (!reporter) {
|
|
84
|
+
deliver({
|
|
85
|
+
type: 'protocol_error',
|
|
86
|
+
message: 'Per-session usage reporting is not available on this host.',
|
|
87
|
+
});
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
void Promise.resolve(reporter(session)).then(
|
|
92
|
+
(report) => deliver({ type: 'usage_report', report }),
|
|
93
|
+
(error) => deliver({ type: 'protocol_error', message: failureMessage(error) }),
|
|
94
|
+
);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
deliver({
|
|
97
|
+
type: 'protocol_error',
|
|
98
|
+
message: failureMessage(error instanceof Error ? error : String(error)),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function handleStoredSessionUsageQuery(
|
|
104
|
+
deliver: TOutboundDeliver,
|
|
105
|
+
msg: Extract<TClientMessage, { type: 'get-stored-session-usage-report' }>,
|
|
106
|
+
reporter: IUsageQueryReporters['storedSessionUsageReporter'],
|
|
107
|
+
): void {
|
|
108
|
+
if (!reporter) {
|
|
109
|
+
deliverStoredSessionUsageError(
|
|
110
|
+
deliver,
|
|
111
|
+
msg,
|
|
112
|
+
'not_available',
|
|
113
|
+
'Stored-session usage reporting is not available on this host.',
|
|
114
|
+
);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
void Promise.resolve(reporter(msg.sessionId)).then(
|
|
119
|
+
(report) =>
|
|
120
|
+
deliver({
|
|
121
|
+
type: 'stored_session_usage_report',
|
|
122
|
+
requestId: msg.requestId,
|
|
123
|
+
sessionId: msg.sessionId,
|
|
124
|
+
report,
|
|
125
|
+
}),
|
|
126
|
+
(error) =>
|
|
127
|
+
deliverStoredSessionUsageError(deliver, msg, 'report_failed', failureMessage(error)),
|
|
128
|
+
);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
deliverStoredSessionUsageError(
|
|
131
|
+
deliver,
|
|
132
|
+
msg,
|
|
133
|
+
'report_failed',
|
|
134
|
+
failureMessage(error instanceof Error ? error : String(error)),
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function deliverStoredSessionUsageError(
|
|
140
|
+
deliver: TOutboundDeliver,
|
|
141
|
+
msg: Extract<TClientMessage, { type: 'get-stored-session-usage-report' }>,
|
|
142
|
+
code: 'not_available' | 'report_failed',
|
|
143
|
+
message: string,
|
|
144
|
+
): void {
|
|
145
|
+
deliver({
|
|
146
|
+
type: 'stored_session_usage_report_error',
|
|
147
|
+
requestId: msg.requestId,
|
|
148
|
+
sessionId: msg.sessionId,
|
|
149
|
+
code,
|
|
150
|
+
message,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function handlePersonalUsageQuery(
|
|
155
|
+
deliver: TOutboundDeliver,
|
|
156
|
+
msg: Extract<TClientMessage, { type: 'get-personal-usage-report' }>,
|
|
157
|
+
reporter: IUsageQueryReporters['personalUsageReporter'],
|
|
158
|
+
): void {
|
|
159
|
+
if (!reporter) {
|
|
160
|
+
deliverPersonalUsageError(
|
|
161
|
+
deliver,
|
|
162
|
+
msg.requestId,
|
|
163
|
+
'not_available',
|
|
164
|
+
'Personal usage reporting is not available on this host.',
|
|
165
|
+
);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
void Promise.resolve(reporter({ period: msg.period, timezone: msg.timezone })).then(
|
|
170
|
+
(report) => deliver({ type: 'personal_usage_report', requestId: msg.requestId, report }),
|
|
171
|
+
(error) =>
|
|
172
|
+
deliverPersonalUsageError(deliver, msg.requestId, 'report_failed', failureMessage(error)),
|
|
173
|
+
);
|
|
174
|
+
} catch (error) {
|
|
175
|
+
deliverPersonalUsageError(
|
|
176
|
+
deliver,
|
|
177
|
+
msg.requestId,
|
|
178
|
+
'report_failed',
|
|
179
|
+
failureMessage(error instanceof Error ? error : String(error)),
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function deliverPersonalUsageError(
|
|
185
|
+
deliver: TOutboundDeliver,
|
|
186
|
+
requestId: string,
|
|
187
|
+
code: 'not_available' | 'report_failed',
|
|
188
|
+
message: string,
|
|
189
|
+
): void {
|
|
190
|
+
deliver({ type: 'personal_usage_report_error', requestId, code, message });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function failureMessage(error: Error | TJsonValue | undefined): string {
|
|
194
|
+
return error instanceof Error ? error.message : String(error);
|
|
195
|
+
}
|