react-websocket 4.0.0 → 4.18.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.
- package/README.md +101 -25
- package/dist/ag-ui.cjs +421 -0
- package/dist/ag-ui.cjs.map +1 -0
- package/dist/ag-ui.d.cts +493 -0
- package/dist/ag-ui.d.ts +171 -0
- package/dist/ag-ui.js +418 -0
- package/dist/ag-ui.js.map +1 -0
- package/dist/core.cjs +689 -153
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +459 -53
- package/dist/core.d.ts +459 -53
- package/dist/core.js +686 -154
- package/dist/core.js.map +1 -1
- package/dist/devtools.cjs +186 -0
- package/dist/devtools.cjs.map +1 -0
- package/dist/devtools.d.cts +32 -0
- package/dist/devtools.d.ts +32 -0
- package/dist/devtools.js +185 -0
- package/dist/devtools.js.map +1 -0
- package/dist/index.cjs +182 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +663 -48
- package/dist/index.d.ts +393 -22
- package/dist/index.js +178 -24
- package/dist/index.js.map +1 -1
- package/dist/outbox.cjs +222 -0
- package/dist/outbox.cjs.map +1 -0
- package/dist/outbox.d.cts +127 -0
- package/dist/outbox.d.ts +127 -0
- package/dist/outbox.js +219 -0
- package/dist/outbox.js.map +1 -0
- package/dist/replay.cjs +324 -0
- package/dist/replay.cjs.map +1 -0
- package/dist/replay.d.cts +124 -0
- package/dist/replay.d.ts +124 -0
- package/dist/replay.js +322 -0
- package/dist/replay.js.map +1 -0
- package/dist/tabs.cjs +336 -0
- package/dist/tabs.cjs.map +1 -0
- package/dist/tabs.d.cts +81 -0
- package/dist/tabs.d.ts +81 -0
- package/dist/tabs.js +335 -0
- package/dist/tabs.js.map +1 -0
- package/dist/timeline.d.cts +1 -216
- package/dist/types-BEecFqIB.d.cts +268 -0
- package/dist/webtransport.cjs +243 -0
- package/dist/webtransport.cjs.map +1 -0
- package/dist/webtransport.d.cts +67 -0
- package/dist/webtransport.d.ts +67 -0
- package/dist/webtransport.js +242 -0
- package/dist/webtransport.js.map +1 -0
- package/package.json +142 -4
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# react-websocket
|
|
2
2
|
|
|
3
|
-
**
|
|
3
|
+
**The real-time toolkit for React 18 and 19.** Start with one hook, `useWebSocket`: shared connections, automatic reconnects, a send queue, typed and validated messages, and Suspense, in about 4 kB (min+gzip) with zero dependencies. Add topics, state, requests, presence, games and AI agents on the same connection when you need them. Each is a separate import, so you only ship what you use.
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/react-websocket)
|
|
6
6
|
[](https://github.com/mehmetkose/react-websocket/actions/workflows/ci.yml)
|
|
@@ -11,19 +11,6 @@
|
|
|
11
11
|
|
|
12
12
|
**[Documentation](https://mehmetkose.github.io/react-websocket/)** · [Getting started](https://mehmetkose.github.io/react-websocket/guide/getting-started) · [API](https://mehmetkose.github.io/react-websocket/api/) · [Recipes](https://mehmetkose.github.io/react-websocket/recipes) · [Changelog](CHANGELOG.md)
|
|
13
13
|
|
|
14
|
-
- **Shared connections.** Components using the same URL share one socket. StrictMode, `<Activity>` and route transitions never open duplicates.
|
|
15
|
-
- **Auto-reconnect.** Exponential backoff with full jitter, plus an immediate retry when the browser comes back online or the tab becomes visible. It backs off from a server that closes right after accepting, and stops on close codes that retrying can't fix. Optional heartbeats detect dead links.
|
|
16
|
-
- **Send queue.** `send()` before the socket is open just works. The message goes out on connect. Mark input `volatile` so it's never replayed late, or `key` it so only the newest is sent. Put control messages first with `priority`, and drop stream data on a slow link with `maxBuffered`.
|
|
17
|
-
- **Typed messages.** `json: true`, your own codec, or validation with any [Standard Schema](https://standardschema.dev) library (zod, valibot, arktype), with inferred types.
|
|
18
|
-
- **Suspense.** `use(client.ready)` waits for the first connection, and reconnects never flash a fallback.
|
|
19
|
-
- **Topic subscriptions.** Reference-counted `subscribe`/`unsubscribe` messages that are sent again after every reconnect, so feeds don't silently stop.
|
|
20
|
-
- **Message state.** Reduce messages into a store, and let each component re-render only when its slice changes, at most once per frame if you like.
|
|
21
|
-
- **Requests, streams and latency.** Await a reply, or iterate over streamed ones such as an LLM's tokens, with timeouts and a cancel that tells the server to stop. Measure round-trip time and the server's clock for ping displays and synchronized countdowns.
|
|
22
|
-
- **Games.** Snapshot interpolation and client-side prediction with server reconciliation, from `react-websocket/timeline`, so other players move smoothly and your own controls respond at once. A send rate that adapts to the connection keeps players on a poor link from building up lag.
|
|
23
|
-
- **Server requests.** Answer requests from the server, such as an AI agent's, in code for browser-only tools, or from a dialog for human approval. Every request gets exactly one reply, and none is sent to the wrong connection.
|
|
24
|
-
- **SSR-safe.** Never connects during a server render, hydrates cleanly, and ships a `'use client'` entry for Next.js and other Server Components frameworks.
|
|
25
|
-
- **Small and typed.** Zero dependencies, ESM + CJS, TypeScript declarations with inline docs, plus a React-free `react-websocket/core` entry.
|
|
26
|
-
|
|
27
14
|
## Install
|
|
28
15
|
|
|
29
16
|
```sh
|
|
@@ -32,6 +19,26 @@ npm install react-websocket
|
|
|
32
19
|
|
|
33
20
|
## Quick start
|
|
34
21
|
|
|
22
|
+
```tsx
|
|
23
|
+
import { useWebSocket } from 'react-websocket';
|
|
24
|
+
|
|
25
|
+
function Echo() {
|
|
26
|
+
const { status, lastMessage, send } = useWebSocket('wss://echo.websocket.org');
|
|
27
|
+
|
|
28
|
+
return (
|
|
29
|
+
<div>
|
|
30
|
+
<p>Status: {status}</p>
|
|
31
|
+
<p>Last message: {String(lastMessage ?? '—')}</p>
|
|
32
|
+
<button onClick={() => send('hello')}>Send</button>
|
|
33
|
+
</div>
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
No provider, no setup and no `useEffect`. That component already shares one socket with every component that uses the same URL, reconnects with backoff when the connection drops, queues messages sent before the socket opens, and never connects during a server render.
|
|
39
|
+
|
|
40
|
+
Most servers send JSON. Turn on `json` and name what you receive and what you send:
|
|
41
|
+
|
|
35
42
|
```tsx
|
|
36
43
|
import { useState } from 'react';
|
|
37
44
|
import { useWebSocket } from 'react-websocket';
|
|
@@ -64,6 +71,52 @@ function Chat() {
|
|
|
64
71
|
|
|
65
72
|
Handlers always see your latest props and state, and changing them never reconnects. `send`, `close` and `reconnect` keep the same identity between renders.
|
|
66
73
|
|
|
74
|
+
## The toolkit
|
|
75
|
+
|
|
76
|
+
Everything builds on the client that `useWebSocket` uses. Each piece is a separate import, and none of them imposes a wire protocol: you describe your server's messages, and they do the bookkeeping.
|
|
77
|
+
|
|
78
|
+
### Connect
|
|
79
|
+
|
|
80
|
+
- **Shared connections.** Components using the same URL share one socket. StrictMode, `<Activity>` and route transitions never open duplicates.
|
|
81
|
+
- **Auto-reconnect.** Exponential backoff with full jitter, plus an immediate retry when the browser comes back online or the tab becomes visible. It backs off from a server that closes right after accepting, and stops on close codes that retrying can't fix. Optional heartbeats detect dead links.
|
|
82
|
+
- **Send queue.** `send()` before the socket is open just works. The message goes out on connect. Mark input `volatile` so it's never replayed late, or `key` it so only the newest is sent. Put control messages first with `priority`, and drop stream data on a slow link with `maxBuffered`.
|
|
83
|
+
- **Typed messages.** `json: true`, your own codec, or validation with any [Standard Schema](https://standardschema.dev) library (zod, valibot, arktype), with inferred types.
|
|
84
|
+
- **Suspense.** `use(client.ready)` waits for the first connection, and reconnects never flash a fallback.
|
|
85
|
+
- **SSR-safe.** Never connects during a server render, hydrates cleanly, and ships a `'use client'` entry for Next.js and other Server Components frameworks.
|
|
86
|
+
- **Small and typed.** Zero dependencies, ESM + CJS, TypeScript declarations with inline docs, plus a React-free `react-websocket/core` entry.
|
|
87
|
+
|
|
88
|
+
### Live data
|
|
89
|
+
|
|
90
|
+
- **Topic subscriptions.** Reference-counted `subscribe`/`unsubscribe` messages that are sent again after every reconnect, so feeds don't silently stop. With numbered messages, each arrives once and in order: duplicates are dropped, gaps are filled, and a reconnect resumes where it left off.
|
|
91
|
+
- **Message state.** Reduce messages into a store, and let each component re-render only when its slice changes, at most once per frame if you like.
|
|
92
|
+
|
|
93
|
+
### Requests and streams
|
|
94
|
+
|
|
95
|
+
- **Requests, streams and latency.** Await a reply, or iterate over streamed ones such as an LLM's tokens, with timeouts and a cancel that tells the server to stop. Measure round-trip time and the server's clock for ping displays and synchronized countdowns.
|
|
96
|
+
|
|
97
|
+
### AI agents
|
|
98
|
+
|
|
99
|
+
- **Server requests.** Answer requests from the server, such as an AI agent's, in code for browser-only tools, or from a dialog for human approval. Every request gets exactly one reply, and none is sent to the wrong connection.
|
|
100
|
+
- **Resumable runs.** An AI agent's streamed answer that survives a refresh, a network switch or a sleeping laptop: it resumes from the last event received, or is cancelled so the server stops spending.
|
|
101
|
+
- **AG-UI.** Run [AG-UI](https://docs.ag-ui.com) agents over a WebSocket with `react-websocket/ag-ui`: messages, tool calls and JSON Patch shared state, with a snapshot when a patch fails, and runs that resume after a reconnect or a reload.
|
|
102
|
+
- **Voice.** Microphone frames that never replay stale or build up lag, control messages that jump the queue, and a [guide](https://mehmetkose.github.io/react-websocket/guide/voice) to interruptions that truncate the transcript to what the user heard.
|
|
103
|
+
|
|
104
|
+
### Multiplayer and presence
|
|
105
|
+
|
|
106
|
+
- **Presence and live cursors.** Share per-peer state such as cursors: throttled, refreshed while idle, never replayed stale, and expired when a peer vanishes without saying goodbye.
|
|
107
|
+
- **Games.** Snapshot interpolation and client-side prediction with server reconciliation, from `react-websocket/timeline`, so other players move smoothly and your own controls respond at once. A send rate that adapts to the connection keeps players on a poor link from building up lag.
|
|
108
|
+
|
|
109
|
+
### Transports and offline
|
|
110
|
+
|
|
111
|
+
- **One connection across tabs.** `react-websocket/tabs` lets every tab of an app share one connection, with a leader tab elected over the Web Locks API, and topics that one tab can't unsubscribe from under another.
|
|
112
|
+
- **WebTransport.** `react-websocket/webtransport` connects over WebTransport behind the same API, with `volatile` sends as datagrams and a WebSocket fallback where it can't connect.
|
|
113
|
+
- **Offline outbox.** Messages kept in IndexedDB until the server acknowledges them, from `react-websocket/outbox`, so an order taken on flaky Wi-Fi survives reconnects and page reloads, and retries are safe with idempotency keys.
|
|
114
|
+
|
|
115
|
+
### Debug and test
|
|
116
|
+
|
|
117
|
+
- **Devtools.** A development panel, `react-websocket/devtools`, with each client's status, queue, send buffer, messages, round-trip time and topics.
|
|
118
|
+
- **Recording and replay.** Record a session to a file and replay it without a server, for bug reports, offline demos, and UI tests that don't call an AI model on every run. Add faults on top with `react-websocket/chaos`.
|
|
119
|
+
|
|
67
120
|
## Shared clients
|
|
68
121
|
|
|
69
122
|
Define a connection once and use it anywhere, including outside React:
|
|
@@ -110,25 +163,47 @@ function Room() {
|
|
|
110
163
|
|
|
111
164
|
| Export | |
|
|
112
165
|
| --- | --- |
|
|
166
|
+
| **Connect** | |
|
|
113
167
|
| `useWebSocket(url \| client, options?)` | Connect; returns `{ status, lastMessage, attempt, send, close, reconnect, client }` |
|
|
114
168
|
| `useWebSocketEvent(client, type, listener)` | Handle `'open'`, `'message'`, `'close'` or `'error'` without re-rendering |
|
|
115
169
|
| `useWebSocketStatus(client)` | The status; re-renders only when it changes |
|
|
116
|
-
| `useWebSocketTopic(topics, topic)` | Hold topic subscriptions that survive reconnects |
|
|
117
|
-
| `useWebSocketState(store, selector?)` | Read state reduced from messages; re-renders only when the selection changes |
|
|
118
|
-
| `useWebSocketLatency(latency)` | Round-trip time and server clock offset |
|
|
119
|
-
| `useAgentApproval(responder, method)` | Requests from the server waiting for a person to answer |
|
|
120
|
-
| `useWebSocketStream(rpc, options?)` | Stream the replies to a request into a value, e.g. tokens into an answer; returns `{ value, status, error, start, abort }` |
|
|
121
170
|
| `createWebSocket(url, options?)` | A shareable client: `send`, `on`, `connect`, `close`, `reconnect`, `ready`, `getSnapshot`, `subscribe` |
|
|
171
|
+
| `MessageError` | Reported to `onError` when a message fails `parse` or `schema` |
|
|
172
|
+
| `retryableClose(close)` | The default `reconnect.shouldReconnect`: retries every close except `1002`, `1003` and `1008` |
|
|
173
|
+
| `retryAfter(close)` | The default `reconnect.retryAfter`: the delay a `1012` (Service Restart) or `1013` (Try Again Later) close asks for, in seconds in its reason |
|
|
174
|
+
| **Live data** | |
|
|
122
175
|
| `createWebSocketTopics(client, { subscribe, unsubscribe })` | Topic subscription manager for `useWebSocketTopic` |
|
|
176
|
+
| `useWebSocketTopic(topics, topic)` | Hold topic subscriptions that survive reconnects |
|
|
177
|
+
| `createWebSocketFeeds(client, { subscribe, sequence, snapshot })` | Topics with numbered messages, each delivered once and in order across reconnects; pass it to `createWebSocketState` |
|
|
123
178
|
| `createWebSocketState(client, { initialState, reduce })` | Message-state store for `useWebSocketState` |
|
|
179
|
+
| `useWebSocketState(store, selector?)` | Read state reduced from messages; re-renders only when the selection changes |
|
|
180
|
+
| `useInView(ref, options?)` | Whether an element is on screen, to pick a topic with: full detail only for what's visible |
|
|
181
|
+
| **Requests and streams** | |
|
|
124
182
|
| `createWebSocketRequests(client, { send, reply })` | `request(message)` returns a promise of the reply, and `stream(message)` an async iterator of replies, with timeouts and `cancel` |
|
|
183
|
+
| `useWebSocketStream(rpc, options?)` | Stream the replies to a request into a value, e.g. tokens into an answer; returns `{ value, status, error, start, abort }` |
|
|
125
184
|
| `createWebSocketLatency(client, { ping, pong })` | Ping tracker for `useWebSocketLatency`, plus `serverNow()` |
|
|
126
|
-
| `
|
|
185
|
+
| `useWebSocketLatency(latency)` | Round-trip time and server clock offset |
|
|
186
|
+
| **AI agents** | |
|
|
127
187
|
| `createWebSocketResponder(client, { request, respond, error })` | Answer the server's requests: `onRequest(method, handler)`, or a person through `useAgentApproval` |
|
|
128
|
-
| `
|
|
129
|
-
| `
|
|
188
|
+
| `useAgentApproval(responder, method)` | Requests from the server waiting for a person to answer |
|
|
189
|
+
| `createWebSocketRuns(client, { start, resume, event, reduce })` | Runs that resume after a reconnect or a reload: `start(request)`, `abort(runId)`, a `keep` or `cancel` policy |
|
|
190
|
+
| `useAgentRun(runs, runId)` | A resumable run's value and status, e.g. an AI answer that keeps streaming after a reconnect or a reload |
|
|
191
|
+
| `createAgUiAgent(client, options?)` | From `react-websocket/ag-ui`: `run({ messages })` an AG-UI agent over a WebSocket; also `applyAgUiEvent` and `applyPatch` |
|
|
192
|
+
| `useAgUiAgent(agent)` | An AG-UI agent's thread: messages, tool calls, shared state and status |
|
|
193
|
+
| **Multiplayer and presence** | |
|
|
194
|
+
| `createWebSocketPresence(client, { send, receive })` | `set(state)` shares this client's state, throttled and refreshed; peers expire after `timeout` |
|
|
195
|
+
| `useWebSocketPresence(presence)` | The other peers' shared state, such as live cursors |
|
|
196
|
+
| `createWebSocketSendRate(client, options?)` | `send(message, key)` coalesced per key at a rate that drops on a congested link |
|
|
130
197
|
| `createWebSocketTimeline(client, { snapshot, interpolate, input })` | From `react-websocket/timeline`: interpolated server snapshots (`at()`) and predicted inputs (`predicted()`, `input()`) for multiplayer games |
|
|
198
|
+
| **Transports and offline** | |
|
|
199
|
+
| `createTabsWebSocket(options?)` | From `react-websocket/tabs`: a `WebSocket` class that shares one connection between all the tabs of an app |
|
|
200
|
+
| `createWebTransportSocket(options?)` | From `react-websocket/webtransport`: a `WebSocket` class over WebTransport, with datagrams for `volatile` sends and a WebSocket fallback |
|
|
201
|
+
| `createWebSocketOutbox(client, { name, send, ack })` | From `react-websocket/outbox`: `add(message)` keeps a message in IndexedDB and sends it until the server acknowledges it, across reconnects and reloads |
|
|
202
|
+
| `useWebSocketOutbox(outbox)` | The messages waiting in an outbox, for a "3 orders waiting to sync" banner |
|
|
203
|
+
| **Debug and test** | |
|
|
204
|
+
| `<WebSocketDevtools sources={…} />` | From `react-websocket/devtools`: a development panel showing every client's status, queue, buffer, messages, RTT and topics |
|
|
131
205
|
| `createChaosWebSocket(options)` | From `react-websocket/chaos`: a `WebSocket` class that adds latency, lost messages and dropped connections in development |
|
|
206
|
+
| `createRecordingWebSocket()` / `createReplayWebSocket(recording)` | From `react-websocket/replay`: record sessions to JSON, and replay them without a server, at any speed |
|
|
132
207
|
|
|
133
208
|
| Option | Default | |
|
|
134
209
|
| --- | --- | --- |
|
|
@@ -137,9 +212,9 @@ function Room() {
|
|
|
137
212
|
| `json` | `false` | `JSON.parse` incoming and `JSON.stringify` outgoing messages |
|
|
138
213
|
| `parse(data)` / `serialize(message)` | | Custom codec; takes precedence over `json` |
|
|
139
214
|
| `schema` | | Standard Schema validation; types are inferred |
|
|
140
|
-
| `reconnect` | `true` | `false`, or `{ maxAttempts, minDelay, maxDelay, factor, jitter, minUptime, shouldReconnect }` |
|
|
215
|
+
| `reconnect` | `true` | `false`, or `{ maxAttempts, minDelay, maxDelay, factor, jitter, minUptime, shouldReconnect, retryAfter }` |
|
|
141
216
|
| `heartbeat` | | `{ interval, message, pong, timeout }` |
|
|
142
|
-
| `queue` | `true` (100 messages) | `false`, or `{ limit }` |
|
|
217
|
+
| `queue` | `true` (100 messages) | `false`, or `{ limit, maxAge }` |
|
|
143
218
|
| `logger` | | e.g. `console.debug` |
|
|
144
219
|
| `WebSocket` | global | Custom implementation for tests, Node, or chaos testing |
|
|
145
220
|
|
|
@@ -150,7 +225,8 @@ function Room() {
|
|
|
150
225
|
- [Shared clients](https://mehmetkose.github.io/react-websocket/guide/shared-clients) · [Messages and types](https://mehmetkose.github.io/react-websocket/guide/messages) · [Reconnecting and heartbeats](https://mehmetkose.github.io/react-websocket/guide/reconnecting)
|
|
151
226
|
- [Suspense](https://mehmetkose.github.io/react-websocket/guide/suspense) · [Server rendering and Next.js](https://mehmetkose.github.io/react-websocket/guide/ssr) · [StrictMode, Activity and lifecycle](https://mehmetkose.github.io/react-websocket/guide/lifecycle)
|
|
152
227
|
- [Authentication](https://mehmetkose.github.io/react-websocket/guide/authentication) · [Performance](https://mehmetkose.github.io/react-websocket/guide/performance) · [Real-time games](https://mehmetkose.github.io/react-websocket/guide/games) · [AI agents](https://mehmetkose.github.io/react-websocket/guide/agents) · [Testing](https://mehmetkose.github.io/react-websocket/guide/testing) · [Chaos testing](https://mehmetkose.github.io/react-websocket/guide/chaos) · [Without React](https://mehmetkose.github.io/react-websocket/guide/without-react)
|
|
153
|
-
- [Recipes](https://mehmetkose.github.io/react-websocket/recipes)
|
|
228
|
+
- [Recipes and real-world guides](https://mehmetkose.github.io/react-websocket/recipes): whole apps, client and server, such as an [AI chatbot](https://mehmetkose.github.io/react-websocket/recipes/ai-chatbot), a [party game](https://mehmetkose.github.io/react-websocket/recipes/party-game), a [team chat](https://mehmetkose.github.io/react-websocket/recipes/team-chat) and a [trading dashboard](https://mehmetkose.github.io/react-websocket/recipes/trading-dashboard)
|
|
229
|
+
- [Troubleshooting](https://mehmetkose.github.io/react-websocket/troubleshooting) · [Migrating from v3](https://mehmetkose.github.io/react-websocket/migration-v3) · [Migrating from v2](https://mehmetkose.github.io/react-websocket/migration)
|
|
154
230
|
|
|
155
231
|
The docs source lives in [`docs/`](docs). Run `npm run docs:dev` to browse it locally.
|
|
156
232
|
|
package/dist/ag-ui.cjs
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let __core_cjs = require("./core.cjs");
|
|
3
|
+
//#region src/ag-ui.ts
|
|
4
|
+
function unescape(token) {
|
|
5
|
+
return token.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
6
|
+
}
|
|
7
|
+
function equal(a, b) {
|
|
8
|
+
if (a === b) return true;
|
|
9
|
+
if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false;
|
|
10
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
11
|
+
const keys = Object.keys(a);
|
|
12
|
+
return keys.length === Object.keys(b).length && keys.every((key) => equal(a[key], b[key]));
|
|
13
|
+
}
|
|
14
|
+
function fail(operation) {
|
|
15
|
+
throw new Error(`JSON Patch failed: ${operation.op} ${operation.path}`);
|
|
16
|
+
}
|
|
17
|
+
const INDEX = /^(0|[1-9]\d*)$/;
|
|
18
|
+
/** A JSON Pointer's tokens. It's empty, for the whole document, or starts with `/`. */
|
|
19
|
+
function tokens(pointer, operation) {
|
|
20
|
+
if (pointer !== "" && pointer[0] !== "/") fail(operation);
|
|
21
|
+
return pointer.split("/").slice(1).map(unescape);
|
|
22
|
+
}
|
|
23
|
+
/** Whether `node` has `token`: an index in range for an array, not `length`; an own key otherwise. */
|
|
24
|
+
function has(node, token) {
|
|
25
|
+
return Array.isArray(node) ? INDEX.test(token) && +token < node.length : Object.hasOwn(node, token);
|
|
26
|
+
}
|
|
27
|
+
/** Set an own property, even `__proto__`, as JSON.parse would. */
|
|
28
|
+
function put(object, key, value) {
|
|
29
|
+
Object.defineProperty(object, key, {
|
|
30
|
+
value,
|
|
31
|
+
writable: true,
|
|
32
|
+
enumerable: true,
|
|
33
|
+
configurable: true
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Apply a JSON Patch (RFC 6902) without changing `document`: what changes is copied, the rest is
|
|
38
|
+
* shared. Throws, leaving `document` as it was, if an operation can't be applied: a missing path,
|
|
39
|
+
* an index out of range, a pointer that doesn't start with `/`, or a failed `test`.
|
|
40
|
+
*/
|
|
41
|
+
function applyPatch(document, operations) {
|
|
42
|
+
let root = document;
|
|
43
|
+
function get(path, operation) {
|
|
44
|
+
let node = root;
|
|
45
|
+
for (const token of tokens(path, operation)) {
|
|
46
|
+
if (typeof node !== "object" || node === null || !has(node, token)) fail(operation);
|
|
47
|
+
node = node[token];
|
|
48
|
+
}
|
|
49
|
+
return node;
|
|
50
|
+
}
|
|
51
|
+
function edit(path, operation, change) {
|
|
52
|
+
const keys = tokens(path, operation);
|
|
53
|
+
if (!keys.length) fail(operation);
|
|
54
|
+
const walk = (node, depth) => {
|
|
55
|
+
if (typeof node !== "object" || node === null) fail(operation);
|
|
56
|
+
const copy = Array.isArray(node) ? [...node] : { ...node };
|
|
57
|
+
const key = keys[depth];
|
|
58
|
+
if (depth === keys.length - 1) change(copy, key);
|
|
59
|
+
else if (!has(node, key)) fail(operation);
|
|
60
|
+
else copy[key] = walk(node[key], depth + 1);
|
|
61
|
+
return copy;
|
|
62
|
+
};
|
|
63
|
+
root = walk(root, 0);
|
|
64
|
+
}
|
|
65
|
+
function index(parent, key, operation, adding) {
|
|
66
|
+
const i = key === "-" ? adding ? parent.length : -1 : INDEX.test(key) ? +key : -1;
|
|
67
|
+
if (i < 0 || i > parent.length - (adding ? 0 : 1)) fail(operation);
|
|
68
|
+
return i;
|
|
69
|
+
}
|
|
70
|
+
function add(path, value, operation) {
|
|
71
|
+
if (path === "") return void (root = value);
|
|
72
|
+
edit(path, operation, (parent, key) => {
|
|
73
|
+
if (Array.isArray(parent)) parent.splice(index(parent, key, operation, true), 0, value);
|
|
74
|
+
else put(parent, key, value);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function remove(path, operation) {
|
|
78
|
+
edit(path, operation, (parent, key) => {
|
|
79
|
+
if (Array.isArray(parent)) parent.splice(index(parent, key, operation, false), 1);
|
|
80
|
+
else if (Object.hasOwn(parent, key)) delete parent[key];
|
|
81
|
+
else fail(operation);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
for (const operation of operations) {
|
|
85
|
+
const { op, path, from, value } = operation;
|
|
86
|
+
if (op === "add") add(path, value, operation);
|
|
87
|
+
else if (op === "remove") remove(path, operation);
|
|
88
|
+
else if (op === "replace") {
|
|
89
|
+
get(path, operation);
|
|
90
|
+
if (path === "") root = value;
|
|
91
|
+
else edit(path, operation, (parent, key) => {
|
|
92
|
+
if (Array.isArray(parent)) parent[key] = value;
|
|
93
|
+
else put(parent, key, value);
|
|
94
|
+
});
|
|
95
|
+
} else if (op === "move" || op === "copy") {
|
|
96
|
+
const moved = get(from ?? fail(operation), operation);
|
|
97
|
+
if (op === "move") remove(from, operation);
|
|
98
|
+
add(path, op === "copy" ? structuredClone(moved) : moved, operation);
|
|
99
|
+
} else if (op === "test") {
|
|
100
|
+
if (!equal(get(path, operation), value)) fail(operation);
|
|
101
|
+
} else fail(operation);
|
|
102
|
+
}
|
|
103
|
+
return root;
|
|
104
|
+
}
|
|
105
|
+
function updateMessage(thread, id, change) {
|
|
106
|
+
return thread.messages.map((message) => message.id === id ? change(message) : message);
|
|
107
|
+
}
|
|
108
|
+
function appendText(message, delta) {
|
|
109
|
+
return {
|
|
110
|
+
...message,
|
|
111
|
+
content: `${message.content ?? ""}${delta ?? ""}`
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function updateToolCall(thread, id, change) {
|
|
115
|
+
return thread.messages.map((message) => message.toolCalls?.some((call) => call.id === id) ? {
|
|
116
|
+
...message,
|
|
117
|
+
toolCalls: message.toolCalls.map((call) => call.id === id ? change(call) : call)
|
|
118
|
+
} : message);
|
|
119
|
+
}
|
|
120
|
+
/** The last message with a tool call, for chunks that leave out `toolCallId`. */
|
|
121
|
+
function lastToolCallId(thread) {
|
|
122
|
+
for (let i = thread.messages.length - 1; i >= 0; i--) {
|
|
123
|
+
const calls = thread.messages[i].toolCalls;
|
|
124
|
+
if (calls?.length) return calls.at(-1).id;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Fold one AG-UI event into a thread, without changing it. Handles the run lifecycle, steps,
|
|
129
|
+
* text, tool calls and their results, reasoning, activity, and message and state snapshots and
|
|
130
|
+
* deltas. A `STATE_DELTA` that can't be applied marks the thread `stale` instead of throwing.
|
|
131
|
+
* Other events, such as `CUSTOM` and `RAW`, return the thread unchanged.
|
|
132
|
+
*
|
|
133
|
+
* Use it as a `reduce` function, or wrap it to handle events of your own.
|
|
134
|
+
*/
|
|
135
|
+
function applyAgUiEvent(thread, event) {
|
|
136
|
+
const e = event;
|
|
137
|
+
const message = (role, extra) => ({
|
|
138
|
+
...thread,
|
|
139
|
+
messages: [...thread.messages, {
|
|
140
|
+
id: e.messageId,
|
|
141
|
+
role,
|
|
142
|
+
content: "",
|
|
143
|
+
...extra
|
|
144
|
+
}]
|
|
145
|
+
});
|
|
146
|
+
const known = (id) => thread.messages.some((m) => m.id === id);
|
|
147
|
+
switch (e.type) {
|
|
148
|
+
case "RUN_STARTED": return {
|
|
149
|
+
...thread,
|
|
150
|
+
status: "running",
|
|
151
|
+
error: void 0,
|
|
152
|
+
result: void 0
|
|
153
|
+
};
|
|
154
|
+
case "RUN_FINISHED": return {
|
|
155
|
+
...thread,
|
|
156
|
+
status: "finished",
|
|
157
|
+
step: void 0,
|
|
158
|
+
result: e.result
|
|
159
|
+
};
|
|
160
|
+
case "RUN_ERROR": return {
|
|
161
|
+
...thread,
|
|
162
|
+
status: "error",
|
|
163
|
+
step: void 0,
|
|
164
|
+
error: {
|
|
165
|
+
message: e.message,
|
|
166
|
+
code: e.code
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
case "STEP_STARTED": return {
|
|
170
|
+
...thread,
|
|
171
|
+
step: e.stepName
|
|
172
|
+
};
|
|
173
|
+
case "STEP_FINISHED": return {
|
|
174
|
+
...thread,
|
|
175
|
+
step: void 0
|
|
176
|
+
};
|
|
177
|
+
case "TEXT_MESSAGE_START": return message(e.role ?? "assistant");
|
|
178
|
+
case "REASONING_MESSAGE_START": return message("reasoning");
|
|
179
|
+
case "TEXT_MESSAGE_CONTENT":
|
|
180
|
+
case "REASONING_MESSAGE_CONTENT": return {
|
|
181
|
+
...thread,
|
|
182
|
+
messages: updateMessage(thread, e.messageId, (m) => appendText(m, e.delta))
|
|
183
|
+
};
|
|
184
|
+
case "TEXT_MESSAGE_CHUNK":
|
|
185
|
+
case "REASONING_MESSAGE_CHUNK": {
|
|
186
|
+
const id = e.messageId ?? thread.messages.at(-1)?.id;
|
|
187
|
+
const role = e.type === "TEXT_MESSAGE_CHUNK" ? e.role ?? "assistant" : "reasoning";
|
|
188
|
+
const next = known(id) ? thread : message(role);
|
|
189
|
+
return {
|
|
190
|
+
...next,
|
|
191
|
+
messages: updateMessage(next, id, (m) => appendText(m, e.delta))
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
case "TOOL_CALL_START":
|
|
195
|
+
case "TOOL_CALL_CHUNK": {
|
|
196
|
+
const id = e.toolCallId ?? lastToolCallId(thread);
|
|
197
|
+
let next = thread;
|
|
198
|
+
if (e.type === "TOOL_CALL_START" || !thread.messages.some((m) => m.toolCalls?.some((c) => c.id === id))) {
|
|
199
|
+
const call = {
|
|
200
|
+
id,
|
|
201
|
+
type: "function",
|
|
202
|
+
function: {
|
|
203
|
+
name: e.toolCallName,
|
|
204
|
+
arguments: ""
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
const parent = e.parentMessageId ?? id;
|
|
208
|
+
next = known(parent) ? thread : {
|
|
209
|
+
...thread,
|
|
210
|
+
messages: [...thread.messages, {
|
|
211
|
+
id: parent,
|
|
212
|
+
role: "assistant"
|
|
213
|
+
}]
|
|
214
|
+
};
|
|
215
|
+
next = {
|
|
216
|
+
...next,
|
|
217
|
+
messages: updateMessage(next, parent, (m) => ({
|
|
218
|
+
...m,
|
|
219
|
+
toolCalls: [...m.toolCalls ?? [], call]
|
|
220
|
+
}))
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
if (e.type === "TOOL_CALL_START") return next;
|
|
224
|
+
return toolArgs(next, id, e.delta);
|
|
225
|
+
}
|
|
226
|
+
case "TOOL_CALL_ARGS": return toolArgs(thread, e.toolCallId, e.delta);
|
|
227
|
+
case "TOOL_CALL_RESULT": return message(e.role ?? "tool", {
|
|
228
|
+
toolCallId: e.toolCallId,
|
|
229
|
+
content: e.content
|
|
230
|
+
});
|
|
231
|
+
case "STATE_SNAPSHOT": return {
|
|
232
|
+
...thread,
|
|
233
|
+
state: e.snapshot,
|
|
234
|
+
stale: false
|
|
235
|
+
};
|
|
236
|
+
case "STATE_DELTA":
|
|
237
|
+
if (thread.stale) return thread;
|
|
238
|
+
try {
|
|
239
|
+
return {
|
|
240
|
+
...thread,
|
|
241
|
+
state: applyPatch(thread.state, e.delta)
|
|
242
|
+
};
|
|
243
|
+
} catch {
|
|
244
|
+
return {
|
|
245
|
+
...thread,
|
|
246
|
+
stale: true
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
case "MESSAGES_SNAPSHOT": return {
|
|
250
|
+
...thread,
|
|
251
|
+
messages: e.messages
|
|
252
|
+
};
|
|
253
|
+
case "ACTIVITY_SNAPSHOT": {
|
|
254
|
+
if (known(e.messageId) && e.replace === false) return thread;
|
|
255
|
+
const next = known(e.messageId) ? thread : message("activity");
|
|
256
|
+
return {
|
|
257
|
+
...next,
|
|
258
|
+
messages: updateMessage(next, e.messageId, (m) => ({
|
|
259
|
+
...m,
|
|
260
|
+
activityType: e.activityType,
|
|
261
|
+
content: e.content
|
|
262
|
+
}))
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
case "ACTIVITY_DELTA": try {
|
|
266
|
+
return {
|
|
267
|
+
...thread,
|
|
268
|
+
messages: updateMessage(thread, e.messageId, (m) => ({
|
|
269
|
+
...m,
|
|
270
|
+
content: applyPatch(m.content, e.patch)
|
|
271
|
+
}))
|
|
272
|
+
};
|
|
273
|
+
} catch {
|
|
274
|
+
return thread;
|
|
275
|
+
}
|
|
276
|
+
default: return thread;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function toolArgs(thread, id, delta) {
|
|
280
|
+
return {
|
|
281
|
+
...thread,
|
|
282
|
+
messages: updateToolCall(thread, id, (call) => ({
|
|
283
|
+
...call,
|
|
284
|
+
function: {
|
|
285
|
+
...call.function,
|
|
286
|
+
arguments: call.function.arguments + (delta ?? "")
|
|
287
|
+
}
|
|
288
|
+
}))
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
function randomId() {
|
|
292
|
+
return globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
293
|
+
}
|
|
294
|
+
const isEnvelope = (message) => typeof message?.runId === "string" && typeof message.offset === "number" && typeof message.event?.type === "string" ? message : void 0;
|
|
295
|
+
const ENDS = /* @__PURE__ */ new Set(["RUN_FINISHED", "RUN_ERROR"]);
|
|
296
|
+
/**
|
|
297
|
+
* Run an [AG-UI](https://docs.ag-ui.com) agent over a WebSocket. Each run streams AG-UI events,
|
|
298
|
+
* which are folded into the thread's messages and shared state with {@link applyAgUiEvent}.
|
|
299
|
+
* Runs come from `createWebSocketRuns`, so they resume after a reconnect or a reload, and a
|
|
300
|
+
* state delta that can't be applied asks for a snapshot (`resync`).
|
|
301
|
+
*
|
|
302
|
+
* AG-UI doesn't define messages for WebSockets, so the defaults are small: the client sends
|
|
303
|
+
* `{ type: 'run', runId, input }`, `{ type: 'resume', runId, after }` and
|
|
304
|
+
* `{ type: 'cancel', runId }`, and the server sends `{ runId, offset, event }`, with `offset`
|
|
305
|
+
* counting each run's events from 1. Each option replaces one of them.
|
|
306
|
+
*
|
|
307
|
+
* @example
|
|
308
|
+
* ```ts
|
|
309
|
+
* import { createAgUiAgent } from 'react-websocket/ag-ui';
|
|
310
|
+
*
|
|
311
|
+
* export const agent = createAgUiAgent(createWebSocket(url, { json: true }));
|
|
312
|
+
*
|
|
313
|
+
* agent.run({ messages: [{ id: crypto.randomUUID(), role: 'user', content: 'Plan my week' }] });
|
|
314
|
+
* ```
|
|
315
|
+
*/
|
|
316
|
+
function createAgUiAgent(client, options = {}) {
|
|
317
|
+
const threadId = options.threadId ?? randomId();
|
|
318
|
+
const empty = {
|
|
319
|
+
messages: [],
|
|
320
|
+
state: options.state,
|
|
321
|
+
status: "idle",
|
|
322
|
+
stale: false
|
|
323
|
+
};
|
|
324
|
+
let base = empty;
|
|
325
|
+
let snapshot = empty;
|
|
326
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
327
|
+
const resynced = /* @__PURE__ */ new Set();
|
|
328
|
+
const event = options.event ?? isEnvelope;
|
|
329
|
+
const send = (message) => client.socket?.readyState === 1 && client.send(message);
|
|
330
|
+
const runs = (0, __core_cjs.createWebSocketRuns)(client, {
|
|
331
|
+
name: options.name ?? "ag-ui",
|
|
332
|
+
start: options.run ?? ((input, runId) => ({
|
|
333
|
+
type: "run",
|
|
334
|
+
runId,
|
|
335
|
+
input
|
|
336
|
+
})),
|
|
337
|
+
resume: options.resume ?? ((runId, after) => ({
|
|
338
|
+
type: "resume",
|
|
339
|
+
runId,
|
|
340
|
+
after
|
|
341
|
+
})),
|
|
342
|
+
cancel: options.cancel ?? ((runId) => ({
|
|
343
|
+
type: "cancel",
|
|
344
|
+
runId
|
|
345
|
+
})),
|
|
346
|
+
event: (message) => event(message),
|
|
347
|
+
done: (message) => ENDS.has(event(message).event.type),
|
|
348
|
+
initial: empty,
|
|
349
|
+
reduce: (thread, message) => applyAgUiEvent(thread, event(message).event),
|
|
350
|
+
policy: options.policy,
|
|
351
|
+
storage: options.storage
|
|
352
|
+
});
|
|
353
|
+
function update() {
|
|
354
|
+
const latest = runs.list().at(-1);
|
|
355
|
+
let next = latest ? latest.value : base;
|
|
356
|
+
if (latest?.status === "aborted" && next.status === "running") next = {
|
|
357
|
+
...next,
|
|
358
|
+
status: "aborted"
|
|
359
|
+
};
|
|
360
|
+
if (latest && !latest.value.stale) resynced.delete(latest.runId);
|
|
361
|
+
else if (latest && options.resync && !resynced.has(latest.runId)) {
|
|
362
|
+
if (send(options.resync(latest.runId))) resynced.add(latest.runId);
|
|
363
|
+
}
|
|
364
|
+
if (next === snapshot) return;
|
|
365
|
+
snapshot = next;
|
|
366
|
+
for (const listener of [...listeners]) listener();
|
|
367
|
+
}
|
|
368
|
+
const off = runs.subscribe(update);
|
|
369
|
+
update();
|
|
370
|
+
function abort() {
|
|
371
|
+
for (const run of runs.list()) runs.abort(run.runId);
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
client,
|
|
375
|
+
runs,
|
|
376
|
+
run(input = {}, runOptions) {
|
|
377
|
+
abort();
|
|
378
|
+
const runId = randomId();
|
|
379
|
+
base = {
|
|
380
|
+
...snapshot,
|
|
381
|
+
stale: false,
|
|
382
|
+
messages: [...snapshot.messages, ...input.messages ?? []]
|
|
383
|
+
};
|
|
384
|
+
runs.start({
|
|
385
|
+
threadId,
|
|
386
|
+
runId,
|
|
387
|
+
state: base.state,
|
|
388
|
+
messages: base.messages,
|
|
389
|
+
tools: input.tools ?? [],
|
|
390
|
+
context: input.context ?? [],
|
|
391
|
+
forwardedProps: input.forwardedProps ?? {}
|
|
392
|
+
}, {
|
|
393
|
+
runId,
|
|
394
|
+
initial: {
|
|
395
|
+
...base,
|
|
396
|
+
status: "running"
|
|
397
|
+
},
|
|
398
|
+
policy: runOptions?.policy
|
|
399
|
+
});
|
|
400
|
+
return runId;
|
|
401
|
+
},
|
|
402
|
+
abort,
|
|
403
|
+
getSnapshot: () => snapshot,
|
|
404
|
+
subscribe(listener) {
|
|
405
|
+
listeners.add(listener);
|
|
406
|
+
return () => {
|
|
407
|
+
listeners.delete(listener);
|
|
408
|
+
};
|
|
409
|
+
},
|
|
410
|
+
dispose() {
|
|
411
|
+
off();
|
|
412
|
+
runs.dispose();
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
//#endregion
|
|
417
|
+
exports.applyAgUiEvent = applyAgUiEvent;
|
|
418
|
+
exports.applyPatch = applyPatch;
|
|
419
|
+
exports.createAgUiAgent = createAgUiAgent;
|
|
420
|
+
|
|
421
|
+
//# sourceMappingURL=ag-ui.cjs.map
|