react-websocket 4.22.1 → 4.22.3

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 (60) hide show
  1. package/dist/ag-ui.cjs +8 -9
  2. package/dist/ag-ui.cjs.map +1 -1
  3. package/dist/ag-ui.d.cts +3 -8
  4. package/dist/ag-ui.d.ts +0 -2
  5. package/dist/ag-ui.js +8 -9
  6. package/dist/ag-ui.js.map +1 -1
  7. package/dist/chaos.cjs +60 -13
  8. package/dist/chaos.cjs.map +1 -1
  9. package/dist/chaos.d.cts +1 -2
  10. package/dist/chaos.d.ts +1 -2
  11. package/dist/chaos.js +60 -13
  12. package/dist/chaos.js.map +1 -1
  13. package/dist/core.cjs +93 -65
  14. package/dist/core.cjs.map +1 -1
  15. package/dist/core.d.cts +4 -25
  16. package/dist/core.d.ts +4 -25
  17. package/dist/core.js +93 -65
  18. package/dist/core.js.map +1 -1
  19. package/dist/devtools.cjs +1 -2
  20. package/dist/devtools.d.cts +0 -2
  21. package/dist/devtools.d.ts +0 -2
  22. package/dist/devtools.js +1 -2
  23. package/dist/index.cjs +1 -2
  24. package/dist/index.d.cts +4 -31
  25. package/dist/index.d.ts +3 -24
  26. package/dist/index.development.cjs +1 -2
  27. package/dist/index.development.js +1 -2
  28. package/dist/index.js +1 -2
  29. package/dist/outbox.cjs +15 -10
  30. package/dist/outbox.cjs.map +1 -1
  31. package/dist/outbox.d.cts +1 -3
  32. package/dist/outbox.d.ts +0 -2
  33. package/dist/outbox.js +15 -10
  34. package/dist/outbox.js.map +1 -1
  35. package/dist/replay.cjs +13 -9
  36. package/dist/replay.cjs.map +1 -1
  37. package/dist/replay.d.cts +8 -4
  38. package/dist/replay.d.ts +8 -4
  39. package/dist/replay.js +13 -9
  40. package/dist/replay.js.map +1 -1
  41. package/dist/tabs.cjs +12 -16
  42. package/dist/tabs.cjs.map +1 -1
  43. package/dist/tabs.d.cts +0 -2
  44. package/dist/tabs.d.ts +0 -2
  45. package/dist/tabs.js +12 -16
  46. package/dist/tabs.js.map +1 -1
  47. package/dist/timeline.cjs +4 -3
  48. package/dist/timeline.cjs.map +1 -1
  49. package/dist/timeline.d.cts +3 -7
  50. package/dist/timeline.d.ts +2 -4
  51. package/dist/timeline.js +4 -3
  52. package/dist/timeline.js.map +1 -1
  53. package/dist/{types-paLT8yQF.d.cts → types-DyZm2F7B.d.cts} +4 -5
  54. package/dist/webtransport.cjs +13 -12
  55. package/dist/webtransport.cjs.map +1 -1
  56. package/dist/webtransport.d.cts +0 -2
  57. package/dist/webtransport.d.ts +0 -2
  58. package/dist/webtransport.js +13 -12
  59. package/dist/webtransport.js.map +1 -1
  60. package/package.json +9 -9
package/dist/ag-ui.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let __core_cjs = require("./core.cjs");
3
- //#region src/ag-ui.ts
3
+ // src/ag-ui.ts
4
4
  function unescape(token) {
5
5
  return token.replace(/~1/g, "/").replace(/~0/g, "~");
6
6
  }
@@ -148,6 +148,7 @@ function applyAgUiEvent(thread, event) {
148
148
  case "RUN_STARTED": return {
149
149
  ...thread,
150
150
  status: "running",
151
+ step: void 0,
151
152
  error: void 0,
152
153
  result: void 0
153
154
  };
@@ -183,7 +184,7 @@ function applyAgUiEvent(thread, event) {
183
184
  };
184
185
  case "TEXT_MESSAGE_CHUNK":
185
186
  case "REASONING_MESSAGE_CHUNK": {
186
- const id = e.messageId ?? thread.messages.at(-1)?.id;
187
+ const id = e.messageId ?? thread.messages.filter((m) => m.role !== "activity").at(-1)?.id;
187
188
  const role = e.type === "TEXT_MESSAGE_CHUNK" ? e.role ?? "assistant" : "reasoning";
188
189
  const next = known(id) ? thread : message(role);
189
190
  return {
@@ -327,6 +328,7 @@ function createAgUiAgent(client, options = {}) {
327
328
  const resynced = /* @__PURE__ */ new Set();
328
329
  const event = options.event ?? isEnvelope;
329
330
  const send = (message) => client.socket?.readyState === 1 && client.send(message);
331
+ const started = (thread) => applyAgUiEvent(thread, { type: "RUN_STARTED" });
330
332
  const runs = (0, __core_cjs.createWebSocketRuns)(client, {
331
333
  name: options.name ?? "ag-ui",
332
334
  start: options.run ?? ((input, runId) => ({
@@ -345,7 +347,7 @@ function createAgUiAgent(client, options = {}) {
345
347
  })),
346
348
  event: (message) => event(message),
347
349
  done: (message) => ENDS.has(event(message).event.type),
348
- initial: empty,
350
+ initial: started(empty),
349
351
  reduce: (thread, message) => applyAgUiEvent(thread, event(message).event),
350
352
  policy: options.policy,
351
353
  storage: options.storage
@@ -355,7 +357,8 @@ function createAgUiAgent(client, options = {}) {
355
357
  let next = latest ? latest.value : base;
356
358
  if (latest?.status === "aborted" && next.status === "running") next = {
357
359
  ...next,
358
- status: "aborted"
360
+ status: "aborted",
361
+ step: void 0
359
362
  };
360
363
  if (latest && !latest.value.stale) resynced.delete(latest.runId);
361
364
  else if (latest && options.resync && !resynced.has(latest.runId)) {
@@ -391,10 +394,7 @@ function createAgUiAgent(client, options = {}) {
391
394
  forwardedProps: input.forwardedProps ?? {}
392
395
  }, {
393
396
  runId,
394
- initial: {
395
- ...base,
396
- status: "running"
397
- },
397
+ initial: started(base),
398
398
  policy: runOptions?.policy
399
399
  });
400
400
  return runId;
@@ -420,7 +420,6 @@ function createAgUiAgent(client, options = {}) {
420
420
  }
421
421
  };
422
422
  }
423
- //#endregion
424
423
  exports.applyAgUiEvent = applyAgUiEvent;
425
424
  exports.applyPatch = applyPatch;
426
425
  exports.createAgUiAgent = createAgUiAgent;
@@ -1 +1 @@
1
- {"version":3,"file":"ag-ui.cjs","names":["createWebSocketRuns"],"sources":["../src/ag-ui.ts"],"sourcesContent":["// The build keeps `./core` external, so this entry shares the client with the others.\nimport {\n createWebSocketRuns,\n type RunPolicy,\n type RunStorage,\n type WebSocketClient,\n type WebSocketRuns\n} from './core';\n\n/** A JSON Patch (RFC 6902) operation, as in AG-UI's `STATE_DELTA` and `ACTIVITY_DELTA`. */\nexport interface JsonPatchOperation {\n readonly op: 'add' | 'remove' | 'replace' | 'move' | 'copy' | 'test';\n /** A JSON Pointer (RFC 6901), such as `/items/0/name`. */\n readonly path: string;\n /** The source of `move` and `copy`. */\n readonly from?: string;\n /** The value to `add`, `replace` with or `test` for. */\n readonly value?: unknown;\n}\n\n/** An AG-UI event: `type` is `'RUN_STARTED'`, `'TEXT_MESSAGE_CONTENT'`, `'STATE_DELTA'`, … */\nexport interface AgUiEvent {\n readonly type: string;\n readonly [field: string]: any;\n}\n\n/** A tool call on an assistant message, as in AG-UI. */\nexport interface AgUiToolCall {\n readonly id: string;\n readonly type: 'function';\n readonly function: { readonly name: string; readonly arguments: string };\n}\n\n/** A message in an AG-UI thread. */\nexport interface AgUiMessage {\n readonly id: string;\n readonly role: 'developer' | 'system' | 'assistant' | 'user' | 'tool' | 'reasoning' | 'activity';\n readonly content?: unknown;\n readonly toolCalls?: readonly AgUiToolCall[];\n /** For a `tool` message, the call it answers. */\n readonly toolCallId?: string;\n /** For an `activity` message. */\n readonly activityType?: string;\n readonly [field: string]: unknown;\n}\n\n/** AG-UI's `RunAgentInput`: what a run starts from. */\nexport interface RunAgentInput {\n readonly threadId: string;\n readonly runId: string;\n readonly parentRunId?: string;\n readonly state?: unknown;\n readonly messages: readonly AgUiMessage[];\n readonly tools: readonly unknown[];\n readonly context: readonly unknown[];\n readonly forwardedProps: unknown;\n}\n\n/** A thread's messages and shared state, reduced from AG-UI events. */\nexport interface AgUiThread<S = unknown> {\n readonly messages: readonly AgUiMessage[];\n /** The shared state, from `STATE_SNAPSHOT` and `STATE_DELTA`. */\n readonly state: S;\n /**\n * `'running'` from `RUN_STARTED`, `'finished'` after `RUN_FINISHED`, `'error'` after\n * `RUN_ERROR`, `'aborted'` when the run was stopped from this side.\n */\n readonly status: 'idle' | 'running' | 'finished' | 'error' | 'aborted';\n /** The step in progress, between `STEP_STARTED` and `STEP_FINISHED`. */\n readonly step?: string;\n /** From `RUN_ERROR`. */\n readonly error?: { readonly message: string; readonly code?: string };\n /** From `RUN_FINISHED`. */\n readonly result?: unknown;\n /**\n * A `STATE_DELTA` couldn't be applied. `state` is the last good one, and later deltas are\n * skipped until a `STATE_SNAPSHOT` arrives.\n */\n readonly stale: boolean;\n}\n\ntype Json = any;\n\nfunction unescape(token: string) {\n return token.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\nfunction equal(a: Json, b: Json): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n return keys.length === Object.keys(b).length && keys.every(key => equal(a[key], b[key]));\n}\n\nfunction fail(operation: JsonPatchOperation): never {\n throw new Error(`JSON Patch failed: ${operation.op} ${operation.path}`);\n}\n\nconst INDEX = /^(0|[1-9]\\d*)$/;\n\n/** A JSON Pointer's tokens. It's empty, for the whole document, or starts with `/`. */\nfunction tokens(pointer: string, operation: JsonPatchOperation) {\n if (pointer !== '' && pointer[0] !== '/') fail(operation);\n return pointer.split('/').slice(1).map(unescape);\n}\n\n/** Whether `node` has `token`: an index in range for an array, not `length`; an own key otherwise. */\nfunction has(node: Json, token: string) {\n return Array.isArray(node)\n ? INDEX.test(token) && +token < node.length\n : Object.hasOwn(node, token);\n}\n\n/** Set an own property, even `__proto__`, as JSON.parse would. */\nfunction put(object: Json, key: string, value: Json) {\n Object.defineProperty(object, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n}\n\n/**\n * Apply a JSON Patch (RFC 6902) without changing `document`: what changes is copied, the rest is\n * shared. Throws, leaving `document` as it was, if an operation can't be applied: a missing path,\n * an index out of range, a pointer that doesn't start with `/`, or a failed `test`.\n */\nexport function applyPatch<T>(document: T, operations: readonly JsonPatchOperation[]): T {\n let root: Json = document;\n\n function get(path: string, operation: JsonPatchOperation): Json {\n let node = root;\n for (const token of tokens(path, operation)) {\n if (typeof node !== 'object' || node === null || !has(node, token)) fail(operation);\n node = node[token];\n }\n return node;\n }\n\n // Replace the parent of `path` with a copy, change it with `change`, and copy its ancestors.\n function edit(\n path: string,\n operation: JsonPatchOperation,\n change: (parent: Json, key: string) => void\n ) {\n const keys = tokens(path, operation);\n if (!keys.length) fail(operation);\n const walk = (node: Json, depth: number): Json => {\n if (typeof node !== 'object' || node === null) fail(operation);\n const copy = Array.isArray(node) ? [...node] : { ...node };\n const key = keys[depth]!;\n if (depth === keys.length - 1) change(copy, key);\n else if (!has(node, key)) fail(operation);\n else copy[key] = walk(node[key], depth + 1);\n return copy;\n };\n root = walk(root, 0);\n }\n\n function index(parent: Json[], key: string, operation: JsonPatchOperation, adding: boolean) {\n // `-` is the end of the array, which only `add` can use.\n const i = key === '-' ? (adding ? parent.length : -1) : INDEX.test(key) ? +key : -1;\n if (i < 0 || i > parent.length - (adding ? 0 : 1)) fail(operation);\n return i;\n }\n\n function add(path: string, value: Json, operation: JsonPatchOperation) {\n if (path === '') return void (root = value);\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent.splice(index(parent, key, operation, true), 0, value);\n else put(parent, key, value);\n });\n }\n\n function remove(path: string, operation: JsonPatchOperation) {\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent.splice(index(parent, key, operation, false), 1);\n else if (Object.hasOwn(parent, key)) delete parent[key];\n else fail(operation);\n });\n }\n\n for (const operation of operations) {\n const { op, path, from, value } = operation;\n if (op === 'add') add(path, value, operation);\n else if (op === 'remove') remove(path, operation);\n else if (op === 'replace') {\n get(path, operation);\n if (path === '') root = value;\n else\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent[key as unknown as number] = value;\n else put(parent, key, value);\n });\n } else if (op === 'move' || op === 'copy') {\n const moved = get(from ?? fail(operation), operation);\n if (op === 'move') remove(from!, operation);\n add(path, op === 'copy' ? structuredClone(moved) : moved, operation);\n } else if (op === 'test') {\n if (!equal(get(path, operation), value)) fail(operation);\n } else fail(operation);\n }\n return root;\n}\n\nfunction updateMessage(\n thread: AgUiThread<any>,\n id: string | undefined,\n change: (message: AgUiMessage) => AgUiMessage\n) {\n return thread.messages.map(message => (message.id === id ? change(message) : message));\n}\n\nfunction appendText(message: AgUiMessage, delta: string | undefined) {\n return { ...message, content: `${(message.content as string | undefined) ?? ''}${delta ?? ''}` };\n}\n\nfunction updateToolCall(\n thread: AgUiThread<any>,\n id: string | undefined,\n change: (call: AgUiToolCall) => AgUiToolCall\n) {\n return thread.messages.map(message =>\n message.toolCalls?.some(call => call.id === id)\n ? {\n ...message,\n toolCalls: message.toolCalls.map(call => (call.id === id ? change(call) : call))\n }\n : message\n );\n}\n\n/** The last message with a tool call, for chunks that leave out `toolCallId`. */\nfunction lastToolCallId(thread: AgUiThread<any>) {\n for (let i = thread.messages.length - 1; i >= 0; i--) {\n const calls = thread.messages[i]!.toolCalls;\n if (calls?.length) return calls.at(-1)!.id;\n }\n}\n\n/**\n * Fold one AG-UI event into a thread, without changing it. Handles the run lifecycle, steps,\n * text, tool calls and their results, reasoning, activity, and message and state snapshots and\n * deltas. A `STATE_DELTA` that can't be applied marks the thread `stale` instead of throwing.\n * Other events, such as `CUSTOM` and `RAW`, return the thread unchanged.\n *\n * Use it as a `reduce` function, or wrap it to handle events of your own.\n */\nexport function applyAgUiEvent<S>(thread: AgUiThread<S>, event: AgUiEvent): AgUiThread<S> {\n const e = event;\n const message = (role: AgUiMessage['role'], extra?: object): AgUiThread<S> => ({\n ...thread,\n messages: [...thread.messages, { id: e.messageId, role, content: '', ...extra }]\n });\n const known = (id: string | undefined) => thread.messages.some(m => m.id === id);\n switch (e.type) {\n case 'RUN_STARTED':\n return { ...thread, status: 'running', error: undefined, result: undefined };\n case 'RUN_FINISHED':\n return { ...thread, status: 'finished', step: undefined, result: e.result };\n case 'RUN_ERROR':\n return {\n ...thread,\n status: 'error',\n step: undefined,\n error: { message: e.message, code: e.code }\n };\n case 'STEP_STARTED':\n return { ...thread, step: e.stepName };\n case 'STEP_FINISHED':\n return { ...thread, step: undefined };\n case 'TEXT_MESSAGE_START':\n return message(e.role ?? 'assistant');\n case 'REASONING_MESSAGE_START':\n return message('reasoning');\n case 'TEXT_MESSAGE_CONTENT':\n case 'REASONING_MESSAGE_CONTENT':\n return {\n ...thread,\n messages: updateMessage(thread, e.messageId, m => appendText(m, e.delta))\n };\n case 'TEXT_MESSAGE_CHUNK':\n case 'REASONING_MESSAGE_CHUNK': {\n // Only the first chunk of a message must carry its id.\n const id = e.messageId ?? thread.messages.at(-1)?.id;\n const role = e.type === 'TEXT_MESSAGE_CHUNK' ? (e.role ?? 'assistant') : 'reasoning';\n const next = known(id) ? thread : message(role);\n return { ...next, messages: updateMessage(next, id, m => appendText(m, e.delta)) };\n }\n case 'TOOL_CALL_START':\n case 'TOOL_CALL_CHUNK': {\n const id = e.toolCallId ?? lastToolCallId(thread);\n let next = thread;\n if (\n e.type === 'TOOL_CALL_START' ||\n !thread.messages.some(m => m.toolCalls?.some(c => c.id === id))\n ) {\n const call: AgUiToolCall = {\n id,\n type: 'function',\n function: { name: e.toolCallName, arguments: '' }\n };\n const parent = e.parentMessageId ?? id;\n next = known(parent)\n ? thread\n : { ...thread, messages: [...thread.messages, { id: parent, role: 'assistant' }] };\n next = {\n ...next,\n messages: updateMessage(next, parent, m => ({\n ...m,\n toolCalls: [...(m.toolCalls ?? []), call]\n }))\n };\n }\n if (e.type === 'TOOL_CALL_START') return next;\n return toolArgs(next, id, e.delta);\n }\n case 'TOOL_CALL_ARGS':\n return toolArgs(thread, e.toolCallId, e.delta);\n case 'TOOL_CALL_RESULT':\n return message(e.role ?? 'tool', { toolCallId: e.toolCallId, content: e.content });\n case 'STATE_SNAPSHOT':\n return { ...thread, state: e.snapshot, stale: false };\n case 'STATE_DELTA':\n if (thread.stale) return thread;\n try {\n return { ...thread, state: applyPatch(thread.state, e.delta) };\n } catch {\n return { ...thread, stale: true };\n }\n case 'MESSAGES_SNAPSHOT':\n return { ...thread, messages: e.messages };\n case 'ACTIVITY_SNAPSHOT': {\n if (known(e.messageId) && e.replace === false) return thread;\n const next = known(e.messageId) ? thread : message('activity');\n return {\n ...next,\n messages: updateMessage(next, e.messageId, m => ({\n ...m,\n activityType: e.activityType,\n content: e.content\n }))\n };\n }\n case 'ACTIVITY_DELTA':\n try {\n return {\n ...thread,\n messages: updateMessage(thread, e.messageId, m => ({\n ...m,\n content: applyPatch(m.content, e.patch)\n }))\n };\n } catch {\n return thread;\n }\n default:\n return thread;\n }\n}\n\nfunction toolArgs<S>(thread: AgUiThread<S>, id: string | undefined, delta: string | undefined) {\n return {\n ...thread,\n messages: updateToolCall(thread, id, call => ({\n ...call,\n function: { ...call.function, arguments: call.function.arguments + (delta ?? '') }\n }))\n };\n}\n\n/** What the server sends for each event of a run: its run, its offset (from 1), and the event. */\nexport interface AgUiEnvelope {\n readonly runId: string;\n readonly offset: number;\n readonly event: AgUiEvent;\n}\n\n/** Options for {@link createAgUiAgent}. The message formats have defaults; see the guide. */\nexport interface AgUiAgentOptions<S, In, Out> {\n /** The thread's id, sent in every `RunAgentInput`. A new random one by default. */\n threadId?: string;\n /** The shared state before the first `STATE_SNAPSHOT`, sent with the first run. */\n state?: S;\n /** Names where streaming runs are remembered across reloads. @default 'ag-ui' */\n name?: string;\n /** @default `{ type: 'run', runId, input }` */\n run?: (input: RunAgentInput, runId: string) => Out;\n /** @default `{ type: 'resume', runId, after }` */\n resume?: (runId: string, after: number | undefined) => Out;\n /** @default `{ type: 'cancel', runId }` */\n cancel?: (runId: string) => Out;\n /**\n * The message that asks the server for a `STATE_SNAPSHOT`, sent when a `STATE_DELTA` can't\n * be applied. Without it, the state stays `stale` until the server sends one by itself.\n */\n resync?: (runId: string) => Out;\n /** Recognize a run's event. @default messages shaped like {@link AgUiEnvelope} */\n event?: (message: In) => AgUiEnvelope | null | undefined;\n /** What happens to a run when its connection drops. @default 'keep' */\n policy?: RunPolicy;\n /** Where streaming runs are remembered. @default sessionStorage */\n storage?: RunStorage | null;\n}\n\n/** An AG-UI agent over a WebSocket. Create with {@link createAgUiAgent}. */\nexport interface AgUiAgent<S> {\n /** The client the runs stream on. */\n readonly client: WebSocketClient<any, any>;\n /** The runs underneath, from `createWebSocketRuns`. */\n readonly runs: WebSocketRuns<RunAgentInput, AgUiThread<S>>;\n /**\n * Start a run with the thread so far plus `input.messages`, which show up in the thread right\n * away. A run that's still streaming is aborted first. Returns the run's id.\n */\n run(\n input?: {\n messages?: readonly AgUiMessage[];\n tools?: readonly unknown[];\n context?: readonly unknown[];\n forwardedProps?: unknown;\n },\n options?: { policy?: RunPolicy }\n ): string;\n /** Stop the run that's streaming, if any. */\n abort(): void;\n /**\n * Forget the thread, e.g. on logout or when another user signs in: its runs (with\n * `runs.clear()`, which sends nothing), messages and state. The next run starts over from\n * `state`, with a new thread id unless `threadId` was given. `abort()` a streaming run first\n * to stop it on the server.\n */\n reset(): void;\n /** The thread as of the latest run. The same object until it changes. */\n getSnapshot(): AgUiThread<S>;\n /** Get notified when the thread changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop following runs, and release the connection. */\n dispose(): void;\n}\n\nfunction randomId() {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\nconst isEnvelope = (message: any): AgUiEnvelope | undefined =>\n typeof message?.runId === 'string' &&\n typeof message.offset === 'number' &&\n typeof message.event?.type === 'string'\n ? message\n : undefined;\n\nconst ENDS = new Set(['RUN_FINISHED', 'RUN_ERROR']);\n\n/**\n * Run an [AG-UI](https://docs.ag-ui.com) agent over a WebSocket. Each run streams AG-UI events,\n * which are folded into the thread's messages and shared state with {@link applyAgUiEvent}.\n * Runs come from `createWebSocketRuns`, so they resume after a reconnect or a reload, and a\n * state delta that can't be applied asks for a snapshot (`resync`).\n *\n * AG-UI doesn't define messages for WebSockets, so the defaults are small: the client sends\n * `{ type: 'run', runId, input }`, `{ type: 'resume', runId, after }` and\n * `{ type: 'cancel', runId }`, and the server sends `{ runId, offset, event }`, with `offset`\n * counting each run's events from 1. Each option replaces one of them.\n *\n * @example\n * ```ts\n * import { createAgUiAgent } from 'react-websocket/ag-ui';\n *\n * export const agent = createAgUiAgent(createWebSocket(url, { json: true }));\n *\n * agent.run({ messages: [{ id: crypto.randomUUID(), role: 'user', content: 'Plan my week' }] });\n * ```\n */\nexport function createAgUiAgent<S = unknown, In = any, Out = any>(\n client: WebSocketClient<In, Out>,\n options: AgUiAgentOptions<S, NoInfer<In>, NoInfer<Out>> = {}\n): AgUiAgent<S> {\n let threadId = options.threadId ?? randomId();\n const empty: AgUiThread<S> = {\n messages: [],\n state: options.state as S,\n status: 'idle',\n stale: false\n };\n let base = empty;\n let snapshot = empty;\n const listeners = new Set<() => void>();\n // Runs that asked for a snapshot after a failed delta, until one arrives.\n const resynced = new Set<string>();\n const event = options.event ?? isEnvelope;\n // Now or never: not queued, and not `volatile`, which can be a datagram that never arrives.\n const send = (message: unknown) => client.socket?.readyState === 1 && client.send(message as Out);\n\n const runs = createWebSocketRuns<RunAgentInput, AgUiThread<S>, In, Out>(client, {\n name: options.name ?? 'ag-ui',\n start: options.run ?? ((input, runId) => ({ type: 'run', runId, input }) as Out),\n resume: options.resume ?? ((runId, after) => ({ type: 'resume', runId, after }) as Out),\n cancel: options.cancel ?? (runId => ({ type: 'cancel', runId }) as Out),\n event: message => event(message),\n done: message => ENDS.has(event(message)!.event.type),\n initial: empty,\n reduce: (thread, message) => applyAgUiEvent(thread, event(message)!.event),\n policy: options.policy,\n storage: options.storage\n });\n\n function update() {\n const latest = runs.list().at(-1);\n let next = latest ? latest.value : base;\n if (latest?.status === 'aborted' && next.status === 'running')\n next = { ...next, status: 'aborted' };\n // Once each time the state goes stale, or on a later event if the socket wasn't open.\n if (latest && !latest.value.stale) resynced.delete(latest.runId);\n else if (latest && options.resync && !resynced.has(latest.runId)) {\n if (send(options.resync(latest.runId))) resynced.add(latest.runId);\n }\n if (next === snapshot) return;\n snapshot = next;\n for (const listener of [...listeners]) listener();\n }\n const off = runs.subscribe(update);\n update();\n\n function abort() {\n for (const run of runs.list()) runs.abort(run.runId);\n }\n\n return {\n client,\n runs,\n run(input = {}, runOptions) {\n abort();\n const runId = randomId();\n // The run starts from the state sent with it, the last good one: its deltas apply to it.\n base = {\n ...snapshot,\n stale: false,\n messages: [...snapshot.messages, ...(input.messages ?? [])]\n };\n runs.start(\n {\n threadId,\n runId,\n state: base.state,\n messages: base.messages,\n tools: input.tools ?? [],\n context: input.context ?? [],\n forwardedProps: input.forwardedProps ?? {}\n },\n { runId, initial: { ...base, status: 'running' }, policy: runOptions?.policy }\n );\n return runId;\n },\n abort,\n reset() {\n // Before the runs go, whose change shows `base`.\n base = empty;\n resynced.clear();\n if (options.threadId === undefined) threadId = randomId();\n runs.clear();\n update();\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n off();\n runs.dispose();\n }\n };\n}\n"],"mappings":";;;AAmFA,SAAS,SAAS,OAAe;CAC/B,OAAO,MAAM,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG;AACrD;AAEA,SAAS,MAAM,GAAS,GAAkB;CACxC,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;CACvE,IAAI,MAAM,QAAQ,CAAC,MAAM,MAAM,QAAQ,CAAC,GAAG,OAAO;CAClD,MAAM,OAAO,OAAO,KAAK,CAAC;CAC1B,OAAO,KAAK,WAAW,OAAO,KAAK,CAAC,CAAC,CAAC,UAAU,KAAK,OAAM,QAAO,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC;AACzF;AAEA,SAAS,KAAK,WAAsC;CAClD,MAAM,IAAI,MAAM,sBAAsB,UAAU,GAAG,GAAG,UAAU,MAAM;AACxE;AAEA,MAAM,QAAQ;;AAGd,SAAS,OAAO,SAAiB,WAA+B;CAC9D,IAAI,YAAY,MAAM,QAAQ,OAAO,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S,CAAC;IACvB,SAAS,MAAM,WAAW,CAAC;IAC3B,gBAAgB,MAAM,kBAAkB,CAAC;GAC3C,GACA;IAAE;IAAO,SAAS;KAAE,GAAG;KAAM,QAAQ;IAAU;IAAG,QAAQ,YAAY;GAAO,CAC/E;GACA,OAAO;EACT;EACA;EACA,QAAQ;GAEN,OAAO;GACP,SAAS,MAAM;GACf,IAAI,QAAQ,aAAa,KAAA,GAAW,WAAW,SAAS;GACxD,KAAK,MAAM;GACX,OAAO;EACT;EACA,mBAAmB;EACnB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,IAAI;GACJ,KAAK,QAAQ;EACf;CACF;AACF"}
1
+ {"version":3,"file":"ag-ui.cjs","names":["createWebSocketRuns"],"sources":["../src/ag-ui.ts"],"sourcesContent":["// The build keeps `./core` external, so this entry shares the client with the others.\nimport {\n createWebSocketRuns,\n type RunPolicy,\n type RunStorage,\n type WebSocketClient,\n type WebSocketRuns\n} from './core';\n\n/** A JSON Patch (RFC 6902) operation, as in AG-UI's `STATE_DELTA` and `ACTIVITY_DELTA`. */\nexport interface JsonPatchOperation {\n readonly op: 'add' | 'remove' | 'replace' | 'move' | 'copy' | 'test';\n /** A JSON Pointer (RFC 6901), such as `/items/0/name`. */\n readonly path: string;\n /** The source of `move` and `copy`. */\n readonly from?: string;\n /** The value to `add`, `replace` with or `test` for. */\n readonly value?: unknown;\n}\n\n/** An AG-UI event: `type` is `'RUN_STARTED'`, `'TEXT_MESSAGE_CONTENT'`, `'STATE_DELTA'`, … */\nexport interface AgUiEvent {\n readonly type: string;\n readonly [field: string]: any;\n}\n\n/** A tool call on an assistant message, as in AG-UI. */\nexport interface AgUiToolCall {\n readonly id: string;\n readonly type: 'function';\n readonly function: { readonly name: string; readonly arguments: string };\n}\n\n/** A message in an AG-UI thread. */\nexport interface AgUiMessage {\n readonly id: string;\n readonly role: 'developer' | 'system' | 'assistant' | 'user' | 'tool' | 'reasoning' | 'activity';\n readonly content?: unknown;\n readonly toolCalls?: readonly AgUiToolCall[];\n /** For a `tool` message, the call it answers. */\n readonly toolCallId?: string;\n /** For an `activity` message. */\n readonly activityType?: string;\n readonly [field: string]: unknown;\n}\n\n/** AG-UI's `RunAgentInput`: what a run starts from. */\nexport interface RunAgentInput {\n readonly threadId: string;\n readonly runId: string;\n readonly parentRunId?: string;\n readonly state?: unknown;\n readonly messages: readonly AgUiMessage[];\n readonly tools: readonly unknown[];\n readonly context: readonly unknown[];\n readonly forwardedProps: unknown;\n}\n\n/** A thread's messages and shared state, reduced from AG-UI events. */\nexport interface AgUiThread<S = unknown> {\n readonly messages: readonly AgUiMessage[];\n /** The shared state, from `STATE_SNAPSHOT` and `STATE_DELTA`. */\n readonly state: S;\n /**\n * `'running'` from `RUN_STARTED`, `'finished'` after `RUN_FINISHED`, `'error'` after\n * `RUN_ERROR`, `'aborted'` when the run was stopped from this side.\n */\n readonly status: 'idle' | 'running' | 'finished' | 'error' | 'aborted';\n /** The step in progress, between `STEP_STARTED` and `STEP_FINISHED`. */\n readonly step?: string;\n /** From `RUN_ERROR`. */\n readonly error?: { readonly message: string; readonly code?: string };\n /** From `RUN_FINISHED`. */\n readonly result?: unknown;\n /**\n * A `STATE_DELTA` couldn't be applied. `state` is the last good one, and later deltas are\n * skipped until a `STATE_SNAPSHOT` arrives.\n */\n readonly stale: boolean;\n}\n\ntype Json = any;\n\nfunction unescape(token: string) {\n return token.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\nfunction equal(a: Json, b: Json): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n return keys.length === Object.keys(b).length && keys.every(key => equal(a[key], b[key]));\n}\n\nfunction fail(operation: JsonPatchOperation): never {\n throw new Error(`JSON Patch failed: ${operation.op} ${operation.path}`);\n}\n\nconst INDEX = /^(0|[1-9]\\d*)$/;\n\n/** A JSON Pointer's tokens. It's empty, for the whole document, or starts with `/`. */\nfunction tokens(pointer: string, operation: JsonPatchOperation) {\n if (pointer !== '' && pointer[0] !== '/') fail(operation);\n return pointer.split('/').slice(1).map(unescape);\n}\n\n/** Whether `node` has `token`: an index in range for an array, not `length`; an own key otherwise. */\nfunction has(node: Json, token: string) {\n return Array.isArray(node)\n ? INDEX.test(token) && +token < node.length\n : Object.hasOwn(node, token);\n}\n\n/** Set an own property, even `__proto__`, as JSON.parse would. */\nfunction put(object: Json, key: string, value: Json) {\n Object.defineProperty(object, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n}\n\n/**\n * Apply a JSON Patch (RFC 6902) without changing `document`: what changes is copied, the rest is\n * shared. Throws, leaving `document` as it was, if an operation can't be applied: a missing path,\n * an index out of range, a pointer that doesn't start with `/`, or a failed `test`.\n */\nexport function applyPatch<T>(document: T, operations: readonly JsonPatchOperation[]): T {\n let root: Json = document;\n\n function get(path: string, operation: JsonPatchOperation): Json {\n let node = root;\n for (const token of tokens(path, operation)) {\n if (typeof node !== 'object' || node === null || !has(node, token)) fail(operation);\n node = node[token];\n }\n return node;\n }\n\n // Replace the parent of `path` with a copy, change it with `change`, and copy its ancestors.\n function edit(\n path: string,\n operation: JsonPatchOperation,\n change: (parent: Json, key: string) => void\n ) {\n const keys = tokens(path, operation);\n if (!keys.length) fail(operation);\n const walk = (node: Json, depth: number): Json => {\n if (typeof node !== 'object' || node === null) fail(operation);\n const copy = Array.isArray(node) ? [...node] : { ...node };\n const key = keys[depth]!;\n if (depth === keys.length - 1) change(copy, key);\n else if (!has(node, key)) fail(operation);\n else copy[key] = walk(node[key], depth + 1);\n return copy;\n };\n root = walk(root, 0);\n }\n\n function index(parent: Json[], key: string, operation: JsonPatchOperation, adding: boolean) {\n // `-` is the end of the array, which only `add` can use.\n const i = key === '-' ? (adding ? parent.length : -1) : INDEX.test(key) ? +key : -1;\n if (i < 0 || i > parent.length - (adding ? 0 : 1)) fail(operation);\n return i;\n }\n\n function add(path: string, value: Json, operation: JsonPatchOperation) {\n if (path === '') return void (root = value);\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent.splice(index(parent, key, operation, true), 0, value);\n else put(parent, key, value);\n });\n }\n\n function remove(path: string, operation: JsonPatchOperation) {\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent.splice(index(parent, key, operation, false), 1);\n else if (Object.hasOwn(parent, key)) delete parent[key];\n else fail(operation);\n });\n }\n\n for (const operation of operations) {\n const { op, path, from, value } = operation;\n if (op === 'add') add(path, value, operation);\n else if (op === 'remove') remove(path, operation);\n else if (op === 'replace') {\n get(path, operation);\n if (path === '') root = value;\n else\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent[key as unknown as number] = value;\n else put(parent, key, value);\n });\n } else if (op === 'move' || op === 'copy') {\n const moved = get(from ?? fail(operation), operation);\n if (op === 'move') remove(from!, operation);\n add(path, op === 'copy' ? structuredClone(moved) : moved, operation);\n } else if (op === 'test') {\n if (!equal(get(path, operation), value)) fail(operation);\n } else fail(operation);\n }\n return root;\n}\n\nfunction updateMessage(\n thread: AgUiThread<any>,\n id: string | undefined,\n change: (message: AgUiMessage) => AgUiMessage\n) {\n return thread.messages.map(message => (message.id === id ? change(message) : message));\n}\n\nfunction appendText(message: AgUiMessage, delta: string | undefined) {\n return { ...message, content: `${(message.content as string | undefined) ?? ''}${delta ?? ''}` };\n}\n\nfunction updateToolCall(\n thread: AgUiThread<any>,\n id: string | undefined,\n change: (call: AgUiToolCall) => AgUiToolCall\n) {\n return thread.messages.map(message =>\n message.toolCalls?.some(call => call.id === id)\n ? {\n ...message,\n toolCalls: message.toolCalls.map(call => (call.id === id ? change(call) : call))\n }\n : message\n );\n}\n\n/** The last message with a tool call, for chunks that leave out `toolCallId`. */\nfunction lastToolCallId(thread: AgUiThread<any>) {\n for (let i = thread.messages.length - 1; i >= 0; i--) {\n const calls = thread.messages[i]!.toolCalls;\n if (calls?.length) return calls.at(-1)!.id;\n }\n}\n\n/**\n * Fold one AG-UI event into a thread, without changing it. Handles the run lifecycle, steps,\n * text, tool calls and their results, reasoning, activity, and message and state snapshots and\n * deltas. A `STATE_DELTA` that can't be applied marks the thread `stale` instead of throwing.\n * Other events, such as `CUSTOM` and `RAW`, return the thread unchanged.\n *\n * Use it as a `reduce` function, or wrap it to handle events of your own.\n */\nexport function applyAgUiEvent<S>(thread: AgUiThread<S>, event: AgUiEvent): AgUiThread<S> {\n const e = event;\n const message = (role: AgUiMessage['role'], extra?: object): AgUiThread<S> => ({\n ...thread,\n messages: [...thread.messages, { id: e.messageId, role, content: '', ...extra }]\n });\n const known = (id: string | undefined) => thread.messages.some(m => m.id === id);\n switch (e.type) {\n case 'RUN_STARTED':\n return { ...thread, status: 'running', step: undefined, error: undefined, result: undefined };\n case 'RUN_FINISHED':\n return { ...thread, status: 'finished', step: undefined, result: e.result };\n case 'RUN_ERROR':\n return {\n ...thread,\n status: 'error',\n step: undefined,\n error: { message: e.message, code: e.code }\n };\n case 'STEP_STARTED':\n return { ...thread, step: e.stepName };\n case 'STEP_FINISHED':\n return { ...thread, step: undefined };\n case 'TEXT_MESSAGE_START':\n return message(e.role ?? 'assistant');\n case 'REASONING_MESSAGE_START':\n return message('reasoning');\n case 'TEXT_MESSAGE_CONTENT':\n case 'REASONING_MESSAGE_CONTENT':\n return {\n ...thread,\n messages: updateMessage(thread, e.messageId, m => appendText(m, e.delta))\n };\n case 'TEXT_MESSAGE_CHUNK':\n case 'REASONING_MESSAGE_CHUNK': {\n // Only the first chunk of a message must carry its id. Activity events can come between\n // chunks without ending the message.\n const id = e.messageId ?? thread.messages.filter(m => m.role !== 'activity').at(-1)?.id;\n const role = e.type === 'TEXT_MESSAGE_CHUNK' ? (e.role ?? 'assistant') : 'reasoning';\n const next = known(id) ? thread : message(role);\n return { ...next, messages: updateMessage(next, id, m => appendText(m, e.delta)) };\n }\n case 'TOOL_CALL_START':\n case 'TOOL_CALL_CHUNK': {\n const id = e.toolCallId ?? lastToolCallId(thread);\n let next = thread;\n if (\n e.type === 'TOOL_CALL_START' ||\n !thread.messages.some(m => m.toolCalls?.some(c => c.id === id))\n ) {\n const call: AgUiToolCall = {\n id,\n type: 'function',\n function: { name: e.toolCallName, arguments: '' }\n };\n const parent = e.parentMessageId ?? id;\n next = known(parent)\n ? thread\n : { ...thread, messages: [...thread.messages, { id: parent, role: 'assistant' }] };\n next = {\n ...next,\n messages: updateMessage(next, parent, m => ({\n ...m,\n toolCalls: [...(m.toolCalls ?? []), call]\n }))\n };\n }\n if (e.type === 'TOOL_CALL_START') return next;\n return toolArgs(next, id, e.delta);\n }\n case 'TOOL_CALL_ARGS':\n return toolArgs(thread, e.toolCallId, e.delta);\n case 'TOOL_CALL_RESULT':\n return message(e.role ?? 'tool', { toolCallId: e.toolCallId, content: e.content });\n case 'STATE_SNAPSHOT':\n return { ...thread, state: e.snapshot, stale: false };\n case 'STATE_DELTA':\n if (thread.stale) return thread;\n try {\n return { ...thread, state: applyPatch(thread.state, e.delta) };\n } catch {\n return { ...thread, stale: true };\n }\n case 'MESSAGES_SNAPSHOT':\n return { ...thread, messages: e.messages };\n case 'ACTIVITY_SNAPSHOT': {\n if (known(e.messageId) && e.replace === false) return thread;\n const next = known(e.messageId) ? thread : message('activity');\n return {\n ...next,\n messages: updateMessage(next, e.messageId, m => ({\n ...m,\n activityType: e.activityType,\n content: e.content\n }))\n };\n }\n case 'ACTIVITY_DELTA':\n try {\n return {\n ...thread,\n messages: updateMessage(thread, e.messageId, m => ({\n ...m,\n content: applyPatch(m.content, e.patch)\n }))\n };\n } catch {\n return thread;\n }\n default:\n return thread;\n }\n}\n\nfunction toolArgs<S>(thread: AgUiThread<S>, id: string | undefined, delta: string | undefined) {\n return {\n ...thread,\n messages: updateToolCall(thread, id, call => ({\n ...call,\n function: { ...call.function, arguments: call.function.arguments + (delta ?? '') }\n }))\n };\n}\n\n/** What the server sends for each event of a run: its run, its offset (from 1), and the event. */\nexport interface AgUiEnvelope {\n readonly runId: string;\n readonly offset: number;\n readonly event: AgUiEvent;\n}\n\n/** Options for {@link createAgUiAgent}. The message formats have defaults; see the guide. */\nexport interface AgUiAgentOptions<S, In, Out> {\n /** The thread's id, sent in every `RunAgentInput`. A new random one by default. */\n threadId?: string;\n /** The shared state before the first `STATE_SNAPSHOT`, sent with the first run. */\n state?: S;\n /** Names where streaming runs are remembered across reloads. @default 'ag-ui' */\n name?: string;\n /** @default `{ type: 'run', runId, input }` */\n run?: (input: RunAgentInput, runId: string) => Out;\n /** @default `{ type: 'resume', runId, after }` */\n resume?: (runId: string, after: number | undefined) => Out;\n /** @default `{ type: 'cancel', runId }` */\n cancel?: (runId: string) => Out;\n /**\n * The message that asks the server for a `STATE_SNAPSHOT`, sent when a `STATE_DELTA` can't\n * be applied. Without it, the state stays `stale` until the server sends one by itself.\n */\n resync?: (runId: string) => Out;\n /** Recognize a run's event. @default messages shaped like {@link AgUiEnvelope} */\n event?: (message: In) => AgUiEnvelope | null | undefined;\n /** What happens to a run when its connection drops. @default 'keep' */\n policy?: RunPolicy;\n /** Where streaming runs are remembered. @default sessionStorage */\n storage?: RunStorage | null;\n}\n\n/** An AG-UI agent over a WebSocket. Create with {@link createAgUiAgent}. */\nexport interface AgUiAgent<S> {\n /** The client the runs stream on. */\n readonly client: WebSocketClient<any, any>;\n /** The runs underneath, from `createWebSocketRuns`. */\n readonly runs: WebSocketRuns<RunAgentInput, AgUiThread<S>>;\n /**\n * Start a run with the thread so far plus `input.messages`, which show up in the thread right\n * away. A run that's still streaming is aborted first. Returns the run's id.\n */\n run(\n input?: {\n messages?: readonly AgUiMessage[];\n tools?: readonly unknown[];\n context?: readonly unknown[];\n forwardedProps?: unknown;\n },\n options?: { policy?: RunPolicy }\n ): string;\n /** Stop the run that's streaming, if any. */\n abort(): void;\n /**\n * Forget the thread, e.g. on logout or when another user signs in: its runs (with\n * `runs.clear()`, which sends nothing), messages and state. The next run starts over from\n * `state`, with a new thread id unless `threadId` was given. `abort()` a streaming run first\n * to stop it on the server.\n */\n reset(): void;\n /** The thread as of the latest run. The same object until it changes. */\n getSnapshot(): AgUiThread<S>;\n /** Get notified when the thread changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop following runs, and release the connection. */\n dispose(): void;\n}\n\nfunction randomId() {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\nconst isEnvelope = (message: any): AgUiEnvelope | undefined =>\n typeof message?.runId === 'string' &&\n typeof message.offset === 'number' &&\n typeof message.event?.type === 'string'\n ? message\n : undefined;\n\nconst ENDS = new Set(['RUN_FINISHED', 'RUN_ERROR']);\n\n/**\n * Run an [AG-UI](https://docs.ag-ui.com) agent over a WebSocket. Each run streams AG-UI events,\n * which are folded into the thread's messages and shared state with {@link applyAgUiEvent}.\n * Runs come from `createWebSocketRuns`, so they resume after a reconnect or a reload, and a\n * state delta that can't be applied asks for a snapshot (`resync`).\n *\n * AG-UI doesn't define messages for WebSockets, so the defaults are small: the client sends\n * `{ type: 'run', runId, input }`, `{ type: 'resume', runId, after }` and\n * `{ type: 'cancel', runId }`, and the server sends `{ runId, offset, event }`, with `offset`\n * counting each run's events from 1. Each option replaces one of them.\n *\n * @example\n * ```ts\n * import { createAgUiAgent } from 'react-websocket/ag-ui';\n *\n * export const agent = createAgUiAgent(createWebSocket(url, { json: true }));\n *\n * agent.run({ messages: [{ id: crypto.randomUUID(), role: 'user', content: 'Plan my week' }] });\n * ```\n */\nexport function createAgUiAgent<S = unknown, In = any, Out = any>(\n client: WebSocketClient<In, Out>,\n options: AgUiAgentOptions<S, NoInfer<In>, NoInfer<Out>> = {}\n): AgUiAgent<S> {\n let threadId = options.threadId ?? randomId();\n const empty: AgUiThread<S> = {\n messages: [],\n state: options.state as S,\n status: 'idle',\n stale: false\n };\n let base = empty;\n let snapshot = empty;\n const listeners = new Set<() => void>();\n // Runs that asked for a snapshot after a failed delta, until one arrives.\n const resynced = new Set<string>();\n const event = options.event ?? isEnvelope;\n // Now or never: not queued, and not `volatile`, which can be a datagram that never arrives.\n const send = (message: unknown) => client.socket?.readyState === 1 && client.send(message as Out);\n // Running, without the step, error or result the thread had before.\n const started = (thread: AgUiThread<S>) => applyAgUiEvent(thread, { type: 'RUN_STARTED' });\n\n const runs = createWebSocketRuns<RunAgentInput, AgUiThread<S>, In, Out>(client, {\n name: options.name ?? 'ag-ui',\n start: options.run ?? ((input, runId) => ({ type: 'run', runId, input }) as Out),\n resume: options.resume ?? ((runId, after) => ({ type: 'resume', runId, after }) as Out),\n cancel: options.cancel ?? (runId => ({ type: 'cancel', runId }) as Out),\n event: message => event(message),\n done: message => ENDS.has(event(message)!.event.type),\n // A run followed again after a reload streams before its events replay.\n initial: started(empty),\n reduce: (thread, message) => applyAgUiEvent(thread, event(message)!.event),\n policy: options.policy,\n storage: options.storage\n });\n\n function update() {\n const latest = runs.list().at(-1);\n let next = latest ? latest.value : base;\n if (latest?.status === 'aborted' && next.status === 'running')\n next = { ...next, status: 'aborted', step: undefined };\n // Once each time the state goes stale, or on a later event if the socket wasn't open.\n if (latest && !latest.value.stale) resynced.delete(latest.runId);\n else if (latest && options.resync && !resynced.has(latest.runId)) {\n if (send(options.resync(latest.runId))) resynced.add(latest.runId);\n }\n if (next === snapshot) return;\n snapshot = next;\n for (const listener of [...listeners]) listener();\n }\n const off = runs.subscribe(update);\n update();\n\n function abort() {\n for (const run of runs.list()) runs.abort(run.runId);\n }\n\n return {\n client,\n runs,\n run(input = {}, runOptions) {\n abort();\n const runId = randomId();\n // The run starts from the state sent with it, the last good one: its deltas apply to it.\n base = {\n ...snapshot,\n stale: false,\n messages: [...snapshot.messages, ...(input.messages ?? [])]\n };\n runs.start(\n {\n threadId,\n runId,\n state: base.state,\n messages: base.messages,\n tools: input.tools ?? [],\n context: input.context ?? [],\n forwardedProps: input.forwardedProps ?? {}\n },\n { runId, initial: started(base), policy: runOptions?.policy }\n );\n return runId;\n },\n abort,\n reset() {\n // Before the runs go, whose change shows `base`.\n base = empty;\n resynced.clear();\n if (options.threadId === undefined) threadId = randomId();\n runs.clear();\n update();\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n off();\n runs.dispose();\n }\n };\n}\n"],"mappings":";;;AAmFA,SAAS,SAAS,OAAe;CAC/B,OAAO,MAAM,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG;AACrD;AAEA,SAAS,MAAM,GAAS,GAAkB;CACxC,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;CACvE,IAAI,MAAM,QAAQ,CAAC,MAAM,MAAM,QAAQ,CAAC,GAAG,OAAO;CAClD,MAAM,OAAO,OAAO,KAAK,CAAC;CAC1B,OAAO,KAAK,WAAW,OAAO,KAAK,CAAC,CAAC,CAAC,UAAU,KAAK,OAAM,QAAO,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC;AACzF;AAEA,SAAS,KAAK,WAAsC;CAClD,MAAM,IAAI,MAAM,sBAAsB,UAAU,GAAG,GAAG,UAAU,MAAM;AACxE;AAEA,MAAM,QAAQ;;AAGd,SAAS,OAAO,SAAiB,WAA+B;CAC9D,IAAI,YAAY,MAAM,QAAQ,OAAO,KAAK,KAAK,SAAS;CACxD,OAAO,QAAQ,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,QAAQ;AACjD;;AAGA,SAAS,IAAI,MAAY,OAAe;CACtC,OAAO,MAAM,QAAQ,IAAI,IACrB,MAAM,KAAK,KAAK,KAAK,CAAC,QAAQ,KAAK,SACnC,OAAO,OAAO,MAAM,KAAK;AAC/B;;AAGA,SAAS,IAAI,QAAc,KAAa,OAAa;CACnD,OAAO,eAAe,QAAQ,KAAK;EACjC;EACA,UAAU;E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GAEN,OAAO;GACP,SAAS,MAAM;GACf,IAAI,QAAQ,aAAa,KAAA,GAAW,WAAW,SAAS;GACxD,KAAK,MAAM;GACX,OAAO;EACT;EACA,mBAAmB;EACnB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,IAAI;GACJ,KAAK,QAAQ;EACf;CACF;AACF"}
package/dist/ag-ui.d.cts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/types.d.ts
2
1
  /**
3
2
  * Where to connect: a URL, or a function that returns one (sync or async).
4
3
  *
@@ -235,8 +234,9 @@ interface WebSocketClient<In = unknown, Out = unknown> {
235
234
  close(code?: number, reason?: string): void;
236
235
  /**
237
236
  * Drop the current socket (if any) and connect again immediately, resetting the
238
- * backoff. Also restarts a `closed` client. The send queue and a `migrate()` target are
239
- * kept: when another user signs in, call `close()` and then `connect()` instead.
237
+ * backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
238
+ * again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
239
+ * are kept: when another user signs in, call `close()` and then `connect()` instead.
240
240
  */
241
241
  reconnect(): void;
242
242
  /**
@@ -268,8 +268,6 @@ interface WebSocketClient<In = unknown, Out = unknown> {
268
268
  */
269
269
  acquire(): () => void;
270
270
  }
271
- //#endregion
272
- //#region src/runs.d.ts
273
271
  /**
274
272
  * What happens to a run when its connection drops: `keep` resumes it on the next connection,
275
273
  * for agents that keep working in the background; `cancel` aborts it and tells the server, for
@@ -332,8 +330,6 @@ interface WebSocketRuns<Req, T> {
332
330
  /** Stop following runs, and release the connection. Remembered runs stay remembered. */
333
331
  dispose(): void;
334
332
  }
335
- //#endregion
336
- //#region src/ag-ui.d.ts
337
333
  /** A JSON Patch (RFC 6902) operation, as in AG-UI's `STATE_DELTA` and `ACTIVITY_DELTA`. */
338
334
  export interface JsonPatchOperation {
339
335
  readonly op: 'add' | 'remove' | 'replace' | 'move' | 'copy' | 'test';
@@ -508,6 +504,5 @@ export interface AgUiAgent<S> {
508
504
  * ```
509
505
  */
510
506
  export declare function createAgUiAgent<S = unknown, In = any, Out = any>(client: WebSocketClient<In, Out>, options?: AgUiAgentOptions<S, NoInfer<In>, NoInfer<Out>>): AgUiAgent<S>;
511
- //#endregion
512
507
  export {};
513
508
  //# sourceMappingURL=ag-ui.d.cts.map
package/dist/ag-ui.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { RunPolicy, RunStorage, WebSocketClient, WebSocketRuns } from "./core.js";
2
- //#region src/ag-ui.d.ts
3
2
  /** A JSON Patch (RFC 6902) operation, as in AG-UI's `STATE_DELTA` and `ACTIVITY_DELTA`. */
4
3
  export interface JsonPatchOperation {
5
4
  readonly op: 'add' | 'remove' | 'replace' | 'move' | 'copy' | 'test';
@@ -174,5 +173,4 @@ export interface AgUiAgent<S> {
174
173
  * ```
175
174
  */
176
175
  export declare function createAgUiAgent<S = unknown, In = any, Out = any>(client: WebSocketClient<In, Out>, options?: AgUiAgentOptions<S, NoInfer<In>, NoInfer<Out>>): AgUiAgent<S>;
177
- //#endregion
178
176
  //# sourceMappingURL=ag-ui.d.ts.map
package/dist/ag-ui.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createWebSocketRuns } from "./core.js";
2
- //#region src/ag-ui.ts
2
+ // src/ag-ui.ts
3
3
  function unescape(token) {
4
4
  return token.replace(/~1/g, "/").replace(/~0/g, "~");
5
5
  }
@@ -147,6 +147,7 @@ function applyAgUiEvent(thread, event) {
147
147
  case "RUN_STARTED": return {
148
148
  ...thread,
149
149
  status: "running",
150
+ step: void 0,
150
151
  error: void 0,
151
152
  result: void 0
152
153
  };
@@ -182,7 +183,7 @@ function applyAgUiEvent(thread, event) {
182
183
  };
183
184
  case "TEXT_MESSAGE_CHUNK":
184
185
  case "REASONING_MESSAGE_CHUNK": {
185
- const id = e.messageId ?? thread.messages.at(-1)?.id;
186
+ const id = e.messageId ?? thread.messages.filter((m) => m.role !== "activity").at(-1)?.id;
186
187
  const role = e.type === "TEXT_MESSAGE_CHUNK" ? e.role ?? "assistant" : "reasoning";
187
188
  const next = known(id) ? thread : message(role);
188
189
  return {
@@ -326,6 +327,7 @@ function createAgUiAgent(client, options = {}) {
326
327
  const resynced = /* @__PURE__ */ new Set();
327
328
  const event = options.event ?? isEnvelope;
328
329
  const send = (message) => client.socket?.readyState === 1 && client.send(message);
330
+ const started = (thread) => applyAgUiEvent(thread, { type: "RUN_STARTED" });
329
331
  const runs = createWebSocketRuns(client, {
330
332
  name: options.name ?? "ag-ui",
331
333
  start: options.run ?? ((input, runId) => ({
@@ -344,7 +346,7 @@ function createAgUiAgent(client, options = {}) {
344
346
  })),
345
347
  event: (message) => event(message),
346
348
  done: (message) => ENDS.has(event(message).event.type),
347
- initial: empty,
349
+ initial: started(empty),
348
350
  reduce: (thread, message) => applyAgUiEvent(thread, event(message).event),
349
351
  policy: options.policy,
350
352
  storage: options.storage
@@ -354,7 +356,8 @@ function createAgUiAgent(client, options = {}) {
354
356
  let next = latest ? latest.value : base;
355
357
  if (latest?.status === "aborted" && next.status === "running") next = {
356
358
  ...next,
357
- status: "aborted"
359
+ status: "aborted",
360
+ step: void 0
358
361
  };
359
362
  if (latest && !latest.value.stale) resynced.delete(latest.runId);
360
363
  else if (latest && options.resync && !resynced.has(latest.runId)) {
@@ -390,10 +393,7 @@ function createAgUiAgent(client, options = {}) {
390
393
  forwardedProps: input.forwardedProps ?? {}
391
394
  }, {
392
395
  runId,
393
- initial: {
394
- ...base,
395
- status: "running"
396
- },
396
+ initial: started(base),
397
397
  policy: runOptions?.policy
398
398
  });
399
399
  return runId;
@@ -419,7 +419,6 @@ function createAgUiAgent(client, options = {}) {
419
419
  }
420
420
  };
421
421
  }
422
- //#endregion
423
422
  export { applyAgUiEvent, applyPatch, createAgUiAgent };
424
423
 
425
424
  //# sourceMappingURL=ag-ui.js.map
package/dist/ag-ui.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ag-ui.js","names":[],"sources":["../src/ag-ui.ts"],"sourcesContent":["// The build keeps `./core` external, so this entry shares the client with the others.\nimport {\n createWebSocketRuns,\n type RunPolicy,\n type RunStorage,\n type WebSocketClient,\n type WebSocketRuns\n} from './core';\n\n/** A JSON Patch (RFC 6902) operation, as in AG-UI's `STATE_DELTA` and `ACTIVITY_DELTA`. */\nexport interface JsonPatchOperation {\n readonly op: 'add' | 'remove' | 'replace' | 'move' | 'copy' | 'test';\n /** A JSON Pointer (RFC 6901), such as `/items/0/name`. */\n readonly path: string;\n /** The source of `move` and `copy`. */\n readonly from?: string;\n /** The value to `add`, `replace` with or `test` for. */\n readonly value?: unknown;\n}\n\n/** An AG-UI event: `type` is `'RUN_STARTED'`, `'TEXT_MESSAGE_CONTENT'`, `'STATE_DELTA'`, … */\nexport interface AgUiEvent {\n readonly type: string;\n readonly [field: string]: any;\n}\n\n/** A tool call on an assistant message, as in AG-UI. */\nexport interface AgUiToolCall {\n readonly id: string;\n readonly type: 'function';\n readonly function: { readonly name: string; readonly arguments: string };\n}\n\n/** A message in an AG-UI thread. */\nexport interface AgUiMessage {\n readonly id: string;\n readonly role: 'developer' | 'system' | 'assistant' | 'user' | 'tool' | 'reasoning' | 'activity';\n readonly content?: unknown;\n readonly toolCalls?: readonly AgUiToolCall[];\n /** For a `tool` message, the call it answers. */\n readonly toolCallId?: string;\n /** For an `activity` message. */\n readonly activityType?: string;\n readonly [field: string]: unknown;\n}\n\n/** AG-UI's `RunAgentInput`: what a run starts from. */\nexport interface RunAgentInput {\n readonly threadId: string;\n readonly runId: string;\n readonly parentRunId?: string;\n readonly state?: unknown;\n readonly messages: readonly AgUiMessage[];\n readonly tools: readonly unknown[];\n readonly context: readonly unknown[];\n readonly forwardedProps: unknown;\n}\n\n/** A thread's messages and shared state, reduced from AG-UI events. */\nexport interface AgUiThread<S = unknown> {\n readonly messages: readonly AgUiMessage[];\n /** The shared state, from `STATE_SNAPSHOT` and `STATE_DELTA`. */\n readonly state: S;\n /**\n * `'running'` from `RUN_STARTED`, `'finished'` after `RUN_FINISHED`, `'error'` after\n * `RUN_ERROR`, `'aborted'` when the run was stopped from this side.\n */\n readonly status: 'idle' | 'running' | 'finished' | 'error' | 'aborted';\n /** The step in progress, between `STEP_STARTED` and `STEP_FINISHED`. */\n readonly step?: string;\n /** From `RUN_ERROR`. */\n readonly error?: { readonly message: string; readonly code?: string };\n /** From `RUN_FINISHED`. */\n readonly result?: unknown;\n /**\n * A `STATE_DELTA` couldn't be applied. `state` is the last good one, and later deltas are\n * skipped until a `STATE_SNAPSHOT` arrives.\n */\n readonly stale: boolean;\n}\n\ntype Json = any;\n\nfunction unescape(token: string) {\n return token.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\nfunction equal(a: Json, b: Json): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n return keys.length === Object.keys(b).length && keys.every(key => equal(a[key], b[key]));\n}\n\nfunction fail(operation: JsonPatchOperation): never {\n throw new Error(`JSON Patch failed: ${operation.op} ${operation.path}`);\n}\n\nconst INDEX = /^(0|[1-9]\\d*)$/;\n\n/** A JSON Pointer's tokens. It's empty, for the whole document, or starts with `/`. */\nfunction tokens(pointer: string, operation: JsonPatchOperation) {\n if (pointer !== '' && pointer[0] !== '/') fail(operation);\n return pointer.split('/').slice(1).map(unescape);\n}\n\n/** Whether `node` has `token`: an index in range for an array, not `length`; an own key otherwise. */\nfunction has(node: Json, token: string) {\n return Array.isArray(node)\n ? INDEX.test(token) && +token < node.length\n : Object.hasOwn(node, token);\n}\n\n/** Set an own property, even `__proto__`, as JSON.parse would. */\nfunction put(object: Json, key: string, value: Json) {\n Object.defineProperty(object, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n}\n\n/**\n * Apply a JSON Patch (RFC 6902) without changing `document`: what changes is copied, the rest is\n * shared. Throws, leaving `document` as it was, if an operation can't be applied: a missing path,\n * an index out of range, a pointer that doesn't start with `/`, or a failed `test`.\n */\nexport function applyPatch<T>(document: T, operations: readonly JsonPatchOperation[]): T {\n let root: Json = document;\n\n function get(path: string, operation: JsonPatchOperation): Json {\n let node = root;\n for (const token of tokens(path, operation)) {\n if (typeof node !== 'object' || node === null || !has(node, token)) fail(operation);\n node = node[token];\n }\n return node;\n }\n\n // Replace the parent of `path` with a copy, change it with `change`, and copy its ancestors.\n function edit(\n path: string,\n operation: JsonPatchOperation,\n change: (parent: Json, key: string) => void\n ) {\n const keys = tokens(path, operation);\n if (!keys.length) fail(operation);\n const walk = (node: Json, depth: number): Json => {\n if (typeof node !== 'object' || node === null) fail(operation);\n const copy = Array.isArray(node) ? [...node] : { ...node };\n const key = keys[depth]!;\n if (depth === keys.length - 1) change(copy, key);\n else if (!has(node, key)) fail(operation);\n else copy[key] = walk(node[key], depth + 1);\n return copy;\n };\n root = walk(root, 0);\n }\n\n function index(parent: Json[], key: string, operation: JsonPatchOperation, adding: boolean) {\n // `-` is the end of the array, which only `add` can use.\n const i = key === '-' ? (adding ? parent.length : -1) : INDEX.test(key) ? +key : -1;\n if (i < 0 || i > parent.length - (adding ? 0 : 1)) fail(operation);\n return i;\n }\n\n function add(path: string, value: Json, operation: JsonPatchOperation) {\n if (path === '') return void (root = value);\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent.splice(index(parent, key, operation, true), 0, value);\n else put(parent, key, value);\n });\n }\n\n function remove(path: string, operation: JsonPatchOperation) {\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent.splice(index(parent, key, operation, false), 1);\n else if (Object.hasOwn(parent, key)) delete parent[key];\n else fail(operation);\n });\n }\n\n for (const operation of operations) {\n const { op, path, from, value } = operation;\n if (op === 'add') add(path, value, operation);\n else if (op === 'remove') remove(path, operation);\n else if (op === 'replace') {\n get(path, operation);\n if (path === '') root = value;\n else\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent[key as unknown as number] = value;\n else put(parent, key, value);\n });\n } else if (op === 'move' || op === 'copy') {\n const moved = get(from ?? fail(operation), operation);\n if (op === 'move') remove(from!, operation);\n add(path, op === 'copy' ? structuredClone(moved) : moved, operation);\n } else if (op === 'test') {\n if (!equal(get(path, operation), value)) fail(operation);\n } else fail(operation);\n }\n return root;\n}\n\nfunction updateMessage(\n thread: AgUiThread<any>,\n id: string | undefined,\n change: (message: AgUiMessage) => AgUiMessage\n) {\n return thread.messages.map(message => (message.id === id ? change(message) : message));\n}\n\nfunction appendText(message: AgUiMessage, delta: string | undefined) {\n return { ...message, content: `${(message.content as string | undefined) ?? ''}${delta ?? ''}` };\n}\n\nfunction updateToolCall(\n thread: AgUiThread<any>,\n id: string | undefined,\n change: (call: AgUiToolCall) => AgUiToolCall\n) {\n return thread.messages.map(message =>\n message.toolCalls?.some(call => call.id === id)\n ? {\n ...message,\n toolCalls: message.toolCalls.map(call => (call.id === id ? change(call) : call))\n }\n : message\n );\n}\n\n/** The last message with a tool call, for chunks that leave out `toolCallId`. */\nfunction lastToolCallId(thread: AgUiThread<any>) {\n for (let i = thread.messages.length - 1; i >= 0; i--) {\n const calls = thread.messages[i]!.toolCalls;\n if (calls?.length) return calls.at(-1)!.id;\n }\n}\n\n/**\n * Fold one AG-UI event into a thread, without changing it. Handles the run lifecycle, steps,\n * text, tool calls and their results, reasoning, activity, and message and state snapshots and\n * deltas. A `STATE_DELTA` that can't be applied marks the thread `stale` instead of throwing.\n * Other events, such as `CUSTOM` and `RAW`, return the thread unchanged.\n *\n * Use it as a `reduce` function, or wrap it to handle events of your own.\n */\nexport function applyAgUiEvent<S>(thread: AgUiThread<S>, event: AgUiEvent): AgUiThread<S> {\n const e = event;\n const message = (role: AgUiMessage['role'], extra?: object): AgUiThread<S> => ({\n ...thread,\n messages: [...thread.messages, { id: e.messageId, role, content: '', ...extra }]\n });\n const known = (id: string | undefined) => thread.messages.some(m => m.id === id);\n switch (e.type) {\n case 'RUN_STARTED':\n return { ...thread, status: 'running', error: undefined, result: undefined };\n case 'RUN_FINISHED':\n return { ...thread, status: 'finished', step: undefined, result: e.result };\n case 'RUN_ERROR':\n return {\n ...thread,\n status: 'error',\n step: undefined,\n error: { message: e.message, code: e.code }\n };\n case 'STEP_STARTED':\n return { ...thread, step: e.stepName };\n case 'STEP_FINISHED':\n return { ...thread, step: undefined };\n case 'TEXT_MESSAGE_START':\n return message(e.role ?? 'assistant');\n case 'REASONING_MESSAGE_START':\n return message('reasoning');\n case 'TEXT_MESSAGE_CONTENT':\n case 'REASONING_MESSAGE_CONTENT':\n return {\n ...thread,\n messages: updateMessage(thread, e.messageId, m => appendText(m, e.delta))\n };\n case 'TEXT_MESSAGE_CHUNK':\n case 'REASONING_MESSAGE_CHUNK': {\n // Only the first chunk of a message must carry its id.\n const id = e.messageId ?? thread.messages.at(-1)?.id;\n const role = e.type === 'TEXT_MESSAGE_CHUNK' ? (e.role ?? 'assistant') : 'reasoning';\n const next = known(id) ? thread : message(role);\n return { ...next, messages: updateMessage(next, id, m => appendText(m, e.delta)) };\n }\n case 'TOOL_CALL_START':\n case 'TOOL_CALL_CHUNK': {\n const id = e.toolCallId ?? lastToolCallId(thread);\n let next = thread;\n if (\n e.type === 'TOOL_CALL_START' ||\n !thread.messages.some(m => m.toolCalls?.some(c => c.id === id))\n ) {\n const call: AgUiToolCall = {\n id,\n type: 'function',\n function: { name: e.toolCallName, arguments: '' }\n };\n const parent = e.parentMessageId ?? id;\n next = known(parent)\n ? thread\n : { ...thread, messages: [...thread.messages, { id: parent, role: 'assistant' }] };\n next = {\n ...next,\n messages: updateMessage(next, parent, m => ({\n ...m,\n toolCalls: [...(m.toolCalls ?? []), call]\n }))\n };\n }\n if (e.type === 'TOOL_CALL_START') return next;\n return toolArgs(next, id, e.delta);\n }\n case 'TOOL_CALL_ARGS':\n return toolArgs(thread, e.toolCallId, e.delta);\n case 'TOOL_CALL_RESULT':\n return message(e.role ?? 'tool', { toolCallId: e.toolCallId, content: e.content });\n case 'STATE_SNAPSHOT':\n return { ...thread, state: e.snapshot, stale: false };\n case 'STATE_DELTA':\n if (thread.stale) return thread;\n try {\n return { ...thread, state: applyPatch(thread.state, e.delta) };\n } catch {\n return { ...thread, stale: true };\n }\n case 'MESSAGES_SNAPSHOT':\n return { ...thread, messages: e.messages };\n case 'ACTIVITY_SNAPSHOT': {\n if (known(e.messageId) && e.replace === false) return thread;\n const next = known(e.messageId) ? thread : message('activity');\n return {\n ...next,\n messages: updateMessage(next, e.messageId, m => ({\n ...m,\n activityType: e.activityType,\n content: e.content\n }))\n };\n }\n case 'ACTIVITY_DELTA':\n try {\n return {\n ...thread,\n messages: updateMessage(thread, e.messageId, m => ({\n ...m,\n content: applyPatch(m.content, e.patch)\n }))\n };\n } catch {\n return thread;\n }\n default:\n return thread;\n }\n}\n\nfunction toolArgs<S>(thread: AgUiThread<S>, id: string | undefined, delta: string | undefined) {\n return {\n ...thread,\n messages: updateToolCall(thread, id, call => ({\n ...call,\n function: { ...call.function, arguments: call.function.arguments + (delta ?? '') }\n }))\n };\n}\n\n/** What the server sends for each event of a run: its run, its offset (from 1), and the event. */\nexport interface AgUiEnvelope {\n readonly runId: string;\n readonly offset: number;\n readonly event: AgUiEvent;\n}\n\n/** Options for {@link createAgUiAgent}. The message formats have defaults; see the guide. */\nexport interface AgUiAgentOptions<S, In, Out> {\n /** The thread's id, sent in every `RunAgentInput`. A new random one by default. */\n threadId?: string;\n /** The shared state before the first `STATE_SNAPSHOT`, sent with the first run. */\n state?: S;\n /** Names where streaming runs are remembered across reloads. @default 'ag-ui' */\n name?: string;\n /** @default `{ type: 'run', runId, input }` */\n run?: (input: RunAgentInput, runId: string) => Out;\n /** @default `{ type: 'resume', runId, after }` */\n resume?: (runId: string, after: number | undefined) => Out;\n /** @default `{ type: 'cancel', runId }` */\n cancel?: (runId: string) => Out;\n /**\n * The message that asks the server for a `STATE_SNAPSHOT`, sent when a `STATE_DELTA` can't\n * be applied. Without it, the state stays `stale` until the server sends one by itself.\n */\n resync?: (runId: string) => Out;\n /** Recognize a run's event. @default messages shaped like {@link AgUiEnvelope} */\n event?: (message: In) => AgUiEnvelope | null | undefined;\n /** What happens to a run when its connection drops. @default 'keep' */\n policy?: RunPolicy;\n /** Where streaming runs are remembered. @default sessionStorage */\n storage?: RunStorage | null;\n}\n\n/** An AG-UI agent over a WebSocket. Create with {@link createAgUiAgent}. */\nexport interface AgUiAgent<S> {\n /** The client the runs stream on. */\n readonly client: WebSocketClient<any, any>;\n /** The runs underneath, from `createWebSocketRuns`. */\n readonly runs: WebSocketRuns<RunAgentInput, AgUiThread<S>>;\n /**\n * Start a run with the thread so far plus `input.messages`, which show up in the thread right\n * away. A run that's still streaming is aborted first. Returns the run's id.\n */\n run(\n input?: {\n messages?: readonly AgUiMessage[];\n tools?: readonly unknown[];\n context?: readonly unknown[];\n forwardedProps?: unknown;\n },\n options?: { policy?: RunPolicy }\n ): string;\n /** Stop the run that's streaming, if any. */\n abort(): void;\n /**\n * Forget the thread, e.g. on logout or when another user signs in: its runs (with\n * `runs.clear()`, which sends nothing), messages and state. The next run starts over from\n * `state`, with a new thread id unless `threadId` was given. `abort()` a streaming run first\n * to stop it on the server.\n */\n reset(): void;\n /** The thread as of the latest run. The same object until it changes. */\n getSnapshot(): AgUiThread<S>;\n /** Get notified when the thread changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop following runs, and release the connection. */\n dispose(): void;\n}\n\nfunction randomId() {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\nconst isEnvelope = (message: any): AgUiEnvelope | undefined =>\n typeof message?.runId === 'string' &&\n typeof message.offset === 'number' &&\n typeof message.event?.type === 'string'\n ? message\n : undefined;\n\nconst ENDS = new Set(['RUN_FINISHED', 'RUN_ERROR']);\n\n/**\n * Run an [AG-UI](https://docs.ag-ui.com) agent over a WebSocket. Each run streams AG-UI events,\n * which are folded into the thread's messages and shared state with {@link applyAgUiEvent}.\n * Runs come from `createWebSocketRuns`, so they resume after a reconnect or a reload, and a\n * state delta that can't be applied asks for a snapshot (`resync`).\n *\n * AG-UI doesn't define messages for WebSockets, so the defaults are small: the client sends\n * `{ type: 'run', runId, input }`, `{ type: 'resume', runId, after }` and\n * `{ type: 'cancel', runId }`, and the server sends `{ runId, offset, event }`, with `offset`\n * counting each run's events from 1. Each option replaces one of them.\n *\n * @example\n * ```ts\n * import { createAgUiAgent } from 'react-websocket/ag-ui';\n *\n * export const agent = createAgUiAgent(createWebSocket(url, { json: true }));\n *\n * agent.run({ messages: [{ id: crypto.randomUUID(), role: 'user', content: 'Plan my week' }] });\n * ```\n */\nexport function createAgUiAgent<S = unknown, In = any, Out = any>(\n client: WebSocketClient<In, Out>,\n options: AgUiAgentOptions<S, NoInfer<In>, NoInfer<Out>> = {}\n): AgUiAgent<S> {\n let threadId = options.threadId ?? randomId();\n const empty: AgUiThread<S> = {\n messages: [],\n state: options.state as S,\n status: 'idle',\n stale: false\n };\n let base = empty;\n let snapshot = empty;\n const listeners = new Set<() => void>();\n // Runs that asked for a snapshot after a failed delta, until one arrives.\n const resynced = new Set<string>();\n const event = options.event ?? isEnvelope;\n // Now or never: not queued, and not `volatile`, which can be a datagram that never arrives.\n const send = (message: unknown) => client.socket?.readyState === 1 && client.send(message as Out);\n\n const runs = createWebSocketRuns<RunAgentInput, AgUiThread<S>, In, Out>(client, {\n name: options.name ?? 'ag-ui',\n start: options.run ?? ((input, runId) => ({ type: 'run', runId, input }) as Out),\n resume: options.resume ?? ((runId, after) => ({ type: 'resume', runId, after }) as Out),\n cancel: options.cancel ?? (runId => ({ type: 'cancel', runId }) as Out),\n event: message => event(message),\n done: message => ENDS.has(event(message)!.event.type),\n initial: empty,\n reduce: (thread, message) => applyAgUiEvent(thread, event(message)!.event),\n policy: options.policy,\n storage: options.storage\n });\n\n function update() {\n const latest = runs.list().at(-1);\n let next = latest ? latest.value : base;\n if (latest?.status === 'aborted' && next.status === 'running')\n next = { ...next, status: 'aborted' };\n // Once each time the state goes stale, or on a later event if the socket wasn't open.\n if (latest && !latest.value.stale) resynced.delete(latest.runId);\n else if (latest && options.resync && !resynced.has(latest.runId)) {\n if (send(options.resync(latest.runId))) resynced.add(latest.runId);\n }\n if (next === snapshot) return;\n snapshot = next;\n for (const listener of [...listeners]) listener();\n }\n const off = runs.subscribe(update);\n update();\n\n function abort() {\n for (const run of runs.list()) runs.abort(run.runId);\n }\n\n return {\n client,\n runs,\n run(input = {}, runOptions) {\n abort();\n const runId = randomId();\n // The run starts from the state sent with it, the last good one: its deltas apply to it.\n base = {\n ...snapshot,\n stale: false,\n messages: [...snapshot.messages, ...(input.messages ?? [])]\n };\n runs.start(\n {\n threadId,\n runId,\n state: base.state,\n messages: base.messages,\n tools: input.tools ?? [],\n context: input.context ?? [],\n forwardedProps: input.forwardedProps ?? {}\n },\n { runId, initial: { ...base, status: 'running' }, policy: runOptions?.policy }\n );\n return runId;\n },\n abort,\n reset() {\n // Before the runs go, whose change shows `base`.\n base = empty;\n resynced.clear();\n if (options.threadId === undefined) threadId = randomId();\n runs.clear();\n update();\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n off();\n runs.dispose();\n }\n };\n}\n"],"mappings":";;AAmFA,SAAS,SAAS,OAAe;CAC/B,OAAO,MAAM,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG;AACrD;AAEA,SAAS,MAAM,GAAS,GAAkB;CACxC,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;CACvE,IAAI,MAAM,QAAQ,CAAC,MAAM,MAAM,QAAQ,CAAC,GAAG,OAAO;CAClD,MAAM,OAAO,OAAO,KAAK,CAAC;CAC1B,OAAO,KAAK,WAAW,OAAO,KAAK,CAAC,CAAC,CAAC,UAAU,KAAK,OAAM,QA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N,MAAM,QAAQ,SAAS;GAEvB,OAAO;IACL,GAAG;IACH,OAAO;IACP,UAAU,CAAC,GAAG,SAAS,UAAU,GAAI,MAAM,YAAY,CAAC,CAAE;GAC5D;GACA,KAAK,MACH;IACE;IACA;IACA,OAAO,KAAK;IACZ,UAAU,KAAK;IACf,OAAO,MAAM,SAAS,CAAC;IACvB,SAAS,MAAM,WAAW,CAAC;IAC3B,gBAAgB,MAAM,kBAAkB,CAAC;GAC3C,GACA;IAAE;IAAO,SAAS;KAAE,GAAG;KAAM,QAAQ;IAAU;IAAG,QAAQ,YAAY;GAAO,CAC/E;GACA,OAAO;EACT;EACA;EACA,QAAQ;GAEN,OAAO;GACP,SAAS,MAAM;GACf,IAAI,QAAQ,aAAa,KAAA,GAAW,WAAW,SAAS;GACxD,KAAK,MAAM;GACX,OAAO;EACT;EACA,mBAAmB;EACnB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,IAAI;GACJ,KAAK,QAAQ;EACf;CACF;AACF"}
1
+ {"version":3,"file":"ag-ui.js","names":[],"sources":["../src/ag-ui.ts"],"sourcesContent":["// The build keeps `./core` external, so this entry shares the client with the others.\nimport {\n createWebSocketRuns,\n type RunPolicy,\n type RunStorage,\n type WebSocketClient,\n type WebSocketRuns\n} from './core';\n\n/** A JSON Patch (RFC 6902) operation, as in AG-UI's `STATE_DELTA` and `ACTIVITY_DELTA`. */\nexport interface JsonPatchOperation {\n readonly op: 'add' | 'remove' | 'replace' | 'move' | 'copy' | 'test';\n /** A JSON Pointer (RFC 6901), such as `/items/0/name`. */\n readonly path: string;\n /** The source of `move` and `copy`. */\n readonly from?: string;\n /** The value to `add`, `replace` with or `test` for. */\n readonly value?: unknown;\n}\n\n/** An AG-UI event: `type` is `'RUN_STARTED'`, `'TEXT_MESSAGE_CONTENT'`, `'STATE_DELTA'`, … */\nexport interface AgUiEvent {\n readonly type: string;\n readonly [field: string]: any;\n}\n\n/** A tool call on an assistant message, as in AG-UI. */\nexport interface AgUiToolCall {\n readonly id: string;\n readonly type: 'function';\n readonly function: { readonly name: string; readonly arguments: string };\n}\n\n/** A message in an AG-UI thread. */\nexport interface AgUiMessage {\n readonly id: string;\n readonly role: 'developer' | 'system' | 'assistant' | 'user' | 'tool' | 'reasoning' | 'activity';\n readonly content?: unknown;\n readonly toolCalls?: readonly AgUiToolCall[];\n /** For a `tool` message, the call it answers. */\n readonly toolCallId?: string;\n /** For an `activity` message. */\n readonly activityType?: string;\n readonly [field: string]: unknown;\n}\n\n/** AG-UI's `RunAgentInput`: what a run starts from. */\nexport interface RunAgentInput {\n readonly threadId: string;\n readonly runId: string;\n readonly parentRunId?: string;\n readonly state?: unknown;\n readonly messages: readonly AgUiMessage[];\n readonly tools: readonly unknown[];\n readonly context: readonly unknown[];\n readonly forwardedProps: unknown;\n}\n\n/** A thread's messages and shared state, reduced from AG-UI events. */\nexport interface AgUiThread<S = unknown> {\n readonly messages: readonly AgUiMessage[];\n /** The shared state, from `STATE_SNAPSHOT` and `STATE_DELTA`. */\n readonly state: S;\n /**\n * `'running'` from `RUN_STARTED`, `'finished'` after `RUN_FINISHED`, `'error'` after\n * `RUN_ERROR`, `'aborted'` when the run was stopped from this side.\n */\n readonly status: 'idle' | 'running' | 'finished' | 'error' | 'aborted';\n /** The step in progress, between `STEP_STARTED` and `STEP_FINISHED`. */\n readonly step?: string;\n /** From `RUN_ERROR`. */\n readonly error?: { readonly message: string; readonly code?: string };\n /** From `RUN_FINISHED`. */\n readonly result?: unknown;\n /**\n * A `STATE_DELTA` couldn't be applied. `state` is the last good one, and later deltas are\n * skipped until a `STATE_SNAPSHOT` arrives.\n */\n readonly stale: boolean;\n}\n\ntype Json = any;\n\nfunction unescape(token: string) {\n return token.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\nfunction equal(a: Json, b: Json): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n return keys.length === Object.keys(b).length && keys.every(key => equal(a[key], b[key]));\n}\n\nfunction fail(operation: JsonPatchOperation): never {\n throw new Error(`JSON Patch failed: ${operation.op} ${operation.path}`);\n}\n\nconst INDEX = /^(0|[1-9]\\d*)$/;\n\n/** A JSON Pointer's tokens. It's empty, for the whole document, or starts with `/`. */\nfunction tokens(pointer: string, operation: JsonPatchOperation) {\n if (pointer !== '' && pointer[0] !== '/') fail(operation);\n return pointer.split('/').slice(1).map(unescape);\n}\n\n/** Whether `node` has `token`: an index in range for an array, not `length`; an own key otherwise. */\nfunction has(node: Json, token: string) {\n return Array.isArray(node)\n ? INDEX.test(token) && +token < node.length\n : Object.hasOwn(node, token);\n}\n\n/** Set an own property, even `__proto__`, as JSON.parse would. */\nfunction put(object: Json, key: string, value: Json) {\n Object.defineProperty(object, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n}\n\n/**\n * Apply a JSON Patch (RFC 6902) without changing `document`: what changes is copied, the rest is\n * shared. Throws, leaving `document` as it was, if an operation can't be applied: a missing path,\n * an index out of range, a pointer that doesn't start with `/`, or a failed `test`.\n */\nexport function applyPatch<T>(document: T, operations: readonly JsonPatchOperation[]): T {\n let root: Json = document;\n\n function get(path: string, operation: JsonPatchOperation): Json {\n let node = root;\n for (const token of tokens(path, operation)) {\n if (typeof node !== 'object' || node === null || !has(node, token)) fail(operation);\n node = node[token];\n }\n return node;\n }\n\n // Replace the parent of `path` with a copy, change it with `change`, and copy its ancestors.\n function edit(\n path: string,\n operation: JsonPatchOperation,\n change: (parent: Json, key: string) => void\n ) {\n const keys = tokens(path, operation);\n if (!keys.length) fail(operation);\n const walk = (node: Json, depth: number): Json => {\n if (typeof node !== 'object' || node === null) fail(operation);\n const copy = Array.isArray(node) ? [...node] : { ...node };\n const key = keys[depth]!;\n if (depth === keys.length - 1) change(copy, key);\n else if (!has(node, key)) fail(operation);\n else copy[key] = walk(node[key], depth + 1);\n return copy;\n };\n root = walk(root, 0);\n }\n\n function index(parent: Json[], key: string, operation: JsonPatchOperation, adding: boolean) {\n // `-` is the end of the array, which only `add` can use.\n const i = key === '-' ? (adding ? parent.length : -1) : INDEX.test(key) ? +key : -1;\n if (i < 0 || i > parent.length - (adding ? 0 : 1)) fail(operation);\n return i;\n }\n\n function add(path: string, value: Json, operation: JsonPatchOperation) {\n if (path === '') return void (root = value);\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent.splice(index(parent, key, operation, true), 0, value);\n else put(parent, key, value);\n });\n }\n\n function remove(path: string, operation: JsonPatchOperation) {\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent.splice(index(parent, key, operation, false), 1);\n else if (Object.hasOwn(parent, key)) delete parent[key];\n else fail(operation);\n });\n }\n\n for (const operation of operations) {\n const { op, path, from, value } = operation;\n if (op === 'add') add(path, value, operation);\n else if (op === 'remove') remove(path, operation);\n else if (op === 'replace') {\n get(path, operation);\n if (path === '') root = value;\n else\n edit(path, operation, (parent, key) => {\n if (Array.isArray(parent)) parent[key as unknown as number] = value;\n else put(parent, key, value);\n });\n } else if (op === 'move' || op === 'copy') {\n const moved = get(from ?? fail(operation), operation);\n if (op === 'move') remove(from!, operation);\n add(path, op === 'copy' ? structuredClone(moved) : moved, operation);\n } else if (op === 'test') {\n if (!equal(get(path, operation), value)) fail(operation);\n } else fail(operation);\n }\n return root;\n}\n\nfunction updateMessage(\n thread: AgUiThread<any>,\n id: string | undefined,\n change: (message: AgUiMessage) => AgUiMessage\n) {\n return thread.messages.map(message => (message.id === id ? change(message) : message));\n}\n\nfunction appendText(message: AgUiMessage, delta: string | undefined) {\n return { ...message, content: `${(message.content as string | undefined) ?? ''}${delta ?? ''}` };\n}\n\nfunction updateToolCall(\n thread: AgUiThread<any>,\n id: string | undefined,\n change: (call: AgUiToolCall) => AgUiToolCall\n) {\n return thread.messages.map(message =>\n message.toolCalls?.some(call => call.id === id)\n ? {\n ...message,\n toolCalls: message.toolCalls.map(call => (call.id === id ? change(call) : call))\n }\n : message\n );\n}\n\n/** The last message with a tool call, for chunks that leave out `toolCallId`. */\nfunction lastToolCallId(thread: AgUiThread<any>) {\n for (let i = thread.messages.length - 1; i >= 0; i--) {\n const calls = thread.messages[i]!.toolCalls;\n if (calls?.length) return calls.at(-1)!.id;\n }\n}\n\n/**\n * Fold one AG-UI event into a thread, without changing it. Handles the run lifecycle, steps,\n * text, tool calls and their results, reasoning, activity, and message and state snapshots and\n * deltas. A `STATE_DELTA` that can't be applied marks the thread `stale` instead of throwing.\n * Other events, such as `CUSTOM` and `RAW`, return the thread unchanged.\n *\n * Use it as a `reduce` function, or wrap it to handle events of your own.\n */\nexport function applyAgUiEvent<S>(thread: AgUiThread<S>, event: AgUiEvent): AgUiThread<S> {\n const e = event;\n const message = (role: AgUiMessage['role'], extra?: object): AgUiThread<S> => ({\n ...thread,\n messages: [...thread.messages, { id: e.messageId, role, content: '', ...extra }]\n });\n const known = (id: string | undefined) => thread.messages.some(m => m.id === id);\n switch (e.type) {\n case 'RUN_STARTED':\n return { ...thread, status: 'running', step: undefined, error: undefined, result: undefined };\n case 'RUN_FINISHED':\n return { ...thread, status: 'finished', step: undefined, result: e.result };\n case 'RUN_ERROR':\n return {\n ...thread,\n status: 'error',\n step: undefined,\n error: { message: e.message, code: e.code }\n };\n case 'STEP_STARTED':\n return { ...thread, step: e.stepName };\n case 'STEP_FINISHED':\n return { ...thread, step: undefined };\n case 'TEXT_MESSAGE_START':\n return message(e.role ?? 'assistant');\n case 'REASONING_MESSAGE_START':\n return message('reasoning');\n case 'TEXT_MESSAGE_CONTENT':\n case 'REASONING_MESSAGE_CONTENT':\n return {\n ...thread,\n messages: updateMessage(thread, e.messageId, m => appendText(m, e.delta))\n };\n case 'TEXT_MESSAGE_CHUNK':\n case 'REASONING_MESSAGE_CHUNK': {\n // Only the first chunk of a message must carry its id. Activity events can come between\n // chunks without ending the message.\n const id = e.messageId ?? thread.messages.filter(m => m.role !== 'activity').at(-1)?.id;\n const role = e.type === 'TEXT_MESSAGE_CHUNK' ? (e.role ?? 'assistant') : 'reasoning';\n const next = known(id) ? thread : message(role);\n return { ...next, messages: updateMessage(next, id, m => appendText(m, e.delta)) };\n }\n case 'TOOL_CALL_START':\n case 'TOOL_CALL_CHUNK': {\n const id = e.toolCallId ?? lastToolCallId(thread);\n let next = thread;\n if (\n e.type === 'TOOL_CALL_START' ||\n !thread.messages.some(m => m.toolCalls?.some(c => c.id === id))\n ) {\n const call: AgUiToolCall = {\n id,\n type: 'function',\n function: { name: e.toolCallName, arguments: '' }\n };\n const parent = e.parentMessageId ?? id;\n next = known(parent)\n ? thread\n : { ...thread, messages: [...thread.messages, { id: parent, role: 'assistant' }] };\n next = {\n ...next,\n messages: updateMessage(next, parent, m => ({\n ...m,\n toolCalls: [...(m.toolCalls ?? []), call]\n }))\n };\n }\n if (e.type === 'TOOL_CALL_START') return next;\n return toolArgs(next, id, e.delta);\n }\n case 'TOOL_CALL_ARGS':\n return toolArgs(thread, e.toolCallId, e.delta);\n case 'TOOL_CALL_RESULT':\n return message(e.role ?? 'tool', { toolCallId: e.toolCallId, content: e.content });\n case 'STATE_SNAPSHOT':\n return { ...thread, state: e.snapshot, stale: false };\n case 'STATE_DELTA':\n if (thread.stale) return thread;\n try {\n return { ...thread, state: applyPatch(thread.state, e.delta) };\n } catch {\n return { ...thread, stale: true };\n }\n case 'MESSAGES_SNAPSHOT':\n return { ...thread, messages: e.messages };\n case 'ACTIVITY_SNAPSHOT': {\n if (known(e.messageId) && e.replace === false) return thread;\n const next = known(e.messageId) ? thread : message('activity');\n return {\n ...next,\n messages: updateMessage(next, e.messageId, m => ({\n ...m,\n activityType: e.activityType,\n content: e.content\n }))\n };\n }\n case 'ACTIVITY_DELTA':\n try {\n return {\n ...thread,\n messages: updateMessage(thread, e.messageId, m => ({\n ...m,\n content: applyPatch(m.content, e.patch)\n }))\n };\n } catch {\n return thread;\n }\n default:\n return thread;\n }\n}\n\nfunction toolArgs<S>(thread: AgUiThread<S>, id: string | undefined, delta: string | undefined) {\n return {\n ...thread,\n messages: updateToolCall(thread, id, call => ({\n ...call,\n function: { ...call.function, arguments: call.function.arguments + (delta ?? '') }\n }))\n };\n}\n\n/** What the server sends for each event of a run: its run, its offset (from 1), and the event. */\nexport interface AgUiEnvelope {\n readonly runId: string;\n readonly offset: number;\n readonly event: AgUiEvent;\n}\n\n/** Options for {@link createAgUiAgent}. The message formats have defaults; see the guide. */\nexport interface AgUiAgentOptions<S, In, Out> {\n /** The thread's id, sent in every `RunAgentInput`. A new random one by default. */\n threadId?: string;\n /** The shared state before the first `STATE_SNAPSHOT`, sent with the first run. */\n state?: S;\n /** Names where streaming runs are remembered across reloads. @default 'ag-ui' */\n name?: string;\n /** @default `{ type: 'run', runId, input }` */\n run?: (input: RunAgentInput, runId: string) => Out;\n /** @default `{ type: 'resume', runId, after }` */\n resume?: (runId: string, after: number | undefined) => Out;\n /** @default `{ type: 'cancel', runId }` */\n cancel?: (runId: string) => Out;\n /**\n * The message that asks the server for a `STATE_SNAPSHOT`, sent when a `STATE_DELTA` can't\n * be applied. Without it, the state stays `stale` until the server sends one by itself.\n */\n resync?: (runId: string) => Out;\n /** Recognize a run's event. @default messages shaped like {@link AgUiEnvelope} */\n event?: (message: In) => AgUiEnvelope | null | undefined;\n /** What happens to a run when its connection drops. @default 'keep' */\n policy?: RunPolicy;\n /** Where streaming runs are remembered. @default sessionStorage */\n storage?: RunStorage | null;\n}\n\n/** An AG-UI agent over a WebSocket. Create with {@link createAgUiAgent}. */\nexport interface AgUiAgent<S> {\n /** The client the runs stream on. */\n readonly client: WebSocketClient<any, any>;\n /** The runs underneath, from `createWebSocketRuns`. */\n readonly runs: WebSocketRuns<RunAgentInput, AgUiThread<S>>;\n /**\n * Start a run with the thread so far plus `input.messages`, which show up in the thread right\n * away. A run that's still streaming is aborted first. Returns the run's id.\n */\n run(\n input?: {\n messages?: readonly AgUiMessage[];\n tools?: readonly unknown[];\n context?: readonly unknown[];\n forwardedProps?: unknown;\n },\n options?: { policy?: RunPolicy }\n ): string;\n /** Stop the run that's streaming, if any. */\n abort(): void;\n /**\n * Forget the thread, e.g. on logout or when another user signs in: its runs (with\n * `runs.clear()`, which sends nothing), messages and state. The next run starts over from\n * `state`, with a new thread id unless `threadId` was given. `abort()` a streaming run first\n * to stop it on the server.\n */\n reset(): void;\n /** The thread as of the latest run. The same object until it changes. */\n getSnapshot(): AgUiThread<S>;\n /** Get notified when the thread changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop following runs, and release the connection. */\n dispose(): void;\n}\n\nfunction randomId() {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\nconst isEnvelope = (message: any): AgUiEnvelope | undefined =>\n typeof message?.runId === 'string' &&\n typeof message.offset === 'number' &&\n typeof message.event?.type === 'string'\n ? message\n : undefined;\n\nconst ENDS = new Set(['RUN_FINISHED', 'RUN_ERROR']);\n\n/**\n * Run an [AG-UI](https://docs.ag-ui.com) agent over a WebSocket. Each run streams AG-UI events,\n * which are folded into the thread's messages and shared state with {@link applyAgUiEvent}.\n * Runs come from `createWebSocketRuns`, so they resume after a reconnect or a reload, and a\n * state delta that can't be applied asks for a snapshot (`resync`).\n *\n * AG-UI doesn't define messages for WebSockets, so the defaults are small: the client sends\n * `{ type: 'run', runId, input }`, `{ type: 'resume', runId, after }` and\n * `{ type: 'cancel', runId }`, and the server sends `{ runId, offset, event }`, with `offset`\n * counting each run's events from 1. Each option replaces one of them.\n *\n * @example\n * ```ts\n * import { createAgUiAgent } from 'react-websocket/ag-ui';\n *\n * export const agent = createAgUiAgent(createWebSocket(url, { json: true }));\n *\n * agent.run({ messages: [{ id: crypto.randomUUID(), role: 'user', content: 'Plan my week' }] });\n * ```\n */\nexport function createAgUiAgent<S = unknown, In = any, Out = any>(\n client: WebSocketClient<In, Out>,\n options: AgUiAgentOptions<S, NoInfer<In>, NoInfer<Out>> = {}\n): AgUiAgent<S> {\n let threadId = options.threadId ?? randomId();\n const empty: AgUiThread<S> = {\n messages: [],\n state: options.state as S,\n status: 'idle',\n stale: false\n };\n let base = empty;\n let snapshot = empty;\n const listeners = new Set<() => void>();\n // Runs that asked for a snapshot after a failed delta, until one arrives.\n const resynced = new Set<string>();\n const event = options.event ?? isEnvelope;\n // Now or never: not queued, and not `volatile`, which can be a datagram that never arrives.\n const send = (message: unknown) => client.socket?.readyState === 1 && client.send(message as Out);\n // Running, without the step, error or result the thread had before.\n const started = (thread: AgUiThread<S>) => applyAgUiEvent(thread, { type: 'RUN_STARTED' });\n\n const runs = createWebSocketRuns<RunAgentInput, AgUiThread<S>, In, Out>(client, {\n name: options.name ?? 'ag-ui',\n start: options.run ?? ((input, runId) => ({ type: 'run', runId, input }) as Out),\n resume: options.resume ?? ((runId, after) => ({ type: 'resume', runId, after }) as Out),\n cancel: options.cancel ?? (runId => ({ type: 'cancel', runId }) as Out),\n event: message => event(message),\n done: message => ENDS.has(event(message)!.event.type),\n // A run followed again after a reload streams before its events replay.\n initial: started(empty),\n reduce: (thread, message) => applyAgUiEvent(thread, event(message)!.event),\n policy: options.policy,\n storage: options.storage\n });\n\n function update() {\n const latest = runs.list().at(-1);\n let next = latest ? latest.value : base;\n if (latest?.status === 'aborted' && next.status === 'running')\n next = { ...next, status: 'aborted', step: undefined };\n // Once each time the state goes stale, or on a later event if the socket wasn't open.\n if (latest && !latest.value.stale) resynced.delete(latest.runId);\n else if (latest && options.resync && !resynced.has(latest.runId)) {\n if (send(options.resync(latest.runId))) resynced.add(latest.runId);\n }\n if (next === snapshot) return;\n snapshot = next;\n for (const listener of [...listeners]) listener();\n }\n const off = runs.subscribe(update);\n update();\n\n function abort() {\n for (const run of runs.list()) runs.abort(run.runId);\n }\n\n return {\n client,\n runs,\n run(input = {}, runOptions) {\n abort();\n const runId = randomId();\n // The run starts from the state sent with it, the last good one: its deltas apply to it.\n base = {\n ...snapshot,\n stale: false,\n messages: [...snapshot.messages, ...(input.messages ?? [])]\n };\n runs.start(\n {\n threadId,\n runId,\n state: base.state,\n messages: base.messages,\n tools: input.tools ?? [],\n context: input.context ?? [],\n forwardedProps: input.forwardedProps ?? {}\n },\n { runId, initial: started(base), policy: runOptions?.policy }\n );\n return runId;\n },\n abort,\n reset() {\n // Before the runs go, whose change shows `base`.\n base = empty;\n resynced.clear();\n if (options.threadId === undefined) threadId = randomId();\n runs.clear();\n update();\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n off();\n runs.dispose();\n }\n };\n}\n"],"mappings":";;AAmFA,SAAS,SAAS,OAAe;CAC/B,OAAO,MAAM,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG;AACrD;AAEA,SAAS,MAAM,GAAS,GAAkB;CACxC,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;CACvE,IAAI,MAAM,QAAQ,CAAC,MAAM,MAAM,QAAQ,CAAC,GAAG,OAAO;CAClD,MAAM,OAAO,OAAO,KAAK,CAAC;CAC1B,OAAO,KAAK,WAAW,OAAO,KAAK,CAAC,CAAC,CAAC,UAAU,KAAK,OAAM,QAAO,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC;AACzF;AAEA,SAAS,KAAK,WAAsC;CAClD,MAAM,IAAI,MAAM,sBAAsB,UAAU,GAAG,GAAG,UAAU,MAAM;AACxE;AAEA,MAAM,QAAQ;;AAGd,SAAS,OAAO,SAAiB,WAA+B;CAC9D,IAAI,YAAY,MAAM,QAAQ,OAAO,KAAK,KAAK,SAAS;CACxD,OAAO,QAAQ,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,QAAQ;AACjD;;AAGA,SAAS,IAAI,MAAY,OAAe;CACtC,OAAO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vB,SAAS,MAAM,WAAW,CAAC;IAC3B,gBAAgB,MAAM,kBAAkB,CAAC;GAC3C,GACA;IAAE;IAAO,SAAS,QAAQ,IAAI;IAAG,QAAQ,YAAY;GAAO,CAC9D;GACA,OAAO;EACT;EACA;EACA,QAAQ;GAEN,OAAO;GACP,SAAS,MAAM;GACf,IAAI,QAAQ,aAAa,KAAA,GAAW,WAAW,SAAS;GACxD,KAAK,MAAM;GACX,OAAO;EACT;EACA,mBAAmB;EACnB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,IAAI;GACJ,KAAK,QAAQ;EACf;CACF;AACF"}
package/dist/chaos.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/chaos.ts
2
+ // src/chaos.ts
3
3
  const CONNECTING = 0;
4
4
  const OPEN = 1;
5
5
  const CLOSING = 2;
@@ -34,24 +34,68 @@ function closeEvent(code, reason, wasClean) {
34
34
  };
35
35
  return typeof CloseEvent === "function" ? new CloseEvent("close", init) : Object.assign(new Event("close"), init);
36
36
  }
37
+ let channel;
38
+ const posted = [];
39
+ function post(run) {
40
+ if (!channel) {
41
+ channel = new MessageChannel();
42
+ channel.port1.onmessage = () => posted.shift()?.();
43
+ channel.port1.unref?.();
44
+ }
45
+ posted.push(run);
46
+ channel.port2.postMessage(null);
47
+ }
48
+ const hidden = () => typeof document === "object" && document.visibilityState === "hidden" && typeof MessageChannel === "function";
49
+ const timed = /* @__PURE__ */ new Set();
50
+ let watching = false;
51
+ function watch() {
52
+ if (watching || typeof document !== "object") return;
53
+ watching = true;
54
+ document.addEventListener("visibilitychange", () => {
55
+ if (hidden()) for (const hurry of [...timed]) hurry();
56
+ });
57
+ }
37
58
  /**
38
59
  * Events delayed in order: each runs in its own task, no earlier than the one before it,
39
60
  * because a WebSocket never reorders. With no delay and nothing waiting, it runs right away.
61
+ *
62
+ * A hidden tab holds timers back by a second to a minute, so a delay would last that long and
63
+ * a heartbeat would give up. There, events run in order without the delay.
40
64
  */
41
65
  function createQueue() {
42
66
  let items = [];
43
67
  let timer;
68
+ let turn = 0;
69
+ let waiting = false;
70
+ function stopTimer() {
71
+ clearTimeout(timer);
72
+ timer = void 0;
73
+ timed.delete(hurry);
74
+ }
75
+ function run(mine) {
76
+ if (mine !== turn) return;
77
+ waiting = false;
78
+ stopTimer();
79
+ try {
80
+ items.shift().run();
81
+ } finally {
82
+ next();
83
+ }
84
+ }
85
+ function hurry() {
86
+ stopTimer();
87
+ const mine = turn;
88
+ post(() => run(mine));
89
+ }
44
90
  function next() {
45
91
  const head = items[0];
46
- if (timer !== void 0 || !head) return;
47
- timer = setTimeout(() => {
48
- timer = void 0;
49
- try {
50
- items.shift().run();
51
- } finally {
52
- next();
53
- }
54
- }, head.at - Date.now());
92
+ if (waiting || !head) return;
93
+ waiting = true;
94
+ const mine = turn;
95
+ if (hidden()) return post(() => run(mine));
96
+ timer = setTimeout(run, head.at - Date.now(), mine);
97
+ timed.add(hurry);
98
+ watch();
55
99
  }
56
100
  return {
57
101
  push(delay, run, data) {
@@ -65,8 +109,9 @@ function createQueue() {
65
109
  },
66
110
  clear() {
67
111
  items = [];
68
- clearTimeout(timer);
69
- timer = void 0;
112
+ stopTimer();
113
+ waiting = false;
114
+ turn++;
70
115
  },
71
116
  bytes: () => items.reduce((sum, item) => sum + (item.data === void 0 ? 0 : size(item.data)), 0)
72
117
  };
@@ -223,6 +268,7 @@ function createChaosWebSocket(options = {}) {
223
268
  }
224
269
  close(code, reason) {
225
270
  if (code !== void 0 && code !== 1e3 && !(code >= 3e3 && code <= 4999)) throw new DOMException(`Invalid close code ${code}`, "InvalidAccessError");
271
+ if (new TextEncoder().encode(reason).length > 123) throw new DOMException("Close reason longer than 123 bytes", "SyntaxError");
226
272
  if (this.#state >= CLOSING) return;
227
273
  const connecting = this.#state === CONNECTING;
228
274
  this.#state = CLOSING;
@@ -260,6 +306,8 @@ function createChaosWebSocket(options = {}) {
260
306
  #stall() {
261
307
  if (this.#state !== OPEN || this.#stalled) return;
262
308
  this.#stalled = true;
309
+ this.#unsent += this.#outgoing.bytes();
310
+ this.#outgoing.clear();
263
311
  log("chaos: stalled", this.url);
264
312
  }
265
313
  /** The only way to CLOSED, so it happens once. */
@@ -278,7 +326,6 @@ function createChaosWebSocket(options = {}) {
278
326
  }
279
327
  return ChaosSocket;
280
328
  }
281
- //#endregion
282
329
  exports.createChaosWebSocket = createChaosWebSocket;
283
330
 
284
331
  //# sourceMappingURL=chaos.cjs.map