@mountaya/client 0.0.0-stage → 0.1.0

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 (96) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +1260 -2
  5. package/dist/admin/index.cjs +3521 -0
  6. package/dist/admin/index.cjs.map +1 -0
  7. package/dist/admin/index.d.cts +1070 -0
  8. package/dist/admin/index.d.ts +1070 -0
  9. package/dist/admin/index.js +301 -0
  10. package/dist/admin/index.js.map +1 -0
  11. package/dist/browser.cjs +8073 -0
  12. package/dist/browser.cjs.map +1 -0
  13. package/dist/browser.d.cts +106 -0
  14. package/dist/browser.d.ts +106 -0
  15. package/dist/browser.js +53 -0
  16. package/dist/browser.js.map +1 -0
  17. package/dist/chunk-BM526BHG.js +342 -0
  18. package/dist/chunk-BM526BHG.js.map +1 -0
  19. package/dist/chunk-D2YEVTG7.js +327 -0
  20. package/dist/chunk-D2YEVTG7.js.map +1 -0
  21. package/dist/chunk-OHKVUREN.js +3500 -0
  22. package/dist/chunk-OHKVUREN.js.map +1 -0
  23. package/dist/chunk-TDTK2L5H.js +3842 -0
  24. package/dist/chunk-TDTK2L5H.js.map +1 -0
  25. package/dist/coreOperations.gen-BMYPoBbz.d.ts +1760 -0
  26. package/dist/coreOperations.gen-BxX5xRxw.d.cts +1760 -0
  27. package/dist/errors-B-GqAtQv.d.cts +75960 -0
  28. package/dist/errors-B-GqAtQv.d.ts +75960 -0
  29. package/dist/events/index.cjs +1972 -0
  30. package/dist/events/index.cjs.map +1 -0
  31. package/dist/events/index.d.cts +781 -0
  32. package/dist/events/index.d.ts +781 -0
  33. package/dist/events/index.js +826 -0
  34. package/dist/events/index.js.map +1 -0
  35. package/dist/index.cjs +8072 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.d.cts +76 -0
  38. package/dist/index.d.ts +76 -0
  39. package/dist/index.js +52 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/operations.gen-CvTyzKNF.d.cts +3993 -0
  42. package/dist/operations.gen-DUD406TV.d.ts +3993 -0
  43. package/package.json +127 -4
  44. package/src/admin/index.ts +47 -0
  45. package/src/admin/rules/mountayaAdmin.ts +102 -0
  46. package/src/browser.ts +232 -0
  47. package/src/core/engines/sessionToken.ts +870 -0
  48. package/src/core/rules/auth.ts +1017 -0
  49. package/src/core/rules/clientHeader.ts +28 -0
  50. package/src/core/rules/dates.ts +200 -0
  51. package/src/core/rules/decode.ts +154 -0
  52. package/src/core/rules/envelope.ts +41 -0
  53. package/src/core/rules/errors.ts +1486 -0
  54. package/src/core/rules/graphql.ts +576 -0
  55. package/src/core/rules/headerValue.ts +42 -0
  56. package/src/core/rules/idempotencyKey.ts +64 -0
  57. package/src/core/rules/nullMask.ts +127 -0
  58. package/src/core/rules/nullMasks.gen.ts +416 -0
  59. package/src/core/rules/paginate.ts +316 -0
  60. package/src/core/rules/rateLimit.ts +507 -0
  61. package/src/core/rules/redaction.ts +219 -0
  62. package/src/core/rules/resourceRef.ts +110 -0
  63. package/src/core/rules/responseBody.ts +492 -0
  64. package/src/core/rules/retry.ts +386 -0
  65. package/src/core/rules/selection.ts +416 -0
  66. package/src/core/rules/sessionAnswer.ts +90 -0
  67. package/src/core/rules/sessionSchedule.ts +131 -0
  68. package/src/core/rules/sessionWait.ts +112 -0
  69. package/src/core/rules/transport.ts +2386 -0
  70. package/src/core/rules/version.gen.ts +16 -0
  71. package/src/core/rules/webAddress.ts +165 -0
  72. package/src/core/rules/webAddresses.gen.ts +30 -0
  73. package/src/data/operations.gen.ts +603 -0
  74. package/src/data/schema.gen.ts +8078 -0
  75. package/src/data/selection.gen.ts +472 -0
  76. package/src/events/index.ts +67 -0
  77. package/src/events/rules/agent.ts +439 -0
  78. package/src/events/rules/collab.ts +554 -0
  79. package/src/events/rules/collabNulls.gen.ts +17 -0
  80. package/src/events/rules/eventStream.ts +94 -0
  81. package/src/events/rules/openSseStream.ts +594 -0
  82. package/src/events/rules/sse.ts +349 -0
  83. package/src/index.ts +231 -0
  84. package/src/rest/adminOperations.gen.ts +70 -0
  85. package/src/rest/adminResources.gen.ts +136 -0
  86. package/src/rest/coreOperations.gen.ts +74 -0
  87. package/src/rest/coreResources.gen.ts +244 -0
  88. package/src/rest/dates.gen.ts +217 -0
  89. package/src/rest/operations.gen.ts +4341 -0
  90. package/src/rest/resources.gen.ts +369 -0
  91. package/src/rest/schema.gen.ts +56840 -0
  92. package/src/tiles/operations.gen.ts +206 -0
  93. package/src/tiles/schema.gen.ts +8408 -0
  94. package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
  95. package/src/webhooks/rules/webhookEvent.ts +38 -0
  96. package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
@@ -0,0 +1,439 @@
1
+ import { MountayaApiError, MountayaConfigurationError } from "../../core/rules/errors.js";
2
+ import type { MountayaTransport } from "../../core/rules/transport.js";
3
+ import { postAgentRun, postAgentRunInput } from "../../rest/operations.gen.js";
4
+ import type {
5
+ AgentRunCreateParams,
6
+ AgentRunEvent,
7
+ AgentRunEventType,
8
+ AgentRunInputParams,
9
+ } from "../../rest/schema.gen.js";
10
+ import { openDeclaredSseStream } from "./openSseStream.js";
11
+ import type { SseFrame } from "./sse.js";
12
+
13
+ /**
14
+ * An agent run's event stream: starting a run, feeding input into it, and reading what it
15
+ * emits.
16
+ *
17
+ * The collaboration streams beside this one do the same job for a different protocol, and
18
+ * the two are deliberately not one. What they share (opening the stream, framing
19
+ * it, stamping the credential) is {@link openSseStream} and `MountayaTransport.streamSeam`. What
20
+ * is written twice is the lifecycle: a run starts, ends and can be resumed, where a change feed
21
+ * has none of those.
22
+ */
23
+
24
+ /**
25
+ * agentRunEventTypes is every event type a run can emit, and the assertion that this
26
+ * module knows exactly the set the contract declares.
27
+ *
28
+ * Both `satisfies` clauses matter and they fail in opposite directions: keyed on
29
+ * `AgentRunEventType` it fails when the contract gains a type this file has not listed (the
30
+ * frame would otherwise be dropped with nothing said), and keyed on the union's own
31
+ * discriminant it fails when this file lists one the contract does not declare, a frame
32
+ * shape nothing can ever send.
33
+ */
34
+ const agentRunEventTypes = {
35
+ "awaiting-input": "awaiting-input",
36
+ "budget-exhausted": "budget-exhausted",
37
+ "checks-unmet": "checks-unmet",
38
+ "confirm-required": "confirm-required",
39
+ done: "done",
40
+ error: "error",
41
+ message: "message",
42
+ "message-delta": "message-delta",
43
+ reconnect: "reconnect",
44
+ "tool-abandoned": "tool-abandoned",
45
+ "tool-call": "tool-call",
46
+ "tool-result": "tool-result",
47
+ } satisfies Record<AgentRunEventType, AgentRunEvent["type"]> satisfies Record<
48
+ AgentRunEvent["type"],
49
+ AgentRunEventType
50
+ >;
51
+
52
+ /** AgentEvent is one decoded frame off a run's event stream. */
53
+ export type AgentEvent = AgentRunEvent;
54
+
55
+ /** AgentInput is one input signal sent into a running run. */
56
+ export type AgentInput = AgentRunInputParams;
57
+
58
+ /**
59
+ * agentTerminalEventTypes are the event types that end a run: once one is seen the
60
+ * stream is finished and the read stops rather than waiting on the server to hang up.
61
+ * `done` is the sole terminal: an ended run always finishes with one.
62
+ */
63
+ export const agentTerminalEventTypes: ReadonlySet<AgentEvent["type"]> = new Set([
64
+ agentRunEventTypes.done,
65
+ ]);
66
+
67
+ /**
68
+ * AgentStreamFrame is one decoded frame paired with its stream position id. A reader
69
+ * records the id of the last frame it consumed, so a reconnect passes it back as
70
+ * `Last-Event-ID` and resumes after it. `id` is the record's own `id:` field, and absent where
71
+ * the record names none: on the API's stream a `message-delta` carries none, since a delta
72
+ * is live and never replayed, and every other frame is numbered. A reader that holds no id
73
+ * resumes as a full replay.
74
+ */
75
+ export interface AgentStreamFrame {
76
+ /** The decoded event, discriminated on `type`. */
77
+ event: AgentEvent;
78
+ /** The record's own `id:`, the position a resume passes back; absent where it names none. */
79
+ id?: string | undefined;
80
+ }
81
+
82
+ /**
83
+ * AgentStreamCloseReason distinguishes how a run's stream finished without an error:
84
+ * `terminal` means a terminal event was seen, so the run is over; `reconnect` means the API ended
85
+ * the stream and asks for a reopen at once. It says so with a `reconnect` event, when the
86
+ * credential the stream was opened with ends (the session token expires or the key is revoked)
87
+ * and when it cannot keep delivering the stream (`interrupted`: the reader fell behind or the
88
+ * subscription was lost), and a close at or after the token's expiry says the same. None is a
89
+ * failure: the reopen goes at once with the token the client holds then, a new one where the
90
+ * credential ended and the one already held where the stream was interrupted, and the last event
91
+ * id. `ended` means the body closed with no terminal, which mid-run is the server hanging up
92
+ * between turns: a candidate for a resume rather than the end of the run.
93
+ */
94
+ export type AgentStreamCloseReason = "terminal" | "reconnect" | "ended";
95
+
96
+ /**
97
+ * AgentStreamHandlers are the callbacks a subscriber wires into a run's event stream. The
98
+ * transport drives them as it reads: `onFrame` per decoded frame, `onSkippedFrame` per frame it
99
+ * skips, `onLastEventId` when the run's position moves without a frame to carry it, then exactly
100
+ * one of `onClose` (finished cleanly) or `onError` (it failed). An abort is the subscriber's own
101
+ * teardown and fires neither.
102
+ */
103
+ export interface AgentStreamHandlers {
104
+ /** onClose is told once the stream finished with no error, and why. */
105
+ onClose: (reason: AgentStreamCloseReason) => void;
106
+ /**
107
+ * onError receives the failure once. It is an error of the client's family, except a fault the
108
+ * subscriber's own `onFrame`, `onSkippedFrame` or `onLastEventId` threw, which arrives as it was
109
+ * thrown: an open the API refused raises the class a request answered the same way raises, and
110
+ * a connection that failed or broke off raises a `MountayaConnectionError` naming
111
+ * `getAgentRunEvents`.
112
+ */
113
+ onError: (error: unknown) => void;
114
+ /**
115
+ * onFrame receives one decoded frame. It is awaited, so returning a promise backpressures
116
+ * the read: the next frame is pulled only once the current one is handled, which throttles
117
+ * the stream to tool dispatch rather than letting frames pile up ahead of their effects.
118
+ */
119
+ onFrame: (frame: AgentStreamFrame) => void | Promise<void>;
120
+ /**
121
+ * onLastEventId receives the run's stream position when it moves to one no frame carries: a
122
+ * record that names an `id:` and no event, or an empty `id:`, which clears the position and
123
+ * arrives as `undefined`. A subscriber keeping a resume cursor records it as it records a
124
+ * frame's id, so a reopen resumes from the last position the stream named.
125
+ *
126
+ * A frame {@link decodeAgentFrame} skips (a kind this build does not know, or a payload that is
127
+ * not an object) is neither handed to onFrame nor reported here, whatever id it carries, so its
128
+ * position reaches a cursor only once a later frame or record names one. A reopen before then
129
+ * replays it, and it is skipped again.
130
+ */
131
+ onLastEventId?: ((lastEventId: string | undefined) => void) | undefined;
132
+ /**
133
+ * onSkippedFrame is told of each frame the stream delivers that {@link decodeAgentFrame} skips:
134
+ * one naming an event this build does not know, or carrying data it cannot read. Nothing of it
135
+ * is handed over, and it moves no position, but it is a frame the stream delivered, so a reader
136
+ * counting what an open delivered, as a reconnect policy does to tell an open that made progress
137
+ * from one that did not, counts it. A `reconnect`, which is the transport's own, is not one.
138
+ */
139
+ onSkippedFrame?: (() => void) | undefined;
140
+ }
141
+
142
+ /**
143
+ * AgentWriteOptions tune one write into a run: starting it, or delivering input into it.
144
+ */
145
+ export interface AgentWriteOptions {
146
+ /**
147
+ * The `Idempotency-Key` the write sends on every attempt. Left out, the client draws one for
148
+ * the call. A caller that asks again itself after a failure passes the key it drew for the first
149
+ * ask, so a start whose answer was lost is answered with the run it started rather than a second
150
+ * run.
151
+ */
152
+ readonly idempotencyKey?: string | undefined;
153
+ }
154
+
155
+ /**
156
+ * AgentSubscribeOptions tune one open. `lastEventId` resumes the durable history after a
157
+ * position (the server replays past it before resuming the live feed); `signal` tears the
158
+ * open stream down from outside, exactly as the returned unsubscribe does.
159
+ */
160
+ export interface AgentSubscribeOptions {
161
+ /** The position to resume after, sent as `Last-Event-ID`; left out, the run replays whole. */
162
+ lastEventId?: string | undefined;
163
+ /** Closes the stream once it aborts, as the unsubscribe `subscribe` returns does. */
164
+ signal?: AbortSignal | undefined;
165
+ }
166
+
167
+ /**
168
+ * AgentTransport is the seam an agent session drives: start a run, deliver input into it,
169
+ * and read its events frame by frame.
170
+ *
171
+ * A session takes this interface rather than a client, so an offline or scripted
172
+ * implementation is a plain object. {@link createAgentTransport} is the live one, which gives up
173
+ * an open that never answers and a stream gone silent as connection errors. A transport of your
174
+ * own bounds both waits the same way: the engine waits as long as `subscribe` says nothing. It
175
+ * reports `onClose("terminal")` only after it has handed over a `done`.
176
+ */
177
+ export interface AgentTransport {
178
+ /**
179
+ * sendInput delivers one input signal into a running run, resolving once the API took it.
180
+ *
181
+ * @throws the `MountayaApiError` class the API's refusal maps to, or a
182
+ * `MountayaConnectionError` when no answer arrived; in the live transport, a
183
+ * `MountayaConfigurationError` before anything is sent for a routing update naming a server
184
+ * tool under a publishable key.
185
+ */
186
+ sendInput: (runId: string, input: AgentInput, options?: AgentWriteOptions) => Promise<void>;
187
+ /**
188
+ * startRun starts a run and answers its id, which `sendInput` and `subscribe` take.
189
+ *
190
+ * @throws the `MountayaApiError` class the API's refusal maps to, including a 202 that names no
191
+ * run, or a `MountayaConnectionError` when no answer arrived; in the live transport, a
192
+ * `MountayaConfigurationError` before anything is sent for a start naming a server tool under
193
+ * a publishable key.
194
+ */
195
+ startRun: (
196
+ params: AgentRunCreateParams,
197
+ options?: AgentWriteOptions,
198
+ ) => Promise<{ runId: string }>;
199
+ /**
200
+ * subscribe opens a run's event stream and returns the function that closes it. Every failure
201
+ * reaches `handlers.onError`; the call itself never throws.
202
+ */
203
+ subscribe: (
204
+ runId: string,
205
+ handlers: AgentStreamHandlers,
206
+ options?: AgentSubscribeOptions,
207
+ ) => () => void;
208
+ }
209
+
210
+ /** AgentRunAccepted is the 202 a run start answers with, as the contract declares it. */
211
+ type AgentRunAccepted = Awaited<ReturnType<typeof postAgentRun>>;
212
+
213
+ /**
214
+ * runIdFrom reads the run id out of the 202 the start answers with. The contract answers the run
215
+ * it started at `data`, and its `id` is the `run_id` the input, events and feedback operations
216
+ * take.
217
+ *
218
+ * Typed off the generated operation, which reads the 202 like a 200 or a 201, so the path is
219
+ * the contract's rather than a transcription of it: a transcribed path the contract does not
220
+ * declare fails every start against the real API while a test encoding the same wrong shape
221
+ * passes. It is still read defensively, because the transport asserts a body's type rather
222
+ * than validating it: a start that answered something else would otherwise produce an
223
+ * undefined run id that fails several frames later.
224
+ */
225
+ const runIdFrom = (body: AgentRunAccepted | undefined): string | undefined => {
226
+ const id: unknown = body?.data?.id;
227
+
228
+ return typeof id === "string" && id !== "" ? id : undefined;
229
+ };
230
+
231
+ /**
232
+ * decodeAgentFrame turns one raw SSE frame into a typed event, or null to skip it.
233
+ *
234
+ * The `event:` line is the discriminant and the `data:` line is the payload without it, so
235
+ * the two are combined and the event line wins over any stray `type` in the body. A frame
236
+ * naming a type this build does not know is skipped rather than fatal, which is what makes
237
+ * a newer server emitting a new event a compatible change. The type is looked up among the
238
+ * table's own keys, so a name every object inherits (`constructor`, `toString`) is one this
239
+ * build does not know.
240
+ *
241
+ * No date mask here: nothing in this union carries a timestamp, so the contract generates no
242
+ * event masks for it, unlike the collaboration stream's.
243
+ *
244
+ * The cast is the decision this module is built on: the contract generates the union, so a
245
+ * frame is TYPED by it rather than re-validated against a hand-written transcription. What
246
+ * is checked at runtime is the one field the wire and the type disagree about, the
247
+ * discriminant, which arrives on its own line, and nothing below it. A `tool-call`'s input
248
+ * is `unknown` either way and is validated by the tool bus against the tool's own schema.
249
+ */
250
+ export const decodeAgentFrame = (frame: SseFrame): AgentEvent | null => {
251
+ if (!Object.hasOwn(agentRunEventTypes, frame.event)) {
252
+ return null;
253
+ }
254
+
255
+ let payload: unknown;
256
+ try {
257
+ payload = frame.data ? JSON.parse(frame.data) : {};
258
+ } catch {
259
+ return null;
260
+ }
261
+
262
+ if (typeof payload !== "object" || payload === null) {
263
+ return null;
264
+ }
265
+
266
+ // The wire's boundary: a frame is typed by the event its `event:` line names, as the contract
267
+ // declares it, and is not validated against that type here.
268
+ return { ...payload, type: frame.event } as AgentEvent;
269
+ };
270
+
271
+ /**
272
+ * AGENT_EVENTS_OPERATION_ID is the operation a run's event stream opens, as the credential it
273
+ * declares names it, and as every failure the open builds names it (a refusal, a connection
274
+ * failure, an answer with no body to read). A failure handed on as it was thrown keeps its own
275
+ * message.
276
+ */
277
+ const AGENT_EVENTS_OPERATION_ID = "getAgentRunEvents";
278
+
279
+ /**
280
+ * refuseServerToolsUnderKey refuses a run start or a routing update whose `server_tools` names
281
+ * anything, under a publishable key: a run under a key calls no server tool, and the API answers a
282
+ * non-empty list there with a 400 naming `server_tools`. Read off the credential the transport
283
+ * projects for a map, which carries a publishable key exactly where the transport holds one, so a
284
+ * share token, a secret key and the browser's own session are never refused here.
285
+ *
286
+ * @throws `MountayaConfigurationError` naming the operation and the engine option that sends the
287
+ * list, before anything is sent.
288
+ */
289
+ const refuseServerToolsUnderKey = (
290
+ transport: MountayaTransport,
291
+ operationId: string,
292
+ serverTools: readonly string[] | undefined,
293
+ ): void => {
294
+ if (serverTools === undefined || serverTools.length === 0) {
295
+ return;
296
+ }
297
+
298
+ if (transport.mapCredential.publishableKey === undefined) {
299
+ return;
300
+ }
301
+
302
+ throw new MountayaConfigurationError(
303
+ `${operationId}: a run under a publishable key calls no server tool, so server_tools must be empty. Turn routesServerTools off.`,
304
+ );
305
+ };
306
+
307
+ /** isReconnect reports whether an event is the `reconnect` that ends a stream with its credential. */
308
+ const isReconnect = (event: AgentEvent): boolean => event.type === agentRunEventTypes.reconnect;
309
+
310
+ /**
311
+ * createAgentTransport binds an agent run's endpoints to one client's transport.
312
+ *
313
+ * The two writes go through the generated operations, so the path, the method and the
314
+ * error taxonomy are the contract's. The read cannot: a run's event stream is open for as
315
+ * long as the run lasts, and every generated reader either buffers the whole body or arms a
316
+ * per-request timeout across it (see `MountayaTransport.streamSeam` for why). It uses `fetch`
317
+ * rather than `EventSource` because the stream must carry the transport's credential and set
318
+ * `Last-Event-ID` on a reconnect, and `EventSource` supports neither. An open the API refuses
319
+ * raises the class a request answered the same way raises, read off the refusal's body.
320
+ *
321
+ * A start or a routing update whose `server_tools` names anything is refused before it is sent
322
+ * under a publishable key, under which a run calls no server tool. An open waits for a session
323
+ * token the credential's source reports on its way, as a request does. The `reconnect` event the
324
+ * API ends a stream with, when its credential ends or when it cannot keep delivering it
325
+ * (`interrupted`), is never handed to `onFrame`: it ends the read and closes it as `reconnect`,
326
+ * whatever reason it names, and so does a close at or after the expiry of the token the open
327
+ * carried, where the credential's source reports one. A frame it skips is told to
328
+ * `onSkippedFrame`.
329
+ */
330
+ export const createAgentTransport = (transport: MountayaTransport): AgentTransport => ({
331
+ sendInput: async (runId, input, options) => {
332
+ if (input.type === "manifest-update") {
333
+ refuseServerToolsUnderKey(transport, "postAgentRunInput", input.server_tools);
334
+ }
335
+
336
+ await postAgentRunInput(transport, {
337
+ body: input,
338
+ idempotencyKey: options?.idempotencyKey,
339
+ run_id: runId,
340
+ });
341
+ },
342
+ startRun: async (params, options) => {
343
+ refuseServerToolsUnderKey(transport, "postAgentRun", params.server_tools);
344
+
345
+ const body = await postAgentRun(transport, {
346
+ body: params,
347
+ idempotencyKey: options?.idempotencyKey,
348
+ });
349
+ const runId = runIdFrom(body);
350
+ if (runId === undefined) {
351
+ throw new MountayaApiError("postAgentRun: 202 named no run", 202, []);
352
+ }
353
+
354
+ return { runId };
355
+ },
356
+ subscribe: (runId, handlers, options) => {
357
+ const seam = transport.streamSeam;
358
+ // When the token this open carries expires, read as the open applies it, and whether the
359
+ // stream ended on a `reconnect`: either makes a close a prompt reopen rather than a resume.
360
+ let expiresAt: Date | undefined;
361
+ let reconnected = false;
362
+
363
+ // The shared opener owns the abort, resume, read and error scaffolding; what this supplies
364
+ // is the run's own policy: how a read outcome maps to a close reason, and a per-frame
365
+ // handler that backpressures on the caller and stops on a terminal event.
366
+ return openDeclaredSseStream<AgentEvent>(
367
+ {
368
+ // What `getAgentRunEvents` declares, stated as its generated operation states it: its
369
+ // only security requirement pairs the key with a session token, and the stream acts as
370
+ // the member that token names. Stating both here is what refuses a credential carrying no
371
+ // session token, or one a source reports as minted without `user_id`, before the open;
372
+ // the refusal reaches onError like any other failed open. No share token reaches it, which
373
+ // the absence of `acceptsShareToken` says.
374
+ applyAuth: (init, method) => {
375
+ const applied = seam.applyAuth(init, method, {
376
+ actsAsMember: true,
377
+ operationId: AGENT_EVENTS_OPERATION_ID,
378
+ requiresSession: true,
379
+ });
380
+ expiresAt = seam.sessionExpiresAt();
381
+
382
+ return applied;
383
+ },
384
+ // A frame skipped is still one the stream delivered, which the subscriber is told of as it
385
+ // is read, in order with the frames handed over.
386
+ decode: (frame) => {
387
+ const event = decodeAgentFrame(frame);
388
+ if (event === null) {
389
+ handlers.onSkippedFrame?.();
390
+ }
391
+
392
+ return event;
393
+ },
394
+ doFetch: seam.doFetch,
395
+ lastEventId: options?.lastEventId,
396
+ onClose: (outcome) => {
397
+ if (outcome === "stopped") {
398
+ handlers.onClose(reconnected ? "reconnect" : "terminal");
399
+
400
+ return;
401
+ }
402
+
403
+ // The last record before a close can be lost on its way, so a close once the token
404
+ // has expired is read as the `reconnect` the API would have written.
405
+ const expired = expiresAt !== undefined && Date.now() >= expiresAt.getTime();
406
+ handlers.onClose(expired ? "reconnect" : "ended");
407
+ },
408
+ onError: (error) => handlers.onError(error),
409
+ onFrame: async (event, id) => {
410
+ if (isReconnect(event)) {
411
+ reconnected = true;
412
+
413
+ return true;
414
+ }
415
+
416
+ await handlers.onFrame({ event, id });
417
+
418
+ return agentTerminalEventTypes.has(event.type);
419
+ },
420
+ onLastEventId: (lastEventId) => handlers.onLastEventId?.(lastEventId),
421
+ onResponse: (response) => {
422
+ seam.report(response, AGENT_EVENTS_OPERATION_ID);
423
+ },
424
+ operationId: AGENT_EVENTS_OPERATION_ID,
425
+ signal: options?.signal,
426
+ // The wait for the stream's response is the client's own per-attempt budget.
427
+ timeoutMs: seam.timeoutMs,
428
+ // Resolved when the open is made, so a run id the path cannot carry (an empty one, or a
429
+ // dot segment) is refused through onError like any other failed open.
430
+ url: () =>
431
+ seam.url(`/v1/agent/runs/${encodeURIComponent(runId)}/events`, AGENT_EVENTS_OPERATION_ID),
432
+ waitForSession: (signal) => seam.waitForSession(AGENT_EVENTS_OPERATION_ID, signal),
433
+ },
434
+ // The same declaration the credential is stamped by, so a refused open names the step a
435
+ // member reading their own run takes.
436
+ { actsAsMember: true },
437
+ );
438
+ },
439
+ });