@robota-sdk/agent-transport 3.0.0-beta.82 → 3.0.0-beta.83

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 (53) hide show
  1. package/CHANGELOG.md +752 -0
  2. package/dist/browser/client.d.ts +2 -2
  3. package/dist/browser/client.js +1 -1
  4. package/dist/browser/index.d.ts +31 -11
  5. package/dist/browser/index.d.ts.map +1 -1
  6. package/dist/browser/index.js +1 -1
  7. package/dist/browser/index.js.map +1 -1
  8. package/dist/browser/observer-messages-Bx-xReUQ.js +2 -0
  9. package/dist/browser/observer-messages-Bx-xReUQ.js.map +1 -0
  10. package/dist/browser/{message-decoders-BB8n-H2X.d.ts → observer-messages-DC_8VHk9.d.ts} +104 -7
  11. package/dist/browser/observer-messages-DC_8VHk9.d.ts.map +1 -0
  12. package/dist/node/index.cjs +1 -1
  13. package/dist/node/index.d.cts +131 -14
  14. package/dist/node/index.d.cts.map +1 -1
  15. package/dist/node/index.d.ts +131 -14
  16. package/dist/node/index.d.ts.map +1 -1
  17. package/dist/node/index.js +1 -1
  18. package/dist/node/index.js.map +1 -1
  19. package/dist/node/node.cjs +1 -1
  20. package/dist/node/node.d.cts +69 -1
  21. package/dist/node/node.d.cts.map +1 -1
  22. package/dist/node/node.d.ts +70 -2
  23. package/dist/node/node.d.ts.map +1 -1
  24. package/dist/node/node.js +1 -1
  25. package/dist/node/node.js.map +1 -1
  26. package/package.json +13 -11
  27. package/src/__tests__/bearer-resource-gate.test.ts +120 -0
  28. package/src/__tests__/history-attached-budget.test.ts +216 -0
  29. package/src/__tests__/message-decoders.test.ts +201 -5
  30. package/src/__tests__/session-detail-loop-status.test.ts +169 -0
  31. package/src/__tests__/session-directory-messages.test.ts +192 -0
  32. package/src/__tests__/session-history-wire.test.ts +342 -0
  33. package/src/__tests__/session-message-handler-observe.test.ts +193 -0
  34. package/src/__tests__/session-message-handler.test.ts +82 -1
  35. package/src/__tests__/ws-broadcast-events.test.ts +10 -0
  36. package/src/client.ts +9 -1
  37. package/src/index.ts +14 -2
  38. package/src/loop-control-messages.ts +34 -0
  39. package/src/message-decoders.ts +82 -4
  40. package/src/node/bearer-resource-gate.ts +291 -0
  41. package/src/node/index.ts +13 -0
  42. package/src/observer-messages.ts +36 -0
  43. package/src/open-prompts.ts +76 -0
  44. package/src/outbound-delivery.ts +11 -2
  45. package/src/protocol-session.ts +7 -1
  46. package/src/session-directory-messages.ts +85 -0
  47. package/src/session-events.ts +93 -18
  48. package/src/session-message-handler.ts +53 -8
  49. package/src/session-query-messages.ts +105 -4
  50. package/src/wire-messages.ts +105 -7
  51. package/dist/browser/message-decoders-BB8n-H2X.d.ts.map +0 -1
  52. package/dist/browser/message-decoders-CDmDoZPR.js +0 -2
  53. package/dist/browser/message-decoders-CDmDoZPR.js.map +0 -1
@@ -0,0 +1,291 @@
1
+ /**
2
+ * The shared admission gate of an OAuth resource server reached over HTTP: RFC 6750 bearer challenges,
3
+ * RFC 9728 protected-resource metadata, the public-URL name checks, and a failure-only throttle per
4
+ * peer address. Every remote HTTP carrier that admits by access token composes these pieces, so the
5
+ * rules are one set of code rather than one per carrier.
6
+ *
7
+ * The host is reached through its PUBLIC URL, usually behind a reverse proxy, so every name the gate
8
+ * checks comes from that URL rather than from the listener: the Host and Origin a request must carry
9
+ * (the proxy must preserve Host) and the paths it serves. The listener's own address is never a name a
10
+ * client uses.
11
+ *
12
+ * Refusals answer with an empty body and, for a token problem, only the standard challenge: an error
13
+ * code from RFC 6750 and where the metadata lives. Only failures are counted, so a peer holding a valid
14
+ * token is never throttled, however many failures share its address. What a carrier reports about a
15
+ * refused peer is a coarse address class, never the address.
16
+ *
17
+ * This module binds no listener; a carrier owns its socket and calls these per request.
18
+ */
19
+
20
+ import { BlockList, isIP } from 'node:net';
21
+
22
+ import type { IncomingMessage, ServerResponse } from 'node:http';
23
+
24
+ const WELL_KNOWN_PREFIX = '/.well-known/oauth-protected-resource';
25
+ /** Window over which one address's failures are counted. */
26
+ const FAILURE_WINDOW_MS = 60_000;
27
+ /** Failures one address may have in a window before its further failures answer 429. */
28
+ const MAX_FAILURES_PER_WINDOW = 20;
29
+ /** Addresses tracked at once; the oldest is forgotten first, so a spray cannot grow memory. */
30
+ const MAX_TRACKED_ADDRESSES = 4096;
31
+ /** RFC 6749 scope-token characters: printable ASCII except space, `"` and `\`. */
32
+ const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
33
+
34
+ /** A coarse class of a peer's address; the address itself is never reported. */
35
+ export type TRemoteAddressClass = 'loopback' | 'private' | 'public' | 'unknown';
36
+
37
+ /** Where a refused request came from, and whether its address is over the failure budget. */
38
+ export interface IBearerFailure {
39
+ readonly remote: TRemoteAddressClass;
40
+ readonly throttled: boolean;
41
+ readonly retryAfterSeconds: number;
42
+ }
43
+
44
+ /** The public-facing identity of one resource server and its per-address failure budget. */
45
+ export interface IBearerResourceServer {
46
+ /** The parsed public URL; its path is the resource's base path. */
47
+ readonly url: URL;
48
+ /**
49
+ * Host and Origin must name the public URL. On a mismatch the 403 is written and false returned;
50
+ * nothing is counted, since no credential was judged.
51
+ */
52
+ checkNames(req: IncomingMessage, res: ServerResponse): boolean;
53
+ /** Count one failure against the request's peer. */
54
+ fail(req: IncomingMessage): IBearerFailure;
55
+ /** The request's peer class without counting anything. */
56
+ remote(req: IncomingMessage): TRemoteAddressClass;
57
+ }
58
+
59
+ /** The challenges and metadata of one protected resource (one audience). */
60
+ export interface IProtectedResource {
61
+ /** The RFC 9728 path clients fetch the metadata from. */
62
+ readonly wellKnownPath: string;
63
+ readonly metadata: string;
64
+ readonly challenges: {
65
+ readonly missing: string;
66
+ readonly invalid: string;
67
+ readonly scope: string;
68
+ };
69
+ }
70
+
71
+ const LOOPBACK_RANGES = new BlockList();
72
+ LOOPBACK_RANGES.addSubnet('127.0.0.0', 8, 'ipv4');
73
+ LOOPBACK_RANGES.addAddress('::1', 'ipv6');
74
+ const PRIVATE_RANGES = new BlockList();
75
+ PRIVATE_RANGES.addSubnet('10.0.0.0', 8, 'ipv4');
76
+ PRIVATE_RANGES.addSubnet('172.16.0.0', 12, 'ipv4');
77
+ PRIVATE_RANGES.addSubnet('192.168.0.0', 16, 'ipv4');
78
+ PRIVATE_RANGES.addSubnet('169.254.0.0', 16, 'ipv4');
79
+ PRIVATE_RANGES.addSubnet('100.64.0.0', 10, 'ipv4');
80
+ PRIVATE_RANGES.addSubnet('fc00::', 7, 'ipv6');
81
+ PRIVATE_RANGES.addSubnet('fe80::', 10, 'ipv6');
82
+
83
+ /** A literal address in one spelling: IPv4-mapped IPv6 folded to IPv4, IPv6 lowercased. */
84
+ function normalizeAddress(value: string | undefined): string | undefined {
85
+ if (value === undefined) return undefined;
86
+ const text = value.trim().toLowerCase();
87
+ const mapped = text.startsWith('::ffff:') ? text.slice('::ffff:'.length) : undefined;
88
+ if (mapped !== undefined && isIP(mapped) === 4) return mapped;
89
+ return isIP(text) === 0 ? undefined : text;
90
+ }
91
+
92
+ function classifyAddress(address: string | undefined): TRemoteAddressClass {
93
+ if (address === undefined) return 'unknown';
94
+ const family = isIP(address) === 4 ? 'ipv4' : 'ipv6';
95
+ if (LOOPBACK_RANGES.check(address, family)) return 'loopback';
96
+ if (PRIVATE_RANGES.check(address, family)) return 'private';
97
+ return 'public';
98
+ }
99
+
100
+ /** Parse a resource server's public URL: plain `https`, no credentials, query or fragment. */
101
+ export function parsePublicHttpsUrl(publicUrl: string, label: string): URL {
102
+ let url: URL;
103
+ try {
104
+ url = new URL(publicUrl);
105
+ } catch {
106
+ throw new Error(`${label} public URL must be an absolute https URL`);
107
+ }
108
+ if (url.protocol !== 'https:') throw new Error(`${label} public URL must use https`);
109
+ if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {
110
+ throw new Error(`${label} public URL must not carry credentials, a query or a fragment`);
111
+ }
112
+ return url;
113
+ }
114
+
115
+ interface IFailureWindow {
116
+ count: number;
117
+ startedAt: number;
118
+ }
119
+
120
+ /** Counts failures per address in fixed windows. Only failures are ever recorded here. */
121
+ function createFailureCounter(now: () => number) {
122
+ const windows = new Map<string, IFailureWindow>();
123
+ return (address: string): { throttled: boolean; retryAfterSeconds: number } => {
124
+ const at = now();
125
+ let entry = windows.get(address);
126
+ if (entry === undefined || at - entry.startedAt >= FAILURE_WINDOW_MS) {
127
+ windows.delete(address);
128
+ if (windows.size >= MAX_TRACKED_ADDRESSES) {
129
+ for (const [key, value] of windows) {
130
+ if (at - value.startedAt >= FAILURE_WINDOW_MS) windows.delete(key);
131
+ }
132
+ const oldest = windows.keys().next();
133
+ if (windows.size >= MAX_TRACKED_ADDRESSES && oldest.done !== true) {
134
+ windows.delete(oldest.value);
135
+ }
136
+ }
137
+ entry = { count: 0, startedAt: at };
138
+ windows.set(address, entry);
139
+ }
140
+ entry.count += 1;
141
+ const remainingMs = FAILURE_WINDOW_MS - (at - entry.startedAt);
142
+ return {
143
+ throttled: entry.count > MAX_FAILURES_PER_WINDOW,
144
+ retryAfterSeconds: Math.max(1, Math.ceil(remainingMs / 1000)),
145
+ };
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Build the public identity of a resource server. Throws when the public URL is not plain `https`,
151
+ * or a trusted proxy is not a literal address. `label` names the carrier in those messages.
152
+ */
153
+ export function createBearerResourceServer(options: {
154
+ readonly publicUrl: string;
155
+ /** Proxy addresses whose `X-Forwarded-For` is believed. Absent: the header is ignored. */
156
+ readonly trustedProxies?: readonly string[];
157
+ readonly label: string;
158
+ readonly now?: () => number;
159
+ }): IBearerResourceServer {
160
+ const url = parsePublicHttpsUrl(options.publicUrl, options.label);
161
+ const trustedProxies = new Set<string>();
162
+ for (const proxy of options.trustedProxies ?? []) {
163
+ const address = normalizeAddress(proxy);
164
+ if (address === undefined) {
165
+ throw new Error(`${options.label} trusted proxy must be a literal IP address`);
166
+ }
167
+ trustedProxies.add(address);
168
+ }
169
+ const expectedHosts = new Set([url.host]);
170
+ if (url.port === '') expectedHosts.add(`${url.hostname}:443`);
171
+ const failures = createFailureCounter(options.now ?? (() => performance.now()));
172
+
173
+ function remoteAddress(req: IncomingMessage): string | undefined {
174
+ const peer = normalizeAddress(req.socket.remoteAddress);
175
+ if (peer === undefined || !trustedProxies.has(peer)) return peer;
176
+ const header = req.headers['x-forwarded-for'];
177
+ const hops = (Array.isArray(header) ? header.join(',') : (header ?? '')).split(',');
178
+ // Walk from the proxy inward: the nearest hop not itself a trusted proxy is the client, as the
179
+ // trusted proxy saw it. Hops further left were written by the client and are not believed.
180
+ for (let index = hops.length - 1; index >= 0; index -= 1) {
181
+ const hop = normalizeAddress(hops[index]);
182
+ if (hop === undefined) return peer;
183
+ if (!trustedProxies.has(hop)) return hop;
184
+ }
185
+ return peer;
186
+ }
187
+
188
+ return {
189
+ url,
190
+ checkNames(req, res) {
191
+ const host = req.headers.host?.toLowerCase();
192
+ const origin = req.headers.origin;
193
+ if (
194
+ host === undefined ||
195
+ !expectedHosts.has(host) ||
196
+ (origin !== undefined && origin !== url.origin)
197
+ ) {
198
+ res.writeHead(403).end();
199
+ return false;
200
+ }
201
+ return true;
202
+ },
203
+ fail(req) {
204
+ const address = remoteAddress(req);
205
+ return { remote: classifyAddress(address), ...failures(address ?? 'unknown') };
206
+ },
207
+ remote(req) {
208
+ return classifyAddress(remoteAddress(req));
209
+ },
210
+ };
211
+ }
212
+
213
+ /**
214
+ * Describe one protected resource: where its RFC 9728 metadata lives and the challenges that point
215
+ * there. Throws for a non-`https` issuer, or no scope or a scope a challenge cannot quote.
216
+ */
217
+ export function describeProtectedResource(options: {
218
+ /** The resource identifier (`aud`), an `https` URL. */
219
+ readonly resource: string;
220
+ readonly issuer: string;
221
+ readonly scopes: readonly string[];
222
+ readonly label: string;
223
+ }): IProtectedResource {
224
+ const url = parsePublicHttpsUrl(options.resource, options.label);
225
+ let issuer: URL;
226
+ try {
227
+ issuer = new URL(options.issuer);
228
+ } catch {
229
+ throw new Error(`${options.label} authorization issuer must be an absolute https URL`);
230
+ }
231
+ if (issuer.protocol !== 'https:') {
232
+ throw new Error(`${options.label} authorization issuer must use https`);
233
+ }
234
+ if (options.scopes.length === 0 || !options.scopes.every((scope) => SCOPE_TOKEN.test(scope))) {
235
+ throw new Error(`${options.label} authorization needs at least one valid scope`);
236
+ }
237
+ // RFC 9728 §3.1: the well-known segment goes between the host and the resource's path, with a
238
+ // lone terminating slash dropped.
239
+ const wellKnownPath = `${WELL_KNOWN_PREFIX}${url.pathname === '/' ? '' : url.pathname}`;
240
+ const metadataUrl = `${url.origin}${wellKnownPath}`;
241
+ const scopeList = options.scopes.join(' ');
242
+ return {
243
+ wellKnownPath,
244
+ metadata: JSON.stringify({
245
+ resource: options.resource,
246
+ authorization_servers: [options.issuer],
247
+ scopes_supported: [...options.scopes],
248
+ bearer_methods_supported: ['header'],
249
+ }),
250
+ challenges: {
251
+ missing: `Bearer resource_metadata="${metadataUrl}"`,
252
+ invalid: `Bearer error="invalid_token", resource_metadata="${metadataUrl}"`,
253
+ scope: `Bearer error="insufficient_scope", scope="${scopeList}", resource_metadata="${metadataUrl}"`,
254
+ },
255
+ };
256
+ }
257
+
258
+ /** Answer a metadata request: GET only, the JSON document, nothing else. */
259
+ export function serveProtectedResourceMetadata(
260
+ req: IncomingMessage,
261
+ res: ServerResponse,
262
+ resource: IProtectedResource,
263
+ ): void {
264
+ if (req.method !== 'GET') {
265
+ res.writeHead(405, { Allow: 'GET' }).end();
266
+ return;
267
+ }
268
+ res.writeHead(200, { 'Content-Type': 'application/json' }).end(resource.metadata);
269
+ }
270
+
271
+ /**
272
+ * Answer a refused bearer token after its failure was counted: 429 once the peer is over budget,
273
+ * 403 `insufficient_scope` for a missing scope, otherwise 401 with the missing-token or
274
+ * `invalid_token` challenge. Always an empty body.
275
+ */
276
+ export function refuseBearerToken(
277
+ res: ServerResponse,
278
+ resource: IProtectedResource,
279
+ refusal: 'missing-token' | 'missing-scope' | 'invalid-token',
280
+ failure: IBearerFailure,
281
+ ): void {
282
+ if (failure.throttled) {
283
+ res.writeHead(429, { 'Retry-After': String(failure.retryAfterSeconds) }).end();
284
+ } else if (refusal === 'missing-scope') {
285
+ res.writeHead(403, { 'WWW-Authenticate': resource.challenges.scope }).end();
286
+ } else {
287
+ const challenge =
288
+ refusal === 'missing-token' ? resource.challenges.missing : resource.challenges.invalid;
289
+ res.writeHead(401, { 'WWW-Authenticate': challenge }).end();
290
+ }
291
+ }
package/src/node/index.ts CHANGED
@@ -8,6 +8,19 @@ export { sealHandoffRecord, verifyHandoffPayload } from './handoff-manifest.js';
8
8
  export type { IIntegrityVerdict, TIntegrityFailure } from './handoff-manifest.js';
9
9
  export { createAccessTokenVerifier } from './access-token-verifier.js';
10
10
  export type { IAccessTokenVerifierDeps } from './access-token-verifier.js';
11
+ export {
12
+ createBearerResourceServer,
13
+ describeProtectedResource,
14
+ parsePublicHttpsUrl,
15
+ refuseBearerToken,
16
+ serveProtectedResourceMetadata,
17
+ } from './bearer-resource-gate.js';
18
+ export type {
19
+ IBearerFailure,
20
+ IBearerResourceServer,
21
+ IProtectedResource,
22
+ TRemoteAddressClass,
23
+ } from './bearer-resource-gate.js';
11
24
  export {
12
25
  DEFAULT_MAX_FILE_BYTES,
13
26
  FILE_CHUNK_BYTES,
@@ -0,0 +1,36 @@
1
+ import type { TClientMessage } from './wire-messages.js';
2
+
3
+ /**
4
+ * The only inbound messages an observer may send: reads of this session. An allowlist, so a message
5
+ * type added later is refused to observers until someone decides it is a read. `get-prompts` is left
6
+ * out: an observer never receives prompts, open ones included.
7
+ *
8
+ * The host refuses anything else from an observer, and a client in observe mode sends only these, so
9
+ * both sides read this one list.
10
+ */
11
+ export const OBSERVER_MESSAGES: ReadonlySet<TClientMessage['type']> = new Set<
12
+ TClientMessage['type']
13
+ >([
14
+ 'get-messages',
15
+ 'get-history',
16
+ 'get-context',
17
+ 'get-status',
18
+ 'get-commands',
19
+ 'get-executing',
20
+ 'get-pending',
21
+ 'get-execution-workspace',
22
+ 'read-execution-detail',
23
+ 'get-usage-report',
24
+ 'list-sessions',
25
+ 'get-background-tasks',
26
+ 'get-background-task',
27
+ 'get-background-job-groups',
28
+ 'get-background-job-group',
29
+ 'wait-background-job-group',
30
+ 'read-background-task-log',
31
+ ]);
32
+
33
+ /** Whether an observer may send a message of this type. */
34
+ export function isObserverMessageType(type: string): boolean {
35
+ return (OBSERVER_MESSAGES as ReadonlySet<string>).has(type);
36
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * #3189: the permission and ask prompts a session has open, as the frames that asked them.
3
+ *
4
+ * The session keeps only the promise each prompt waits on, and emits the prompt once, when it is
5
+ * asked. A client that attaches later would never see a prompt already open. This keeps what the
6
+ * transport forwarded, per session, for a `get-prompts` reply.
7
+ *
8
+ * It is held by the connections that receive prompts and learns everything through their own
9
+ * subscriptions, so it never listens to the session itself. That matters: a session asks only while
10
+ * someone listens for prompts, and a listener of its own here would keep an unattended session's
11
+ * prompt open instead of failing it closed. When the last such connection goes, the session settles
12
+ * every open prompt, so nothing is kept.
13
+ */
14
+
15
+ import type { IProtocolSession } from './protocol-session.js';
16
+ import type { TServerMessage } from './wire-messages.js';
17
+
18
+ export type TOpenPromptFrame = Extract<
19
+ TServerMessage,
20
+ { type: 'permission_request' | 'ask_request' }
21
+ >;
22
+
23
+ interface IOpenPrompts {
24
+ readonly frames: Map<string, TOpenPromptFrame>;
25
+ holders: number;
26
+ }
27
+
28
+ const openPromptsBySession = new WeakMap<IProtocolSession, IOpenPrompts>();
29
+
30
+ /** One connection's hold on its session's open prompts; every holder reports what it forwards. */
31
+ export interface IOpenPromptsHold {
32
+ /** A prompt was asked. */
33
+ record(frame: TOpenPromptFrame): void;
34
+ /** A prompt was settled, by an answer or by the session. */
35
+ forget(id: string): void;
36
+ /** The host made another session current; the previous session's prompts are settled. */
37
+ clear(): void;
38
+ /** This connection no longer receives prompts. */
39
+ release(): void;
40
+ }
41
+
42
+ /** Called by a connection that receives prompts, before it subscribes to them. */
43
+ export function holdOpenPrompts(session: IProtocolSession): IOpenPromptsHold {
44
+ let open = openPromptsBySession.get(session);
45
+ if (open === undefined) {
46
+ open = { frames: new Map(), holders: 0 };
47
+ openPromptsBySession.set(session, open);
48
+ }
49
+ const held = open;
50
+ held.holders += 1;
51
+ let released = false;
52
+ return {
53
+ record: (frame) => {
54
+ if (!released) held.frames.set(frame.event.id, frame);
55
+ },
56
+ forget: (id) => {
57
+ held.frames.delete(id);
58
+ },
59
+ clear: () => {
60
+ held.frames.clear();
61
+ },
62
+ release: () => {
63
+ if (released) return;
64
+ released = true;
65
+ held.holders -= 1;
66
+ if (held.holders === 0 && openPromptsBySession.get(session) === held) {
67
+ openPromptsBySession.delete(session);
68
+ }
69
+ },
70
+ };
71
+ }
72
+
73
+ /** The prompts open now, oldest first; none when no connection that receives prompts is attached. */
74
+ export function listOpenPrompts(session: IProtocolSession): readonly TOpenPromptFrame[] {
75
+ return [...(openPromptsBySession.get(session)?.frames.values() ?? [])];
76
+ }
@@ -64,8 +64,8 @@ export type TOutboundDeliver = ((message: TServerMessage) => void) & {
64
64
 
65
65
  /**
66
66
  * Observe THIS connection's first outbound delivery failure. `event` is the `type` of the frame that
67
- * could not be delivered — a session event's own name for the fan-out (they are identical), and the
68
- * reply's type for a reply (`command_result`, `protocol_error`, …).
67
+ * could not be delivered — for the fan-out, the frame a session event was forwarded as (usually, not
68
+ * always, the event's own name), and the reply's type for a reply (`command_result`, `protocol_error`, …).
69
69
  *
70
70
  * Required, never optional: a carrier that could opt out of observing its own delivery failures is the
71
71
  * silent-failure shape this boundary exists to remove.
@@ -98,6 +98,15 @@ export type TDeliveryErrorHandler = (error: Error, event: TServerMessage['type']
98
98
  const BYTES_PER_MIB = Number('1024') * Number('1024');
99
99
  export const DEFAULT_MAX_PENDING_BYTES = Number('8') * BYTES_PER_MIB;
100
100
 
101
+ /**
102
+ * Backpressure budget for a terminal attached to a session on the same host, in either role.
103
+ *
104
+ * 1 MiB, tighter than the default: an attached terminal reads a local socket, so a backlog this large
105
+ * means it stopped reading rather than that a network is slow. Exceeding it closes that connection
106
+ * only; the session never waits for a reader, so other surfaces keep streaming.
107
+ */
108
+ export const ATTACHED_SURFACE_MAX_PENDING_BYTES = BYTES_PER_MIB;
109
+
101
110
  /**
102
111
  * Is this carrier holding more than the budget allows?
103
112
  *
@@ -5,9 +5,12 @@ import type {
5
5
  ISessionConversationRead,
6
6
  ISessionDriverAttribution,
7
7
  ISessionEvents,
8
+ ISessionExecutionDetail,
8
9
  ISessionExecutionState,
9
10
  ISessionExecutionWorkspace,
10
11
  ISessionPromptResolution,
12
+ ISessionSelfPacedLoopControl,
13
+ ISessionStatusRead,
11
14
  ISessionTurnControl,
12
15
  ISessionTurnSubmission,
13
16
  } from '@robota-sdk/agent-interface-session';
@@ -18,6 +21,7 @@ export interface IProtocolSession
18
21
  ISessionTurnSubmission,
19
22
  ISessionTurnControl,
20
23
  ISessionCommands,
24
+ ISessionStatusRead,
21
25
  ISessionEvents,
22
26
  ISessionPromptResolution,
23
27
  ISessionConversationRead,
@@ -25,4 +29,6 @@ export interface IProtocolSession
25
29
  ISessionDriverAttribution,
26
30
  ISessionBackgroundTasks,
27
31
  ISessionBackgroundGroups,
28
- ISessionExecutionWorkspace {}
32
+ ISessionExecutionWorkspace,
33
+ ISessionExecutionDetail,
34
+ ISessionSelfPacedLoopControl {}
@@ -0,0 +1,85 @@
1
+ import { isSessionChangeRefusal } from '@robota-sdk/agent-interface-session';
2
+
3
+ import type { TOutboundDeliver } from './outbound-delivery.js';
4
+ import type { TClientMessage } from './wire-messages.js';
5
+ import type { ISessionDirectory } from '@robota-sdk/agent-interface-session';
6
+
7
+ type TSessionDirectoryMessage = Extract<
8
+ TClientMessage,
9
+ { type: 'list-sessions' | 'new-session' | 'switch-session' }
10
+ >;
11
+
12
+ export function isSessionDirectoryMessage(msg: TClientMessage): msg is TSessionDirectoryMessage {
13
+ return (
14
+ msg.type === 'list-sessions' || msg.type === 'new-session' || msg.type === 'switch-session'
15
+ );
16
+ }
17
+
18
+ /**
19
+ * #3189: the host's sessions. Listing answers on its own correlated reply. A new session or a switch
20
+ * answers nothing on success: `session_switched` from the connection's own session is the signal. A
21
+ * refusal answers `session_change_failed`, carrying the host's code (or `failed` for an error that is
22
+ * not a declared refusal) and the request's `requestId`.
23
+ */
24
+ export function handleSessionDirectoryMessage(
25
+ deliver: TOutboundDeliver,
26
+ msg: TSessionDirectoryMessage,
27
+ directory: ISessionDirectory | undefined,
28
+ ): void {
29
+ if (msg.type === 'list-sessions') {
30
+ listSessions(deliver, msg.requestId, directory);
31
+ return;
32
+ }
33
+ const request = msg.requestId !== undefined ? { requestId: msg.requestId } : {};
34
+ if (!directory) {
35
+ deliver({
36
+ type: 'session_change_failed',
37
+ code: 'not_available',
38
+ message: 'Sessions cannot be switched on this host.',
39
+ ...request,
40
+ });
41
+ return;
42
+ }
43
+ const change = (): Promise<void> =>
44
+ msg.type === 'new-session' ? directory.newSession() : directory.switchSession(msg.sessionId);
45
+ void Promise.resolve()
46
+ .then(change)
47
+ .catch((error: Error | string) =>
48
+ deliver({
49
+ type: 'session_change_failed',
50
+ code: isSessionChangeRefusal(error) ? error.code : 'failed',
51
+ message: failureMessage(error),
52
+ ...request,
53
+ }),
54
+ );
55
+ }
56
+
57
+ function listSessions(
58
+ deliver: TOutboundDeliver,
59
+ requestId: string,
60
+ directory: ISessionDirectory | undefined,
61
+ ): void {
62
+ if (!directory) {
63
+ deliver({
64
+ type: 'sessions_error',
65
+ requestId,
66
+ code: 'not_available',
67
+ message: 'Session listing is not available on this host.',
68
+ });
69
+ return;
70
+ }
71
+ try {
72
+ deliver({ type: 'sessions', requestId, listing: directory.listSessions() });
73
+ } catch (error) {
74
+ deliver({
75
+ type: 'sessions_error',
76
+ requestId,
77
+ code: 'list_failed',
78
+ message: failureMessage(error instanceof Error ? error : String(error)),
79
+ });
80
+ }
81
+ }
82
+
83
+ function failureMessage(error: Error | string): string {
84
+ return error instanceof Error ? error.message : String(error);
85
+ }