@ably/ai-transport 0.0.1 → 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 (167) hide show
  1. package/README.md +114 -116
  2. package/dist/ably-ai-transport.js +1743 -961
  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 +117 -39
  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 +410 -101
  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 +97 -17
  18. package/dist/core/transport/index.d.ts +5 -3
  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 -8
  24. package/dist/core/transport/run-manager.d.ts +78 -0
  25. package/dist/core/transport/tree.d.ts +435 -0
  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 -402
  32. package/dist/core/transport/view.d.ts +354 -0
  33. package/dist/errors.d.ts +37 -9
  34. package/dist/index.d.ts +6 -6
  35. package/dist/logger.d.ts +12 -0
  36. package/dist/react/ably-ai-transport-react.js +1164 -645
  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 +16 -10
  44. package/dist/react/internal/use-resolved-session.d.ts +36 -0
  45. package/dist/react/use-ably-messages.d.ts +20 -11
  46. package/dist/react/use-client-session.d.ts +81 -0
  47. package/dist/react/use-create-view.d.ts +23 -0
  48. package/dist/react/use-tree.d.ts +35 -0
  49. package/dist/react/use-view.d.ts +110 -0
  50. package/dist/utils.d.ts +32 -23
  51. package/dist/vercel/ably-ai-transport-vercel.js +2748 -1625
  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 +50 -0
  61. package/dist/vercel/index.d.ts +4 -2
  62. package/dist/vercel/react/ably-ai-transport-vercel-react.js +10298 -1410
  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 +70 -1
  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 +33 -0
  67. package/dist/vercel/react/contexts/chat-transport-provider.d.ts +96 -0
  68. package/dist/vercel/react/index.d.ts +4 -0
  69. package/dist/vercel/react/use-chat-transport.d.ts +66 -21
  70. package/dist/vercel/react/use-message-sync.d.ts +31 -12
  71. package/dist/vercel/run-end-reason.d.ts +29 -0
  72. package/dist/vercel/transport/chat-transport.d.ts +71 -30
  73. package/dist/vercel/transport/index.d.ts +25 -18
  74. package/dist/vercel/transport/run-output-stream.d.ts +56 -0
  75. package/dist/version.d.ts +2 -0
  76. package/package.json +47 -34
  77. package/src/constants.ts +126 -47
  78. package/src/core/agent.ts +68 -0
  79. package/src/core/codec/decoder.ts +71 -98
  80. package/src/core/codec/encoder.ts +115 -58
  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 +438 -106
  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 +182 -19
  89. package/src/core/transport/index.ts +29 -22
  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 +58 -40
  95. package/src/core/transport/run-manager.ts +249 -0
  96. package/src/core/transport/tree.ts +1167 -0
  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 -527
  103. package/src/core/transport/view.ts +1271 -0
  104. package/src/errors.ts +42 -9
  105. package/src/event-emitter.ts +3 -2
  106. package/src/index.ts +55 -39
  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 +27 -10
  112. package/src/react/internal/use-resolved-session.ts +63 -0
  113. package/src/react/use-ably-messages.ts +47 -19
  114. package/src/react/use-client-session.ts +201 -0
  115. package/src/react/use-create-view.ts +72 -0
  116. package/src/react/use-tree.ts +84 -0
  117. package/src/react/use-view.ts +275 -0
  118. package/src/react/vite.config.ts +4 -1
  119. package/src/utils.ts +63 -45
  120. package/src/vercel/codec/decoder.ts +336 -255
  121. package/src/vercel/codec/encoder.ts +348 -196
  122. package/src/vercel/codec/events.ts +87 -0
  123. package/src/vercel/codec/index.ts +59 -14
  124. package/src/vercel/codec/reducer.ts +977 -0
  125. package/src/vercel/codec/tool-transitions.ts +122 -0
  126. package/src/vercel/index.ts +7 -3
  127. package/src/vercel/react/contexts/chat-transport-context.ts +41 -0
  128. package/src/vercel/react/contexts/chat-transport-provider.tsx +150 -0
  129. package/src/vercel/react/index.ts +13 -1
  130. package/src/vercel/react/use-chat-transport.ts +162 -42
  131. package/src/vercel/react/use-message-sync.ts +121 -22
  132. package/src/vercel/react/vite.config.ts +4 -2
  133. package/src/vercel/run-end-reason.ts +78 -0
  134. package/src/vercel/transport/chat-transport.ts +553 -113
  135. package/src/vercel/transport/index.ts +40 -28
  136. package/src/vercel/transport/run-output-stream.ts +170 -0
  137. package/src/version.ts +2 -0
  138. package/dist/core/transport/client-transport.d.ts +0 -10
  139. package/dist/core/transport/conversation-tree.d.ts +0 -9
  140. package/dist/core/transport/decode-history.d.ts +0 -41
  141. package/dist/core/transport/server-transport.d.ts +0 -7
  142. package/dist/core/transport/stream-router.d.ts +0 -19
  143. package/dist/core/transport/turn-manager.d.ts +0 -34
  144. package/dist/react/use-active-turns.d.ts +0 -8
  145. package/dist/react/use-client-transport.d.ts +0 -7
  146. package/dist/react/use-conversation-tree.d.ts +0 -20
  147. package/dist/react/use-edit.d.ts +0 -7
  148. package/dist/react/use-history.d.ts +0 -19
  149. package/dist/react/use-messages.d.ts +0 -7
  150. package/dist/react/use-regenerate.d.ts +0 -7
  151. package/dist/react/use-send.d.ts +0 -7
  152. package/dist/vercel/codec/accumulator.d.ts +0 -21
  153. package/src/core/transport/client-transport.ts +0 -959
  154. package/src/core/transport/conversation-tree.ts +0 -434
  155. package/src/core/transport/decode-history.ts +0 -337
  156. package/src/core/transport/server-transport.ts +0 -458
  157. package/src/core/transport/stream-router.ts +0 -118
  158. package/src/core/transport/turn-manager.ts +0 -147
  159. package/src/react/use-active-turns.ts +0 -61
  160. package/src/react/use-client-transport.ts +0 -37
  161. package/src/react/use-conversation-tree.ts +0 -71
  162. package/src/react/use-edit.ts +0 -24
  163. package/src/react/use-history.ts +0 -111
  164. package/src/react/use-messages.ts +0 -32
  165. package/src/react/use-regenerate.ts +0 -24
  166. package/src/react/use-send.ts +0 -25
  167. package/src/vercel/codec/accumulator.ts +0 -603
@@ -1,8 +1,12 @@
1
1
  /**
2
- * Core codec interfaces as defined in the general codec specification.
2
+ * Core codec interfaces for the event-sourced model.
3
3
  *
4
- * These types define the contract between domain event streams and Ably's
5
- * native message primitives (publish, append, update, delete).
4
+ * The codec describes the wire as a flat stream of TEvent values. A reducer
5
+ * folds events into an opaque TProjection. The SDK extracts TMessage[] from
6
+ * the projection to populate the conversation Tree.
7
+ *
8
+ * All types are framework-agnostic. Domain codecs (e.g. the Vercel codec)
9
+ * choose concrete shapes for TEvent / TProjection / TMessage.
6
10
  */
7
11
 
8
12
  import type * as Ably from 'ably';
@@ -36,12 +40,12 @@ export interface ChannelWriter {
36
40
  }
37
41
 
38
42
  // ---------------------------------------------------------------------------
39
- // WriteOptions — per-write overrides for encoder operations
43
+ // Extras / WriteOptions — per-write overrides for encoder operations
40
44
  // ---------------------------------------------------------------------------
41
45
 
42
- /** Shape of the extras object passed through WriteOptions and EncoderOptions. */
46
+ /** Shape of the extras config passed through WriteOptions and EncoderOptions. */
43
47
  export interface Extras {
44
- /** Headers to attach to the Ably message extras. */
48
+ /** Transport-tier headers to attach to the message's `extras.ai.transport` namespace. */
45
49
  headers?: Record<string, string>;
46
50
  }
47
51
 
@@ -51,20 +55,21 @@ export interface WriteOptions {
51
55
  clientId?: string;
52
56
  /** Override the default extras for this write. */
53
57
  extras?: Extras;
54
- /** Message identity for accumulator correlation. Stamped as `x-ably-msg-id`. */
58
+ /** Message identity for projection routing. Stamped as `codec-message-id`. */
55
59
  messageId?: string;
56
60
  }
57
61
 
58
62
  // ---------------------------------------------------------------------------
59
- // MessagePayload shared description of a message for encode and decode
63
+ // MessagePayload / StreamPayload codec-internal wire descriptions
60
64
  // ---------------------------------------------------------------------------
61
65
 
62
66
  /**
63
67
  * A codec-agnostic description of a discrete Ably message. Used on both sides:
64
68
  * - **Encode:** the domain encoder describes what to publish; the encoder core
65
69
  * handles header merging, clientId resolution, and the actual publish.
66
- * - **Decode:** the decoder core extracts these fields from an `Ably.InboundMessage`
67
- * before calling domain hooks, keeping hooks free of Ably SDK types.
70
+ * - **Decode:** the decoder core extracts these fields from an
71
+ * `Ably.InboundMessage` before calling domain hooks, keeping hooks free of
72
+ * Ably SDK types.
68
73
  *
69
74
  * Data is `unknown` because discrete messages can carry arbitrary payloads
70
75
  * (strings, objects, etc.) — Ably handles serialization natively.
@@ -74,24 +79,35 @@ export interface MessagePayload {
74
79
  name: string;
75
80
  /** Message data. Ably handles serialization — strings, objects, and arrays are all valid. */
76
81
  data: unknown;
77
- /** Headers from the Ably message extras. */
78
- headers?: Record<string, string>;
82
+ /** Codec-tier headers the codec's own fields, carried under `extras.ai.codec`. */
83
+ codecHeaders?: Record<string, string>;
84
+ /**
85
+ * Transport-tier headers a codec needs to stamp directly (e.g. `role`,
86
+ * `status`), carried under `extras.ai.transport`. Most codec payloads leave
87
+ * this unset and let the transport layer supply transport headers via config.
88
+ */
89
+ transportHeaders?: Record<string, string>;
79
90
  /** Mark this message as ephemeral (not persisted in channel history). Only meaningful on encode. */
80
91
  ephemeral?: boolean;
81
92
  }
82
93
 
83
94
  /**
84
- * Payload for streamed messages. Data must be a string because
85
- * the message append lifecycle uses text append/accumulate semantics —
86
- * deltas are concatenated for recovery and prefix-matching on the decoder.
95
+ * Payload for streamed messages. Data must be a string because the message
96
+ * append lifecycle uses text append/accumulate semantics — deltas are
97
+ * concatenated for recovery and prefix-matching on the decoder.
87
98
  */
88
99
  export interface StreamPayload {
89
100
  /** Ably message name (e.g. "text", "reasoning", "tool-input"). */
90
101
  name: string;
91
102
  /** Initial or closing data for the stream. Must be a string for append/accumulate semantics. */
92
103
  data: string;
93
- /** Headers from the Ably message extras. */
94
- headers?: Record<string, string>;
104
+ /** Codec-tier headers the codec's own fields, carried under `extras.ai.codec`. */
105
+ codecHeaders?: Record<string, string>;
106
+ /**
107
+ * Transport-tier headers a codec needs to stamp directly (e.g. `role`,
108
+ * `status`), carried under `extras.ai.transport`.
109
+ */
110
+ transportHeaders?: Record<string, string>;
95
111
  }
96
112
 
97
113
  // ---------------------------------------------------------------------------
@@ -109,141 +125,457 @@ export interface StreamTrackerState {
109
125
  streamId: string;
110
126
  /** Full accumulated text so far. */
111
127
  accumulated: string;
112
- /** Current headers for this stream. Initially set from the first publish, but may be replaced on update. */
113
- headers: Record<string, string>;
114
- /** Whether this stream has been closed (finished or aborted). */
128
+ /**
129
+ * Current codec-tier headers (`extras.ai.codec`) for this stream. Initially
130
+ * set from the first publish, but may be replaced on update.
131
+ */
132
+ codecHeaders: Record<string, string>;
133
+ /**
134
+ * Current transport-tier headers (`extras.ai.transport`) for this stream.
135
+ * Initially set from the first publish, but may be replaced on update.
136
+ */
137
+ transportHeaders: Record<string, string>;
138
+ /** Whether this stream has been closed (complete or cancelled). */
115
139
  closed: boolean;
116
140
  }
117
141
 
118
142
  // ---------------------------------------------------------------------------
119
- // DiscreteEncoderstateless discrete publish operations
143
+ // Reducerpure event-sourced state machine
120
144
  // ---------------------------------------------------------------------------
121
145
 
122
146
  /**
123
- * The subset of encoder operations that are stateless — safe for long-lived
124
- * reuse across turns. Publishes complete messages and discrete events without
125
- * any streaming lifecycle (no trackers, no pending appends, no close).
147
+ * Transport-derived metadata passed alongside each TEvent into `fold`. Read
148
+ * by the SDK from the inbound Ably message and stamped before each fold call.
149
+ */
150
+ export interface ReducerMeta {
151
+ /**
152
+ * Ably channel serial of the message that produced this event. The reducer
153
+ * uses this for idempotency / dedup: events at or below the projection's
154
+ * high-water-mark serial must be skipped (no-op return).
155
+ */
156
+ serial: string;
157
+ /**
158
+ * Optional `codec-message-id` from the inbound Ably message. Reducers use this
159
+ * to route an event to a target message within the projection (e.g. to
160
+ * amend an existing assistant message addressed by its codec-message-id).
161
+ */
162
+ messageId?: string;
163
+ }
164
+
165
+ /**
166
+ * Pure, stateless reducer contract. A reducer folds TEvents into an opaque
167
+ * TProjection. The same `(state, event, meta)` triple must produce the same
168
+ * result every time — `fold` is a pure function and the reducer holds no
169
+ * instance state.
170
+ *
171
+ * Idempotency: re-folding an event whose serial has already been incorporated
172
+ * must be a no-op. The reducer is free to store a high-water-mark inside the
173
+ * projection.
126
174
  *
127
- * The server transport calls `writeMessages` to publish user messages to the
128
- * channel. All messages in a single call are published atomically and share
129
- * a single `x-ably-msg-id`, forming one node in the conversation tree.
130
- * `writeEvent` is a public API for consumers to publish standalone discrete
131
- * events outside the streaming flow — it is not called by the transport internally.
175
+ * Mutation: `fold` is allowed to mutate the projection passed in and return
176
+ * it. The caller treats the projection as single-owner and never retains a
177
+ * reference to an old state.
132
178
  */
133
- export interface DiscreteEncoder<TEvent, TMessage> {
179
+ export interface Reducer<TEvent, TProjection> {
134
180
  /**
135
- * Encode and publish one or more domain messages atomically in a single
136
- * channel publish. All messages share the encoder's transport headers
137
- * (including `x-ably-msg-id`), so they form one logical unit in the
138
- * conversation tree.
181
+ * Build an empty initial projection. Called once per conversation node a
182
+ * Run node or a run-less input node — before any of that node's events are
183
+ * folded.
139
184
  */
140
- writeMessages(messages: TMessage[], options?: WriteOptions): Promise<Ably.PublishResult>;
185
+ init(): TProjection;
141
186
  /**
142
- * Encode and publish a single domain event as a standalone discrete message.
143
- * Available for consumers to publish events outside the streaming flow.
144
- * Implementations should throw for event types that are only meaningful
145
- * within a stream (e.g. text deltas).
187
+ * Fold one TEvent into the projection and return the updated projection.
188
+ * The reducer may mutate `state` in place.
146
189
  */
147
- writeEvent(event: TEvent, options?: WriteOptions): Promise<Ably.PublishResult>;
190
+ fold(state: TProjection, event: TEvent, meta: ReducerMeta): TProjection;
148
191
  }
149
192
 
150
193
  // ---------------------------------------------------------------------------
151
- // StreamEncodermaps domain events to Ably channel operations
194
+ // Encoderdirection-typed publication API
152
195
  // ---------------------------------------------------------------------------
153
196
 
197
+ /** Options passed to a codec's `createEncoder` factory. */
198
+ export interface EncoderOptions {
199
+ /** Default clientId for all writes. */
200
+ clientId?: string;
201
+ /** Default extras (e.g. headers) merged into every Ably message. */
202
+ extras?: Extras;
203
+ /** Hook called before each Ably message is published. Mutate the message in place to add transport-level headers under `extras.ai`. */
204
+ onMessage?: (message: Ably.Message) => void;
205
+ /**
206
+ * Default `codec-message-id` for messages where the event payload doesn't
207
+ * supply one. Overridden by `WriteOptions.messageId` per-publish.
208
+ */
209
+ messageId?: string;
210
+ }
211
+
154
212
  /**
155
- * Full streaming encoder with single-turn lifecycle. Extends
156
- * `DiscreteEncoder` with stateful streaming operations (`appendEvent` for
157
- * content streams, `close` to flush). Used by the server transport.
213
+ * Stateful encoder for a single channel. Two publish methods enforce
214
+ * direction at the call site `publishInput` for client-published events
215
+ * (`ai-input` wire) and `publishOutput` for agent-published events
216
+ * (`ai-output` wire). Stream-tracker state lives inside the encoder and
217
+ * is shared across both directions.
158
218
  */
159
- export interface StreamEncoder<TEvent, TMessage> extends DiscreteEncoder<TEvent, TMessage> {
160
- /** Encode and append a streaming domain event to an in-progress stream (delta semantics). */
161
- appendEvent(event: TEvent, options?: WriteOptions): Promise<void>;
219
+ export interface Encoder<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent> {
220
+ /**
221
+ * Encode and publish a single client input on the `ai-input` wire.
222
+ * Throws synchronously if the codec cannot encode the given input
223
+ * variant.
224
+ */
225
+ publishInput(input: TInput, options?: WriteOptions): Promise<void>;
226
+ /**
227
+ * Encode and publish a single agent output on the `ai-output` wire.
228
+ * Throws synchronously if the codec cannot encode the given output
229
+ * variant.
230
+ */
231
+ publishOutput(output: TOutput, options?: WriteOptions): Promise<void>;
162
232
  /**
163
- * Abort all in-progress streams and publish a codec-specific abort signal.
164
- * Called by the transport when a turn is cancelled. Idempotent — calling
165
- * abort after all streams are already aborted is a no-op.
166
- * @param reason - Optional reason string for the abort (e.g. 'cancelled').
233
+ * Cancel any in-progress streams and emit a codec-specific cancel signal.
234
+ * Idempotent across repeated calls a second `cancel` is a no-op. Must not
235
+ * be called after `close`; doing so throws because the encoder is already
236
+ * closed.
237
+ * @param reason - Optional reason string for the cancellation (e.g. 'cancelled').
167
238
  */
168
- abort(reason?: string): Promise<void>;
169
- /** Flush all pending appends and close the encoder. */
239
+ cancel(reason?: string): Promise<void>;
240
+ /** Flush pending appends and release encoder resources. */
170
241
  close(): Promise<void>;
171
242
  }
172
243
 
173
244
  // ---------------------------------------------------------------------------
174
- // DecoderOutputunified return type from the decoder
245
+ // Decoderdirection-tagged output
175
246
  // ---------------------------------------------------------------------------
176
247
 
177
248
  /**
178
- * A single output from the decoder: either a domain event or a complete domain message.
179
- * Event outputs may carry a `messageId` read from the `x-ably-msg-id` header, which the
180
- * accumulator uses to route events to the correct in-progress message.
249
+ * Tagged result of decoding one inbound Ably message the codec routes
250
+ * by the wire `name` and returns inputs and outputs separately so the
251
+ * SDK never has to introspect direction.
181
252
  */
182
- export type DecoderOutput<TEvent, TMessage> =
183
- | { kind: 'event'; event: TEvent; messageId?: string }
184
- | { kind: 'message'; message: TMessage };
253
+ export interface DecodedMessage<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent> {
254
+ /** Inputs decoded from the inbound message (only populated when the wire `name` is `ai-input`). */
255
+ inputs: TInput[];
256
+ /** Outputs decoded from the inbound message (only populated when the wire `name` is `ai-output`). */
257
+ outputs: TOutput[];
258
+ }
259
+
260
+ /**
261
+ * Stateful decoder for a single channel subscription. Maintains internal
262
+ * stream-tracker state across messages so that mid-stream join (history
263
+ * compaction, partial-history page boundary, rewind miss) synthesizes any
264
+ * missing start events before deltas reach the SDK — the reducer always
265
+ * sees a clean `(start, delta*, end)` sequence.
266
+ */
267
+ export interface Decoder<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent> {
268
+ /** Decode one Ably inbound message into the input/output halves. */
269
+ decode(message: Ably.InboundMessage): DecodedMessage<TInput, TOutput>;
270
+ }
185
271
 
186
272
  // ---------------------------------------------------------------------------
187
- // StreamDecoder maps Ably messages to decoder outputs
273
+ // Codec input events well-known input variant shapes
188
274
  // ---------------------------------------------------------------------------
189
275
 
190
- /** Decodes Ably messages into domain events and messages. */
191
- export interface StreamDecoder<TEvent, TMessage> {
192
- /** Decode a single Ably message into zero or more domain outputs. */
193
- decode(message: Ably.InboundMessage): DecoderOutput<TEvent, TMessage>[];
276
+ /**
277
+ * Structural base every codec input variant must satisfy. Codec authors
278
+ * compose their `TInput` union from variants extending this type; the
279
+ * transport reads the routing fields directly off the variant to stamp
280
+ * wire headers, so no runtime classification step is needed.
281
+ *
282
+ * The `kind` discriminator is required on every variant so the codec's
283
+ * reducer can switch on it. Codec authors pick the literal value per
284
+ * variant; the SDK ships well-known literals (`'user-message'`,
285
+ * `'regenerate'`) — see {@link UserMessage}, {@link Regenerate}.
286
+ */
287
+ export interface CodecInputEvent {
288
+ /**
289
+ * Discriminator. Codec authors pick the literal value per variant. The
290
+ * SDK reserves the literals used by well-known variants
291
+ * ({@link UserMessage}, {@link Regenerate}); codec-specific variants pick
292
+ * any other literal.
293
+ */
294
+ kind: string;
295
+ /**
296
+ * Sets the wire `parent` header — the codec-message-id of the
297
+ * preceding codec-message on this branch. When omitted, the SDK
298
+ * auto-computes the parent from the visible branch tail at send time.
299
+ */
300
+ parent?: string;
301
+ /**
302
+ * Pointer to another codec-message this input references. The semantic
303
+ * depends on `kind` — for `regenerate`, the assistant codec-message to
304
+ * regenerate; codec-specific `kind`s may give it other meanings. The
305
+ * input event itself does not create a fork — it requests one. The fork
306
+ * relationship is established on the agent's response (and on
307
+ * `ai-run-start`), which the codec encoder maps `target` to via the
308
+ * wire's `fork-of` header.
309
+ */
310
+ target?: string;
311
+ /**
312
+ * Targets an existing codec-message-id instead of minting a fresh one.
313
+ * Used by continuation inputs (tool results, approval responses) that
314
+ * amend an existing assistant message rather than creating a new one;
315
+ * the wire's `codec-message-id` is stamped with this value so
316
+ * the reducer's direct-fold path matches by codec-message-id.
317
+ */
318
+ codecMessageId?: string;
319
+ }
320
+
321
+ /**
322
+ * Well-known input variant: a new user message in the codec's domain
323
+ * representation. Pinned `kind: 'user-message'`. Produced by the SDK's
324
+ * `Codec.createUserMessage` factory and published via `View.send`
325
+ * (e.g. `view.send(codec.createUserMessage(message))`).
326
+ * @template TMessage - The codec's per-message domain type.
327
+ */
328
+ export interface UserMessage<TMessage> extends CodecInputEvent {
329
+ /** Discriminator. */
330
+ kind: 'user-message';
331
+ /** The user's message in the codec's domain representation. */
332
+ message: TMessage;
194
333
  }
195
334
 
335
+ /**
336
+ * Well-known input variant: request that an existing assistant
337
+ * codec-message be regenerated. Pinned `kind: 'regenerate'`. This event
338
+ * is a signal, not itself a fork — `target` names the assistant message
339
+ * to regenerate, and `parent` names the user message the new assistant
340
+ * threads under. Both are required; the codec cannot regenerate without
341
+ * both. Produced by the SDK's `Codec.createRegenerate` factory and
342
+ * surfaced via `View.regenerate`.
343
+ */
344
+ export interface Regenerate extends CodecInputEvent {
345
+ /** Discriminator. */
346
+ kind: 'regenerate';
347
+ /** The codec-message-id of the assistant to regenerate. Required. */
348
+ target: string;
349
+ /** The codec-message-id of the parent user message the new assistant threads under. Required. */
350
+ parent: string;
351
+ }
352
+
353
+ /**
354
+ * Well-known input variant: client-published tool result (success). The
355
+ * tool ran and produced output. Mutates the assistant codec-message
356
+ * addressed by `codecMessageId` — the codec's reducer applies the result
357
+ * onto the existing tool-call state of the referenced assistant.
358
+ *
359
+ * The core is domain-independent: it knows only that this input amends the
360
+ * assistant at `codecMessageId` and carries a codec-defined `payload`. The
361
+ * shape of `payload` (e.g. the tool-call id and output value) is supplied
362
+ * by the codec via `TPayload` — see the Vercel layer's payload type.
363
+ *
364
+ * Codecs opt in to client-side tool resolution by including this variant
365
+ * in their `TInput` union. Codecs whose domain model doesn't natively
366
+ * distinguish client-side tool results as a top-level event type (e.g.
367
+ * Anthropic Messages, where tool results are normally embedded in a
368
+ * user-role message) can still use this variant — the codec's reducer
369
+ * translates the wire-level update into the codec's domain representation.
370
+ * @template TPayload - The codec's domain payload for a tool result.
371
+ */
372
+ export interface ToolResult<TPayload> extends CodecInputEvent {
373
+ /** Discriminator. */
374
+ kind: 'tool-result';
375
+ /** The assistant codec-message containing the tool call. Required. */
376
+ codecMessageId: string;
377
+ /** The codec's domain payload describing the tool result. */
378
+ payload: TPayload;
379
+ }
380
+
381
+ /**
382
+ * Well-known input variant: client-published tool result (failure). The
383
+ * tool ran and failed. Mutates the assistant codec-message addressed by
384
+ * `codecMessageId`. The failure detail (e.g. tool-call id and error text)
385
+ * is the codec's domain `payload` — see the Vercel layer's payload type.
386
+ * @template TPayload - The codec's domain payload for a tool-result failure.
387
+ */
388
+ export interface ToolResultError<TPayload> extends CodecInputEvent {
389
+ /** Discriminator. */
390
+ kind: 'tool-result-error';
391
+ /** The assistant codec-message containing the tool call. Required. */
392
+ codecMessageId: string;
393
+ /** The codec's domain payload describing the failure. */
394
+ payload: TPayload;
395
+ }
396
+
397
+ /**
398
+ * Well-known input variant: client-published response to an
399
+ * agent-emitted tool-approval request. Mutates the assistant
400
+ * codec-message addressed by `codecMessageId` — flipping the targeted
401
+ * tool call from pending-approval to approved or denied. The decision
402
+ * detail (e.g. tool-call id, approved flag, reason) is the codec's domain
403
+ * `payload` — see the Vercel layer's payload type.
404
+ *
405
+ * Codecs may layer approval semantics on top of domain models that don't
406
+ * natively support gating tool execution behind an approval — the codec
407
+ * is responsible for mapping the decision into its own representation.
408
+ * @template TPayload - The codec's domain payload for an approval response.
409
+ */
410
+ export interface ToolApprovalResponse<TPayload> extends CodecInputEvent {
411
+ /** Discriminator. */
412
+ kind: 'tool-approval-response';
413
+ /** The assistant codec-message containing the tool call. Required. */
414
+ codecMessageId: string;
415
+ /** The codec's domain payload describing the approval decision. */
416
+ payload: TPayload;
417
+ }
418
+
419
+ /**
420
+ * Extract the domain `payload` type of a codec's {@link ToolResult} member
421
+ * from its `TInput` union, or `never` if the codec has no tool-result
422
+ * variant. Used to type {@link Codec.createToolResult} without adding a
423
+ * standalone type parameter to the codec.
424
+ * @template TInput - The codec's input union.
425
+ */
426
+ export type ToolResultPayloadOf<TInput> = TInput extends ToolResult<infer P> ? P : never;
427
+
428
+ /**
429
+ * Extract the domain `payload` type of a codec's {@link ToolResultError}
430
+ * member from its `TInput` union, or `never` if absent.
431
+ * @template TInput - The codec's input union.
432
+ */
433
+ export type ToolResultErrorPayloadOf<TInput> = TInput extends ToolResultError<infer P> ? P : never;
434
+
435
+ /**
436
+ * Extract the domain `payload` type of a codec's {@link ToolApprovalResponse}
437
+ * member from its `TInput` union, or `never` if absent.
438
+ * @template TInput - The codec's input union.
439
+ */
440
+ export type ToolApprovalResponsePayloadOf<TInput> = TInput extends ToolApprovalResponse<infer P> ? P : never;
441
+
196
442
  // ---------------------------------------------------------------------------
197
- // MessageAccumulatorbuilds messages from decoder outputs
443
+ // Codec output events base shape for the output side
198
444
  // ---------------------------------------------------------------------------
199
445
 
200
- /** Accumulates decoder outputs into a list of domain messages, tracking active streams. */
201
- export interface MessageAccumulator<TEvent, TMessage> {
202
- /** Process a batch of decoder outputs, updating internal message state. */
203
- processOutputs(outputs: DecoderOutput<TEvent, TMessage>[]): void;
204
- /** Apply an external update to a message (e.g. from an update callback). */
205
- updateMessage(message: TMessage): void;
206
- /** All messages accumulated so far (in-progress and completed). */
207
- readonly messages: TMessage[];
208
- /** Only messages whose streams have finished. */
209
- readonly completedMessages: TMessage[];
210
- /** Whether any stream is still actively receiving data. */
211
- readonly hasActiveStream: boolean;
446
+ /**
447
+ * Structural base every codec output variant must satisfy. The output
448
+ * counterpart of {@link CodecInputEvent}: pins a `type` discriminator so
449
+ * the SDK can reliably narrow `TInput | TOutput` (inputs carry `kind`,
450
+ * outputs carry `type`) and reserves a contract for future routing
451
+ * fields on outputs without a breaking generic-arity change.
452
+ *
453
+ * The `type` discriminator is required on every variant so the codec's
454
+ * reducer can switch on it. `AI.UIMessageChunk` already satisfies this
455
+ * constraint structurally — its `type` literal is assignable to
456
+ * `string` so the Vercel codec needs no implementation changes.
457
+ *
458
+ * No routing fields today: outputs carry no per-event `codecMessageId` /
459
+ * `parent` / `forkOf` overrides. Those move onto this base when a concrete
460
+ * output needs to carry them.
461
+ */
462
+ export interface CodecOutputEvent {
463
+ /** Discriminator. Codec authors pick the literal value per variant. */
464
+ type: string;
212
465
  }
213
466
 
214
467
  // ---------------------------------------------------------------------------
215
- // Codec — composite interface for transport use
468
+ // Codec message a per-message domain object paired with its identity
216
469
  // ---------------------------------------------------------------------------
217
470
 
218
- /** Options passed to a codec's `createEncoder` factory to configure default identity and message hooks. */
219
- export interface EncoderOptions {
220
- /** Default clientId for all writes. */
221
- clientId?: string;
222
- /** Default extras (e.g. headers) merged into every Ably message. */
223
- extras?: Extras;
224
- /** Hook called before each Ably message is published. Mutate the message in place to add transport-level headers. */
225
- onMessage?: (message: Ably.Message) => void;
471
+ /**
472
+ * A single domain message paired with the codec-message-id that identifies
473
+ * it on the wire. Returned from {@link Codec.getMessages}.
474
+ *
475
+ * The two fields are deliberately separate: `message` is reconstructed to
476
+ * faithfully reproduce the values the source produced (e.g. the id the AI
477
+ * SDK stream assigned) and is surfaced to the application as-is; the SDK
478
+ * never inspects `message` for identity. All internal correlation —
479
+ * Tree indexing, parent/fork/regenerate routing, branch grouping — keys on
480
+ * `codecMessageId`, the SDK's own client-minted identifier. The two need
481
+ * not be equal.
482
+ * @template TMessage - The codec's per-message domain type.
483
+ */
484
+ export interface CodecMessage<TMessage> {
485
+ /** The SDK's codec-message-id for this message — the correlation key. */
486
+ codecMessageId: string;
487
+ /** The domain message, reconstructed verbatim from the source values. */
488
+ message: TMessage;
226
489
  }
227
490
 
491
+ // ---------------------------------------------------------------------------
492
+ // Codec — full contract for the transport
493
+ // ---------------------------------------------------------------------------
494
+
228
495
  /**
229
- * The complete codec contract that a core transport needs.
496
+ * The codec describes the wire and folds events into a per-node projection.
230
497
  *
231
- * Combines factory methods (createEncoder, createDecoder, createAccumulator)
232
- * with protocol knowledge (isTerminal). Transport-level concerns like turn
233
- * correlation, optimistic reconciliation, and cancel signals
234
- * are handled by the transport layer using standard `x-ably-*` headers.
235
- */
236
- export interface Codec<TEvent, TMessage> {
237
- /** Create a streaming encoder bound to the given channel. */
238
- createEncoder(channel: ChannelWriter, options?: EncoderOptions): StreamEncoder<TEvent, TMessage>;
239
- /** Create a decoder for converting Ably messages back into domain outputs. */
240
- createDecoder(): StreamDecoder<TEvent, TMessage>;
241
- /** Create an accumulator for building domain messages from decoder outputs. */
242
- createAccumulator(): MessageAccumulator<TEvent, TMessage>;
243
-
244
- /** Whether an event signals stream completion (finish, error, abort). */
245
- isTerminal(event: TEvent): boolean;
246
-
247
- /** Return a stable key for a message (used by MessageStore for upsert/delete). */
248
- getMessageKey(message: TMessage): string;
498
+ * Type parameters:
499
+ * - `TInput` the union of input variants the client publishes on the
500
+ * `ai-input` wire. Every variant extends {@link CodecInputEvent}.
501
+ * - `TOutput` the union of output variants the agent publishes on the
502
+ * `ai-output` wire. Every variant extends {@link CodecOutputEvent}.
503
+ * - `TProjection` — the opaque per-node state the reducer folds events into
504
+ * (one projection per node, whether a RunNode or a run-less input node).
505
+ * The SDK never inspects it directly; use {@link Codec.getMessages} to
506
+ * extract messages for the conversation Tree.
507
+ * - `TMessage` — the per-message shape consumed by the Tree. Returned from
508
+ * {@link Codec.getMessages}.
509
+ */
510
+ export interface Codec<
511
+ TInput extends CodecInputEvent,
512
+ TOutput extends CodecOutputEvent,
513
+ TProjection,
514
+ TMessage,
515
+ > extends Reducer<TInput | TOutput, TProjection> {
516
+ /** Create a stateful encoder bound to the given channel. */
517
+ createEncoder(channel: ChannelWriter, options?: EncoderOptions): Encoder<TInput, TOutput>;
518
+ /** Create a stateful decoder for converting Ably inbound messages into typed inputs and outputs. */
519
+ createDecoder(): Decoder<TInput, TOutput>;
520
+ /**
521
+ * Extract the per-message list from a projection, each message paired
522
+ * with its codec-message-id (see {@link CodecMessage}). The SDK uses the
523
+ * `codecMessageId` to correlate messages — it never reads identity from
524
+ * the message itself — and surfaces `message` to the application
525
+ * unchanged.
526
+ */
527
+ getMessages(projection: TProjection): CodecMessage<TMessage>[];
528
+ /**
529
+ * Wrap a TMessage as the codec's well-known {@link UserMessage} variant,
530
+ * returned as a `TInput` ready to publish on the `ai-input` wire. This is
531
+ * the public way to turn a caller-provided TMessage into an input for
532
+ * `View.send`; the client session's seed-message path uses it too. The
533
+ * returned value is a `UserMessage<TMessage>` member of the codec's
534
+ * `TInput` union — typed as `TInput` so callers need no cast.
535
+ * @param message - The user's message in the codec's domain representation.
536
+ * @returns A `TInput` (the codec's {@link UserMessage} variant).
537
+ */
538
+ createUserMessage(message: TMessage): TInput;
539
+ /**
540
+ * Build a {@link Regenerate} for the codec, returned as a `TInput`. The
541
+ * View calls this from `regenerate(messageId)`; the input event is a
542
+ * signal (not itself a fork) that targets the assistant codec-message to
543
+ * be regenerated.
544
+ *
545
+ * The new Run is a CONTINUATION of the regenerated message's Run, not a
546
+ * fork at the Run level. The message-level replacement (the new
547
+ * assistant supersedes the original) happens at the View's
548
+ * projection-extraction step (Spec: AIT-CT13d).
549
+ * @param target - The codec-message-id of the assistant being regenerated.
550
+ * @param parent - The codec-message-id of the parent user message the new assistant threads under.
551
+ * @returns A `TInput` (the codec's {@link Regenerate} variant).
552
+ */
553
+ createRegenerate(target: string, parent: string): TInput;
554
+ /**
555
+ * Build a {@link ToolResult} for the codec, returned as a `TInput`.
556
+ * Amends the assistant at `codecMessageId` with the codec's domain
557
+ * `payload`. Optional — only codecs whose `TInput` includes the
558
+ * {@link ToolResult} variant implement it.
559
+ * @param codecMessageId - The assistant codec-message the result amends.
560
+ * @param payload - The codec's domain tool-result payload.
561
+ * @returns A `TInput` (the codec's {@link ToolResult} variant).
562
+ */
563
+ createToolResult?(codecMessageId: string, payload: ToolResultPayloadOf<TInput>): TInput;
564
+ /**
565
+ * Build a {@link ToolResultError} for the codec, returned as a `TInput`.
566
+ * Optional — only codecs whose `TInput` includes the variant implement it.
567
+ * @param codecMessageId - The assistant codec-message the error amends.
568
+ * @param payload - The codec's domain tool-result-failure payload.
569
+ * @returns A `TInput` (the codec's {@link ToolResultError} variant).
570
+ */
571
+ createToolResultError?(codecMessageId: string, payload: ToolResultErrorPayloadOf<TInput>): TInput;
572
+ /**
573
+ * Build a {@link ToolApprovalResponse} for the codec, returned as a
574
+ * `TInput`. Optional — only codecs whose `TInput` includes the variant
575
+ * implement it.
576
+ * @param codecMessageId - The assistant codec-message the response amends.
577
+ * @param payload - The codec's domain approval-decision payload.
578
+ * @returns A `TInput` (the codec's {@link ToolApprovalResponse} variant).
579
+ */
580
+ createToolApprovalResponse?(codecMessageId: string, payload: ToolApprovalResponsePayloadOf<TInput>): TInput;
249
581
  }