@ably/ai-transport 0.1.0 → 0.2.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 (163) hide show
  1. package/README.md +91 -100
  2. package/dist/ably-ai-transport.js +1553 -1238
  3. package/dist/ably-ai-transport.js.map +1 -1
  4. package/dist/ably-ai-transport.umd.cjs +1 -1
  5. package/dist/ably-ai-transport.umd.cjs.map +1 -1
  6. package/dist/constants.d.ts +116 -42
  7. package/dist/core/agent.d.ts +29 -0
  8. package/dist/core/codec/decoder.d.ts +20 -23
  9. package/dist/core/codec/encoder.d.ts +11 -8
  10. package/dist/core/codec/index.d.ts +1 -2
  11. package/dist/core/codec/lifecycle-tracker.d.ts +10 -9
  12. package/dist/core/codec/types.d.ts +407 -115
  13. package/dist/core/transport/agent-session.d.ts +10 -0
  14. package/dist/core/transport/branch-chain.d.ts +43 -0
  15. package/dist/core/transport/client-session.d.ts +13 -0
  16. package/dist/core/transport/decode-fold.d.ts +47 -0
  17. package/dist/core/transport/headers.d.ts +96 -18
  18. package/dist/core/transport/index.d.ts +5 -6
  19. package/dist/core/transport/internal/bounded-map.d.ts +20 -0
  20. package/dist/core/transport/invocation.d.ts +74 -0
  21. package/dist/core/transport/load-conversation.d.ts +128 -0
  22. package/dist/core/transport/load-history.d.ts +39 -0
  23. package/dist/core/transport/pipe-stream.d.ts +9 -9
  24. package/dist/core/transport/run-manager.d.ts +78 -0
  25. package/dist/core/transport/tree.d.ts +373 -109
  26. package/dist/core/transport/types/agent.d.ts +353 -0
  27. package/dist/core/transport/types/client.d.ts +168 -0
  28. package/dist/core/transport/types/shared.d.ts +24 -0
  29. package/dist/core/transport/types/tree.d.ts +315 -0
  30. package/dist/core/transport/types/view.d.ts +222 -0
  31. package/dist/core/transport/types.d.ts +13 -553
  32. package/dist/core/transport/view.d.ts +272 -84
  33. package/dist/errors.d.ts +21 -10
  34. package/dist/index.d.ts +6 -8
  35. package/dist/logger.d.ts +12 -0
  36. package/dist/react/ably-ai-transport-react.js +976 -990
  37. package/dist/react/ably-ai-transport-react.js.map +1 -1
  38. package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
  39. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
  40. package/dist/react/contexts/client-session-context.d.ts +36 -0
  41. package/dist/react/contexts/client-session-provider.d.ts +53 -0
  42. package/dist/react/create-session-hooks.d.ts +116 -0
  43. package/dist/react/index.d.ts +12 -12
  44. package/dist/react/internal/use-resolved-session.d.ts +36 -0
  45. package/dist/react/use-ably-messages.d.ts +17 -14
  46. package/dist/react/use-client-session.d.ts +81 -0
  47. package/dist/react/use-create-view.d.ts +14 -13
  48. package/dist/react/use-tree.d.ts +30 -15
  49. package/dist/react/use-view.d.ts +82 -51
  50. package/dist/utils.d.ts +32 -23
  51. package/dist/vercel/ably-ai-transport-vercel.js +2573 -2086
  52. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
  53. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
  54. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
  55. package/dist/vercel/codec/decoder.d.ts +5 -18
  56. package/dist/vercel/codec/encoder.d.ts +6 -36
  57. package/dist/vercel/codec/events.d.ts +51 -0
  58. package/dist/vercel/codec/index.d.ts +24 -12
  59. package/dist/vercel/codec/reducer.d.ts +144 -0
  60. package/dist/vercel/codec/tool-transitions.d.ts +2 -2
  61. package/dist/vercel/index.d.ts +4 -5
  62. package/dist/vercel/react/ably-ai-transport-vercel-react.js +3907 -3266
  63. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
  64. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +33 -8
  65. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
  66. package/dist/vercel/react/contexts/chat-transport-context.d.ts +7 -6
  67. package/dist/vercel/react/contexts/chat-transport-provider.d.ts +53 -41
  68. package/dist/vercel/react/index.d.ts +1 -2
  69. package/dist/vercel/react/use-chat-transport.d.ts +30 -26
  70. package/dist/vercel/react/use-message-sync.d.ts +17 -30
  71. package/dist/vercel/run-end-reason.d.ts +29 -0
  72. package/dist/vercel/transport/chat-transport.d.ts +43 -24
  73. package/dist/vercel/transport/index.d.ts +25 -21
  74. package/dist/vercel/transport/run-output-stream.d.ts +56 -0
  75. package/dist/version.d.ts +2 -0
  76. package/package.json +30 -23
  77. package/src/constants.ts +124 -51
  78. package/src/core/agent.ts +68 -0
  79. package/src/core/codec/decoder.ts +71 -98
  80. package/src/core/codec/encoder.ts +113 -65
  81. package/src/core/codec/index.ts +13 -6
  82. package/src/core/codec/lifecycle-tracker.ts +10 -9
  83. package/src/core/codec/types.ts +436 -120
  84. package/src/core/transport/agent-session.ts +1344 -0
  85. package/src/core/transport/branch-chain.ts +58 -0
  86. package/src/core/transport/client-session.ts +775 -0
  87. package/src/core/transport/decode-fold.ts +91 -0
  88. package/src/core/transport/headers.ts +181 -22
  89. package/src/core/transport/index.ts +25 -26
  90. package/src/core/transport/internal/bounded-map.ts +27 -0
  91. package/src/core/transport/invocation.ts +98 -0
  92. package/src/core/transport/load-conversation.ts +355 -0
  93. package/src/core/transport/load-history.ts +269 -0
  94. package/src/core/transport/pipe-stream.ts +54 -39
  95. package/src/core/transport/run-manager.ts +249 -0
  96. package/src/core/transport/tree.ts +926 -308
  97. package/src/core/transport/types/agent.ts +407 -0
  98. package/src/core/transport/types/client.ts +211 -0
  99. package/src/core/transport/types/shared.ts +27 -0
  100. package/src/core/transport/types/tree.ts +344 -0
  101. package/src/core/transport/types/view.ts +259 -0
  102. package/src/core/transport/types.ts +13 -706
  103. package/src/core/transport/view.ts +864 -433
  104. package/src/errors.ts +22 -9
  105. package/src/event-emitter.ts +3 -2
  106. package/src/index.ts +52 -41
  107. package/src/logger.ts +14 -1
  108. package/src/react/contexts/client-session-context.ts +41 -0
  109. package/src/react/contexts/client-session-provider.tsx +186 -0
  110. package/src/react/create-session-hooks.ts +141 -0
  111. package/src/react/index.ts +23 -13
  112. package/src/react/internal/use-resolved-session.ts +63 -0
  113. package/src/react/use-ably-messages.ts +32 -22
  114. package/src/react/use-client-session.ts +201 -0
  115. package/src/react/use-create-view.ts +33 -29
  116. package/src/react/use-tree.ts +61 -30
  117. package/src/react/use-view.ts +139 -97
  118. package/src/utils.ts +63 -45
  119. package/src/vercel/codec/decoder.ts +336 -258
  120. package/src/vercel/codec/encoder.ts +343 -205
  121. package/src/vercel/codec/events.ts +87 -0
  122. package/src/vercel/codec/index.ts +60 -13
  123. package/src/vercel/codec/reducer.ts +977 -0
  124. package/src/vercel/codec/tool-transitions.ts +2 -2
  125. package/src/vercel/index.ts +6 -19
  126. package/src/vercel/react/contexts/chat-transport-context.ts +7 -6
  127. package/src/vercel/react/contexts/chat-transport-provider.tsx +87 -59
  128. package/src/vercel/react/index.ts +3 -5
  129. package/src/vercel/react/use-chat-transport.ts +47 -49
  130. package/src/vercel/react/use-message-sync.ts +80 -39
  131. package/src/vercel/run-end-reason.ts +78 -0
  132. package/src/vercel/transport/chat-transport.ts +392 -98
  133. package/src/vercel/transport/index.ts +39 -38
  134. package/src/vercel/transport/run-output-stream.ts +170 -0
  135. package/src/version.ts +2 -0
  136. package/dist/core/transport/client-transport.d.ts +0 -10
  137. package/dist/core/transport/decode-history.d.ts +0 -43
  138. package/dist/core/transport/server-transport.d.ts +0 -7
  139. package/dist/core/transport/stream-router.d.ts +0 -29
  140. package/dist/core/transport/turn-manager.d.ts +0 -37
  141. package/dist/react/contexts/transport-context.d.ts +0 -31
  142. package/dist/react/contexts/transport-provider.d.ts +0 -49
  143. package/dist/react/create-transport-hooks.d.ts +0 -124
  144. package/dist/react/use-active-turns.d.ts +0 -12
  145. package/dist/react/use-client-transport.d.ts +0 -80
  146. package/dist/vercel/codec/accumulator.d.ts +0 -21
  147. package/dist/vercel/react/use-staged-add-tool-approval-response.d.ts +0 -30
  148. package/dist/vercel/tool-approvals.d.ts +0 -124
  149. package/dist/vercel/tool-events.d.ts +0 -26
  150. package/src/core/transport/client-transport.ts +0 -977
  151. package/src/core/transport/decode-history.ts +0 -485
  152. package/src/core/transport/server-transport.ts +0 -612
  153. package/src/core/transport/stream-router.ts +0 -136
  154. package/src/core/transport/turn-manager.ts +0 -165
  155. package/src/react/contexts/transport-context.ts +0 -37
  156. package/src/react/contexts/transport-provider.tsx +0 -164
  157. package/src/react/create-transport-hooks.ts +0 -144
  158. package/src/react/use-active-turns.ts +0 -72
  159. package/src/react/use-client-transport.ts +0 -197
  160. package/src/vercel/codec/accumulator.ts +0 -588
  161. package/src/vercel/react/use-staged-add-tool-approval-response.ts +0 -87
  162. package/src/vercel/tool-approvals.ts +0 -380
  163. package/src/vercel/tool-events.ts +0 -53
@@ -1,712 +1,19 @@
1
1
  /**
2
2
  * Core transport types, parameterized by codec event and message types.
3
3
  *
4
- * These types define the contract for both client and server transport
5
- * implementations, independent of which codec (Vercel AI SDK, etc.) is used.
6
- */
7
-
8
- import type * as Ably from 'ably';
9
-
10
- import type { Logger } from '../../logger.js';
11
- import type { Codec, WriteOptions } from '../codec/types.js';
12
-
13
- // ---------------------------------------------------------------------------
14
- // Shared types
15
- // ---------------------------------------------------------------------------
16
-
17
- /** Why a turn ended. */
18
- export type TurnEndReason = 'complete' | 'cancelled' | 'error';
19
-
20
- /** Filter for cancel operations. At most one field should be set. */
21
- export interface CancelFilter {
22
- /** Cancel a specific turn by ID. */
23
- turnId?: string;
24
- /** Cancel all turns belonging to the sender's clientId. */
25
- own?: boolean;
26
- /** Cancel all turns belonging to a specific clientId. */
27
- clientId?: string;
28
- /** Cancel all turns on the channel. */
29
- all?: boolean;
30
- }
31
-
32
- /**
33
- * Passed to the server's `onCancel` hook for authorization decisions.
34
- * The hook inspects the incoming cancel message and decides whether to
35
- * allow each matched turn to be aborted.
36
- */
37
- export interface CancelRequest {
38
- /** The raw Ably message that carried the cancel signal. */
39
- message: Ably.InboundMessage;
40
- /** The parsed cancel scope from the message headers. */
41
- filter: CancelFilter;
42
- /** Which active turnIds would be cancelled if allowed. */
43
- matchedTurnIds: string[];
44
- /** Map of turnId to the ownerClientId for the matched turns. */
45
- turnOwners: Map<string, string>;
46
- }
47
-
48
- // ---------------------------------------------------------------------------
49
- // Server transport options
50
- // ---------------------------------------------------------------------------
51
-
52
- /** Options for creating a server transport. */
53
- export interface ServerTransportOptions<TEvent, TMessage> {
54
- /** The Ably channel to publish to. Must match the client's channel. */
55
- channel: Ably.RealtimeChannel;
56
- /** The codec to use for encoding events and messages. */
57
- codec: Codec<TEvent, TMessage>;
58
- /** Logger instance for diagnostic output. */
59
- logger?: Logger;
60
- /**
61
- * Called with non-fatal transport-level errors not scoped to any turn.
62
- * Examples: cancel listener subscription failure, channel attach errors,
63
- * channel continuity loss (FAILED/SUSPENDED/DETACHED or re-attach with
64
- * `resumed: false`).
65
- */
66
- onError?: (error: Ably.ErrorInfo) => void;
67
- }
68
-
69
- // ---------------------------------------------------------------------------
70
- // Turn options
71
- // ---------------------------------------------------------------------------
72
-
73
- /** Options for addMessages — per-operation overrides for attribution. */
74
- export interface AddMessageOptions {
75
- /** The user's clientId for attribution. */
76
- clientId?: string;
77
- }
78
-
79
- /** Result of publishing user messages via addMessages. */
80
- export interface AddMessagesResult {
81
- /** The `x-ably-msg-id` of each published message, in order. */
82
- msgIds: string[];
83
- }
84
-
85
- /**
86
- * A batch of events targeting an existing message.
87
- * Each node specifies the target message and the events to apply to it.
88
- * Used for cross-turn updates such as tool result delivery.
89
- */
90
- export interface EventsNode<TEvent> {
91
- /** Discriminator — identifies this as an events node. */
92
- kind: 'event';
93
- /** The `x-ably-msg-id` of the existing message to update. */
94
- msgId: string;
95
- /** Events to apply to the target message. */
96
- events: TEvent[];
97
- }
98
-
99
- /** @deprecated Use {@link EventsNode} instead. */
100
- export type EventNode<TEvent> = EventsNode<TEvent>;
101
-
102
- /**
103
- * Options for streamResponse — per-operation overrides for the assistant message.
104
- * @template TEvent - The codec event type carried by the stream; used by the `resolveWriteOptions` hook.
105
- */
106
- export interface StreamResponseOptions<TEvent> {
107
- /** The msg-id of the immediately preceding message in this branch. */
108
- parent?: string;
109
- /** The msg-id of the message this response replaces (for regeneration). */
110
- forkOf?: string;
111
- /**
112
- * Optional per-event hook invoked before each event is encoded. The
113
- * returned {@link WriteOptions} (if any) override the stream's default
114
- * headers and `msgId` for that one encode call only; return `undefined`
115
- * to use the stream defaults.
116
- *
117
- * Used to carry a subset of events within the stream to a different
118
- * message (e.g. `tool-output-available` chunks that belong on a prior
119
- * assistant message, stamped with `x-ably-amend`). Must not be used
120
- * for events that participate in the encoder's stream-append pipeline
121
- * — streaming state (stream tracker, append ordering) is anchored to
122
- * the stream's default identity and is not affected by per-event
123
- * overrides.
124
- * @param event - The event about to be encoded.
125
- * @returns Per-write overrides for this event, or undefined.
126
- */
127
- resolveWriteOptions?: (event: TEvent) => WriteOptions | undefined;
128
- }
129
-
130
- /** The result of streaming a response through the encoder. */
131
- export interface StreamResult {
132
- /** Why the stream ended. */
133
- reason: TurnEndReason;
134
- /**
135
- * The error that caused the stream to fail, present when `reason` is
136
- * `'error'`. This is the original error (e.g. from the LLM provider)
137
- * preserved so the caller can inspect provider-specific fields. The
138
- * turn's `onError` callback also fires with a wrapped `Ably.ErrorInfo`
139
- * (code `StreamError`) for standardized observability.
140
- */
141
- error?: Error;
142
- }
143
-
144
- /** Options passed to newTurn for configuring the turn lifecycle. */
145
- export interface NewTurnOptions<TEvent> {
146
- /** The turn identifier (generated by the client transport or the server). */
147
- turnId: string;
148
-
149
- /** The user's clientId for attribution. */
150
- clientId?: string;
151
-
152
- /**
153
- * The msg-id of the immediately preceding message in this branch.
154
- * Used as the default parent for user messages (via addMessages) and
155
- * assistant messages (via streamResponse) when not overridden per-operation.
156
- */
157
- parent?: string;
158
-
159
- /**
160
- * The msg-id of the message this turn replaces (creates a fork).
161
- * Stamped on user messages (for edits) or assistant messages
162
- * (for regeneration).
163
- */
164
- forkOf?: string;
165
-
166
- /**
167
- * Called before each Ably message is published in this turn.
168
- * Mutate the Ably message in place to add custom extras.headers.
169
- */
170
- onMessage?: (message: Ably.Message) => void;
171
-
172
- /**
173
- * Called when the turn's stream is aborted (by cancel or server).
174
- * Receives a write function to publish final events before the abort finalises.
175
- */
176
- onAbort?: (write: (event: TEvent) => Promise<void>) => void | Promise<void>;
177
-
178
- /**
179
- * Called when a cancel message arrives matching this turn.
180
- * Return true to allow cancellation (fires abortSignal, stream aborts).
181
- * Return false to reject (cancel ignored, stream continues).
182
- * If not provided, all cancels are accepted.
183
- */
184
- onCancel?: (request: CancelRequest) => Promise<boolean>;
185
-
186
- /**
187
- * Called with non-fatal turn-scoped errors that have no other delivery
188
- * path. Fires in two scenarios:
189
- * - Stream failures in `streamResponse` — the underlying error is also
190
- * returned on `StreamResult.error`, but this callback delivers it
191
- * wrapped as an `Ably.ErrorInfo` (code `StreamError`) for standardized
192
- * observability.
193
- * - Failures in the `onCancel` handler.
194
- *
195
- * Publish failures in `start`, `addMessages`, `addEvents`, and `end`
196
- * are not delivered here — those methods reject their returned promise
197
- * with an `Ably.ErrorInfo`, and the caller should handle it at the await
198
- * site. Turn errors never render the transport unusable, but the turn
199
- * may be in an inconsistent state; the caller should typically `end` it
200
- * with reason `'error'`.
201
- *
202
- * Channel-wide events (e.g. continuity loss) are delivered via the
203
- * transport-level `onError` on {@link ServerTransportOptions}, not here.
204
- */
205
- onError?: (error: Ably.ErrorInfo) => void;
206
-
207
- /**
208
- * An external abort signal (typically the HTTP request's `req.signal`) that,
209
- * when fired, aborts this turn. This allows platform-level cancellation —
210
- * request cancellation, serverless function timeout — to stop LLM generation
211
- * and stream piping gracefully.
212
- */
213
- signal?: AbortSignal;
214
- }
215
-
216
- // ---------------------------------------------------------------------------
217
- // Turn interface
218
- // ---------------------------------------------------------------------------
219
-
220
- /** A server-side turn with explicit lifecycle methods. */
221
- export interface Turn<TEvent, TMessage> {
222
- /** The turn's unique identifier. */
223
- readonly turnId: string;
224
-
225
- /** Abort signal scoped to this turn. Fires when a cancel event arrives for this turnId. */
226
- readonly abortSignal: AbortSignal;
227
-
228
- /** Publish turn-start event to the channel. Must be called before addMessages or streamResponse. */
229
- start(): Promise<void>;
230
-
231
- /**
232
- * Publish user messages to the channel, scoped to this turn.
233
- * Each node's `msgId`, `parentId`, and `forkOf` are used for message identity
234
- * and branching. The node's `headers` override transport-generated defaults
235
- * (e.g. for optimistic reconciliation with the client's inserts).
236
- * @returns The msg-ids of all published messages, in order.
237
- */
238
- addMessages(messages: MessageNode<TMessage>[], options?: AddMessageOptions): Promise<AddMessagesResult>;
239
-
240
- /**
241
- * Pipe a ReadableStream through the encoder to the channel.
242
- * Returns when the stream completes, is cancelled, or errors.
243
- * Does NOT call end() — the caller must call end() after streamResponse returns.
244
- */
245
- streamResponse(stream: ReadableStream<TEvent>, options?: StreamResponseOptions<TEvent>): Promise<StreamResult>;
246
-
247
- /**
248
- * Publish events targeting existing messages in the tree. Each node
249
- * specifies a target message (by `msgId`) and the events to apply.
250
- * Events are encoded and published with the target's `x-ably-msg-id`,
251
- * so receiving clients apply them to the existing node rather than
252
- * creating a new one.
253
- *
254
- * Used for cross-turn updates such as tool result delivery after
255
- * approval or client-side tool execution.
256
- */
257
- addEvents(nodes: EventsNode<TEvent>[]): Promise<void>;
258
-
259
- /** Publish turn-end event to the channel and clean up. */
260
- end(reason: TurnEndReason): Promise<void>;
261
- }
262
-
263
- // ---------------------------------------------------------------------------
264
- // Server transport interface
265
- // ---------------------------------------------------------------------------
266
-
267
- /** Server-side transport that manages turn lifecycles over an Ably channel. */
268
- export interface ServerTransport<TEvent, TMessage> {
269
- /**
270
- * Create a new turn. Synchronous — no channel activity until start() is called.
271
- * The turn is registered for cancel routing immediately so that early cancels
272
- * fire the abort signal.
273
- */
274
- newTurn(options: NewTurnOptions<TEvent>): Turn<TEvent, TMessage>;
275
-
276
- /** Unsubscribe from cancel messages, abort all active turns, and clean up. */
277
- close(): void;
278
- }
279
-
280
- // ---------------------------------------------------------------------------
281
- // Client transport options
282
- // ---------------------------------------------------------------------------
283
-
284
- /** Options for creating a client transport. */
285
- export interface ClientTransportOptions<TEvent, TMessage> {
286
- /** The Ably channel to receive responses on and publish cancel signals to. */
287
- channel: Ably.RealtimeChannel;
288
-
289
- /** The codec to use for encoding/decoding. */
290
- codec: Codec<TEvent, TMessage>;
291
-
292
- /** The client's identity. Sent to the server in the POST body. */
293
- clientId?: string;
294
-
295
- /** Server endpoint URL for the HTTP POST. */
296
- api: string;
297
-
298
- /** Headers for the HTTP POST. Function form for dynamic values (e.g. auth tokens). */
299
- headers?: Record<string, string> | (() => Record<string, string>);
300
-
301
- /** Additional body fields merged into the HTTP POST. Function form for dynamic values. */
302
- body?: Record<string, unknown> | (() => Record<string, unknown>);
303
-
304
- /** Fetch credentials mode for the HTTP POST. */
305
- credentials?: RequestCredentials;
306
-
307
- /** Custom fetch implementation. Defaults to `globalThis.fetch`. */
308
- fetch?: typeof globalThis.fetch;
309
-
310
- /** Initial messages to seed the conversation tree with. Forms a linear chain. */
311
- messages?: TMessage[];
312
-
313
- /** Logger instance for diagnostic output. */
314
- logger?: Logger;
315
- }
316
-
317
- // ---------------------------------------------------------------------------
318
- // Send options
319
- // ---------------------------------------------------------------------------
320
-
321
- /** Per-send options for customizing the HTTP POST and branching metadata. */
322
- export interface SendOptions {
323
- /** Additional fields merged into the HTTP POST body. */
324
- body?: Record<string, unknown>;
325
- /** Additional headers for the HTTP POST. */
326
- headers?: Record<string, string>;
327
- /**
328
- * The msg-id of the message this send replaces (fork).
329
- * Set for regeneration (forkOf an assistant message) or
330
- * edit (forkOf a user message).
331
- */
332
- forkOf?: string;
333
- /**
334
- * The msg-id of the message that precedes this one in the
335
- * conversation thread. If omitted, auto-computed from the last
336
- * message in the view.
337
- */
338
- parent?: string;
339
- }
340
-
341
- // ---------------------------------------------------------------------------
342
- // Turn lifecycle events
343
- // ---------------------------------------------------------------------------
344
-
345
- /** A structured event describing a turn starting or ending. */
346
- export type TurnLifecycleEvent =
347
- | {
348
- type: 'x-ably-turn-start';
349
- turnId: string;
350
- clientId: string;
351
- /** The msg-id of the parent message, if known. Omitted for root turns. */
352
- parent?: string;
353
- /** The msg-id being forked/replaced, if this is a regeneration or edit. */
354
- forkOf?: string;
355
- }
356
- | { type: 'x-ably-turn-end'; turnId: string; clientId: string; reason: TurnEndReason };
357
-
358
- // ---------------------------------------------------------------------------
359
- // Active turn handle
360
- // ---------------------------------------------------------------------------
361
-
362
- /** A handle to an active client-side turn, returned by `send()`, `regenerate()`, and `edit()`. */
363
- export interface ActiveTurn<TEvent> {
364
- /** The decoded event stream for this turn. May error if the delivery guarantee is broken (e.g. POST failure, channel continuity loss). */
365
- stream: ReadableStream<TEvent>;
366
- /** The turn's unique identifier. */
367
- turnId: string;
368
- /** Cancel this specific turn. Publishes a cancel message and closes the local stream. */
369
- cancel(): Promise<void>;
370
- /**
371
- * The msg-ids of optimistically inserted user messages, in order.
372
- * Present when the send included user messages (edit); empty for
373
- * regeneration (no user messages to insert optimistically).
374
- */
375
- optimisticMsgIds: string[];
376
- }
377
-
378
- // ---------------------------------------------------------------------------
379
- // Close options
380
- // ---------------------------------------------------------------------------
381
-
382
- /** Options for closing a client transport. */
383
- export interface CloseOptions {
384
- /** Cancel in-progress turns before closing. Publishes a cancel message to the channel. */
385
- cancel?: CancelFilter;
386
- }
387
-
388
- // ---------------------------------------------------------------------------
389
- // History / pagination
390
- // ---------------------------------------------------------------------------
391
-
392
- /** A single decoded history item with its transport metadata. */
393
- export interface HistoryItem<TMessage> {
394
- /** The decoded domain message. */
395
- message: TMessage;
396
- /** Transport headers for tree identity and ordering. */
397
- headers: Record<string, string>;
398
- /** Ably serial for tree ordering. */
399
- serial: string;
400
- }
401
-
402
- /** A page of decoded history from the channel. Internal to View/decodeHistory. */
403
- export interface HistoryPage<TMessage> {
404
- /** Decoded items in chronological order (oldest first). */
405
- items: HistoryItem<TMessage>[];
406
- /** Raw Ably messages that produced this page, in chronological order. */
407
- rawMessages: Ably.InboundMessage[];
408
- /** Whether there are older pages available. */
409
- hasNext(): boolean;
410
- /** Fetch the next (older) page. Returns undefined if no more pages. */
411
- next(): Promise<HistoryPage<TMessage> | undefined>;
412
- }
413
-
414
- /** Options for loading channel history. */
415
- export interface LoadHistoryOptions {
416
- /** Max messages per page. Default: 100. */
417
- limit?: number;
418
- }
419
-
420
- // ---------------------------------------------------------------------------
421
- // Conversation tree (branching history)
422
- // ---------------------------------------------------------------------------
423
-
424
- /** A node in the conversation tree, representing a single domain message. */
425
- export interface MessageNode<TMessage> {
426
- /** Discriminator — identifies this as a message node. */
427
- kind: 'message';
428
- /** The domain message. */
429
- message: TMessage;
430
- /** The x-ably-msg-id of this node — primary key in the tree. */
431
- msgId: string;
432
- /** Parent node's msg-id (x-ably-parent), or undefined for root messages. */
433
- parentId: string | undefined;
434
- /** The msg-id this node forks from (x-ably-fork-of), or undefined if first version. */
435
- forkOf: string | undefined;
436
- /** Full Ably headers for this message. */
437
- headers: Record<string, string>;
438
- /**
439
- * Ably serial for this message. Lexicographically comparable for total order.
440
- * Used to sort siblings deterministically regardless of delivery/history order.
441
- * Absent for optimistic messages (set when the server relay arrives).
442
- */
443
- serial: string | undefined;
444
- }
445
-
446
- /** @deprecated Use {@link MessageNode} instead. */
447
- export type TreeNode<TMessage> = MessageNode<TMessage>;
448
-
449
- /**
450
- * Materializes a branching conversation tree from a flat oplog.
4
+ * The definitions live in `./types/`, split along the Tree / View / Session
5
+ * boundary. This barrel re-exports them so consumers keep importing from a
6
+ * single module:
451
7
  *
452
- * Owns the complete conversation state every node from live messages and
453
- * history. `flattenNodes()` returns the linear message list for the currently
454
- * selected branches. Events fire for any change across the full tree.
8
+ * - `shared.ts`cross-cutting (RunEndReason, CancelRequest).
9
+ * - `agent.ts` agent session, run runtime, Run / AgentSession.
10
+ * - `tree.ts` conversation-tree nodes, lifecycle events, Tree.
11
+ * - `view.ts` — history pagination, branch selection, View.
12
+ * - `client.ts` — client session options, ActiveRun, ClientSession.
455
13
  */
456
- export interface Tree<TMessage> {
457
- /**
458
- * Get all messages that are siblings (alternatives) at a given
459
- * fork point. Returns an array ordered chronologically by serial.
460
- * The message identified by msgId is always included.
461
- */
462
- getSiblings(msgId: string): TMessage[];
463
-
464
- /** Whether a message has sibling alternatives (i.e., show navigation arrows). */
465
- hasSiblings(msgId: string): boolean;
466
-
467
- /** Get a node by msgId, or undefined if not found. */
468
- getNode(msgId: string): MessageNode<TMessage> | undefined;
469
-
470
- /** Get the stored headers for a node by msgId, or undefined if not found. */
471
- getHeaders(msgId: string): Record<string, string> | undefined;
472
-
473
- // --- Mutation (used by the transport, not the UI) ---
474
-
475
- /**
476
- * Insert or update a message in the tree. Reads parent/forkOf from the
477
- * provided headers. If the message already exists (by msgId), updates
478
- * it in place. The optional serial is the Ably message serial used for
479
- * deterministic sibling ordering.
480
- */
481
- upsert(msgId: string, message: TMessage, headers: Record<string, string>, serial?: string): void;
482
-
483
- /** Remove a message from the tree. */
484
- delete(msgId: string): void;
485
-
486
- // --- Events ---
487
-
488
- /** Active turn IDs grouped by clientId (all turns, not just visible). */
489
- getActiveTurnIds(): Map<string, Set<string>>;
490
-
491
- /** Subscribe to tree structure changes (insert, update, delete). */
492
- on(event: 'update', handler: () => void): () => void;
493
-
494
- /** Subscribe to raw Ably messages arriving on the channel. */
495
- on(event: 'ably-message', handler: (msg: Ably.InboundMessage) => void): () => void;
496
-
497
- /** Subscribe to turn lifecycle events (start and end). */
498
- on(event: 'turn', handler: (event: TurnLifecycleEvent) => void): () => void;
499
- }
500
-
501
- // ---------------------------------------------------------------------------
502
- // View — windowed projection over the tree
503
- // ---------------------------------------------------------------------------
504
-
505
- /**
506
- * A paginated, branch-aware projection of the conversation tree.
507
- *
508
- * Returns only the visible portion of the selected branch. New live messages
509
- * appear immediately; older messages are revealed progressively via
510
- * `loadOlder()`. Events are scoped to the visible window — subscribers
511
- * are only notified when the visible output changes.
512
- */
513
- export interface View<TEvent, TMessage> {
514
- /** The visible domain messages along the selected branch. Shorthand for `flattenNodes().map(n => n.message)`. */
515
- getMessages(): TMessage[];
516
-
517
- /** Visible nodes along the selected branch, filtered by the pagination window. */
518
- flattenNodes(): MessageNode<TMessage>[];
519
-
520
- /** Whether there are older messages that can be loaded or revealed. */
521
- hasOlder(): boolean;
522
-
523
- /**
524
- * Reveal older messages. Loads from channel history if the tree doesn't
525
- * have enough, then advances the window to show up to `limit` more messages.
526
- * Emits 'update' when the visible list changes.
527
- * @param limit - Maximum number of older messages to reveal. Defaults to 100.
528
- */
529
- loadOlder(limit?: number): Promise<void>;
530
-
531
- // --- Branch navigation ---
532
-
533
- /**
534
- * Select a sibling at a fork point by index. Updates this view's
535
- * branch selection. Index is clamped to `[0, siblings.length - 1]`.
536
- * Emits 'update' when the visible output changes.
537
- */
538
- select(msgId: string, index: number): void;
539
-
540
- /** Get the index of the currently selected sibling at a fork point. */
541
- getSelectedIndex(msgId: string): number;
542
-
543
- /**
544
- * Get all messages that are siblings (alternatives) at a given
545
- * fork point. Returns an array ordered chronologically by serial.
546
- */
547
- getSiblings(msgId: string): TMessage[];
548
-
549
- /** Whether a message has sibling alternatives (i.e., show navigation arrows). */
550
- hasSiblings(msgId: string): boolean;
551
-
552
- /** Get a node by msgId, or undefined if not found. */
553
- getNode(msgId: string): MessageNode<TMessage> | undefined;
554
-
555
- // --- Write operations ---
556
-
557
- /**
558
- * Send one or more messages and start a new turn. The parent is
559
- * auto-computed from this view's selected branch unless overridden.
560
- * The HTTP POST is fire-and-forget — the returned stream is available
561
- * immediately. If the POST fails, the error is surfaced via the
562
- * transport's `on("error")` and the stream is errored.
563
- */
564
- send(messages: TMessage | TMessage[], options?: SendOptions): Promise<ActiveTurn<TEvent>>;
565
-
566
- /**
567
- * Regenerate an assistant message. Creates a new turn that forks the
568
- * target message with no new user messages. Automatically computes
569
- * `forkOf`, `parent`, and truncated `history` from this view's branch.
570
- */
571
- regenerate(messageId: string, options?: SendOptions): Promise<ActiveTurn<TEvent>>;
572
-
573
- /**
574
- * Edit a user message. Creates a new turn that forks the target message
575
- * with replacement content. Automatically computes `forkOf`, `parent`,
576
- * and `history` from this view's branch.
577
- */
578
- edit(messageId: string, newMessages: TMessage | TMessage[], options?: SendOptions): Promise<ActiveTurn<TEvent>>;
579
-
580
- /**
581
- * Update an existing message and start a continuation turn.
582
- * The local tree is updated optimistically, then the events are sent
583
- * to the server in the POST body. The server publishes them to the channel
584
- * and streams a continuation response.
585
- * @param msgId - The `x-ably-msg-id` of the existing message to amend.
586
- * @param events - Events to apply to the target message (e.g. tool output).
587
- * @param options - Optional send options (body, headers).
588
- * @returns An active turn with the continuation response stream.
589
- */
590
- update(msgId: string, events: TEvent[], options?: SendOptions): Promise<ActiveTurn<TEvent>>;
591
-
592
- // --- Observation ---
593
-
594
- /** Active turn IDs for turns with visible messages, grouped by clientId. */
595
- getActiveTurnIds(): Map<string, Set<string>>;
596
-
597
- /** The visible message list changed (new visible node, branch switch, window shift). */
598
- on(event: 'update', handler: () => void): () => void;
599
-
600
- /** A raw Ably message arrived that corresponds to a visible node. */
601
- on(event: 'ably-message', handler: (msg: Ably.InboundMessage) => void): () => void;
602
-
603
- /** A turn event occurred for a turn with visible messages in the window. */
604
- on(event: 'turn', handler: (event: TurnLifecycleEvent) => void): () => void;
605
-
606
- /** Tear down the view — unsubscribe from tree events and clear internal state. */
607
- close(): void;
608
- }
609
-
610
- // ---------------------------------------------------------------------------
611
- // Internal sub-component types
612
- // ---------------------------------------------------------------------------
613
-
614
- /** Entry in the StreamRouter's turn map. Not part of the public API. */
615
- export interface TurnEntry<TEvent> {
616
- /** The ReadableStream controller for this turn. */
617
- controller: ReadableStreamDefaultController<TEvent>;
618
- /** The turn's unique identifier. */
619
- turnId: string;
620
- }
621
-
622
- // ---------------------------------------------------------------------------
623
- // Client transport interface
624
- // ---------------------------------------------------------------------------
625
-
626
- /** Client-side transport that manages conversation state over an Ably channel. */
627
- export interface ClientTransport<TEvent, TMessage> {
628
- /** The complete conversation tree — all known nodes, events for any change. */
629
- readonly tree: Tree<TMessage>;
630
-
631
- /** The default paginated, branch-aware view for rendering — events scoped to visible messages. */
632
- readonly view: View<TEvent, TMessage>;
633
-
634
- /**
635
- * Create an additional view over the same conversation tree.
636
- * Each view has independent branch selections and pagination state.
637
- * The caller is responsible for calling `close()` on the returned view
638
- * when it is no longer needed, or it will be closed when the transport closes.
639
- */
640
- createView(): View<TEvent, TMessage>;
641
-
642
- /** Cancel turns matching the filter. Defaults to `{ own: true }` (all own turns). */
643
- cancel(filter?: CancelFilter): Promise<void>;
644
-
645
- /**
646
- * Apply events to an existing tree message locally and queue them for
647
- * delivery on the next send.
648
- *
649
- * Use for cross-turn updates where the event value is produced on the
650
- * client (e.g. after `addToolResult` resolves a client-executed tool) and
651
- * must appear in the tree immediately so downstream observers — such as a
652
- * destructive `setMessages(...)` mirror — cannot wipe it before it lands
653
- * on the wire.
654
- *
655
- * The events are applied to the tree via the codec's accumulator
656
- * (tree `update` fires once with the merged message) and queued on the
657
- * transport. The next send operation flushes the queue into the POST
658
- * body's `events` field so the server can republish them over the channel.
659
- *
660
- * If `msgId` is not present in the tree, the call is a no-op and a
661
- * warning is logged.
662
- * @param msgId - The x-ably-msg-id of the existing message to amend.
663
- * @param events - Events to apply and later ship.
664
- */
665
- stageEvents(msgId: string, events: TEvent[]): void;
666
-
667
- /**
668
- * Replace the tree's copy of an existing message with a caller-provided
669
- * version, preserving headers and serial.
670
- *
671
- * Use for useChat-style state transitions the codec can't express as
672
- * chunks — the canonical example is `addToolApprovalResponse`, which
673
- * sets `state: 'approval-responded'` on a `dynamic-tool` part directly
674
- * on the UIMessage and has no corresponding chunk variant.
675
- *
676
- * Unlike {@link stageEvents}, staged messages are NOT queued for the
677
- * next send: the tree is authoritative for the POST body's history,
678
- * so updating it is sufficient.
679
- *
680
- * Runs synchronously. Subsequent tree observers (e.g. useMessageSync)
681
- * see the patched state on the next tick, so an interleaved
682
- * observer-turn sync can't clobber it back.
683
- *
684
- * If `msgId` is not present in the tree, the call is a no-op and a
685
- * warning is logged.
686
- * @param msgId - The x-ably-msg-id of the existing message to replace.
687
- * @param message - The patched message to store.
688
- */
689
- stageMessage(msgId: string, message: TMessage): void;
690
-
691
- /**
692
- * Returns a promise that resolves when all active turns matching the filter
693
- * have completed. Resolves immediately if no matching turns are active.
694
- * Defaults to `{ own: true }`.
695
- */
696
- waitForTurn(filter?: CancelFilter): Promise<void>;
697
-
698
- /**
699
- * Subscribe to non-fatal transport errors. These indicate something went
700
- * wrong but the transport is still operational. Returns an unsubscribe function.
701
- */
702
- on(event: 'error', handler: (error: Ably.ErrorInfo) => void): () => void;
703
14
 
704
- /**
705
- * Tear down the transport: unsubscribe from the channel, close active
706
- * streams, clear all handlers, and prevent further operations.
707
- *
708
- * Pass `cancel` to publish a cancel message before closing. Without it,
709
- * only local state is torn down (the server keeps streaming).
710
- */
711
- close(options?: CloseOptions): Promise<void>;
712
- }
15
+ export type * from './types/agent.js';
16
+ export type * from './types/client.js';
17
+ export type * from './types/shared.js';
18
+ export type * from './types/tree.js';
19
+ export type * from './types/view.js';