@ably/ai-transport 0.0.1

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 (118) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +426 -0
  3. package/dist/ably-ai-transport.js +1388 -0
  4. package/dist/ably-ai-transport.js.map +1 -0
  5. package/dist/ably-ai-transport.umd.cjs +2 -0
  6. package/dist/ably-ai-transport.umd.cjs.map +1 -0
  7. package/dist/constants.d.ts +50 -0
  8. package/dist/core/codec/decoder.d.ts +62 -0
  9. package/dist/core/codec/encoder.d.ts +56 -0
  10. package/dist/core/codec/index.d.ts +8 -0
  11. package/dist/core/codec/lifecycle-tracker.d.ts +74 -0
  12. package/dist/core/codec/types.d.ts +188 -0
  13. package/dist/core/transport/client-transport.d.ts +10 -0
  14. package/dist/core/transport/conversation-tree.d.ts +9 -0
  15. package/dist/core/transport/decode-history.d.ts +41 -0
  16. package/dist/core/transport/headers.d.ts +26 -0
  17. package/dist/core/transport/index.d.ts +4 -0
  18. package/dist/core/transport/pipe-stream.d.ts +16 -0
  19. package/dist/core/transport/server-transport.d.ts +7 -0
  20. package/dist/core/transport/stream-router.d.ts +19 -0
  21. package/dist/core/transport/turn-manager.d.ts +34 -0
  22. package/dist/core/transport/types.d.ts +407 -0
  23. package/dist/errors.d.ts +46 -0
  24. package/dist/event-emitter.d.ts +65 -0
  25. package/dist/index.d.ts +11 -0
  26. package/dist/logger.d.ts +103 -0
  27. package/dist/react/ably-ai-transport-react.js +823 -0
  28. package/dist/react/ably-ai-transport-react.js.map +1 -0
  29. package/dist/react/ably-ai-transport-react.umd.cjs +2 -0
  30. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -0
  31. package/dist/react/index.d.ts +11 -0
  32. package/dist/react/use-ably-messages.d.ts +18 -0
  33. package/dist/react/use-active-turns.d.ts +8 -0
  34. package/dist/react/use-client-transport.d.ts +7 -0
  35. package/dist/react/use-conversation-tree.d.ts +20 -0
  36. package/dist/react/use-edit.d.ts +7 -0
  37. package/dist/react/use-history.d.ts +19 -0
  38. package/dist/react/use-messages.d.ts +7 -0
  39. package/dist/react/use-regenerate.d.ts +7 -0
  40. package/dist/react/use-send.d.ts +7 -0
  41. package/dist/utils.d.ts +127 -0
  42. package/dist/vercel/ably-ai-transport-vercel.js +2331 -0
  43. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -0
  44. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +2 -0
  45. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -0
  46. package/dist/vercel/codec/accumulator.d.ts +21 -0
  47. package/dist/vercel/codec/decoder.d.ts +22 -0
  48. package/dist/vercel/codec/encoder.d.ts +41 -0
  49. package/dist/vercel/codec/index.d.ts +22 -0
  50. package/dist/vercel/index.d.ts +3 -0
  51. package/dist/vercel/react/ably-ai-transport-vercel-react.js +2082 -0
  52. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -0
  53. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +2 -0
  54. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -0
  55. package/dist/vercel/react/index.d.ts +3 -0
  56. package/dist/vercel/react/use-chat-transport.d.ts +29 -0
  57. package/dist/vercel/react/use-message-sync.d.ts +19 -0
  58. package/dist/vercel/transport/chat-transport.d.ts +118 -0
  59. package/dist/vercel/transport/index.d.ts +36 -0
  60. package/package.json +123 -0
  61. package/react/README.md +3 -0
  62. package/react/index.d.ts +1 -0
  63. package/react/index.js +1 -0
  64. package/react/index.umd.cjs +1 -0
  65. package/src/constants.ts +98 -0
  66. package/src/core/codec/decoder.ts +402 -0
  67. package/src/core/codec/encoder.ts +470 -0
  68. package/src/core/codec/index.ts +28 -0
  69. package/src/core/codec/lifecycle-tracker.ts +140 -0
  70. package/src/core/codec/types.ts +249 -0
  71. package/src/core/transport/client-transport.ts +959 -0
  72. package/src/core/transport/conversation-tree.ts +434 -0
  73. package/src/core/transport/decode-history.ts +337 -0
  74. package/src/core/transport/headers.ts +46 -0
  75. package/src/core/transport/index.ts +34 -0
  76. package/src/core/transport/pipe-stream.ts +95 -0
  77. package/src/core/transport/server-transport.ts +458 -0
  78. package/src/core/transport/stream-router.ts +118 -0
  79. package/src/core/transport/turn-manager.ts +147 -0
  80. package/src/core/transport/types.ts +533 -0
  81. package/src/errors.ts +58 -0
  82. package/src/event-emitter.ts +103 -0
  83. package/src/index.ts +89 -0
  84. package/src/logger.ts +241 -0
  85. package/src/react/index.ts +11 -0
  86. package/src/react/use-ably-messages.ts +37 -0
  87. package/src/react/use-active-turns.ts +61 -0
  88. package/src/react/use-client-transport.ts +37 -0
  89. package/src/react/use-conversation-tree.ts +71 -0
  90. package/src/react/use-edit.ts +24 -0
  91. package/src/react/use-history.ts +111 -0
  92. package/src/react/use-messages.ts +32 -0
  93. package/src/react/use-regenerate.ts +24 -0
  94. package/src/react/use-send.ts +25 -0
  95. package/src/react/vite.config.ts +32 -0
  96. package/src/tsconfig.json +25 -0
  97. package/src/utils.ts +230 -0
  98. package/src/vercel/codec/accumulator.ts +603 -0
  99. package/src/vercel/codec/decoder.ts +615 -0
  100. package/src/vercel/codec/encoder.ts +396 -0
  101. package/src/vercel/codec/index.ts +37 -0
  102. package/src/vercel/index.ts +12 -0
  103. package/src/vercel/react/index.ts +4 -0
  104. package/src/vercel/react/use-chat-transport.ts +60 -0
  105. package/src/vercel/react/use-message-sync.ts +34 -0
  106. package/src/vercel/react/vite.config.ts +33 -0
  107. package/src/vercel/transport/chat-transport.ts +278 -0
  108. package/src/vercel/transport/index.ts +56 -0
  109. package/src/vercel/vite.config.ts +33 -0
  110. package/src/vite.config.ts +31 -0
  111. package/vercel/README.md +3 -0
  112. package/vercel/index.d.ts +1 -0
  113. package/vercel/index.js +1 -0
  114. package/vercel/index.umd.cjs +1 -0
  115. package/vercel/react/README.md +3 -0
  116. package/vercel/react/index.d.ts +1 -0
  117. package/vercel/react/index.js +1 -0
  118. package/vercel/react/index.umd.cjs +1 -0
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,426 @@
1
+ # Ably AI Transport SDK
2
+
3
+ A durable transport layer between AI agents and users. Streams AI responses over [Ably](https://ably.com/) channels - responses resume after disconnections, conversations persist across page reloads and devices, with support for cancellation, branching conversations, and multi-user sync.
4
+
5
+ > **Status:** Pre-release (`0.x`). The API is evolving. Feedback and contributions are welcome.
6
+
7
+ ## The problem
8
+
9
+ Most AI frameworks stream tokens over HTTP response bodies or SSE. That works until it doesn't: connections drop through corporate proxies, responses vanish on page refresh, and sessions are stuck on a single device or tab. Once an agent starts a long-running task, the user has no way to interrupt it, check if it's still running, or continue the conversation from another device. If a human needs to take over from the agent, the session context is lost.
10
+
11
+ Ably AI Transport replaces the HTTP stream with an Ably channel. The server publishes tokens to the channel as they arrive from the LLM; the response accumulates on the channel and persists, so partial responses survive disconnection. Any client can subscribe to the same channel from any device. Cancel signals, turn lifecycle events, and conversation history all flow through the channel rather than depending on a single HTTP connection.
12
+
13
+ ```mermaid
14
+ sequenceDiagram
15
+ participant U as User
16
+ participant CT as Client Transport
17
+ participant AC as Ably Channel
18
+ participant ST as Server Transport
19
+ participant LLM
20
+
21
+ U->>CT: type message
22
+ CT->>ST: HTTP POST (messages)
23
+ ST->>LLM: prompt
24
+ LLM-->>ST: token stream
25
+ ST->>AC: publish chunks
26
+ AC->>CT: subscribe (decode)
27
+ CT->>U: render tokens
28
+ ```
29
+
30
+ Ably AI Transport SDK is not an agent framework or orchestration layer - it works alongside whatever agent framework/model provider you choose, through a pluggable codec architecture (Vercel AI SDK supported now, more frameworks and models coming soon). It can be used in a serverless architecture (e.g. Next.js), with a durable execution framework (e.g. Temporal, Vercel Workflow DevKit) or in a traditional client-server architecture.
31
+
32
+ ## What this gives you
33
+
34
+ - **Resumable streaming** - If a connection drops mid-response, client reconnects and picks up where it left off. The response persists on the channel, so nothing is lost.
35
+ - **Session continuity across surfaces** - The session belongs to the channel, not the connection. A user can change tab or device and pick up at the same point.
36
+ - **Multi-client sync** - Multiple users, agents, or operators subscribe to the same channel. Human-AI handover is a channel operation, not a session migration.
37
+ - **Cancellation** - Cancel signals travel over the Ably channel, not the HTTP connection, and the server turn's `abortSignal` fires automatically.
38
+ - **Interruption** - Users send new messages while the AI is still responding, with composable primitives for cancel-and-resend or queue-until-complete.
39
+ - **Concurrent turns** - Multiple request-response cycles run in parallel on the same channel. Each turn has its own stream and abort signal.
40
+ - **History** - The Ably channel is the conversation record. Clients hydrate from channel history on load - no separate database query needed.
41
+ - **Branching** - Regenerate or edit messages to fork the conversation. The SDK tracks parent/child relationships and exposes a navigable tree.
42
+ - **Framework-agnostic** - A codec interface decouples transport from the AI framework. Ships with a Vercel AI SDK codec; bring your own for any other stack.
43
+
44
+ ### When you need this
45
+
46
+ - AI products where connection reliability and session durability are non-negotiable
47
+ - Multi-surface experiences where a user needs to see the session in multiple tabs or devices
48
+ - Collaborative AI where multiple users or agents interact in the same conversation
49
+ - Customer support products where AI conversations are handed to human agents
50
+
51
+ ---
52
+
53
+ ## Getting started
54
+
55
+ ### Installation
56
+
57
+ ```sh
58
+ npm install @ably/ai-transport ably
59
+ ```
60
+
61
+ For Vercel AI SDK projects, also install the `ai` package:
62
+
63
+ ```sh
64
+ npm install @ably/ai-transport ably ai
65
+ ```
66
+
67
+ ### Supported platforms
68
+
69
+ | Platform | Support |
70
+ | ------------- | -------------------------------------------------- |
71
+ | Node.js | 20+ |
72
+ | Browsers | All major browsers (Chrome, Firefox, Edge, Safari) |
73
+ | TypeScript | Written in TypeScript, ships with types |
74
+ | React | 18+ and 19+ via dedicated hooks |
75
+ | Vercel AI SDK | v6 via dedicated codec and transport adapters |
76
+
77
+ ---
78
+
79
+ ## Usage with Vercel AI SDK
80
+
81
+ AI Transport is complementary to the Vercel AI SDK, not a replacement. The Vercel AI SDK handles model calls, message formatting, and React hooks. AI Transport replaces the transport layer underneath, so tokens stream over Ably instead of an HTTP response body. You keep `useChat`, `streamText`, and everything else you're used to.
82
+
83
+ ### Server - Next.js API route
84
+
85
+ ```typescript
86
+ import { after } from 'next/server';
87
+ import { streamText, convertToModelMessages } from 'ai';
88
+ import type { UIMessage } from 'ai';
89
+ import { anthropic } from '@ai-sdk/anthropic';
90
+ import Ably from 'ably';
91
+ import { createServerTransport } from '@ably/ai-transport/vercel';
92
+ import type { MessageWithHeaders } from '@ably/ai-transport';
93
+
94
+ interface ChatRequestBody {
95
+ turnId: string;
96
+ clientId: string;
97
+ messages: MessageWithHeaders<UIMessage>[];
98
+ history?: MessageWithHeaders<UIMessage>[];
99
+ id: string;
100
+ forkOf?: string;
101
+ parent?: string | null;
102
+ }
103
+
104
+ const ably = new Ably.Realtime({ key: process.env.ABLY_API_KEY });
105
+
106
+ export async function POST(req: Request) {
107
+ const { messages, history, id, turnId, clientId, forkOf, parent } = (await req.json()) as ChatRequestBody;
108
+
109
+ const channel = ably.channels.get(id);
110
+ const transport = createServerTransport({ channel });
111
+ const turn = transport.newTurn({ turnId, clientId, parent, forkOf });
112
+
113
+ await turn.start();
114
+
115
+ if (messages.length > 0) {
116
+ await turn.addMessages(messages, { clientId });
117
+ }
118
+
119
+ const historyMsgs = (history ?? []).map((h) => h.message);
120
+ const newMsgs = messages.map((m) => m.message);
121
+
122
+ const result = streamText({
123
+ model: anthropic('claude-sonnet-4-20250514'),
124
+ system: 'You are a helpful assistant.',
125
+ messages: await convertToModelMessages([...historyMsgs, ...newMsgs]),
126
+ abortSignal: turn.abortSignal,
127
+ });
128
+
129
+ // Stream the response over Ably in the background
130
+ after(async () => {
131
+ const { reason } = await turn.streamResponse(result.toUIMessageStream());
132
+ await turn.end(reason);
133
+ transport.close();
134
+ });
135
+
136
+ return new Response(null, { status: 200 });
137
+ }
138
+ ```
139
+
140
+ ### Client - React with `useChat`
141
+
142
+ ```tsx
143
+ 'use client';
144
+
145
+ import { useChat } from '@ai-sdk/react';
146
+ import { useChannel } from 'ably/react';
147
+ import { useClientTransport, useActiveTurns, useHistory } from '@ably/ai-transport/react';
148
+ import { useChatTransport, useMessageSync } from '@ably/ai-transport/vercel/react';
149
+ import { UIMessageCodec } from '@ably/ai-transport/vercel';
150
+
151
+ function Chat({ chatId, clientId }: { chatId: string; clientId?: string }) {
152
+ const { channel } = useChannel({ channelName: chatId });
153
+
154
+ const transport = useClientTransport({ channel, codec: UIMessageCodec, clientId });
155
+ const chatTransport = useChatTransport(transport);
156
+
157
+ const { messages, setMessages, sendMessage, stop } = useChat({
158
+ id: chatId,
159
+ transport: chatTransport,
160
+ });
161
+
162
+ useMessageSync(transport, setMessages);
163
+
164
+ const activeTurns = useActiveTurns(transport);
165
+ const history = useHistory(transport, { limit: 30 });
166
+
167
+ return (
168
+ <div>
169
+ {messages.map((msg) => (
170
+ <div key={msg.id}>{msg.parts.map((part, i) => (part.type === 'text' ? <p key={i}>{part.text}</p> : null))}</div>
171
+ ))}
172
+ <form
173
+ onSubmit={(e) => {
174
+ e.preventDefault();
175
+ sendMessage({ text: 'Hello' });
176
+ }}
177
+ >
178
+ {activeTurns.size > 0 ? (
179
+ <button
180
+ type="button"
181
+ onClick={stop}
182
+ >
183
+ Stop
184
+ </button>
185
+ ) : (
186
+ <button type="submit">Send</button>
187
+ )}
188
+ </form>
189
+ </div>
190
+ );
191
+ }
192
+ ```
193
+
194
+ ### Authentication
195
+
196
+ The Ably client authenticates via token auth. Create an endpoint that issues token requests:
197
+
198
+ ```typescript
199
+ // app/api/auth/ably-token/route.ts
200
+ import Ably from 'ably';
201
+
202
+ const ably = new Ably.Rest({ key: process.env.ABLY_API_KEY });
203
+
204
+ export async function GET(req: Request) {
205
+ const { searchParams } = new URL(req.url);
206
+ const clientId = searchParams.get('clientId') ?? 'anonymous';
207
+ const token = await ably.auth.createTokenRequest({ clientId });
208
+ return Response.json(token);
209
+ }
210
+ ```
211
+
212
+ ```typescript
213
+ // Client-side Ably setup
214
+ const ably = new Ably.Realtime({
215
+ authCallback: async (_params, callback) => {
216
+ const response = await fetch('/api/auth/ably-token');
217
+ const token = await response.json();
218
+ callback(null, token);
219
+ },
220
+ });
221
+ ```
222
+
223
+ ---
224
+
225
+ ## Core usage with a custom codec
226
+
227
+ The core entry point is framework-agnostic. Bring your own `Codec` to map between your AI framework's event/message types and the Ably wire format.
228
+
229
+ ### Client
230
+
231
+ ```typescript
232
+ import { createClientTransport } from '@ably/ai-transport';
233
+ import { myCodec } from './my-codec';
234
+
235
+ const transport = createClientTransport({
236
+ channel, // Ably RealtimeChannel
237
+ codec: myCodec,
238
+ clientId: 'user-123',
239
+ api: '/api/chat',
240
+ });
241
+
242
+ const turn = await transport.send(messages);
243
+
244
+ // Read the stream
245
+ const reader = turn.stream.getReader();
246
+ while (true) {
247
+ const { done, value } = await reader.read();
248
+ if (done) break;
249
+ console.log(value); // Your codec's event type
250
+ }
251
+ ```
252
+
253
+ ### Server
254
+
255
+ ```typescript
256
+ import { createServerTransport } from '@ably/ai-transport';
257
+ import { myCodec } from './my-codec';
258
+
259
+ const transport = createServerTransport({ channel, codec: myCodec });
260
+ const turn = transport.newTurn({ turnId, clientId, parent, forkOf });
261
+
262
+ await turn.start();
263
+ await turn.addMessages(messages, { clientId });
264
+
265
+ const { reason } = await turn.streamResponse(aiStream);
266
+ await turn.end(reason);
267
+ transport.close();
268
+ ```
269
+
270
+ ---
271
+
272
+ ## Package exports
273
+
274
+ | Export path | Purpose | Peer dependencies |
275
+ | ----------------------------------------- | ------------------------------------------- | --------------------- |
276
+ | `@ably/ai-transport` | Core transport, codec interfaces, utilities | `ably` |
277
+ | `@ably/ai-transport/react` | React hooks for any codec | `ably`, `react` |
278
+ | `@ably/ai-transport/vercel` | Vercel AI SDK codec, transport factories | `ably`, `ai` |
279
+ | `@ably/ai-transport/vercel/react` | React hooks for Vercel's `useChat` | `ably`, `ai`, `react` |
280
+
281
+ ### React hooks
282
+
283
+ | Hook | Entry point | Description |
284
+ | --------------------- | --------------- | --------------------------------------------------- |
285
+ | `useClientTransport` | `/react` | Create and memoize a client transport instance |
286
+ | `useMessages` | `/react` | Subscribe to decoded messages |
287
+ | `useSend` | `/react` | Stable send callback |
288
+ | `useRegenerate` | `/react` | Regenerate a message (fork the conversation) |
289
+ | `useEdit` | `/react` | Edit a message and regenerate from that point |
290
+ | `useActiveTurns` | `/react` | Track active turns by client ID |
291
+ | `useHistory` | `/react` | Paginate through conversation history |
292
+ | `useConversationTree` | `/react` | Navigate branches in a forked conversation |
293
+ | `useAblyMessages` | `/react` | Access raw Ably messages |
294
+ | `useChatTransport` | `/vercel/react` | Wrap transport for Vercel's `useChat` |
295
+ | `useMessageSync` | `/vercel/react` | Sync transport state with `useChat`'s `setMessages` |
296
+
297
+ ---
298
+
299
+ ## Key features
300
+
301
+ ### Connection recovery
302
+
303
+ Two mechanisms cover different failure modes:
304
+
305
+ - **Network blips** - Ably's connection protocol automatically reconnects and delivers any messages published while the client was disconnected. No application code required.
306
+ - **Resumable streams** - A client that joins or rejoins a channel mid-response (after a page refresh, on a new device, or as a second participant) receives the in-progress stream immediately on subscribing. Load previous conversation history from the channel via `history()`, or from your own database.
307
+
308
+ ### Cancellation
309
+
310
+ ```typescript
311
+ // Client: cancel your own active turns
312
+ await transport.cancel();
313
+
314
+ // Cancel a specific turn
315
+ await transport.cancel({ turnId: 'turn-abc' });
316
+
317
+ // Server: the turn's abortSignal fires automatically
318
+ const result = streamText({
319
+ model: anthropic('claude-sonnet-4-20250514'),
320
+ messages,
321
+ abortSignal: turn.abortSignal, // Aborted when client cancels
322
+ });
323
+ ```
324
+
325
+ ### Branching conversations
326
+
327
+ Regenerate or edit messages to create forks in the conversation tree. The SDK tracks parent/child relationships and exposes a navigable tree.
328
+
329
+ ```typescript
330
+ // Regenerate the last assistant message
331
+ const turn = await transport.regenerate(assistantMessageId);
332
+
333
+ // Edit a user message and regenerate from that point
334
+ const turn = await transport.edit(userMessageId, [newMessage]);
335
+
336
+ // Navigate branches
337
+ const tree = transport.getTree();
338
+ const siblings = tree.getSiblings(messageId);
339
+ tree.select(messageId, 1); // Switch to second branch
340
+ ```
341
+
342
+ ### History and hydration
343
+
344
+ Load previous conversation state when a client joins or returns to a session.
345
+
346
+ ```typescript
347
+ const page = await transport.history({ limit: 50 });
348
+ console.log(page.items); // Decoded messages
349
+
350
+ if (page.hasNext()) {
351
+ const older = await page.next();
352
+ }
353
+ ```
354
+
355
+ ### Events
356
+
357
+ ```typescript
358
+ transport.on('message', () => {
359
+ console.log(transport.getMessages());
360
+ });
361
+
362
+ transport.on('turn', (event) => {
363
+ console.log(event.turnId, event.type); // 'x-ably-turn-start' | 'x-ably-turn-end'
364
+ });
365
+
366
+ transport.on('error', (error) => {
367
+ console.error(error.code, error.message);
368
+ });
369
+ ```
370
+
371
+ ---
372
+
373
+ ## Documentation
374
+
375
+ Detailed documentation lives in the [`docs/`](./docs/) directory:
376
+
377
+ - **[Concepts](./docs/concepts/)** - [Transport architecture](./docs/concepts/transport.md), [Turns](./docs/concepts/turns.md)
378
+ - **[Get started](./docs/get-started/)** - [Vercel AI SDK with useChat](./docs/get-started/vercel-use-chat.md), [Vercel AI SDK with useClientTransport](./docs/get-started/vercel-use-client-transport.md)
379
+ - **[Frameworks](./docs/frameworks/)** - [Vercel AI SDK](./docs/frameworks/vercel-ai-sdk.md)
380
+ - **[Features](./docs/features/)** - [Streaming](./docs/features/streaming.md), [Cancellation](./docs/features/cancel.md), [Barge-in](./docs/features/barge-in.md), [Optimistic updates](./docs/features/optimistic-updates.md), [History](./docs/features/history.md), [Branching](./docs/features/branching.md), [Multi-client sync](./docs/features/multi-client.md), [Tool calls](./docs/features/tool-calls.md), [Concurrent turns](./docs/features/concurrent-turns.md)
381
+ - **[Reference](./docs/reference/)** - [React hooks](./docs/reference/react-hooks.md), [Error codes](./docs/reference/error-codes.md)
382
+ - **[Internals](./docs/internals/)** - Architecture details for contributors
383
+
384
+ ---
385
+
386
+ ## Demo apps
387
+
388
+ Working demo applications live in the [`demo/`](./demo/) directory:
389
+
390
+ - **[`demo/vercel/react/use-chat/`](./demo/vercel/react/use-chat/)** - Vercel AI SDK with `useChat` integration
391
+ - **[`demo/vercel/react/use-client-transport/`](./demo/vercel/react/use-client-transport/)** - Vercel AI SDK with direct `useClientTransport` hooks
392
+
393
+ ---
394
+
395
+ ## Development
396
+
397
+ ```bash
398
+ npm install
399
+ npm run build # Build all entry points (ESM + UMD/CJS + .d.ts)
400
+ npm run typecheck # Type check
401
+ npm run lint # Lint
402
+ npm test # Unit tests (mocks only)
403
+ npm run test:integration # Integration tests (needs ABLY_API_KEY)
404
+ npm run precommit # format:check + lint + typecheck
405
+ ```
406
+
407
+ ### Project structure
408
+
409
+ ```
410
+ src/
411
+ ├── core/ # Generic transport and codec (no framework deps)
412
+ │ ├── codec/ # Codec interfaces and core encoder/decoder
413
+ │ └── transport/ # ClientTransport, ServerTransport, ConversationTree
414
+ ├── react/ # React hooks for any codec
415
+ ├── vercel/ # Vercel AI SDK codec and transport adapters
416
+ │ ├── codec/ # UIMessageCodec
417
+ │ ├── transport/ # Vercel-specific factories, ChatTransport
418
+ │ └── react/ # useChatTransport, useMessageSync
419
+ └── index.ts # Core entry point
420
+ ```
421
+
422
+ ---
423
+
424
+ ## Contributing
425
+
426
+ See [CONTRIBUTING.md](./CONTRIBUTING.md). [Open an issue](https://github.com/ably/ably-ai-transport-js/issues) to share feedback or request a feature.