@ably/ai-transport 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +114 -116
  2. package/dist/ably-ai-transport.js +1743 -961
  3. package/dist/ably-ai-transport.js.map +1 -1
  4. package/dist/ably-ai-transport.umd.cjs +1 -1
  5. package/dist/ably-ai-transport.umd.cjs.map +1 -1
  6. package/dist/constants.d.ts +117 -39
  7. package/dist/core/agent.d.ts +29 -0
  8. package/dist/core/codec/decoder.d.ts +20 -23
  9. package/dist/core/codec/encoder.d.ts +11 -8
  10. package/dist/core/codec/index.d.ts +1 -2
  11. package/dist/core/codec/lifecycle-tracker.d.ts +10 -9
  12. package/dist/core/codec/types.d.ts +410 -101
  13. package/dist/core/transport/agent-session.d.ts +10 -0
  14. package/dist/core/transport/branch-chain.d.ts +43 -0
  15. package/dist/core/transport/client-session.d.ts +13 -0
  16. package/dist/core/transport/decode-fold.d.ts +47 -0
  17. package/dist/core/transport/headers.d.ts +97 -17
  18. package/dist/core/transport/index.d.ts +5 -3
  19. package/dist/core/transport/internal/bounded-map.d.ts +20 -0
  20. package/dist/core/transport/invocation.d.ts +74 -0
  21. package/dist/core/transport/load-conversation.d.ts +128 -0
  22. package/dist/core/transport/load-history.d.ts +39 -0
  23. package/dist/core/transport/pipe-stream.d.ts +9 -8
  24. package/dist/core/transport/run-manager.d.ts +78 -0
  25. package/dist/core/transport/tree.d.ts +435 -0
  26. package/dist/core/transport/types/agent.d.ts +353 -0
  27. package/dist/core/transport/types/client.d.ts +168 -0
  28. package/dist/core/transport/types/shared.d.ts +24 -0
  29. package/dist/core/transport/types/tree.d.ts +315 -0
  30. package/dist/core/transport/types/view.d.ts +222 -0
  31. package/dist/core/transport/types.d.ts +13 -402
  32. package/dist/core/transport/view.d.ts +354 -0
  33. package/dist/errors.d.ts +37 -9
  34. package/dist/index.d.ts +6 -6
  35. package/dist/logger.d.ts +12 -0
  36. package/dist/react/ably-ai-transport-react.js +1164 -645
  37. package/dist/react/ably-ai-transport-react.js.map +1 -1
  38. package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
  39. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
  40. package/dist/react/contexts/client-session-context.d.ts +36 -0
  41. package/dist/react/contexts/client-session-provider.d.ts +53 -0
  42. package/dist/react/create-session-hooks.d.ts +116 -0
  43. package/dist/react/index.d.ts +16 -10
  44. package/dist/react/internal/use-resolved-session.d.ts +36 -0
  45. package/dist/react/use-ably-messages.d.ts +20 -11
  46. package/dist/react/use-client-session.d.ts +81 -0
  47. package/dist/react/use-create-view.d.ts +23 -0
  48. package/dist/react/use-tree.d.ts +35 -0
  49. package/dist/react/use-view.d.ts +110 -0
  50. package/dist/utils.d.ts +32 -23
  51. package/dist/vercel/ably-ai-transport-vercel.js +2748 -1625
  52. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
  53. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
  54. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
  55. package/dist/vercel/codec/decoder.d.ts +5 -18
  56. package/dist/vercel/codec/encoder.d.ts +6 -36
  57. package/dist/vercel/codec/events.d.ts +51 -0
  58. package/dist/vercel/codec/index.d.ts +24 -12
  59. package/dist/vercel/codec/reducer.d.ts +144 -0
  60. package/dist/vercel/codec/tool-transitions.d.ts +50 -0
  61. package/dist/vercel/index.d.ts +4 -2
  62. package/dist/vercel/react/ably-ai-transport-vercel-react.js +10298 -1410
  63. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
  64. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +70 -1
  65. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
  66. package/dist/vercel/react/contexts/chat-transport-context.d.ts +33 -0
  67. package/dist/vercel/react/contexts/chat-transport-provider.d.ts +96 -0
  68. package/dist/vercel/react/index.d.ts +4 -0
  69. package/dist/vercel/react/use-chat-transport.d.ts +66 -21
  70. package/dist/vercel/react/use-message-sync.d.ts +31 -12
  71. package/dist/vercel/run-end-reason.d.ts +29 -0
  72. package/dist/vercel/transport/chat-transport.d.ts +71 -30
  73. package/dist/vercel/transport/index.d.ts +25 -18
  74. package/dist/vercel/transport/run-output-stream.d.ts +56 -0
  75. package/dist/version.d.ts +2 -0
  76. package/package.json +47 -34
  77. package/src/constants.ts +126 -47
  78. package/src/core/agent.ts +68 -0
  79. package/src/core/codec/decoder.ts +71 -98
  80. package/src/core/codec/encoder.ts +115 -58
  81. package/src/core/codec/index.ts +13 -6
  82. package/src/core/codec/lifecycle-tracker.ts +10 -9
  83. package/src/core/codec/types.ts +438 -106
  84. package/src/core/transport/agent-session.ts +1344 -0
  85. package/src/core/transport/branch-chain.ts +58 -0
  86. package/src/core/transport/client-session.ts +775 -0
  87. package/src/core/transport/decode-fold.ts +91 -0
  88. package/src/core/transport/headers.ts +182 -19
  89. package/src/core/transport/index.ts +29 -22
  90. package/src/core/transport/internal/bounded-map.ts +27 -0
  91. package/src/core/transport/invocation.ts +98 -0
  92. package/src/core/transport/load-conversation.ts +355 -0
  93. package/src/core/transport/load-history.ts +269 -0
  94. package/src/core/transport/pipe-stream.ts +58 -40
  95. package/src/core/transport/run-manager.ts +249 -0
  96. package/src/core/transport/tree.ts +1167 -0
  97. package/src/core/transport/types/agent.ts +407 -0
  98. package/src/core/transport/types/client.ts +211 -0
  99. package/src/core/transport/types/shared.ts +27 -0
  100. package/src/core/transport/types/tree.ts +344 -0
  101. package/src/core/transport/types/view.ts +259 -0
  102. package/src/core/transport/types.ts +13 -527
  103. package/src/core/transport/view.ts +1271 -0
  104. package/src/errors.ts +42 -9
  105. package/src/event-emitter.ts +3 -2
  106. package/src/index.ts +55 -39
  107. package/src/logger.ts +14 -1
  108. package/src/react/contexts/client-session-context.ts +41 -0
  109. package/src/react/contexts/client-session-provider.tsx +186 -0
  110. package/src/react/create-session-hooks.ts +141 -0
  111. package/src/react/index.ts +27 -10
  112. package/src/react/internal/use-resolved-session.ts +63 -0
  113. package/src/react/use-ably-messages.ts +47 -19
  114. package/src/react/use-client-session.ts +201 -0
  115. package/src/react/use-create-view.ts +72 -0
  116. package/src/react/use-tree.ts +84 -0
  117. package/src/react/use-view.ts +275 -0
  118. package/src/react/vite.config.ts +4 -1
  119. package/src/utils.ts +63 -45
  120. package/src/vercel/codec/decoder.ts +336 -255
  121. package/src/vercel/codec/encoder.ts +348 -196
  122. package/src/vercel/codec/events.ts +87 -0
  123. package/src/vercel/codec/index.ts +59 -14
  124. package/src/vercel/codec/reducer.ts +977 -0
  125. package/src/vercel/codec/tool-transitions.ts +122 -0
  126. package/src/vercel/index.ts +7 -3
  127. package/src/vercel/react/contexts/chat-transport-context.ts +41 -0
  128. package/src/vercel/react/contexts/chat-transport-provider.tsx +150 -0
  129. package/src/vercel/react/index.ts +13 -1
  130. package/src/vercel/react/use-chat-transport.ts +162 -42
  131. package/src/vercel/react/use-message-sync.ts +121 -22
  132. package/src/vercel/react/vite.config.ts +4 -2
  133. package/src/vercel/run-end-reason.ts +78 -0
  134. package/src/vercel/transport/chat-transport.ts +553 -113
  135. package/src/vercel/transport/index.ts +40 -28
  136. package/src/vercel/transport/run-output-stream.ts +170 -0
  137. package/src/version.ts +2 -0
  138. package/dist/core/transport/client-transport.d.ts +0 -10
  139. package/dist/core/transport/conversation-tree.d.ts +0 -9
  140. package/dist/core/transport/decode-history.d.ts +0 -41
  141. package/dist/core/transport/server-transport.d.ts +0 -7
  142. package/dist/core/transport/stream-router.d.ts +0 -19
  143. package/dist/core/transport/turn-manager.d.ts +0 -34
  144. package/dist/react/use-active-turns.d.ts +0 -8
  145. package/dist/react/use-client-transport.d.ts +0 -7
  146. package/dist/react/use-conversation-tree.d.ts +0 -20
  147. package/dist/react/use-edit.d.ts +0 -7
  148. package/dist/react/use-history.d.ts +0 -19
  149. package/dist/react/use-messages.d.ts +0 -7
  150. package/dist/react/use-regenerate.d.ts +0 -7
  151. package/dist/react/use-send.d.ts +0 -7
  152. package/dist/vercel/codec/accumulator.d.ts +0 -21
  153. package/src/core/transport/client-transport.ts +0 -959
  154. package/src/core/transport/conversation-tree.ts +0 -434
  155. package/src/core/transport/decode-history.ts +0 -337
  156. package/src/core/transport/server-transport.ts +0 -458
  157. package/src/core/transport/stream-router.ts +0 -118
  158. package/src/core/transport/turn-manager.ts +0 -147
  159. package/src/react/use-active-turns.ts +0 -61
  160. package/src/react/use-client-transport.ts +0 -37
  161. package/src/react/use-conversation-tree.ts +0 -71
  162. package/src/react/use-edit.ts +0 -24
  163. package/src/react/use-history.ts +0 -111
  164. package/src/react/use-messages.ts +0 -32
  165. package/src/react/use-regenerate.ts +0 -24
  166. package/src/react/use-send.ts +0 -25
  167. package/src/vercel/codec/accumulator.ts +0 -603
@@ -1 +1 @@
1
- {"version":3,"file":"ably-ai-transport-vercel.js","names":[],"sources":["../../src/constants.ts","../../src/utils.ts","../../src/vercel/codec/accumulator.ts","../../src/core/codec/decoder.ts","../../src/core/codec/lifecycle-tracker.ts","../../src/vercel/codec/decoder.ts","../../src/errors.ts","../../src/core/codec/encoder.ts","../../src/vercel/codec/encoder.ts","../../src/vercel/codec/index.ts","../../src/vercel/transport/chat-transport.ts","../../src/event-emitter.ts","../../src/logger.ts","../../src/core/transport/conversation-tree.ts","../../src/core/transport/decode-history.ts","../../src/core/transport/headers.ts","../../src/core/transport/stream-router.ts","../../src/core/transport/client-transport.ts","../../src/core/transport/pipe-stream.ts","../../src/core/transport/turn-manager.ts","../../src/core/transport/server-transport.ts","../../src/vercel/transport/index.ts"],"sourcesContent":["/**\n * Shared constants used by both codec and transport layers.\n *\n * Header constants define the `x-ably-*` wire protocol. Message and event\n * name constants define the transport lifecycle signals on the channel.\n *\n * These live at the top level (not in codec/ or transport/) because both\n * layers need them — the codec core reads/writes stream and status headers,\n * while the transport layer reads/writes turn, cancel, and role headers.\n */\n\n// ---------------------------------------------------------------------------\n// Stream headers (used by codec encoder/decoder core)\n// ---------------------------------------------------------------------------\n\n/** Header: whether this Ably message uses streaming (message appends) or is discrete. Always \"true\" or \"false\". */\nexport const HEADER_STREAM = 'x-ably-stream';\n\n/** Header: lifecycle status of a streamed message. Only set when x-ably-stream is \"true\". */\nexport const HEADER_STATUS = 'x-ably-status';\n\n/** Header: stream identity. Set by the encoder on every streamed message; read by the decoder to correlate streams. */\nexport const HEADER_STREAM_ID = 'x-ably-stream-id';\n\n// ---------------------------------------------------------------------------\n// Identity headers (used by transport for turn correlation)\n// ---------------------------------------------------------------------------\n\n/** Header: turn correlation ID. Set on every message in a turn. */\nexport const HEADER_TURN_ID = 'x-ably-turn-id';\n\n/** Header: message identity. Assigned per message (user or assistant). Used for optimistic reconciliation on the client. */\nexport const HEADER_MSG_ID = 'x-ably-msg-id';\n\n/** Header: clientId of the user who initiated the turn. Set by the server on stream messages. */\nexport const HEADER_TURN_CLIENT_ID = 'x-ably-turn-client-id';\n\n/** Header: message role (e.g. \"user\", \"assistant\"). */\nexport const HEADER_ROLE = 'x-ably-role';\n\n// ---------------------------------------------------------------------------\n// Cancel headers\n// ---------------------------------------------------------------------------\n\n/** Header: cancel a specific turn by ID. */\nexport const HEADER_CANCEL_TURN_ID = 'x-ably-cancel-turn-id';\n\n/** Header: cancel all turns belonging to the sender's clientId. */\nexport const HEADER_CANCEL_OWN = 'x-ably-cancel-own';\n\n/** Header: cancel all turns on the channel. */\nexport const HEADER_CANCEL_ALL = 'x-ably-cancel-all';\n\n/** Header: cancel all turns belonging to a specific clientId. */\nexport const HEADER_CANCEL_CLIENT_ID = 'x-ably-cancel-client-id';\n\n// ---------------------------------------------------------------------------\n// Fork / branching headers\n// ---------------------------------------------------------------------------\n\n/** Header: the msg-id of the immediately preceding message in this branch. */\nexport const HEADER_PARENT = 'x-ably-parent';\n\n/** Header: the msg-id of the message this one replaces (creates a fork). */\nexport const HEADER_FORK_OF = 'x-ably-fork-of';\n\n// ---------------------------------------------------------------------------\n// Turn lifecycle headers\n// ---------------------------------------------------------------------------\n\n/** Header: reason a turn ended (on x-ably-turn-end messages). */\nexport const HEADER_TURN_REASON = 'x-ably-turn-reason';\n\n// ---------------------------------------------------------------------------\n// Message / event names\n// ---------------------------------------------------------------------------\n\n/** Message name: client->server cancel signal. */\nexport const EVENT_CANCEL = 'x-ably-cancel';\n\n/** Message name: server publishes this to signal a turn has started. */\nexport const EVENT_TURN_START = 'x-ably-turn-start';\n\n/** Message name: server publishes this to signal a turn has ended. */\nexport const EVENT_TURN_END = 'x-ably-turn-end';\n\n/** Message name: transport-level abort signal (stream cancelled). */\nexport const EVENT_ABORT = 'x-ably-abort';\n\n/** Message name: transport-level error signal. */\nexport const EVENT_ERROR = 'x-ably-error';\n\n// ---------------------------------------------------------------------------\n// Domain header prefix (used by codec implementations)\n// ---------------------------------------------------------------------------\n\n/** Prefix for domain-specific headers. Distinguishes codec-layer headers from transport `x-ably-*` headers. */\nexport const DOMAIN_HEADER_PREFIX = 'x-domain-';\n","/**\n * Shared utilities for working with Ably messages.\n *\n * These are general-purpose helpers used by both the codec and transport\n * layers. They live at the top level to avoid either layer depending on\n * the other.\n */\n\nimport type * as Ably from 'ably';\n\nimport { DOMAIN_HEADER_PREFIX } from './constants.js';\n\n/**\n * Extract extras.headers from an Ably InboundMessage.\n * @param message - The Ably message to extract headers from.\n * @returns The headers record, or an empty object if absent.\n */\nexport const getHeaders = (message: Ably.InboundMessage): Record<string, string> => {\n // CAST: Ably SDK types `extras` as `any`; runtime checks below guard access.\n const extras = message.extras as unknown;\n if (!extras || typeof extras !== 'object') return {};\n const headers = (extras as { headers?: unknown }).headers;\n if (!headers || typeof headers !== 'object') return {};\n // CAST: Ably wire protocol guarantees headers is Record<string, string>\n // when present, verified by the runtime guards above.\n return headers as Record<string, string>;\n};\n\n/**\n * Parse a JSON string, returning undefined on failure.\n * @param value - The JSON string to parse.\n * @returns The parsed value, or undefined if parsing fails.\n */\nexport const parseJson = (value: string | undefined): unknown => {\n if (value === undefined) return undefined;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Set a header value if defined, skipping undefined and null. Strings are set directly,\n * booleans and numbers are stringified, objects are JSON-serialized.\n * @param headers - The headers object to mutate.\n * @param key - The header key.\n * @param value - The value to set.\n */\nexport const setIfPresent = (headers: Record<string, string>, key: string, value: unknown): void => {\n if (value === undefined || value === null) return;\n if (typeof value === 'string') {\n headers[key] = value;\n } else if (typeof value === 'boolean' || typeof value === 'number') {\n headers[key] = String(value);\n } else if (typeof value === 'object') {\n headers[key] = JSON.stringify(value);\n }\n};\n\n/**\n * Set multiple headers at once, skipping entries whose values are undefined or null.\n * Each value is converted using the same rules as {@link setIfPresent}.\n * @param headers - The headers object to mutate.\n * @param entries - Key-value pairs to set.\n */\nexport const setHeadersIfPresent = (headers: Record<string, string>, entries: Record<string, unknown>): void => {\n for (const [key, value] of Object.entries(entries)) {\n setIfPresent(headers, key, value);\n }\n};\n\n/**\n * Merge two header records into a new object. Later values override earlier ones.\n * Undefined inputs are treated as empty.\n * @param base - Base headers (lower priority).\n * @param overrides - Override headers (higher priority).\n * @returns A new merged headers object.\n */\nexport const mergeHeaders = (\n base: Record<string, string> | undefined,\n overrides: Record<string, string> | undefined,\n): Record<string, string> => ({\n ...base,\n ...overrides,\n});\n\n/**\n * Parse a boolean header (\"true\"/\"false\"), returning undefined if absent.\n * @param value - The header string to parse.\n * @returns True if \"true\", false for any other string, or undefined if absent.\n */\nexport const parseBool = (value: string | undefined): boolean | undefined => {\n if (value === undefined) return undefined;\n return value === 'true';\n};\n\n/**\n * Build a domain headers record from key-value pairs. Each key is automatically\n * prefixed with {@link DOMAIN_HEADER_PREFIX}. Values that are undefined or null\n * are skipped; strings are set directly; booleans, numbers, and objects are\n * converted using the same rules as {@link setIfPresent}.\n * @param entries - Unprefixed key-value pairs (e.g. `{ toolCallId: 'tc-1' }` becomes `{ 'x-domain-toolCallId': 'tc-1' }`).\n * @returns A new headers record with prefixed keys.\n */\nexport const domainHeaders = (entries: Record<string, unknown>): Record<string, string> => {\n const h: Record<string, string> = {};\n for (const [key, value] of Object.entries(entries)) {\n setIfPresent(h, DOMAIN_HEADER_PREFIX + key, value);\n }\n return h;\n};\n\n/**\n * Read a domain header value from a headers record.\n * @param headers - The headers record to read from.\n * @param key - The unprefixed domain key (e.g. `'toolCallId'` reads `'x-domain-toolCallId'`).\n * @returns The header value, or undefined if absent.\n */\nexport const getDomainHeader = (headers: Record<string, string>, key: string): string | undefined =>\n headers[DOMAIN_HEADER_PREFIX + key];\n\n/**\n * Mapped type that converts properties whose type includes `undefined`\n * into optional properties with `undefined` excluded from the value.\n * Properties typed as `unknown` are kept required (since `undefined extends unknown`\n * is always true, but `unknown` fields are intentionally broad, not optional).\n */\nexport type Stripped<T> = {\n [K in keyof T as undefined extends T[K] ? (unknown extends T[K] ? K : never) : K]: T[K];\n} & {\n [K in keyof T as undefined extends T[K] ? (unknown extends T[K] ? never : K) : never]?: Exclude<T[K], undefined>;\n};\n\n/**\n * Remove all keys whose value is `undefined` from a shallow object.\n * Returns a new object — the input is not mutated. Useful for building\n * chunk literals with optional fields without conditional spread noise.\n *\n * The return type converts `{ foo: T | undefined }` to `{ foo?: T }`,\n * matching the optional-field pattern used by the AI SDK chunk types.\n * @param obj - The object to strip undefined values from.\n * @returns A shallow copy with undefined-valued keys removed.\n */\nexport const stripUndefined = <T extends Record<string, unknown>>(obj: T): Stripped<T> => {\n const result = {} as Record<string, unknown>;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] !== undefined) {\n result[key] = obj[key];\n }\n }\n // CAST: The runtime strip guarantees the Stripped<T> contract —\n // required keys are always present, optional keys are absent when undefined.\n return result as Stripped<T>;\n};\n\n// ---------------------------------------------------------------------------\n// DomainHeaderReader — typed accessors for domain headers\n// ---------------------------------------------------------------------------\n\n/**\n * Typed accessor wrapper around a headers record for reading domain headers.\n * Reduces repetitive `getDomainHeader` + `parseBool` / `parseJson` chains.\n */\nexport interface DomainHeaderReader {\n /** Read a domain header as a string, or undefined if absent. */\n str(key: string): string | undefined;\n /** Read a domain header as a string, falling back to a default if absent. */\n strOr(key: string, fallback: string): string;\n /** Read a domain header as a boolean (\"true\"/\"false\"), or undefined if absent. */\n bool(key: string): boolean | undefined;\n /** Read a domain header as parsed JSON, or undefined if absent or invalid. */\n json(key: string): unknown;\n}\n\n/**\n * Create a {@link DomainHeaderReader} over a headers record.\n * @param headers - The raw headers record to read domain headers from.\n * @returns A typed accessor for domain header values.\n */\nexport const headerReader = (headers: Record<string, string>): DomainHeaderReader => ({\n str: (key: string) => getDomainHeader(headers, key),\n strOr: (key: string, fallback: string) => getDomainHeader(headers, key) ?? fallback,\n bool: (key: string) => parseBool(getDomainHeader(headers, key)),\n json: (key: string) => parseJson(getDomainHeader(headers, key)),\n});\n\n// ---------------------------------------------------------------------------\n// DomainHeaderWriter — typed builder for domain headers\n// ---------------------------------------------------------------------------\n\n/**\n * Fluent builder for constructing domain header records with typed setters.\n * Mirrors {@link DomainHeaderReader} with the same method names for symmetry.\n * Undefined values are silently skipped on all setters.\n */\nexport interface DomainHeaderWriter {\n /** Set a string domain header. Skips if value is undefined. */\n str(key: string, value: string | undefined): DomainHeaderWriter;\n /** Set a boolean domain header (serialized as \"true\"/\"false\"). Skips if value is undefined. */\n bool(key: string, value: boolean | undefined): DomainHeaderWriter;\n /** Set a JSON-serialized domain header. Skips if value is undefined or null. */\n json(key: string, value: unknown): DomainHeaderWriter;\n /** Return the accumulated headers record. */\n build(): Record<string, string>;\n}\n\n/**\n * Create a {@link DomainHeaderWriter} for building a domain headers record.\n * @returns A fluent builder that prefixes each key with the domain header prefix.\n */\nexport const headerWriter = (): DomainHeaderWriter => {\n const h: Record<string, string> = {};\n const writer: DomainHeaderWriter = {\n str: (key: string, value: string | undefined) => {\n if (value !== undefined) h[DOMAIN_HEADER_PREFIX + key] = value;\n return writer;\n },\n bool: (key: string, value: boolean | undefined) => {\n if (value !== undefined) h[DOMAIN_HEADER_PREFIX + key] = String(value);\n return writer;\n },\n json: (key: string, value: unknown) => {\n if (value !== undefined && value !== null) h[DOMAIN_HEADER_PREFIX + key] = JSON.stringify(value);\n return writer;\n },\n build: () => h,\n };\n return writer;\n};\n","/**\n * Vercel AI SDK Message Accumulator\n *\n * Builds and maintains a UIMessage[] list from decoder outputs.\n * Implements MessageAccumulator<UIMessageChunk, UIMessage>.\n *\n * The accumulator consumes DecoderOutput[] from the decoder and groups\n * streaming events into UIMessage objects using lifecycle boundaries\n * (start/finish). Complete messages (from writeMessages) are inserted\n * directly.\n *\n * Multiple messages can be in-progress concurrently — each is identified\n * by the `messageId` field on DecoderOutput (read from x-ably-msg-id).\n */\n\nimport type * as AI from 'ai';\n\nimport type { DecoderOutput, MessageAccumulator } from '../../core/codec/types.js';\nimport { stripUndefined } from '../../utils.js';\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\n/** Status of a streamed message (text, reasoning, or tool-input). */\ntype StreamStatus = 'streaming' | 'finished' | 'aborted';\n\n/**\n * Tracks an in-progress tool part's position and accumulated streaming input.\n * Text and reasoning parts don't need this — we write directly to the part.\n * Tool parts need the extra `inputText` buffer because deltas arrive as raw\n * JSON fragments that must be accumulated before parsing.\n */\ninterface ToolPartTracker {\n /** Index in the message's parts array. */\n partIndex: number;\n /** Accumulated streaming input text (for JSON parsing on completion). */\n inputText: string;\n}\n\n/** Fields shared by all DynamicToolUIPart state variants. */\ninterface ToolBaseFields {\n type: 'dynamic-tool';\n toolName: string;\n toolCallId: string;\n title?: string;\n providerExecuted?: boolean;\n}\n\n/** Bundled per-message state for an in-progress message. */\ninterface ActiveMessageState {\n message: AI.UIMessage;\n textStreams: DeltaStreamTracker;\n reasoningStreams: DeltaStreamTracker;\n toolTrackers: Record<string, ToolPartTracker>;\n streamStatus: Map<string, StreamStatus>;\n}\n\n// ---------------------------------------------------------------------------\n// Tool base helper\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the state-independent base fields for a DynamicToolUIPart.\n * Works with both chunks (tool-input-start, etc.) and existing parts.\n * @param source - Any object containing the required tool identity fields.\n * @param source.toolCallId - The tool call identifier.\n * @param source.toolName - The tool name.\n * @param source.title - Optional display title.\n * @param source.providerExecuted - Whether the provider executed the tool.\n * @returns Base fields shared across all DynamicToolUIPart state variants.\n */\nconst toolBase = (source: {\n toolCallId: string;\n toolName: string;\n title?: string;\n providerExecuted?: boolean;\n}): ToolBaseFields =>\n stripUndefined({\n type: 'dynamic-tool' as const,\n toolCallId: source.toolCallId,\n toolName: source.toolName,\n title: source.title,\n providerExecuted: source.providerExecuted,\n });\n\n// ---------------------------------------------------------------------------\n// DeltaStreamTracker — manages text or reasoning stream accumulation\n// ---------------------------------------------------------------------------\n\n/**\n * Tracks in-progress text or reasoning streams within a single message.\n * Owns the mapping from stream ID to part index, enforcing the pairing\n * of part type and index map by construction.\n */\nclass DeltaStreamTracker {\n private readonly _partType: 'text' | 'reasoning';\n private _activeIndex = new Map<string, number>();\n\n constructor(partType: 'text' | 'reasoning') {\n this._partType = partType;\n }\n\n start(id: string, msg: AI.UIMessage, streamStatus: Map<string, StreamStatus>): void {\n this._activeIndex.set(id, msg.parts.length);\n msg.parts.push({ type: this._partType, text: '' });\n streamStatus.set(id, 'streaming');\n }\n\n delta(id: string, msg: AI.UIMessage, text: string): void {\n const idx = this._activeIndex.get(id);\n if (idx === undefined) return;\n const part = msg.parts[idx];\n if (part?.type === this._partType) {\n part.text += text;\n }\n }\n\n end(id: string, streamStatus: Map<string, StreamStatus>): void {\n streamStatus.set(id, 'finished');\n this._activeIndex.delete(id);\n }\n\n reset(): void {\n this._activeIndex = new Map();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\nclass DefaultUIMessageAccumulator implements MessageAccumulator<AI.UIMessageChunk, AI.UIMessage> {\n private readonly _messageList: AI.UIMessage[] = [];\n private readonly _activeMessages = new Map<string, ActiveMessageState>();\n\n get messages(): AI.UIMessage[] {\n return this._messageList;\n }\n\n get completedMessages(): AI.UIMessage[] {\n const activeSet = new Set<AI.UIMessage>();\n for (const state of this._activeMessages.values()) {\n activeSet.add(state.message);\n }\n return this._messageList.filter((msg) => !activeSet.has(msg));\n }\n\n get hasActiveStream(): boolean {\n for (const state of this._activeMessages.values()) {\n for (const status of state.streamStatus.values()) {\n if (status === 'streaming') return true;\n }\n }\n return false;\n }\n\n processOutputs(outputs: DecoderOutput<AI.UIMessageChunk, AI.UIMessage>[]): void {\n for (const output of outputs) {\n if (output.kind === 'message') {\n this._messageList.push(output.message);\n } else if (output.messageId !== undefined) {\n this._processEvent(output.event, output.messageId);\n }\n }\n }\n\n updateMessage(message: AI.UIMessage): void {\n const idx = this._messageList.findIndex((m) => m.id === message.id);\n if (idx !== -1) {\n this._messageList[idx] = message;\n }\n }\n\n // -------------------------------------------------------------------------\n // Shared helpers\n // -------------------------------------------------------------------------\n\n private _ensureActiveMessage(messageId: string): ActiveMessageState {\n const existing = this._activeMessages.get(messageId);\n if (existing) return existing;\n\n const state: ActiveMessageState = {\n message: { id: messageId, role: 'assistant', parts: [] },\n textStreams: new DeltaStreamTracker('text'),\n reasoningStreams: new DeltaStreamTracker('reasoning'),\n toolTrackers: {},\n streamStatus: new Map(),\n };\n this._activeMessages.set(messageId, state);\n this._messageList.push(state.message);\n return state;\n }\n\n /**\n * Look up a tracked tool part by toolCallId within a message state.\n * @param toolCallId - The tool call identifier to look up.\n * @param state - The active message state to search in.\n * @returns The tracker and current part, or undefined if not found.\n */\n private _getToolPart(\n toolCallId: string,\n state: ActiveMessageState,\n ): { tracker: ToolPartTracker; part: AI.DynamicToolUIPart } | undefined {\n const tracker = state.toolTrackers[toolCallId];\n if (!tracker) return undefined;\n\n const existing = state.message.parts[tracker.partIndex];\n if (existing?.type !== 'dynamic-tool') return undefined;\n\n return { tracker, part: existing };\n }\n\n // -------------------------------------------------------------------------\n // Event dispatch\n // -------------------------------------------------------------------------\n\n private _processEvent(chunk: AI.UIMessageChunk, messageId: string): void {\n switch (chunk.type) {\n case 'start':\n case 'start-step':\n case 'finish-step':\n case 'finish':\n case 'abort':\n case 'error':\n case 'message-metadata': {\n this._processLifecycle(chunk, messageId);\n break;\n }\n\n case 'text-start':\n case 'text-delta':\n case 'text-end':\n case 'reasoning-start':\n case 'reasoning-delta':\n case 'reasoning-end': {\n this._processTextOrReasoning(chunk, messageId);\n break;\n }\n\n case 'tool-input-start':\n case 'tool-input-delta':\n case 'tool-input-available':\n case 'tool-input-error': {\n this._processToolInput(chunk, messageId);\n break;\n }\n\n case 'tool-output-available':\n case 'tool-output-error':\n case 'tool-output-denied':\n case 'tool-approval-request': {\n this._processToolOutput(chunk, messageId);\n break;\n }\n\n case 'file':\n case 'source-url':\n case 'source-document': {\n this._processContentPart(chunk, messageId);\n break;\n }\n\n default: {\n if (chunk.type.startsWith('data-')) {\n if (chunk.transient) break;\n\n const state = this._ensureActiveMessage(messageId);\n\n // CAST: chunk.type is `data-${string}` which satisfies DataUIPart,\n // but TypeScript cannot verify the template literal matches a\n // specific UIMessagePart variant at the type level.\n const dataPart = stripUndefined({\n type: chunk.type,\n id: chunk.id,\n data: chunk.data,\n }) as AI.UIMessage['parts'][number];\n\n if (chunk.id !== undefined) {\n const idx = state.message.parts.findIndex((p) => p.type === chunk.type && 'id' in p && p.id === chunk.id);\n if (idx !== -1) {\n state.message.parts[idx] = dataPart;\n break;\n }\n }\n\n state.message.parts.push(dataPart);\n }\n break;\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Lifecycle events\n // -------------------------------------------------------------------------\n\n private _processLifecycle(\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'start' | 'start-step' | 'finish-step' | 'finish' | 'abort' | 'error' | 'message-metadata' }\n >,\n messageId: string,\n ): void {\n switch (chunk.type) {\n case 'start': {\n const state = this._ensureActiveMessage(messageId);\n if (chunk.messageId) state.message.id = chunk.messageId;\n if (chunk.messageMetadata !== undefined) {\n state.message.metadata = chunk.messageMetadata;\n }\n break;\n }\n\n case 'start-step': {\n const state = this._ensureActiveMessage(messageId);\n state.message.parts.push({ type: 'step-start' });\n break;\n }\n\n case 'finish-step': {\n const state = this._activeMessages.get(messageId);\n if (state) {\n state.textStreams.reset();\n state.reasoningStreams.reset();\n }\n break;\n }\n\n case 'finish': {\n const state = this._activeMessages.get(messageId);\n if (state && chunk.messageMetadata !== undefined) {\n state.message.metadata = chunk.messageMetadata;\n }\n this._activeMessages.delete(messageId);\n break;\n }\n\n case 'abort': {\n const state = this._activeMessages.get(messageId);\n if (state) {\n for (const [id, status] of state.streamStatus) {\n if (status === 'streaming') {\n state.streamStatus.set(id, 'aborted');\n }\n }\n }\n this._activeMessages.delete(messageId);\n break;\n }\n\n case 'error': {\n break;\n }\n\n case 'message-metadata': {\n const state = this._activeMessages.get(messageId);\n if (state && chunk.messageMetadata !== undefined) {\n state.message.metadata = chunk.messageMetadata;\n }\n break;\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Text and reasoning streaming\n // -------------------------------------------------------------------------\n\n private _processTextOrReasoning(\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'text-start' | 'text-delta' | 'text-end' | 'reasoning-start' | 'reasoning-delta' | 'reasoning-end' }\n >,\n messageId: string,\n ): void {\n const state = this._ensureActiveMessage(messageId);\n\n switch (chunk.type) {\n case 'text-start': {\n state.textStreams.start(chunk.id, state.message, state.streamStatus);\n break;\n }\n case 'text-delta': {\n state.textStreams.delta(chunk.id, state.message, chunk.delta);\n break;\n }\n case 'text-end': {\n state.textStreams.end(chunk.id, state.streamStatus);\n break;\n }\n case 'reasoning-start': {\n state.reasoningStreams.start(chunk.id, state.message, state.streamStatus);\n break;\n }\n case 'reasoning-delta': {\n state.reasoningStreams.delta(chunk.id, state.message, chunk.delta);\n break;\n }\n case 'reasoning-end': {\n state.reasoningStreams.end(chunk.id, state.streamStatus);\n break;\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Tool input streaming\n // -------------------------------------------------------------------------\n\n private _processToolInput(\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'tool-input-start' | 'tool-input-delta' | 'tool-input-available' | 'tool-input-error' }\n >,\n messageId: string,\n ): void {\n switch (chunk.type) {\n case 'tool-input-start': {\n const state = this._ensureActiveMessage(messageId);\n const partIndex = state.message.parts.length;\n state.message.parts.push({ ...toolBase(chunk), state: 'input-streaming', input: undefined });\n state.toolTrackers[chunk.toolCallId] = { partIndex, inputText: '' };\n state.streamStatus.set(chunk.toolCallId, 'streaming');\n break;\n }\n\n case 'tool-input-delta': {\n const state = this._ensureActiveMessage(messageId);\n const tracker = state.toolTrackers[chunk.toolCallId];\n if (!tracker) break;\n tracker.inputText += chunk.inputTextDelta;\n\n let parsedInput: unknown;\n try {\n // CAST: JSON.parse returns any; unknown is the safe trust-boundary type.\n parsedInput = JSON.parse(tracker.inputText) as unknown;\n } catch {\n parsedInput = undefined;\n }\n\n const found = this._getToolPart(chunk.toolCallId, state);\n if (!found) break;\n state.message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'input-streaming',\n input: parsedInput,\n };\n break;\n }\n\n case 'tool-input-available': {\n const state = this._ensureActiveMessage(messageId);\n const found = this._getToolPart(chunk.toolCallId, state);\n if (!found) break;\n state.message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'input-available',\n input: chunk.input,\n };\n state.streamStatus.set(chunk.toolCallId, 'finished');\n break;\n }\n\n case 'tool-input-error': {\n const state = this._ensureActiveMessage(messageId);\n const found = this._getToolPart(chunk.toolCallId, state);\n if (found) {\n state.message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'output-error',\n input: chunk.input,\n errorText: chunk.errorText,\n };\n } else {\n const partIndex = state.message.parts.length;\n state.message.parts.push({\n ...toolBase(chunk),\n state: 'output-error',\n input: chunk.input,\n errorText: chunk.errorText,\n });\n state.toolTrackers[chunk.toolCallId] = { partIndex, inputText: '' };\n }\n state.streamStatus.set(chunk.toolCallId, 'finished');\n break;\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Tool output transitions\n // -------------------------------------------------------------------------\n\n private _processToolOutput(\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'tool-output-available' | 'tool-output-error' | 'tool-output-denied' | 'tool-approval-request' }\n >,\n messageId: string,\n ): void {\n const state = this._ensureActiveMessage(messageId);\n const found = this._getToolPart(chunk.toolCallId, state);\n if (!found) return;\n\n switch (chunk.type) {\n case 'tool-output-available': {\n state.message.parts[found.tracker.partIndex] = stripUndefined({\n ...toolBase(found.part),\n state: 'output-available' as const,\n input: found.part.input,\n output: chunk.output,\n preliminary: chunk.preliminary,\n });\n break;\n }\n\n case 'tool-output-error': {\n state.message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'output-error',\n input: found.part.input,\n errorText: chunk.errorText,\n };\n break;\n }\n\n case 'tool-output-denied': {\n state.message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'output-denied',\n input: found.part.input,\n approval: { id: '', approved: false },\n };\n break;\n }\n\n case 'tool-approval-request': {\n state.message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'approval-requested',\n input: found.part.input,\n approval: { id: chunk.approvalId },\n };\n break;\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Content parts\n // -------------------------------------------------------------------------\n\n private _processContentPart(\n chunk: Extract<AI.UIMessageChunk, { type: 'file' | 'source-url' | 'source-document' }>,\n messageId: string,\n ): void {\n const state = this._ensureActiveMessage(messageId);\n\n switch (chunk.type) {\n case 'file': {\n state.message.parts.push({ type: 'file', mediaType: chunk.mediaType, url: chunk.url });\n break;\n }\n\n case 'source-url': {\n state.message.parts.push(\n stripUndefined({\n type: 'source-url' as const,\n sourceId: chunk.sourceId,\n url: chunk.url,\n title: chunk.title,\n }),\n );\n break;\n }\n\n case 'source-document': {\n state.message.parts.push(\n stripUndefined({\n type: 'source-document' as const,\n sourceId: chunk.sourceId,\n mediaType: chunk.mediaType,\n title: chunk.title,\n filename: chunk.filename,\n }),\n );\n break;\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Vercel AI SDK accumulator that builds UIMessage[] from decoder outputs.\n * @returns A {@link MessageAccumulator} for UIMessageChunk/UIMessage.\n */\nexport const createAccumulator = (): MessageAccumulator<AI.UIMessageChunk, AI.UIMessage> =>\n new DefaultUIMessageAccumulator();\n","/**\n * Decoder core — action dispatch and serial tracking machinery.\n *\n * Handles the Ably message action patterns (create, append, update, delete)\n * and delegates to domain-specific hooks for event building and discrete\n * event decoding.\n *\n * Domain decoders call `createDecoderCore(hooks, options)` and provide hooks\n * for stream classification, event building, and discrete decoding.\n */\n\nimport type * as Ably from 'ably';\n\nimport { HEADER_MSG_ID, HEADER_STATUS, HEADER_STREAM, HEADER_STREAM_ID } from '../../constants.js';\nimport type { Logger } from '../../logger.js';\nimport { getHeaders } from '../../utils.js';\nimport type { DecoderOutput, MessagePayload, StreamTrackerState } from './types.js';\n\n/**\n * Wrap a domain event as a single-element decoder output array.\n * @param event - The domain event to wrap.\n * @returns A single-element array containing the event as a decoder output.\n */\nexport const eventOutput = <TEvent, TMessage>(event: TEvent): DecoderOutput<TEvent, TMessage>[] => [\n { kind: 'event', event },\n];\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for creating a decoder core. */\nexport interface DecoderCoreOptions {\n /** Called when a tracked stream is replaced (non-prefix update). Receives the tracker with updated state. */\n onStreamUpdate?: (tracker: StreamTrackerState) => void;\n /** Called when a message is deleted. Receives the serial and tracker (if one exists). */\n onStreamDelete?: (serial: string, tracker: StreamTrackerState | undefined) => void;\n /** Logger instance for diagnostic output. */\n logger?: Logger;\n}\n\n// ---------------------------------------------------------------------------\n// Domain hooks\n// ---------------------------------------------------------------------------\n\n/** Hooks that a domain codec provides to the decoder core for stream classification and event building. */\nexport interface DecoderCoreHooks<TEvent, TMessage> {\n /**\n * Build domain events emitted when a new stream starts. May return multiple\n * events (e.g. a start event and a start-step event).\n */\n buildStartEvents(tracker: StreamTrackerState): DecoderOutput<TEvent, TMessage>[];\n\n /** Build domain events for a text delta received on a stream. */\n buildDeltaEvents(tracker: StreamTrackerState, delta: string): DecoderOutput<TEvent, TMessage>[];\n\n /**\n * Build domain events emitted when a stream finishes (x-ably-status:finished).\n * Not called for aborted streams. The closing headers may differ from\n * tracker.headers if the closing append carried updated headers.\n */\n buildEndEvents(\n tracker: StreamTrackerState,\n closingHeaders: Record<string, string>,\n ): DecoderOutput<TEvent, TMessage>[];\n\n /**\n * Decode a discrete message (message.create where x-ably-stream is \"false\",\n * or a non-streamable first-contact update). Handles user messages, lifecycle\n * events, tool lifecycle, data-*, etc.\n */\n decodeDiscrete(input: MessagePayload): DecoderOutput<TEvent, TMessage>[];\n}\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/** The decoder core returned by {@link createDecoderCore}. */\nexport interface DecoderCore<TEvent, TMessage> {\n /** Decode a single Ably message into zero or more domain outputs. */\n decode(message: Ably.InboundMessage): DecoderOutput<TEvent, TMessage>[];\n}\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CD7\nclass DefaultDecoderCore<TEvent, TMessage> implements DecoderCore<TEvent, TMessage> {\n private readonly _hooks: DecoderCoreHooks<TEvent, TMessage>;\n private readonly _logger: Logger | undefined;\n private readonly _onStreamUpdate: ((tracker: StreamTrackerState) => void) | undefined;\n private readonly _onStreamDelete: ((serial: string, tracker: StreamTrackerState | undefined) => void) | undefined;\n private readonly _serialState = new Map<string, StreamTrackerState>();\n\n constructor(hooks: DecoderCoreHooks<TEvent, TMessage>, options: DecoderCoreOptions = {}) {\n this._hooks = hooks;\n this._onStreamUpdate = options.onStreamUpdate;\n this._onStreamDelete = options.onStreamDelete;\n this._logger = options.logger?.withContext({ component: 'DecoderCore' });\n }\n\n decode(message: Ably.InboundMessage): DecoderOutput<TEvent, TMessage>[] {\n const action = message.action;\n\n this._logger?.trace('DefaultDecoderCore.decode();', { action, serial: message.serial, name: message.name });\n\n let outputs: DecoderOutput<TEvent, TMessage>[];\n\n switch (action) {\n // Spec: AIT-CD7a\n case 'message.create': {\n const payload = this._toPayload(message);\n\n outputs =\n payload.headers?.[HEADER_STREAM] === 'true'\n ? this._decodeStreamedCreate(payload, message.serial)\n : this._hooks.decodeDiscrete(payload);\n break;\n }\n\n case 'message.append': {\n outputs = this._decodeAppend(message);\n break;\n }\n\n case 'message.update': {\n outputs = this._decodeUpdate(message);\n break;\n }\n\n case 'message.delete': {\n outputs = this._decodeDelete(message);\n break;\n }\n\n default: {\n return [];\n }\n }\n\n // Tag all event outputs with the message ID from x-ably-msg-id for accumulator correlation.\n const messageId = getHeaders(message)[HEADER_MSG_ID];\n if (messageId) {\n for (const output of outputs) {\n if (output.kind === 'event') {\n output.messageId = messageId;\n }\n }\n }\n\n return outputs;\n }\n\n // -------------------------------------------------------------------------\n // Private: extract MessagePayload\n // -------------------------------------------------------------------------\n\n private _toPayload(message: Ably.InboundMessage): MessagePayload {\n return {\n name: message.name ?? '',\n // CAST: Ably SDK types `data` as `any`; cast to unknown is the safe boundary type.\n data: message.data as unknown,\n headers: getHeaders(message),\n };\n }\n\n /**\n * Extract string data from an Ably message, for stream accumulation paths.\n * @param message - The Ably message to extract string data from.\n * @returns The string data, or empty string if data is not a string.\n */\n private _stringData(message: Ably.InboundMessage): string {\n return typeof message.data === 'string' ? message.data : '';\n }\n\n // -------------------------------------------------------------------------\n // Private: safe callback invocation\n // -------------------------------------------------------------------------\n\n private _invokeOnStreamUpdate(tracker: StreamTrackerState): void {\n if (!this._onStreamUpdate) return;\n try {\n this._onStreamUpdate(tracker);\n } catch (error) {\n this._logger?.error('DefaultDecoderCore._invokeOnStreamUpdate(); callback threw', { error });\n }\n }\n\n private _invokeOnStreamDelete(serial: string, tracker: StreamTrackerState | undefined): void {\n if (!this._onStreamDelete) return;\n try {\n this._onStreamDelete(serial, tracker);\n } catch (error) {\n this._logger?.error('DefaultDecoderCore._invokeOnStreamDelete(); callback threw', { error });\n }\n }\n\n // -------------------------------------------------------------------------\n // Private: streamed message create\n // -------------------------------------------------------------------------\n\n private _decodeStreamedCreate(\n payload: MessagePayload,\n serial: string | undefined,\n ): DecoderOutput<TEvent, TMessage>[] {\n if (!serial) return [];\n\n const streamId = payload.headers?.[HEADER_STREAM_ID] ?? '';\n const h = payload.headers ?? {};\n\n const tracker: StreamTrackerState = {\n name: payload.name,\n streamId,\n accumulated: '',\n headers: { ...h },\n closed: false,\n };\n this._serialState.set(serial, tracker);\n\n this._logger?.debug('DefaultDecoderCore._decodeStreamedCreate(); new stream', {\n name: payload.name,\n streamId,\n serial,\n });\n\n return this._hooks.buildStartEvents(tracker);\n }\n\n // -------------------------------------------------------------------------\n // Private: append handling\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CD8\n private _decodeAppend(message: Ably.InboundMessage): DecoderOutput<TEvent, TMessage>[] {\n const serial = message.serial;\n if (!serial) return [];\n\n const tracker = this._serialState.get(serial);\n if (!tracker) {\n // Unknown serial on append — treat as first-contact update\n return this._decodeUpdate(message);\n }\n\n const h = getHeaders(message);\n const delta = typeof message.data === 'string' ? message.data : '';\n const status = h[HEADER_STATUS];\n const outputs: DecoderOutput<TEvent, TMessage>[] = [];\n\n if (delta.length > 0) {\n tracker.accumulated += delta;\n outputs.push(...this._hooks.buildDeltaEvents(tracker, delta));\n }\n\n if (status === 'finished' && !tracker.closed) {\n tracker.closed = true;\n outputs.push(...this._hooks.buildEndEvents(tracker, h));\n this._logger?.debug('DefaultDecoderCore._decodeAppend(); stream finished', { streamId: tracker.streamId });\n } else if (status === 'aborted' && !tracker.closed) {\n tracker.closed = true;\n this._logger?.debug('DefaultDecoderCore._decodeAppend(); stream aborted', { streamId: tracker.streamId });\n }\n\n return outputs;\n }\n\n // -------------------------------------------------------------------------\n // Private: update handling (first-contact, prefix-match, replacement)\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CD9\n private _decodeUpdate(message: Ably.InboundMessage): DecoderOutput<TEvent, TMessage>[] {\n const serial = message.serial;\n if (!serial) return [];\n\n const payload = this._toPayload(message);\n const h = payload.headers ?? {};\n const isStreamed = h[HEADER_STREAM] === 'true';\n const status = h[HEADER_STATUS];\n\n const tracker = this._serialState.get(serial);\n\n if (!tracker) {\n return this._decodeFirstContact(payload, isStreamed, status, serial);\n }\n\n // Updates to tracked streams use string data for prefix-match accumulation\n const data = this._stringData(message);\n\n // --- Tracker exists: prefix-match or replacement ---\n if (data.startsWith(tracker.accumulated)) {\n const delta = data.slice(tracker.accumulated.length);\n const outputs: DecoderOutput<TEvent, TMessage>[] = [];\n\n if (delta.length > 0) {\n tracker.accumulated = data;\n outputs.push(...this._hooks.buildDeltaEvents(tracker, delta));\n }\n\n if (status === 'finished' && !tracker.closed) {\n tracker.closed = true;\n outputs.push(...this._hooks.buildEndEvents(tracker, h));\n } else if (status === 'aborted' && !tracker.closed) {\n tracker.closed = true;\n }\n\n return outputs;\n }\n\n // --- Replacement (NOT a prefix match) ---\n tracker.accumulated = data;\n tracker.headers = { ...h };\n\n this._invokeOnStreamUpdate(tracker);\n\n return [];\n }\n\n private _decodeFirstContact(\n payload: MessagePayload,\n isStreamed: boolean,\n status: string | undefined,\n serial: string,\n ): DecoderOutput<TEvent, TMessage>[] {\n // Non-streamed messages are discrete\n if (!isStreamed) {\n return this._hooks.decodeDiscrete(payload);\n }\n\n const streamId = payload.headers?.[HEADER_STREAM_ID] ?? '';\n const h = payload.headers ?? {};\n const data = typeof payload.data === 'string' ? payload.data : '';\n\n this._logger?.debug('DefaultDecoderCore._decodeFirstContact(); first-contact stream', {\n name: payload.name,\n streamId,\n serial,\n });\n\n // Create tracker\n const newTracker: StreamTrackerState = {\n name: payload.name,\n streamId,\n accumulated: data,\n headers: { ...h },\n closed: status === 'finished' || status === 'aborted',\n };\n this._serialState.set(serial, newTracker);\n\n // Emit start + delta (if any) + end (if finished)\n const outputs = this._hooks.buildStartEvents(newTracker);\n\n if (data.length > 0) {\n outputs.push(...this._hooks.buildDeltaEvents(newTracker, data));\n }\n\n if (status === 'finished') {\n outputs.push(...this._hooks.buildEndEvents(newTracker, h));\n }\n\n return outputs;\n }\n\n // -------------------------------------------------------------------------\n // Private: delete handling\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CD10\n private _decodeDelete(message: Ably.InboundMessage): DecoderOutput<TEvent, TMessage>[] {\n const serial = message.serial;\n if (!serial) return [];\n\n const tracker = this._serialState.get(serial);\n\n this._invokeOnStreamDelete(serial, tracker);\n\n if (tracker) {\n tracker.accumulated = '';\n tracker.closed = true;\n }\n\n this._logger?.debug('DefaultDecoderCore._decodeDelete();', { serial });\n\n return [];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a decoder core with the given domain hooks.\n * @param hooks - Domain-specific hooks for stream classification, event building, and discrete decoding.\n * @param options - Decoder configuration (callbacks, logger).\n * @returns A new {@link DecoderCore} instance.\n */\nexport const createDecoderCore = <TEvent, TMessage>(\n hooks: DecoderCoreHooks<TEvent, TMessage>,\n options: DecoderCoreOptions = {},\n): DecoderCore<TEvent, TMessage> => new DefaultDecoderCore(hooks, options);\n","/**\n * Generic lifecycle tracker for codec decoders.\n *\n * Manages per-scope (typically per-turn) tracking of lifecycle phases that\n * must be emitted before content events. When a phase has not been emitted\n * (e.g. mid-stream join), the tracker synthesizes the missing events using\n * codec-provided build functions.\n *\n * Codecs configure the tracker with an ordered list of phases, then compose\n * it into their decoder hooks. The tracker is independent of any specific\n * codec or event type.\n */\n\n// ---------------------------------------------------------------------------\n// Phase configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration for a single lifecycle phase that may need to be\n * synthesized when missing from the wire stream.\n */\nexport interface PhaseConfig<TEvent> {\n /** Unique key identifying this phase (e.g. \"start\", \"start-step\"). */\n key: string;\n /**\n * Build the synthetic event(s) for this phase. Called with a context\n * record that codecs populate at the call site — the tracker passes\n * it through without interpreting it.\n * @param context - Key-value pairs from the call site (e.g. headers).\n * @returns One or more synthetic events to emit for this phase.\n */\n build(context: Record<string, string | undefined>): TEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Tracker interface\n// ---------------------------------------------------------------------------\n\n/**\n * Per-scope lifecycle tracker that ensures required phases are emitted\n * before content events, synthesizing missing ones for mid-stream joins.\n *\n * Scoped by an arbitrary string key (typically a turn ID). Each scope\n * tracks independently which phases have been emitted.\n */\nexport interface LifecycleTracker<TEvent> {\n /**\n * Ensure all configured phases have been emitted for the given scope.\n * Returns synthetic events for any phases not yet marked as emitted,\n * then marks them. Returns an empty array if all phases are current.\n * @param scopeId - The scope to check (e.g. turn ID).\n * @param context - Key-value pairs passed through to phase build functions.\n * @returns Synthetic events for missing phases, in configuration order.\n */\n ensurePhases(scopeId: string, context: Record<string, string | undefined>): TEvent[];\n\n /**\n * Mark a phase as emitted from the wire (not synthetic). Call this\n * when the real event arrives so the tracker does not re-synthesize it.\n * @param scopeId - The scope (e.g. turn ID).\n * @param phaseKey - The phase key to mark.\n */\n markEmitted(scopeId: string, phaseKey: string): void;\n\n /**\n * Reset a phase so it will be re-synthesized on the next\n * {@link ensurePhases} call. Used for repeating phases (e.g. \"start-step\"\n * resets after \"finish-step\").\n * @param scopeId - The scope (e.g. turn ID).\n * @param phaseKey - The phase key to reset.\n */\n resetPhase(scopeId: string, phaseKey: string): void;\n\n /**\n * Remove all tracking state for a scope. Call on turn completion\n * (finish, abort) to free memory.\n * @param scopeId - The scope to clear.\n */\n clearScope(scopeId: string): void;\n}\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CD13\nclass DefaultLifecycleTracker<TEvent> implements LifecycleTracker<TEvent> {\n private readonly _phases: PhaseConfig<TEvent>[];\n private readonly _emitted = new Map<string, Set<string>>();\n\n constructor(phases: PhaseConfig<TEvent>[]) {\n this._phases = phases;\n }\n\n ensurePhases(scopeId: string, context: Record<string, string | undefined>): TEvent[] {\n const emitted = this._getOrCreate(scopeId);\n const events: TEvent[] = [];\n for (const phase of this._phases) {\n if (!emitted.has(phase.key)) {\n emitted.add(phase.key);\n events.push(...phase.build(context));\n }\n }\n return events;\n }\n\n markEmitted(scopeId: string, phaseKey: string): void {\n this._getOrCreate(scopeId).add(phaseKey);\n }\n\n resetPhase(scopeId: string, phaseKey: string): void {\n this._emitted.get(scopeId)?.delete(phaseKey);\n }\n\n clearScope(scopeId: string): void {\n this._emitted.delete(scopeId);\n }\n\n private _getOrCreate(scopeId: string): Set<string> {\n let set = this._emitted.get(scopeId);\n if (!set) {\n set = new Set();\n this._emitted.set(scopeId, set);\n }\n return set;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a lifecycle tracker configured with the given phases.\n * Phases are checked and synthesized in array order.\n * @param phases - Ordered phase configurations.\n * @returns A new {@link LifecycleTracker} instance.\n */\nexport const createLifecycleTracker = <TEvent>(phases: PhaseConfig<TEvent>[]): LifecycleTracker<TEvent> =>\n new DefaultLifecycleTracker(phases);\n","/**\n * Vercel AI SDK Decoder\n *\n * Maps Ably inbound messages to DecoderOutput<UIMessageChunk, UIMessage>[].\n *\n * Delegates action dispatch and serial tracking to the decoder core.\n * This file contains only the Vercel-specific event building, discrete\n * event decoding, and synthetic event emission.\n *\n * Domain-specific headers use the `x-domain-` prefix. Transport-level\n * headers use the `x-ably-` prefix.\n */\n\nimport type * as Ably from 'ably';\nimport type * as AI from 'ai';\n\nimport { HEADER_ROLE, HEADER_TURN_ID } from '../../constants.js';\nimport type { DecoderCore, DecoderCoreHooks, DecoderCoreOptions } from '../../core/codec/decoder.js';\nimport { createDecoderCore, eventOutput } from '../../core/codec/decoder.js';\nimport type { LifecycleTracker } from '../../core/codec/lifecycle-tracker.js';\nimport { createLifecycleTracker } from '../../core/codec/lifecycle-tracker.js';\nimport type { DecoderOutput, MessagePayload, StreamDecoder, StreamTrackerState } from '../../core/codec/types.js';\nimport { type DomainHeaderReader, headerReader as rawHeaderReader, stripUndefined } from '../../utils.js';\n\n// ---------------------------------------------------------------------------\n// Vercel-specific header reader (casts providerMetadata to AI.ProviderMetadata)\n// ---------------------------------------------------------------------------\n\ninterface VercelHeaderReader extends DomainHeaderReader {\n /** Read the `providerMetadata` domain header, cast to the AI SDK type. */\n providerMetadata(): AI.ProviderMetadata | undefined;\n}\n\n/**\n * Create a header reader that adds Vercel-specific `providerMetadata` typing.\n * @param headers - The raw headers record to read domain headers from.\n * @returns A typed accessor with Vercel-specific providerMetadata typing.\n */\nconst headerReader = (headers: Record<string, string>): VercelHeaderReader => {\n const base = rawHeaderReader(headers);\n return {\n ...base,\n // CAST: Trust boundary — the encoder serialized a valid ProviderMetadata value.\n providerMetadata: () => base.json('providerMetadata') as AI.ProviderMetadata | undefined,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Wire format types (trust boundaries for JSON-parsed data)\n// ---------------------------------------------------------------------------\n\n/** Wire format for tool-input-error data payload. */\ninterface ToolInputErrorWireData {\n errorText?: string;\n input?: unknown;\n}\n\n/** Wire format for tool-output-available data payload. */\ninterface ToolOutputAvailableWireData {\n output?: unknown;\n}\n\n/** Wire format for tool-output-error data payload. */\ninterface ToolOutputErrorWireData {\n errorText?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Shared output type alias\n// ---------------------------------------------------------------------------\n\ntype Out = DecoderOutput<AI.UIMessageChunk, AI.UIMessage>;\n\n/**\n * Bind eventOutput to the Vercel domain types.\n * @param chunk - The UIMessageChunk to wrap.\n * @returns A single-element decoder output array.\n */\nconst event = (chunk: AI.UIMessageChunk): Out[] => eventOutput<AI.UIMessageChunk, AI.UIMessage>(chunk);\n\n// ---------------------------------------------------------------------------\n// JSON boundary helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Validate a finish reason string against the FinishReason union.\n * @param value - The finish reason string from the wire, or undefined.\n * @param fallback - Default finish reason if the value is not recognized.\n * @returns The validated FinishReason.\n */\nconst parseFinishReason = (value: string | undefined, fallback: AI.FinishReason): AI.FinishReason => {\n if (\n value === 'stop' ||\n value === 'length' ||\n value === 'content-filter' ||\n value === 'tool-calls' ||\n value === 'error' ||\n value === 'other'\n ) {\n return value;\n }\n return fallback;\n};\n\n/**\n * Type predicate for data-* message names.\n * @param name - The message name to check.\n * @returns True if the name starts with \"data-\".\n */\nconst isDataEventName = (name: string): name is `data-${string}` => name.startsWith('data-');\n\n/**\n * Parse a string as JSON, returning the raw string if parsing fails\n * or undefined if empty.\n * @param value - The string to attempt JSON parsing on.\n * @returns The parsed value, the raw string on parse failure, or undefined if empty.\n */\nconst parseJsonOrString = (value: string): unknown => {\n if (!value) return undefined;\n try {\n // CAST: JSON.parse returns any; unknown is the safe trust-boundary type.\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Streamed message event builders\n// ---------------------------------------------------------------------------\n\nconst buildStartChunk = (tracker: StreamTrackerState): AI.UIMessageChunk => {\n const r = headerReader(tracker.headers);\n switch (tracker.name) {\n case 'text': {\n return stripUndefined({\n type: 'text-start' as const,\n id: tracker.streamId,\n providerMetadata: r.providerMetadata(),\n });\n }\n case 'reasoning': {\n return stripUndefined({\n type: 'reasoning-start' as const,\n id: tracker.streamId,\n providerMetadata: r.providerMetadata(),\n });\n }\n case 'tool-input': {\n return stripUndefined({\n type: 'tool-input-start' as const,\n toolCallId: tracker.streamId,\n toolName: r.strOr('toolName', ''),\n dynamic: r.bool('dynamic'),\n title: r.str('title'),\n providerExecuted: r.bool('providerExecuted'),\n providerMetadata: r.providerMetadata(),\n });\n }\n default: {\n return { type: 'text-start', id: tracker.streamId };\n }\n }\n};\n\nconst buildDeltaChunk = (tracker: StreamTrackerState, delta: string): AI.UIMessageChunk => {\n switch (tracker.name) {\n case 'text': {\n return { type: 'text-delta', id: tracker.streamId, delta };\n }\n case 'reasoning': {\n return { type: 'reasoning-delta', id: tracker.streamId, delta };\n }\n case 'tool-input': {\n return { type: 'tool-input-delta', toolCallId: tracker.streamId, inputTextDelta: delta };\n }\n default: {\n return { type: 'text-delta', id: tracker.streamId, delta };\n }\n }\n};\n\nconst buildEndChunk = (tracker: StreamTrackerState, closingHeaders: Record<string, string>): AI.UIMessageChunk => {\n const r = headerReader(closingHeaders);\n switch (tracker.name) {\n case 'text': {\n return stripUndefined({\n type: 'text-end' as const,\n id: tracker.streamId,\n providerMetadata: r.providerMetadata(),\n });\n }\n case 'reasoning': {\n return stripUndefined({\n type: 'reasoning-end' as const,\n id: tracker.streamId,\n providerMetadata: r.providerMetadata(),\n });\n }\n case 'tool-input': {\n return stripUndefined({\n type: 'tool-input-available' as const,\n toolCallId: tracker.streamId,\n toolName: r.strOr('toolName', headerReader(tracker.headers).strOr('toolName', '')),\n input: parseJsonOrString(tracker.accumulated),\n providerMetadata: r.providerMetadata(),\n });\n }\n default: {\n return { type: 'text-end', id: tracker.streamId };\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Lifecycle tracker configuration (synthetic event phases)\n// ---------------------------------------------------------------------------\n\nconst createVercelLifecycleTracker = (): LifecycleTracker<AI.UIMessageChunk> =>\n createLifecycleTracker<AI.UIMessageChunk>([\n {\n key: 'start',\n build: (ctx) => [stripUndefined({ type: 'start' as const, messageId: ctx.messageId })],\n },\n {\n key: 'start-step',\n build: () => [{ type: 'start-step' as const }],\n },\n ]);\n\n/**\n * Run the lifecycle tracker and wrap results as DecoderOutput events.\n * @param lifecycle - The lifecycle tracker instance.\n * @param turnId - The turn scope ID.\n * @param context - Context passed through to phase build functions.\n * @returns Decoder outputs for any synthesized lifecycle events.\n */\nconst ensurePhases = (\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n turnId: string,\n context: Record<string, string | undefined>,\n): Out[] => lifecycle.ensurePhases(turnId, context).map((e) => ({ kind: 'event', event: e }));\n\n// ---------------------------------------------------------------------------\n// Discrete event decoders (one function per event type)\n// ---------------------------------------------------------------------------\n\nconst decodeStart = (r: VercelHeaderReader, turnId: string, lifecycle: LifecycleTracker<AI.UIMessageChunk>): Out[] => {\n lifecycle.markEmitted(turnId, 'start');\n return event(\n stripUndefined({\n type: 'start' as const,\n messageId: r.str('messageId'),\n messageMetadata: r.json('messageMetadata'),\n }),\n );\n};\n\nconst decodeStartStep = (turnId: string, lifecycle: LifecycleTracker<AI.UIMessageChunk>): Out[] => {\n lifecycle.markEmitted(turnId, 'start-step');\n return event({ type: 'start-step' });\n};\n\nconst decodeFinishStep = (turnId: string, lifecycle: LifecycleTracker<AI.UIMessageChunk>): Out[] => {\n lifecycle.resetPhase(turnId, 'start-step');\n return event({ type: 'finish-step' });\n};\n\nconst decodeFinish = (r: VercelHeaderReader, turnId: string, lifecycle: LifecycleTracker<AI.UIMessageChunk>): Out[] => {\n lifecycle.clearScope(turnId);\n return event(\n stripUndefined({\n type: 'finish' as const,\n finishReason: parseFinishReason(r.str('finishReason'), 'stop'),\n messageMetadata: r.json('messageMetadata'),\n }),\n );\n};\n\nconst decodeError = (data: unknown): Out[] => {\n const errorText = typeof data === 'string' ? data : '';\n return event({ type: 'error', errorText });\n};\n\nconst decodeAbort = (data: unknown, turnId: string, lifecycle: LifecycleTracker<AI.UIMessageChunk>): Out[] => {\n lifecycle.clearScope(turnId);\n const reason = typeof data === 'string' && data ? data : undefined;\n return event(stripUndefined({ type: 'abort' as const, reason }));\n};\n\nconst decodeMessageMetadata = (r: VercelHeaderReader): Out[] =>\n event({ type: 'message-metadata', messageMetadata: r.json('messageMetadata') });\n\nconst decodeFile = (r: VercelHeaderReader, data: unknown): Out[] =>\n event(\n stripUndefined({\n type: 'file' as const,\n url: typeof data === 'string' ? data : '',\n mediaType: r.strOr('mediaType', ''),\n providerMetadata: r.providerMetadata(),\n }),\n );\n\nconst decodeSourceUrl = (r: VercelHeaderReader, data: unknown): Out[] =>\n event(\n stripUndefined({\n type: 'source-url' as const,\n sourceId: r.strOr('sourceId', ''),\n url: typeof data === 'string' ? data : '',\n title: r.str('title'),\n providerMetadata: r.providerMetadata(),\n }),\n );\n\nconst decodeSourceDocument = (r: VercelHeaderReader): Out[] =>\n event(\n stripUndefined({\n type: 'source-document' as const,\n sourceId: r.strOr('sourceId', ''),\n mediaType: r.strOr('mediaType', ''),\n title: r.strOr('title', ''),\n filename: r.str('filename'),\n providerMetadata: r.providerMetadata(),\n }),\n );\n\nconst decodeToolInputError = (r: VercelHeaderReader, data: unknown): Out[] => {\n // CAST: Trust boundary — encoder produced the expected object shape.\n const parsed = data as ToolInputErrorWireData | undefined;\n return event(\n stripUndefined({\n type: 'tool-input-error' as const,\n toolCallId: r.strOr('toolCallId', ''),\n toolName: r.strOr('toolName', ''),\n errorText: parsed?.errorText ?? '',\n input: parsed?.input,\n dynamic: r.bool('dynamic'),\n title: r.str('title'),\n providerExecuted: r.bool('providerExecuted'),\n providerMetadata: r.providerMetadata(),\n }),\n );\n};\n\nconst decodeToolOutputAvailable = (r: VercelHeaderReader, data: unknown): Out[] => {\n // CAST: Trust boundary — encoder produced the expected object shape.\n const parsed = data as ToolOutputAvailableWireData | undefined;\n return event(\n stripUndefined({\n type: 'tool-output-available' as const,\n toolCallId: r.strOr('toolCallId', ''),\n output: parsed?.output,\n dynamic: r.bool('dynamic'),\n providerExecuted: r.bool('providerExecuted'),\n preliminary: r.bool('preliminary'),\n }),\n );\n};\n\nconst decodeToolOutputError = (r: VercelHeaderReader, data: unknown): Out[] => {\n // CAST: Trust boundary — encoder produced the expected object shape.\n const parsed = data as ToolOutputErrorWireData | undefined;\n return event(\n stripUndefined({\n type: 'tool-output-error' as const,\n toolCallId: r.strOr('toolCallId', ''),\n errorText: parsed?.errorText ?? '',\n dynamic: r.bool('dynamic'),\n providerExecuted: r.bool('providerExecuted'),\n }),\n );\n};\n\nconst decodeToolApprovalRequest = (r: VercelHeaderReader): Out[] =>\n event({\n type: 'tool-approval-request',\n toolCallId: r.strOr('toolCallId', ''),\n approvalId: r.strOr('approvalId', ''),\n });\n\nconst decodeToolOutputDenied = (r: VercelHeaderReader): Out[] =>\n event({ type: 'tool-output-denied', toolCallId: r.strOr('toolCallId', '') });\n\nconst decodeDataEvent = (name: `data-${string}`, r: VercelHeaderReader, data: unknown): Out[] =>\n event(\n stripUndefined({\n type: name,\n data,\n id: r.str('id'),\n transient: r.bool('transient'),\n }),\n );\n\n// ---------------------------------------------------------------------------\n// Non-streaming tool-input helper\n// ---------------------------------------------------------------------------\n\nconst decodeNonStreamingToolInput = (\n r: VercelHeaderReader,\n data: unknown,\n turnId: string,\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n): Out[] => {\n const outputs = ensurePhases(lifecycle, turnId, { messageId: r.str('messageId') });\n\n outputs.push(\n {\n kind: 'event',\n event: stripUndefined({\n type: 'tool-input-start' as const,\n toolCallId: r.strOr('toolCallId', ''),\n toolName: r.strOr('toolName', ''),\n dynamic: r.bool('dynamic'),\n title: r.str('title'),\n providerExecuted: r.bool('providerExecuted'),\n providerMetadata: r.providerMetadata(),\n }),\n },\n {\n kind: 'event',\n event: stripUndefined({\n type: 'tool-input-available' as const,\n toolCallId: r.strOr('toolCallId', ''),\n toolName: r.strOr('toolName', ''),\n input: data,\n providerMetadata: r.providerMetadata(),\n }),\n },\n );\n\n return outputs;\n};\n\n// ---------------------------------------------------------------------------\n// Discrete event dispatch\n// ---------------------------------------------------------------------------\n\n/**\n * Reconstruct a UIMessage from a discrete message part published by writeMessages.\n * The encoder splits each UIMessage into per-part Ably messages with a shared\n * x-domain-messageId. This function rebuilds a single-part UIMessage from one\n * such Ably message. The transport's tree upsert merges parts that share the\n * same x-ably-msg-id, so multi-part messages accumulate correctly over\n * successive decoder calls.\n * @param input - The discrete message payload to decode.\n * @returns A single-element array with the reconstructed UIMessage, or empty if unrecognized.\n */\nconst decodeDiscreteMessage = (input: MessagePayload): Out[] => {\n const h = input.headers ?? {};\n const r = headerReader(h);\n const role = (h[HEADER_ROLE] ?? 'user') as AI.UIMessage['role'];\n const messageId = r.str('messageId') ?? '';\n\n let part: AI.UIMessage['parts'][number] | undefined;\n\n switch (input.name) {\n case 'text': {\n part = { type: 'text', text: typeof input.data === 'string' ? input.data : '' };\n break;\n }\n case 'file': {\n part = {\n type: 'file',\n mediaType: r.strOr('mediaType', ''),\n url: typeof input.data === 'string' ? input.data : '',\n };\n break;\n }\n default: {\n if (isDataEventName(input.name)) {\n // CAST: data-* part type matches the DataUIPart shape.\n part = stripUndefined({ type: input.name, id: r.str('id'), data: input.data }) as AI.UIMessage['parts'][number];\n }\n break;\n }\n }\n\n if (!part) return [];\n\n const message: AI.UIMessage = { id: messageId, role, parts: [part] };\n return [{ kind: 'message', message }];\n};\n\n/**\n * Whether a message name represents a discrete message part (written by writeMessages)\n * rather than a streaming lifecycle event. Discrete message parts carry x-ably-role\n * and encode a single UIMessage part each.\n * @param name - The Ably message name to check.\n * @param headers - The Ably message headers to inspect for role presence.\n * @returns True if this is a discrete message part, false if it's a lifecycle event.\n */\nconst isDiscreteMessagePart = (name: string, headers: Record<string, string>): boolean =>\n (name === 'text' || name === 'file' || isDataEventName(name)) && HEADER_ROLE in headers;\n\nconst decodeDiscretePayload = (input: MessagePayload, lifecycle: LifecycleTracker<AI.UIMessageChunk>): Out[] => {\n const h = input.headers ?? {};\n const r = headerReader(h);\n const turnId = h[HEADER_TURN_ID] ?? '';\n\n // Discrete message parts from writeMessages (user messages, history entries).\n // Distinguished from lifecycle events by the presence of x-ably-role.\n if (isDiscreteMessagePart(input.name, h)) {\n return decodeDiscreteMessage(input);\n }\n\n if (input.name === 'tool-input') {\n return decodeNonStreamingToolInput(r, input.data, turnId, lifecycle);\n }\n\n switch (input.name) {\n case 'start': {\n return decodeStart(r, turnId, lifecycle);\n }\n case 'start-step': {\n return decodeStartStep(turnId, lifecycle);\n }\n case 'finish-step': {\n return decodeFinishStep(turnId, lifecycle);\n }\n case 'finish': {\n return decodeFinish(r, turnId, lifecycle);\n }\n case 'error': {\n return decodeError(input.data);\n }\n case 'abort': {\n return decodeAbort(input.data, turnId, lifecycle);\n }\n case 'message-metadata': {\n return decodeMessageMetadata(r);\n }\n case 'file': {\n return decodeFile(r, input.data);\n }\n case 'source-url': {\n return decodeSourceUrl(r, input.data);\n }\n case 'source-document': {\n return decodeSourceDocument(r);\n }\n case 'tool-input-error': {\n return decodeToolInputError(r, input.data);\n }\n case 'tool-output-available': {\n return decodeToolOutputAvailable(r, input.data);\n }\n case 'tool-output-error': {\n return decodeToolOutputError(r, input.data);\n }\n case 'tool-approval-request': {\n return decodeToolApprovalRequest(r);\n }\n case 'tool-output-denied': {\n return decodeToolOutputDenied(r);\n }\n default: {\n return isDataEventName(input.name) ? decodeDataEvent(input.name, r, input.data) : [];\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Decoder core hooks\n// ---------------------------------------------------------------------------\n\nconst createHooks = (\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n): DecoderCoreHooks<AI.UIMessageChunk, AI.UIMessage> => ({\n buildStartEvents: (tracker: StreamTrackerState): Out[] => {\n const turnId = tracker.headers[HEADER_TURN_ID] ?? '';\n const messageId = headerReader(tracker.headers).str('messageId');\n const outputs = ensurePhases(lifecycle, turnId, { messageId });\n outputs.push({ kind: 'event', event: buildStartChunk(tracker) });\n return outputs;\n },\n\n buildDeltaEvents: (tracker: StreamTrackerState, delta: string): Out[] => event(buildDeltaChunk(tracker, delta)),\n\n buildEndEvents: (tracker: StreamTrackerState, closingHeaders: Record<string, string>): Out[] =>\n event(buildEndChunk(tracker, closingHeaders)),\n\n decodeDiscrete: (payload: MessagePayload): Out[] => decodeDiscretePayload(payload, lifecycle),\n});\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\nclass DefaultUIMessageDecoder implements StreamDecoder<AI.UIMessageChunk, AI.UIMessage> {\n private readonly _core: DecoderCore<AI.UIMessageChunk, AI.UIMessage>;\n\n constructor(options: DecoderCoreOptions = {}) {\n this._core = createDecoderCore<AI.UIMessageChunk, AI.UIMessage>(\n createHooks(createVercelLifecycleTracker()),\n options,\n );\n }\n\n decode(message: Ably.InboundMessage): Out[] {\n return this._core.decode(message);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Vercel AI SDK decoder that maps Ably messages to UIMessageChunk\n * events and UIMessage objects via the decoder core.\n * @param options - Decoder configuration (callbacks, logger).\n * @returns A {@link StreamDecoder} for UIMessageChunk/UIMessage.\n */\nexport const createDecoder = (options: DecoderCoreOptions = {}): StreamDecoder<AI.UIMessageChunk, AI.UIMessage> =>\n new DefaultUIMessageDecoder(options);\n","import * as Ably from 'ably';\n\n/**\n * Error codes for the AI Transport SDK.\n */\nexport enum ErrorCode {\n /**\n * The request was invalid.\n */\n BadRequest = 40000,\n\n /**\n * Invalid argument provided.\n */\n InvalidArgument = 40003,\n\n // 104000 - 104999 are reserved for AI Transport SDK errors\n\n /**\n * Encoder recovery failed after flush — one or more updateMessage calls\n * could not recover a failed append pipeline.\n */\n EncoderRecoveryFailed = 104000,\n\n /**\n * A transport-level channel subscription callback threw unexpectedly.\n */\n TransportSubscriptionError = 104001,\n\n /**\n * Cancel listener or onCancel hook threw while processing a cancel message.\n */\n CancelListenerError = 104002,\n\n /**\n * A turn lifecycle event (turn-start or turn-end) failed to publish.\n */\n TurnLifecycleError = 104003,\n\n /**\n * An operation was attempted on a transport that has already been closed.\n */\n TransportClosed = 104004,\n\n /**\n * The HTTP POST to the server endpoint failed (network error or non-2xx response).\n */\n TransportSendFailed = 104005,\n}\n\n/**\n * Returns true if the {@link Ably.ErrorInfo} code matches the provided ErrorCode value.\n * @param errorInfo The error info to check.\n * @param error The error code to compare against.\n * @returns true if the error code matches, false otherwise.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\nexport const errorInfoIs = (errorInfo: Ably.ErrorInfo, error: ErrorCode): boolean => errorInfo.code === error;\n","/**\n * Encoder core — message append lifecycle machinery.\n *\n * Provides Ably primitives (publish, append, close, abort, flush) that\n * domain-specific encoders wire their event types to.\n *\n * Domain encoders call `createEncoderCore(writer, options)` and use the\n * returned core to map domain events to Ably operations without\n * reimplementing the message append lifecycle.\n */\n\nimport * as Ably from 'ably';\n\nimport { HEADER_MSG_ID, HEADER_STATUS, HEADER_STREAM, HEADER_STREAM_ID } from '../../constants.js';\nimport { ErrorCode } from '../../errors.js';\nimport type { Logger } from '../../logger.js';\nimport { mergeHeaders } from '../../utils.js';\nimport type { ChannelWriter, EncoderOptions, Extras, MessagePayload, StreamPayload, WriteOptions } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for creating an encoder core. Extends {@link EncoderOptions} with a logger. */\nexport interface EncoderCoreOptions extends EncoderOptions {\n /** Logger instance for diagnostic output. */\n logger?: Logger;\n}\n\n// ---------------------------------------------------------------------------\n// Stream tracker (internal)\n// ---------------------------------------------------------------------------\n\ninterface StreamState {\n serial: string;\n name: string;\n streamId: string;\n accumulated: string;\n persistentHeaders: Record<string, string>;\n aborted: boolean;\n}\n\ninterface PendingAppend {\n promise: Promise<Ably.UpdateDeleteResult>;\n streamId: string;\n}\n\n// ---------------------------------------------------------------------------\n// Encoder core interface\n// ---------------------------------------------------------------------------\n\n/** The core encoder primitives that domain codec encoders delegate to. */\nexport interface EncoderCore {\n /** Publish a single discrete (non-streaming) message described by a payload. */\n publishDiscrete(payload: MessagePayload, opts?: WriteOptions): Promise<Ably.PublishResult>;\n\n /** Publish multiple discrete messages atomically in a single channel publish. */\n publishDiscreteBatch(payloads: MessagePayload[], opts?: WriteOptions): Promise<Ably.PublishResult>;\n\n /** Start a streamed message with x-ably-status:streaming. */\n startStream(streamId: string, payload: StreamPayload, opts?: WriteOptions): Promise<void>;\n\n /**\n * Append data to an in-flight streamed message. Fire-and-forget: errors are\n * collected internally and surfaced by {@link closeStream} or {@link close}.\n */\n appendStream(streamId: string, data: string): void;\n\n /**\n * Close a streamed message with x-ably-status:finished. Flushes all pending\n * appends for recovery before returning. Repeats persistent and payload headers.\n */\n closeStream(streamId: string, payload: StreamPayload): Promise<void>;\n\n /**\n * Abort a single in-progress stream (x-ably-status:aborted) and flush all\n * pending appends for recovery before returning.\n */\n abortStream(streamId: string, opts?: WriteOptions): Promise<void>;\n\n /**\n * Abort all in-progress streams (x-ably-status:aborted) and flush all\n * pending appends for recovery before returning.\n */\n abortAllStreams(opts?: WriteOptions): Promise<void>;\n\n /** Flush + clear trackers. Idempotent. */\n close(): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CD1\nclass DefaultEncoderCore implements EncoderCore {\n private readonly _writer: ChannelWriter;\n private readonly _defaultClientId: string | undefined;\n private readonly _defaultExtras: Extras | undefined;\n private readonly _onMessageHook: (message: Ably.Message) => void;\n private readonly _logger: Logger | undefined;\n private readonly _trackers = new Map<string, StreamState>();\n private _pending: PendingAppend[] = [];\n private _flushPromise: Promise<void> | undefined;\n private _closed = false;\n\n constructor(writer: ChannelWriter, options: EncoderCoreOptions = {}) {\n this._writer = writer;\n this._defaultClientId = options.clientId;\n this._defaultExtras = options.extras;\n this._onMessageHook =\n options.onMessage ??\n (() => {\n /* noop */\n });\n this._logger = options.logger?.withContext({ component: 'EncoderCore' });\n }\n\n // Spec: AIT-CD11\n async publishDiscrete(payload: MessagePayload, opts?: WriteOptions): Promise<Ably.PublishResult> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.publishDiscrete();', { name: payload.name });\n const msg = this._buildDiscreteMessage(payload, opts);\n return this._writer.publish(msg);\n }\n\n // Spec: AIT-CD11a\n async publishDiscreteBatch(payloads: MessagePayload[], opts?: WriteOptions): Promise<Ably.PublishResult> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.publishDiscreteBatch();', { count: payloads.length });\n const msgs = payloads.map((p) => this._buildDiscreteMessage(p, opts));\n return this._writer.publish(msgs);\n }\n\n // Spec: AIT-CD2\n async startStream(streamId: string, payload: StreamPayload, opts?: WriteOptions): Promise<void> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.startStream();', { name: payload.name, streamId });\n\n const allHeaders = this._buildHeaders(payload.headers ?? {}, opts);\n allHeaders[HEADER_STREAM] = 'true';\n allHeaders[HEADER_STATUS] = 'streaming';\n allHeaders[HEADER_STREAM_ID] = streamId;\n\n const clientId = this._resolveClientId(opts);\n const msg: Ably.Message = {\n name: payload.name,\n data: payload.data,\n extras: { headers: allHeaders },\n ...(clientId ? { clientId } : {}),\n };\n\n this._invokeOnMessage(msg);\n const result = await this._writer.publish(msg);\n const serial = result.serials[0];\n\n if (!serial) {\n throw new Ably.ErrorInfo(\n `unable to start stream; no serial returned for stream '${payload.name}' (streamId: ${streamId})`,\n ErrorCode.BadRequest,\n 400,\n );\n }\n\n this._trackers.set(streamId, {\n serial,\n name: payload.name,\n streamId,\n accumulated: payload.data,\n persistentHeaders: allHeaders,\n aborted: false,\n });\n\n this._logger?.debug('DefaultEncoderCore.startStream(); stream started', {\n name: payload.name,\n streamId,\n serial,\n });\n }\n\n // Spec: AIT-CD3\n appendStream(streamId: string, data: string): void {\n this._assertNotClosed();\n const tracker = this._trackers.get(streamId);\n if (!tracker) {\n throw new Ably.ErrorInfo(\n `unable to append to stream; no active stream for streamId '${streamId}'`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n tracker.accumulated += data;\n\n const appendMsg: Ably.Message = {\n serial: tracker.serial,\n data,\n extras: { headers: { ...tracker.persistentHeaders } },\n };\n\n this._invokeOnMessage(appendMsg);\n const p = this._writer.appendMessage(appendMsg);\n this._pending.push({ promise: p, streamId });\n }\n\n // Spec: AIT-CD4, AIT-CD4a\n async closeStream(streamId: string, payload: StreamPayload): Promise<void> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.closeStream();', { streamId });\n\n const tracker = this._trackers.get(streamId);\n if (!tracker) {\n throw new Ably.ErrorInfo(\n `unable to close stream; no active stream for streamId '${streamId}'`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n // Accumulate closing data so recovery has the full content\n tracker.accumulated += payload.data;\n\n const allHeaders = this._buildClosingHeaders(tracker, payload.headers ?? {});\n allHeaders[HEADER_STATUS] = 'finished';\n\n const msg: Ably.Message = {\n serial: tracker.serial,\n data: payload.data,\n extras: { headers: allHeaders },\n };\n\n this._invokeOnMessage(msg);\n const p = this._writer.appendMessage(msg);\n this._pending.push({ promise: p, streamId });\n\n await this._flushPending();\n\n this._logger?.debug('DefaultEncoderCore.closeStream(); stream closed', { streamId });\n }\n\n // Spec: AIT-CD5, AIT-CD5b\n async abortStream(streamId: string, opts?: WriteOptions): Promise<void> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.abortStream();', { streamId });\n\n const tracker = this._trackers.get(streamId);\n if (!tracker) {\n throw new Ably.ErrorInfo(\n `unable to abort stream; no active stream for streamId '${streamId}'`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n tracker.aborted = true;\n\n const allHeaders = this._buildClosingHeaders(tracker, {}, opts);\n allHeaders[HEADER_STATUS] = 'aborted';\n\n const msg: Ably.Message = {\n serial: tracker.serial,\n data: '',\n extras: { headers: allHeaders },\n };\n\n this._invokeOnMessage(msg);\n const p = this._writer.appendMessage(msg);\n this._pending.push({ promise: p, streamId });\n\n await this._flushPending();\n\n this._logger?.debug('DefaultEncoderCore.abortStream(); stream aborted', { streamId });\n }\n\n // Spec: AIT-CD5a\n async abortAllStreams(opts?: WriteOptions): Promise<void> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.abortAllStreams();', { streamCount: this._trackers.size });\n\n for (const tracker of this._trackers.values()) {\n tracker.aborted = true;\n\n const allHeaders = this._buildClosingHeaders(tracker, {}, opts);\n allHeaders[HEADER_STATUS] = 'aborted';\n\n const msg: Ably.Message = {\n serial: tracker.serial,\n data: '',\n extras: { headers: allHeaders },\n };\n\n this._invokeOnMessage(msg);\n const p = this._writer.appendMessage(msg);\n this._pending.push({ promise: p, streamId: tracker.streamId });\n }\n\n await this._flushPending();\n }\n\n // Spec: AIT-CD6\n private async _flushPending(): Promise<void> {\n // Re-entrancy guard: if a flush is already in progress, await it instead of starting a new one.\n if (this._flushPromise) {\n return this._flushPromise;\n }\n\n const snapshot = this._pending;\n this._pending = [];\n\n if (snapshot.length === 0) return;\n\n this._logger?.trace('DefaultEncoderCore._flushPending();', { count: snapshot.length });\n\n this._flushPromise = this._doFlush(snapshot);\n try {\n await this._flushPromise;\n } finally {\n this._flushPromise = undefined;\n }\n }\n\n private async _doFlush(snapshot: PendingAppend[]): Promise<void> {\n const results = await Promise.allSettled(snapshot.map(async (p) => p.promise));\n const failures = new Set<string>();\n\n for (const [i, result] of results.entries()) {\n const entry = snapshot[i];\n if (entry && result.status === 'rejected') {\n failures.add(entry.streamId);\n }\n }\n\n if (failures.size === 0) {\n this._logger?.debug('DefaultEncoderCore._flushPending(); all appends succeeded');\n return;\n }\n\n this._logger?.warn('DefaultEncoderCore._flushPending(); recovering failed appends', {\n failedStreams: [...failures],\n });\n\n const recoveryErrors: { streamId: string; error: unknown }[] = [];\n\n for (const streamId of failures) {\n const tracker = this._trackers.get(streamId);\n if (!tracker) continue;\n\n const recoveryStatus = tracker.aborted ? 'aborted' : 'finished';\n const msg: Ably.Message = {\n serial: tracker.serial,\n data: tracker.accumulated,\n extras: { headers: { ...tracker.persistentHeaders, [HEADER_STATUS]: recoveryStatus } },\n };\n\n try {\n await this._writer.updateMessage(msg);\n } catch (error) {\n recoveryErrors.push({ streamId, error });\n }\n }\n\n if (recoveryErrors.length > 0) {\n const ids = recoveryErrors.map((e) => e.streamId).join(', ');\n this._logger?.error('DefaultEncoderCore._flushPending(); recovery failed', { failedStreams: ids });\n throw new Ably.ErrorInfo(\n `unable to flush pending appends; recovery failed for stream(s): ${ids}`,\n ErrorCode.EncoderRecoveryFailed,\n 500,\n );\n }\n }\n\n // Spec: AIT-CD12\n async close(): Promise<void> {\n if (this._closed) return;\n this._logger?.trace('DefaultEncoderCore.close();');\n this._closed = true;\n try {\n await this._flushPending();\n } finally {\n this._trackers.clear();\n }\n this._logger?.debug('DefaultEncoderCore.close(); encoder closed');\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CD14\n private _invokeOnMessage(msg: Ably.Message): void {\n try {\n this._onMessageHook(msg);\n } catch (error) {\n this._logger?.error('DefaultEncoderCore._invokeOnMessage(); hook threw', { error });\n }\n }\n\n private _assertNotClosed(): void {\n if (this._closed) {\n throw new Ably.ErrorInfo('unable to write to encoder; encoder has been closed', ErrorCode.InvalidArgument, 400);\n }\n }\n\n private _resolveClientId(opts?: WriteOptions): string | undefined {\n return opts?.clientId ?? this._defaultClientId;\n }\n\n private _buildHeaders(codecHeaders: Record<string, string>, opts?: WriteOptions): Record<string, string> {\n const callerHeaders = mergeHeaders(this._defaultExtras?.headers, opts?.extras?.headers);\n const merged = { ...callerHeaders, ...codecHeaders };\n if (opts?.messageId !== undefined) {\n merged[HEADER_MSG_ID] = opts.messageId;\n }\n return merged;\n }\n\n private _buildDiscreteMessage(payload: MessagePayload, opts?: WriteOptions): Ably.Message {\n const headers = this._buildHeaders(payload.headers ?? {}, opts);\n headers[HEADER_STREAM] = 'false';\n const clientId = this._resolveClientId(opts);\n\n const msg: Ably.Message = {\n name: payload.name,\n data: payload.data,\n extras: {\n headers,\n ...(payload.ephemeral ? { ephemeral: true } : {}),\n },\n ...(clientId ? { clientId } : {}),\n };\n\n this._invokeOnMessage(msg);\n return msg;\n }\n\n /**\n * Build headers for a closing append. Closing appends must repeat ALL\n * persistent headers (Ably replaces the entire extras object on append).\n * Then layer caller and codec overrides.\n * @param tracker - The stream tracker with persistent headers.\n * @param codecHeaders - Codec-layer headers to merge.\n * @param opts - Optional per-write overrides.\n * @returns Merged headers for the closing append.\n */\n private _buildClosingHeaders(\n tracker: StreamState,\n codecHeaders: Record<string, string>,\n opts?: WriteOptions,\n ): Record<string, string> {\n const h = { ...tracker.persistentHeaders };\n const callerHeaders = mergeHeaders(this._defaultExtras?.headers, opts?.extras?.headers);\n Object.assign(h, callerHeaders);\n Object.assign(h, codecHeaders);\n return h;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create an encoder core bound to the given channel writer.\n * @param writer - The channel writer to publish messages through.\n * @param options - Encoder configuration (clientId, extras, hooks, logger).\n * @returns A new {@link EncoderCore} instance.\n */\nexport const createEncoderCore = (writer: ChannelWriter, options: EncoderCoreOptions = {}): EncoderCore =>\n new DefaultEncoderCore(writer, options);\n","/**\n * Vercel AI SDK Encoder\n *\n * Maps UIMessageChunk events and complete UIMessage objects to Ably channel\n * operations (publish, appendMessage, updateMessage).\n *\n * Delegates the message append lifecycle (publish, append, close, abort,\n * flush/recover) to the encoder core. This file contains only the\n * Vercel-specific event-to-operation mapping.\n *\n * Domain-specific headers use the `x-domain-` prefix to distinguish them\n * from transport-level `x-ably-` headers.\n *\n * ## Core operations and domain headers\n *\n * Each UIMessageChunk maps to exactly one encoder core operation. Domain\n * headers are passed to every operation that accepts them — the core handles\n * merging, persistence, and deduplication:\n *\n * - **`startStream`**: Opens a message stream. Domain headers become\n * \"persistent headers\" — the core repeats them on every subsequent append.\n * - **`appendStream`**: Appends a text delta. Data only, no headers parameter.\n * The core automatically carries persistent headers from start.\n * - **`closeStream`**: Closes the stream. Pass all domain headers from the\n * chunk — the core merges them on top of persistent headers, so changed\n * values (e.g. updated providerMetadata) are picked up and unchanged\n * values are harmlessly deduplicated.\n * - **`publishDiscrete`**: Publishes a standalone message. All domain headers\n * for the chunk are passed directly.\n */\n\nimport * as Ably from 'ably';\nimport type * as AI from 'ai';\nimport { isDataUIPart } from 'ai';\n\nimport { HEADER_STATUS } from '../../constants.js';\nimport type { EncoderCore, EncoderCoreOptions } from '../../core/codec/encoder.js';\nimport { createEncoderCore } from '../../core/codec/encoder.js';\nimport type { ChannelWriter, MessagePayload, StreamEncoder, WriteOptions } from '../../core/codec/types.js';\nimport { ErrorCode, errorInfoIs } from '../../errors.js';\nimport { headerWriter } from '../../utils.js';\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\nclass DefaultUIMessageEncoder implements StreamEncoder<AI.UIMessageChunk, AI.UIMessage> {\n private readonly _core: EncoderCore;\n private _aborted = false;\n\n constructor(writer: ChannelWriter, options: EncoderCoreOptions = {}) {\n this._core = createEncoderCore(writer, options);\n }\n\n async appendEvent(chunk: AI.UIMessageChunk, perWrite?: WriteOptions): Promise<void> {\n switch (chunk.type) {\n // -- Stream start: open a message stream with persistent headers -------\n\n case 'text-start': {\n const h = headerWriter().str('id', chunk.id).json('providerMetadata', chunk.providerMetadata).build();\n await this._core.startStream(chunk.id, { name: 'text', data: '', headers: h }, perWrite);\n break;\n }\n\n case 'reasoning-start': {\n const h = headerWriter().str('id', chunk.id).json('providerMetadata', chunk.providerMetadata).build();\n await this._core.startStream(chunk.id, { name: 'reasoning', data: '', headers: h }, perWrite);\n break;\n }\n\n case 'tool-input-start': {\n const h = headerWriter()\n .str('toolCallId', chunk.toolCallId)\n .str('toolName', chunk.toolName)\n .bool('dynamic', chunk.dynamic)\n .str('title', chunk.title)\n .bool('providerExecuted', chunk.providerExecuted)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.startStream(chunk.toolCallId, { name: 'tool-input', data: '', headers: h }, perWrite);\n break;\n }\n\n // -- Stream append: data only, core carries persistent headers --------\n\n case 'text-delta': {\n this._core.appendStream(chunk.id, chunk.delta);\n break;\n }\n\n case 'reasoning-delta': {\n this._core.appendStream(chunk.id, chunk.delta);\n break;\n }\n\n case 'tool-input-delta': {\n this._core.appendStream(chunk.toolCallId, chunk.inputTextDelta);\n break;\n }\n\n // -- Stream close: pass all chunk headers, core merges with persistent\n\n case 'text-end': {\n const h = headerWriter().str('id', chunk.id).json('providerMetadata', chunk.providerMetadata).build();\n await this._core.closeStream(chunk.id, { name: 'text', data: '', headers: h });\n break;\n }\n\n case 'reasoning-end': {\n const h = headerWriter().str('id', chunk.id).json('providerMetadata', chunk.providerMetadata).build();\n await this._core.closeStream(chunk.id, { name: 'reasoning', data: '', headers: h });\n break;\n }\n\n case 'tool-input-available': {\n // If a stream tracker exists, this tool call was streamed — close it.\n // Otherwise it's a non-streaming tool call — publish discrete.\n try {\n const h = headerWriter()\n .str('toolCallId', chunk.toolCallId)\n .str('toolName', chunk.toolName)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.closeStream(chunk.toolCallId, { name: 'tool-input', data: '', headers: h });\n } catch (error: unknown) {\n // Only fall through to discrete for \"no active stream\" — rethrow real failures\n if (!(error instanceof Ably.ErrorInfo && errorInfoIs(error, ErrorCode.InvalidArgument))) {\n throw error;\n }\n const h = headerWriter()\n .str('toolCallId', chunk.toolCallId)\n .str('toolName', chunk.toolName)\n .bool('dynamic', chunk.dynamic)\n .str('title', chunk.title)\n .bool('providerExecuted', chunk.providerExecuted)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({ name: 'tool-input', data: chunk.input, headers: h });\n }\n break;\n }\n\n // -- Discrete: lifecycle events ---------------------------------------\n\n case 'start': {\n const h = headerWriter()\n .str('messageId', chunk.messageId)\n .json('messageMetadata', chunk.messageMetadata)\n .build();\n await this._core.publishDiscrete({ name: 'start', data: '', headers: h }, perWrite);\n break;\n }\n\n case 'start-step': {\n await this._core.publishDiscrete({ name: 'start-step', data: '' }, perWrite);\n break;\n }\n\n case 'finish-step': {\n await this._core.publishDiscrete({ name: 'finish-step', data: '' }, perWrite);\n break;\n }\n\n case 'finish': {\n const h = headerWriter()\n .str('finishReason', chunk.finishReason)\n .json('messageMetadata', chunk.messageMetadata)\n .build();\n await this._core.publishDiscrete({ name: 'finish', data: '', headers: h }, perWrite);\n break;\n }\n\n case 'error': {\n await this._core.publishDiscrete({ name: 'error', data: chunk.errorText }, perWrite);\n break;\n }\n\n case 'abort': {\n this._aborted = true;\n await this._core.abortAllStreams(perWrite);\n await this._core.publishDiscrete(\n { name: 'abort', data: chunk.reason ?? '', headers: { [HEADER_STATUS]: 'aborted' } },\n perWrite,\n );\n break;\n }\n\n // -- Discrete: tool lifecycle events ----------------------------------\n\n case 'tool-input-error': {\n const h = headerWriter()\n .str('toolCallId', chunk.toolCallId)\n .str('toolName', chunk.toolName)\n .bool('dynamic', chunk.dynamic)\n .str('title', chunk.title)\n .bool('providerExecuted', chunk.providerExecuted)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({\n name: 'tool-input-error',\n data: { errorText: chunk.errorText, input: chunk.input },\n headers: h,\n });\n break;\n }\n\n case 'tool-output-available': {\n const h = headerWriter()\n .str('toolCallId', chunk.toolCallId)\n .bool('dynamic', chunk.dynamic)\n .bool('providerExecuted', chunk.providerExecuted)\n .bool('preliminary', chunk.preliminary)\n .build();\n await this._core.publishDiscrete({\n name: 'tool-output-available',\n data: { output: chunk.output },\n headers: h,\n });\n break;\n }\n\n case 'tool-output-error': {\n const h = headerWriter()\n .str('toolCallId', chunk.toolCallId)\n .bool('dynamic', chunk.dynamic)\n .bool('providerExecuted', chunk.providerExecuted)\n .build();\n await this._core.publishDiscrete({\n name: 'tool-output-error',\n data: { errorText: chunk.errorText },\n headers: h,\n });\n break;\n }\n\n case 'tool-approval-request': {\n const h = headerWriter().str('toolCallId', chunk.toolCallId).str('approvalId', chunk.approvalId).build();\n await this._core.publishDiscrete({ name: 'tool-approval-request', data: '', headers: h }, perWrite);\n break;\n }\n\n case 'tool-output-denied': {\n const h = headerWriter().str('toolCallId', chunk.toolCallId).build();\n await this._core.publishDiscrete({ name: 'tool-output-denied', data: '', headers: h }, perWrite);\n break;\n }\n\n // -- Discrete: content parts ------------------------------------------\n\n case 'file': {\n const h = headerWriter()\n .str('mediaType', chunk.mediaType)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({ name: 'file', data: chunk.url, headers: h }, perWrite);\n break;\n }\n\n case 'source-url': {\n const h = headerWriter()\n .str('sourceId', chunk.sourceId)\n .str('title', chunk.title)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({ name: 'source-url', data: chunk.url, headers: h }, perWrite);\n break;\n }\n\n case 'source-document': {\n const h = headerWriter()\n .str('sourceId', chunk.sourceId)\n .str('mediaType', chunk.mediaType)\n .str('title', chunk.title)\n .str('filename', chunk.filename)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({ name: 'source-document', data: '', headers: h }, perWrite);\n break;\n }\n\n case 'message-metadata': {\n const h = headerWriter().json('messageMetadata', chunk.messageMetadata).build();\n await this._core.publishDiscrete({ name: 'message-metadata', data: '', headers: h }, perWrite);\n break;\n }\n\n // -- Discrete: data-* custom chunks -----------------------------------\n\n default: {\n if (chunk.type.startsWith('data-')) {\n const h = headerWriter().str('id', chunk.id).bool('transient', chunk.transient).build();\n const ephemeral = chunk.transient === true;\n await this._core.publishDiscrete({ name: chunk.type, data: chunk.data, headers: h, ephemeral }, perWrite);\n }\n break;\n }\n }\n }\n\n async writeEvent(chunk: AI.UIMessageChunk, perWrite?: WriteOptions): Promise<Ably.PublishResult> {\n if (!chunk.type.startsWith('data-')) {\n throw new Ably.ErrorInfo(\n `unable to write event; only data-* chunk types are supported, got '${chunk.type}'`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n const h = headerWriter()\n .str('id', 'id' in chunk ? chunk.id : undefined)\n .bool('transient', 'transient' in chunk ? chunk.transient : undefined)\n .build();\n const ephemeral = 'transient' in chunk && chunk.transient === true;\n return this._core.publishDiscrete(\n { name: chunk.type, data: 'data' in chunk ? chunk.data : undefined, headers: h, ephemeral },\n perWrite,\n );\n }\n\n async writeMessages(messages: AI.UIMessage[], perWrite?: WriteOptions): Promise<Ably.PublishResult> {\n const payloads = messages.flatMap((msg) => encodeMessagePayloads(msg));\n return this._core.publishDiscreteBatch(payloads, perWrite);\n }\n\n async abort(reason?: string): Promise<void> {\n if (this._aborted) return;\n this._aborted = true;\n await this._core.abortAllStreams();\n await this._core.publishDiscrete({\n name: 'abort',\n data: reason ?? '',\n headers: { [HEADER_STATUS]: 'aborted' },\n });\n }\n\n async close(): Promise<void> {\n await this._core.close();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Message payload encoding (stateless helper)\n// ---------------------------------------------------------------------------\n\nconst encodeMessagePayloads = (message: AI.UIMessage): MessagePayload[] => {\n const messageId = message.id;\n const payloads: MessagePayload[] = [];\n\n for (const part of message.parts) {\n switch (part.type) {\n case 'text': {\n payloads.push({ name: 'text', data: part.text, headers: headerWriter().str('messageId', messageId).build() });\n break;\n }\n case 'file': {\n payloads.push({\n name: 'file',\n data: part.url,\n headers: headerWriter().str('messageId', messageId).str('mediaType', part.mediaType).build(),\n });\n break;\n }\n default: {\n if (isDataUIPart(part)) {\n payloads.push({\n name: part.type,\n data: part.data,\n headers: headerWriter().str('messageId', messageId).str('id', part.id).build(),\n });\n }\n break;\n }\n }\n }\n\n if (payloads.length === 0) {\n payloads.push({ name: 'text', data: '', headers: headerWriter().str('messageId', messageId).build() });\n }\n\n return payloads;\n};\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Vercel AI SDK encoder that maps UIMessageChunk events to Ably\n * channel operations via the encoder core.\n * @param writer - The channel writer to publish messages through.\n * @param options - Encoder configuration (clientId, extras, hooks, logger).\n * @returns A {@link StreamEncoder} for UIMessageChunk/UIMessage.\n */\nexport const createEncoder = (\n writer: ChannelWriter,\n options: EncoderCoreOptions = {},\n): StreamEncoder<AI.UIMessageChunk, AI.UIMessage> => new DefaultUIMessageEncoder(writer, options);\n","/**\n * Vercel AI SDK codec — maps UIMessageChunk events and UIMessage objects\n * to/from native Ably message primitives (publish, append, update, delete).\n *\n * ```ts\n * import { UIMessageCodec } from '@ably/ai-transport/vercel';\n *\n * const encoder = UIMessageCodec.createEncoder(writer, options);\n * const decoder = UIMessageCodec.createDecoder();\n * const accumulator = UIMessageCodec.createAccumulator();\n * ```\n */\n\nimport type * as AI from 'ai';\n\nimport type { Codec } from '../../core/codec/types.js';\nimport { createAccumulator } from './accumulator.js';\nimport { createDecoder } from './decoder.js';\nimport { createEncoder } from './encoder.js';\n\n/**\n * Vercel AI SDK codec implementing `Codec<UIMessageChunk, UIMessage>`.\n *\n * Provides factory methods for creating encoders, decoders, and accumulators\n * that map between Vercel's UIMessageChunk/UIMessage types and Ably's native\n * message primitives.\n */\nexport const UIMessageCodec: Codec<AI.UIMessageChunk, AI.UIMessage> = {\n createEncoder,\n createDecoder,\n createAccumulator,\n\n getMessageKey: (message: AI.UIMessage): string => message.id,\n\n isTerminal: (event: AI.UIMessageChunk): boolean =>\n event.type === 'finish' || event.type === 'error' || event.type === 'abort',\n};\n","/**\n * Vercel chat transport: wraps a core ClientTransport to satisfy the\n * ChatTransport interface that useChat expects.\n *\n * This is a thin adapter — the real logic lives in the core transport.\n * The chat transport maps Vercel's sendMessages/reconnectToStream contract\n * to the core transport's send/cancel methods.\n *\n * useChat manages message state before calling sendMessages:\n * - submit-message: appends the new user message, passes the full array\n * - regenerate-message: truncates after the target, passes the truncated array\n *\n * The adapter uses `trigger` to determine the history/messages split:\n * - submit-message: last message is new (publish to channel), rest is history\n * - regenerate-message: no new messages, entire array is history\n */\n\nimport * as Ably from 'ably';\nimport type * as AI from 'ai';\n\nimport type { ClientTransport, CloseOptions, SendOptions } from '../../core/transport/types.js';\nimport { ErrorCode } from '../../errors.js';\n\n// ---------------------------------------------------------------------------\n// ChatTransport options\n// ---------------------------------------------------------------------------\n\n/**\n * Context passed to {@link ChatTransportOptions.prepareSendMessagesRequest} for\n * customizing the HTTP POST body and headers.\n */\nexport interface SendMessagesRequestContext {\n /** Chat session ID (from useChat's id). */\n id?: string;\n /** What triggered the request: user sent a message, or requested regeneration. */\n trigger: 'submit-message' | 'regenerate-message';\n /**\n * The message ID for regeneration requests. Identifies which assistant\n * message to regenerate. Undefined for submit-message.\n */\n messageId?: string;\n /** Previous messages in the conversation (context for the LLM). */\n history: AI.UIMessage[];\n /** The new message(s) being sent (to publish to the channel). Empty for regeneration. */\n messages: AI.UIMessage[];\n /** The msg-id of the message being forked (regenerated or edited). */\n forkOf?: string;\n /** The msg-id of the predecessor in the conversation thread. */\n parent?: string | null;\n}\n\n/** Options for customizing the ChatTransport behavior. */\nexport interface ChatTransportOptions {\n /**\n * Customize the POST body before sending. Called by sendMessages()\n * with the conversation context. Return the body and headers for\n * the HTTP POST.\n *\n * Default: sends all previous messages as `history` in the body.\n * @param context - The conversation context for the current request.\n * @returns The body and headers to use for the HTTP POST.\n */\n prepareSendMessagesRequest?: (context: SendMessagesRequestContext) => {\n body?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n}\n\n// ---------------------------------------------------------------------------\n// ChatTransport interface\n// ---------------------------------------------------------------------------\n\n/**\n * Additional options passed through from useChat alongside the core\n * sendMessages/reconnectToStream parameters.\n *\n * Mirrors the AI SDK's internal ChatRequestOptions type, which is not\n * exported from the `ai` package.\n */\ninterface ChatRequestOptions {\n /** Additional headers for the request. */\n headers?: Record<string, string> | Headers;\n /** Additional JSON body properties for the request. */\n body?: object;\n /** Custom metadata to attach to the request. */\n metadata?: unknown;\n}\n\n/**\n * Transport interface for Vercel AI SDK's useChat hook.\n *\n * Structurally compatible with the AI SDK's internal `ChatTransport<UIMessage>`\n * interface. Extended with `close()` for releasing the underlying Ably transport\n * resources.\n */\nexport interface ChatTransport {\n /** Send messages and return a streaming response of UIMessageChunk events. */\n sendMessages: (\n options: {\n /** The type of message submission — new message or regeneration. */\n trigger: 'submit-message' | 'regenerate-message';\n /** Unique identifier for the chat session. */\n chatId: string;\n /** ID of the message to regenerate, or undefined for new messages. */\n messageId: string | undefined;\n /** Array of UI messages representing the conversation history. */\n messages: AI.UIMessage[];\n /** Signal to abort the request if needed. */\n abortSignal: AbortSignal | undefined;\n } & ChatRequestOptions,\n ) => Promise<ReadableStream<AI.UIMessageChunk>>;\n\n /**\n * Reconnect to an existing streaming response. Returns null if no active\n * stream exists for the specified chat session.\n */\n reconnectToStream: (\n options: {\n /** Unique identifier for the chat session to reconnect to. */\n chatId: string;\n } & ChatRequestOptions,\n ) => Promise<ReadableStream<AI.UIMessageChunk> | null>;\n\n /** Close the underlying transport, releasing all resources. */\n close(options?: CloseOptions): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Vercel ChatTransport from a core ClientTransport.\n *\n * Maps Vercel's useChat contract to the core transport's methods:\n * - trigger 'submit-message' → transport.send(lastMessage) with history in body\n * - trigger 'regenerate-message' → transport.send([]) with all messages as history\n * - abortSignal → transport.cancel({ all: true })\n * - reconnectToStream → null (observer mode handles in-progress streams)\n * @param transport - The core client transport to wrap.\n * @param chatOptions - Optional hooks for customizing request construction.\n * @returns A {@link ChatTransport} compatible with Vercel's useChat hook.\n */\nexport const createChatTransport = (\n transport: ClientTransport<AI.UIMessageChunk, AI.UIMessage>,\n chatOptions?: ChatTransportOptions,\n): ChatTransport => ({\n sendMessages: async (opts) => {\n const { messages, abortSignal, trigger, messageId } = opts;\n\n // Determine the history/messages split based on trigger.\n // - submit-message: useChat appended the new user message → last is new\n // - regenerate-message: useChat truncated the array → no new messages\n let newMessages: AI.UIMessage[];\n let history: AI.UIMessage[];\n\n if (trigger === 'regenerate-message') {\n newMessages = [];\n history = messages;\n } else {\n if (messages.length === 0) {\n throw new Ably.ErrorInfo(\n 'unable to send messages; messages array is empty for submit-message trigger',\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n // CAST: length check above guarantees at least one element; .at(-1) cannot be undefined.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style -- prefer `as` over `!` per TYPES.md\n newMessages = [messages.at(-1) as AI.UIMessage];\n history = messages.slice(0, -1);\n }\n\n // Compute fork metadata from the conversation tree.\n // For regeneration: forkOf = messageId (the assistant message being regenerated),\n // parent = the parent of that message in the tree.\n let forkOf: string | undefined;\n let parent: string | null | undefined;\n\n if (trigger === 'regenerate-message' && messageId) {\n forkOf = messageId;\n // Look up the parent of the message being regenerated.\n // messageId comes from useChat (UIMessage.id), so use getNodeByKey\n // which resolves via the codec key secondary index.\n const node = transport.getTree().getNodeByKey(messageId);\n if (node) {\n // Use the tree node's msgId (x-ably-msg-id) as forkOf — this is\n // what the server stamps on the wire, not the UIMessage.id.\n forkOf = node.msgId;\n parent = node.parentId;\n }\n }\n\n let sendBody: Record<string, unknown>;\n let sendHeaders: Record<string, string> | undefined;\n\n if (chatOptions?.prepareSendMessagesRequest) {\n const prepared = chatOptions.prepareSendMessagesRequest({\n id: opts.chatId,\n trigger,\n messageId,\n history,\n messages: newMessages,\n forkOf,\n parent,\n });\n sendBody = prepared.body ?? {};\n sendHeaders = prepared.headers;\n } else {\n const historyWithHeaders = history.map((m) => ({\n message: m,\n headers: transport.getMessageHeaders(m),\n }));\n sendBody = {\n history: historyWithHeaders,\n id: opts.chatId,\n trigger,\n ...(messageId !== undefined && { messageId }),\n ...(forkOf !== undefined && { forkOf }),\n ...(parent !== undefined && { parent }),\n };\n sendHeaders = undefined;\n }\n\n const sendOpts: SendOptions = { body: sendBody, headers: sendHeaders };\n if (forkOf !== undefined) sendOpts.forkOf = forkOf;\n if (parent !== undefined) sendOpts.parent = parent;\n\n const turn = await transport.send(newMessages, sendOpts);\n\n // Wire abort signal to cancel all turns on the channel.\n // In multi-user scenarios, any client can stop any stream — cancelling\n // by specific turnId would only work for the sender.\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => void transport.cancel({ all: true }), {\n once: true,\n });\n }\n\n // Return an empty stream that closes when the turn ends.\n // useChat consumes the returned stream to accumulate the assistant message,\n // but useMessageSync already pushes the transport's authoritative message\n // state into useChat via setMessages. Returning the real event stream would\n // cause useChat to accumulate a duplicate assistant message. Instead, we\n // return a stream that produces no chunks and closes when the turn's stream\n // finishes, so useChat knows when streaming is done without duplicating state.\n const { readable, writable } = new TransformStream<AI.UIMessageChunk>();\n const writer = writable.getWriter();\n // Fire-and-forget: we only care about the close/abort signal, not the piped data.\n // Errors on the turn stream are surfaced via transport.on('error'), not here.\n /* eslint-disable @typescript-eslint/no-empty-function -- swallow: writer.close() rejection after stream teardown is unrecoverable */\n turn.stream\n .pipeTo(\n new WritableStream({\n close: () => {\n writer.close().catch(() => {});\n },\n abort: () => {\n writer.close().catch(() => {});\n },\n }),\n )\n .catch(() => {\n writer.close().catch(() => {});\n });\n /* eslint-enable @typescript-eslint/no-empty-function */\n return readable;\n },\n\n // Observer mode handles in-progress streams automatically.\n // The transport subscribes before attach — on the next server append,\n // observer accumulation emits lifecycle events that useMessageSync\n // upserts into React state.\n // eslint-disable-next-line unicorn/no-null, @typescript-eslint/promise-function-async -- null is required by the AI SDK ChatTransport contract; no await needed\n reconnectToStream: () => Promise.resolve(null),\n\n close: async (options?: CloseOptions) => transport.close(options),\n});\n","/**\n * Type-safe EventEmitter wrapping Ably's internal EventEmitter.\n *\n * Takes a single `EventsMap` type parameter — an interface mapping event names\n * to payload types — rather than Ably's three type parameters. Adapted from\n * the ably-chat-js SDK.\n *\n * ```ts\n * interface MyEvents {\n * reaction: { emoji: string };\n * status: { online: boolean };\n * }\n *\n * const emitter = new EventEmitter<MyEvents>(logger);\n * emitter.on('reaction', (event) => console.log(event.emoji));\n * emitter.emit('reaction', { emoji: '👍' });\n * ```\n */\n\nimport * as Ably from 'ably';\n\nimport type { Logger } from './logger.js';\n\n/** Callback receiving a union of all possible event payloads. */\ntype Callback<EventsMap> = (arg: EventsMap[keyof EventsMap]) => void;\n\n/** Callback receiving the payload for a single event type. */\ntype CallbackSingle<K> = (arg: K) => void;\n\n/**\n * Type-safe interface for the Ably EventEmitter, parameterized by an EventsMap\n * that maps event names to their payload types.\n */\ninterface InterfaceEventEmitter<EventsMap> extends Ably.EventEmitter<Callback<EventsMap>, void, keyof EventsMap> {\n /** Emit an event with a type-safe payload. Payload is optional for `undefined`-typed events. */\n emit<K extends keyof EventsMap>(\n event: K,\n ...args: EventsMap[K] extends undefined ? [EventsMap[K]?] : [EventsMap[K]]\n ): void;\n\n /** Subscribe to a single event with a typed callback. */\n on<K extends keyof EventsMap>(event: K, callback: CallbackSingle<EventsMap[K]>): void;\n /** Subscribe to two events with a union-typed callback. */\n on<K1 extends keyof EventsMap, K2 extends keyof EventsMap>(\n events: [K1, K2],\n callback: CallbackSingle<EventsMap[K1] | EventsMap[K2]>,\n ): void;\n /** Subscribe to three events with a union-typed callback. */\n on<K1 extends keyof EventsMap, K2 extends keyof EventsMap, K3 extends keyof EventsMap>(\n events: [K1, K2, K3],\n callback: CallbackSingle<EventsMap[K1] | EventsMap[K2] | EventsMap[K3]>,\n ): void;\n /** Subscribe to an array of events. */\n on(events: (keyof EventsMap)[], callback: Callback<EventsMap>): void;\n /** Subscribe to all events. */\n on(callback: Callback<EventsMap>): void;\n\n /** Unsubscribe a callback from a specific event. */\n off<K extends keyof EventsMap>(event: K, listener: CallbackSingle<EventsMap[K]>): void;\n /** Unsubscribe a callback from all events, or remove all listeners if no callback provided. */\n off(listener?: Callback<EventsMap>): void;\n}\n\n/**\n * Bridge from our {@link Logger} to the Ably EventEmitter's internal logger\n * contract. Ably's EventEmitter calls `logger.logAction(level, action, message)`\n * when a listener throws — we route that to our Logger's `error` method.\n * @param logger - The application logger to delegate to.\n * @returns An object satisfying the Ably EventEmitter's logger interface.\n */\nconst toAblyLogger = (logger: Logger): unknown => ({\n logAction: (_level: number, action: string, message?: string) => {\n logger.error(action, { detail: message });\n },\n shouldLog: () => true,\n});\n\n// CAST: Access Ably's internal EventEmitter constructor. Not publicly exported\n// but available to other Ably SDKs. The logger parameter ensures listener\n// exceptions are caught and logged rather than crashing.\nconst InternalEventEmitter: new <EventsMap>(logger: unknown) => InterfaceEventEmitter<EventsMap> = (\n Ably.Realtime as unknown as { EventEmitter: new <EventsMap>(logger: unknown) => InterfaceEventEmitter<EventsMap> }\n).EventEmitter;\n\n/**\n * Type-safe EventEmitter based on Ably's internal EventEmitter.\n *\n * Provides the same semantics as {@link Ably.EventEmitter} (error isolation\n * between listeners, synchronous dispatch) but with a single `EventsMap` type\n * parameter for ergonomic type safety.\n *\n * Requires a {@link Logger} so that listener exceptions are routed through\n * the application's logging infrastructure rather than silently swallowed.\n */\nexport class EventEmitter<EventsMap> extends InternalEventEmitter<EventsMap> {\n /**\n * Create a new EventEmitter.\n * @param logger - Application logger. Listener exceptions are logged at error level.\n */\n constructor(logger: Logger) {\n super(toAblyLogger(logger));\n }\n}\n","import * as Ably from 'ably';\n\nimport { ErrorCode } from './errors.js';\n\n/**\n * Structured logger with leveled output and hierarchical context.\n * Implementations filter messages by level and delegate to a {@link LogHandler}.\n */\nexport interface Logger {\n /**\n * Log a message at the trace level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n trace(message: string, context?: LogContext): void;\n\n /**\n * Log a message at the debug level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log a message at the info level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a message at the warn level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log a message at the error level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n error(message: string, context?: LogContext): void;\n\n /**\n * Creates a new logger with a context that will be merged with any context provided to individual log calls.\n * The context will be overridden by any matching keys in the individual log call's context.\n * @param context The context to use for all log calls.\n * @returns A new logger instance with the context.\n */\n withContext(context: LogContext): Logger;\n}\n\n/**\n * Represents the different levels of logging that can be used.\n */\nexport enum LogLevel {\n /**\n * Something routine and expected has occurred. This level will provide logs for the vast majority of operations\n * and function calls.\n */\n Trace = 'trace',\n\n /**\n * Development information, messages that are useful when trying to debug library behavior,\n * but superfluous to normal operation.\n */\n Debug = 'debug',\n\n /**\n * Informational messages. Operationally significant to the library but not out of the ordinary.\n */\n Info = 'info',\n\n /**\n * Anything that is not immediately an error, but could cause unexpected behavior in the future. For example,\n * passing an invalid value to an option. Indicates that some action should be taken to prevent future errors.\n */\n Warn = 'warn',\n\n /**\n * A given operation has failed and cannot be automatically recovered. The error may threaten the continuity\n * of operation.\n */\n Error = 'error',\n\n /**\n * No logging will be performed.\n */\n Silent = 'silent',\n}\n\n/**\n * Represents the context of a log message.\n * It is an object of key-value pairs that can be used to provide additional context to a log message.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type LogContext = Record<string, any>;\n\n/**\n * A function that can be used to handle log messages.\n * @param message The message to log.\n * @param level The log level of the message.\n * @param context The context of the log message as key-value pairs.\n */\nexport type LogHandler = (message: string, level: LogLevel, context?: LogContext) => void;\n\n/**\n * A simple console logger that logs messages to the console.\n * @param message The message to log.\n * @param level The log level of the message.\n * @param context - The context of the log message as key-value pairs.\n */\nexport const consoleLogger = (message: string, level: LogLevel, context?: LogContext) => {\n const contextString = context ? `, context: ${JSON.stringify(context)}` : '';\n const formattedMessage = `[${new Date().toISOString()}] ${level.valueOf().toUpperCase()} ably-ai-transport: ${message}${contextString}`;\n\n switch (level) {\n case LogLevel.Trace:\n case LogLevel.Debug: {\n console.log(formattedMessage);\n break;\n }\n case LogLevel.Info: {\n console.info(formattedMessage);\n break;\n }\n case LogLevel.Warn: {\n console.warn(formattedMessage);\n break;\n }\n case LogLevel.Error: {\n console.error(formattedMessage);\n break;\n }\n case LogLevel.Silent: {\n break;\n }\n }\n};\n\n/**\n * Options for creating a logger.\n */\nexport interface LoggerOptions {\n logHandler?: LogHandler;\n logLevel: LogLevel;\n}\n\nexport const makeLogger = (options: LoggerOptions): Logger => {\n const logHandler = options.logHandler ?? consoleLogger;\n\n return new DefaultLogger(logHandler, options.logLevel);\n};\n\n/**\n * A convenient list of log levels as numbers that can be used for easier comparison.\n */\nenum LogLevelNumber {\n Trace = 0,\n Debug = 1,\n Info = 2,\n Warn = 3,\n Error = 4,\n Silent = 5,\n}\n\n/**\n * A mapping of log levels to their numeric equivalents.\n */\nconst logLevelNumberMap = new Map<LogLevel, LogLevelNumber>([\n [LogLevel.Trace, LogLevelNumber.Trace],\n [LogLevel.Debug, LogLevelNumber.Debug],\n [LogLevel.Info, LogLevelNumber.Info],\n [LogLevel.Warn, LogLevelNumber.Warn],\n [LogLevel.Error, LogLevelNumber.Error],\n [LogLevel.Silent, LogLevelNumber.Silent],\n]);\n\n/**\n * A default logger implementation.\n */\nclass DefaultLogger implements Logger {\n private readonly _handler: LogHandler;\n private readonly _levelNumber: LogLevelNumber;\n private readonly _context?: LogContext;\n\n constructor(handler: LogHandler, level: LogLevel, context?: LogContext) {\n this._handler = handler;\n this._context = context;\n\n const levelNumber = logLevelNumberMap.get(level);\n if (levelNumber === undefined) {\n throw new Ably.ErrorInfo(`unable to create logger; invalid log level: ${level}`, ErrorCode.InvalidArgument, 400);\n }\n\n this._levelNumber = levelNumber;\n }\n\n trace(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Trace, LogLevelNumber.Trace, context);\n }\n\n debug(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Debug, LogLevelNumber.Debug, context);\n }\n\n info(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Info, LogLevelNumber.Info, context);\n }\n\n warn(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Warn, LogLevelNumber.Warn, context);\n }\n\n error(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Error, LogLevelNumber.Error, context);\n }\n\n withContext(context: LogContext): Logger {\n // Get the original log level by finding the key in logLevelNumberMap that matches this._levelNumber\n const originalLevel =\n [...logLevelNumberMap.entries()].find(([, value]) => value === this._levelNumber)?.[0] ?? LogLevel.Error;\n\n return new DefaultLogger(this._handler, originalLevel, this._mergeContext(context));\n }\n\n private _write(message: string, level: LogLevel, levelNumber: LogLevelNumber, context?: LogContext): void {\n if (levelNumber >= this._levelNumber) {\n this._handler(message, level, this._mergeContext(context));\n }\n }\n\n private _mergeContext(context?: LogContext): LogContext | undefined {\n if (!this._context) {\n return context ?? undefined;\n }\n\n return context ? { ...this._context, ...context } : this._context;\n }\n}\n","/**\n * ConversationTree — materializes a branching conversation from a flat\n * oplog of Ably messages using serial-first ordering.\n *\n * Serial order (the total order assigned by Ably) is the primary mechanism\n * for linear message sequences. `x-ably-parent` and `x-ably-fork-of` headers\n * are only structurally meaningful at branch points — where the user is\n * interacting with a visible message and the client always has it loaded.\n *\n * `upsert()` is the sole mutation method. Messages can arrive in any order\n * (live subscription, history pages, seed data) and the tree produces the\n * correct `flatten()` output once all messages are present.\n *\n * The tree owns conversation state. `flatten()` returns the linear message\n * list for the currently selected branches — this is what the transport's\n * `getMessages()` delegates to.\n */\n\nimport { HEADER_FORK_OF, HEADER_PARENT } from '../../constants.js';\nimport type { Logger } from '../../logger.js';\nimport type { ConversationNode, ConversationTree } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Internal node type\n// ---------------------------------------------------------------------------\n\ninterface InternalNode<TMessage> {\n node: ConversationNode<TMessage>;\n /** Insertion sequence — tiebreaker for null-serial messages. */\n insertSeq: number;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CT13\nclass DefaultConversationTree<TMessage> implements ConversationTree<TMessage> {\n /** All nodes indexed by msgId (x-ably-msg-id). */\n private readonly _nodeIndex = new Map<string, InternalNode<TMessage>>();\n\n /** Secondary index: codec message key to msgId. Bridges UIMessage.id to x-ably-msg-id. */\n private readonly _codecKeyIndex = new Map<string, string>();\n\n /**\n * All nodes sorted by serial (lexicographic). Null-serial messages\n * (optimistic inserts, seed data) sort after all serial-bearing messages,\n * ordered among themselves by insertion sequence.\n */\n private readonly _sortedList: InternalNode<TMessage>[] = [];\n\n /**\n * Parent index: parentId to set of child msgIds.\n * Nodes with no parent are indexed under the key `null`.\n */\n private readonly _parentIndex = new Map<string | undefined, Set<string>>();\n\n /**\n * Selected sibling index at each fork point, keyed by the msgId of\n * the first sibling in the group (the fork target). Default: last.\n */\n private readonly _selections = new Map<string, number>();\n\n private readonly _getKey: (message: TMessage) => string;\n private readonly _logger: Logger;\n\n /** Monotonically increasing counter for insertion sequence. */\n private _seqCounter = 0;\n\n constructor(getKey: (message: TMessage) => string, logger: Logger) {\n this._getKey = getKey;\n this._logger = logger;\n }\n\n // -------------------------------------------------------------------------\n // Sorted list maintenance\n // -------------------------------------------------------------------------\n\n /**\n * Compare two nodes for sorted list ordering.\n * Serial-bearing nodes sort by serial (lexicographic).\n * Null-serial nodes sort after all serial-bearing nodes.\n * Among null-serial nodes, sort by insertion sequence.\n * @param a - First node to compare.\n * @param b - Second node to compare.\n * @returns Negative if a sorts before b, positive if after, zero if equal.\n */\n // Spec: AIT-CT13a\n private _compareNodes(a: InternalNode<TMessage>, b: InternalNode<TMessage>): number {\n const sa = a.node.serial;\n const sb = b.node.serial;\n if (sa === undefined && sb === undefined) return a.insertSeq - b.insertSeq;\n if (sa === undefined) return 1; // a sorts after serial-bearing b\n if (sb === undefined) return -1; // b sorts after serial-bearing a\n if (sa < sb) return -1;\n if (sa > sb) return 1;\n return a.insertSeq - b.insertSeq; // same serial: preserve insertion order\n }\n\n /**\n * Insert a node into sortedList at the correct position via binary search.\n * @param internal - The node to insert.\n */\n private _insertSorted(internal: InternalNode<TMessage>): void {\n const serial = internal.node.serial;\n\n // Fast path: null-serial always appends to end (among other null-serials)\n if (serial === undefined) {\n this._sortedList.push(internal);\n return;\n }\n\n // Binary search for insertion point among serial-bearing nodes.\n let lo = 0;\n let hi = this._sortedList.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n const midNode = this._sortedList[mid];\n if (!midNode) break; // unreachable: mid is always in bounds\n if (this._compareNodes(midNode, internal) <= 0) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n this._sortedList.splice(lo, 0, internal);\n }\n\n /**\n * Remove a node from sortedList.\n * @param internal - The node to remove.\n */\n private _removeSorted(internal: InternalNode<TMessage>): void {\n const idx = this._sortedList.indexOf(internal);\n if (idx !== -1) this._sortedList.splice(idx, 1);\n }\n\n // -------------------------------------------------------------------------\n // Parent index maintenance\n // -------------------------------------------------------------------------\n\n private _addToParentIndex(parentId: string | undefined, msgId: string): void {\n let set = this._parentIndex.get(parentId);\n if (!set) {\n set = new Set();\n this._parentIndex.set(parentId, set);\n }\n set.add(msgId);\n }\n\n private _removeFromParentIndex(parentId: string | undefined, msgId: string): void {\n const set = this._parentIndex.get(parentId);\n if (set) {\n set.delete(msgId);\n if (set.size === 0) this._parentIndex.delete(parentId);\n }\n }\n\n // -------------------------------------------------------------------------\n // Sibling grouping\n // -------------------------------------------------------------------------\n\n /**\n * Get the sibling group that `msgId` belongs to.\n *\n * A sibling group is: the original message + all messages whose `forkOf`\n * points to the original (or transitively to a sibling). We find the\n * group root by following `forkOf` chains to the earliest ancestor that\n * has no `forkOf` (or whose `forkOf` target doesn't share the same parent).\n * @param msgId - The msg-id to look up the sibling group for.\n * @returns The ordered list of sibling nodes.\n */\n // Spec: AIT-CT13b\n private _getSiblingGroup(msgId: string): ConversationNode<TMessage>[] {\n const entry = this._nodeIndex.get(msgId);\n if (!entry) return [];\n\n // Find the \"original\" — the message at the root of the fork chain\n // that shares the same parentId. Guard against cycles in forkOf chains.\n let original = entry.node;\n const visitedGroup = new Set<string>([original.msgId]);\n while (original.forkOf) {\n if (visitedGroup.has(original.forkOf)) break; // cycle guard\n const forkTarget = this._nodeIndex.get(original.forkOf);\n if (!forkTarget || forkTarget.node.parentId !== original.parentId) break;\n original = forkTarget.node;\n visitedGroup.add(original.msgId);\n }\n\n // Collect all siblings: nodes with the same parentId that either\n // ARE the original, or have a forkOf chain leading to the original.\n const parentId = original.parentId;\n const originalId = original.msgId;\n const siblings: InternalNode<TMessage>[] = [];\n\n const candidateIds = this._parentIndex.get(parentId);\n if (candidateIds) {\n for (const childId of candidateIds) {\n const childEntry = this._nodeIndex.get(childId);\n if (childEntry && this._isSiblingOf(childEntry.node, originalId)) {\n siblings.push(childEntry);\n }\n }\n }\n\n // Sort by Ably serial (lexicographic). Messages without a serial\n // (optimistic inserts before server relay) sort after all serial-bearing\n // siblings — they represent the user's most recent action.\n siblings.sort((a, b) => this._compareNodes(a, b));\n return siblings.map((s) => s.node);\n }\n\n /**\n * Check if `node` belongs to the sibling group rooted at `originalId`.\n * A node is a sibling if it IS the original or its forkOf chain leads\n * to the original (with the same parentId).\n * @param node - The node to check.\n * @param originalId - The group root to match against.\n * @returns True if the node belongs to the sibling group.\n */\n private _isSiblingOf(node: ConversationNode<TMessage>, originalId: string): boolean {\n if (node.msgId === originalId) return true;\n let current = node;\n const visited = new Set<string>([current.msgId]);\n while (current.forkOf) {\n if (current.forkOf === originalId) return true;\n if (visited.has(current.forkOf)) break; // cycle guard\n const target = this._nodeIndex.get(current.forkOf);\n if (!target) break;\n current = target.node;\n visited.add(current.msgId);\n }\n return false;\n }\n\n /**\n * Get the \"group root\" msgId for a sibling group — the original message\n * that all forks trace back to.\n * @param msgId - Any msg-id in the sibling group.\n * @returns The msg-id of the group root.\n */\n private _getGroupRoot(msgId: string): string {\n const entry = this._nodeIndex.get(msgId);\n if (!entry) return msgId;\n\n let current = entry.node;\n const visited = new Set<string>([current.msgId]);\n while (current.forkOf) {\n if (visited.has(current.forkOf)) break; // cycle guard\n const forkTarget = this._nodeIndex.get(current.forkOf);\n if (!forkTarget || forkTarget.node.parentId !== current.parentId) break;\n current = forkTarget.node;\n visited.add(current.msgId);\n }\n return current.msgId;\n }\n\n // -------------------------------------------------------------------------\n // Public query methods\n // -------------------------------------------------------------------------\n\n flatten(): TMessage[] {\n const result: TMessage[] = [];\n const currentPath = new Set<string>();\n // Track which sibling groups we've already resolved to avoid\n // re-resolving for every member of the group.\n const resolvedGroups = new Map<string, string>(); // groupRootId → selected msgId\n\n for (const internal of this._sortedList) {\n const node = internal.node;\n const { msgId, parentId } = node;\n\n // Step 1: Check parent reachability.\n if (parentId !== undefined && !currentPath.has(parentId)) {\n continue;\n }\n\n // Step 2: Check sibling selection.\n const group = this._getSiblingGroup(msgId);\n if (group.length > 1) {\n const groupRootId = this._getGroupRoot(msgId);\n let selectedId = resolvedGroups.get(groupRootId);\n if (selectedId === undefined) {\n const selectedIdx = this._selections.get(groupRootId) ?? group.length - 1;\n const clamped = Math.max(0, Math.min(selectedIdx, group.length - 1));\n const selected = group[clamped];\n if (!selected) break; // unreachable: clamped is always in bounds\n selectedId = selected.msgId;\n resolvedGroups.set(groupRootId, selectedId);\n }\n if (msgId !== selectedId) {\n continue;\n }\n }\n\n currentPath.add(msgId);\n result.push(node.message);\n }\n\n return result;\n }\n\n getSiblings(msgId: string): TMessage[] {\n return this._getSiblingGroup(msgId).map((n) => n.message);\n }\n\n hasSiblings(msgId: string): boolean {\n return this._getSiblingGroup(msgId).length > 1;\n }\n\n getSelectedIndex(msgId: string): number {\n const group = this._getSiblingGroup(msgId);\n if (group.length <= 1) return 0;\n const groupRootId = this._getGroupRoot(msgId);\n const stored = this._selections.get(groupRootId);\n if (stored !== undefined) return Math.max(0, Math.min(stored, group.length - 1));\n return group.length - 1; // default: latest\n }\n\n // Spec: AIT-CT13c\n select(msgId: string, index: number): void {\n this._logger.debug('ConversationTree.select();', { msgId, index });\n const group = this._getSiblingGroup(msgId);\n if (group.length <= 1) return;\n const groupRootId = this._getGroupRoot(msgId);\n this._selections.set(groupRootId, Math.max(0, Math.min(index, group.length - 1)));\n }\n\n getNode(msgId: string): ConversationNode<TMessage> | undefined {\n return this._nodeIndex.get(msgId)?.node;\n }\n\n getNodeByKey(key: string): ConversationNode<TMessage> | undefined {\n const msgId = this._codecKeyIndex.get(key);\n if (!msgId) return undefined;\n return this._nodeIndex.get(msgId)?.node;\n }\n\n getHeaders(msgId: string): Record<string, string> | undefined {\n return this._nodeIndex.get(msgId)?.node.headers;\n }\n\n // -------------------------------------------------------------------------\n // Mutation\n // -------------------------------------------------------------------------\n\n upsert(msgId: string, message: TMessage, headers: Record<string, string>, serial?: string): void {\n const parentId = headers[HEADER_PARENT] ?? undefined;\n const forkOf = headers[HEADER_FORK_OF] ?? undefined;\n\n // Maintain codec key → msgId secondary index\n this._codecKeyIndex.set(this._getKey(message), msgId);\n\n const existing = this._nodeIndex.get(msgId);\n if (existing) {\n // Update in place — message content may have changed (e.g. streaming).\n // Only update headers if the new headers are non-empty (prevents\n // streaming updates from erasing canonical headers).\n existing.node.message = message;\n if (Object.keys(headers).length > 0) {\n existing.node.headers = { ...headers };\n }\n // Spec: AIT-CT13d\n // Promote serial: optimistic (null) → server-assigned on relay.\n if (serial && !existing.node.serial) {\n this._logger.debug('ConversationTree.upsert(); promoting serial', { msgId, serial });\n existing.node.serial = serial;\n // Re-sort: remove from current position, re-insert at correct position.\n this._removeSorted(existing);\n this._insertSorted(existing);\n }\n return;\n }\n\n this._logger.trace('ConversationTree.upsert(); inserting new node', { msgId, parentId, forkOf });\n\n const node: ConversationNode<TMessage> = {\n message,\n msgId,\n parentId,\n forkOf,\n headers: { ...headers },\n serial,\n };\n\n const internal: InternalNode<TMessage> = { node, insertSeq: this._seqCounter++ };\n this._nodeIndex.set(msgId, internal);\n this._addToParentIndex(parentId, msgId);\n this._insertSorted(internal);\n }\n\n delete(msgId: string): void {\n const entry = this._nodeIndex.get(msgId);\n if (!entry) return;\n\n this._logger.debug('ConversationTree.delete();', { msgId });\n\n const { node } = entry;\n\n // Clean up secondary index\n const codecKey = this._getKey(node.message);\n if (this._codecKeyIndex.get(codecKey) === msgId) {\n this._codecKeyIndex.delete(codecKey);\n }\n\n // Remove from parent index\n this._removeFromParentIndex(node.parentId, msgId);\n\n // Remove from sorted list\n this._removeSorted(entry);\n\n // Remove from primary index\n this._nodeIndex.delete(msgId);\n this._selections.delete(msgId);\n\n // Children are NOT deleted — they become unreachable in flatten()\n // because their parent is no longer on the active path.\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a ConversationTree that materializes branching history from a flat oplog.\n * @param getKey - Codec function that returns a stable key for a domain message.\n * @param logger - Logger for diagnostic output.\n * @returns A new {@link ConversationTree} instance.\n */\nexport const createConversationTree = <TMessage>(\n getKey: (message: TMessage) => string,\n logger: Logger,\n): ConversationTree<TMessage> => new DefaultConversationTree(getKey, logger);\n","/**\n * decodeHistory — load conversation history from an Ably channel and\n * return decoded messages as a PaginatedMessages result.\n *\n * Uses a fresh decoder (not shared with the live subscription) to avoid\n * state conflicts. Per-turn accumulators handle interleaved turns correctly.\n *\n * The `limit` option controls the number of **messages** returned,\n * not the number of Ably wire messages fetched. The implementation pages\n * back through Ably history until `limit` complete messages have\n * been assembled. Partial turns (incomplete at the page boundary) are\n * buffered internally and completed when `next()` fetches more pages.\n *\n * Only completed messages appear in `items`. A message is complete when\n * its terminal event (finish/abort/error) has been received.\n *\n * Because Ably history returns newest-first while the decoder requires\n * chronological order, all collected Ably messages are re-decoded from\n * oldest to newest after each page fetch. This handles turns that span\n * page boundaries correctly.\n */\n\nimport type * as Ably from 'ably';\n\nimport { HEADER_MSG_ID, HEADER_TURN_ID } from '../../constants.js';\nimport type { Logger } from '../../logger.js';\nimport { getHeaders } from '../../utils.js';\nimport type { Codec, DecoderOutput, MessageAccumulator } from '../codec/types.js';\nimport type { LoadHistoryOptions, PaginatedMessages } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Shared state across pages within one history traversal\n// ---------------------------------------------------------------------------\n\ninterface HistoryState<TEvent, TMessage> {\n codec: Codec<TEvent, TMessage>;\n /** All raw Ably messages collected so far, in newest-first order (as received from Ably). */\n rawMessages: Ably.InboundMessage[];\n /** How many completed messages have been returned to the consumer so far. */\n returnedCount: number;\n /** How many raw Ably messages have been returned to the consumer so far. */\n returnedRawCount: number;\n /** The last Ably page cursor for continued pagination. */\n lastAblyPage: Ably.PaginatedResult<Ably.InboundMessage> | undefined;\n /** Key function for domain messages (codec.getMessageKey). */\n getMessageKey: (message: TMessage) => string;\n logger: Logger;\n}\n\n/** A completed message paired with its canonical wire headers and serial. */\ninterface DecodedItem<TMessage> {\n message: TMessage;\n headers: Record<string, string>;\n /** Ably serial from the first Ably message for this domain message. */\n serial: string;\n}\n\n// ---------------------------------------------------------------------------\n// Decode all collected messages from scratch (chronological order)\n// ---------------------------------------------------------------------------\n\n/**\n * Re-decode all collected raw messages into completed domain messages.\n * @param state - The shared history traversal state.\n * @returns Completed messages in newest-first order.\n */\nconst decodeAll = <TEvent, TMessage>(state: HistoryState<TEvent, TMessage>): DecodedItem<TMessage>[] => {\n // Reverse to chronological (oldest first)\n const chronological = [...state.rawMessages].toReversed();\n\n // Fresh decoder and per-turn accumulators for each full re-decode.\n const decoder = state.codec.createDecoder();\n const turns = new Map<\n string,\n {\n accumulator: MessageAccumulator<TEvent, TMessage>;\n firstSeen: number;\n /** Headers from the first Ably message per x-ably-msg-id within this turn. */\n msgHeaders: Map<string, Record<string, string>>;\n /** Ably serial from the first Ably message per x-ably-msg-id within this turn. */\n msgSerials: Map<string, string>;\n }\n >();\n const defaultAccumulator = state.codec.createAccumulator();\n let orderCounter = 0;\n\n // Headers for discrete messages (writeMessages output), keyed by codec message key.\n const discreteHeaders = new Map<string, Record<string, string>>();\n // Serials for discrete messages, keyed by codec message key.\n const discreteSerials = new Map<string, string>();\n\n for (const msg of chronological) {\n const outputs: DecoderOutput<TEvent, TMessage>[] = decoder.decode(msg);\n const headers = getHeaders(msg);\n const turnId = headers[HEADER_TURN_ID];\n const msgId = headers[HEADER_MSG_ID];\n const serial = msg.serial;\n\n if (turnId) {\n let turn = turns.get(turnId);\n if (!turn) {\n turn = {\n accumulator: state.codec.createAccumulator(),\n firstSeen: orderCounter++,\n msgHeaders: new Map(),\n msgSerials: new Map(),\n };\n turns.set(turnId, turn);\n }\n // Capture headers per msg-id within this turn. Update on later\n // messages too (e.g. closing append overrides status from\n // \"streaming\" to \"finished\"/\"aborted\"). Only merge when the\n // incoming message has non-empty headers.\n if (msgId) {\n const existing = turn.msgHeaders.get(msgId);\n if (!existing) {\n turn.msgHeaders.set(msgId, { ...headers });\n if (serial) turn.msgSerials.set(msgId, serial);\n } else if (Object.keys(headers).length > 0) {\n Object.assign(existing, headers);\n }\n }\n turn.accumulator.processOutputs(outputs);\n } else {\n defaultAccumulator.processOutputs(outputs);\n }\n\n // Capture headers and serial for discrete messages by codec key.\n for (const output of outputs) {\n if (output.kind === 'message') {\n const key = state.getMessageKey(output.message);\n const existingDiscrete = discreteHeaders.get(key);\n if (!existingDiscrete) {\n discreteHeaders.set(key, { ...headers });\n if (serial) discreteSerials.set(key, serial);\n } else if (Object.keys(headers).length > 0) {\n Object.assign(existingDiscrete, headers);\n }\n }\n }\n }\n\n // Collect completed messages in chronological order (oldest first) by turn.\n const completed: DecodedItem<TMessage>[] = [];\n\n for (const msg of defaultAccumulator.completedMessages) {\n const key = state.getMessageKey(msg);\n completed.push({\n message: msg,\n headers: discreteHeaders.get(key) ?? {},\n serial: discreteSerials.get(key) ?? '',\n });\n }\n\n const sorted = [...turns.values()].toSorted((a, b) => a.firstSeen - b.firstSeen);\n for (const turn of sorted) {\n // Assign headers and serials to each completed message in this turn.\n // Discrete messages were already captured by codec key. Accumulated\n // messages need to be matched to the turn's per-msg-id headers.\n const claimedMsgIds = new Set<string>();\n\n // First pass: resolve discrete messages and mark their msg-ids as claimed\n const turnKeyHeaders = new Map<string, Record<string, string>>();\n const turnKeySerials = new Map<string, string>();\n for (const msg of turn.accumulator.completedMessages) {\n const key = state.getMessageKey(msg);\n const discrete = discreteHeaders.get(key);\n if (discrete) {\n turnKeyHeaders.set(key, discrete);\n const dSerial = discreteSerials.get(key);\n if (dSerial) turnKeySerials.set(key, dSerial);\n const mid = discrete[HEADER_MSG_ID];\n if (mid) claimedMsgIds.add(mid);\n }\n }\n\n // Second pass: assign unclaimed msg-id entries to remaining messages\n const unclaimedEntries = [...turn.msgHeaders.entries()].filter(([mid]) => !claimedMsgIds.has(mid));\n let unclaimedIdx = 0;\n\n for (const msg of turn.accumulator.completedMessages) {\n const key = state.getMessageKey(msg);\n const unclaimed = unclaimedEntries[unclaimedIdx];\n if (!turnKeyHeaders.has(key) && unclaimed) {\n const [mid, hdrs] = unclaimed;\n turnKeyHeaders.set(key, hdrs);\n const mSerial = turn.msgSerials.get(mid);\n if (mSerial) turnKeySerials.set(key, mSerial);\n unclaimedIdx++;\n }\n }\n\n for (const msg of turn.accumulator.completedMessages) {\n const key = state.getMessageKey(msg);\n completed.push({\n message: msg,\n headers: turnKeyHeaders.get(key) ?? {},\n serial: turnKeySerials.get(key) ?? '',\n });\n }\n }\n\n // Reverse to newest-first. The consumer slices from the front for the\n // most recent page, and progressively deeper for older pages.\n return completed.toReversed();\n};\n\n// ---------------------------------------------------------------------------\n// Fetch Ably pages until we have enough completed messages\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch Ably history pages until we have enough completed messages.\n * @param state - The shared history traversal state.\n * @param ablyPage - The current Ably paginated result to start from.\n * @param limit - Target number of completed messages beyond what has already been returned.\n */\nconst fetchUntilLimit = async <TEvent, TMessage>(\n state: HistoryState<TEvent, TMessage>,\n ablyPage: Ably.PaginatedResult<Ably.InboundMessage>,\n limit: number,\n): Promise<void> => {\n state.rawMessages.push(...ablyPage.items);\n state.lastAblyPage = ablyPage;\n\n let decodedCount = decodeAll(state).length;\n while (decodedCount < state.returnedCount + limit && ablyPage.hasNext()) {\n state.logger.debug('decodeHistory.fetchUntilLimit(); fetching next page', {\n collected: state.rawMessages.length,\n decoded: decodedCount,\n });\n const nextPage = await ablyPage.next();\n if (!nextPage) break;\n ablyPage = nextPage;\n state.rawMessages.push(...nextPage.items);\n state.lastAblyPage = nextPage;\n decodedCount = decodeAll(state).length;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Build PaginatedMessages result from current state\n// ---------------------------------------------------------------------------\n\n/**\n * Build a PaginatedMessages page from the current decode state.\n * @param state - The shared history traversal state.\n * @param limit - Max messages per page.\n * @returns A page of decoded messages with a `next()` cursor.\n */\nconst buildResult = <TEvent, TMessage>(\n state: HistoryState<TEvent, TMessage>,\n limit: number,\n): PaginatedMessages<TMessage> => {\n // allCompleted is newest-first. Slice from returnedCount for this page,\n // then reverse to chronological for display.\n const allCompleted = decodeAll(state);\n\n const pageSlice = allCompleted.slice(state.returnedCount, state.returnedCount + limit);\n const chronSlice = [...pageSlice].toReversed();\n state.returnedCount += pageSlice.length;\n\n const moreCompleted = allCompleted.length > state.returnedCount;\n const moreAblyPages = state.lastAblyPage?.hasNext() ?? false;\n\n // Raw Ably messages for this page in chronological order.\n const newRawCount = state.rawMessages.length - state.returnedRawCount;\n const rawSlice = newRawCount > 0 ? state.rawMessages.slice(state.returnedRawCount).toReversed() : [];\n state.returnedRawCount = state.rawMessages.length;\n\n return {\n items: chronSlice.map((d) => d.message),\n itemHeaders: chronSlice.map((d) => d.headers),\n itemSerials: chronSlice.map((d) => d.serial),\n rawMessages: rawSlice,\n hasNext: () => moreCompleted || moreAblyPages,\n next: async () => {\n if (moreCompleted) {\n return buildResult(state, limit);\n }\n if (!moreAblyPages || !state.lastAblyPage) return;\n const nextAbly = await state.lastAblyPage.next();\n if (!nextAbly) return;\n await fetchUntilLimit(state, nextAbly, limit);\n return buildResult(state, limit);\n },\n };\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Load conversation history from a channel and return decoded messages.\n *\n * Attaches the channel if not already attached, then calls\n * `channel.history({ untilAttach: true })` to guarantee no gap between\n * historical and live messages. The attach is idempotent.\n *\n * The `limit` option controls the number of complete messages\n * returned per page, not the number of Ably wire messages fetched.\n * @param channel - The Ably channel to load history from.\n * @param codec - The codec for decoding wire messages into domain messages.\n * @param options - Pagination options.\n * @param logger - Logger for diagnostic output.\n * @returns The first page of decoded history messages.\n */\n// Spec: AIT-CT11, AIT-CT11b\nexport const decodeHistory = async <TEvent, TMessage>(\n channel: Ably.RealtimeChannel,\n codec: Codec<TEvent, TMessage>,\n options: LoadHistoryOptions | undefined,\n logger: Logger,\n): Promise<PaginatedMessages<TMessage>> => {\n const limit = options?.limit ?? 100;\n const state: HistoryState<TEvent, TMessage> = {\n codec,\n rawMessages: [],\n returnedCount: 0,\n returnedRawCount: 0,\n lastAblyPage: undefined,\n getMessageKey: codec.getMessageKey.bind(codec),\n logger,\n };\n\n logger.trace('decodeHistory();', { limit });\n\n // Request more Ably messages than the domain limit to account for\n // the many-to-one ratio (multiple wire messages per message).\n const wireLimit = limit * 10;\n\n await channel.attach();\n const ablyPage = await channel.history({ untilAttach: true, limit: wireLimit });\n await fetchUntilLimit(state, ablyPage, limit);\n return buildResult(state, limit);\n};\n","/**\n * Transport header builder.\n *\n * Single source of truth for which `x-ably-*` headers every transport\n * message carries. Used by the server transport (addMessages, streamResponse)\n * and will be used by the client transport (optimistic message stamping).\n */\n\nimport {\n HEADER_FORK_OF,\n HEADER_MSG_ID,\n HEADER_PARENT,\n HEADER_ROLE,\n HEADER_TURN_CLIENT_ID,\n HEADER_TURN_ID,\n} from '../../constants.js';\n\n/**\n * Build the standard transport header set for a message.\n * @param opts - The header values to include.\n * @param opts.role - Message role (e.g. \"user\", \"assistant\").\n * @param opts.turnId - Turn correlation ID.\n * @param opts.msgId - Message identity.\n * @param opts.turnClientId - ClientId of the turn initiator.\n * @param opts.parent - Preceding message's msg-id (for branching). Null means root.\n * @param opts.forkOf - Forked message's msg-id (for edit/regen).\n * @returns A headers record with the `x-ably-*` transport headers set.\n */\nexport const buildTransportHeaders = (opts: {\n role: string;\n turnId: string;\n msgId: string;\n turnClientId?: string;\n parent?: string | null;\n forkOf?: string;\n}): Record<string, string> => {\n const h: Record<string, string> = {\n [HEADER_ROLE]: opts.role,\n [HEADER_TURN_ID]: opts.turnId,\n [HEADER_MSG_ID]: opts.msgId,\n };\n if (opts.turnClientId !== undefined) h[HEADER_TURN_CLIENT_ID] = opts.turnClientId;\n if (opts.parent) h[HEADER_PARENT] = opts.parent;\n if (opts.forkOf) h[HEADER_FORK_OF] = opts.forkOf;\n return h;\n};\n","/**\n * Client-side stream routing.\n *\n * Maintains a map of turnId to ReadableStreamController. Routes decoded events\n * to the correct stream. Closes streams on terminal events or explicit close.\n */\n\nimport * as Ably from 'ably';\n\nimport { ErrorCode } from '../../errors.js';\nimport type { Logger } from '../../logger.js';\nimport type { TurnEntry } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/** Routes decoded events to the correct turn's ReadableStream. */\nexport interface StreamRouter<TEvent> {\n /** Register a new stream for a turnId. Returns the ReadableStream the consumer reads from. */\n createStream(turnId: string): ReadableStream<TEvent>;\n /** Close the stream for a turnId. Returns true if a stream was closed. */\n closeStream(turnId: string): boolean;\n /** Enqueue an event to the correct stream. Returns true if routed successfully. */\n route(turnId: string, event: TEvent): boolean;\n /** Whether a specific turnId has an active stream. */\n has(turnId: string): boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CT14\nclass DefaultStreamRouter<TEvent> implements StreamRouter<TEvent> {\n private readonly _turns = new Map<string, TurnEntry<TEvent>>();\n private readonly _isTerminal: (event: TEvent) => boolean;\n private readonly _logger: Logger;\n\n constructor(isTerminal: (event: TEvent) => boolean, logger: Logger) {\n this._isTerminal = isTerminal;\n this._logger = logger;\n }\n\n createStream(turnId: string): ReadableStream<TEvent> {\n this._logger.trace('StreamRouter.createStream();', { turnId });\n\n // Build stream+controller together. ReadableStream's start() runs synchronously\n // per spec, so the controller is captured before the constructor returns.\n const entry: { controller?: ReadableStreamDefaultController<TEvent> } = {};\n const stream = new ReadableStream<TEvent>({\n start(controller) {\n entry.controller = controller;\n },\n });\n if (!entry.controller) {\n throw new Ably.ErrorInfo(\n 'unable to create stream; ReadableStream start() was not called synchronously',\n ErrorCode.TransportSubscriptionError,\n 500,\n );\n }\n this._turns.set(turnId, { controller: entry.controller, turnId });\n return stream;\n }\n\n // Spec: AIT-CT14b\n closeStream(turnId: string): boolean {\n const turn = this._turns.get(turnId);\n if (!turn) return false;\n\n this._logger.debug('StreamRouter.closeStream(); closing stream', { turnId });\n try {\n turn.controller.close();\n } catch {\n /* already closed */\n }\n this._turns.delete(turnId);\n return true;\n }\n\n // Spec: AIT-CT14a\n route(turnId: string, event: TEvent): boolean {\n const turn = this._turns.get(turnId);\n if (!turn) return false;\n\n try {\n turn.controller.enqueue(event);\n } catch {\n this._turns.delete(turnId);\n return false;\n }\n\n if (this._isTerminal(event)) {\n this.closeStream(turnId);\n }\n return true;\n }\n\n has(turnId: string): boolean {\n return this._turns.has(turnId);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a StreamRouter that routes decoded events to per-turn ReadableStreams.\n * @param isTerminal - Predicate that returns true for events that close the stream.\n * @param logger - Logger for diagnostic output.\n * @returns A new {@link StreamRouter} instance.\n */\nexport const createStreamRouter = <TEvent>(\n isTerminal: (event: TEvent) => boolean,\n logger: Logger,\n): StreamRouter<TEvent> => new DefaultStreamRouter(isTerminal, logger);\n","/**\n * Core client-side transport, parameterized by codec.\n *\n * Composes StreamRouter and ConversationTree to handle the full client-side\n * lifecycle. Subscribes to the Ably channel on construction. The same\n * subscription, decoder, and channel are reused across turns.\n *\n * The client never publishes user messages directly. Instead, it sends them\n * to the server via HTTP POST. The server publishes user messages and turn\n * lifecycle events (turn-start, turn-end) on behalf of the client.\n */\n\nimport * as Ably from 'ably';\n\nimport {\n EVENT_CANCEL,\n EVENT_TURN_END,\n EVENT_TURN_START,\n HEADER_CANCEL_ALL,\n HEADER_CANCEL_CLIENT_ID,\n HEADER_CANCEL_OWN,\n HEADER_CANCEL_TURN_ID,\n HEADER_MSG_ID,\n HEADER_PARENT,\n HEADER_ROLE,\n HEADER_TURN_CLIENT_ID,\n HEADER_TURN_ID,\n HEADER_TURN_REASON,\n} from '../../constants.js';\nimport { ErrorCode } from '../../errors.js';\nimport { EventEmitter } from '../../event-emitter.js';\nimport type { Logger } from '../../logger.js';\nimport { LogLevel, makeLogger } from '../../logger.js';\nimport { getHeaders } from '../../utils.js';\nimport type { DecoderOutput, MessageAccumulator, StreamDecoder } from '../codec/types.js';\nimport { createConversationTree } from './conversation-tree.js';\nimport { decodeHistory } from './decode-history.js';\nimport { buildTransportHeaders } from './headers.js';\nimport type { StreamRouter } from './stream-router.js';\nimport { createStreamRouter } from './stream-router.js';\nimport type {\n ActiveTurn,\n CancelFilter,\n ClientTransport,\n ClientTransportOptions,\n CloseOptions,\n ConversationTree,\n LoadHistoryOptions,\n MessageWithHeaders,\n PaginatedMessages,\n SendOptions,\n TurnEndReason,\n TurnLifecycleEvent,\n} from './types.js';\n\n/**\n * Returned from `on()` when the transport is already closed — the subscription\n * is silently ignored since no further events will fire.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-function -- intentional no-op\nconst noopUnsubscribe = (): void => {};\n\n// ---------------------------------------------------------------------------\n// Event map for the transport's typed EventEmitter\n// ---------------------------------------------------------------------------\n\ninterface ClientTransportEventsMap {\n message: undefined;\n turn: TurnLifecycleEvent;\n error: Ably.ErrorInfo;\n 'ably-message': undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Per-turn observer state — consolidated to avoid parallel-map bookkeeping\n// ---------------------------------------------------------------------------\n\ninterface TurnObserverState<TEvent, TMessage> {\n headers: Record<string, string>;\n serial: string | undefined;\n accumulator: MessageAccumulator<TEvent, TMessage>;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CT1\nclass DefaultClientTransport<TEvent, TMessage> implements ClientTransport<TEvent, TMessage> {\n private readonly _channel: Ably.RealtimeChannel;\n private readonly _codec: ClientTransportOptions<TEvent, TMessage>['codec'];\n private readonly _clientId: string | undefined;\n private readonly _api: string;\n private readonly _credentials: RequestCredentials | undefined;\n private readonly _headersFn: (() => Record<string, string>) | undefined;\n private readonly _bodyFn: (() => Record<string, unknown>) | undefined;\n private readonly _fetchFn: typeof globalThis.fetch;\n private readonly _logger: Logger;\n\n // Typed event emitter for all transport events\n private readonly _emitter: EventEmitter<ClientTransportEventsMap>;\n\n // Relay detection — tracks msg-ids of optimistic inserts for reconciliation\n private readonly _ownMsgIds = new Set<string>();\n private readonly _ownTurnIds = new Set<string>();\n\n // Track clientId per turn for getActiveTurnIds()\n private readonly _turnClientIds = new Map<string, string>();\n // Track msgIds per turn for cleanup on turn-end\n private readonly _turnMsgIds = new Map<string, Set<string>>();\n\n // Per-turn observer state: headers, serial, and accumulator in one map.\n // A single .delete(turnId) cleans up all three.\n private readonly _turnObservers = new Map<string, TurnObserverState<TEvent, TMessage>>();\n\n // Raw Ably message log\n private readonly _ablyMessages: Ably.InboundMessage[] = [];\n\n // History pagination: withheld messages hidden from getMessages()\n private readonly _withheldKeys = new Set<string>();\n\n // Sub-components\n private readonly _tree: ConversationTree<TMessage>;\n private readonly _router: StreamRouter<TEvent>;\n private readonly _decoder: StreamDecoder<TEvent, TMessage>;\n\n // Channel subscription — subscribe() returns a Promise that resolves when the channel attaches\n private readonly _attachPromise: Promise<unknown>;\n private readonly _onMessage: (msg: Ably.InboundMessage) => void;\n\n private _closed = false;\n\n constructor(options: ClientTransportOptions<TEvent, TMessage>) {\n this._channel = options.channel;\n this._codec = options.codec;\n this._clientId = options.clientId;\n this._api = options.api ?? '/api/chat';\n this._credentials = options.credentials;\n this._headersFn =\n typeof options.headers === 'function'\n ? options.headers\n : options.headers\n ? () => options.headers as Record<string, string>\n : undefined;\n this._bodyFn =\n typeof options.body === 'function'\n ? options.body\n : options.body\n ? () => options.body as Record<string, unknown>\n : undefined;\n this._fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this._logger = (options.logger ?? makeLogger({ logLevel: LogLevel.Silent })).withContext({\n component: 'ClientTransport',\n });\n\n this._emitter = new EventEmitter<ClientTransportEventsMap>(this._logger);\n\n // Compose sub-components\n this._tree = createConversationTree<TMessage>(this._codec.getMessageKey.bind(this._codec), this._logger);\n this._router = createStreamRouter<TEvent>(this._codec.isTerminal.bind(this._codec), this._logger);\n this._decoder = this._codec.createDecoder();\n\n // Seed tree with initial messages\n if (options.messages) {\n let prevMsgId: string | undefined;\n for (const msg of options.messages) {\n const msgId = this._codec.getMessageKey(msg);\n const seedHeaders: Record<string, string> = {};\n if (prevMsgId) seedHeaders[HEADER_PARENT] = prevMsgId;\n this._tree.upsert(msgId, msg, seedHeaders);\n prevMsgId = msgId;\n }\n this._emitter.emit('message');\n }\n\n // Spec: AIT-CT2\n // Subscribe before attach (RTL7g)\n this._onMessage = (ablyMessage: Ably.InboundMessage) => {\n this._handleMessage(ablyMessage);\n };\n this._attachPromise = this._channel.subscribe(this._onMessage);\n }\n\n // ---------------------------------------------------------------------------\n // Message subscription handler\n // ---------------------------------------------------------------------------\n\n private _handleMessage(ablyMessage: Ably.InboundMessage): void {\n if (this._closed) return;\n\n this._ablyMessages.push(ablyMessage);\n this._emitter.emit('ably-message');\n\n try {\n // Spec: AIT-CT16a\n // --- Turn lifecycle events from the server ---\n if (ablyMessage.name === EVENT_TURN_START) {\n const headers = getHeaders(ablyMessage);\n const turnId = headers[HEADER_TURN_ID];\n const turnCid = headers[HEADER_TURN_CLIENT_ID] ?? '';\n if (turnId) {\n this._turnClientIds.set(turnId, turnCid);\n this._emitter.emit('turn', { type: EVENT_TURN_START, turnId, clientId: turnCid });\n }\n return;\n }\n\n if (ablyMessage.name === EVENT_TURN_END) {\n const headers = getHeaders(ablyMessage);\n const turnId = headers[HEADER_TURN_ID];\n const turnCid = headers[HEADER_TURN_CLIENT_ID] ?? '';\n // CAST: server always writes a valid TurnEndReason; default to 'complete' for robustness\n const reason = (headers[HEADER_TURN_REASON] ?? 'complete') as TurnEndReason;\n if (turnId) {\n this._router.closeStream(turnId);\n this._turnObservers.delete(turnId);\n this._turnClientIds.delete(turnId);\n // Clean up per-turn relay-detection state\n const msgIds = this._turnMsgIds.get(turnId);\n if (msgIds) {\n for (const mid of msgIds) this._ownMsgIds.delete(mid);\n this._turnMsgIds.delete(turnId);\n }\n this._ownTurnIds.delete(turnId);\n this._emitter.emit('turn', { type: EVENT_TURN_END, turnId, clientId: turnCid, reason });\n }\n return;\n }\n\n // --- Codec-decoded messages ---\n const outputs = this._decoder.decode(ablyMessage);\n const headers = getHeaders(ablyMessage);\n const serial = ablyMessage.serial;\n\n // Always update observer headers, even when the decoder produces no outputs.\n // This ensures header transitions (e.g. x-ably-status: streaming → aborted)\n // are captured for events that the decoder suppresses (AIT-CD8: aborted\n // stream appends emit no events but still carry the updated status header).\n const turnId = headers[HEADER_TURN_ID];\n if (turnId) {\n this._updateTurnObserverHeaders(turnId, headers, serial);\n }\n\n for (const output of outputs) {\n if (output.kind === 'message') {\n this._handleMessageOutput(output.message, headers, serial, ablyMessage.action);\n } else {\n this._handleEventOutput(output, headers);\n }\n }\n } catch (error) {\n const cause = error instanceof Ably.ErrorInfo ? error : undefined;\n this._emitter.emit(\n 'error',\n new Ably.ErrorInfo(\n `unable to process channel message; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.TransportSubscriptionError,\n 500,\n cause,\n ),\n );\n }\n }\n\n /**\n * Handle a decoded domain message (user message create or relayed own message).\n * @param message - The decoded domain message.\n * @param headers - Ably headers from the wire message.\n * @param serial - Ably serial for tree ordering.\n * @param action - Ably message action (e.g. 'message.create').\n */\n private _handleMessageOutput(\n message: TMessage,\n headers: Record<string, string>,\n serial: string | undefined,\n action: string | undefined,\n ): void {\n // Spec: AIT-CT15\n const msgId = headers[HEADER_MSG_ID];\n if (msgId && this._ownMsgIds.has(msgId)) {\n // Relayed own message — reconcile optimistic entry with server-assigned fields\n this._upsertAndNotify(message, headers, serial);\n return;\n }\n\n if (action === 'message.create') {\n this._upsertAndNotify(message, headers, serial);\n }\n }\n\n /**\n * Handle a decoded streaming event: route to own-turn stream or accumulate for observer.\n * @param output - The decoded event output from the codec.\n * @param headers - Ably headers from the wire message.\n */\n private _handleEventOutput(output: DecoderOutput<TEvent, TMessage>, headers: Record<string, string>): void {\n if (output.kind !== 'event') return;\n const event = output.event;\n const turnId = headers[HEADER_TURN_ID];\n if (!turnId) return;\n\n // Observer headers are already updated in _handleMessage (before outputs\n // are iterated) so that header transitions are captured even when the\n // decoder produces no outputs (e.g. aborted stream appends per AIT-CD8).\n\n // Active own turn — route to the ReadableStream\n if (this._router.route(turnId, event)) {\n this._accumulateAndEmit(turnId, output);\n if (this._codec.isTerminal(event)) this._turnObservers.delete(turnId);\n return;\n }\n\n // Completed own turn — late arrival, skip\n if (this._ownTurnIds.has(turnId) && !this._turnObservers.has(turnId)) return;\n\n // Spec: AIT-CT16\n // Observer turn — accumulate and emit\n this._accumulateAndEmit(turnId, output);\n if (this._codec.isTerminal(event)) this._turnObservers.delete(turnId);\n }\n\n // ---------------------------------------------------------------------------\n // Tree mutation + notification helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Upsert a message into the tree and notify subscribers.\n * @param message - The domain message to insert or update.\n * @param headers - Ably headers for the message.\n * @param serial - Ably serial for tree ordering.\n */\n private _upsertAndNotify(message: TMessage, headers: Record<string, string>, serial?: string): void {\n const key = this._codec.getMessageKey(message);\n const msgId = headers[HEADER_MSG_ID] ?? key;\n this._tree.upsert(msgId, message, headers, serial);\n this._emitter.emit('message');\n }\n\n // ---------------------------------------------------------------------------\n // Observer accumulation\n // ---------------------------------------------------------------------------\n\n /**\n * Ensure a TurnObserverState exists for turnId, updating headers and serial as new events arrive.\n * @param turnId - The turn to track.\n * @param headers - Headers from the current event.\n * @param serial - Ably serial from the current event.\n */\n private _updateTurnObserverHeaders(\n turnId: string,\n headers: Record<string, string>,\n serial: string | undefined,\n ): void {\n const existing = this._turnObservers.get(turnId);\n if (existing) {\n if (Object.keys(headers).length > 0) {\n Object.assign(existing.headers, headers);\n }\n // Always advance the serial so the tree node sorts after all\n // earlier messages in the turn (e.g. user-message relays that\n // arrive before the assistant response).\n if (serial !== undefined) {\n existing.serial = serial;\n }\n } else {\n this._turnObservers.set(turnId, {\n headers: { ...headers },\n serial,\n accumulator: this._codec.createAccumulator(),\n });\n }\n }\n\n /**\n * Process a streaming event through the turn's accumulator and emit the latest message.\n * @param turnId - The turn this event belongs to.\n * @param output - The decoded event output to accumulate.\n */\n private _accumulateAndEmit(turnId: string, output: DecoderOutput<TEvent, TMessage>): void {\n const observer = this._turnObservers.get(turnId);\n if (!observer) return;\n\n observer.accumulator.processOutputs([output]);\n\n const messages = observer.accumulator.messages;\n if (messages.length === 0) return;\n\n let message: TMessage | undefined;\n try {\n message = structuredClone(messages.at(-1));\n } catch {\n // CAST: structuredClone can fail if the message contains non-cloneable\n // values (e.g. functions). Fall back to the reference — the tree upsert\n // below copies headers independently, so shared message state is the\n // only risk. Accumulator messages are replaced on each event, so\n // mutation between events is not a practical concern.\n message = messages.at(-1);\n }\n\n if (message) {\n this._tree.upsert(\n observer.headers[HEADER_MSG_ID] ?? this._codec.getMessageKey(message),\n message,\n { ...observer.headers },\n observer.serial,\n );\n this._emitter.emit('message');\n }\n }\n\n // ---------------------------------------------------------------------------\n // Cancel helpers\n // ---------------------------------------------------------------------------\n\n private async _publishCancel(filter: CancelFilter): Promise<void> {\n this._logger.trace('ClientTransport._publishCancel();', { filter });\n\n const headers: Record<string, string> = {};\n if (filter.turnId) {\n headers[HEADER_CANCEL_TURN_ID] = filter.turnId;\n } else if (filter.own) {\n headers[HEADER_CANCEL_OWN] = 'true';\n } else if (filter.clientId) {\n headers[HEADER_CANCEL_CLIENT_ID] = filter.clientId;\n } else if (filter.all) {\n headers[HEADER_CANCEL_ALL] = 'true';\n }\n\n await this._channel.publish({\n name: EVENT_CANCEL,\n extras: { headers },\n });\n }\n\n private _closeMatchingTurnStreams(filter: CancelFilter): void {\n // Only close the router streams here — do NOT clear _turnObservers.\n // The observer must remain alive so that late server events (e.g. abort,\n // x-ably-status: aborted) arriving before turn-end are still accumulated\n // into the message store. The turn-end handler cleans up observers.\n if (filter.all) {\n for (const turnId of this._ownTurnIds) {\n this._router.closeStream(turnId);\n }\n } else if (filter.own) {\n for (const tid of this._ownTurnIds) {\n this._router.closeStream(tid);\n }\n } else if (filter.clientId) {\n for (const [tid, cid] of this._turnClientIds) {\n if (cid === filter.clientId) {\n this._router.closeStream(tid);\n }\n }\n } else if (filter.turnId) {\n this._router.closeStream(filter.turnId);\n }\n }\n\n private _getMatchingTurnIds(filter: CancelFilter): Set<string> {\n const matched = new Set<string>();\n if (filter.all) {\n for (const turnId of this._turnClientIds.keys()) matched.add(turnId);\n } else if (filter.own) {\n for (const [turnId, cid] of this._turnClientIds) {\n if (cid === this._clientId) matched.add(turnId);\n }\n } else if (filter.clientId) {\n for (const [turnId, cid] of this._turnClientIds) {\n if (cid === filter.clientId) matched.add(turnId);\n }\n } else if (filter.turnId && this._turnClientIds.has(filter.turnId)) {\n matched.add(filter.turnId);\n }\n return matched;\n }\n\n // ---------------------------------------------------------------------------\n // Input message helpers\n // ---------------------------------------------------------------------------\n\n private _getMessagesWithHeaders(): MessageWithHeaders<TMessage>[] {\n return this._tree.flatten().map((m) => ({\n message: m,\n headers: this.getMessageHeaders(m),\n }));\n }\n\n /**\n * Compute truncated history: everything before the target message.\n * Used by regenerate so the LLM doesn't see the response being replaced.\n * @param messageId - The msg-id to truncate history before.\n * @returns Input messages preceding the target.\n */\n private _getHistoryBefore(messageId: string): MessageWithHeaders<TMessage>[] {\n const all = this._getMessagesWithHeaders();\n const idx = all.findIndex((inp) => inp.headers?.[HEADER_MSG_ID] === messageId);\n return idx === -1 ? all : all.slice(0, idx);\n }\n\n // ---------------------------------------------------------------------------\n // History pagination helpers\n // ---------------------------------------------------------------------------\n\n private _processHistoryPage(page: PaginatedMessages<TMessage>): void {\n for (const [i, message] of page.items.entries()) {\n const headers = page.itemHeaders?.[i] ?? {};\n const serial = page.itemSerials?.[i];\n const key = this._codec.getMessageKey(message);\n const msgId = headers[HEADER_MSG_ID] ?? key;\n this._tree.upsert(msgId, message, headers, serial);\n }\n this._emitter.emit('message');\n\n // Prepend raw Ably messages (older messages go at the beginning)\n if (page.rawMessages && page.rawMessages.length > 0) {\n this._ablyMessages.unshift(...page.rawMessages);\n this._emitter.emit('ably-message');\n }\n }\n\n private async _loadUntilVisible(\n firstPage: PaginatedMessages<TMessage>,\n target: number,\n beforeKeys: Set<string>,\n ): Promise<{ newVisible: TMessage[]; lastPage: PaginatedMessages<TMessage> }> {\n this._processHistoryPage(firstPage);\n let page = firstPage;\n\n const newVisibleCount = (): number => {\n let count = 0;\n for (const m of this._tree.flatten()) {\n if (!beforeKeys.has(this._codec.getMessageKey(m))) count++;\n }\n return count;\n };\n\n while (newVisibleCount() < target && page.hasNext()) {\n const nextPage = await page.next();\n if (!nextPage) break;\n this._processHistoryPage(nextPage);\n page = nextPage;\n }\n\n const newVisible = this._tree.flatten().filter((m) => !beforeKeys.has(this._codec.getMessageKey(m)));\n return { newVisible, lastPage: page };\n }\n\n private _releaseWithheld(messages: TMessage[]): void {\n for (const m of messages) {\n this._withheldKeys.delete(this._codec.getMessageKey(m));\n }\n if (messages.length > 0) {\n this._emitter.emit('message');\n }\n }\n\n // ---------------------------------------------------------------------------\n // Public API\n // ---------------------------------------------------------------------------\n\n // Spec: AIT-CT3, AIT-CT4\n async send(input: TMessage | TMessage[], sendOptions?: SendOptions): Promise<ActiveTurn<TEvent>> {\n if (this._closed) {\n throw new Ably.ErrorInfo('unable to send; transport is closed', ErrorCode.TransportClosed, 400);\n }\n await this._attachPromise;\n // CAST: re-check after await — close() may have been called while waiting for attach.\n // TypeScript's control flow narrows _closed to false after the first check, but the\n // await yields and close() can mutate _closed concurrently.\n if (this._closed as boolean) {\n throw new Ably.ErrorInfo('unable to send; transport is closed', ErrorCode.TransportClosed, 400);\n }\n\n this._logger.trace('ClientTransport.send();');\n\n const msgs = Array.isArray(input) ? input : [input];\n const turnId = crypto.randomUUID();\n this._ownTurnIds.add(turnId);\n\n const msgIds = new Set<string>();\n const postMessages: { message: TMessage; headers: Record<string, string> }[] = [];\n\n // Capture history BEFORE optimistic inserts. The optimistic messages are\n // sent in the `messages` field — including them in `history` too would\n // cause the server to see them twice.\n const preInsertHistory = this._getMessagesWithHeaders();\n\n // Spec: AIT-CT3d\n // Auto-compute parent from the current thread if not explicitly provided\n let autoParent: string | undefined;\n if (sendOptions?.parent === undefined && !sendOptions?.forkOf) {\n const flat = this._tree.flatten();\n if (flat.length > 0) {\n const lastMsg = flat.at(-1);\n if (lastMsg) {\n const lastKey = this._codec.getMessageKey(lastMsg);\n const lastNode = this._tree.getNodeByKey(lastKey);\n autoParent = lastNode?.msgId ?? lastKey;\n }\n }\n }\n\n // Capture the first parent for the POST body before the loop advances it.\n const postParent = sendOptions?.parent === undefined ? autoParent : sendOptions.parent;\n\n for (const message of msgs) {\n const msgId = crypto.randomUUID();\n this._ownMsgIds.add(msgId);\n msgIds.add(msgId);\n\n const resolvedParent = sendOptions?.parent === undefined ? autoParent : (sendOptions.parent ?? undefined);\n\n const optimisticHeaders = buildTransportHeaders({\n role: 'user',\n turnId,\n msgId,\n turnClientId: this._clientId,\n parent: resolvedParent,\n forkOf: sendOptions?.forkOf,\n });\n // Spec: AIT-CT3c\n // Optimistically insert each user message into the tree\n this._upsertAndNotify(message, optimisticHeaders);\n\n // Include per-message parent so the server chains messages correctly.\n const postHeaders: Record<string, string> = { [HEADER_MSG_ID]: msgId, [HEADER_ROLE]: 'user' };\n if (resolvedParent) postHeaders[HEADER_PARENT] = resolvedParent;\n postMessages.push({ message, headers: postHeaders });\n\n // Spec: AIT-CT3e\n // Chain: each subsequent message in the batch parents off the previous\n // one, forming a linear conversation thread rather than siblings.\n if (sendOptions?.parent === undefined && !sendOptions?.forkOf) {\n autoParent = msgId;\n }\n }\n\n this._turnMsgIds.set(turnId, msgIds);\n\n // Create ReadableStream via router\n const stream = this._router.createStream(turnId);\n\n // Resolve headers and body\n const resolvedHeaders = this._headersFn?.() ?? {};\n const resolvedBody = this._bodyFn?.() ?? {};\n\n const postBody: Record<string, unknown> = {\n ...resolvedBody,\n history: preInsertHistory,\n ...sendOptions?.body,\n turnId,\n clientId: this._clientId,\n messages: postMessages,\n ...(sendOptions?.forkOf !== undefined && { forkOf: sendOptions.forkOf }),\n ...(postParent !== undefined && { parent: postParent }),\n };\n\n const postHeaders: Record<string, string> = {\n ...resolvedHeaders,\n ...sendOptions?.headers,\n };\n\n // Spec: AIT-CT3a, AIT-CT3b\n // Fire-and-forget: POST must not block the stream return to the caller.\n // .catch() is intentional — async/await would delay stream availability.\n this._fetchFn(this._api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...postHeaders,\n },\n body: JSON.stringify(postBody),\n ...(this._credentials ? { credentials: this._credentials } : {}),\n })\n .then((response) => {\n if (!response.ok) {\n this._emitter.emit(\n 'error',\n new Ably.ErrorInfo(\n `unable to send; HTTP POST to ${this._api} returned ${String(response.status)} ${response.statusText}`,\n ErrorCode.TransportSendFailed,\n response.status,\n ),\n );\n this._router.closeStream(turnId);\n }\n })\n .catch((error: unknown) => {\n const cause = error instanceof Ably.ErrorInfo ? error : undefined;\n this._emitter.emit(\n 'error',\n new Ably.ErrorInfo(\n `unable to send; HTTP POST to ${this._api} failed: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.TransportSendFailed,\n 500,\n cause,\n ),\n );\n this._router.closeStream(turnId);\n });\n\n return {\n stream,\n turnId,\n cancel: async () => this.cancel({ turnId }),\n };\n }\n\n // Spec: AIT-CT5\n async regenerate(messageId: string, sendOptions?: SendOptions): Promise<ActiveTurn<TEvent>> {\n this._logger.trace('ClientTransport.regenerate();', { messageId });\n\n const node = this._tree.getNode(messageId);\n const parentId = node?.parentId;\n\n return this.send([], {\n ...sendOptions,\n body: {\n history: this._getHistoryBefore(messageId),\n ...sendOptions?.body,\n },\n forkOf: messageId,\n parent: parentId,\n });\n }\n\n // Spec: AIT-CT6\n async edit(\n messageId: string,\n newMessages: TMessage | TMessage[],\n sendOptions?: SendOptions,\n ): Promise<ActiveTurn<TEvent>> {\n this._logger.trace('ClientTransport.edit();', { messageId });\n\n const node = this._tree.getNode(messageId);\n const parentId = node?.parentId;\n\n return this.send(newMessages, {\n ...sendOptions,\n body: {\n history: this._getHistoryBefore(messageId),\n ...sendOptions?.body,\n },\n forkOf: messageId,\n parent: parentId,\n });\n }\n\n // Spec: AIT-CT7, AIT-CT7a\n async cancel(filter?: CancelFilter): Promise<void> {\n if (this._closed) return;\n const resolved = filter ?? { own: true };\n this._logger.debug('ClientTransport.cancel();', { filter: resolved });\n await this._publishCancel(resolved);\n this._closeMatchingTurnStreams(resolved);\n }\n\n // Spec: AIT-CT18\n async waitForTurn(filter?: CancelFilter): Promise<void> {\n if (this._closed) return;\n const resolved = filter ?? { own: true };\n const remaining = this._getMatchingTurnIds(resolved);\n if (remaining.size === 0) return;\n\n this._logger.debug('ClientTransport.waitForTurn();', { turnIds: [...remaining] });\n\n return new Promise<void>((resolve) => {\n const handler = (event: TurnLifecycleEvent): void => {\n if (event.type !== EVENT_TURN_END) return;\n remaining.delete(event.turnId);\n if (remaining.size === 0) {\n this._emitter.off('turn', handler);\n resolve();\n }\n };\n this._emitter.on('turn', handler);\n });\n }\n\n // Spec: AIT-CT8, AIT-CT8a, AIT-CT8b, AIT-CT8c, AIT-CT8d\n on(event: 'message' | 'ably-message', handler: () => void): () => void;\n on(event: 'turn', handler: (event: TurnLifecycleEvent) => void): () => void;\n on(event: 'error', handler: (error: Ably.ErrorInfo) => void): () => void;\n on(\n eventName: 'message' | 'turn' | 'error' | 'ably-message',\n handler: (() => void) | ((event: TurnLifecycleEvent) => void) | ((error: Ably.ErrorInfo) => void),\n ): () => void {\n if (this._closed) return noopUnsubscribe;\n // CAST: the overload signatures enforce correct handler types per event name.\n // The implementation must cast to satisfy the EventEmitter's generic callback type.\n const cb = handler as (arg: ClientTransportEventsMap[keyof ClientTransportEventsMap]) => void;\n this._emitter.on(eventName, cb);\n return () => {\n this._emitter.off(eventName, cb);\n };\n }\n\n // Spec: AIT-CT10\n getTree(): ConversationTree<TMessage> {\n return this._tree;\n }\n\n // Spec: AIT-CT17\n getActiveTurnIds(): Map<string, Set<string>> {\n const result = new Map<string, Set<string>>();\n for (const [turnId, cid] of this._turnClientIds) {\n let set = result.get(cid);\n if (!set) {\n set = new Set();\n result.set(cid, set);\n }\n set.add(turnId);\n }\n return result;\n }\n\n getMessageHeaders(message: TMessage): Record<string, string> | undefined {\n const key = this._codec.getMessageKey(message);\n return this._tree.getNodeByKey(key)?.headers;\n }\n\n // Spec: AIT-CT9\n getMessages(): TMessage[] {\n if (this._withheldKeys.size === 0) return this._tree.flatten();\n return this._tree.flatten().filter((m) => !this._withheldKeys.has(this._codec.getMessageKey(m)));\n }\n\n getMessagesWithHeaders(): MessageWithHeaders<TMessage>[] {\n return this._getMessagesWithHeaders();\n }\n\n getAblyMessages(): Ably.InboundMessage[] {\n return [...this._ablyMessages];\n }\n\n // Spec: AIT-CT11, AIT-CT11a, AIT-CT11b, AIT-CT11c\n async history(opts?: LoadHistoryOptions): Promise<PaginatedMessages<TMessage>> {\n if (this._closed) {\n throw new Ably.ErrorInfo('unable to load history; transport is closed', ErrorCode.TransportClosed, 400);\n }\n this._logger.trace('ClientTransport.history();', { limit: opts?.limit });\n const limit = opts?.limit ?? 100;\n\n // Snapshot before loading — everything already in the tree stays visible\n const beforeKeys = new Set(this._tree.flatten().map((m) => this._codec.getMessageKey(m)));\n\n let lastPage = await decodeHistory(this._channel, this._codec, opts, this._logger);\n\n const initial = await this._loadUntilVisible(lastPage, limit, beforeKeys);\n lastPage = initial.lastPage;\n\n // newVisible is chronological (oldest-first from flatten).\n // For \"load older\" pagination: release the NEWEST `limit` now,\n // withhold the older ones for subsequent next() calls.\n const newVisible = initial.newVisible;\n\n // Withhold ALL new visible messages first, then release the newest batch\n for (const m of newVisible) {\n this._withheldKeys.add(this._codec.getMessageKey(m));\n }\n\n const released = newVisible.slice(-limit);\n // Mutable buffer of older messages, drained newest-first by successive next() calls\n const withheldBuffer = newVisible.slice(0, -limit);\n this._releaseWithheld(released);\n\n const buildPage = (items: TMessage[]): PaginatedMessages<TMessage> => ({\n items,\n hasNext: () => withheldBuffer.length > 0 || lastPage.hasNext(),\n next: async () => {\n // Drain withheld buffer first (older messages, released newest-first)\n if (withheldBuffer.length > 0) {\n // Remove and return the newest `limit` items from the buffer\n const batch = withheldBuffer.splice(-limit, limit);\n this._releaseWithheld(batch);\n return buildPage(batch);\n }\n\n // Buffer exhausted — load more pages from decodeHistory\n if (!lastPage.hasNext()) return;\n\n const nextInternal = await lastPage.next();\n if (!nextInternal) return;\n\n // Everything currently in the tree is \"already known\"\n const alreadyKnown = new Set(beforeKeys);\n for (const m of this._tree.flatten()) {\n alreadyKnown.add(this._codec.getMessageKey(m));\n }\n\n const loaded = await this._loadUntilVisible(nextInternal, limit, alreadyKnown);\n lastPage = loaded.lastPage;\n\n const moreVisible = loaded.newVisible;\n for (const m of moreVisible) {\n this._withheldKeys.add(this._codec.getMessageKey(m));\n }\n // Remove and return the newest `limit` items; rest stays in buffer\n const moreBatch = moreVisible.splice(-limit, limit);\n withheldBuffer.push(...moreVisible);\n this._releaseWithheld(moreBatch);\n\n if (moreBatch.length === 0) return;\n return buildPage(moreBatch);\n },\n });\n\n return buildPage(released);\n }\n\n // Spec: AIT-CT12, AIT-CT12a, AIT-CT12b\n async close(options?: CloseOptions): Promise<void> {\n if (this._closed) return;\n this._closed = true;\n this._logger.info('ClientTransport.close();');\n\n // Best-effort cancel publish before tearing down local state\n if (options?.cancel) {\n try {\n await this._publishCancel(options.cancel);\n } catch {\n // Swallow: cancel is best-effort during teardown\n }\n this._closeMatchingTurnStreams(options.cancel);\n }\n\n this._channel.unsubscribe(this._onMessage);\n\n // Close any remaining active streams\n for (const turnId of this._ownTurnIds) {\n this._router.closeStream(turnId);\n }\n\n this._turnObservers.clear();\n this._emitter.off();\n this._ownTurnIds.clear();\n this._ownMsgIds.clear();\n this._turnMsgIds.clear();\n this._turnClientIds.clear();\n this._withheldKeys.clear();\n this._ablyMessages.length = 0;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a client-side transport that manages conversation state over an Ably channel.\n *\n * Subscribes to the channel immediately (before attach per RTL7g). The caller should\n * ensure the channel is attached or will be attached shortly after creation.\n * @param options - Configuration for the client transport.\n * @returns A new {@link ClientTransport} instance.\n */\nexport const createClientTransport = <TEvent, TMessage>(\n options: ClientTransportOptions<TEvent, TMessage>,\n): ClientTransport<TEvent, TMessage> => new DefaultClientTransport(options);\n","/**\n * Pure stream piping function.\n *\n * Reads events from a ReadableStream, writes them to a streaming encoder,\n * and handles abort/error. No dependencies on turn state or transport internals.\n */\n\nimport type { Logger } from '../../logger.js';\nimport type { StreamEncoder } from '../codec/types.js';\nimport type { StreamResult } from './types.js';\n\n/**\n * Pipe an event stream through an encoder to the channel.\n *\n * Returns when the stream completes, is cancelled (via signal), or errors.\n * The `reason` field of the result indicates which case occurred.\n * @param stream - The event stream to read from.\n * @param encoder - The streaming encoder to write events through.\n * @param signal - Abort signal to monitor for cancellation.\n * @param onAbort - Optional callback invoked when the stream is cancelled, before the stream ends.\n * @param logger - Optional logger for diagnostic output.\n * @returns The reason the pipe ended.\n */\nexport const pipeStream = async <TEvent, TMessage>(\n stream: ReadableStream<TEvent>,\n encoder: StreamEncoder<TEvent, TMessage>,\n signal: AbortSignal | undefined,\n onAbort?: (write: (event: TEvent) => Promise<void>) => void | Promise<void>,\n logger?: Logger,\n): Promise<StreamResult> => {\n logger?.trace('pipeStream();');\n\n const reader = stream.getReader();\n\n let abortListener: (() => void) | undefined;\n const abortPromise = signal\n ? new Promise<void>((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n abortListener = () => {\n resolve();\n };\n signal.addEventListener('abort', abortListener, { once: true });\n })\n : // eslint-disable-next-line @typescript-eslint/no-empty-function -- never-resolving promise: no signal means no cancellation path\n new Promise<void>(() => {});\n\n let reason: StreamResult['reason'] = 'complete';\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- intentional infinite loop broken by return/break\n while (true) {\n // .then() is intentional: transforms the abort signal into a discriminant\n // for Promise.race — no async/await equivalent for this pattern.\n const result = await Promise.race([reader.read(), abortPromise.then(() => 'aborted' as const)]);\n\n if (result === 'aborted') {\n reason = 'cancelled';\n logger?.debug('pipeStream(); stream cancelled by abort signal');\n if (onAbort) {\n await onAbort(async (event: TEvent) => encoder.appendEvent(event));\n }\n await encoder.abort('cancelled');\n break;\n }\n\n const { done, value } = result;\n if (done) {\n await encoder.close();\n logger?.debug('pipeStream(); stream completed');\n break;\n }\n\n await encoder.appendEvent(value);\n }\n } catch (error) {\n reason = 'error';\n const errorText = error instanceof Error ? error.message : String(error);\n logger?.error('pipeStream(); stream error', { error: errorText });\n try {\n await encoder.close();\n } catch {\n // Best-effort: encoder close in the error path may also fail\n // (e.g. channel disconnected). The original error is preserved in\n // the StreamResult reason (\"error\").\n }\n } finally {\n if (abortListener) signal?.removeEventListener('abort', abortListener);\n reader.releaseLock();\n }\n\n return { reason };\n};\n","/**\n * Server-side turn state management and lifecycle event publishing.\n *\n * Owns the authoritative turn lifecycle. Tracks active turns with their\n * AbortControllers and clientIds. Publishes turn-start and turn-end events\n * on the Ably channel so all clients can react to turn state changes.\n */\n\nimport type * as Ably from 'ably';\n\nimport {\n EVENT_TURN_END,\n EVENT_TURN_START,\n HEADER_TURN_CLIENT_ID,\n HEADER_TURN_ID,\n HEADER_TURN_REASON,\n} from '../../constants.js';\nimport type { Logger } from '../../logger.js';\nimport type { TurnEndReason } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/** Manages active turns and publishes turn lifecycle events on the channel. */\nexport interface TurnManager {\n /** Register a new turn. Publishes turn-start on the channel. Returns AbortSignal. */\n startTurn(turnId: string, clientId?: string, controller?: AbortController): Promise<AbortSignal>;\n /** End a turn. Publishes turn-end on the channel. Cleans up internal state. */\n endTurn(turnId: string, reason: TurnEndReason): Promise<void>;\n /** Get the AbortSignal for a turn. */\n getSignal(turnId: string): AbortSignal | undefined;\n /** Get the clientId that owns a turn. */\n getClientId(turnId: string): string | undefined;\n /** Abort the signal for a turn. */\n abort(turnId: string): void;\n /** Get all active turn IDs. */\n getActiveTurnIds(): string[];\n /** Abort all active turns and clear state. */\n close(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\ninterface TurnState {\n controller: AbortController;\n clientId: string;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nclass DefaultTurnManager implements TurnManager {\n private readonly _channel: Ably.RealtimeChannel;\n private readonly _logger: Logger | undefined;\n private readonly _activeTurns = new Map<string, TurnState>();\n\n constructor(channel: Ably.RealtimeChannel, logger?: Logger) {\n this._channel = channel;\n this._logger = logger?.withContext({ component: 'TurnManager' });\n }\n\n async startTurn(turnId: string, clientId?: string, externalController?: AbortController): Promise<AbortSignal> {\n this._logger?.trace('DefaultTurnManager.startTurn();', { turnId, clientId });\n\n const controller = externalController ?? new AbortController();\n const resolvedClientId = clientId ?? '';\n this._activeTurns.set(turnId, { controller, clientId: resolvedClientId });\n\n await this._channel.publish({\n name: EVENT_TURN_START,\n extras: {\n headers: {\n [HEADER_TURN_ID]: turnId,\n [HEADER_TURN_CLIENT_ID]: resolvedClientId,\n },\n },\n });\n\n this._logger?.debug('DefaultTurnManager.startTurn(); turn started', { turnId });\n return controller.signal;\n }\n\n async endTurn(turnId: string, reason: TurnEndReason): Promise<void> {\n this._logger?.trace('DefaultTurnManager.endTurn();', { turnId, reason });\n\n const state = this._activeTurns.get(turnId);\n const resolvedClientId = state?.clientId ?? '';\n\n // Publish before deleting local state so that if publish fails,\n // the turn remains in the active set and can be retried or cleaned up.\n await this._channel.publish({\n name: EVENT_TURN_END,\n extras: {\n headers: {\n [HEADER_TURN_ID]: turnId,\n [HEADER_TURN_CLIENT_ID]: resolvedClientId,\n [HEADER_TURN_REASON]: reason,\n },\n },\n });\n\n this._activeTurns.delete(turnId);\n this._logger?.debug('DefaultTurnManager.endTurn(); turn ended', { turnId, reason });\n }\n\n getSignal(turnId: string): AbortSignal | undefined {\n return this._activeTurns.get(turnId)?.controller.signal;\n }\n\n getClientId(turnId: string): string | undefined {\n return this._activeTurns.get(turnId)?.clientId;\n }\n\n abort(turnId: string): void {\n this._logger?.debug('DefaultTurnManager.abort();', { turnId });\n this._activeTurns.get(turnId)?.controller.abort();\n }\n\n getActiveTurnIds(): string[] {\n return [...this._activeTurns.keys()];\n }\n\n close(): void {\n this._logger?.trace('DefaultTurnManager.close();', { activeTurns: this._activeTurns.size });\n for (const state of this._activeTurns.values()) {\n state.controller.abort();\n }\n this._activeTurns.clear();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a turn manager bound to the given channel.\n * @param channel - The Ably channel to publish lifecycle events on.\n * @param logger - Optional logger for diagnostic output.\n * @returns A new {@link TurnManager} instance.\n */\nexport const createTurnManager = (channel: Ably.RealtimeChannel, logger?: Logger): TurnManager =>\n new DefaultTurnManager(channel, logger);\n","/**\n * Core server-side transport, parameterized by codec.\n *\n * Composes TurnManager and pipeStream to handle the full server-side turn\n * lifecycle. Cancel message routing is handled directly by the transport's\n * single channel subscription — no separate cancel manager needed.\n *\n * The transport exposes a single factory method — `newTurn()` — which returns\n * a Turn object with explicit lifecycle methods: start(), addMessages(),\n * streamResponse(), and end().\n */\n\nimport * as Ably from 'ably';\n\nimport {\n EVENT_CANCEL,\n HEADER_CANCEL_ALL,\n HEADER_CANCEL_CLIENT_ID,\n HEADER_CANCEL_OWN,\n HEADER_CANCEL_TURN_ID,\n HEADER_MSG_ID,\n} from '../../constants.js';\nimport { ErrorCode } from '../../errors.js';\nimport type { Logger } from '../../logger.js';\nimport { getHeaders, mergeHeaders } from '../../utils.js';\nimport { buildTransportHeaders } from './headers.js';\nimport { pipeStream } from './pipe-stream.js';\nimport type { TurnManager } from './turn-manager.js';\nimport { createTurnManager } from './turn-manager.js';\nimport type {\n AddMessageOptions,\n AddMessagesResult,\n CancelFilter,\n CancelRequest,\n MessageWithHeaders,\n NewTurnOptions,\n ServerTransport,\n ServerTransportOptions,\n StreamResponseOptions,\n StreamResult,\n Turn,\n TurnEndReason,\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Internal turn record for cancel routing\n// ---------------------------------------------------------------------------\n\ninterface RegisteredTurn {\n turnId: string;\n clientId: string;\n controller: AbortController;\n onCancel?: (request: CancelRequest) => Promise<boolean>;\n onError?: (error: Ably.ErrorInfo) => void;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-ST1\nclass DefaultServerTransport<TEvent, TMessage> implements ServerTransport<TEvent, TMessage> {\n private readonly _channel: Ably.RealtimeChannel;\n private readonly _codec: ServerTransportOptions<TEvent, TMessage>['codec'];\n private readonly _logger: Logger | undefined;\n private readonly _onError: ((error: Ably.ErrorInfo) => void) | undefined;\n private readonly _turnManager: TurnManager;\n private readonly _registeredTurns = new Map<string, RegisteredTurn>();\n private readonly _channelListener: (msg: Ably.InboundMessage) => void;\n private readonly _attachPromise: Promise<void>;\n\n constructor(options: ServerTransportOptions<TEvent, TMessage>) {\n this._channel = options.channel;\n this._codec = options.codec;\n this._logger = options.logger?.withContext({ component: 'ServerTransport' });\n this._onError = options.onError;\n this._turnManager = createTurnManager(this._channel, this._logger);\n\n this._channelListener = (msg: Ably.InboundMessage) => {\n this._handleChannelMessage(msg);\n };\n\n // Spec: AIT-ST2\n // Subscribe before attach (RTL7g) — ensures no messages are missed.\n this._attachPromise = this._channel.subscribe(EVENT_CANCEL, this._channelListener).then(\n /* eslint-disable @typescript-eslint/no-empty-function -- discard subscription handle */\n () => {},\n /* eslint-enable @typescript-eslint/no-empty-function */\n (error: unknown) => {\n const errInfo = new Ably.ErrorInfo(\n `unable to subscribe to cancel messages; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.TransportSubscriptionError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger?.error('DefaultServerTransport(); subscribe failed');\n this._onError?.(errInfo);\n },\n );\n\n this._logger?.debug('DefaultServerTransport(); transport created');\n }\n\n // -------------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------------\n\n // Spec: AIT-ST3\n newTurn(turnOpts: NewTurnOptions<TEvent>): Turn<TEvent, TMessage> {\n this._logger?.trace('DefaultServerTransport.newTurn();', { turnId: turnOpts.turnId });\n return this._createTurn(turnOpts);\n }\n\n // Spec: AIT-ST11\n close(): void {\n this._logger?.trace('DefaultServerTransport.close();');\n this._channel.unsubscribe(EVENT_CANCEL, this._channelListener);\n for (const reg of this._registeredTurns.values()) {\n reg.controller.abort();\n }\n this._registeredTurns.clear();\n this._turnManager.close();\n this._logger?.debug('DefaultServerTransport.close(); transport closed');\n }\n\n // -------------------------------------------------------------------------\n // Cancel message routing\n // -------------------------------------------------------------------------\n\n private _resolveFilter(filter: CancelFilter, senderClientId?: string): string[] {\n const turnIds = [...this._registeredTurns.keys()];\n\n if (filter.all) return turnIds;\n if (filter.own && senderClientId) {\n return turnIds.filter((id) => this._registeredTurns.get(id)?.clientId === senderClientId);\n }\n if (filter.clientId) {\n return turnIds.filter((id) => this._registeredTurns.get(id)?.clientId === filter.clientId);\n }\n if (filter.turnId && this._registeredTurns.has(filter.turnId)) {\n return [filter.turnId];\n }\n return [];\n }\n\n // Spec: AIT-ST8, AIT-ST9\n private async _handleCancelMessage(msg: Ably.InboundMessage): Promise<void> {\n const headers = getHeaders(msg);\n\n const filter: CancelFilter = {};\n if (headers[HEADER_CANCEL_TURN_ID]) {\n filter.turnId = headers[HEADER_CANCEL_TURN_ID];\n } else if (headers[HEADER_CANCEL_OWN] === 'true') {\n filter.own = true;\n } else if (headers[HEADER_CANCEL_CLIENT_ID]) {\n filter.clientId = headers[HEADER_CANCEL_CLIENT_ID];\n } else if (headers[HEADER_CANCEL_ALL] === 'true') {\n filter.all = true;\n }\n\n const matchedTurnIds = this._resolveFilter(filter, msg.clientId);\n if (matchedTurnIds.length === 0) return;\n\n this._logger?.debug('DefaultServerTransport._handleCancelMessage(); matched turns', {\n matchedTurnIds,\n filter,\n });\n\n const owners = new Map<string, string>();\n for (const tid of matchedTurnIds) {\n const reg = this._registeredTurns.get(tid);\n owners.set(tid, reg?.clientId ?? '');\n }\n const request: CancelRequest = { message: msg, filter, matchedTurnIds, turnOwners: owners };\n\n for (const turnId of matchedTurnIds) {\n const reg = this._registeredTurns.get(turnId);\n if (!reg) continue;\n\n try {\n if (reg.onCancel) {\n const allowed = await reg.onCancel(request);\n if (!allowed) {\n this._logger?.debug('DefaultServerTransport._handleCancelMessage(); cancel rejected by onCancel', {\n turnId,\n });\n continue;\n }\n }\n reg.controller.abort();\n this._logger?.debug('DefaultServerTransport._handleCancelMessage(); turn aborted', { turnId });\n } catch (error) {\n // A throwing onCancel handler must not prevent other turns from being cancelled.\n const errInfo = new Ably.ErrorInfo(\n `unable to process cancel for turn ${turnId}; onCancel handler threw: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.CancelListenerError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger?.error('DefaultServerTransport._handleCancelMessage(); onCancel threw', { turnId });\n (reg.onError ?? this._onError)?.(errInfo);\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Channel subscription handler\n // -------------------------------------------------------------------------\n\n private _handleChannelMessage(msg: Ably.InboundMessage): void {\n try {\n if (msg.name === EVENT_CANCEL) {\n // Fire-and-forget async handler — errors are caught internally.\n this._handleCancelMessage(msg).catch((error: unknown) => {\n const errInfo = new Ably.ErrorInfo(\n `unable to route cancel message; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.CancelListenerError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger?.error('DefaultServerTransport._handleChannelMessage(); cancel routing error');\n this._onError?.(errInfo);\n });\n }\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to process channel message; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.TransportSubscriptionError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger?.error('DefaultServerTransport._handleChannelMessage(); subscription error');\n this._onError?.(errInfo);\n }\n }\n\n // -------------------------------------------------------------------------\n // Turn creation\n // -------------------------------------------------------------------------\n\n private _createTurn(turnOpts: NewTurnOptions<TEvent>): Turn<TEvent, TMessage> {\n const {\n turnId,\n clientId: turnClientId,\n onMessage,\n onAbort,\n onCancel,\n onError: turnOnError,\n parent: turnParent,\n forkOf: turnForkOf,\n } = turnOpts;\n\n const controller = new AbortController();\n let started = false;\n let ended = false;\n\n // Register immediately so early cancels can fire the abort signal.\n const registration: RegisteredTurn = {\n turnId,\n clientId: turnClientId ?? '',\n controller,\n onCancel,\n onError: turnOnError,\n };\n this._registeredTurns.set(turnId, registration);\n\n // Capture instance members as locals so arrow functions close over them\n // without needing `this` (avoids unicorn/no-this-assignment).\n const logger = this._logger;\n const turnManager = this._turnManager;\n const attachPromise = this._attachPromise;\n const codec = this._codec;\n const channel = this._channel;\n const registeredTurns = this._registeredTurns;\n\n const turn: Turn<TEvent, TMessage> = {\n get turnId() {\n return turnId;\n },\n get abortSignal() {\n return controller.signal;\n },\n\n // Spec: AIT-ST4\n start: async (): Promise<void> => {\n logger?.trace('Turn.start();', { turnId });\n\n if (controller.signal.aborted) {\n throw new Ably.ErrorInfo(\n `unable to start turn; turn ${turnId} was cancelled before start()`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n if (started) return;\n started = true;\n\n try {\n await turnManager.startTurn(turnId, turnClientId, controller);\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to publish turn-start for turn ${turnId}; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.TurnLifecycleError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n logger?.error('Turn.start(); failed to publish turn-start', { turnId });\n turnOnError?.(errInfo);\n throw errInfo;\n }\n\n logger?.debug('Turn.start(); turn started', { turnId });\n },\n\n // Spec: AIT-ST5\n addMessages: async (\n inputs: MessageWithHeaders<TMessage>[],\n opts?: AddMessageOptions,\n ): Promise<AddMessagesResult> => {\n logger?.trace('Turn.addMessages();', { turnId, count: inputs.length });\n\n if (!started) {\n throw new Ably.ErrorInfo(\n `unable to add messages; start() must be called before addMessages() (turn ${turnId})`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n await attachPromise;\n\n const msgIds: string[] = [];\n\n for (const input of inputs) {\n const msgId = crypto.randomUUID();\n\n // Transport headers are the defaults; per-message headers from the\n // client override them. This lets the client's x-ably-msg-id pass\n // through for optimistic reconciliation with client inserts.\n const headers = mergeHeaders(\n buildTransportHeaders({\n role: 'user',\n turnId,\n msgId,\n turnClientId: opts?.clientId,\n // Per-operation options override turn-level defaults\n parent: opts?.parent === undefined ? (turnParent ?? undefined) : (opts.parent ?? undefined),\n forkOf: opts?.forkOf ?? turnForkOf,\n }),\n input.headers,\n );\n\n const encoder = codec.createEncoder(channel, {\n extras: { headers },\n onMessage,\n });\n\n await encoder.writeMessages([input.message], opts?.clientId ? { clientId: opts.clientId } : undefined);\n\n // Capture the effective msg-id after input.headers may have overridden it.\n msgIds.push(headers[HEADER_MSG_ID] ?? msgId);\n }\n\n logger?.debug('Turn.addMessages(); messages published', { turnId, count: inputs.length });\n return { msgIds };\n },\n\n // Spec: AIT-ST6\n streamResponse: async (\n stream: ReadableStream<TEvent>,\n streamOpts?: StreamResponseOptions,\n ): Promise<StreamResult> => {\n logger?.trace('Turn.streamResponse();', { turnId });\n\n if (!started) {\n throw new Ably.ErrorInfo(\n `unable to stream response; start() must be called before streamResponse() (turn ${turnId})`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n await attachPromise;\n\n const signal = turnManager.getSignal(turnId);\n const turnOwnerClientId = turnManager.getClientId(turnId);\n\n // Per-operation parent overrides the turn-level default.\n const assistantParent =\n streamOpts?.parent === undefined ? (turnParent ?? undefined) : (streamOpts.parent ?? undefined);\n\n const defaultHeaders = buildTransportHeaders({\n role: 'assistant',\n turnId,\n msgId: crypto.randomUUID(),\n turnClientId: turnOwnerClientId,\n parent: assistantParent,\n forkOf: streamOpts?.forkOf ?? turnForkOf,\n });\n const encoder = codec.createEncoder(channel, {\n extras: { headers: defaultHeaders },\n onMessage,\n });\n\n const result = await pipeStream(stream, encoder, signal, onAbort, logger);\n\n logger?.debug('Turn.streamResponse(); stream finished', { turnId, reason: result.reason });\n return result;\n },\n\n // Spec: AIT-ST7\n end: async (reason: TurnEndReason): Promise<void> => {\n logger?.trace('Turn.end();', { turnId, reason });\n\n if (!started) {\n throw new Ably.ErrorInfo(\n `unable to end turn; start() must be called before end() (turn ${turnId})`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n if (ended) return;\n ended = true;\n\n try {\n await turnManager.endTurn(turnId, reason);\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to publish turn-end for turn ${turnId}; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.TurnLifecycleError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n logger?.error('Turn.end(); failed to publish turn-end', { turnId });\n turnOnError?.(errInfo);\n throw errInfo;\n } finally {\n registeredTurns.delete(turnId);\n }\n\n logger?.debug('Turn.end(); turn ended', { turnId, reason });\n },\n };\n\n return turn;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a server transport bound to the given channel and codec.\n * @param options - Transport configuration.\n * @returns A new {@link ServerTransport} instance.\n */\nexport const createServerTransport = <TEvent, TMessage>(\n options: ServerTransportOptions<TEvent, TMessage>,\n): ServerTransport<TEvent, TMessage> => new DefaultServerTransport(options);\n","/**\n * Vercel AI SDK transport wrappers that pre-bind the UIMessageCodec.\n *\n * These are convenience factories so consumers don't need to pass the codec\n * explicitly when using the Vercel AI SDK integration.\n *\n * ```ts\n * import { createClientTransport } from '@ably/ai-transport/vercel';\n *\n * const transport = createClientTransport({ channel });\n * ```\n */\n\n// Chat transport adapter\nexport type { ChatTransport, ChatTransportOptions, SendMessagesRequestContext } from './chat-transport.js';\nexport { createChatTransport } from './chat-transport.js';\n\nimport type * as AI from 'ai';\n\nimport { createClientTransport as createCoreClientTransport } from '../../core/transport/client-transport.js';\nimport { createServerTransport as createCoreServerTransport } from '../../core/transport/server-transport.js';\nimport type {\n ClientTransport,\n ClientTransportOptions,\n ServerTransport,\n ServerTransportOptions,\n} from '../../core/transport/types.js';\nimport { UIMessageCodec } from '../codec/index.js';\n\n/** Options for creating a Vercel client transport. Same as core options but without the codec field. */\nexport type VercelClientTransportOptions = Omit<ClientTransportOptions<AI.UIMessageChunk, AI.UIMessage>, 'codec'>;\n\n/** Options for creating a Vercel server transport. Same as core options but without the codec field. */\nexport type VercelServerTransportOptions = Omit<ServerTransportOptions<AI.UIMessageChunk, AI.UIMessage>, 'codec'>;\n\n/**\n * Create a client-side transport pre-configured with the Vercel AI SDK codec.\n *\n * Equivalent to calling the core `createClientTransport` with `codec: UIMessageCodec`.\n * @param options - Configuration for the client transport (codec is provided automatically).\n * @returns A new {@link ClientTransport} for Vercel AI SDK UIMessage/UIMessageChunk types.\n */\nexport const createClientTransport = (\n options: VercelClientTransportOptions,\n): ClientTransport<AI.UIMessageChunk, AI.UIMessage> => createCoreClientTransport({ ...options, codec: UIMessageCodec });\n\n/**\n * Create a server-side transport pre-configured with the Vercel AI SDK codec.\n *\n * Equivalent to calling the core `createServerTransport` with `codec: UIMessageCodec`.\n * @param options - Configuration for the server transport (codec is provided automatically).\n * @returns A new {@link ServerTransport} for Vercel AI SDK UIMessage/UIMessageChunk types.\n */\nexport const createServerTransport = (\n options: VercelServerTransportOptions,\n): ServerTransport<AI.UIMessageChunk, AI.UIMessage> => createCoreServerTransport({ ...options, codec: UIMessageCodec });\n"],"mappings":";;;AAgBA,IAAa,IAAgB,iBAGhB,IAAgB,iBAGhB,IAAmB,oBAOnB,IAAiB,kBAGjB,IAAgB,iBAGhB,IAAwB,yBAGxB,IAAc,eAOd,IAAwB,yBAGxB,IAAoB,qBAGpB,IAAoB,qBAGpB,IAA0B,2BAO1B,IAAgB,iBAGhB,IAAiB,kBAOjB,IAAqB,sBAOrB,IAAe,iBAGf,IAAmB,qBAGnB,IAAiB,mBAajB,IAAuB,aChFvB,KAAc,MAAyD;CAElF,IAAM,IAA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iB,EAAK,YAAY,IAAQ,KAAA,EAC3C;AAGD,YAFA,GAAQ,MAAM,0CAA0C,EAAE,WAAQ,CAAC,EACnE,IAAc,EAAQ,EAChB;eACE;AACR,QAAgB,OAAO,EAAO;;AAGhC,QAAQ,MAAM,0BAA0B;MAAE;MAAQ;MAAQ,CAAC;;;GAE9D;;GAeQ,MACX,MACsC,IAAI,GAAuB,EAAQ,EC/Z9D,MACX,MACqD,EAA0B;CAAE,GAAG;CAAS,OAAO;CAAgB,CAAC,EAS1G,MACX,MACqD,GAA0B;CAAE,GAAG;CAAS,OAAO;CAAgB,CAAC"}
1
+ {"version":3,"file":"ably-ai-transport-vercel.js","names":[],"sources":["../../src/constants.ts","../../src/utils.ts","../../src/core/codec/decoder.ts","../../src/core/codec/lifecycle-tracker.ts","../../src/vercel/codec/decoder.ts","../../src/errors.ts","../../src/core/codec/encoder.ts","../../src/vercel/codec/encoder.ts","../../src/vercel/codec/tool-transitions.ts","../../src/vercel/codec/reducer.ts","../../src/vercel/codec/index.ts","../../src/event-emitter.ts","../../src/logger.ts","../../src/vercel/transport/run-output-stream.ts","../../src/vercel/transport/chat-transport.ts","../../src/version.ts","../../src/core/agent.ts","../../src/core/transport/headers.ts","../../src/core/transport/internal/bounded-map.ts","../../src/core/transport/branch-chain.ts","../../src/core/transport/decode-fold.ts","../../src/core/transport/load-conversation.ts","../../src/core/transport/pipe-stream.ts","../../src/core/transport/run-manager.ts","../../src/core/transport/agent-session.ts","../../src/core/transport/invocation.ts","../../src/core/transport/tree.ts","../../src/core/transport/load-history.ts","../../src/core/transport/view.ts","../../src/core/transport/client-session.ts","../../src/vercel/transport/index.ts","../../src/vercel/run-end-reason.ts"],"sourcesContent":["/**\n * Shared constants used by both codec and transport layers.\n *\n * Header constants define the transport wire header names. Message and event\n * name constants define the session lifecycle signals on the channel.\n *\n * These live at the top level (not in codec/ or transport/) because both\n * layers need them — the codec core reads/writes stream and status headers,\n * while the transport layer reads/writes run, cancel, and role headers.\n */\n\n// ---------------------------------------------------------------------------\n// Stream headers (used by codec encoder/decoder core)\n// ---------------------------------------------------------------------------\n\n/** Header: whether this Ably message uses streaming (message appends) or is discrete. Always \"true\" or \"false\". */\nexport const HEADER_STREAM = 'stream';\n\n/** Header: lifecycle status of a streamed message. Only set when stream is \"true\". One of \"streaming\", \"complete\", or \"cancelled\". */\nexport const HEADER_STATUS = 'status';\n\n/** Header: stream identity. Set by the encoder on every streamed message; read by the decoder to correlate streams. */\nexport const HEADER_STREAM_ID = 'stream-id';\n\n/** Header: marks a message as a discrete message part (from writeMessages). Set by publishDiscreteBatch; not set on lifecycle events from publishDiscrete. */\nexport const HEADER_DISCRETE = 'discrete';\n\n// ---------------------------------------------------------------------------\n// Identity headers (used by transport for run correlation)\n// ---------------------------------------------------------------------------\n\n/** Header: run correlation ID. Set on every agent-published message and on continuation client inputs, but omitted from the originating fresh client input (the agent mints the run-id at run-start). */\nexport const HEADER_RUN_ID = 'run-id';\n\n/** Header: invocation correlation ID; identifies a specific invocation under a run. Agent-minted and stamped by the agent on every event it publishes for the invocation — run lifecycle (run-start/resume/suspend/end) and assistant outputs. Never set by the client on its input. */\nexport const HEADER_INVOCATION_ID = 'invocation-id';\n\n/**\n * Header: per-event identifier stamped by the client on every\n * client-published event in a send — user-message events AND amend\n * events (tool-approval responses, client tool outputs). Distinct from\n * `codec-message-id` so it survives edits/retries that reuse the same\n * codec-message-id, and so amend events that target an existing message can\n * carry their own per-send identity. The invocation body lists every\n * inputEventId the agent must observe on the channel before starting LLM\n * work — see `Run.start()`'s input-event lookup.\n */\nexport const HEADER_EVENT_ID = 'event-id';\n\n/** Header: message identity. Assigned per message (user or assistant). Used for optimistic reconciliation on the client. */\nexport const HEADER_CODEC_MESSAGE_ID = 'codec-message-id';\n\n/** Header: clientId of the user who initiated the run. Stamped by the client on its user input and re-stamped by the agent on the run's lifecycle and stream messages. */\nexport const HEADER_RUN_CLIENT_ID = 'run-client-id';\n\n/**\n * Header: clientId of the input event (the `ai-input`) that drove the\n * current invocation. The agent reads the publisher's Ably-level `clientId`\n * from the triggering input event on the channel and re-stamps it as\n * `input-client-id` on every event it publishes for that invocation\n * (run lifecycle and assistant outputs). May differ from\n * `run-client-id` on continuation invocations driven by an input\n * from a non-owner (e.g. a tool-result publish from a different client).\n * Not stamped on `ai-input` events themselves — the wire publisher's\n * Ably `clientId` already conveys that.\n */\nexport const HEADER_INPUT_CLIENT_ID = 'input-client-id';\n\n/** Header: message role (e.g. \"user\", \"assistant\"). */\nexport const HEADER_ROLE = 'role';\n\n// ---------------------------------------------------------------------------\n// Fork / branching headers\n// ---------------------------------------------------------------------------\n\n/** Header: the codec-message-id of the immediately preceding message in this branch. */\nexport const HEADER_PARENT = 'parent';\n\n/** Header: the codec-message-id of the message this one replaces (creates a fork). */\nexport const HEADER_FORK_OF = 'fork-of';\n\n/**\n * Header: the codec-message-id of the assistant message this run regenerates.\n *\n * Stamped on the regenerate wire (and echoed on `run-start`) when the\n * client requested a regeneration. A regenerate run parents at the SAME input\n * node as the reply it regenerates, so it joins that input's reply runs as a\n * same-parent sibling (no fork-of). The View consults this header to resolve\n * the message-level sibling group and to drop the regenerated message from\n * earlier Runs in the visible chain (Spec: AIT-CT13d).\n */\nexport const HEADER_MSG_REGENERATE = 'msg-regenerate';\n\n// ---------------------------------------------------------------------------\n// Run lifecycle headers\n// ---------------------------------------------------------------------------\n\n/** Header: reason a run ended (on ai-run-end messages). */\nexport const HEADER_RUN_REASON = 'run-reason';\n\n/**\n * Header: the `codec-message-id` of the input event that triggered the run.\n * The triggering input is the one whose `event-id` matches the invocation's\n * `inputEventId` (the last input of the originating send). The agent\n * re-stamps it on every event it publishes for the invocation (run\n * lifecycle + assistant outputs), mirroring `input-client-id`. This is the\n * codec-message-id the client owns at send time, so it lets the client\n * correlate any of those events back to the originating input without\n * depending on a client-minted run-id or invocation-id.\n */\nexport const HEADER_INPUT_CODEC_MESSAGE_ID = 'input-codec-message-id';\n\n// ---------------------------------------------------------------------------\n// Run-end error headers (set on `ai-run-end` when `run-reason: error`)\n// ---------------------------------------------------------------------------\n\n/** Header: numeric error code accompanying an `ai-run-end` with reason `error`. */\nexport const HEADER_ERROR_CODE = 'error-code';\n\n/** Header: human-readable error message accompanying an `ai-run-end` with reason `error`. */\nexport const HEADER_ERROR_MESSAGE = 'error-message';\n\n// ---------------------------------------------------------------------------\n// Message / event names\n// ---------------------------------------------------------------------------\n\n/**\n * Message name: client->agent cancel intent. Targets a run by `run-id` (a\n * continuation, whose run-id the client already knows) and/or by\n * `input-codec-message-id` (a fresh send, whose run-id the agent mints at\n * run-start — so the client can only key the cancel by the triggering input's\n * codec-message-id it owns at send time). The agent resolves whichever is\n * present to the registered run; a cancel that arrives before the run is known\n * (the input-event lookup hasn't resolved the input id to a run yet) is\n * buffered by `input-codec-message-id` and honoured when the run resolves it.\n * Also carries an `event-id` so channel rewind redelivers it to a per-request /\n * serverless agent that attaches after the cancel was published.\n */\nexport const EVENT_CANCEL = 'ai-cancel';\n\n/** Message name: server publishes this to signal a run has started. */\nexport const EVENT_RUN_START = 'ai-run-start';\n\n/**\n * Message name: server publishes this to signal a run has suspended — paused\n * awaiting participant input (e.g. a client tool result or approval) without\n * ending. The run stays live and may be resumed under the same `runId`.\n * Distinct from `ai-run-end`, which is terminal.\n */\nexport const EVENT_RUN_SUSPEND = 'ai-run-suspend';\n\n/**\n * Message name: server publishes this when a subsequent invocation re-enters an\n * already-started run (e.g. a tool-result follow-up under the same `runId`).\n * A pure re-entry signal: unlike `ai-run-start` it carries no `parent` / `fork-of`\n * (the original `ai-run-start` already established the run's structure).\n */\nexport const EVENT_RUN_RESUME = 'ai-run-resume';\n\n/** Message name: server publishes this to signal a run has ended. */\nexport const EVENT_RUN_END = 'ai-run-end';\n\n/**\n * Message name: every agent-published codec event (text, reasoning, tool calls,\n * tool outputs, lifecycle helpers, file / source parts, data-* chunks) rides\n * this single wire name. The codec event's own `type` is carried in the\n * codec-level `type` header so the decoder can dispatch.\n */\nexport const EVENT_AI_OUTPUT = 'ai-output';\n\n/**\n * Message name: every client-published codec event (user-message parts,\n * tool-approval responses, regenerate signals) rides this single wire\n * name. The codec event's own kind is carried in the codec-level `type`\n * header so the decoder can dispatch.\n */\nexport const EVENT_AI_INPUT = 'ai-input';\n","/**\n * Shared utilities for working with Ably messages.\n *\n * These are general-purpose helpers used by both the codec and transport\n * layers. They live at the top level to avoid either layer depending on\n * the other.\n */\n\nimport type * as Ably from 'ably';\n\n/**\n * Read one tier of the SDK's `extras.ai` namespace from an Ably message.\n * `extras.ai` is the SDK's reserved corner of the message envelope, split into\n * a `transport` tier (generic transport headers) and a `codec` tier (codec\n * headers). The application's own `extras.headers` is deliberately left\n * untouched.\n * @param message - The Ably message to read from.\n * @param tier - Which `extras.ai` sub-namespace to read.\n * @returns The tier's headers record, or an empty object if absent.\n */\nconst getAiTier = (message: Ably.InboundMessage, tier: 'transport' | 'codec'): Record<string, string> => {\n // CAST: Ably SDK types `extras` as `any`; runtime checks below guard access.\n const extras = message.extras as unknown;\n if (!extras || typeof extras !== 'object') return {};\n const ai = (extras as { ai?: unknown }).ai;\n if (!ai || typeof ai !== 'object') return {};\n const sub = (ai as Record<string, unknown>)[tier];\n if (!sub || typeof sub !== 'object') return {};\n // CAST: Ably wire protocol guarantees the tier is Record<string, string>\n // when present, verified by the runtime guards above.\n return sub as Record<string, string>;\n};\n\n/**\n * Extract the transport-tier headers (`extras.ai.transport`) from an Ably\n * InboundMessage. These are the generic transport headers (run/stream/identity/\n * branching), set and read by the transport layer.\n * @param message - The Ably message to extract headers from.\n * @returns The transport headers record, or an empty object if absent.\n */\nexport const getTransportHeaders = (message: Ably.InboundMessage): Record<string, string> =>\n getAiTier(message, 'transport');\n\n/**\n * Extract the codec-tier headers (`extras.ai.codec`) from an Ably\n * InboundMessage. These are the codec's own headers, with no prefix — the\n * tier isolates them from transport headers.\n * @param message - The Ably message to extract headers from.\n * @returns The codec headers record, or an empty object if absent.\n */\nexport const getCodecHeaders = (message: Ably.InboundMessage): Record<string, string> => getAiTier(message, 'codec');\n\n/**\n * Parse a JSON string, returning undefined on failure.\n * @param value - The JSON string to parse.\n * @returns The parsed value, or undefined if parsing fails.\n */\nexport const parseJson = (value: string | undefined): unknown => {\n if (value === undefined) return undefined;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Set a header value if defined, skipping undefined and null. Strings are set directly,\n * booleans and numbers are stringified, objects are JSON-serialized.\n * @param headers - The headers object to mutate.\n * @param key - The header key.\n * @param value - The value to set.\n */\nexport const setIfPresent = (headers: Record<string, string>, key: string, value: unknown): void => {\n if (value === undefined || value === null) return;\n if (typeof value === 'string') {\n headers[key] = value;\n } else if (typeof value === 'boolean' || typeof value === 'number') {\n headers[key] = String(value);\n } else if (typeof value === 'object') {\n headers[key] = JSON.stringify(value);\n }\n};\n\n/**\n * Merge two header records into a new object. Later values override earlier ones.\n * Undefined inputs are treated as empty.\n * @param base - Base headers (lower priority).\n * @param overrides - Override headers (higher priority).\n * @returns A new merged headers object.\n */\nexport const mergeHeaders = (\n base: Record<string, string> | undefined,\n overrides: Record<string, string> | undefined,\n): Record<string, string> => ({\n ...base,\n ...overrides,\n});\n\n/**\n * Parse a boolean header (\"true\"/\"false\"), returning undefined if absent.\n * @param value - The header string to parse.\n * @returns True if \"true\", false for any other string, or undefined if absent.\n */\nexport const parseBool = (value: string | undefined): boolean | undefined => {\n if (value === undefined) return undefined;\n return value === 'true';\n};\n\n/** A record carrying an optional Ably `serial`, orderable by {@link compareBySerial}. */\ninterface HasSerial {\n /** Ably serial, or undefined if the server has not yet assigned one. */\n readonly serial?: string;\n}\n\n/**\n * Comparator that orders records by their Ably `serial` ascending\n * (chronological). Serials are lexicographically comparable; records whose\n * serial is undefined sort last. Pass directly to `Array.prototype.sort`.\n * @param a - First record to compare.\n * @param b - Second record to compare.\n * @returns Negative if `a` precedes `b`, positive if `a` follows `b`, 0 if equal.\n */\nexport const compareBySerial = (a: HasSerial, b: HasSerial): number => {\n if (a.serial === undefined && b.serial === undefined) return 0;\n if (a.serial === undefined) return 1;\n if (b.serial === undefined) return -1;\n if (a.serial < b.serial) return -1;\n if (a.serial > b.serial) return 1;\n return 0;\n};\n\n/**\n * Read a domain header value from a codec-tier headers record.\n * @param headers - The codec headers record to read from.\n * @param key - The domain key (e.g. `'toolCallId'`).\n * @returns The header value, or undefined if absent.\n */\nexport const getDomainHeader = (headers: Record<string, string>, key: string): string | undefined => headers[key];\n\n/**\n * Mapped type that converts properties whose type includes `undefined`\n * into optional properties with `undefined` excluded from the value.\n * Properties typed as `unknown` are kept required (since `undefined extends unknown`\n * is always true, but `unknown` fields are intentionally broad, not optional).\n */\nexport type Stripped<T> = {\n [K in keyof T as undefined extends T[K] ? (unknown extends T[K] ? K : never) : K]: T[K];\n} & {\n [K in keyof T as undefined extends T[K] ? (unknown extends T[K] ? never : K) : never]?: Exclude<T[K], undefined>;\n};\n\n/**\n * Remove all keys whose value is `undefined` from a shallow object.\n * Returns a new object — the input is not mutated. Useful for building\n * chunk literals with optional fields without conditional spread noise.\n *\n * The return type converts `{ foo: T | undefined }` to `{ foo?: T }`,\n * matching the optional-field pattern used by the AI SDK chunk types.\n * @param obj - The object to strip undefined values from.\n * @returns A shallow copy with undefined-valued keys removed.\n */\nexport const stripUndefined = <T extends Record<string, unknown>>(obj: T): Stripped<T> => {\n const result = {} as Record<string, unknown>;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] !== undefined) {\n result[key] = obj[key];\n }\n }\n // CAST: The runtime strip guarantees the Stripped<T> contract —\n // required keys are always present, optional keys are absent when undefined.\n return result as Stripped<T>;\n};\n\n// ---------------------------------------------------------------------------\n// DomainHeaderReader — typed accessors for domain headers\n// ---------------------------------------------------------------------------\n\n/**\n * Typed accessor wrapper around a headers record for reading domain headers.\n * Reduces repetitive `getDomainHeader` + `parseBool` / `parseJson` chains.\n */\nexport interface DomainHeaderReader {\n /** Read a domain header as a string, or undefined if absent. */\n str(key: string): string | undefined;\n /** Read a domain header as a string, falling back to a default if absent. */\n strOr(key: string, fallback: string): string;\n /** Read a domain header as a boolean: `true` only for the exact string \"true\", `false` for any other present value, or undefined if absent. */\n bool(key: string): boolean | undefined;\n /** Read a domain header as parsed JSON, or undefined if absent or invalid. */\n json(key: string): unknown;\n}\n\n/**\n * Create a {@link DomainHeaderReader} over a headers record.\n * @param headers - The raw headers record to read domain headers from.\n * @returns A typed accessor for domain header values.\n */\nexport const headerReader = (headers: Record<string, string>): DomainHeaderReader => ({\n str: (key: string) => getDomainHeader(headers, key),\n strOr: (key: string, fallback: string) => getDomainHeader(headers, key) ?? fallback,\n bool: (key: string) => parseBool(getDomainHeader(headers, key)),\n json: (key: string) => parseJson(getDomainHeader(headers, key)),\n});\n\n// ---------------------------------------------------------------------------\n// DomainHeaderWriter — typed builder for domain headers\n// ---------------------------------------------------------------------------\n\n/**\n * Fluent builder for constructing domain header records with typed setters.\n * Mirrors {@link DomainHeaderReader} with the same method names for symmetry.\n * Undefined values are silently skipped on all setters.\n */\nexport interface DomainHeaderWriter {\n /** Set a string domain header. Skips if value is undefined. */\n str(key: string, value: string | undefined): DomainHeaderWriter;\n /** Set a boolean domain header (serialized as \"true\"/\"false\"). Skips if value is undefined. */\n bool(key: string, value: boolean | undefined): DomainHeaderWriter;\n /** Set a JSON-serialized domain header. Skips if value is undefined or null. */\n json(key: string, value: unknown): DomainHeaderWriter;\n /** Return the accumulated headers record. */\n build(): Record<string, string>;\n}\n\n/**\n * Create a {@link DomainHeaderWriter} for building a codec-tier headers record.\n * @returns A fluent builder that accumulates codec headers under their bare keys.\n */\nexport const headerWriter = (): DomainHeaderWriter => {\n const h: Record<string, string> = {};\n const writer: DomainHeaderWriter = {\n str: (key: string, value: string | undefined) => {\n if (value !== undefined) h[key] = value;\n return writer;\n },\n bool: (key: string, value: boolean | undefined) => {\n if (value !== undefined) h[key] = String(value);\n return writer;\n },\n json: (key: string, value: unknown) => {\n if (value !== undefined && value !== null) h[key] = JSON.stringify(value);\n return writer;\n },\n build: () => h,\n };\n return writer;\n};\n","/**\n * Decoder core — action dispatch and serial tracking machinery.\n *\n * Handles the Ably message action patterns (create, append, update, delete)\n * and delegates to domain-specific hooks for event building and discrete\n * event decoding.\n *\n * Domain decoders call `createDecoderCore(hooks, options)` and provide hooks\n * for stream classification, event building, and discrete decoding. Hooks\n * return a flat `TEvent[]` — no event-vs-message union. Per-message routing\n * concerns (`codec-message-id`) are handled by the SDK via `ReducerMeta`, not\n * here.\n */\n\nimport type * as Ably from 'ably';\n\nimport { HEADER_STATUS, HEADER_STREAM, HEADER_STREAM_ID } from '../../constants.js';\nimport type { Logger } from '../../logger.js';\nimport { getCodecHeaders, getTransportHeaders } from '../../utils.js';\nimport type { MessagePayload, StreamTrackerState } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for creating a decoder core. */\nexport interface DecoderCoreOptions {\n /** Called when a tracked stream is replaced (non-prefix update). Receives the tracker with updated state. */\n onStreamUpdate?: (tracker: StreamTrackerState) => void;\n /** Called when a message is deleted. Receives the serial and tracker (if one exists). */\n onStreamDelete?: (serial: string, tracker: StreamTrackerState | undefined) => void;\n /** Logger instance for diagnostic output. */\n logger?: Logger;\n}\n\n// ---------------------------------------------------------------------------\n// Domain hooks\n// ---------------------------------------------------------------------------\n\n/** Hooks that a domain codec provides to the decoder core for stream classification and event building. */\nexport interface DecoderCoreHooks<TEvent> {\n /**\n * Build domain events emitted when a new stream starts. May return multiple\n * events (e.g. a start event and a start-step event).\n */\n buildStartEvents(tracker: StreamTrackerState): TEvent[];\n\n /** Build domain events for a text delta received on a stream. */\n buildDeltaEvents(tracker: StreamTrackerState, delta: string): TEvent[];\n\n /**\n * Build domain events emitted when a stream completes (status:complete).\n * Not called for cancelled streams. The closing codec headers may differ\n * from tracker.codecHeaders if the closing append carried updated headers.\n */\n buildEndEvents(tracker: StreamTrackerState, closingCodecHeaders: Record<string, string>): TEvent[];\n\n /**\n * Decode a discrete message (a `message.create` whose stream header is not\n * \"true\", or a non-streamable first-contact update). Handles user messages,\n * tool lifecycle, data-*, etc.\n */\n decodeDiscrete(input: MessagePayload): TEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/** The decoder core returned by {@link createDecoderCore}. */\nexport interface DecoderCore<TEvent> {\n /** Decode a single Ably message into zero or more domain TEvents. */\n decode(message: Ably.InboundMessage): TEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CD7\nclass DefaultDecoderCore<TEvent> implements DecoderCore<TEvent> {\n private readonly _hooks: DecoderCoreHooks<TEvent>;\n private readonly _logger: Logger | undefined;\n private readonly _onStreamUpdate: ((tracker: StreamTrackerState) => void) | undefined;\n private readonly _onStreamDelete: ((serial: string, tracker: StreamTrackerState | undefined) => void) | undefined;\n private readonly _serialState = new Map<string, StreamTrackerState>();\n\n constructor(hooks: DecoderCoreHooks<TEvent>, options: DecoderCoreOptions = {}) {\n this._hooks = hooks;\n this._onStreamUpdate = options.onStreamUpdate;\n this._onStreamDelete = options.onStreamDelete;\n this._logger = options.logger?.withContext({ component: 'DecoderCore' });\n }\n\n decode(message: Ably.InboundMessage): TEvent[] {\n const action = message.action;\n\n this._logger?.trace('DefaultDecoderCore.decode();', { action, serial: message.serial, name: message.name });\n\n switch (action) {\n // Spec: AIT-CD7a\n case 'message.create': {\n const payload = this._toPayload(message);\n return payload.transportHeaders?.[HEADER_STREAM] === 'true'\n ? this._decodeStreamedCreate(payload, message.serial)\n : this._hooks.decodeDiscrete(payload);\n }\n\n case 'message.append': {\n return this._decodeAppend(message);\n }\n\n case 'message.update': {\n return this._decodeUpdate(message);\n }\n\n case 'message.delete': {\n return this._decodeDelete(message);\n }\n\n default: {\n return [];\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Private: extract MessagePayload\n // -------------------------------------------------------------------------\n\n private _toPayload(message: Ably.InboundMessage): MessagePayload {\n return {\n name: message.name ?? '',\n // CAST: Ably SDK types `data` as `any`; cast to unknown is the safe boundary type.\n data: message.data as unknown,\n transportHeaders: getTransportHeaders(message),\n codecHeaders: getCodecHeaders(message),\n };\n }\n\n /**\n * Extract string data from an Ably message, for stream accumulation paths.\n * @param message - The Ably message to extract string data from.\n * @returns The string data, or empty string if data is not a string.\n */\n private _stringData(message: Ably.InboundMessage): string {\n return typeof message.data === 'string' ? message.data : '';\n }\n\n // -------------------------------------------------------------------------\n // Private: safe callback invocation\n // -------------------------------------------------------------------------\n\n private _invokeOnStreamUpdate(tracker: StreamTrackerState): void {\n if (!this._onStreamUpdate) return;\n try {\n this._onStreamUpdate(tracker);\n } catch (error) {\n this._logger?.error('DefaultDecoderCore._invokeOnStreamUpdate(); callback threw', { error });\n }\n }\n\n private _invokeOnStreamDelete(serial: string, tracker: StreamTrackerState | undefined): void {\n if (!this._onStreamDelete) return;\n try {\n this._onStreamDelete(serial, tracker);\n } catch (error) {\n this._logger?.error('DefaultDecoderCore._invokeOnStreamDelete(); callback threw', { error });\n }\n }\n\n // -------------------------------------------------------------------------\n // Private: streamed message create\n // -------------------------------------------------------------------------\n\n private _decodeStreamedCreate(payload: MessagePayload, serial: string | undefined): TEvent[] {\n if (!serial) return [];\n\n const streamId = payload.transportHeaders?.[HEADER_STREAM_ID] ?? '';\n\n const tracker: StreamTrackerState = {\n name: payload.name,\n streamId,\n accumulated: '',\n codecHeaders: { ...payload.codecHeaders },\n transportHeaders: { ...payload.transportHeaders },\n closed: false,\n };\n this._serialState.set(serial, tracker);\n\n this._logger?.debug('DefaultDecoderCore._decodeStreamedCreate(); new stream', {\n name: payload.name,\n streamId,\n serial,\n });\n\n return this._hooks.buildStartEvents(tracker);\n }\n\n // -------------------------------------------------------------------------\n // Private: append handling\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CD8\n private _decodeAppend(message: Ably.InboundMessage): TEvent[] {\n const serial = message.serial;\n if (!serial) return [];\n\n const tracker = this._serialState.get(serial);\n if (!tracker) {\n // Unknown serial on append — treat as first-contact update\n return this._decodeUpdate(message);\n }\n\n const transport = getTransportHeaders(message);\n const closingCodec = getCodecHeaders(message);\n const delta = typeof message.data === 'string' ? message.data : '';\n const status = transport[HEADER_STATUS];\n const outputs: TEvent[] = [];\n\n if (delta.length > 0) {\n tracker.accumulated += delta;\n outputs.push(...this._hooks.buildDeltaEvents(tracker, delta));\n }\n\n if (status === 'complete' && !tracker.closed) {\n tracker.closed = true;\n outputs.push(...this._hooks.buildEndEvents(tracker, closingCodec));\n this._logger?.debug('DefaultDecoderCore._decodeAppend(); stream complete', { streamId: tracker.streamId });\n } else if (status === 'cancelled' && !tracker.closed) {\n tracker.closed = true;\n this._logger?.debug('DefaultDecoderCore._decodeAppend(); stream cancelled', { streamId: tracker.streamId });\n }\n\n return outputs;\n }\n\n // -------------------------------------------------------------------------\n // Private: update handling (first-contact, prefix-match, replacement)\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CD9\n private _decodeUpdate(message: Ably.InboundMessage): TEvent[] {\n const serial = message.serial;\n if (!serial) return [];\n\n const payload = this._toPayload(message);\n const transport = payload.transportHeaders ?? {};\n const codec = payload.codecHeaders ?? {};\n const isStreamed = transport[HEADER_STREAM] === 'true';\n const status = transport[HEADER_STATUS];\n\n const tracker = this._serialState.get(serial);\n\n if (!tracker) {\n return this._decodeFirstContact(payload, isStreamed, status, serial);\n }\n\n // Updates to tracked streams use string data for prefix-match accumulation\n const data = this._stringData(message);\n\n // --- Tracker exists: prefix-match or replacement ---\n if (data.startsWith(tracker.accumulated)) {\n const delta = data.slice(tracker.accumulated.length);\n const outputs: TEvent[] = [];\n\n if (delta.length > 0) {\n tracker.accumulated = data;\n outputs.push(...this._hooks.buildDeltaEvents(tracker, delta));\n }\n\n if (status === 'complete' && !tracker.closed) {\n tracker.closed = true;\n outputs.push(...this._hooks.buildEndEvents(tracker, codec));\n } else if (status === 'cancelled' && !tracker.closed) {\n tracker.closed = true;\n }\n\n return outputs;\n }\n\n // --- Replacement (NOT a prefix match) ---\n tracker.accumulated = data;\n tracker.codecHeaders = { ...codec };\n tracker.transportHeaders = { ...transport };\n\n this._invokeOnStreamUpdate(tracker);\n\n return [];\n }\n\n private _decodeFirstContact(\n payload: MessagePayload,\n isStreamed: boolean,\n status: string | undefined,\n serial: string,\n ): TEvent[] {\n // Non-streamed messages are discrete\n if (!isStreamed) {\n return this._hooks.decodeDiscrete(payload);\n }\n\n const streamId = payload.transportHeaders?.[HEADER_STREAM_ID] ?? '';\n const codec = payload.codecHeaders ?? {};\n const data = typeof payload.data === 'string' ? payload.data : '';\n\n this._logger?.debug('DefaultDecoderCore._decodeFirstContact(); first-contact stream', {\n name: payload.name,\n streamId,\n serial,\n });\n\n // Create tracker\n const newTracker: StreamTrackerState = {\n name: payload.name,\n streamId,\n accumulated: data,\n codecHeaders: { ...codec },\n transportHeaders: { ...payload.transportHeaders },\n closed: status === 'complete' || status === 'cancelled',\n };\n this._serialState.set(serial, newTracker);\n\n // Emit start + delta (if any) + end (if complete)\n const outputs = this._hooks.buildStartEvents(newTracker);\n\n if (data.length > 0) {\n outputs.push(...this._hooks.buildDeltaEvents(newTracker, data));\n }\n\n if (status === 'complete') {\n outputs.push(...this._hooks.buildEndEvents(newTracker, codec));\n }\n\n return outputs;\n }\n\n // -------------------------------------------------------------------------\n // Private: delete handling\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CD10\n private _decodeDelete(message: Ably.InboundMessage): TEvent[] {\n const serial = message.serial;\n if (!serial) return [];\n\n const tracker = this._serialState.get(serial);\n\n this._invokeOnStreamDelete(serial, tracker);\n\n if (tracker) {\n tracker.accumulated = '';\n tracker.closed = true;\n }\n\n this._logger?.debug('DefaultDecoderCore._decodeDelete();', { serial });\n\n return [];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a decoder core with the given domain hooks.\n * @param hooks - Domain-specific hooks for stream classification, event building, and discrete decoding.\n * @param options - Decoder configuration (callbacks, logger).\n * @returns A new {@link DecoderCore} instance.\n */\nexport const createDecoderCore = <TEvent>(\n hooks: DecoderCoreHooks<TEvent>,\n options: DecoderCoreOptions = {},\n): DecoderCore<TEvent> => new DefaultDecoderCore(hooks, options);\n","/**\n * Generic lifecycle tracker for codec decoders.\n *\n * Manages per-scope (typically per-run) tracking of lifecycle phases that\n * must be emitted before content events. When a phase has not been emitted\n * (e.g. mid-stream join), the tracker synthesizes the missing events using\n * codec-provided build functions.\n *\n * Codecs configure the tracker with an ordered list of phases, then compose\n * it into their decoder hooks. The tracker is independent of any specific\n * codec or event type.\n */\n\n// ---------------------------------------------------------------------------\n// Phase configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration for a single lifecycle phase that may need to be\n * synthesized when missing from the wire stream.\n */\nexport interface PhaseConfig<TEvent> {\n /** Unique key identifying this phase (e.g. \"start\", \"start-step\"). */\n key: string;\n /**\n * Build the synthetic event(s) for this phase. Called with a context\n * record that codecs populate at the call site — the tracker passes\n * it through without interpreting it.\n * @param context - Key-value pairs from the call site (e.g. headers).\n * @returns One or more synthetic events to emit for this phase.\n */\n build(context: Record<string, string | undefined>): TEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Tracker interface\n// ---------------------------------------------------------------------------\n\n/**\n * Per-scope lifecycle tracker that ensures required phases are emitted\n * before content events, synthesizing missing ones for mid-stream joins.\n *\n * Scoped by an arbitrary string key (typically a run ID). Each scope\n * tracks independently which phases have been emitted.\n */\nexport interface LifecycleTracker<TEvent> {\n /**\n * Ensure all configured phases have been emitted for the given scope.\n * Synthesizes and returns the events for any phases not yet marked as\n * emitted, marking each as emitted so it is not synthesized again.\n * Returns an empty array if all phases are already emitted.\n * @param scopeId - The scope to check (e.g. run ID).\n * @param context - Key-value pairs passed through to phase build functions.\n * @returns Synthetic events for missing phases, in configuration order.\n */\n ensurePhases(scopeId: string, context: Record<string, string | undefined>): TEvent[];\n\n /**\n * Mark a phase as emitted from the wire (not synthetic). Call this\n * when the real event arrives so the tracker does not re-synthesize it.\n * @param scopeId - The scope (e.g. run ID).\n * @param phaseKey - The phase key to mark.\n */\n markEmitted(scopeId: string, phaseKey: string): void;\n\n /**\n * Reset a phase so it will be re-synthesized on the next\n * {@link ensurePhases} call. Used for repeating phases (e.g. \"start-step\"\n * resets after \"finish-step\").\n * @param scopeId - The scope (e.g. run ID).\n * @param phaseKey - The phase key to reset.\n */\n resetPhase(scopeId: string, phaseKey: string): void;\n\n /**\n * Remove all tracking state for a scope. Call on run completion\n * (finish, cancel) to free memory.\n * @param scopeId - The scope to clear.\n */\n clearScope(scopeId: string): void;\n}\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CD13\nclass DefaultLifecycleTracker<TEvent> implements LifecycleTracker<TEvent> {\n private readonly _phases: PhaseConfig<TEvent>[];\n private readonly _emitted = new Map<string, Set<string>>();\n\n constructor(phases: PhaseConfig<TEvent>[]) {\n this._phases = phases;\n }\n\n ensurePhases(scopeId: string, context: Record<string, string | undefined>): TEvent[] {\n const emitted = this._getOrCreate(scopeId);\n const events: TEvent[] = [];\n for (const phase of this._phases) {\n if (!emitted.has(phase.key)) {\n emitted.add(phase.key);\n events.push(...phase.build(context));\n }\n }\n return events;\n }\n\n markEmitted(scopeId: string, phaseKey: string): void {\n this._getOrCreate(scopeId).add(phaseKey);\n }\n\n resetPhase(scopeId: string, phaseKey: string): void {\n this._emitted.get(scopeId)?.delete(phaseKey);\n }\n\n clearScope(scopeId: string): void {\n this._emitted.delete(scopeId);\n }\n\n private _getOrCreate(scopeId: string): Set<string> {\n let set = this._emitted.get(scopeId);\n if (!set) {\n set = new Set();\n this._emitted.set(scopeId, set);\n }\n return set;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a lifecycle tracker configured with the given phases.\n * Phases are checked and synthesized in array order.\n * @param phases - Ordered phase configurations.\n * @returns A new {@link LifecycleTracker} instance.\n */\nexport const createLifecycleTracker = <TEvent>(phases: PhaseConfig<TEvent>[]): LifecycleTracker<TEvent> =>\n new DefaultLifecycleTracker(phases);\n","/**\n * Vercel AI SDK Decoder.\n *\n * Maps Ably inbound messages to {@link DecodedMessage} — a `{ inputs,\n * outputs }` tagged result. The decoder routes by the wire `name`\n * (`ai-input` vs `ai-output`) so the SDK never has to inspect direction:\n * input-side messages produce `VercelInput` variants; output-side\n * messages produce `VercelOutput` (`UIMessageChunk`) variants.\n *\n * The `LifecycleTracker` is an internal helper used to pre-roll missing\n * `start` / `start-step` chunks on mid-stream join (history compaction,\n * rewind miss, partial page) so the reducer always sees a clean event\n * sequence for streamed output.\n *\n * Receive-side dispatch reads the wire `name` first and then routes by\n * the codec `type` header carrying the codec event type. Codec headers live\n * under `extras.ai.codec` and transport headers under `extras.ai.transport`;\n * both are read unprefixed from their respective tier.\n */\n\nimport type * as Ably from 'ably';\nimport type * as AI from 'ai';\n\nimport {\n EVENT_AI_INPUT,\n EVENT_AI_OUTPUT,\n HEADER_CODEC_MESSAGE_ID,\n HEADER_DISCRETE,\n HEADER_ROLE,\n HEADER_RUN_ID,\n} from '../../constants.js';\nimport type { DecoderCore, DecoderCoreHooks, DecoderCoreOptions } from '../../core/codec/decoder.js';\nimport { createDecoderCore } from '../../core/codec/decoder.js';\nimport type { LifecycleTracker } from '../../core/codec/lifecycle-tracker.js';\nimport { createLifecycleTracker } from '../../core/codec/lifecycle-tracker.js';\nimport type {\n DecodedMessage,\n Decoder,\n MessagePayload,\n StreamTrackerState,\n UserMessage,\n} from '../../core/codec/types.js';\nimport { type DomainHeaderReader, headerReader as rawHeaderReader, stripUndefined } from '../../utils.js';\nimport type { VercelInput, VercelOutput } from './events.js';\n\n// Decoder-internal union — the codec emits inputs and outputs through the\n// same flat list from the underlying core and partitions on the way out.\ntype AnyEvent = VercelInput | VercelOutput;\n\n// ---------------------------------------------------------------------------\n// Vercel-specific header reader (casts providerMetadata to AI.ProviderMetadata)\n// ---------------------------------------------------------------------------\n\ninterface VercelHeaderReader extends DomainHeaderReader {\n /** Read the `providerMetadata` domain header, cast to the AI SDK type. */\n providerMetadata(): AI.ProviderMetadata | undefined;\n}\n\n/**\n * Create a header reader that adds Vercel-specific `providerMetadata` typing.\n * @param headers - The raw headers record to read domain headers from.\n * @returns A typed accessor with Vercel-specific providerMetadata typing.\n */\nconst headerReader = (headers: Record<string, string>): VercelHeaderReader => {\n const base = rawHeaderReader(headers);\n return {\n ...base,\n // CAST: Trust boundary — the encoder serialized a valid ProviderMetadata value.\n providerMetadata: () => base.json('providerMetadata') as AI.ProviderMetadata | undefined,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Wire format types (trust boundaries for JSON-parsed data)\n// ---------------------------------------------------------------------------\n\n/** Wire format for the agent-side `tool-input-error` chunk data payload. */\ninterface ToolInputErrorWireData {\n errorText?: string;\n input?: unknown;\n}\n\n/** Wire format for the `tool-output-available` (agent) / `tool-result` (client) data payload. */\ninterface ToolOutputAvailableWireData {\n output?: unknown;\n}\n\n/** Wire format for the agent-side `tool-output-error` chunk data payload. */\ninterface AgentToolOutputErrorWireData {\n errorText?: string;\n}\n\n/** Wire format for the client-side `tool-result-error` input data payload. */\ninterface ClientToolResultErrorWireData {\n message?: string;\n}\n\n// ---------------------------------------------------------------------------\n// JSON boundary helpers\n// ---------------------------------------------------------------------------\n\nconst parseFinishReason = (value: string | undefined, fallback: AI.FinishReason): AI.FinishReason => {\n if (\n value === 'stop' ||\n value === 'length' ||\n value === 'content-filter' ||\n value === 'tool-calls' ||\n value === 'error' ||\n value === 'other'\n ) {\n return value;\n }\n return fallback;\n};\n\nconst isDataEventName = (name: string): name is `data-${string}` => name.startsWith('data-');\n\nconst parseJsonOrString = (value: string): unknown => {\n if (!value) return undefined;\n try {\n // CAST: JSON.parse returns any; unknown is the safe trust-boundary type.\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Streamed message event builders (output-side)\n// ---------------------------------------------------------------------------\n\n/**\n * Read the codec event type from a tracker's codec headers. The encoder\n * stamps the codec `type` header on every `ai-output` publish; the value\n * carries the AI-SDK chunk family (`text` / `reasoning` / `tool-input`)\n * that the stream represents.\n * @param tracker - The stream tracker carrying the persistent headers.\n * @returns The codec event type, or the empty string when absent.\n */\nconst codecTypeOf = (tracker: StreamTrackerState): string => headerReader(tracker.codecHeaders).strOr('type', '');\n\nconst buildStartChunk = (tracker: StreamTrackerState): AI.UIMessageChunk => {\n const r = headerReader(tracker.codecHeaders);\n switch (codecTypeOf(tracker)) {\n case 'text': {\n return stripUndefined({\n type: 'text-start' as const,\n id: tracker.streamId,\n providerMetadata: r.providerMetadata(),\n });\n }\n case 'reasoning': {\n return stripUndefined({\n type: 'reasoning-start' as const,\n id: tracker.streamId,\n providerMetadata: r.providerMetadata(),\n });\n }\n case 'tool-input': {\n return stripUndefined({\n type: 'tool-input-start' as const,\n toolCallId: tracker.streamId,\n toolName: r.strOr('toolName', ''),\n dynamic: r.bool('dynamic'),\n title: r.str('title'),\n providerExecuted: r.bool('providerExecuted'),\n providerMetadata: r.providerMetadata(),\n });\n }\n default: {\n return { type: 'text-start', id: tracker.streamId };\n }\n }\n};\n\nconst buildDeltaChunk = (tracker: StreamTrackerState, delta: string): AI.UIMessageChunk => {\n switch (codecTypeOf(tracker)) {\n case 'text': {\n return { type: 'text-delta', id: tracker.streamId, delta };\n }\n case 'reasoning': {\n return { type: 'reasoning-delta', id: tracker.streamId, delta };\n }\n case 'tool-input': {\n return { type: 'tool-input-delta', toolCallId: tracker.streamId, inputTextDelta: delta };\n }\n default: {\n return { type: 'text-delta', id: tracker.streamId, delta };\n }\n }\n};\n\nconst buildEndChunk = (tracker: StreamTrackerState, closingHeaders: Record<string, string>): AI.UIMessageChunk => {\n const r = headerReader(closingHeaders);\n switch (codecTypeOf(tracker)) {\n case 'text': {\n return stripUndefined({\n type: 'text-end' as const,\n id: tracker.streamId,\n providerMetadata: r.providerMetadata(),\n });\n }\n case 'reasoning': {\n return stripUndefined({\n type: 'reasoning-end' as const,\n id: tracker.streamId,\n providerMetadata: r.providerMetadata(),\n });\n }\n case 'tool-input': {\n return stripUndefined({\n type: 'tool-input-available' as const,\n toolCallId: tracker.streamId,\n toolName: r.strOr('toolName', headerReader(tracker.codecHeaders).strOr('toolName', '')),\n input: parseJsonOrString(tracker.accumulated),\n providerMetadata: r.providerMetadata(),\n });\n }\n default: {\n return { type: 'text-end', id: tracker.streamId };\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Lifecycle tracker configuration (synthetic event phases on mid-stream join)\n// ---------------------------------------------------------------------------\n\nconst createVercelLifecycleTracker = (): LifecycleTracker<AI.UIMessageChunk> =>\n createLifecycleTracker<AI.UIMessageChunk>([\n {\n key: 'start',\n build: (ctx) => [stripUndefined({ type: 'start' as const, messageId: ctx.messageId })],\n },\n {\n key: 'start-step',\n build: () => [{ type: 'start-step' as const }],\n },\n ]);\n\n// ---------------------------------------------------------------------------\n// Discrete output decoders (ai-output → UIMessageChunk)\n// ---------------------------------------------------------------------------\n\nconst decodeStart = (\n r: VercelHeaderReader,\n runId: string,\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n): AI.UIMessageChunk[] => {\n lifecycle.markEmitted(runId, 'start');\n return [\n stripUndefined({\n type: 'start' as const,\n messageId: r.str('messageId'),\n messageMetadata: r.json('messageMetadata'),\n }),\n ];\n};\n\nconst decodeStartStep = (runId: string, lifecycle: LifecycleTracker<AI.UIMessageChunk>): AI.UIMessageChunk[] => {\n lifecycle.markEmitted(runId, 'start-step');\n return [{ type: 'start-step' }];\n};\n\nconst decodeFinishStep = (runId: string, lifecycle: LifecycleTracker<AI.UIMessageChunk>): AI.UIMessageChunk[] => {\n lifecycle.resetPhase(runId, 'start-step');\n return [{ type: 'finish-step' }];\n};\n\nconst decodeFinish = (\n r: VercelHeaderReader,\n runId: string,\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n): AI.UIMessageChunk[] => {\n lifecycle.clearScope(runId);\n return [\n stripUndefined({\n type: 'finish' as const,\n finishReason: parseFinishReason(r.str('finishReason'), 'stop'),\n messageMetadata: r.json('messageMetadata'),\n }),\n ];\n};\n\nconst decodeError = (\n data: unknown,\n runId: string,\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n): AI.UIMessageChunk[] => {\n lifecycle.clearScope(runId);\n const errorText = typeof data === 'string' ? data : '';\n return [{ type: 'error', errorText }];\n};\n\nconst decodeAbort = (\n data: unknown,\n runId: string,\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n): AI.UIMessageChunk[] => {\n lifecycle.clearScope(runId);\n const reason = typeof data === 'string' && data ? data : undefined;\n return [stripUndefined({ type: 'abort' as const, reason })];\n};\n\nconst decodeMessageMetadata = (r: VercelHeaderReader): AI.UIMessageChunk[] => [\n { type: 'message-metadata', messageMetadata: r.json('messageMetadata') },\n];\n\nconst decodeFile = (r: VercelHeaderReader, data: unknown): AI.UIMessageChunk[] => [\n stripUndefined({\n type: 'file' as const,\n url: typeof data === 'string' ? data : '',\n mediaType: r.strOr('mediaType', ''),\n providerMetadata: r.providerMetadata(),\n }),\n];\n\nconst decodeSourceUrl = (r: VercelHeaderReader, data: unknown): AI.UIMessageChunk[] => [\n stripUndefined({\n type: 'source-url' as const,\n sourceId: r.strOr('sourceId', ''),\n url: typeof data === 'string' ? data : '',\n title: r.str('title'),\n providerMetadata: r.providerMetadata(),\n }),\n];\n\nconst decodeSourceDocument = (r: VercelHeaderReader): AI.UIMessageChunk[] => [\n stripUndefined({\n type: 'source-document' as const,\n sourceId: r.strOr('sourceId', ''),\n mediaType: r.strOr('mediaType', ''),\n title: r.strOr('title', ''),\n filename: r.str('filename'),\n providerMetadata: r.providerMetadata(),\n }),\n];\n\nconst decodeToolInputError = (r: VercelHeaderReader, data: unknown): AI.UIMessageChunk[] => {\n // CAST: Trust boundary — encoder produced the expected object shape.\n const parsed = data as ToolInputErrorWireData | undefined;\n return [\n stripUndefined({\n type: 'tool-input-error' as const,\n toolCallId: r.strOr('toolCallId', ''),\n toolName: r.strOr('toolName', ''),\n errorText: parsed?.errorText ?? '',\n input: parsed?.input,\n dynamic: r.bool('dynamic'),\n title: r.str('title'),\n providerExecuted: r.bool('providerExecuted'),\n providerMetadata: r.providerMetadata(),\n }),\n ];\n};\n\nconst decodeAgentToolOutputAvailable = (r: VercelHeaderReader, data: unknown): AI.UIMessageChunk[] => {\n // CAST: Trust boundary — encoder produced the expected object shape.\n const parsed = data as ToolOutputAvailableWireData | undefined;\n return [\n stripUndefined({\n type: 'tool-output-available' as const,\n toolCallId: r.strOr('toolCallId', ''),\n output: parsed?.output,\n dynamic: r.bool('dynamic'),\n providerExecuted: r.bool('providerExecuted'),\n preliminary: r.bool('preliminary'),\n }),\n ];\n};\n\nconst decodeAgentToolOutputError = (r: VercelHeaderReader, data: unknown): AI.UIMessageChunk[] => {\n // CAST: Trust boundary — encoder produced the expected object shape.\n const parsed = data as AgentToolOutputErrorWireData | undefined;\n return [\n stripUndefined({\n type: 'tool-output-error' as const,\n toolCallId: r.strOr('toolCallId', ''),\n errorText: parsed?.errorText ?? '',\n dynamic: r.bool('dynamic'),\n providerExecuted: r.bool('providerExecuted'),\n }),\n ];\n};\n\nconst decodeToolApprovalRequest = (r: VercelHeaderReader): AI.UIMessageChunk[] => [\n {\n type: 'tool-approval-request',\n toolCallId: r.strOr('toolCallId', ''),\n approvalId: r.strOr('approvalId', ''),\n },\n];\n\nconst decodeToolOutputDenied = (r: VercelHeaderReader): AI.UIMessageChunk[] => [\n { type: 'tool-output-denied', toolCallId: r.strOr('toolCallId', '') },\n];\n\nconst decodeDataEvent = (name: `data-${string}`, r: VercelHeaderReader, data: unknown): AI.UIMessageChunk[] => [\n stripUndefined({\n type: name,\n data,\n id: r.str('id'),\n transient: r.bool('transient'),\n }),\n];\n\n// ---------------------------------------------------------------------------\n// Non-streaming tool-input helper (agent-side)\n// ---------------------------------------------------------------------------\n\nconst decodeNonStreamingToolInput = (\n r: VercelHeaderReader,\n data: unknown,\n runId: string,\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n): AI.UIMessageChunk[] => [\n ...lifecycle.ensurePhases(runId, { messageId: r.str('messageId') }),\n stripUndefined({\n type: 'tool-input-start' as const,\n toolCallId: r.strOr('toolCallId', ''),\n toolName: r.strOr('toolName', ''),\n dynamic: r.bool('dynamic'),\n title: r.str('title'),\n providerExecuted: r.bool('providerExecuted'),\n providerMetadata: r.providerMetadata(),\n }),\n stripUndefined({\n type: 'tool-input-available' as const,\n toolCallId: r.strOr('toolCallId', ''),\n toolName: r.strOr('toolName', ''),\n input: data,\n providerMetadata: r.providerMetadata(),\n }),\n];\n\n// ---------------------------------------------------------------------------\n// Input-side decoders (ai-input → VercelInput)\n// ---------------------------------------------------------------------------\n\n/**\n * Decode a single discrete message part (from the user-message multi-part\n * wire format) into a {@link UserMessage} carrying a one-part\n * UIMessage. The reducer's `_foldUserMessage` merges parts that share\n * the same codec-message-id.\n * @param input - The discrete message payload (name, data, headers).\n * @returns A single `user-message` input, or an empty array when the part type is unrecognised.\n */\nconst decodeDiscreteMessagePart = (input: MessagePayload): VercelInput[] => {\n const r = headerReader(input.codecHeaders ?? {});\n const role = (input.transportHeaders?.[HEADER_ROLE] ?? 'user') as AI.UIMessage['role'];\n const messageId = r.str('messageId') ?? '';\n const codecType = r.strOr('type', '');\n\n let part: AI.UIMessage['parts'][number] | undefined;\n\n switch (codecType) {\n case 'text': {\n part = { type: 'text', text: typeof input.data === 'string' ? input.data : '' };\n break;\n }\n case 'file': {\n part = {\n type: 'file',\n mediaType: r.strOr('mediaType', ''),\n url: typeof input.data === 'string' ? input.data : '',\n };\n break;\n }\n default: {\n if (isDataEventName(codecType)) {\n part = stripUndefined({ type: codecType, id: r.str('id'), data: input.data });\n }\n break;\n }\n }\n\n if (!part) return [];\n\n const message: AI.UIMessage = { id: messageId, role, parts: [part] };\n const userMessage: UserMessage<AI.UIMessage> = { kind: 'user-message', message };\n return [userMessage];\n};\n\nconst isDiscreteMessagePart = (codecType: string, headers: Record<string, string>): boolean =>\n (codecType === 'text' || codecType === 'file' || isDataEventName(codecType)) && HEADER_DISCRETE in headers;\n\nconst decodeClientToolResult = (codecMessageId: string, r: VercelHeaderReader, data: unknown): VercelInput[] => {\n // CAST: Trust boundary — encoder produced the expected object shape.\n const parsed = data as ToolOutputAvailableWireData | undefined;\n return [\n {\n kind: 'tool-result',\n codecMessageId,\n payload: { toolCallId: r.strOr('toolCallId', ''), output: parsed?.output },\n },\n ];\n};\n\nconst decodeClientToolResultError = (codecMessageId: string, r: VercelHeaderReader, data: unknown): VercelInput[] => {\n // CAST: Trust boundary — encoder produced the expected object shape.\n const parsed = data as ClientToolResultErrorWireData | undefined;\n return [\n {\n kind: 'tool-result-error',\n codecMessageId,\n payload: { toolCallId: r.strOr('toolCallId', ''), message: parsed?.message ?? '' },\n },\n ];\n};\n\nconst decodeClientToolApprovalResponse = (codecMessageId: string, r: VercelHeaderReader): VercelInput[] => [\n {\n kind: 'tool-approval-response',\n codecMessageId,\n payload: stripUndefined({\n toolCallId: r.strOr('toolCallId', ''),\n approved: r.bool('approved') ?? false,\n reason: r.str('reason'),\n }),\n },\n];\n\n// ---------------------------------------------------------------------------\n// Discrete payload dispatch\n// ---------------------------------------------------------------------------\n\nconst decodeAiOutputPayload = (\n codecType: string,\n r: VercelHeaderReader,\n data: unknown,\n runId: string,\n lifecycle: LifecycleTracker<AI.UIMessageChunk>,\n): AnyEvent[] => {\n switch (codecType) {\n case 'start': {\n return decodeStart(r, runId, lifecycle);\n }\n case 'start-step': {\n return decodeStartStep(runId, lifecycle);\n }\n case 'finish-step': {\n return decodeFinishStep(runId, lifecycle);\n }\n case 'finish': {\n return decodeFinish(r, runId, lifecycle);\n }\n case 'error': {\n return decodeError(data, runId, lifecycle);\n }\n case 'abort': {\n return decodeAbort(data, runId, lifecycle);\n }\n case 'message-metadata': {\n return decodeMessageMetadata(r);\n }\n case 'file': {\n return decodeFile(r, data);\n }\n case 'source-url': {\n return decodeSourceUrl(r, data);\n }\n case 'source-document': {\n return decodeSourceDocument(r);\n }\n case 'tool-input': {\n return decodeNonStreamingToolInput(r, data, runId, lifecycle);\n }\n case 'tool-input-error': {\n return decodeToolInputError(r, data);\n }\n case 'tool-output-available': {\n return decodeAgentToolOutputAvailable(r, data);\n }\n case 'tool-output-error': {\n return decodeAgentToolOutputError(r, data);\n }\n case 'tool-approval-request': {\n return decodeToolApprovalRequest(r);\n }\n case 'tool-output-denied': {\n return decodeToolOutputDenied(r);\n }\n default: {\n return isDataEventName(codecType) ? decodeDataEvent(codecType, r, data) : [];\n }\n }\n};\n\nconst decodeAiInputPayload = (codecType: string, input: MessagePayload, r: VercelHeaderReader): AnyEvent[] => {\n // Multi-part user-message parts (text / file / data-*) carry discrete\n // because they ride publishDiscreteBatch; the receive-side fans them back\n // out into a UserMessage.\n if (isDiscreteMessagePart(codecType, input.transportHeaders ?? {})) {\n return decodeDiscreteMessagePart(input);\n }\n\n const codecMessageId = input.transportHeaders?.[HEADER_CODEC_MESSAGE_ID] ?? '';\n\n switch (codecType) {\n case 'tool-result': {\n return decodeClientToolResult(codecMessageId, r, input.data);\n }\n case 'tool-result-error': {\n return decodeClientToolResultError(codecMessageId, r, input.data);\n }\n case 'tool-approval-response': {\n return decodeClientToolApprovalResponse(codecMessageId, r);\n }\n case 'regenerate': {\n // Wire-only signal — carries `parent` / `msg-regenerate` on transport\n // headers, no domain payload. The agent's input-event lookup reads\n // transport headers directly from the inbound Ably message; no\n // projection fold is needed here.\n return [];\n }\n default: {\n return [];\n }\n }\n};\n\nconst decodeDiscretePayload = (input: MessagePayload, lifecycle: LifecycleTracker<AI.UIMessageChunk>): AnyEvent[] => {\n const r = headerReader(input.codecHeaders ?? {});\n const runId = input.transportHeaders?.[HEADER_RUN_ID] ?? '';\n const codecType = r.strOr('type', '');\n\n if (input.name === EVENT_AI_INPUT) {\n return decodeAiInputPayload(codecType, input, r);\n }\n\n if (input.name === EVENT_AI_OUTPUT) {\n return decodeAiOutputPayload(codecType, r, input.data, runId, lifecycle);\n }\n\n return [];\n};\n\n// ---------------------------------------------------------------------------\n// Decoder core hooks\n// ---------------------------------------------------------------------------\n\nconst createHooks = (lifecycle: LifecycleTracker<AI.UIMessageChunk>): DecoderCoreHooks<AnyEvent> => ({\n buildStartEvents: (tracker: StreamTrackerState): AnyEvent[] => {\n const runId = tracker.transportHeaders[HEADER_RUN_ID] ?? '';\n const messageId = headerReader(tracker.codecHeaders).str('messageId');\n return [...lifecycle.ensurePhases(runId, { messageId }), buildStartChunk(tracker)];\n },\n\n buildDeltaEvents: (tracker: StreamTrackerState, delta: string): AnyEvent[] => [buildDeltaChunk(tracker, delta)],\n\n buildEndEvents: (tracker: StreamTrackerState, closingHeaders: Record<string, string>): AnyEvent[] => [\n buildEndChunk(tracker, closingHeaders),\n ],\n\n decodeDiscrete: (payload: MessagePayload): AnyEvent[] => decodeDiscretePayload(payload, lifecycle),\n});\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\nconst isInput = (event: AnyEvent): event is VercelInput => 'kind' in event;\n\nclass DefaultUIMessageDecoder implements Decoder<VercelInput, VercelOutput> {\n private readonly _core: DecoderCore<AnyEvent>;\n\n constructor(options: DecoderCoreOptions = {}) {\n this._core = createDecoderCore<AnyEvent>(createHooks(createVercelLifecycleTracker()), options);\n }\n\n decode(message: Ably.InboundMessage): DecodedMessage<VercelInput, VercelOutput> {\n const events = this._core.decode(message);\n const inputs: VercelInput[] = [];\n const outputs: VercelOutput[] = [];\n for (const event of events) {\n if (isInput(event)) {\n inputs.push(event);\n } else {\n outputs.push(event);\n }\n }\n return { inputs, outputs };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Vercel AI SDK decoder that maps Ably messages to {@link DecodedMessage}.\n * @param options - Decoder configuration (callbacks, logger).\n * @returns A {@link Decoder} typed in both directions for the Vercel codec.\n */\nexport const createDecoder = (options: DecoderCoreOptions = {}): Decoder<VercelInput, VercelOutput> =>\n new DefaultUIMessageDecoder(options);\n","import * as Ably from 'ably';\n\n/**\n * Error codes for the AI Transport SDK.\n */\nexport enum ErrorCode {\n /**\n * The request was invalid.\n */\n BadRequest = 40000,\n\n /**\n * Invalid argument provided.\n */\n InvalidArgument = 40003,\n\n /**\n * Operation not permitted with the provided capability (Ably 40160).\n * Used when the Ably channel rejects a publish for a capability reason.\n */\n InsufficientCapability = 40160,\n\n // 104000 - 104999 are reserved for AI Transport SDK errors\n\n /**\n * Encoder recovery failed during flush — one or more updateMessage calls\n * could not recover a failed append pipeline.\n */\n EncoderRecoveryFailed = 104000,\n\n /**\n * A session-level channel subscription callback threw unexpectedly.\n */\n SessionSubscriptionError = 104001,\n\n /**\n * Cancel listener or onCancel hook threw while processing a cancel message.\n */\n CancelListenerError = 104002,\n\n /**\n * A publish within a run failed (lifecycle event, message, or event).\n */\n RunLifecycleError = 104003,\n\n /**\n * An operation was attempted on a session that has already been closed.\n */\n SessionClosed = 104004,\n\n /**\n * The HTTP POST to the agent endpoint failed (network error or non-2xx response).\n */\n SessionSendFailed = 104005,\n\n /**\n * The Ably channel lost message continuity — the channel entered FAILED,\n * SUSPENDED, or DETACHED, or re-attached with `resumed: false`. Active\n * streams can no longer be guaranteed to receive all events.\n */\n ChannelContinuityLost = 104006,\n\n /**\n * An operation was attempted but the channel is not in a usable state\n * (not ATTACHED or ATTACHING).\n */\n ChannelNotReady = 104007,\n\n /**\n * An error occurred while piping a response stream to the channel — either\n * the source event stream threw (e.g. LLM provider rate limit, model error,\n * network failure) or an underlying publish failed mid-stream.\n */\n StreamError = 104008,\n\n /**\n * The agent attached to the channel and waited for the input event(s) the\n * invocation points at (rewind + live wait) but `inputEventLookupTimeoutMs`\n * lapsed without seeing them.\n */\n InputEventNotFound = 104010,\n}\n\n/**\n * Returns true if the {@link Ably.ErrorInfo} code matches the provided ErrorCode value.\n * @param errorInfo The error info to check.\n * @param error The error code to compare against.\n * @returns true if the error code matches, false otherwise.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\nexport const errorInfoIs = (errorInfo: Ably.ErrorInfo, error: ErrorCode): boolean => errorInfo.code === error;\n","/**\n * Encoder core — message append lifecycle machinery.\n *\n * Provides Ably primitives (publish, append, close, cancel, flush) that\n * domain-specific encoders wire their event types to.\n *\n * Domain encoders call `createEncoderCore(writer, options)` and use the\n * returned core to map domain events to Ably operations without\n * reimplementing the message append lifecycle.\n */\n\nimport * as Ably from 'ably';\n\nimport {\n HEADER_CODEC_MESSAGE_ID,\n HEADER_DISCRETE,\n HEADER_STATUS,\n HEADER_STREAM,\n HEADER_STREAM_ID,\n} from '../../constants.js';\nimport { ErrorCode } from '../../errors.js';\nimport type { Logger } from '../../logger.js';\nimport { mergeHeaders } from '../../utils.js';\nimport type { ChannelWriter, EncoderOptions, Extras, MessagePayload, StreamPayload, WriteOptions } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for creating an encoder core. Extends {@link EncoderOptions} with a logger. */\nexport interface EncoderCoreOptions extends EncoderOptions {\n /** Logger instance for diagnostic output. */\n logger?: Logger;\n}\n\n// ---------------------------------------------------------------------------\n// Stream tracker (internal)\n// ---------------------------------------------------------------------------\n\ninterface StreamState {\n serial: string;\n name: string;\n streamId: string;\n accumulated: string;\n /** Transport-tier headers repeated on every append (`extras.ai.transport`). */\n persistentTransport: Record<string, string>;\n /** Codec-tier headers repeated on every append (`extras.ai.codec`). */\n persistentCodec: Record<string, string>;\n cancelled: boolean;\n}\n\n/**\n * The SDK's `extras.ai` namespace as written to the wire: a `transport` tier\n * (always present on SDK-published messages) and an optional `codec` tier.\n */\ninterface AiExtras {\n transport: Record<string, string>;\n codec?: Record<string, string>;\n}\n\ninterface PendingAppend {\n promise: Promise<Ably.UpdateDeleteResult>;\n streamId: string;\n}\n\n// ---------------------------------------------------------------------------\n// Encoder core interface\n// ---------------------------------------------------------------------------\n\n/** The core encoder primitives that domain codec encoders delegate to. */\nexport interface EncoderCore {\n /** Publish a single discrete (non-streaming) message described by a payload. */\n publishDiscrete(payload: MessagePayload, opts?: WriteOptions): Promise<Ably.PublishResult>;\n\n /** Publish multiple discrete messages atomically in a single channel publish. */\n publishDiscreteBatch(payloads: MessagePayload[], opts?: WriteOptions): Promise<Ably.PublishResult>;\n\n /** Start a streamed message with status:streaming. */\n startStream(streamId: string, payload: StreamPayload, opts?: WriteOptions): Promise<void>;\n\n /**\n * Append data to an in-flight streamed message. Fire-and-forget: errors are\n * collected internally and surfaced by {@link closeStream}, {@link cancelStream},\n * {@link cancelAllStreams} or {@link close}.\n * @throws {Ably.ErrorInfo} InvalidArgument if there is no active stream for `streamId` or the core is closed.\n */\n appendStream(streamId: string, data: string): void;\n\n /**\n * Close a streamed message with status:complete. Flushes all pending\n * appends for recovery before returning. Repeats persistent and payload headers.\n * @throws {Ably.ErrorInfo} InvalidArgument if there is no active stream for `streamId`, or the encoder has been closed; EncoderRecoveryFailed if a failed append cannot be recovered during the flush.\n */\n closeStream(streamId: string, payload: StreamPayload): Promise<void>;\n\n /**\n * Cancel a single in-progress stream (status:cancelled) and flush all\n * pending appends for recovery before returning.\n */\n cancelStream(streamId: string, opts?: WriteOptions): Promise<void>;\n\n /**\n * Cancel all in-progress streams (status:cancelled) and flush all\n * pending appends for recovery before returning.\n */\n cancelAllStreams(opts?: WriteOptions): Promise<void>;\n\n /** Flush + clear trackers. Idempotent. */\n close(): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CD1\nclass DefaultEncoderCore implements EncoderCore {\n private readonly _writer: ChannelWriter;\n private readonly _defaultClientId: string | undefined;\n private readonly _defaultExtras: Extras | undefined;\n private readonly _onMessageHook: (message: Ably.Message) => void;\n private readonly _logger: Logger | undefined;\n private readonly _trackers = new Map<string, StreamState>();\n private _pending: PendingAppend[] = [];\n private _flushPromise: Promise<void> | undefined;\n private _closed = false;\n\n constructor(writer: ChannelWriter, options: EncoderCoreOptions = {}) {\n this._writer = writer;\n this._defaultClientId = options.clientId;\n this._defaultExtras = options.extras;\n this._onMessageHook =\n options.onMessage ??\n (() => {\n /* noop */\n });\n this._logger = options.logger?.withContext({ component: 'EncoderCore' });\n }\n\n // Spec: AIT-CD11\n async publishDiscrete(payload: MessagePayload, opts?: WriteOptions): Promise<Ably.PublishResult> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.publishDiscrete();', { name: payload.name });\n const msg = this._buildDiscreteMessage(payload, opts);\n return this._writer.publish(msg);\n }\n\n // Spec: AIT-CD11a\n async publishDiscreteBatch(payloads: MessagePayload[], opts?: WriteOptions): Promise<Ably.PublishResult> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.publishDiscreteBatch();', { count: payloads.length });\n const msgs = payloads.map((p) => this._buildDiscreteMessage(p, opts, true));\n return this._writer.publish(msgs);\n }\n\n // Spec: AIT-CD2\n async startStream(streamId: string, payload: StreamPayload, opts?: WriteOptions): Promise<void> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.startStream();', { name: payload.name, streamId });\n\n const transport = this._buildTransport(payload.transportHeaders, opts);\n transport[HEADER_STREAM] = 'true';\n transport[HEADER_STATUS] = 'streaming';\n transport[HEADER_STREAM_ID] = streamId;\n const codec = payload.codecHeaders ?? {};\n\n const clientId = this._resolveClientId(opts);\n const msg: Ably.Message = {\n name: payload.name,\n data: payload.data,\n extras: { ai: this._aiExtras(transport, codec) },\n ...(clientId ? { clientId } : {}),\n };\n\n this._invokeOnMessage(msg);\n const result = await this._writer.publish(msg);\n const serial = result.serials[0];\n\n // Spec: AIT-CD2a\n if (!serial) {\n throw new Ably.ErrorInfo(\n `unable to start stream; no serial returned for stream '${payload.name}' (streamId: ${streamId})`,\n ErrorCode.BadRequest,\n 400,\n );\n }\n\n this._trackers.set(streamId, {\n serial,\n name: payload.name,\n streamId,\n accumulated: payload.data,\n persistentTransport: transport,\n persistentCodec: codec,\n cancelled: false,\n });\n\n this._logger?.debug('DefaultEncoderCore.startStream(); stream started', {\n name: payload.name,\n streamId,\n serial,\n });\n }\n\n // Spec: AIT-CD3\n appendStream(streamId: string, data: string): void {\n this._assertNotClosed();\n // Spec: AIT-CD3a\n const tracker = this._trackers.get(streamId);\n if (!tracker) {\n throw new Ably.ErrorInfo(\n `unable to append to stream; no active stream for streamId '${streamId}'`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n tracker.accumulated += data;\n\n const appendMsg: Ably.Message = {\n serial: tracker.serial,\n data,\n extras: { ai: this._aiExtras({ ...tracker.persistentTransport }, { ...tracker.persistentCodec }) },\n };\n\n this._invokeOnMessage(appendMsg);\n const p = this._writer.appendMessage(appendMsg);\n this._pending.push({ promise: p, streamId });\n }\n\n // Spec: AIT-CD4, AIT-CD4a\n async closeStream(streamId: string, payload: StreamPayload): Promise<void> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.closeStream();', { streamId });\n\n const tracker = this._trackers.get(streamId);\n if (!tracker) {\n throw new Ably.ErrorInfo(\n `unable to close stream; no active stream for streamId '${streamId}'`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n // Accumulate closing data so recovery has the full content\n tracker.accumulated += payload.data;\n\n const { transport, codec } = this._buildClosing(tracker, payload);\n transport[HEADER_STATUS] = 'complete';\n\n const msg: Ably.Message = {\n serial: tracker.serial,\n data: payload.data,\n extras: { ai: this._aiExtras(transport, codec) },\n };\n\n this._invokeOnMessage(msg);\n const p = this._writer.appendMessage(msg);\n this._pending.push({ promise: p, streamId });\n\n await this._flushPending();\n\n this._logger?.debug('DefaultEncoderCore.closeStream(); stream closed', { streamId });\n }\n\n // Spec: AIT-CD5, AIT-CD5b\n async cancelStream(streamId: string, opts?: WriteOptions): Promise<void> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.cancelStream();', { streamId });\n\n const tracker = this._trackers.get(streamId);\n if (!tracker) {\n throw new Ably.ErrorInfo(\n `unable to cancel stream; no active stream for streamId '${streamId}'`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n tracker.cancelled = true;\n\n const { transport, codec } = this._buildClosing(tracker, undefined, opts);\n transport[HEADER_STATUS] = 'cancelled';\n\n const msg: Ably.Message = {\n serial: tracker.serial,\n data: '',\n extras: { ai: this._aiExtras(transport, codec) },\n };\n\n this._invokeOnMessage(msg);\n const p = this._writer.appendMessage(msg);\n this._pending.push({ promise: p, streamId });\n\n await this._flushPending();\n\n this._logger?.debug('DefaultEncoderCore.cancelStream(); stream cancelled', { streamId });\n }\n\n // Spec: AIT-CD5a\n async cancelAllStreams(opts?: WriteOptions): Promise<void> {\n this._assertNotClosed();\n this._logger?.trace('DefaultEncoderCore.cancelAllStreams();', { streamCount: this._trackers.size });\n\n for (const tracker of this._trackers.values()) {\n tracker.cancelled = true;\n\n const { transport, codec } = this._buildClosing(tracker, undefined, opts);\n transport[HEADER_STATUS] = 'cancelled';\n\n const msg: Ably.Message = {\n serial: tracker.serial,\n data: '',\n extras: { ai: this._aiExtras(transport, codec) },\n };\n\n this._invokeOnMessage(msg);\n const p = this._writer.appendMessage(msg);\n this._pending.push({ promise: p, streamId: tracker.streamId });\n }\n\n await this._flushPending();\n }\n\n // Spec: AIT-CD6\n private async _flushPending(): Promise<void> {\n // Re-entrancy guard: if a flush is already in progress, await it instead of starting a new one.\n if (this._flushPromise) {\n return this._flushPromise;\n }\n\n const snapshot = this._pending;\n this._pending = [];\n\n if (snapshot.length === 0) return;\n\n this._logger?.trace('DefaultEncoderCore._flushPending();', { count: snapshot.length });\n\n this._flushPromise = this._doFlush(snapshot);\n try {\n await this._flushPromise;\n } finally {\n this._flushPromise = undefined;\n }\n }\n\n private async _doFlush(snapshot: PendingAppend[]): Promise<void> {\n const results = await Promise.allSettled(snapshot.map(async (p) => p.promise));\n const failures = new Set<string>();\n\n for (const [i, result] of results.entries()) {\n const entry = snapshot[i];\n if (entry && result.status === 'rejected') {\n failures.add(entry.streamId);\n }\n }\n\n if (failures.size === 0) {\n this._logger?.debug('DefaultEncoderCore._flushPending(); all appends succeeded');\n return;\n }\n\n this._logger?.warn('DefaultEncoderCore._flushPending(); recovering failed appends', {\n failedStreams: [...failures],\n });\n\n const recoveryErrors: { streamId: string; error: unknown }[] = [];\n\n for (const streamId of failures) {\n const tracker = this._trackers.get(streamId);\n if (!tracker) continue;\n\n const recoveryStatus = tracker.cancelled ? 'cancelled' : 'complete';\n const msg: Ably.Message = {\n serial: tracker.serial,\n data: tracker.accumulated,\n extras: {\n ai: this._aiExtras(\n { ...tracker.persistentTransport, [HEADER_STATUS]: recoveryStatus },\n { ...tracker.persistentCodec },\n ),\n },\n };\n\n try {\n await this._writer.updateMessage(msg);\n } catch (error) {\n recoveryErrors.push({ streamId, error });\n }\n }\n\n if (recoveryErrors.length > 0) {\n const ids = recoveryErrors.map((e) => e.streamId).join(', ');\n this._logger?.error('DefaultEncoderCore._flushPending(); recovery failed', { failedStreams: ids });\n throw new Ably.ErrorInfo(\n `unable to flush pending appends; recovery failed for stream(s): ${ids}`,\n ErrorCode.EncoderRecoveryFailed,\n 500,\n );\n }\n }\n\n // Spec: AIT-CD12\n async close(): Promise<void> {\n if (this._closed) return;\n this._logger?.trace('DefaultEncoderCore.close();');\n this._closed = true;\n try {\n await this._flushPending();\n } finally {\n this._trackers.clear();\n }\n this._logger?.debug('DefaultEncoderCore.close(); encoder closed');\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CD14\n private _invokeOnMessage(msg: Ably.Message): void {\n try {\n this._onMessageHook(msg);\n } catch (error) {\n this._logger?.error('DefaultEncoderCore._invokeOnMessage(); hook threw', { error });\n }\n }\n\n private _assertNotClosed(): void {\n if (this._closed) {\n throw new Ably.ErrorInfo('unable to write to encoder; encoder has been closed', ErrorCode.InvalidArgument, 400);\n }\n }\n\n private _resolveClientId(opts?: WriteOptions): string | undefined {\n return opts?.clientId ?? this._defaultClientId;\n }\n\n /**\n * Build the transport-tier header record for a message: caller-configured\n * transport headers (default extras + per-write overrides) layered with any\n * transport headers the codec payload stamps directly, plus the message-id.\n * @param payloadTransport - Transport headers carried on the codec payload.\n * @param opts - Optional per-write overrides.\n * @returns The transport-tier headers record (`extras.ai.transport`).\n */\n private _buildTransport(\n payloadTransport: Record<string, string> | undefined,\n opts?: WriteOptions,\n ): Record<string, string> {\n const callerHeaders = mergeHeaders(this._defaultExtras?.headers, opts?.extras?.headers);\n const transport = { ...callerHeaders, ...payloadTransport };\n if (opts?.messageId !== undefined) {\n transport[HEADER_CODEC_MESSAGE_ID] = opts.messageId;\n }\n return transport;\n }\n\n /**\n * Assemble the `extras.ai` namespace from its two tiers, omitting the codec\n * tier when empty.\n * @param transport - Transport-tier headers (always present on SDK messages).\n * @param codec - Codec-tier headers; omitted from the wire when empty.\n * @returns The `extras.ai` object.\n */\n private _aiExtras(transport: Record<string, string>, codec: Record<string, string>): AiExtras {\n return Object.keys(codec).length > 0 ? { transport, codec } : { transport };\n }\n\n private _buildDiscreteMessage(payload: MessagePayload, opts?: WriteOptions, discrete = false): Ably.Message {\n const transport = this._buildTransport(payload.transportHeaders, opts);\n transport[HEADER_STREAM] = 'false';\n if (discrete) {\n // Mark batch-published payloads as discrete message parts (from writeMessages).\n // The decoder relies on this header to distinguish message parts from lifecycle\n // events that also happen to be discrete (stream: false).\n transport[HEADER_DISCRETE] = 'true';\n }\n const clientId = this._resolveClientId(opts);\n\n const msg: Ably.Message = {\n name: payload.name,\n data: payload.data,\n extras: {\n ai: this._aiExtras(transport, payload.codecHeaders ?? {}),\n ...(payload.ephemeral ? { ephemeral: true } : {}),\n },\n ...(clientId ? { clientId } : {}),\n };\n\n this._invokeOnMessage(msg);\n return msg;\n }\n\n /**\n * Build both header tiers for a closing append. Closing appends must repeat\n * ALL persistent headers (Ably replaces the entire extras object on append).\n * Then layer caller and codec overrides.\n * @param tracker - The stream tracker with persistent headers.\n * @param payload - The closing stream payload (codec + transport headers).\n * @param opts - Optional per-write overrides.\n * @returns The two tiers for the closing append.\n */\n private _buildClosing(\n tracker: StreamState,\n payload: StreamPayload | undefined,\n opts?: WriteOptions,\n ): { transport: Record<string, string>; codec: Record<string, string> } {\n const callerHeaders = mergeHeaders(this._defaultExtras?.headers, opts?.extras?.headers);\n const transport = { ...tracker.persistentTransport, ...callerHeaders, ...payload?.transportHeaders };\n const codec = { ...tracker.persistentCodec, ...payload?.codecHeaders };\n return { transport, codec };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create an encoder core bound to the given channel writer.\n * @param writer - The channel writer to publish messages through.\n * @param options - Encoder configuration (clientId, extras, hooks, logger).\n * @returns A new {@link EncoderCore} instance.\n */\nexport const createEncoderCore = (writer: ChannelWriter, options: EncoderCoreOptions = {}): EncoderCore =>\n new DefaultEncoderCore(writer, options);\n","/**\n * Vercel AI SDK encoder.\n *\n * Two publish methods enforce direction at the call site:\n *\n * - {@link DefaultUIMessageEncoder.publishInput} encodes a `VercelInput`\n * variant and publishes it on the `ai-input` wire.\n * - {@link DefaultUIMessageEncoder.publishOutput} encodes a `VercelOutput`\n * (`AI.UIMessageChunk`) and publishes it on the `ai-output` wire,\n * driving the underlying stream-tracker for streamed chunks\n * (text / reasoning / tool-input) and falling back to discrete\n * publishes for everything else.\n *\n * The codec event's own discriminator (`kind` for inputs, `type` for\n * outputs) is carried in the codec tier's `type` header so the\n * decoder can dispatch. Stream-tracker state lives inside the encoder\n * core; only the output direction (text / reasoning / tool-input chunks)\n * drives it — inputs are always published as discrete messages.\n */\n\nimport * as Ably from 'ably';\nimport type * as AI from 'ai';\nimport { isDataUIPart } from 'ai';\n\nimport { EVENT_AI_INPUT, EVENT_AI_OUTPUT, HEADER_ROLE, HEADER_STATUS } from '../../constants.js';\nimport type { EncoderCore, EncoderCoreOptions } from '../../core/codec/encoder.js';\nimport { createEncoderCore } from '../../core/codec/encoder.js';\nimport type {\n ChannelWriter,\n Encoder,\n MessagePayload,\n ToolApprovalResponse,\n ToolResult,\n ToolResultError,\n UserMessage,\n WriteOptions,\n} from '../../core/codec/types.js';\nimport { ErrorCode, errorInfoIs } from '../../errors.js';\nimport { headerWriter } from '../../utils.js';\nimport type {\n VercelInput,\n VercelOutput,\n VercelToolApprovalResponsePayload,\n VercelToolResultErrorPayload,\n VercelToolResultPayload,\n} from './events.js';\n\n// ---------------------------------------------------------------------------\n// Default implementation\n// ---------------------------------------------------------------------------\n\nclass DefaultUIMessageEncoder implements Encoder<VercelInput, VercelOutput> {\n private readonly _core: EncoderCore;\n private readonly _messageId: string | undefined;\n private _cancelled = false;\n\n constructor(writer: ChannelWriter, options: EncoderCoreOptions = {}) {\n this._core = createEncoderCore(writer, options);\n this._messageId = options.messageId;\n }\n\n async publishInput(input: VercelInput, options?: WriteOptions): Promise<void> {\n switch (input.kind) {\n case 'user-message': {\n await this._publishUserMessage(input, options);\n return;\n }\n case 'regenerate': {\n await this._publishRegenerate(options);\n return;\n }\n case 'tool-result': {\n await this._publishToolResult(input, options);\n return;\n }\n case 'tool-result-error': {\n await this._publishToolResultError(input, options);\n return;\n }\n case 'tool-approval-response': {\n await this._publishToolApprovalResponse(input, options);\n return;\n }\n }\n }\n\n async publishOutput(output: VercelOutput, options?: WriteOptions): Promise<void> {\n await this._publishChunk(output, options);\n }\n\n async cancel(reason?: string): Promise<void> {\n if (this._cancelled) return;\n this._cancelled = true;\n await this._core.cancelAllStreams();\n await this._core.publishDiscrete({\n name: EVENT_AI_OUTPUT,\n data: reason ?? '',\n codecHeaders: headerWriter().str('type', 'abort').build(),\n transportHeaders: { [HEADER_STATUS]: 'cancelled' },\n });\n }\n\n async close(): Promise<void> {\n await this._core.close();\n }\n\n // -------------------------------------------------------------------------\n // VercelOutput routing — UIMessageChunk\n // -------------------------------------------------------------------------\n\n private async _publishChunk(chunk: AI.UIMessageChunk, perWrite?: WriteOptions): Promise<void> {\n switch (chunk.type) {\n // -- Stream start -----------------------------------------------------\n case 'text-start': {\n const h = headerWriter()\n .str('type', 'text')\n .str('id', chunk.id)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.startStream(chunk.id, { name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n case 'reasoning-start': {\n const h = headerWriter()\n .str('type', 'reasoning')\n .str('id', chunk.id)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.startStream(chunk.id, { name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n case 'tool-input-start': {\n const h = headerWriter()\n .str('type', 'tool-input')\n .str('toolCallId', chunk.toolCallId)\n .str('toolName', chunk.toolName)\n .bool('dynamic', chunk.dynamic)\n .str('title', chunk.title)\n .bool('providerExecuted', chunk.providerExecuted)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.startStream(chunk.toolCallId, { name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n\n // -- Stream append ----------------------------------------------------\n case 'text-delta': {\n this._core.appendStream(chunk.id, chunk.delta);\n return;\n }\n case 'reasoning-delta': {\n this._core.appendStream(chunk.id, chunk.delta);\n return;\n }\n case 'tool-input-delta': {\n this._core.appendStream(chunk.toolCallId, chunk.inputTextDelta);\n return;\n }\n\n // -- Stream close -----------------------------------------------------\n case 'text-end': {\n const h = headerWriter()\n .str('type', 'text')\n .str('id', chunk.id)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.closeStream(chunk.id, { name: EVENT_AI_OUTPUT, data: '', codecHeaders: h });\n return;\n }\n case 'reasoning-end': {\n const h = headerWriter()\n .str('type', 'reasoning')\n .str('id', chunk.id)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.closeStream(chunk.id, { name: EVENT_AI_OUTPUT, data: '', codecHeaders: h });\n return;\n }\n case 'tool-input-available': {\n try {\n const h = headerWriter()\n .str('type', 'tool-input')\n .str('toolCallId', chunk.toolCallId)\n .str('toolName', chunk.toolName)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.closeStream(chunk.toolCallId, { name: EVENT_AI_OUTPUT, data: '', codecHeaders: h });\n } catch (error: unknown) {\n // closeStream raises ErrorCode.InvalidArgument when there is no active stream for this id; fall through to a discrete publish in that case and rethrow any other error.\n if (!(error instanceof Ably.ErrorInfo && errorInfoIs(error, ErrorCode.InvalidArgument))) {\n throw error;\n }\n const h = headerWriter()\n .str('type', 'tool-input')\n .str('toolCallId', chunk.toolCallId)\n .str('toolName', chunk.toolName)\n .bool('dynamic', chunk.dynamic)\n .str('title', chunk.title)\n .bool('providerExecuted', chunk.providerExecuted)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: chunk.input, codecHeaders: h });\n }\n return;\n }\n\n // -- Lifecycle (discrete) ---------------------------------------------\n case 'start': {\n const h = headerWriter()\n .str('type', 'start')\n .str('messageId', chunk.messageId ?? this._messageId)\n .json('messageMetadata', chunk.messageMetadata)\n .build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n case 'start-step': {\n const h = headerWriter().str('type', 'start-step').build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n case 'finish-step': {\n const h = headerWriter().str('type', 'finish-step').build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n case 'finish': {\n const h = headerWriter()\n .str('type', 'finish')\n .str('finishReason', chunk.finishReason)\n .json('messageMetadata', chunk.messageMetadata)\n .build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n case 'error': {\n const h = headerWriter().str('type', 'error').build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: chunk.errorText, codecHeaders: h }, perWrite);\n return;\n }\n case 'abort': {\n this._cancelled = true;\n await this._core.cancelAllStreams(perWrite);\n await this._core.publishDiscrete(\n {\n name: EVENT_AI_OUTPUT,\n data: chunk.reason ?? '',\n codecHeaders: headerWriter().str('type', 'abort').build(),\n transportHeaders: { [HEADER_STATUS]: 'cancelled' },\n },\n perWrite,\n );\n return;\n }\n case 'message-metadata': {\n const h = headerWriter().str('type', 'message-metadata').json('messageMetadata', chunk.messageMetadata).build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n\n // -- Tool lifecycle (discrete) ----------------------------------------\n case 'tool-input-error': {\n const h = headerWriter()\n .str('type', 'tool-input-error')\n .str('toolCallId', chunk.toolCallId)\n .str('toolName', chunk.toolName)\n .bool('dynamic', chunk.dynamic)\n .str('title', chunk.title)\n .bool('providerExecuted', chunk.providerExecuted)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete(\n { name: EVENT_AI_OUTPUT, data: { errorText: chunk.errorText, input: chunk.input }, codecHeaders: h },\n perWrite,\n );\n return;\n }\n case 'tool-output-available':\n case 'tool-output-error':\n case 'tool-approval-request':\n case 'tool-output-denied': {\n await this._core.publishDiscrete(buildToolOutputPayload(chunk), perWrite);\n return;\n }\n\n // -- Content parts (discrete) -----------------------------------------\n case 'file': {\n const h = headerWriter()\n .str('type', 'file')\n .str('mediaType', chunk.mediaType)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: chunk.url, codecHeaders: h }, perWrite);\n return;\n }\n case 'source-url': {\n const h = headerWriter()\n .str('type', 'source-url')\n .str('sourceId', chunk.sourceId)\n .str('title', chunk.title)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: chunk.url, codecHeaders: h }, perWrite);\n return;\n }\n case 'source-document': {\n const h = headerWriter()\n .str('type', 'source-document')\n .str('sourceId', chunk.sourceId)\n .str('mediaType', chunk.mediaType)\n .str('title', chunk.title)\n .str('filename', chunk.filename)\n .json('providerMetadata', chunk.providerMetadata)\n .build();\n await this._core.publishDiscrete({ name: EVENT_AI_OUTPUT, data: '', codecHeaders: h }, perWrite);\n return;\n }\n\n // -- data-* (discrete) ------------------------------------------------\n default: {\n if (chunk.type.startsWith('data-')) {\n // CAST: data-* chunks always have id, transient, and data fields per AI SDK types.\n // TypeScript can't narrow the template literal union in a default case.\n const dataChunk = chunk;\n const h = headerWriter()\n .str('type', dataChunk.type)\n .str('id', dataChunk.id)\n .bool('transient', dataChunk.transient)\n .build();\n const ephemeral = dataChunk.transient === true;\n await this._core.publishDiscrete(\n { name: EVENT_AI_OUTPUT, data: dataChunk.data, codecHeaders: h, ephemeral },\n perWrite,\n );\n return;\n }\n throw new Ably.ErrorInfo(\n `unable to publish output; unsupported chunk type '${chunk.type}'`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // VercelInput routing\n // -------------------------------------------------------------------------\n\n /**\n * Publish a user-message input as a batch of per-part discrete Ably\n * messages on the `ai-input` wire. Wire format matches the multi-part\n * user-message convention; the receive-side decoder fans the parts back\n * out into a single `UserMessage`.\n * @param input - The user-message input carrying the UIMessage to encode.\n * @param perWrite - Optional per-write overrides.\n */\n private async _publishUserMessage(input: UserMessage<AI.UIMessage>, perWrite?: WriteOptions): Promise<void> {\n const payloads = encodeMessagePayloads(input.message);\n // Stamp role (a transport header) on every payload so the decoder can\n // reconstruct a `role: 'user'` UIMessage.\n for (const payload of payloads) {\n payload.transportHeaders = { ...payload.transportHeaders, [HEADER_ROLE]: 'user' };\n }\n await this._core.publishDiscreteBatch(payloads, perWrite);\n }\n\n /**\n * Publish a regenerate input as a discrete `ai-input` Ably message\n * carrying codec `type: 'regenerate'`. The wire carries no domain\n * payload — `parent` / `target` are stamped on the transport headers by\n * the client-session (it reads them off the input directly and builds\n * `buildTransportHeaders`).\n * @param perWrite - Per-write overrides carrying the transport headers built by client-session.\n */\n private async _publishRegenerate(perWrite?: WriteOptions): Promise<void> {\n const h = headerWriter().str('type', 'regenerate').build();\n await this._core.publishDiscrete({ name: EVENT_AI_INPUT, data: '', codecHeaders: h }, perWrite);\n }\n\n /**\n * Publish a client-side tool output on the `ai-input` wire. Targets the\n * assistant addressed by `input.codecMessageId`; the wire's\n * `codec-message-id` is stamped via `perWrite.messageId` by the\n * client-session.\n * @param input - The tool-output input.\n * @param perWrite - Per-write overrides carrying the wire codecMessageId.\n */\n private async _publishToolResult(input: ToolResult<VercelToolResultPayload>, perWrite?: WriteOptions): Promise<void> {\n const h = headerWriter().str('type', 'tool-result').str('toolCallId', input.payload.toolCallId).build();\n await this._core.publishDiscrete(\n { name: EVENT_AI_INPUT, data: { output: input.payload.output }, codecHeaders: h },\n perWrite,\n );\n }\n\n /**\n * Publish a client-side tool error on the `ai-input` wire. Targets the\n * assistant addressed by `input.codecMessageId`.\n * @param input - The tool-result-error input.\n * @param perWrite - Per-write overrides.\n */\n private async _publishToolResultError(\n input: ToolResultError<VercelToolResultErrorPayload>,\n perWrite?: WriteOptions,\n ): Promise<void> {\n const h = headerWriter().str('type', 'tool-result-error').str('toolCallId', input.payload.toolCallId).build();\n await this._core.publishDiscrete(\n { name: EVENT_AI_INPUT, data: { message: input.payload.message }, codecHeaders: h },\n perWrite,\n );\n }\n\n /**\n * Publish a client-side tool approval response on the `ai-input` wire.\n * Targets the assistant addressed by `input.codecMessageId`.\n * @param input - The approval-response input.\n * @param perWrite - Per-write overrides.\n */\n private async _publishToolApprovalResponse(\n input: ToolApprovalResponse<VercelToolApprovalResponsePayload>,\n perWrite?: WriteOptions,\n ): Promise<void> {\n const h = headerWriter()\n .str('type', 'tool-approval-response')\n .str('toolCallId', input.payload.toolCallId)\n .bool('approved', input.payload.approved)\n .str('reason', input.payload.reason)\n .build();\n await this._core.publishDiscrete({ name: EVENT_AI_INPUT, data: '', codecHeaders: h }, perWrite);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool output discrete payload builder (agent-side `ai-output` wire)\n// ---------------------------------------------------------------------------\n\nconst buildToolOutputPayload = (\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'tool-output-available' | 'tool-output-error' | 'tool-approval-request' | 'tool-output-denied' }\n >,\n): MessagePayload => {\n switch (chunk.type) {\n case 'tool-output-available': {\n const h = headerWriter()\n .str('type', 'tool-output-available')\n .str('toolCallId', chunk.toolCallId)\n .bool('dynamic', chunk.dynamic)\n .bool('providerExecuted', chunk.providerExecuted)\n .bool('preliminary', chunk.preliminary)\n .build();\n return { name: EVENT_AI_OUTPUT, data: { output: chunk.output }, codecHeaders: h };\n }\n case 'tool-output-error': {\n const h = headerWriter()\n .str('type', 'tool-output-error')\n .str('toolCallId', chunk.toolCallId)\n .bool('dynamic', chunk.dynamic)\n .bool('providerExecuted', chunk.providerExecuted)\n .build();\n return { name: EVENT_AI_OUTPUT, data: { errorText: chunk.errorText }, codecHeaders: h };\n }\n case 'tool-approval-request': {\n const h = headerWriter()\n .str('type', 'tool-approval-request')\n .str('toolCallId', chunk.toolCallId)\n .str('approvalId', chunk.approvalId)\n .build();\n return { name: EVENT_AI_OUTPUT, data: '', codecHeaders: h };\n }\n case 'tool-output-denied': {\n const h = headerWriter().str('type', 'tool-output-denied').str('toolCallId', chunk.toolCallId).build();\n return { name: EVENT_AI_OUTPUT, data: '', codecHeaders: h };\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// User-message per-part payload encoding\n// ---------------------------------------------------------------------------\n\nconst encodeMessagePayloads = (message: AI.UIMessage): MessagePayload[] => {\n const messageId = message.id;\n const payloads: MessagePayload[] = [];\n\n for (const part of message.parts) {\n switch (part.type) {\n case 'text': {\n payloads.push({\n name: EVENT_AI_INPUT,\n data: part.text,\n codecHeaders: headerWriter().str('type', 'text').str('messageId', messageId).build(),\n });\n break;\n }\n case 'file': {\n payloads.push({\n name: EVENT_AI_INPUT,\n data: part.url,\n codecHeaders: headerWriter()\n .str('type', 'file')\n .str('messageId', messageId)\n .str('mediaType', part.mediaType)\n .build(),\n });\n break;\n }\n default: {\n if (isDataUIPart(part)) {\n payloads.push({\n name: EVENT_AI_INPUT,\n data: part.data,\n codecHeaders: headerWriter().str('type', part.type).str('messageId', messageId).str('id', part.id).build(),\n });\n }\n break;\n }\n }\n }\n\n if (payloads.length === 0) {\n // Always emit at least one part so the decoder can reconstruct the codec-message-id and role from headers, even when the user-message carried no encodable parts.\n payloads.push({\n name: EVENT_AI_INPUT,\n data: '',\n codecHeaders: headerWriter().str('type', 'text').str('messageId', messageId).build(),\n });\n }\n\n return payloads;\n};\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Vercel AI SDK encoder that maps VercelInput / VercelOutput to\n * Ably channel operations via the encoder core.\n * @param writer - The channel writer to publish messages through.\n * @param options - Encoder configuration (clientId, extras, hooks, logger).\n * @returns An {@link Encoder} typed in both directions for the Vercel codec.\n */\nexport const createEncoder = (\n writer: ChannelWriter,\n options: EncoderCoreOptions = {},\n): Encoder<VercelInput, VercelOutput> => new DefaultUIMessageEncoder(writer, options);\n","/**\n * Shared tool part transition logic for the Vercel AI SDK codec.\n *\n * Keeps the tool output state transition logic in one place, reusable by the\n * Vercel codec reducer and any other callers.\n */\n\nimport type * as AI from 'ai';\n\nimport { stripUndefined } from '../../utils.js';\n\n// ---------------------------------------------------------------------------\n// Tool output chunk type guard\n// ---------------------------------------------------------------------------\n\n/** The set of UIMessageChunk types that represent tool output transitions. */\nexport type ToolOutputChunk = Extract<\n AI.UIMessageChunk,\n { type: 'tool-output-available' | 'tool-output-error' | 'tool-output-denied' | 'tool-approval-request' }\n>;\n\n/**\n * Whether a UIMessageChunk is a tool output transition event.\n * @param chunk - The chunk to test.\n * @returns True if the chunk is a tool output transition type.\n */\nexport const isToolOutputChunk = (chunk: AI.UIMessageChunk): chunk is ToolOutputChunk =>\n chunk.type === 'tool-output-available' ||\n chunk.type === 'tool-output-error' ||\n chunk.type === 'tool-output-denied' ||\n chunk.type === 'tool-approval-request';\n\n// ---------------------------------------------------------------------------\n// Tool base helper\n// ---------------------------------------------------------------------------\n\n/** Fields shared by all DynamicToolUIPart state variants. */\ninterface ToolBaseFields {\n type: 'dynamic-tool';\n toolName: string;\n toolCallId: string;\n title?: string;\n providerExecuted?: boolean;\n}\n\n/**\n * Extract the state-independent base fields for a DynamicToolUIPart.\n * Works with both chunks (tool-input-start, etc.) and existing parts.\n * @param source - Any object containing the required tool identity fields.\n * @param source.toolCallId - The tool call identifier.\n * @param source.toolName - The tool name.\n * @param source.title - Optional display title.\n * @param source.providerExecuted - Whether the provider executed the tool.\n * @returns Base fields shared across all DynamicToolUIPart state variants.\n */\nexport const toolBase = (source: {\n toolCallId: string;\n toolName: string;\n title?: string;\n providerExecuted?: boolean;\n}): ToolBaseFields =>\n stripUndefined({\n type: 'dynamic-tool' as const,\n toolCallId: source.toolCallId,\n toolName: source.toolName,\n title: source.title,\n providerExecuted: source.providerExecuted,\n });\n\n// ---------------------------------------------------------------------------\n// Tool part transition\n// ---------------------------------------------------------------------------\n\n/**\n * Transition a DynamicToolUIPart to a new state based on a tool output chunk.\n * Pure function — does not mutate the input part.\n * @param part - The existing tool part to transition.\n * @param chunk - The tool output chunk describing the transition.\n * @returns A new DynamicToolUIPart in the target state.\n */\nexport const transitionToolPart = (part: AI.DynamicToolUIPart, chunk: ToolOutputChunk): AI.DynamicToolUIPart => {\n const base = toolBase(part);\n\n switch (chunk.type) {\n case 'tool-output-available': {\n return stripUndefined({\n ...base,\n state: 'output-available' as const,\n input: part.input,\n output: chunk.output,\n preliminary: chunk.preliminary,\n });\n }\n\n case 'tool-output-error': {\n return {\n ...base,\n state: 'output-error',\n input: part.input,\n errorText: chunk.errorText,\n };\n }\n\n case 'tool-output-denied': {\n return {\n ...base,\n state: 'output-denied',\n input: part.input,\n approval: { id: '', approved: false },\n };\n }\n\n case 'tool-approval-request': {\n return {\n ...base,\n state: 'approval-requested',\n input: part.input,\n approval: { id: chunk.approvalId },\n };\n }\n }\n};\n","/**\n * Vercel AI SDK reducer.\n *\n * Pure `(init, fold)` over the `VercelInput | VercelOutput` union. Folds\n * input variants (user-message, tool-result, tool-result-error,\n * tool-approval-response) and `UIMessageChunk` outputs into a\n * VercelProjection holding `UIMessage[]` plus internal stream-tracker\n * state.\n *\n * The reducer is stateless: every fold is `(state, event, meta) → state'`,\n * with no instance state. Mutation in place is allowed — the projection\n * is single-owner.\n *\n * Idempotency is **per conflict key**, not stream-wide: when two events\n * compete for the same logical state (e.g. two `tool-output-available`\n * for the same `toolCallId`), the higher-serial one wins and the other\n * is dropped. Unrelated events arrive freely in any order. See\n * `_conflictKeyOf` for the per-variant key derivation.\n *\n * Client-published tool resolutions (`ToolResult`, `ToolResultError`,\n * `ToolApprovalResponse`) carry `codecMessageId` targeting the assistant\n * they amend; the reducer applies the resolution onto that assistant's\n * `dynamic-tool` part directly. If the assistant has not yet arrived in\n * the projection (out-of-order delivery), the resolution is buffered in\n * `pendingToolResolutions` and re-evaluated on each subsequent fold.\n */\n\nimport type * as AI from 'ai';\n\nimport type {\n CodecMessage,\n ReducerMeta,\n ToolApprovalResponse,\n ToolResult,\n ToolResultError,\n} from '../../core/codec/types.js';\nimport { stripUndefined } from '../../utils.js';\nimport type {\n VercelInput,\n VercelOutput,\n VercelToolApprovalResponsePayload,\n VercelToolResultErrorPayload,\n VercelToolResultPayload,\n} from './events.js';\nimport { toolBase, transitionToolPart } from './tool-transitions.js';\n\n// ---------------------------------------------------------------------------\n// Internal tracker state\n// ---------------------------------------------------------------------------\n\n/**\n * Tracks an in-progress tool part within a UIMessage. Text and reasoning\n * parts don't need this — we write to them directly via partIndex. Tool\n * parts need an extra `inputText` buffer because deltas arrive as raw\n * JSON fragments that must be accumulated before parsing.\n */\ninterface ToolPartTracker {\n /** Index in the message's parts array. */\n partIndex: number;\n /** Accumulated streaming input text (for JSON parsing on completion). */\n inputText: string;\n}\n\n/** Per-codecMessageId tracking state for in-progress streams within a UIMessage. */\ninterface MessageTrackers {\n /** Text stream id → partIndex. */\n text: Map<string, number>;\n /** Reasoning stream id → partIndex. */\n reasoning: Map<string, number>;\n /** Tool call id → tracker. */\n tools: Map<string, ToolPartTracker>;\n}\n\n// ---------------------------------------------------------------------------\n// Projection\n// ---------------------------------------------------------------------------\n\n/**\n * The per-Run state produced by the Vercel codec's reducer.\n *\n * The SDK reads only `messages` (via `Codec.getMessages`). The remaining\n * fields are internal to the reducer; they happen to live on the\n * projection because the projection is the only thing the reducer can\n * carry from fold to fold (it has no instance state).\n */\nexport interface VercelProjection {\n /**\n * UIMessages produced or modified in this Run, in publication order,\n * each paired with its codec-message-id. The reducer correlates strictly\n * on `codecMessageId`; `message.id` is preserved verbatim from the source\n * (the AI SDK stream's `start.messageId` for assistants, the caller's id\n * for user messages) and is never used as an identity key.\n */\n messages: CodecMessage<AI.UIMessage>[];\n /**\n * Per-conflict-key high-water-marks. Maps a codec-derived conflict key\n * (see `_conflictKeyOf`) to the highest `meta.serial` already folded for\n * that key. Events whose serial is `<=` the stored value are dropped as\n * duplicates of an already-incorporated operation. Events that have no\n * conflict key (additive content, lifecycle markers) are folded\n * unconditionally.\n */\n conflictSerials: Map<string, string>;\n /** Per-codecMessageId tracker state for streamed parts. Internal — do not access. */\n trackers: Map<string, MessageTrackers>;\n /**\n * Tool-resolution events that arrived before any assistant in this\n * projection had a matching `toolCallId`. Re-evaluated on every\n * subsequent fold so that an out-of-order tool output is folded as\n * soon as the corresponding assistant lands.\n */\n pendingToolResolutions: PendingToolResolution[];\n}\n\n/**\n * A buffered tool resolution waiting for its assistant message to arrive.\n * The reducer scans pending entries after every successful fold so an\n * out-of-order tool output is promoted as soon as the matching assistant\n * is added to the projection.\n */\ninterface PendingToolResolution {\n /** The codec-message-id of the assistant the resolution targets. */\n targetCodecMessageId: string;\n /** Tool call this resolution targets. */\n toolCallId: string;\n /** Serial of the wire message — used by the conflict-key check on promotion. */\n serial: string;\n /** Variant of the tool-resolution used to transition the assistant's tool part. */\n resolution:\n | { kind: 'tool-result'; output: unknown }\n | { kind: 'tool-result-error'; message: string }\n | { kind: 'tool-approval-response'; approved: boolean; reason?: string };\n}\n\n// ---------------------------------------------------------------------------\n// init\n// ---------------------------------------------------------------------------\n\n/**\n * Build an empty initial projection.\n * @returns A fresh VercelProjection with no messages and no tracker state.\n */\nexport const init = (): VercelProjection => ({\n messages: [],\n conflictSerials: new Map(),\n trackers: new Map(),\n pendingToolResolutions: [],\n});\n\n// ---------------------------------------------------------------------------\n// fold\n// ---------------------------------------------------------------------------\n\n/**\n * Fold one input or output event into the projection. Mutates and returns\n * `state`.\n *\n * Idempotency is per conflict key (see `_conflictKeyOf`): if the event has\n * a conflict key and the projection has already folded an event for that\n * key at a higher-or-equal serial, this call is a no-op. Events without a\n * conflict key (additive content, lifecycle markers) are folded\n * unconditionally. Orphan events (e.g. tool-output for an unknown\n * toolCallId) are dropped silently inside the per-variant fold helpers.\n * @param state - Projection to fold into (may be mutated in place).\n * @param event - Input or output event to fold.\n * @param meta - Transport-derived metadata (serial, optional messageId).\n * @returns The same projection reference, possibly mutated.\n */\nexport const fold = (\n state: VercelProjection,\n event: VercelInput | VercelOutput,\n meta: ReducerMeta,\n): VercelProjection => {\n if (meta.serial) {\n const key = _conflictKeyOf(event, meta);\n if (key !== undefined) {\n const seen = state.conflictSerials.get(key);\n if (seen !== undefined && meta.serial <= seen) {\n return state;\n }\n state.conflictSerials.set(key, meta.serial);\n }\n }\n\n if (_isInput(event)) {\n switch (event.kind) {\n case 'user-message': {\n _foldUserMessage(state, event.message, meta);\n break;\n }\n case 'regenerate': {\n // Regenerate input — wire-only signal. Carries no projection state;\n // the agent reads `target` / `parent` from the wire headers via\n // the input-event lookup path. No fold work to do here.\n break;\n }\n case 'tool-result': {\n _foldClientToolResult(state, event, meta);\n break;\n }\n case 'tool-result-error': {\n _foldClientToolResultError(state, event, meta);\n break;\n }\n case 'tool-approval-response': {\n _foldToolApprovalResponse(state, event, meta);\n break;\n }\n }\n } else {\n _foldChunk(state, event, meta);\n }\n\n // Re-evaluate pending tool resolutions in case the just-folded event\n // produced the assistant they were waiting on. Cheap when the list is\n // empty (the common case).\n if (state.pendingToolResolutions.length > 0) {\n _retryPendingResolutions(state);\n }\n\n return state;\n};\n\n/**\n * Narrow the union to TInput vs TOutput by the discriminator field name.\n * VercelInput variants carry `kind`; VercelOutput variants carry `type`.\n * @param event - The event to narrow.\n * @returns True when the event is a VercelInput, false for VercelOutput.\n */\nconst _isInput = (event: VercelInput | VercelOutput): event is VercelInput => 'kind' in event;\n\n// ---------------------------------------------------------------------------\n// Conflict-key derivation\n// ---------------------------------------------------------------------------\n\n/**\n * Derive a per-event conflict key, or `undefined` if the event doesn't\n * compete with any other event for shared state. Used by `fold` to scope\n * the high-water-mark check to genuine conflicts (e.g. two\n * `tool-output-available` for the same `toolCallId`) rather than to every\n * event in the stream.\n * @param event - The event being folded.\n * @param meta - Transport-derived metadata (used for events keyed by codec-message-id).\n * @returns The conflict key, or `undefined` if the event is additive / independent.\n */\nconst _conflictKeyOf = (event: VercelInput | VercelOutput, meta: ReducerMeta): string | undefined => {\n if (_isInput(event)) {\n switch (event.kind) {\n case 'user-message': {\n // Dedup re-publishes of the same user message by its wire\n // codec-message-id, never by the domain `message.id`. Without a\n // codec-message-id there is nothing to correlate on, so the fold\n // is left unconditional.\n return meta.messageId === undefined ? undefined : `user-msg:${meta.messageId}`;\n }\n case 'tool-approval-response': {\n return `tool-approval:${event.payload.toolCallId}`;\n }\n // Client tool results compete for the same final state of the tool\n // call (against agent-side `tool-output-available`/`tool-output-error`\n // chunks and against `tool-output-denied`/`tool-approval-request`).\n // Highest serial wins. Shares the `tool-output:` namespace with the\n // agent-side chunks below.\n case 'tool-result':\n case 'tool-result-error': {\n return `tool-output:${event.payload.toolCallId}`;\n }\n case 'regenerate': {\n return undefined;\n }\n }\n }\n\n switch (event.type) {\n // Tool-input state machine, keyed by toolCallId.\n case 'tool-input-start':\n case 'tool-input-available':\n case 'tool-input-error': {\n return `${event.type}:${event.toolCallId}`;\n }\n\n // All \"tool-output-ish\" output variants compete for the same final\n // state of the tool call. Shares the `tool-output:` namespace with\n // the client-published input variants above.\n case 'tool-output-available':\n case 'tool-output-error':\n case 'tool-output-denied':\n case 'tool-approval-request': {\n return `tool-output:${event.toolCallId}`;\n }\n\n // Per-stream start/end markers: duplicates would create phantom parts\n // or wipe accumulated text. Keyed by (codec-message-id, stream-id).\n case 'text-start':\n case 'text-end':\n case 'reasoning-start':\n case 'reasoning-end': {\n return `${event.type}:${meta.messageId ?? ''}:${event.id}`;\n }\n\n // Message-level markers, keyed by codec-message-id.\n case 'finish':\n case 'message-metadata': {\n return `${event.type}:${meta.messageId ?? ''}`;\n }\n\n // Purely additive or independent — never dedup:\n // text-delta / reasoning-delta / tool-input-delta (additive content)\n // start / start-step / finish-step / abort / error (lifecycle)\n // file / source-url / source-document (independent attachments)\n // data-* (opaque to the reducer)\n default: {\n return undefined;\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Input folds\n// ---------------------------------------------------------------------------\n\nconst _foldUserMessage = (state: VercelProjection, message: AI.UIMessage, meta: ReducerMeta): VercelProjection => {\n // Correlate the projection entry on the wire codec-message-id; the\n // caller-supplied `message.id` is preserved verbatim and surfaced to the\n // application unchanged. Without a codec-message-id the message has no\n // identity to key on, so it is appended as a fresh entry.\n const codecMessageId = meta.messageId;\n if (codecMessageId === undefined) {\n state.messages.push({ codecMessageId: message.id, message });\n return state;\n }\n const existingIdx = state.messages.findIndex((e) => e.codecMessageId === codecMessageId);\n if (existingIdx === -1) {\n state.messages.push({ codecMessageId, message });\n } else {\n state.messages[existingIdx] = { codecMessageId, message };\n }\n return state;\n};\n\n/**\n * Fold a client-published `ToolResult`. The input carries\n * `codecMessageId` pointing at the assistant whose `dynamic-tool` part\n * holds the matching `toolCallId`. If the assistant and its matching\n * `dynamic-tool` part are both present, fold directly; otherwise pend\n * until that tool part arrives.\n * @param state - Projection to fold into.\n * @param event - The tool-result input (codecMessageId + domain payload).\n * @param meta - Transport-derived metadata.\n * @returns The same projection reference.\n */\nconst _foldClientToolResult = (\n state: VercelProjection,\n event: ToolResult<VercelToolResultPayload>,\n meta: ReducerMeta,\n): VercelProjection => {\n const { toolCallId, output } = event.payload;\n const owner = _findOwner(state, event.codecMessageId, toolCallId);\n if (owner) {\n owner.message.parts[owner.tracker.partIndex] = transitionToolPart(owner.part, {\n type: 'tool-output-available',\n toolCallId,\n output,\n });\n return state;\n }\n\n state.pendingToolResolutions.push({\n targetCodecMessageId: event.codecMessageId,\n toolCallId,\n serial: meta.serial,\n resolution: { kind: 'tool-result', output },\n });\n return state;\n};\n\n/**\n * Fold a client-published `ToolResultError`. Mirrors\n * {@link _foldClientToolResult} but with the error transition.\n * @param state - Projection to fold into.\n * @param event - The tool-result-error input (codecMessageId + domain payload).\n * @param meta - Transport-derived metadata.\n * @returns The same projection reference.\n */\nconst _foldClientToolResultError = (\n state: VercelProjection,\n event: ToolResultError<VercelToolResultErrorPayload>,\n meta: ReducerMeta,\n): VercelProjection => {\n const { toolCallId, message } = event.payload;\n const owner = _findOwner(state, event.codecMessageId, toolCallId);\n if (owner) {\n owner.message.parts[owner.tracker.partIndex] = transitionToolPart(owner.part, {\n type: 'tool-output-error',\n toolCallId,\n errorText: message,\n });\n return state;\n }\n\n state.pendingToolResolutions.push({\n targetCodecMessageId: event.codecMessageId,\n toolCallId,\n serial: meta.serial,\n resolution: { kind: 'tool-result-error', message },\n });\n return state;\n};\n\n/**\n * Fold a client-published `ToolApprovalResponse`. The input carries\n * `codecMessageId` pointing at the assistant whose `dynamic-tool` part\n * holds the matching `toolCallId`. Approval → `approval-responded`;\n * denial → `output-denied` via {@link transitionToolPart}.\n * @param state - Projection to fold into.\n * @param event - The approval-response input.\n * @param meta - Transport-derived metadata.\n * @returns The same projection reference.\n */\nconst _foldToolApprovalResponse = (\n state: VercelProjection,\n event: ToolApprovalResponse<VercelToolApprovalResponsePayload>,\n meta: ReducerMeta,\n): VercelProjection => {\n const { toolCallId, approved, reason } = event.payload;\n const owner = _findOwner(state, event.codecMessageId, toolCallId);\n if (owner) {\n owner.message.parts[owner.tracker.partIndex] = _approvalTransition(owner.part, approved, reason);\n return state;\n }\n\n state.pendingToolResolutions.push({\n targetCodecMessageId: event.codecMessageId,\n toolCallId,\n serial: meta.serial,\n resolution: {\n kind: 'tool-approval-response',\n approved,\n ...(reason === undefined ? {} : { reason }),\n },\n });\n return state;\n};\n\ninterface OwnerLookup {\n message: AI.UIMessage;\n tracker: ToolPartTracker;\n part: AI.DynamicToolUIPart;\n}\n\nconst _findOwner = (state: VercelProjection, codecMessageId: string, toolCallId: string): OwnerLookup | undefined => {\n const entry = state.messages.find((e) => e.codecMessageId === codecMessageId);\n if (!entry) return undefined;\n const trackers = _ensureTrackers(state, codecMessageId);\n const found = _getToolPart(entry.message, trackers, toolCallId);\n if (!found) return undefined;\n return { message: entry.message, tracker: found.tracker, part: found.part };\n};\n\n/**\n * Locate the `dynamic-tool` part for a `toolCallId` anywhere in the projection.\n * Agent-emitted second-pass tool outputs (after an approved tool runs) are\n * stamped with a fresh codec-message-id that differs from the assistant holding\n * the tool call, so they can't be found via `meta.messageId` — they fold onto\n * whichever message holds the matching tool call (created in the first pass or\n * by an approval response).\n * @param state - Projection to scan.\n * @param toolCallId - The tool call to locate.\n * @returns The owning message, tracker, and part, or `undefined` if absent.\n */\nconst _findToolPartOwner = (state: VercelProjection, toolCallId: string): OwnerLookup | undefined => {\n for (const entry of state.messages) {\n const trackers = state.trackers.get(entry.codecMessageId);\n if (!trackers) continue;\n const found = _getToolPart(entry.message, trackers, toolCallId);\n if (found) return { message: entry.message, tracker: found.tracker, part: found.part };\n }\n return undefined;\n};\n\n/**\n * Build the next `dynamic-tool` part shape for an approval response.\n *\n * For `approved=true`, transition to `approval-responded` so the AI SDK's\n * multi-step loop will auto-run the tool on the next step.\n * `transitionToolPart` has no shape for this transition, so we synthesize\n * the part directly.\n *\n * For `approved=false`, delegate to `transitionToolPart` with a synthetic\n * `tool-output-denied` chunk so denial mirrors the chunk-driven path.\n * @param part - The existing `dynamic-tool` part being transitioned.\n * @param approved - Whether the user approved the tool execution.\n * @param reason - Optional human-readable reason.\n * @returns The replacement `dynamic-tool` part.\n */\nconst _approvalTransition = (\n part: AI.DynamicToolUIPart,\n approved: boolean,\n reason: string | undefined,\n): AI.DynamicToolUIPart => {\n if (approved) {\n return {\n ...toolBase(part),\n state: 'approval-responded',\n input: 'input' in part ? part.input : undefined,\n approval: {\n id: 'approval' in part && part.approval ? part.approval.id : '',\n approved: true,\n ...(reason === undefined ? {} : { reason }),\n },\n };\n }\n return transitionToolPart(part, {\n type: 'tool-output-denied',\n toolCallId: part.toolCallId,\n ...(reason === undefined ? {} : { reason }),\n });\n};\n\n/**\n * Re-attempt every pending tool resolution against the current projection.\n * Successfully promoted entries are removed from the pending list. Cheap:\n * bounded by the number of pending entries.\n * @param state - Projection to walk and mutate.\n */\nconst _retryPendingResolutions = (state: VercelProjection): void => {\n const next: PendingToolResolution[] = [];\n for (const pending of state.pendingToolResolutions) {\n const owner = _findOwner(state, pending.targetCodecMessageId, pending.toolCallId);\n if (!owner) {\n next.push(pending);\n continue;\n }\n switch (pending.resolution.kind) {\n case 'tool-result': {\n owner.message.parts[owner.tracker.partIndex] = transitionToolPart(owner.part, {\n type: 'tool-output-available',\n toolCallId: pending.toolCallId,\n output: pending.resolution.output,\n });\n break;\n }\n case 'tool-result-error': {\n owner.message.parts[owner.tracker.partIndex] = transitionToolPart(owner.part, {\n type: 'tool-output-error',\n toolCallId: pending.toolCallId,\n errorText: pending.resolution.message,\n });\n break;\n }\n case 'tool-approval-response': {\n owner.message.parts[owner.tracker.partIndex] = _approvalTransition(\n owner.part,\n pending.resolution.approved,\n pending.resolution.reason,\n );\n break;\n }\n }\n }\n state.pendingToolResolutions = next;\n};\n\n// ---------------------------------------------------------------------------\n// UIMessageChunk fold\n// ---------------------------------------------------------------------------\n\nconst _foldChunk = (state: VercelProjection, chunk: VercelOutput, meta: ReducerMeta): VercelProjection => {\n const messageId = meta.messageId;\n if (messageId === undefined) {\n // Without a target codec-message-id, a chunk has nowhere to land. Drop.\n return state;\n }\n\n switch (chunk.type) {\n case 'start':\n case 'start-step':\n case 'finish-step':\n case 'finish':\n case 'abort':\n case 'error':\n case 'message-metadata': {\n return _foldLifecycle(state, chunk, messageId);\n }\n\n case 'text-start':\n case 'text-delta':\n case 'text-end':\n case 'reasoning-start':\n case 'reasoning-delta':\n case 'reasoning-end': {\n return _foldTextOrReasoning(state, chunk, messageId);\n }\n\n case 'tool-input-start':\n case 'tool-input-delta':\n case 'tool-input-available':\n case 'tool-input-error': {\n return _foldToolInput(state, chunk, messageId);\n }\n\n case 'tool-output-available':\n case 'tool-output-error':\n case 'tool-output-denied':\n case 'tool-approval-request': {\n return _foldToolOutput(state, chunk, messageId);\n }\n\n case 'file':\n case 'source-url':\n case 'source-document': {\n return _foldContentPart(state, chunk, messageId);\n }\n\n default: {\n if (chunk.type.startsWith('data-')) {\n return _foldDataPart(state, chunk, messageId);\n }\n return state;\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Message + tracker helpers\n// ---------------------------------------------------------------------------\n\nconst _ensureMessage = (state: VercelProjection, codecMessageId: string): AI.UIMessage => {\n let entry = state.messages.find((e) => e.codecMessageId === codecMessageId);\n if (!entry) {\n // No source id seen yet — seed the domain `message.id` with the\n // codec-message-id as a fallback. The `start` chunk overwrites it with\n // the stream's `messageId` when the stream provides one.\n entry = { codecMessageId, message: { id: codecMessageId, role: 'assistant', parts: [] } };\n state.messages.push(entry);\n }\n return entry.message;\n};\n\nconst _ensureTrackers = (state: VercelProjection, messageId: string): MessageTrackers => {\n let trackers = state.trackers.get(messageId);\n if (!trackers) {\n trackers = { text: new Map(), reasoning: new Map(), tools: new Map() };\n state.trackers.set(messageId, trackers);\n }\n return trackers;\n};\n\nconst _getToolPart = (\n message: AI.UIMessage,\n trackers: MessageTrackers,\n toolCallId: string,\n): { tracker: ToolPartTracker; part: AI.DynamicToolUIPart } | undefined => {\n const tracker = trackers.tools.get(toolCallId);\n if (!tracker) return undefined;\n const part = message.parts[tracker.partIndex];\n if (part?.type !== 'dynamic-tool') return undefined;\n return { tracker, part };\n};\n\n// ---------------------------------------------------------------------------\n// Lifecycle events\n// ---------------------------------------------------------------------------\n\nconst _foldLifecycle = (\n state: VercelProjection,\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'start' | 'start-step' | 'finish-step' | 'finish' | 'abort' | 'error' | 'message-metadata' }\n >,\n messageId: string,\n): VercelProjection => {\n switch (chunk.type) {\n case 'start': {\n // The projection entry is keyed on the wire codec-message-id\n // (`messageId`); every subsequent chunk for this message correlates on\n // that, independent of `message.id`. So we faithfully reproduce the\n // stream's own `messageId` on the reconstructed `UIMessage.id` (the\n // value surfaced to the application) without risk of orphaning later\n // chunks. When the stream omits it, the codec-message-id seeded by\n // `_ensureMessage` stands as the fallback id.\n const message = _ensureMessage(state, messageId);\n if (chunk.messageId !== undefined) message.id = chunk.messageId;\n if (chunk.messageMetadata !== undefined) message.metadata = chunk.messageMetadata;\n return state;\n }\n case 'start-step': {\n const message = _ensureMessage(state, messageId);\n message.parts.push({ type: 'step-start' });\n return state;\n }\n case 'finish-step': {\n // Reset text/reasoning stream trackers so a follow-up step can start\n // new parts with potentially-reused stream ids.\n const trackers = state.trackers.get(messageId);\n if (trackers) {\n trackers.text.clear();\n trackers.reasoning.clear();\n }\n return state;\n }\n case 'finish': {\n const message = state.messages.find((e) => e.codecMessageId === messageId)?.message;\n if (message && chunk.messageMetadata !== undefined) {\n message.metadata = chunk.messageMetadata;\n }\n // Tracker state retained — late events still resolvable; cleanup happens at Run end.\n return state;\n }\n case 'abort':\n case 'error': {\n // No state mutation — run termination is observed via the wire run-end\n // event, not the projection.\n return state;\n }\n case 'message-metadata': {\n const message = state.messages.find((e) => e.codecMessageId === messageId)?.message;\n if (message && chunk.messageMetadata !== undefined) {\n message.metadata = chunk.messageMetadata;\n }\n return state;\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Text and reasoning streaming\n// ---------------------------------------------------------------------------\n\nconst _foldTextOrReasoning = (\n state: VercelProjection,\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'text-start' | 'text-delta' | 'text-end' | 'reasoning-start' | 'reasoning-delta' | 'reasoning-end' }\n >,\n messageId: string,\n): VercelProjection => {\n const message = _ensureMessage(state, messageId);\n const trackers = _ensureTrackers(state, messageId);\n\n const isText = chunk.type.startsWith('text-');\n const partType = isText ? 'text' : 'reasoning';\n const activeMap = isText ? trackers.text : trackers.reasoning;\n\n switch (chunk.type) {\n case 'text-start':\n case 'reasoning-start': {\n activeMap.set(chunk.id, message.parts.length);\n message.parts.push({ type: partType, text: '' });\n return state;\n }\n case 'text-delta':\n case 'reasoning-delta': {\n const idx = activeMap.get(chunk.id);\n if (idx === undefined) return state;\n const part = message.parts[idx];\n if (part?.type === partType) {\n part.text += chunk.delta;\n }\n return state;\n }\n case 'text-end':\n case 'reasoning-end': {\n activeMap.delete(chunk.id);\n return state;\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Tool input streaming\n// ---------------------------------------------------------------------------\n\nconst _foldToolInput = (\n state: VercelProjection,\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'tool-input-start' | 'tool-input-delta' | 'tool-input-available' | 'tool-input-error' }\n >,\n messageId: string,\n): VercelProjection => {\n const message = _ensureMessage(state, messageId);\n const trackers = _ensureTrackers(state, messageId);\n\n switch (chunk.type) {\n case 'tool-input-start': {\n const partIndex = message.parts.length;\n message.parts.push({ ...toolBase(chunk), state: 'input-streaming', input: undefined });\n trackers.tools.set(chunk.toolCallId, { partIndex, inputText: '' });\n return state;\n }\n case 'tool-input-delta': {\n const tracker = trackers.tools.get(chunk.toolCallId);\n if (!tracker) return state;\n tracker.inputText += chunk.inputTextDelta;\n\n let parsedInput: unknown;\n try {\n // CAST: JSON.parse returns any; unknown is the safe trust-boundary type.\n parsedInput = JSON.parse(tracker.inputText) as unknown;\n } catch {\n parsedInput = undefined;\n }\n\n const found = _getToolPart(message, trackers, chunk.toolCallId);\n if (!found) return state;\n message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'input-streaming',\n input: parsedInput,\n };\n return state;\n }\n case 'tool-input-available': {\n const found = _getToolPart(message, trackers, chunk.toolCallId);\n if (!found) return state;\n message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'input-available',\n input: chunk.input,\n };\n return state;\n }\n case 'tool-input-error': {\n const found = _getToolPart(message, trackers, chunk.toolCallId);\n if (found) {\n message.parts[found.tracker.partIndex] = {\n ...toolBase(found.part),\n state: 'output-error',\n input: chunk.input,\n errorText: chunk.errorText,\n };\n } else {\n const partIndex = message.parts.length;\n message.parts.push({\n ...toolBase(chunk),\n state: 'output-error',\n input: chunk.input,\n errorText: chunk.errorText,\n });\n trackers.tools.set(chunk.toolCallId, { partIndex, inputText: '' });\n }\n return state;\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Tool output transitions (agent-published chunks)\n// ---------------------------------------------------------------------------\n\nconst _foldToolOutput = (\n state: VercelProjection,\n chunk: Extract<\n AI.UIMessageChunk,\n { type: 'tool-output-available' | 'tool-output-error' | 'tool-output-denied' | 'tool-approval-request' }\n >,\n messageId: string,\n): VercelProjection => {\n // `tool-output-available` / `tool-output-error` after an approved tool runs\n // are emitted by streamText's continuation pass under a fresh\n // codec-message-id that differs from the assistant holding the tool call.\n // Resolve the owning part by toolCallId across the whole projection so the\n // output folds onto the original message. Deliberately do NOT materialise\n // `messageId` first — that would leave a phantom empty message behind the\n // fresh id. Drop on miss: a tool output with no matching tool call has no\n // anchor to attach to.\n if (chunk.type === 'tool-output-available' || chunk.type === 'tool-output-error') {\n const owner = _findToolPartOwner(state, chunk.toolCallId);\n if (!owner) return state;\n owner.message.parts[owner.tracker.partIndex] = transitionToolPart(owner.part, chunk);\n return state;\n }\n\n // `tool-approval-request` (first pass) creates the part on the run's own\n // message; `tool-output-denied` transitions that same part. Both key on the\n // stamped messageId.\n const message = _ensureMessage(state, messageId);\n const trackers = _ensureTrackers(state, messageId);\n\n const found = _getToolPart(message, trackers, chunk.toolCallId);\n if (!found) return state;\n\n message.parts[found.tracker.partIndex] = transitionToolPart(found.part, chunk);\n return state;\n};\n\n// ---------------------------------------------------------------------------\n// File / source content parts\n// ---------------------------------------------------------------------------\n\nconst _foldContentPart = (\n state: VercelProjection,\n chunk: Extract<AI.UIMessageChunk, { type: 'file' | 'source-url' | 'source-document' }>,\n messageId: string,\n): VercelProjection => {\n const message = _ensureMessage(state, messageId);\n\n switch (chunk.type) {\n case 'file': {\n message.parts.push({ type: 'file', mediaType: chunk.mediaType, url: chunk.url });\n return state;\n }\n case 'source-url': {\n message.parts.push(\n stripUndefined({\n type: 'source-url' as const,\n sourceId: chunk.sourceId,\n url: chunk.url,\n title: chunk.title,\n }),\n );\n return state;\n }\n case 'source-document': {\n message.parts.push(\n stripUndefined({\n type: 'source-document' as const,\n sourceId: chunk.sourceId,\n mediaType: chunk.mediaType,\n title: chunk.title,\n filename: chunk.filename,\n }),\n );\n return state;\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// data-* parts\n// ---------------------------------------------------------------------------\n\nconst _foldDataPart = (\n state: VercelProjection,\n chunk: Extract<AI.UIMessageChunk, { type: `data-${string}` }>,\n messageId: string,\n): VercelProjection => {\n if (chunk.transient) return state;\n\n const message = _ensureMessage(state, messageId);\n\n // CAST: chunk.type is `data-${string}` which satisfies DataUIPart, but\n // TypeScript cannot verify the template literal matches a specific\n // UIMessagePart variant at the type level.\n const dataPart = stripUndefined({\n type: chunk.type,\n id: chunk.id,\n data: chunk.data,\n }) as AI.UIMessage['parts'][number];\n\n if (chunk.id !== undefined) {\n const idx = message.parts.findIndex((p) => p.type === chunk.type && 'id' in p && p.id === chunk.id);\n if (idx !== -1) {\n message.parts[idx] = dataPart;\n return state;\n }\n }\n\n message.parts.push(dataPart);\n return state;\n};\n\n// ---------------------------------------------------------------------------\n// getMessages\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the UIMessage list from a projection, each paired with its\n * codec-message-id. Client-published tool resolutions amend existing\n * assistants in place via `kind: 'tool-result'` etc. — they never\n * materialise as their own UIMessage in the projection, so no filtering is\n * needed here.\n * @param projection - Projection produced by `init` + repeated `fold` calls.\n * @returns The visible messages with their codec-message-ids, in publication order.\n */\nexport const getMessages = (projection: VercelProjection): CodecMessage<AI.UIMessage>[] => projection.messages;\n","/**\n * Vercel AI SDK codec — implements\n * `Codec<VercelInput, VercelOutput, VercelProjection, UIMessage>`.\n *\n * The codec is the reducer (extends `Reducer<VercelInput | VercelOutput,\n * VercelProjection>`) plus encoder/decoder factories and `getMessages`\n * for Tree population.\n *\n * ```ts\n * import { UIMessageCodec } from '@ably/ai-transport/vercel';\n *\n * const encoder = UIMessageCodec.createEncoder(writer, options);\n * const decoder = UIMessageCodec.createDecoder();\n * const projection = UIMessageCodec.init();\n * ```\n */\n\nimport type * as AI from 'ai';\n\nimport type { Codec } from '../../core/codec/types.js';\nimport { createDecoder } from './decoder.js';\nimport { createEncoder } from './encoder.js';\nimport type {\n VercelInput,\n VercelOutput,\n VercelToolApprovalResponsePayload,\n VercelToolResultErrorPayload,\n VercelToolResultPayload,\n} from './events.js';\nimport { fold, getMessages, init, type VercelProjection } from './reducer.js';\n\n/**\n * Vercel AI SDK codec implementing\n * `Codec<VercelInput, VercelOutput, VercelProjection, UIMessage>`.\n *\n * Folds `VercelInput`s and `VercelOutput`s into a `VercelProjection`\n * carrying `UIMessage[]`. Encoder and decoder factories handle the wire\n * mapping for both directions.\n */\nconst uiMessageCodecImpl = {\n // Internal field - picked up by registerAgent via AdapterTagHolder cast. Spec: AIT-CT1a3, AIT-ST1a3.\n adapterTag: 'vercel-ai-sdk-ui-message' as const,\n init,\n fold,\n createEncoder,\n createDecoder,\n getMessages,\n createUserMessage: (message: AI.UIMessage): VercelInput => ({ kind: 'user-message', message }),\n createRegenerate: (target: string, parent: string): VercelInput => ({\n kind: 'regenerate',\n target,\n parent,\n }),\n createToolResult: (codecMessageId: string, payload: VercelToolResultPayload): VercelInput => ({\n kind: 'tool-result',\n codecMessageId,\n payload,\n }),\n createToolResultError: (codecMessageId: string, payload: VercelToolResultErrorPayload): VercelInput => ({\n kind: 'tool-result-error',\n codecMessageId,\n payload,\n }),\n createToolApprovalResponse: (codecMessageId: string, payload: VercelToolApprovalResponsePayload): VercelInput => ({\n kind: 'tool-approval-response',\n codecMessageId,\n payload,\n }),\n};\n\n// Validate Codec conformance via `satisfies` on the variable (no excess-property\n// check, so the internal `adapterTag` is permitted) while keeping the concrete\n// type so the codec-specific factories (createToolResult, etc.) stay callable.\nexport const UIMessageCodec = uiMessageCodecImpl satisfies Codec<\n VercelInput,\n VercelOutput,\n VercelProjection,\n AI.UIMessage\n>;\n\nexport type { VercelInput, VercelOutput } from './events.js';\nexport { type VercelProjection } from './reducer.js';\n","/**\n * Type-safe EventEmitter wrapping Ably's internal EventEmitter.\n *\n * Takes a single `EventsMap` type parameter — an interface mapping event names\n * to payload types — rather than Ably's three type parameters. Adapted from\n * the ably-chat-js SDK.\n *\n * ```ts\n * interface MyEvents {\n * reaction: { emoji: string };\n * status: { online: boolean };\n * }\n *\n * const emitter = new EventEmitter<MyEvents>(logger);\n * emitter.on('reaction', (event) => console.log(event.emoji));\n * emitter.emit('reaction', { emoji: '👍' });\n * ```\n */\n\nimport * as Ably from 'ably';\n\nimport type { Logger } from './logger.js';\n\n/** Callback receiving a union of all possible event payloads. */\ntype Callback<EventsMap> = (arg: EventsMap[keyof EventsMap]) => void;\n\n/** Callback receiving the payload for a single event type. */\ntype CallbackSingle<K> = (arg: K) => void;\n\n/**\n * Type-safe interface for the Ably EventEmitter, parameterized by an EventsMap\n * that maps event names to their payload types.\n */\ninterface InterfaceEventEmitter<EventsMap> extends Ably.EventEmitter<Callback<EventsMap>, void, keyof EventsMap> {\n /** Emit an event with a type-safe payload. Payload is optional for `undefined`-typed events. */\n emit<K extends keyof EventsMap>(\n event: K,\n ...args: EventsMap[K] extends undefined ? [EventsMap[K]?] : [EventsMap[K]]\n ): void;\n\n /** Subscribe to a single event with a typed callback. */\n on<K extends keyof EventsMap>(event: K, callback: CallbackSingle<EventsMap[K]>): void;\n /** Subscribe to two events with a union-typed callback. */\n on<K1 extends keyof EventsMap, K2 extends keyof EventsMap>(\n events: [K1, K2],\n callback: CallbackSingle<EventsMap[K1] | EventsMap[K2]>,\n ): void;\n /** Subscribe to three events with a union-typed callback. */\n on<K1 extends keyof EventsMap, K2 extends keyof EventsMap, K3 extends keyof EventsMap>(\n events: [K1, K2, K3],\n callback: CallbackSingle<EventsMap[K1] | EventsMap[K2] | EventsMap[K3]>,\n ): void;\n /** Subscribe to an array of events. */\n on(events: (keyof EventsMap)[], callback: Callback<EventsMap>): void;\n /** Subscribe to all events. */\n on(callback: Callback<EventsMap>): void;\n\n /** Unsubscribe a callback from a specific event. */\n off<K extends keyof EventsMap>(event: K, listener: CallbackSingle<EventsMap[K]>): void;\n /** Unsubscribe a callback from all events, or remove all listeners if no callback provided. */\n off(listener?: Callback<EventsMap>): void;\n}\n\n/**\n * Bridge from our {@link Logger} to the Ably EventEmitter's internal logger\n * contract. Ably's EventEmitter calls `logger.logAction(level, action, message)`\n * when a listener throws — we route that to our Logger's `error` method.\n * @param logger - The application logger to delegate to.\n * @returns An object satisfying the Ably EventEmitter's logger interface.\n */\nconst toAblyLogger = (logger: Logger): unknown => ({\n logAction: (_level: number, action: string, message?: string) => {\n logger.error(action, { detail: message });\n },\n shouldLog: () => true,\n});\n\n// CAST: Access Ably's internal EventEmitter constructor. Not publicly exported\n// but available to other Ably SDKs. Ably always catches listener exceptions\n// internally; the logger parameter ensures those caught exceptions are logged\n// rather than silently swallowed.\nconst InternalEventEmitter: new <EventsMap>(logger: unknown) => InterfaceEventEmitter<EventsMap> = (\n Ably.Realtime as unknown as { EventEmitter: new <EventsMap>(logger: unknown) => InterfaceEventEmitter<EventsMap> }\n).EventEmitter;\n\n/**\n * Type-safe EventEmitter based on Ably's internal EventEmitter.\n *\n * Provides the same semantics as {@link Ably.EventEmitter} (error isolation\n * between listeners, synchronous dispatch) but with a single `EventsMap` type\n * parameter for ergonomic type safety.\n *\n * Requires a {@link Logger} so that listener exceptions are routed through\n * the application's logging infrastructure rather than silently swallowed.\n */\nexport class EventEmitter<EventsMap> extends InternalEventEmitter<EventsMap> {\n /**\n * Create a new EventEmitter.\n * @param logger - Application logger. Listener exceptions are logged at error level.\n */\n constructor(logger: Logger) {\n super(toAblyLogger(logger));\n }\n}\n","import * as Ably from 'ably';\n\nimport { ErrorCode } from './errors.js';\n\n/**\n * Structured logger with leveled output and hierarchical context.\n * Implementations filter messages by level and delegate to a {@link LogHandler}.\n */\nexport interface Logger {\n /**\n * Log a message at the trace level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n trace(message: string, context?: LogContext): void;\n\n /**\n * Log a message at the debug level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log a message at the info level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a message at the warn level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log a message at the error level.\n * @param message The message to log.\n * @param context The context of the log message as key-value pairs.\n */\n error(message: string, context?: LogContext): void;\n\n /**\n * Creates a new logger with a context that will be merged with any context provided to individual log calls.\n * The context will be overridden by any matching keys in the individual log call's context.\n * @param context The context to use for all log calls.\n * @returns A new logger instance with the context.\n */\n withContext(context: LogContext): Logger;\n}\n\n/**\n * Represents the different levels of logging that can be used.\n */\nexport enum LogLevel {\n /**\n * Something routine and expected has occurred. This level will provide logs for the vast majority of operations\n * and function calls.\n */\n Trace = 'trace',\n\n /**\n * Development information, messages that are useful when trying to debug library behavior,\n * but superfluous to normal operation.\n */\n Debug = 'debug',\n\n /**\n * Informational messages. Operationally significant to the library but not out of the ordinary.\n */\n Info = 'info',\n\n /**\n * Anything that is not immediately an error, but could cause unexpected behavior in the future. For example,\n * passing an invalid value to an option. Indicates that some action should be taken to prevent future errors.\n */\n Warn = 'warn',\n\n /**\n * A given operation has failed and cannot be automatically recovered. The error may threaten the continuity\n * of operation.\n */\n Error = 'error',\n\n /**\n * No logging will be performed.\n */\n Silent = 'silent',\n}\n\n/**\n * Represents the context of a log message.\n * It is an object of key-value pairs that can be used to provide additional context to a log message.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type LogContext = Record<string, any>;\n\n/**\n * A function that can be used to handle log messages.\n * @param message The message to log.\n * @param level The log level of the message.\n * @param context The context of the log message as key-value pairs.\n */\nexport type LogHandler = (message: string, level: LogLevel, context?: LogContext) => void;\n\n/**\n * A simple console logger that logs messages to the console.\n * @param message The message to log.\n * @param level The log level of the message.\n * @param context - The context of the log message as key-value pairs.\n */\nexport const consoleLogger = (message: string, level: LogLevel, context?: LogContext) => {\n const contextString = context ? `, context: ${JSON.stringify(context)}` : '';\n const formattedMessage = `[${new Date().toISOString()}] ${level.valueOf().toUpperCase()} ably-ai-transport: ${message}${contextString}`;\n\n switch (level) {\n case LogLevel.Trace:\n case LogLevel.Debug: {\n console.log(formattedMessage);\n break;\n }\n case LogLevel.Info: {\n console.info(formattedMessage);\n break;\n }\n case LogLevel.Warn: {\n console.warn(formattedMessage);\n break;\n }\n case LogLevel.Error: {\n console.error(formattedMessage);\n break;\n }\n case LogLevel.Silent: {\n break;\n }\n }\n};\n\n/**\n * Options for creating a logger.\n */\nexport interface LoggerOptions {\n /**\n * The handler that receives formatted log messages. Defaults to {@link consoleLogger} when omitted.\n */\n logHandler?: LogHandler;\n /**\n * The minimum level to emit; messages below this level are suppressed. Must be a valid {@link LogLevel}, otherwise logger creation throws.\n */\n logLevel: LogLevel;\n}\n\n/**\n * Creates a {@link Logger} from the given options.\n * @param options The handler and minimum level for the logger.\n * @returns A logger that filters by level and delegates to the handler.\n * @throws {@link Ably.ErrorInfo} with {@link ErrorCode.InvalidArgument} if `options.logLevel` is not a recognised {@link LogLevel}.\n */\nexport const makeLogger = (options: LoggerOptions): Logger => {\n const logHandler = options.logHandler ?? consoleLogger;\n\n return new DefaultLogger(logHandler, options.logLevel);\n};\n\n/**\n * A convenient list of log levels as numbers that can be used for easier comparison.\n */\nenum LogLevelNumber {\n Trace = 0,\n Debug = 1,\n Info = 2,\n Warn = 3,\n Error = 4,\n Silent = 5,\n}\n\n/**\n * A mapping of log levels to their numeric equivalents.\n */\nconst logLevelNumberMap = new Map<LogLevel, LogLevelNumber>([\n [LogLevel.Trace, LogLevelNumber.Trace],\n [LogLevel.Debug, LogLevelNumber.Debug],\n [LogLevel.Info, LogLevelNumber.Info],\n [LogLevel.Warn, LogLevelNumber.Warn],\n [LogLevel.Error, LogLevelNumber.Error],\n [LogLevel.Silent, LogLevelNumber.Silent],\n]);\n\n/**\n * A default logger implementation.\n */\nclass DefaultLogger implements Logger {\n private readonly _handler: LogHandler;\n private readonly _levelNumber: LogLevelNumber;\n private readonly _context?: LogContext;\n\n constructor(handler: LogHandler, level: LogLevel, context?: LogContext) {\n this._handler = handler;\n this._context = context;\n\n const levelNumber = logLevelNumberMap.get(level);\n if (levelNumber === undefined) {\n throw new Ably.ErrorInfo(`unable to create logger; invalid log level: ${level}`, ErrorCode.InvalidArgument, 400);\n }\n\n this._levelNumber = levelNumber;\n }\n\n trace(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Trace, LogLevelNumber.Trace, context);\n }\n\n debug(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Debug, LogLevelNumber.Debug, context);\n }\n\n info(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Info, LogLevelNumber.Info, context);\n }\n\n warn(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Warn, LogLevelNumber.Warn, context);\n }\n\n error(message: string, context?: LogContext): void {\n this._write(message, LogLevel.Error, LogLevelNumber.Error, context);\n }\n\n withContext(context: LogContext): Logger {\n // Get the original log level by finding the key in logLevelNumberMap that matches this._levelNumber.\n // The Error fallback is defensive and unreachable in practice: _levelNumber always originates from the map.\n const originalLevel =\n [...logLevelNumberMap.entries()].find(([, value]) => value === this._levelNumber)?.[0] ?? LogLevel.Error;\n\n return new DefaultLogger(this._handler, originalLevel, this._mergeContext(context));\n }\n\n private _write(message: string, level: LogLevel, levelNumber: LogLevelNumber, context?: LogContext): void {\n if (levelNumber >= this._levelNumber) {\n this._handler(message, level, this._mergeContext(context));\n }\n }\n\n private _mergeContext(context?: LogContext): LogContext | undefined {\n if (!this._context) {\n return context ?? undefined;\n }\n\n return context ? { ...this._context, ...context } : this._context;\n }\n}\n","/**\n * Vercel-owned per-run output stream.\n *\n * Builds the `ReadableStream<UIMessageChunk>` that `useChat` consumes by\n * subscribing to the session Tree's `output` and `run` events for a single\n * run. Streaming is a useChat-integration concern, so it lives in the Vercel\n * layer rather than the generic core: the core Tree is the fan-out point, and\n * this projects its events into the shape `useChat` expects.\n *\n * Close semantics — the stream the consumer reads ends when:\n * - a **terminal chunk** (`finish` / `error` / `abort`) is folded for the run.\n * This is the signal `useChat`'s `sendAutomaticallyWhen` waits for, and it\n * fires even when the run merely *suspends* for a tool call (a tool-calls\n * `finish` ends the consumer stream while the core run stays alive in the\n * Tree for the continuation); or\n * - the run reaches `run-end`, which is always terminal (safety net for a run\n * that ends without emitting a terminal chunk). A `run-suspend` keeps the\n * core run alive and does not close the consumer stream.\n *\n * It errors when the session emits a non-fatal `error` (e.g. channel\n * continuity loss, or an agent-reported mid-run error), so the consumer's\n * reader rejects rather than hanging.\n */\n\nimport * as Ably from 'ably';\nimport type * as AI from 'ai';\n\nimport type { ClientSession } from '../../core/transport/types.js';\nimport { ErrorCode } from '../../errors.js';\nimport type { VercelInput, VercelOutput, VercelProjection } from '../codec/index.js';\n\ntype VercelSession = ClientSession<VercelInput, VercelOutput, VercelProjection, AI.UIMessage>;\n\n/**\n * Whether a Vercel output chunk ends the consumer-facing stream. The terminal\n * variants are `finish` (end of an LLM turn, including tool-calls), `error`,\n * and `abort`.\n * @param output - The decoded output chunk.\n * @returns True when the chunk should close the consumer stream.\n */\nconst isTerminalChunk = (output: VercelOutput): boolean =>\n output.type === 'finish' || output.type === 'error' || output.type === 'abort';\n\n/** A consumer-facing run output stream plus the handles to settle it externally. */\nexport interface RunOutputStream {\n /** The stream of decoded outputs for the run, as `useChat` consumes it. */\n stream: ReadableStream<VercelOutput>;\n /** Close the stream now (e.g. on local cancel). Idempotent. */\n close: () => void;\n /** Error the stream now (e.g. on a failed agent-invocation POST). Idempotent. */\n error: (reason: Ably.ErrorInfo) => void;\n}\n\n/**\n * Create a consumer-facing output stream for a send, sourced from the session\n * Tree's events. See the module docs for close/error semantics. The returned\n * `close`/`error` let the caller settle the stream for conditions the Tree\n * doesn't surface (local cancel, POST failure).\n *\n * Outputs route PURELY by the triggering input's codec-message-id — the key the\n * client owns from send time, before the agent mints the runId. The agent's\n * minted runId is supplied as a promise so the run-end safety-net can still\n * close the stream once it resolves.\n * @param session - The Vercel client session whose Tree to observe.\n * @param runId - The agent-minted runId, resolved when run-start is observed.\n * Used only by the run-end safety-net; routing keys on `inputCodecMessageId`.\n * @param inputCodecMessageId - The triggering input's codec-message-id. An\n * output routes to this stream when it carries this id.\n * @returns The stream and its external settle handles.\n */\nexport const createRunOutputStream = (\n session: VercelSession,\n runId: Promise<string>,\n inputCodecMessageId: string,\n): RunOutputStream => {\n const holder: { controller?: ReadableStreamDefaultController<VercelOutput> } = {};\n // ReadableStream's start() runs synchronously, so the controller is captured\n // before the constructor returns.\n const unsubscribe: (() => void)[] = [];\n const stream = new ReadableStream<VercelOutput>({\n start: (controller) => {\n holder.controller = controller;\n },\n cancel: () => {\n teardown();\n },\n });\n const { controller } = holder;\n if (!controller) {\n throw new Ably.ErrorInfo(\n 'unable to create run stream; ReadableStream start() was not called synchronously',\n ErrorCode.SessionSubscriptionError,\n 500,\n );\n }\n\n // The agent mints the runId; learn it (for the run-end safety-net) when the\n // promise resolves. Fire-and-forget: the stream opens on the input key, so a\n // never-resolving runId only forgoes the safety-net, not normal close.\n let resolvedRunId: string | undefined;\n // Best-effort: failure only disables the run-end safety-net; normal close is\n // the terminal chunk. `void` discards the promise (no await needed here).\n void runId.then(\n (id) => {\n resolvedRunId = id;\n },\n () => {\n /* session closed before run-start; safety-net stays disarmed */\n },\n );\n\n let settled = false;\n const teardown = (): void => {\n for (const unsub of unsubscribe) unsub();\n unsubscribe.length = 0;\n };\n // Settle the stream at most once: run the controller action (close/error),\n // swallow the throw if the consumer already cancelled, then tear down.\n const settle = (action: () => void): void => {\n if (settled) return;\n settled = true;\n try {\n action();\n } catch {\n /* consumer already cancelled the stream */\n }\n teardown();\n };\n const close = (): void => {\n settle(() => {\n controller.close();\n });\n };\n const error = (reason: Ably.ErrorInfo): void => {\n settle(() => {\n controller.error(reason);\n });\n };\n\n unsubscribe.push(\n session.tree.on('output', (event) => {\n if (event.inputCodecMessageId !== inputCodecMessageId) return;\n for (const output of event.events) {\n try {\n controller.enqueue(output);\n } catch {\n close();\n return;\n }\n if (isTerminalChunk(output)) {\n close();\n return;\n }\n }\n }),\n session.tree.on('run', (event) => {\n // run-end is always terminal; a run-suspend (event.type === 'suspend')\n // keeps the core run alive and must not close the consumer stream. Match\n // against the resolved runId once the agent has minted it.\n if (event.type === 'end' && resolvedRunId !== undefined && event.runId === resolvedRunId) {\n close();\n }\n }),\n session.on('error', (reason) => {\n error(reason);\n }),\n );\n\n return { stream, close, error };\n};\n","/**\n * Vercel chat transport: wraps a core ClientSession to satisfy the\n * ChatTransport interface that useChat expects.\n *\n * This is a thin adapter — the real logic lives in the core client session.\n * The chat transport maps Vercel's sendMessages/reconnectToStream contract\n * to the core session's send/cancel methods.\n *\n * useChat manages message state before calling sendMessages:\n * - submit-message (new): appends the new user message, passes the full array\n * - submit-message (edit): truncates after the edited message, replaces it,\n * passes the truncated array with messageId set\n * - regenerate-message: truncates after the target, passes the truncated array\n *\n * The adapter uses `(trigger, last-message role)` to determine the\n * history/messages split:\n * - submit-message + last message is a user message: that last message is new\n * (publish to channel), rest is history. A new submit and an edit both take\n * this path — an edit just carries a messageId.\n * - submit-message + last message is an assistant already in the tree\n * (continuation): no new messages, entire array is history\n * - regenerate-message: no new messages, entire array is history\n *\n * For an edit (submit-message with messageId) and for forking off an\n * unresolved tool call, the adapter computes fork metadata (forkOf/parent)\n * from the conversation tree so the server can place the response on the\n * correct branch. Regeneration fork metadata is NOT computed here —\n * `View.regenerate` derives forkOf/parent from the tree itself.\n */\n\nimport * as Ably from 'ably';\nimport type * as AI from 'ai';\n\nimport type { CodecMessage } from '../../core/codec/types.js';\nimport type { ActiveRun, ClientSession, SendOptions } from '../../core/transport/types.js';\nimport { ErrorCode } from '../../errors.js';\nimport { EventEmitter } from '../../event-emitter.js';\nimport { LogLevel, makeLogger } from '../../logger.js';\nimport type { VercelInput, VercelOutput, VercelProjection } from '../codec/index.js';\nimport { UIMessageCodec } from '../codec/index.js';\nimport { createRunOutputStream } from './run-output-stream.js';\n\n// ---------------------------------------------------------------------------\n// ChatTransport options\n// ---------------------------------------------------------------------------\n\n/**\n * Context passed to {@link ChatTransportOptions.prepareSendMessagesRequest} for\n * customizing the HTTP POST body and headers.\n */\nexport interface SendMessagesRequestContext {\n /** Chat session ID (from useChat's id). */\n chatId?: string;\n /** What triggered the request: user sent a message, or requested regeneration. */\n trigger: 'submit-message' | 'regenerate-message';\n /**\n * The message ID for edit or regeneration requests. For regeneration,\n * identifies the assistant message to regenerate. For edits (submit-message\n * with messageId), identifies the user message being replaced. Undefined\n * when submitting a new message.\n */\n messageId?: string;\n /** Previous messages in the conversation (context for the LLM). */\n history: AI.UIMessage[];\n /** The new message(s) being sent (to publish to the channel). Empty for regeneration and for continuations (an auto-submit where the last message is an already-tracked assistant). */\n messages: AI.UIMessage[];\n /** The codec-message-id of the message being forked — the edited user message, or the preceding assistant when forking off an unresolved tool call. Undefined for regeneration (View.regenerate derives it) and fresh sends. */\n forkOf?: string;\n /** The codec-message-id of the predecessor in the conversation thread. */\n parent?: string;\n}\n\n/** Default agent endpoint the transport POSTs invocations to — mirrors Vercel's DefaultChatTransport. */\nexport const DEFAULT_VERCEL_API = '/api/chat';\n\n/** Options for customizing the ChatTransport behavior. */\nexport interface ChatTransportOptions {\n /**\n * Endpoint the transport POSTs the invocation pointer to, to wake the\n * agent. Mirrors useChat's request-driven contract. Default `/api/chat`.\n */\n api?: string;\n /** Fetch credentials mode for the invocation POST (e.g. `'include'`). */\n credentials?: RequestCredentials;\n /** Custom fetch implementation for the invocation POST. Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /**\n * Customize the invocation POST before sending. Called by sendMessages()\n * with the conversation context; the returned `body` is merged into the\n * POST body (the run's invocation identifiers always take precedence) and\n * `headers` are added to the request. Use it for auth headers or extra\n * agent metadata.\n * @param context - The conversation context for the current request.\n * @returns The body and headers to merge into the invocation POST.\n */\n prepareSendMessagesRequest?: (context: SendMessagesRequestContext) => {\n body?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n}\n\n// ---------------------------------------------------------------------------\n// ChatTransport interface\n// ---------------------------------------------------------------------------\n\n/**\n * Additional options passed through from useChat alongside the core\n * sendMessages/reconnectToStream parameters.\n *\n * Mirrors the AI SDK's internal ChatRequestOptions type, which is not\n * exported from the `ai` package.\n */\ninterface ChatRequestOptions {\n /** Additional headers for the request. */\n headers?: Record<string, string> | Headers;\n /** Additional JSON body properties for the request. */\n body?: object;\n /** Custom metadata to attach to the request. */\n metadata?: unknown;\n}\n\n/**\n * Transport interface for Vercel AI SDK's useChat hook.\n *\n * Structurally compatible with the AI SDK's internal `ChatTransport<UIMessage>`\n * interface. Extended with `close()` for releasing the underlying Ably transport\n * resources and `streaming` / `onStreamingChange` for coordinating with\n * useMessageSync.\n */\nexport interface ChatTransport {\n /** Send messages and return a streaming response of UIMessageChunk events. */\n sendMessages: (\n options: {\n /** The type of message submission — new message or regeneration. */\n trigger: 'submit-message' | 'regenerate-message';\n /** Unique identifier for the chat session. */\n chatId: string;\n /** ID of the message to regenerate, or undefined for new messages. */\n messageId: string | undefined;\n /** Array of UI messages representing the conversation history. */\n messages: AI.UIMessage[];\n /** Signal to abort the request if needed. */\n abortSignal: AbortSignal | undefined;\n } & ChatRequestOptions,\n ) => Promise<ReadableStream<AI.UIMessageChunk>>;\n\n /**\n * Reconnect to an existing streaming response. Returns null if no active\n * stream exists for the specified chat session.\n */\n reconnectToStream: (\n options: {\n /** Unique identifier for the chat session to reconnect to. */\n chatId: string;\n } & ChatRequestOptions,\n ) => Promise<ReadableStream<AI.UIMessageChunk> | null>;\n\n /** Close the underlying transport, releasing all resources. */\n close(): Promise<void>;\n\n /** Whether an own-run stream is currently being consumed by useChat. */\n readonly streaming: boolean;\n\n /**\n * Subscribe to streaming state changes. The callback fires when the\n * ChatTransport transitions between streaming and idle. Used by\n * useMessageSync to gate setMessages calls during active streams.\n * @param callback - Called with `true` when a stream starts, `false` when it ends.\n * @returns Unsubscribe function.\n */\n onStreamingChange(callback: (streaming: boolean) => void): () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Stream wrapper — passthrough that signals completion via a promise\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap a ReadableStream in a passthrough TransformStream that resolves a\n * promise when the stream completes or errors. The returned stream passes\n * all chunks through unchanged, and `fail(reason)` errors the readable side\n * useChat consumes without cancelling or otherwise disturbing the source run\n * stream (used when the agent-invocation POST fails).\n * @param source - The original stream to wrap.\n * @returns The wrapped stream, a `done` promise that resolves when the stream\n * closes, and a `fail` callback that errors the wrapped stream.\n */\n\nconst wrapStreamWithDone = <T>(\n source: ReadableStream<T>,\n): { stream: ReadableStream<T>; done: Promise<void>; fail: (reason: Ably.ErrorInfo) => void } => {\n let resolveDone: () => void;\n const done = new Promise<void>((resolve) => {\n resolveDone = resolve;\n });\n\n const passthrough = new TransformStream<T, T>({\n flush: () => {\n resolveDone();\n },\n });\n\n // Aborting this signal errors the destination (the readable useChat reads)\n // with the abort reason. `preventCancel` keeps the source run stream intact\n // so the tree/observers are unaffected — only the useChat-facing view fails.\n const failController = new AbortController();\n\n // Pipe in the background. If the source errors/cancels, or `fail()` aborts,\n // resolve done so the serialization queue advances.\n // Fire-and-forget: the pipe runs independently; errors surface through\n // the readable side that useChat consumes.\n source.pipeTo(passthrough.writable, { signal: failController.signal, preventCancel: true }).catch(() => {\n resolveDone();\n });\n\n return {\n stream: passthrough.readable,\n done,\n fail: (reason: Ably.ErrorInfo) => {\n failController.abort(reason);\n },\n };\n};\n\n// ---------------------------------------------------------------------------\n// Unresolved tool call detection\n// ---------------------------------------------------------------------------\n\n/**\n * Whether a UIMessage part is a tool part — either the codec-normalised\n * `dynamic-tool` shape or the AI SDK's statically-declared `tool-${name}`\n * shape. Both carry `toolCallId` and `state`; the shape check at the end\n * is defensive against a future AI SDK release introducing a non-tool\n * variant under the `tool-` prefix (none exists today).\n * @param part - The UIMessage part to inspect.\n * @returns True when the part is a tool part of either representation.\n */\nconst _isToolPart = (part: AI.UIMessage['parts'][number]): part is AI.DynamicToolUIPart | AI.ToolUIPart =>\n (part.type === 'dynamic-tool' || part.type.startsWith('tool-')) && 'toolCallId' in part && 'state' in part;\n\n/**\n * Whether an assistant message has a `dynamic-tool` part that can't resolve\n * without further user action. Matches:\n * - `input-streaming` / `input-available` — tool call emitted, not yet run.\n * - `approval-requested` — waiting for the user.\n *\n * Excludes `approval-responded` (streamText will run the tool this run)\n * and all terminal `output-*` states.\n * @param msg - The UIMessage to inspect.\n * @returns True when a fork-on-send is warranted to avoid shipping a\n * dangling tool call to the LLM.\n */\nconst hasUnresolvedToolCall = (msg: AI.UIMessage): boolean =>\n msg.role === 'assistant' &&\n msg.parts.some(\n (p) =>\n _isToolPart(p) &&\n (p.state === 'input-streaming' || p.state === 'input-available' || p.state === 'approval-requested'),\n );\n\n/**\n * `dynamic-tool` part states that mean \"the LLM produced a tool call and\n * is waiting on it\". Used to detect new client-side resolutions in the\n * useChat overlay relative to the tree.\n */\nconst UNRESOLVED_TOOL_STATES = new Set(['input-streaming', 'input-available', 'approval-requested']);\n\n/**\n * Walk the useChat message overlay against the session tree and synthesize\n * the {@link VercelInput}s needed to resolve every `dynamic-tool` part the\n * user acted on (executed a tool, approved, denied) but the tree's reduced\n * state hasn't reflected yet.\n *\n * Each input carries the prior assistant's tree codec-message-id (the one\n * holding the original `dynamic-tool` part the resolution targets) in its\n * `codecMessageId` field, so the encoder stamps `codec-message-id`\n * and the reducer's direct-fold path lands the resolution on that assistant\n * in one step — no cross-message redirect-by-toolCallId fallback. Every\n * variant rides the `ai-input` wire, matching its publisher (client → input).\n *\n * The resulting inputs are passed alongside the continuation `view.send`\n * so the channel publish and the continuation POST land as ONE atomic\n * operation — the agent's `loadProjection()` history fetch is guaranteed\n * to see them because the channel publish happens before the POST inside\n * `_internalSend`.\n *\n * Three resolutions are produced:\n *\n * - `approval-responded` overlay vs `approval-requested` tree →\n * `tool-approval-response` carrying the user's decision\n * (`approved` = `overlayPart.approval.approved`, i.e. approve or deny)\n * - `output-available` overlay vs unresolved tree → `tool-result`\n * - `output-error` overlay vs unresolved tree → `tool-result-error`\n * @param codecMessages - The visible tree messages paired with their codec-message-ids.\n * @param messages - useChat's local overlay messages.\n * @returns The continuation inputs to publish, in tree order. Each input\n * carries its own `codecMessageId` targeting the prior assistant it folds\n * onto.\n */\nconst deriveContinuationInputs = (\n codecMessages: CodecMessage<AI.UIMessage>[],\n messages: AI.UIMessage[],\n): VercelInput[] => {\n const inputs: VercelInput[] = [];\n for (const overlay of messages) {\n if (overlay.role !== 'assistant') continue;\n // Match the overlay to its tree message by domain id (both sides\n // reconstruct the same stream id), but address the emitted inputs by\n // the tree message's codec-message-id — the agent folds tool\n // resolutions onto the assistant by codec-message-id, never by the\n // domain `message.id`.\n const treeEntry = codecMessages.find((p) => p.message.id === overlay.id);\n if (!treeEntry) continue;\n const { codecMessageId, message: treeMessage } = treeEntry;\n\n for (const overlayPart of overlay.parts) {\n if (!_isToolPart(overlayPart)) continue;\n // The codec normalises every tool part to `dynamic-tool`, but the\n // AI SDK's useChat overlay emits `tool-${name}` parts for statically\n // declared tools. Match by toolCallId rather than the type prefix\n // so the cross-representation comparison works regardless of which\n // side the tool was declared on.\n const treePart = treeMessage.parts.find(\n (p: AI.UIMessage['parts'][number]): p is AI.DynamicToolUIPart | AI.ToolUIPart =>\n _isToolPart(p) && p.toolCallId === overlayPart.toolCallId,\n );\n\n // Approval response: useChat's `addToolApprovalResponse` flipped the\n // overlay part to `approval-responded` while the tree still sits on\n // `approval-requested`. Publish a `tool-approval-response` TInput so the\n // agent's projection sees the decision.\n if (overlayPart.state === 'approval-responded' && (!treePart || treePart.state === 'approval-requested')) {\n inputs.push(\n UIMessageCodec.createToolApprovalResponse(codecMessageId, {\n toolCallId: overlayPart.toolCallId,\n approved: overlayPart.approval.approved,\n ...(overlayPart.approval.reason === undefined ? {} : { reason: overlayPart.approval.reason }),\n }),\n );\n continue;\n }\n\n // Client-tool resolution: overlay has `output-available` / `output-error`\n // while the tree's part is still unresolved. Construct a TInput\n // variant (not a UIMessageChunk) so the encoder publishes on the\n // `ai-input` wire — client tool results belong on `ai-input`, matching\n // their client publisher, not on `ai-output`.\n if (overlayPart.state !== 'output-available' && overlayPart.state !== 'output-error') continue;\n // Tree already resolved (echo arrived back) — nothing to do.\n if (treePart && !UNRESOLVED_TOOL_STATES.has(treePart.state)) continue;\n\n if (overlayPart.state === 'output-available') {\n inputs.push(\n UIMessageCodec.createToolResult(codecMessageId, {\n toolCallId: overlayPart.toolCallId,\n output: overlayPart.output,\n }),\n );\n } else {\n inputs.push(\n UIMessageCodec.createToolResultError(codecMessageId, {\n toolCallId: overlayPart.toolCallId,\n message: overlayPart.errorText,\n }),\n );\n }\n }\n }\n return inputs;\n};\n\n/**\n * Find the codec-message-id immediately preceding the message identified by\n * domain id `domainId` in the flat visible conversation. The target is\n * located by its domain `message.id` (the id useChat references), but the\n * returned value is the predecessor's codec-message-id — never a domain id.\n * Returns undefined if the target is the first message or not found.\n * @param codecMessages - Visible messages paired with their codec-message-ids.\n * @param domainId - The domain id of the target message.\n * @returns The predecessor's codec-message-id, or undefined.\n */\nconst findPredecessorCodecId = (codecMessages: CodecMessage<AI.UIMessage>[], domainId: string): string | undefined => {\n const idx = codecMessages.findIndex((p) => p.message.id === domainId);\n if (idx <= 0) return undefined;\n return codecMessages[idx - 1]?.codecMessageId;\n};\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/** Internal EventEmitter events map backing the transport's streaming state. */\ninterface ChatTransportEventsMap {\n /** Fired on every streaming-state transition with the new value. */\n streaming: boolean;\n}\n\n/**\n * Create a Vercel ChatTransport from a core ClientSession.\n *\n * Exposes a `streaming` flag and `onStreamingChange` callback so that\n * `useMessageSync` can gate `setMessages` calls during active own-run\n * streams, preventing the push/replace ID mismatch in useChat's `write()`.\n *\n * Note: concurrent `sendMessage` calls from the same user are a useChat\n * limitation that cannot be fixed from the transport layer. The\n * developer must respect useChat's `status` and only call `sendMessage`\n * when status is `'ready'`.\n * @param session - The core client session to wrap.\n * @param chatOptions - Optional hooks for customizing request construction.\n * @returns A {@link ChatTransport} compatible with Vercel's useChat hook.\n */\nexport const createChatTransport = (\n session: ClientSession<VercelInput, VercelOutput, VercelProjection, AI.UIMessage>,\n chatOptions?: ChatTransportOptions,\n): ChatTransport => {\n // -- Invocation POST config (the transport owns waking the agent) ----------\n const api = chatOptions?.api ?? DEFAULT_VERCEL_API;\n const fetchFn = chatOptions?.fetch ?? globalThis.fetch.bind(globalThis);\n const credentials = chatOptions?.credentials;\n\n // -- Streaming state -------------------------------------------------------\n // Backed by the shared EventEmitter for listener error isolation (one bad\n // onStreamingChange handler can't prevent others from firing or block the\n // state transition) and uniform emitter behaviour across the SDK. The\n // factory takes no logger, so a silent one is used — listener exceptions are\n // swallowed by the emitter rather than surfaced.\n let _streaming = false;\n const emitter = new EventEmitter<ChatTransportEventsMap>(makeLogger({ logLevel: LogLevel.Silent }));\n\n const setStreaming = (value: boolean): void => {\n _streaming = value;\n emitter.emit('streaming', value);\n };\n\n // -- sendMessages implementation -------------------------------------------\n\n const sendMessages: ChatTransport['sendMessages'] = async (opts) => {\n const { messages, abortSignal, trigger, messageId } = opts;\n\n // The visible messages paired with their codec-message-ids. useChat\n // references messages by their domain `message.id`; we match on that to\n // locate a message in the tree, then route every transport operation by\n // the message's codec-message-id (the SDK never correlates on the domain\n // id, which may differ from the codec-message-id).\n const codecMessages = session.view.getMessages();\n const codecIdByDomainId = new Map(codecMessages.map((m) => [m.message.id, m.codecMessageId]));\n const codecIdOf = (domainId: string): string | undefined => codecIdByDomainId.get(domainId);\n\n // useChat calls sendMessages in three distinct modes. We disambiguate\n // by (trigger, last-message role) so each mode dispatches correctly:\n //\n // - 'regenerate-message' → fork an assistant\n // - 'submit-message' + last message is assistant → continuation\n // (auto-submit after\n // addToolResult, or\n // multi-step tool use)\n // - 'submit-message' + last message is user → new user message\n // (or edit if\n // messageId is set)\n //\n // Continuation mode must NOT publish the assistant as a new message or\n // treat messageId as a fork target — useChat v6's sendAutomaticallyWhen\n // path always sets messageId to the last message id regardless.\n const lastMessage = messages.at(-1);\n const lastMessageInTree = !!lastMessage && codecIdByDomainId.has(lastMessage.id);\n const isContinuation = trigger === 'submit-message' && lastMessage?.role === 'assistant' && lastMessageInTree;\n\n // Fork-on-unresolved-tool: user sent a new message while the preceding\n // assistant has an unresolved tool call (approval-requested, input-*).\n // Fork the new message off the preceding assistant so the unresolved\n // tool call stays dormant on a sibling branch. Inference for this run runs\n // on the clean fork — the LLM never sees the dangling tool_use.\n //\n // Only applies to fresh user-message submits (not continuations, not\n // regenerates, not edits-with-messageId).\n //\n // `messages.at(-1)` is the fresh user-prompt being submitted right now;\n // `messages.at(-2)` is therefore the prior assistant whose tool state\n // we need to inspect for the unresolved-tool gate below.\n const precedingMessage =\n trigger === 'submit-message' && !messageId && lastMessage?.role === 'user' ? messages.at(-2) : undefined;\n // The domain id of the preceding assistant when it carries an unresolved\n // tool call and is present in the tree — the new user message forks off it.\n const forkSourceDomainId =\n precedingMessage && hasUnresolvedToolCall(precedingMessage) && codecIdByDomainId.has(precedingMessage.id)\n ? precedingMessage.id\n : undefined;\n\n // Determine the history/messages split based on mode.\n let newMessages: AI.UIMessage[];\n let history: AI.UIMessage[];\n\n if (trigger === 'regenerate-message' || isContinuation) {\n newMessages = [];\n history = messages;\n } else {\n if (messages.length === 0) {\n throw new Ably.ErrorInfo(\n 'unable to send messages; messages array is empty for submit-message trigger',\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n // CAST: length check above guarantees at least one element; .at(-1) cannot be undefined.\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style -- prefer `as` over `!` per TYPES.md\n newMessages = [messages.at(-1) as AI.UIMessage];\n // When forking off an unresolved tool call, drop the unresolved\n // assistant from history too — it belongs on the sibling branch, not\n // the ancestor chain of the new message.\n history = forkSourceDomainId ? messages.slice(0, -2) : messages.slice(0, -1);\n }\n\n // Compute fork metadata for edit (submit-message with messageId) and\n // fork-on-unresolved-tool. Regenerate is NOT precomputed here —\n // `View.regenerate` derives forkOf/parent from the tree itself and\n // overrides anything we'd set.\n let forkOf: string | undefined;\n let parent: string | undefined;\n\n if (trigger === 'submit-message' && messageId && !isContinuation) {\n // Edit: messageId is the domain id of the user message being replaced.\n // forkOf = its codec-message-id, parent = the immediately-preceding\n // codec-message-id in the flat conversation.\n forkOf = codecIdOf(messageId);\n parent = findPredecessorCodecId(codecMessages, messageId);\n } else if (forkSourceDomainId) {\n // Fork off the preceding assistant — the new user message becomes a\n // sibling of the unresolved tool call assistant, rooted at its parent.\n forkOf = codecIdOf(forkSourceDomainId);\n parent = findPredecessorCodecId(codecMessages, forkSourceDomainId);\n }\n\n let sendBody: Record<string, unknown>;\n let sendHeaders: Record<string, string> | undefined;\n\n if (chatOptions?.prepareSendMessagesRequest) {\n const prepared = chatOptions.prepareSendMessagesRequest({\n chatId: opts.chatId,\n trigger,\n messageId,\n history,\n messages: newMessages,\n forkOf,\n parent,\n });\n sendBody = prepared.body ?? {};\n sendHeaders = prepared.headers;\n } else {\n sendBody = {};\n sendHeaders = undefined;\n }\n\n const sendOpts: SendOptions = {};\n if (forkOf !== undefined) sendOpts.forkOf = forkOf;\n if (parent !== undefined) sendOpts.parent = parent;\n // Continuations reuse the suspended assistant's runId so the agent's\n // existing run resumes under a fresh invocation rather than spinning\n // up a brand-new run. `isContinuation` implies `lastMessage` is defined.\n if (isContinuation) {\n // `isContinuation` implies `lastMessage` is defined (it gates on\n // `lastMessage?.role`). Route the runId lookup by codec-message-id.\n const codecId = codecIdOf(lastMessage.id);\n const run = codecId === undefined ? undefined : session.view.runOf(codecId);\n if (run) sendOpts.runId = run.runId;\n }\n\n // Dispatch by mode:\n //\n // - Continuation: derive tool-resolution events from useChat's overlay\n // vs the tree and pair each with the prior assistant's tree codec-message-id —\n // the SDK stamps the wire's `codec-message-id` to that id so the\n // reducer's direct fold path runs (no redirect, no consume).\n // - Regenerate: route through `view.regenerate`. The View mints a\n // wire-only regenerate event (`ait-regenerate`) carrying\n // `forkOf=A1` / `parent=U1` on transport headers. U1 is NOT\n // republished — A1 and A2 group as tree siblings under U1 via the\n // existing forkOf machinery. The LLM receives the truncated history\n // through U1 inclusive via the body.\n // - Fresh send / edit: publish the new user-message input(s) via\n // `view.send`.\n let run: ActiveRun;\n if (isContinuation) {\n const inputs = deriveContinuationInputs(codecMessages, messages);\n run = await session.view.send(inputs, sendOpts);\n } else if (trigger === 'regenerate-message') {\n if (messageId === undefined) {\n throw new Ably.ErrorInfo(\n 'unable to regenerate; regenerate-message trigger fired without messageId',\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n // useChat passes the assistant's domain id; route by its codec-message-id.\n const regenCodecId = codecIdOf(messageId);\n if (regenCodecId === undefined) {\n throw new Ably.ErrorInfo(\n `unable to regenerate; message not visible: ${messageId}`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n run = await session.view.regenerate(regenCodecId, sendOpts);\n } else {\n const inputs = newMessages.map((m) => UIMessageCodec.createUserMessage(m));\n run = await session.view.send(inputs, sendOpts);\n }\n\n // Build the consumer-facing stream from the Tree's events for this run.\n // Streaming is a useChat concern owned by the Vercel layer; the core\n // session exposes no per-run stream. Key it on\n // `run.inputCodecMessageId` — the triggering input's codec-message-id, which\n // the client owns from send time and the agent echoes as\n // `input-codec-message-id`. The agent mints the runId, supplied as\n // `run.runId` (a promise) for the run-end safety-net.\n const runStream = createRunOutputStream(session, run.runId, run.inputCodecMessageId);\n\n if (abortSignal) {\n const onAbort = (): void => {\n // Best-effort cancel via the run handle (knows its own key / runId);\n // the core resolves the runId once the agent mints it.\n void run.cancel();\n // Close the consumer stream immediately so useChat's reader ends\n // without waiting for the agent's run-end round-trip.\n runStream.close();\n };\n // useChat sets `status: 'submitted'` synchronously inside `makeRequest`\n // BEFORE awaiting `transport.sendMessages`. That immediately enables\n // the Stop button in the UI. If the user clicks Stop while\n // `session.view.send` is still awaiting the run-start ack (which\n // can take seconds for a real LLM), useChat aborts the signal before\n // we ever get here. `addEventListener('abort', ...)` does not fire\n // for an already-aborted signal, so we'd silently lose the cancel\n // and the agent would keep streaming.\n if (abortSignal.aborted) {\n onAbort();\n } else {\n abortSignal.addEventListener('abort', onAbort, { once: true });\n }\n }\n\n // Wrap the stream to detect completion. The streaming flag gates\n // useMessageSync so that setMessages doesn't interfere with\n // useChat's internal write() during active streams.\n const { stream, done, fail } = wrapStreamWithDone(runStream.stream);\n setStreaming(true);\n\n // Fire-and-forget: clear the streaming flag when the stream ends.\n void done.then(() => {\n setStreaming(false);\n });\n\n // Wake the agent: POST the invocation pointer to the configured endpoint.\n // useChat's transport contract is request-driven, so the transport owns\n // this POST (the core session is HTTP-free). Fire-and-forget — `await`\n // would delay the stream return, and the agent's response arrives over\n // the Ably channel, not the HTTP response. The run's invocation\n // identifiers always win over any custom body so the agent can parse it\n // via Invocation.fromJSON. A failed POST means the agent never woke, so\n // error the useChat-facing stream; the core run and observers are\n // untouched.\n const postBody = { ...sendBody, ...run.toInvocation().toJSON() };\n fetchFn(api, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...sendHeaders },\n body: JSON.stringify(postBody),\n ...(credentials ? { credentials } : {}),\n })\n .then((response) => {\n if (!response.ok) {\n fail(\n new Ably.ErrorInfo(\n `unable to send; HTTP POST to ${api} returned ${String(response.status)} ${response.statusText}`,\n ErrorCode.SessionSendFailed,\n response.status,\n ),\n );\n }\n })\n .catch((error: unknown) => {\n const cause = error instanceof Ably.ErrorInfo ? error : undefined;\n fail(\n new Ably.ErrorInfo(\n `unable to send; HTTP POST to ${api} failed: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.SessionSendFailed,\n 500,\n cause,\n ),\n );\n });\n\n return stream;\n };\n\n return {\n sendMessages,\n\n // Observer mode handles in-progress streams automatically.\n // The transport subscribes before attach — on the next server append,\n // observer accumulation emits lifecycle events that useMessageSync\n // upserts into React state.\n // eslint-disable-next-line unicorn/no-null, @typescript-eslint/promise-function-async -- null is required by the AI SDK ChatTransport contract; no await needed\n reconnectToStream: () => Promise.resolve(null),\n\n close: async () => session.close(),\n\n get streaming(): boolean {\n return _streaming;\n },\n\n onStreamingChange: (callback: (streaming: boolean) => void): (() => void) => {\n emitter.on('streaming', callback);\n return () => {\n emitter.off('streaming', callback);\n };\n },\n };\n};\n","/** SDK version. Kept in sync with `package.json` by the `/release` workflow. */\nexport const VERSION = '0.2.0';\n","/**\n * Wraps the two paths chat-js uses (see ChatClient._addAgent): the\n * `options.agents` mutation (read by ably-js when opening the initial\n * WebSocket) and the `params.agent` channel option (sent on ATTACH so\n * an already-open connection still carries the identifier).\n *\n * `options.agents` is a private API on the Realtime client — no public\n * typed accessor exists in the `ably` package — so this module casts to a\n * `RealtimeWithOptions` shape to write it.\n */\n\nimport type * as Ably from 'ably';\n\nimport { VERSION } from '../version.js';\n\ninterface RealtimeWithOptions extends Ably.Realtime {\n options: { agents?: Record<string, string | undefined> };\n}\n\nconst SDK_NAME = 'ai-transport-js';\n\n/** Internal shape a codec may carry to opt into Ably-Agent header registration. */\ninterface AdapterTagHolder {\n readonly adapterTag?: string;\n}\n\n/**\n * Merge `agents` into `client.options.agents` and return the space-separated\n * `params.agent` string for channel ATTACH.\n * @param client - The Ably Realtime client to mutate.\n * @param agents - Map of agent-name to version strings to register.\n * @returns Channel options containing `params.agent` for `channels.get`.\n */\nconst injectAgents = (\n client: Ably.Realtime,\n // CAST: Ably.Realtime's public type omits `options.agents`, but the SDK\n // does carry it at runtime. ably-chat-js relies on the same shape — see\n // ChatClient._addAgent in https://github.com/ably/ably-chat-js.\n agents: Record<string, string>,\n): { params: { agent: string } } => {\n const realtime = client as RealtimeWithOptions;\n realtime.options.agents = { ...realtime.options.agents, ...agents };\n const agentString = Object.entries(agents)\n .map(([name, version]) => `${name}/${version}`)\n .join(' ');\n return { params: { agent: agentString } };\n};\n\n/**\n * Register this SDK (and optionally a codec) on the supplied Realtime client\n * and return the channel options the caller should pass to\n * `client.channels.get(...)` so the agent is also carried on channel ATTACH.\n * Sets `options.agents['ai-transport-js'] = VERSION`. When the codec carries\n * an internal `adapterTag` field (via {@link AdapterTagHolder}), also sets\n * `options.agents[adapterTag] = VERSION`.\n * Idempotent — repeated calls with the same client and codec produce the same keys/values.\n * Spec: AIT-CT1a, AIT-CT1a2, AIT-CT1a3, AIT-ST1a, AIT-ST1a2, AIT-ST1a3.\n * @param client - The Ably Realtime client to register on.\n * @param codec - The codec instance; cast to {@link AdapterTagHolder} to detect an optional identifier.\n * @returns Channel options containing `params.agent` for `channels.get`.\n */\nexport const registerAgent = (client: Ably.Realtime, codec?: unknown): { params: { agent: string } } => {\n // CAST: AdapterTagHolder is an internal opt-in shape — not part of the public Codec interface.\n const adapterTag = (codec as AdapterTagHolder | undefined)?.adapterTag;\n const agents: Record<string, string> = { [SDK_NAME]: VERSION };\n if (adapterTag) agents[adapterTag] = VERSION;\n return injectAgents(client, agents);\n};\n","/**\n * Transport header builder.\n *\n * Single source of truth for which transport headers every transport\n * message carries. Used by the agent session (pipe, addEvents) and by\n * the client session (optimistic message stamping).\n */\n\nimport {\n EVENT_RUN_END,\n EVENT_RUN_RESUME,\n EVENT_RUN_START,\n EVENT_RUN_SUSPEND,\n HEADER_CODEC_MESSAGE_ID,\n HEADER_EVENT_ID,\n HEADER_FORK_OF,\n HEADER_INPUT_CLIENT_ID,\n HEADER_INPUT_CODEC_MESSAGE_ID,\n HEADER_INVOCATION_ID,\n HEADER_MSG_REGENERATE,\n HEADER_PARENT,\n HEADER_ROLE,\n HEADER_RUN_CLIENT_ID,\n HEADER_RUN_ID,\n HEADER_RUN_REASON,\n} from '../../constants.js';\nimport type { RunEndReason, RunLifecycleEvent } from './types.js';\n\n/**\n * Build the standard transport header set for a message.\n * @param opts - The header values to include.\n * @param opts.role - Message role (e.g. \"user\", \"assistant\").\n * @param opts.runId - Run correlation ID, or `undefined` for a fresh client\n * input (the agent mints run-ids, so it is not known synchronously). Omitted\n * from the headers when undefined; a continuation still carries the known run-id.\n * @param opts.codecMessageId - Message identity — the wire `codec-message-id` for this message.\n * @param opts.runClientId - ClientId of the run initiator.\n * @param opts.parent - Preceding message's codec-message-id (for branching).\n * @param opts.forkOf - Forked user-prompt's codec-message-id (for edits — creates a Run-level fork sibling).\n * @param opts.regenerates - Assistant codec-message-id this run regenerates. Stamps\n * `msg-regenerate`. Distinct from `forkOf`: regenerate is a\n * continuation of the prior run (no Run-level fork), with the message\n * replacement resolved at projection extraction time.\n * @param opts.invocationId - Agent-minted invocation id. Stamped by the agent on every event it publishes for the invocation (run lifecycle + outputs) so the client can observe it; not set by the client on the input.\n * @param opts.inputClientId - ClientId of the input event (the `ai-input`) that\n * drove the current invocation. The agent reads it from the publisher's\n * Ably-level `clientId` on the matched input event and re-stamps it on its\n * own publishes (run lifecycle + outputs). Differs from `runClientId` on\n * continuation invocations driven by an input from a non-owner.\n * @param opts.inputEventId - Per-event identifier. Set on each client-published user-prompt message; the invocation body's `inputEventIds` lists the ids the agent should look up.\n * @param opts.inputCodecMessageId - The codec-message-id of the input event that\n * triggered the current invocation (the one whose `event-id` matched the\n * invocation's `inputEventId`). The agent re-stamps it on every event it\n * publishes for the invocation (run lifecycle + outputs), mirroring\n * `inputClientId`, so the client can correlate any of those events back to\n * the originating input by the id it owned at send time.\n * @returns A headers record with the transport headers set.\n */\nexport const buildTransportHeaders = (opts: {\n role: string;\n runId?: string;\n codecMessageId: string;\n runClientId?: string;\n parent?: string;\n forkOf?: string;\n regenerates?: string;\n invocationId?: string;\n inputClientId?: string;\n inputCodecMessageId?: string;\n inputEventId?: string;\n}): Record<string, string> => {\n const h: Record<string, string> = {\n [HEADER_ROLE]: opts.role,\n [HEADER_CODEC_MESSAGE_ID]: opts.codecMessageId,\n };\n if (opts.runId !== undefined) h[HEADER_RUN_ID] = opts.runId;\n if (opts.runClientId !== undefined) h[HEADER_RUN_CLIENT_ID] = opts.runClientId;\n if (opts.parent) h[HEADER_PARENT] = opts.parent;\n if (opts.forkOf) h[HEADER_FORK_OF] = opts.forkOf;\n if (opts.regenerates) h[HEADER_MSG_REGENERATE] = opts.regenerates;\n if (opts.invocationId) h[HEADER_INVOCATION_ID] = opts.invocationId;\n if (opts.inputClientId !== undefined) h[HEADER_INPUT_CLIENT_ID] = opts.inputClientId;\n if (opts.inputCodecMessageId !== undefined) h[HEADER_INPUT_CODEC_MESSAGE_ID] = opts.inputCodecMessageId;\n if (opts.inputEventId) h[HEADER_EVENT_ID] = opts.inputEventId;\n return h;\n};\n\n/**\n * Build the transport header set for a run-lifecycle event (run-start,\n * run-resume, run-suspend, run-end). Single source of truth for lifecycle\n * header stamping, mirroring {@link buildTransportHeaders} for the\n * message-carrier path. Every field except `runId`/`runClientId` is optional\n * and omitted when not provided.\n *\n * A resume suppresses the structural `parent` / `forkOf` / `regenerates`\n * headers — the caller passes them only for a fresh run-start. `reason` is\n * stamped only on run-end.\n * @param opts - The lifecycle header values to include.\n * @param opts.runId - The run's id.\n * @param opts.runClientId - ClientId of the run initiator (empty string when unknown).\n * @param opts.parent - Structural parent codec-message-id (fresh run-start only).\n * @param opts.forkOf - Forked user-prompt codec-message-id (fresh run-start only).\n * @param opts.regenerates - Regenerated assistant codec-message-id (fresh run-start only).\n * @param opts.invocationId - Agent-minted invocation id; carried on every lifecycle event.\n * @param opts.inputClientId - ClientId of the triggering input event.\n * @param opts.inputCodecMessageId - Codec-message-id of the triggering input event.\n * @param opts.reason - Terminal reason; stamped on run-end only.\n * @returns A headers record with the lifecycle headers set.\n */\nexport const buildLifecycleHeaders = (opts: {\n runId: string;\n runClientId: string;\n parent?: string;\n forkOf?: string;\n regenerates?: string;\n invocationId?: string;\n inputClientId?: string;\n inputCodecMessageId?: string;\n reason?: RunEndReason;\n}): Record<string, string> => {\n const h: Record<string, string> = {\n [HEADER_RUN_ID]: opts.runId,\n [HEADER_RUN_CLIENT_ID]: opts.runClientId,\n };\n if (opts.reason !== undefined) h[HEADER_RUN_REASON] = opts.reason;\n if (opts.parent !== undefined) h[HEADER_PARENT] = opts.parent;\n if (opts.forkOf !== undefined) h[HEADER_FORK_OF] = opts.forkOf;\n if (opts.regenerates !== undefined) h[HEADER_MSG_REGENERATE] = opts.regenerates;\n if (opts.invocationId !== undefined) h[HEADER_INVOCATION_ID] = opts.invocationId;\n if (opts.inputClientId !== undefined) h[HEADER_INPUT_CLIENT_ID] = opts.inputClientId;\n if (opts.inputCodecMessageId !== undefined) h[HEADER_INPUT_CODEC_MESSAGE_ID] = opts.inputCodecMessageId;\n return h;\n};\n\n/** The four run-lifecycle Ably message names. */\ntype RunLifecycleName =\n | typeof EVENT_RUN_START\n | typeof EVENT_RUN_SUSPEND\n | typeof EVENT_RUN_RESUME\n | typeof EVENT_RUN_END;\n\n/**\n * Whether an Ably message `name` is one of the run-lifecycle event names\n * (run-start / run-suspend / run-resume / run-end). Single source of truth for\n * the classification both decode loops and the agent's history scan use to\n * route lifecycle wires away from the codec decoder. Narrows `name` to a\n * lifecycle name so callers can pass it straight to {@link parseRunLifecycle}.\n * @param name - The inbound Ably message `name`, or undefined.\n * @returns True when `name` is a run-lifecycle event name.\n */\nexport const isRunLifecycleName = (name: string | undefined): name is RunLifecycleName =>\n name === EVENT_RUN_START || name === EVENT_RUN_SUSPEND || name === EVENT_RUN_RESUME || name === EVENT_RUN_END;\n\n/**\n * Parse an inbound run-lifecycle Ably message into a {@link RunLifecycleEvent}.\n *\n * Single source of truth for turning the wire run-lifecycle message `name`,\n * transport headers, and channel serial into the structured lifecycle event\n * the Tree consumes. Used by the client decode loop (live) and the View's\n * history replay so both build the event identically.\n * @param name - The inbound Ably message `name`.\n * @param headers - Transport headers from the inbound Ably message.\n * @param serial - Ably channel serial of the message, or `undefined` for an\n * optimistic local event. Stamped onto the returned event.\n * @returns The lifecycle event, or `undefined` when `name` is not a\n * run-lifecycle event name or the message carries no `run-id`.\n */\nexport const parseRunLifecycle = (\n name: string,\n headers: Record<string, string>,\n serial: string | undefined,\n): RunLifecycleEvent | undefined => {\n const runId = headers[HEADER_RUN_ID];\n if (!runId) return undefined;\n\n const clientId = headers[HEADER_RUN_CLIENT_ID] ?? '';\n\n if (name === EVENT_RUN_START) {\n const parent = headers[HEADER_PARENT];\n const forkOf = headers[HEADER_FORK_OF];\n const regenerates = headers[HEADER_MSG_REGENERATE];\n return {\n type: 'start',\n runId,\n clientId,\n serial,\n invocationId: headers[HEADER_INVOCATION_ID] ?? '',\n ...(parent !== undefined && { parent }),\n ...(forkOf !== undefined && { forkOf }),\n ...(regenerates !== undefined && { regenerates }),\n };\n }\n\n if (name === EVENT_RUN_SUSPEND) {\n return { type: 'suspend', runId, clientId, serial, invocationId: headers[HEADER_INVOCATION_ID] ?? '' };\n }\n\n if (name === EVENT_RUN_RESUME) {\n return { type: 'resume', runId, clientId, serial, invocationId: headers[HEADER_INVOCATION_ID] ?? '' };\n }\n\n if (name === EVENT_RUN_END) {\n // CAST: agent always writes a valid RunEndReason; default to 'complete' for robustness.\n const reason = (headers[HEADER_RUN_REASON] ?? 'complete') as RunEndReason;\n return { type: 'end', runId, clientId, serial, invocationId: headers[HEADER_INVOCATION_ID] ?? '', reason };\n }\n\n return undefined;\n};\n","/**\n * Helpers for FIFO-bounded `Map`s — Maps used as capacity-limited buffers that\n * must evict their oldest entry when full.\n */\n\n/**\n * Make room for a new key in a FIFO-bounded map: if `map` is at (or over)\n * `limit` and does not already contain `key`, evict the oldest entry (insertion\n * order) and return its key so the caller can log the eviction. Returns\n * `undefined` when nothing was evicted (the key already exists, the map is\n * below the limit, or it is empty).\n *\n * The caller performs the actual set/append afterwards — this only frees a\n * slot — so it works for maps whose values are replaced and for maps whose\n * values are appended-to lists.\n * @param map - The bounded map to evict from.\n * @param key - The key about to be added; an existing key never evicts.\n * @param limit - The maximum number of entries the map may hold.\n * @returns The evicted key, or `undefined` if nothing was evicted.\n */\nexport const evictOldestIfFull = <K, V>(map: Map<K, V>, key: K, limit: number): K | undefined => {\n if (map.has(key) || map.size < limit) return undefined;\n const oldest = map.keys().next().value;\n if (oldest === undefined) return undefined;\n map.delete(oldest);\n return oldest;\n};\n","/**\n * buildBranchChain — order a single conversation branch by walking\n * codec-message-id parent links upward from an anchor node to the root.\n *\n * This is the shared ordering spine of the agent's conversation\n * reconstruction and of history decode: both need the same root→anchor\n * sequence of nodes before folding each node's projection. Keeping the walk\n * here — pure, with no codec, no I/O, no logger — lets it be proven in\n * isolation and reused by both engines without drift.\n *\n * Branch selection is implicit: a node reaches only its own ancestors via\n * `parentCodecMessageId`, so sibling branches (edits / regenerates that the\n * anchor did not descend from) are never visited. There is no separate\n * fork/regenerate filtering step — the un-taken sibling is simply unreachable.\n */\n\n/**\n * The single field {@link buildBranchChain} reads from a node. Richer node-meta\n * shapes (carrying run-id, fork-of, regenerates, …) satisfy this structurally,\n * so callers can pass their full index map directly.\n */\nexport interface BranchChainNode {\n /**\n * Codec-message-id of this node's structural parent — the node it hangs off\n * — or `undefined` for a root node. This is the only edge the walk follows.\n */\n parentCodecMessageId: string | undefined;\n}\n\n/**\n * Walk `parentCodecMessageId` links upward from `anchorCodecMessageId` and\n * return the branch it sits on, ordered root-first (oldest) to anchor (newest,\n * last). The anchor is always the final element.\n *\n * The walk stops at the root (a node with no parent), at a dangling parent\n * (a parent id absent from `nodeMeta` is still included as the chain head,\n * then the walk ends), or on revisiting a node (a cycle in malformed data is\n * broken best-effort rather than looping forever).\n * @param nodeMeta - Lookup from codec-message-id to its node meta. Need not\n * contain the anchor or every ancestor; missing entries simply end the walk.\n * @param anchorCodecMessageId - The codec-message-id to start the walk from\n * (the newest node on the branch; included in the result).\n * @returns The branch's codec-message-ids ordered root-first to anchor-last.\n */\nexport const buildBranchChain = (\n nodeMeta: ReadonlyMap<string, BranchChainNode>,\n anchorCodecMessageId: string,\n): string[] => {\n const chain: string[] = [];\n const seen = new Set<string>();\n let current: string | undefined = anchorCodecMessageId;\n while (current !== undefined && !seen.has(current)) {\n seen.add(current);\n chain.push(current);\n current = nodeMeta.get(current)?.parentCodecMessageId;\n }\n return chain.toReversed();\n};\n","/**\n * Shared wire decode-and-apply engine.\n *\n * The client's live decode loop and the View's history replay both reconstruct\n * the conversation Tree from the same raw Ably wire log. This module is the one\n * place that classifies a wire message (run-lifecycle vs codec-decoded), parses\n * or decodes it, and applies it to the Tree — so the two paths can never drift.\n */\n\nimport type * as Ably from 'ably';\n\nimport { HEADER_RUN_ID } from '../../constants.js';\nimport { getTransportHeaders } from '../../utils.js';\nimport type { Codec, CodecInputEvent, CodecOutputEvent, Decoder } from '../codec/types.js';\nimport { isRunLifecycleName, parseRunLifecycle } from './headers.js';\nimport type { TreeInternal } from './tree.js';\nimport type { RunLifecycleEvent } from './types.js';\n\n/**\n * Apply one inbound wire message to the tree.\n *\n * Run-lifecycle messages are turned into a {@link RunLifecycleEvent} via\n * {@link parseRunLifecycle} and applied with `applyRunLifecycle`; everything\n * else is decoded with `decoder` and applied with `applyMessage`, skipping\n * wire-only carriers that decode to no events and carry no run-id (the eventual\n * reply run is created later by its run-start).\n *\n * Does NOT emit the tree's `ably-message` event — the caller owns that, because\n * the live loop emits per message while history replay emits in a batch once\n * the whole page is applied. Returns the parsed lifecycle event so a live\n * caller can run its own side-effects (resolving a pending run-start,\n * surfacing an agent error); returns `undefined` for a codec-decoded message\n * or a lifecycle message that carried no run-id.\n * @param tree - The tree to apply the message to.\n * @param decoder - The codec decoder used for non-lifecycle messages.\n * @param rawMsg - The inbound Ably wire message.\n * @returns The parsed run-lifecycle event, or `undefined`.\n */\nexport const applyWireMessage = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection>(\n tree: TreeInternal<TInput, TOutput, TProjection>,\n decoder: Decoder<TInput, TOutput>,\n rawMsg: Ably.InboundMessage,\n): RunLifecycleEvent | undefined => {\n const headers = getTransportHeaders(rawMsg);\n const serial = rawMsg.serial;\n\n if (isRunLifecycleName(rawMsg.name)) {\n const event = parseRunLifecycle(rawMsg.name, headers, serial);\n if (event) tree.applyRunLifecycle(event);\n return event;\n }\n\n const { inputs, outputs } = decoder.decode(rawMsg);\n if (inputs.length > 0 || outputs.length > 0 || headers[HEADER_RUN_ID]) {\n tree.applyMessage({ inputs, outputs }, headers, serial);\n }\n return undefined;\n};\n\n/**\n * Decode one wire message with `decoder` and fold its events into `projection`,\n * returning the updated projection. Unlike {@link applyWireMessage} this builds\n * a standalone projection rather than applying to a tree — used by the agent's\n * conversation reconstruction. The caller owns the decoder so its streaming\n * state can span the messages of a run, and chooses the reducer routing key.\n * @param codec - The codec whose inherited Reducer `fold` method folds each decoded event into the projection.\n * @param decoder - The caller-owned codec decoder (reused across a run's wires).\n * @param projection - The projection to fold the message's events into.\n * @param rawMsg - The wire message to decode and fold.\n * @param messageId - The reducer routing key (codec-message-id) for this message.\n * @returns The projection after folding all of the message's decoded events.\n */\nexport const foldMessageInto = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(\n codec: Codec<TInput, TOutput, TProjection, TMessage>,\n decoder: Decoder<TInput, TOutput>,\n projection: TProjection,\n rawMsg: Ably.InboundMessage,\n messageId: string,\n): TProjection => {\n const { inputs, outputs } = decoder.decode(rawMsg);\n let next = projection;\n for (const event of [...inputs, ...outputs]) {\n next = codec.fold(next, event, { serial: rawMsg.serial ?? '', messageId });\n }\n return next;\n};\n","/**\n * Agent-side conversation reconstruction from the channel wire log.\n *\n * When an agent wakes (or resumes) it has no in-memory tree — it rebuilds the\n * state it needs by paging channel history and folding the wires through the\n * codec. Two entry points:\n *\n * - {@link loadRunProjection} — fold a single run's wires into one projection\n * (used to resume a suspended run with its client tool-output amends).\n * - {@link loadConversation} — walk the structural parent chain from the\n * current run's input node to the root and fold each node, producing the full\n * multi-turn message history along the taken branch.\n *\n * Both reuse {@link foldMessageInto} (the shared per-message fold primitive) and\n * {@link buildBranchChain} (the shared parent-chain walk), so the agent's\n * reconstruction can't drift from the client/View decode paths.\n */\n\nimport * as Ably from 'ably';\n\nimport { EVENT_RUN_START, HEADER_CODEC_MESSAGE_ID, HEADER_PARENT, HEADER_RUN_ID } from '../../constants.js';\nimport { ErrorCode } from '../../errors.js';\nimport type { Logger } from '../../logger.js';\nimport { compareBySerial, getTransportHeaders } from '../../utils.js';\nimport type { Codec, CodecInputEvent, CodecOutputEvent } from '../codec/types.js';\nimport type { BranchChainNode } from './branch-chain.js';\nimport { buildBranchChain } from './branch-chain.js';\nimport { foldMessageInto } from './decode-fold.js';\nimport { isRunLifecycleName } from './headers.js';\n\n// ---------------------------------------------------------------------------\n// History collection + dedup\n// ---------------------------------------------------------------------------\n\n/**\n * Merge messages observed live (e.g. by the input-event lookup) into a set of\n * collected history messages, dedup by serial, and sort chronologically.\n *\n * History messages take priority in deduplication (history serial wins if the\n * same message appears in both). Messages without a serial are dropped because\n * they cannot be reliably ordered.\n * @param collected - Raw messages from channel.history (any order).\n * @param live - Messages observed live (e.g. by the input-event lookup); may be undefined.\n * @returns Deduplicated, chronologically sorted messages.\n */\nexport const withLiveMessages = (\n collected: readonly Ably.InboundMessage[],\n live?: readonly Ably.InboundMessage[],\n): Ably.InboundMessage[] => {\n const seen = new Set<string>();\n const result: Ably.InboundMessage[] = [];\n for (const msg of collected) {\n if (msg.serial !== undefined && !seen.has(msg.serial)) {\n seen.add(msg.serial);\n result.push(msg);\n }\n }\n if (live !== undefined) {\n for (const msg of live) {\n if (msg.serial !== undefined && !seen.has(msg.serial)) {\n seen.add(msg.serial);\n result.push(msg);\n }\n }\n }\n return result.toSorted(compareBySerial);\n};\n\n/**\n * Page through a channel's history and collect raw messages, bounded so a\n * long-lived channel can't exhaust memory. No `untilAttach` — callers need\n * messages published after the channel first attached (e.g. client tool-output\n * amends on a suspended run).\n * @param channel - The Ably channel to read history from.\n * @param pageLimit - Messages requested per history page.\n * @param maxMessages - Stop paging once this many messages are collected.\n * @returns The collected messages in history order (newest first per Ably).\n */\nconst collectHistory = async (\n channel: Ably.RealtimeChannel,\n pageLimit: number,\n maxMessages: number,\n): Promise<Ably.InboundMessage[]> => {\n const collected: Ably.InboundMessage[] = [];\n let page = await channel.history({ limit: pageLimit });\n collected.push(...page.items);\n while (page.hasNext() && collected.length < maxMessages) {\n const nextPage: Ably.PaginatedResult<Ably.InboundMessage> | null = await page.next();\n if (!nextPage) break;\n collected.push(...nextPage.items);\n page = nextPage;\n }\n return collected;\n};\n\n// ---------------------------------------------------------------------------\n// Per-node folds\n// ---------------------------------------------------------------------------\n\n/**\n * Fold a pre-sorted array of wire messages for a single run into a projection.\n *\n * Skips lifecycle events (they carry no codec content) and stops before the\n * message whose `codec-message-id` equals `truncateAt` (exclusive — that\n * message is not folded). Used by both {@link loadRunProjection} (no\n * truncation) and {@link loadConversation} (per-ancestor folding).\n * @param codec - Codec used to decode and fold events.\n * @param sortedMessages - Chronologically ordered wire messages (all runs).\n * @param runId - Only messages stamped with this run-id are folded.\n * @param truncateAt - Stop before this codec-message-id; omit to fold all messages.\n * @returns The projection and the count of messages that were folded.\n */\nexport const foldRunMessages = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(\n codec: Codec<TInput, TOutput, TProjection, TMessage>,\n sortedMessages: readonly Ably.InboundMessage[],\n runId: string,\n truncateAt?: string,\n): { projection: TProjection; folded: number } => {\n const decoder = codec.createDecoder();\n let projection = codec.init();\n let folded = 0;\n for (const msg of sortedMessages) {\n const h = getTransportHeaders(msg);\n if (h[HEADER_RUN_ID] !== runId) continue;\n if (isRunLifecycleName(msg.name)) continue;\n const codecMsgId = h[HEADER_CODEC_MESSAGE_ID];\n if (truncateAt !== undefined && codecMsgId === truncateAt) break;\n projection = foldMessageInto(codec, decoder, projection, msg, codecMsgId ?? '');\n folded++;\n }\n return { projection, folded };\n};\n\n/**\n * Fold a single run-less INPUT node's events into a fresh projection: every\n * wire stamped with `codecMessageId` and NO run-id (the user prompt the client\n * published before the agent minted a run-id). The two-node analogue of\n * {@link foldRunMessages} for the user-input side of the conversation chain.\n * @param codec - Codec used to decode and fold events.\n * @param sortedMessages - Chronologically ordered wire messages (all runs).\n * @param codecMessageId - The input node's codec-message-id.\n * @returns The folded projection for that input node.\n */\nexport const foldInputMessages = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(\n codec: Codec<TInput, TOutput, TProjection, TMessage>,\n sortedMessages: readonly Ably.InboundMessage[],\n codecMessageId: string,\n): TProjection => {\n const decoder = codec.createDecoder();\n let projection = codec.init();\n for (const msg of sortedMessages) {\n const h = getTransportHeaders(msg);\n if (h[HEADER_RUN_ID] !== undefined) continue;\n if (h[HEADER_CODEC_MESSAGE_ID] !== codecMessageId) continue;\n projection = foldMessageInto(codec, decoder, projection, msg, codecMessageId);\n }\n return projection;\n};\n\n// ---------------------------------------------------------------------------\n// Run-state reconstruction\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch all messages on the channel that belong to `runId`, decode them\n * through the codec, and fold them into a single projection. Used by the agent\n * to reconstruct a run's full state — including client-published tool-output\n * amends — when resuming a suspended run in a fresh agent session.\n *\n * Doesn't require channel rewind: an explicit `channel.history()` call returns\n * the same data even if the channel is already attached from a prior session.\n * @param opts - Load parameters.\n * @param opts.channel - The Ably channel to read history from.\n * @param opts.codec - Codec used to decode and fold events.\n * @param opts.runId - Run identifier whose events should be folded.\n * @param opts.signal - AbortSignal checked once at entry: if already aborted the call throws immediately and no history is fetched. It does not interrupt an in-flight load.\n * @param opts.logger - Optional logger for diagnostic output.\n * @param opts.liveMessages - Raw Ably messages already observed live (e.g. by\n * the input-event lookup). Folded alongside the history fetch so just-published\n * client wires don't depend on Ably's history-indexing window.\n * @returns The projection produced by folding all run events in serial order.\n * @throws {Ably.ErrorInfo} with code ErrorCode.InvalidArgument if `signal` is already aborted at entry (the run was cancelled before loading began).\n */\nexport const loadRunProjection = async <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(opts: {\n channel: Ably.RealtimeChannel;\n codec: Codec<TInput, TOutput, TProjection, TMessage>;\n runId: string;\n signal: AbortSignal;\n logger: Logger | undefined;\n liveMessages?: readonly Ably.InboundMessage[];\n}): Promise<TProjection> => {\n const { channel, codec, runId, signal, logger, liveMessages } = opts;\n\n if (signal.aborted) {\n throw new Ably.ErrorInfo(\n `unable to load run projection; run ${runId} was cancelled`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n await channel.attach();\n\n // 2000 wire messages is generously more than any single run could produce.\n const collected = await collectHistory(channel, 200, 2000);\n\n const sorted = withLiveMessages(collected, liveMessages);\n const { projection, folded } = foldRunMessages(codec, sorted, runId);\n\n logger?.debug('loadRunProjection(); folded run events', { runId, folded });\n return projection;\n};\n\n/** A node in the reconstruction index — {@link BranchChainNode} plus its run-id. */\ninterface NodeMeta extends BranchChainNode {\n /** The run-id this node belongs to, or undefined for a run-less input node. */\n runId: string | undefined;\n}\n\n/**\n * Reconstruct the full multi-turn conversation history along the branch the\n * current run sits on.\n *\n * Pages channel history (merging live lookup messages), indexes each\n * codec-message-id's structural parent and run-id with sticky identity (the\n * first wire wins; later amends can't poison it), backfills a reply run's\n * parent from its `ai-run-start` when the output wire wasn't indexed, then\n * walks the structural parent chain from the current run's input node\n * (`assistantParentFallback`) to the root and folds each node in chain order.\n * The current run is folded once, wholesale, at the tail.\n * @param opts - Reconstruction parameters.\n * @param opts.channel - The Ably channel to read history from.\n * @param opts.codec - Codec used to decode and fold events.\n * @param opts.runId - The current run's id.\n * @param opts.signal - AbortSignal checked once at entry; if already aborted the call throws before any history is fetched. It does not interrupt an in-flight load.\n * @param opts.logger - Optional logger for diagnostic output.\n * @param opts.liveMessages - Wires already observed live, merged into history.\n * @param opts.assistantParentFallback - The current run's input node\n * (codec-message-id) — the anchor the parent-chain walk starts from. When\n * undefined, only the current run is folded.\n * @param opts.pageLimit - Messages requested per history page.\n * @param opts.maxMessages - Stop paging once this many messages are collected.\n * @returns The branch's messages (root-first) and the current run's projection.\n * @throws {Ably.ErrorInfo} with code ErrorCode.InvalidArgument when `signal` is already aborted at entry.\n */\nexport const loadConversation = async <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(opts: {\n channel: Ably.RealtimeChannel;\n codec: Codec<TInput, TOutput, TProjection, TMessage>;\n runId: string;\n signal: AbortSignal;\n logger: Logger | undefined;\n liveMessages: readonly Ably.InboundMessage[] | undefined;\n assistantParentFallback: string | undefined;\n pageLimit: number;\n maxMessages: number;\n}): Promise<{ messages: TMessage[]; projection: TProjection }> => {\n const { channel, codec, runId, signal, logger, liveMessages, assistantParentFallback, pageLimit, maxMessages } = opts;\n\n if (signal.aborted) {\n throw new Ably.ErrorInfo(`unable to load conversation; run ${runId} was cancelled`, ErrorCode.InvalidArgument, 400);\n }\n\n // Single channel.history() fetch for all runs. Live lookup messages are\n // merged in so the current run's just-published client wires don't depend on\n // Ably's history-indexing window. Deduped by serial (history wins), sorted.\n const collected = await collectHistory(channel, pageLimit, maxMessages);\n const sortedMessages = withLiveMessages(collected, liveMessages);\n\n // Index pass — node metadata per codec-message-id from the serial-sorted\n // history, with sticky identity (the first wire for a codec-message-id wins\n // for the structural parent; a later amend can't poison it). Run-bearing\n // wires record their runId; run-less user inputs are input nodes (runId\n // undefined).\n const nodeMeta = new Map<string, NodeMeta>();\n const runIdToCodecMessageId = new Map<string, string>();\n for (const msg of sortedMessages) {\n if (isRunLifecycleName(msg.name)) continue;\n const h = getTransportHeaders(msg);\n const cid = h[HEADER_CODEC_MESSAGE_ID];\n if (cid === undefined) continue;\n const msgRunId = h[HEADER_RUN_ID];\n if (msgRunId !== undefined) runIdToCodecMessageId.set(msgRunId, cid);\n if (!nodeMeta.has(cid)) {\n nodeMeta.set(cid, { runId: msgRunId, parentCodecMessageId: h[HEADER_PARENT] });\n }\n }\n // Backfill a reply run's structural parent from ai-run-start when its output\n // wire wasn't indexed (rare history lag). Keyed by runId → codec-message-id.\n for (const msg of sortedMessages) {\n if (msg.name !== EVENT_RUN_START) continue;\n const h = getTransportHeaders(msg);\n const msgRunId = h[HEADER_RUN_ID];\n if (msgRunId === undefined) continue;\n const cid = runIdToCodecMessageId.get(msgRunId);\n if (cid === undefined) continue;\n const meta = nodeMeta.get(cid);\n if (meta && meta.parentCodecMessageId === undefined) meta.parentCodecMessageId = h[HEADER_PARENT];\n }\n\n // Walk the structural parent chain from the current run's input node up to\n // the conversation root, then fold each node in chain order. The upward walk\n // naturally excludes un-taken branch siblings (an edit's alternate prompt, a\n // regenerate's superseded reply), so no per-ancestor truncation is needed.\n // (Open caveat, deferred with a golden test: regenerating a non-trailing\n // message of a multi-message reply — the node walk can't slice inside one\n // run's projection.)\n const messages: TMessage[] = [];\n let chainLength = 0;\n if (assistantParentFallback !== undefined) {\n const chain = buildBranchChain(nodeMeta, assistantParentFallback);\n chainLength = chain.length;\n for (const cid of chain) {\n const meta = nodeMeta.get(cid);\n // Skip any chain node belonging to the CURRENT run — it is folded once,\n // wholesale, at the tail below. For a continuation the run-id is reused\n // and `assistantParentFallback` points at a message INSIDE the current\n // run, so it would otherwise be folded twice and emit duplicate tool_use\n // ids.\n if (meta?.runId === runId) continue;\n const projection =\n meta?.runId === undefined\n ? foldInputMessages(codec, sortedMessages, cid)\n : foldRunMessages(codec, sortedMessages, meta.runId).projection;\n messages.push(...codec.getMessages(projection).map((m) => m.message));\n }\n }\n\n // Current run — folded from the same sorted messages, appended at the chain\n // tail (the chain ended at this run's input node).\n const { projection, folded } = foldRunMessages(codec, sortedMessages, runId);\n messages.push(...codec.getMessages(projection).map((m) => m.message));\n\n logger?.debug('loadConversation(); built', { runId, chainLength, totalMessages: messages.length, folded });\n return { messages, projection };\n};\n","/**\n * Pure stream piping function.\n *\n * Reads outputs from a ReadableStream, writes them to an encoder via\n * `publishOutput`, and handles cancel/error. No dependencies on run\n * state or session internals.\n */\n\nimport type { Logger } from '../../logger.js';\nimport type { CodecInputEvent, CodecOutputEvent, Encoder, WriteOptions } from '../codec/types.js';\nimport type { StreamResult } from './types.js';\n\n/**\n * Adapt an AbortSignal into a promise that resolves once the signal aborts,\n * paired with a cleanup that detaches the listener. With no signal the promise\n * never resolves (there is no cancellation path); an already-aborted signal\n * resolves immediately. `cleanup` is a no-op unless a listener was attached.\n * @param signal - The AbortSignal to watch, or undefined for no cancellation.\n * @returns The abort promise and a cleanup to call when racing is done.\n */\nconst abortSignalToPromise = (signal: AbortSignal | undefined): { promise: Promise<void>; cleanup: () => void } => {\n let listener: (() => void) | undefined;\n const promise =\n signal === undefined\n ? // eslint-disable-next-line @typescript-eslint/no-empty-function -- never-resolving promise: no signal means no cancellation path\n new Promise<void>(() => {})\n : signal.aborted\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n listener = () => {\n resolve();\n };\n signal.addEventListener('abort', listener, { once: true });\n });\n const cleanup = (): void => {\n if (listener && signal) signal.removeEventListener('abort', listener);\n };\n return { promise, cleanup };\n};\n\n/**\n * Pipe an output stream through an encoder to the channel.\n *\n * Returns when the stream completes, is cancelled (via signal), or errors.\n * The `reason` field of the result indicates which case occurred.\n * @param stream - The output stream to read from.\n * @param encoder - The encoder to publish outputs through.\n * @param signal - AbortSignal to monitor for cancellation.\n * @param onCancelled - Optional callback invoked when the stream is cancelled, before the stream ends.\n * @param resolveWriteOptions - Optional per-output hook returning {@link WriteOptions} overrides to pass to `encoder.publishOutput`.\n * @param logger - Optional logger for diagnostic output.\n * @returns A {@link StreamResult}: `reason` is why the pipe ended, and `error` holds the caught error when `reason` is `'error'`.\n */\nexport const pipeStream = async <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent>(\n stream: ReadableStream<TOutput>,\n encoder: Encoder<TInput, TOutput>,\n signal: AbortSignal | undefined,\n onCancelled?: (write: (output: TOutput) => Promise<void>) => void | Promise<void>,\n resolveWriteOptions?: (output: TOutput) => WriteOptions | undefined,\n logger?: Logger,\n): Promise<StreamResult> => {\n logger?.trace('pipeStream();');\n\n const reader = stream.getReader();\n const abort = abortSignalToPromise(signal);\n\n let reason: StreamResult['reason'] = 'complete';\n let caughtError: Error | undefined;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- intentional infinite loop broken by return/break\n while (true) {\n // .then() is intentional: transforms the AbortSignal into a discriminant\n // for Promise.race — no async/await equivalent for this pattern.\n const result = await Promise.race([reader.read(), abort.promise.then(() => 'cancelled' as const)]);\n\n if (result === 'cancelled') {\n reason = 'cancelled';\n logger?.debug('pipeStream(); stream cancelled by AbortSignal');\n if (onCancelled) {\n await onCancelled(async (output: TOutput) => encoder.publishOutput(output));\n }\n await encoder.cancel('cancelled');\n break;\n }\n\n const { done, value } = result;\n if (done) {\n await encoder.close();\n logger?.debug('pipeStream(); stream completed');\n break;\n }\n\n await encoder.publishOutput(value, resolveWriteOptions?.(value));\n }\n } catch (error) {\n reason = 'error';\n caughtError = error instanceof Error ? error : new Error(String(error));\n logger?.error('pipeStream(); stream error', { error: caughtError.message });\n try {\n await encoder.close();\n } catch {\n // Best-effort: encoder close in the error path may also fail\n // (e.g. channel disconnected). The original error is preserved in\n // the StreamResult reason (\"error\").\n }\n } finally {\n abort.cleanup();\n reader.releaseLock();\n }\n\n return { reason, error: caughtError };\n};\n","/**\n * Server-side run state management and lifecycle event publishing.\n *\n * Owns the authoritative run lifecycle. Tracks active runs with their\n * AbortControllers and clientIds. Publishes run-start, run-resume, run-suspend, and\n * run-end events on the Ably channel so all clients can react to run\n * state changes.\n */\n\nimport type * as Ably from 'ably';\n\nimport { EVENT_RUN_END, EVENT_RUN_RESUME, EVENT_RUN_START, EVENT_RUN_SUSPEND } from '../../constants.js';\nimport type { Logger } from '../../logger.js';\nimport { buildLifecycleHeaders } from './headers.js';\nimport type { RunEndReason } from './types.js';\n\n/**\n * Per-invocation metadata carried on a run's opening lifecycle event. A\n * continuation (re-entering an existing run) sets `continuation` and omits the\n * structural `parent` / `forkOf` / `regenerates` fields.\n */\nexport interface StartRunMetadata {\n /** Structural parent codec-message-id (fresh run-start only). */\n parent?: string;\n /** Forked user-prompt codec-message-id for an edit (fresh run-start only). */\n forkOf?: string;\n /** Regenerated assistant codec-message-id (fresh run-start only). */\n regenerates?: string;\n /** Agent-minted invocation id, carried on the lifecycle event. */\n invocationId?: string;\n /** ClientId of the triggering input event. */\n inputClientId?: string;\n /** Codec-message-id of the triggering input event. */\n inputCodecMessageId?: string;\n /** When true, publish `ai-run-resume` (re-entry) instead of `ai-run-start`. */\n continuation?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/** Manages active runs and publishes run lifecycle events on the channel. */\nexport interface RunManager {\n /**\n * Register a run and publish its opening lifecycle event. Publishes\n * `ai-run-start` for a fresh run, or `ai-run-resume` when `metadata.continuation`\n * is set (a subsequent invocation re-entering an existing run). A resume omits\n * the structural `parent` / `forkOf` / `regenerates` headers — the original\n * run-start owns the run's structure. Returns the run's AbortSignal.\n */\n startRun(\n runId: string,\n clientId?: string,\n controller?: AbortController,\n metadata?: StartRunMetadata,\n ): Promise<AbortSignal>;\n /**\n * Suspend a run. Publishes run-suspend on the channel and drops the run's\n * active-run entry — the agent process terminates on suspend, so there is no\n * live AbortController to retain. A cancel arriving during suspension is a\n * no-op; the resuming invocation re-registers the run via {@link startRun}.\n * Carries the same per-invocation attribution as {@link endRun}\n * (`inputClientId`, `inputCodecMessageId`), since a suspend is the terminal\n * event of the suspending invocation just as run-end is of an ending one.\n */\n suspendRun(runId: string, invocationId?: string, inputClientId?: string, inputCodecMessageId?: string): Promise<void>;\n /**\n * End a run. Publishes run-end on the channel (stamping `reason` as the\n * run-reason header) and drops the run's active-run entry. Carries the same\n * per-invocation attribution as {@link suspendRun} (`invocationId`,\n * `inputClientId`, `inputCodecMessageId`), since run-end is the terminal event\n * of the ending invocation.\n */\n endRun(\n runId: string,\n reason: RunEndReason,\n invocationId?: string,\n inputClientId?: string,\n inputCodecMessageId?: string,\n ): Promise<void>;\n /** Get the AbortSignal for a run. */\n getSignal(runId: string): AbortSignal | undefined;\n /** Get the clientId that owns a run. */\n getClientId(runId: string): string | undefined;\n /** Fire the AbortSignal for a run to cancel any in-flight work. */\n cancel(runId: string): void;\n /** Get all active run IDs. */\n getActiveRunIds(): string[];\n /** Cancel all active runs and clear state. */\n close(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\ninterface ActiveRunEntry {\n controller: AbortController;\n clientId: string;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nclass DefaultRunManager implements RunManager {\n private readonly _channel: Ably.RealtimeChannel;\n private readonly _logger: Logger | undefined;\n private readonly _activeRuns = new Map<string, ActiveRunEntry>();\n\n constructor(channel: Ably.RealtimeChannel, logger?: Logger) {\n this._channel = channel;\n this._logger = logger?.withContext({ component: 'RunManager' });\n }\n\n async startRun(\n runId: string,\n clientId?: string,\n externalController?: AbortController,\n metadata?: StartRunMetadata,\n ): Promise<AbortSignal> {\n this._logger?.trace('DefaultRunManager.startRun();', { runId, clientId });\n\n const controller = externalController ?? new AbortController();\n const resolvedClientId = clientId ?? '';\n this._activeRuns.set(runId, { controller, clientId: resolvedClientId });\n\n // A continuation re-enters an already-started run: publish `ai-run-resume`\n // rather than `ai-run-start`. Resume is a pure re-entry signal — the\n // original run-start already established the run's structure, so the\n // parent / forkOf / regenerates metadata is NOT re-stamped here (doing so\n // would point the run at content within itself). The agent learned this is\n // a continuation from the run-id on the triggering input; the re-entry is\n // conveyed to clients by the event name, not a header echo. The\n // invocation-id / input attribution headers are carried on both.\n const continuation = metadata?.continuation === true;\n\n const headers = buildLifecycleHeaders({\n runId,\n runClientId: resolvedClientId,\n parent: continuation ? undefined : metadata?.parent,\n forkOf: continuation ? undefined : metadata?.forkOf,\n regenerates: continuation ? undefined : metadata?.regenerates,\n invocationId: metadata?.invocationId,\n inputClientId: metadata?.inputClientId,\n inputCodecMessageId: metadata?.inputCodecMessageId,\n });\n\n await this._channel.publish({\n name: continuation ? EVENT_RUN_RESUME : EVENT_RUN_START,\n extras: { ai: { transport: headers } },\n });\n\n this._logger?.debug('DefaultRunManager.startRun(); run started', { runId });\n return controller.signal;\n }\n\n async suspendRun(\n runId: string,\n invocationId?: string,\n inputClientId?: string,\n inputCodecMessageId?: string,\n ): Promise<void> {\n this._logger?.trace('DefaultRunManager.suspendRun();', { runId });\n await this._publishTerminal(EVENT_RUN_SUSPEND, runId, { invocationId, inputClientId, inputCodecMessageId });\n this._logger?.debug('DefaultRunManager.suspendRun(); run suspended', { runId });\n }\n\n async endRun(\n runId: string,\n reason: RunEndReason,\n invocationId?: string,\n inputClientId?: string,\n inputCodecMessageId?: string,\n ): Promise<void> {\n this._logger?.trace('DefaultRunManager.endRun();', { runId, reason });\n await this._publishTerminal(EVENT_RUN_END, runId, { reason, invocationId, inputClientId, inputCodecMessageId });\n this._logger?.debug('DefaultRunManager.endRun(); run ended', { runId, reason });\n }\n\n /**\n * Publish a run's terminal lifecycle event (run-suspend or run-end) and drop\n * its active-run entry. Both events are the suspending/ending invocation's\n * terminal signal, carrying the same per-invocation correlation; they differ\n * only by event name and the run-reason header (run-end). Publishes BEFORE\n * dropping local state so a publish failure leaves the run in the active set.\n * @param eventName - The lifecycle event to publish (run-suspend or run-end).\n * @param runId - The run being suspended or ended.\n * @param attribution - Per-invocation correlation and the terminal reason.\n * @param attribution.reason - Terminal reason; set for run-end, omitted for run-suspend.\n * @param attribution.invocationId - The invocation's id.\n * @param attribution.inputClientId - ClientId of the triggering input event.\n * @param attribution.inputCodecMessageId - Codec-message-id of the triggering input event.\n */\n private async _publishTerminal(\n eventName: string,\n runId: string,\n attribution: {\n reason?: RunEndReason;\n invocationId?: string;\n inputClientId?: string;\n inputCodecMessageId?: string;\n },\n ): Promise<void> {\n const resolvedClientId = this._activeRuns.get(runId)?.clientId ?? '';\n const headers = buildLifecycleHeaders({ runId, runClientId: resolvedClientId, ...attribution });\n await this._channel.publish({ name: eventName, extras: { ai: { transport: headers } } });\n this._activeRuns.delete(runId);\n }\n\n getSignal(runId: string): AbortSignal | undefined {\n return this._activeRuns.get(runId)?.controller.signal;\n }\n\n getClientId(runId: string): string | undefined {\n return this._activeRuns.get(runId)?.clientId;\n }\n\n cancel(runId: string): void {\n this._logger?.debug('DefaultRunManager.cancel();', { runId });\n this._activeRuns.get(runId)?.controller.abort();\n }\n\n getActiveRunIds(): string[] {\n return [...this._activeRuns.keys()];\n }\n\n close(): void {\n this._logger?.trace('DefaultRunManager.close();', { activeRuns: this._activeRuns.size });\n for (const state of this._activeRuns.values()) {\n state.controller.abort();\n }\n this._activeRuns.clear();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a run manager bound to the given channel.\n * @param channel - The Ably channel to publish lifecycle events on.\n * @param logger - Optional logger for diagnostic output.\n * @returns A new {@link RunManager} instance.\n */\nexport const createRunManager = (channel: Ably.RealtimeChannel, logger?: Logger): RunManager =>\n new DefaultRunManager(channel, logger);\n","/**\n * Core agent (server-side) session, parameterized by codec.\n *\n * Composes RunManager and pipeStream to handle the full server-side run\n * lifecycle. Cancel message routing is handled directly by the session's\n * single channel subscription — no separate cancel manager needed.\n *\n * The session exposes a single factory method — `createRun()` — which returns\n * a Run object with explicit lifecycle methods: start(), pipe(), addEvents(),\n * suspend(), and end() (suspend() and end() are both terminal).\n */\n\nimport * as Ably from 'ably';\n\nimport {\n EVENT_CANCEL,\n HEADER_CODEC_MESSAGE_ID,\n HEADER_EVENT_ID,\n HEADER_FORK_OF,\n HEADER_INPUT_CODEC_MESSAGE_ID,\n HEADER_MSG_REGENERATE,\n HEADER_PARENT,\n HEADER_RUN_CLIENT_ID,\n HEADER_RUN_ID,\n} from '../../constants.js';\nimport { ErrorCode } from '../../errors.js';\nimport type { Logger } from '../../logger.js';\nimport { compareBySerial, getTransportHeaders } from '../../utils.js';\nimport { registerAgent } from '../agent.js';\nimport type { Codec, CodecInputEvent, CodecOutputEvent } from '../codec/types.js';\nimport { buildTransportHeaders } from './headers.js';\nimport { evictOldestIfFull } from './internal/bounded-map.js';\nimport { Invocation } from './invocation.js';\nimport { loadConversation, loadRunProjection } from './load-conversation.js';\nimport { pipeStream } from './pipe-stream.js';\nimport type { RunManager } from './run-manager.js';\nimport { createRunManager } from './run-manager.js';\nimport type {\n AgentSession,\n AgentSessionOptions,\n CancelRequest,\n EventsNode,\n LoadConversationOptions,\n MessageNode,\n PipeOptions,\n Run,\n RunEndReason,\n RunRuntime,\n RunView,\n StreamResult,\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Run-state lookup helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Wait for every event-id in `expectedInputEventIds` to arrive as a channel\n * message before letting the run proceed to LLM work. Uses the session's\n * unfiltered channel dispatcher (registered in `connect()`) so that\n * messages replayed via channel rewind on attach reach the lookup — no\n * separate history fetch needed.\n *\n * Scope: this awaits the data-carrying input events a send publishes —\n * fresh prompts, edits, regenerates, tool results, and approvals. Control\n * events (cancel etc.) carry no `event-id`, are dispatched\n * separately, and never enter this lookup.\n *\n * Each client-published event in a send (user-message AND amend events\n * such as tool-approval responses and client tool outputs) is stamped\n * with its own `event-id`.\n * The lookup matches incoming messages against the expected set; ids\n * not in the set are ignored, duplicates (rewind redelivering a message\n * also seen live) are deduped by event-id. The wait completes when\n * every expected id has arrived, guaranteeing the channel state is\n * consistent with what the client promised before any downstream\n * processing (loadProjection, streamText) runs.\n *\n * User-message arrivals decode into MessageNodes that populate\n * `run.view.messages`; amend arrivals fold into a fresh projection that\n * has no target message, so they're orphaned and dropped — they only\n * count toward the wait. Collected nodes are returned sorted by Ably\n * `serial` ascending.\n *\n * Bounded by `timeoutMs` as a total budget across all N arrivals. The\n * caller's `signal` aborts the wait. On partial collection at timeout the\n * promise rejects with `InputEventNotFound` and an error message including\n * \"received X of Y\". If any decode throws mid-collection, the whole lookup\n * rejects with `InputEventNotFound` wrapping the decode error as cause —\n * already-collected messages are discarded.\n * @param opts - Lookup parameters.\n * @param opts.register - Session-provided registration that delivers the input events for the expected event-ids. Returns an unregister function.\n * @param opts.codec - Codec used to decode arriving messages.\n * @param opts.invocationId - Invocation identifier — used only for diagnostic logging and error messages.\n * @param opts.runId - Run identifier (used for logging and error messages).\n * @param opts.expectedInputEventIds - Input-event ids the lookup must observe before resolving.\n * @param opts.timeoutMs - Maximum total time to wait for all event-id arrivals.\n * @param opts.signal - AbortSignal that cancels the wait when the run is cancelled.\n * @param opts.logger - Optional logger for diagnostic output.\n * @returns The MessageNodes for arriving user-message events (sorted by Ably\n * serial — empty when every input event was a tool-resolution wire message that\n * decoded to a chunk and produced no node), and the transport headers of\n * the first matched wire message. `firstHeaders` is the canonical source for\n * run-level metadata (clientId, parent, forkOf, continuation flag) because\n * it lands whether or not the decode produced a MessageNode. `firstClientId`\n * carries the publisher's Ably-level `clientId` from that same message — the\n * source of `inputClientId` re-stamping on the agent's published events.\n */\ninterface InputEventLookupResult<TMessage> {\n nodes: MessageNode<TMessage>[];\n firstHeaders?: Record<string, string>;\n firstClientId?: string;\n /**\n * Raw Ably messages observed live for the matched input-event ids, in\n * arrival order. The agent forwards these to `loadRunProjection` so a\n * continuation invocation can fold the just-published client wires\n * (e.g. a tool-output-available) without waiting on Ably's channel\n * history indexing window.\n */\n rawMessages: Ably.InboundMessage[];\n}\n\nconst lookupInputEvents = async <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(opts: {\n register: (callback: (msg: Ably.InboundMessage) => void) => () => void;\n codec: Codec<TInput, TOutput, TProjection, TMessage>;\n invocationId: string;\n runId: string;\n expectedInputEventIds: readonly string[];\n timeoutMs: number;\n signal: AbortSignal;\n logger: Logger | undefined;\n}): Promise<InputEventLookupResult<TMessage>> => {\n const { register, codec, invocationId, runId, expectedInputEventIds, timeoutMs, signal, logger } = opts;\n const expectedSet = new Set(expectedInputEventIds);\n const expectedCount = expectedSet.size;\n\n const collected: MessageNode<TMessage>[] = [];\n const rawMessages: Ably.InboundMessage[] = [];\n const matchedInputEventIds = new Set<string>();\n let firstHeaders: Record<string, string> | undefined;\n let firstClientId: string | undefined;\n\n /**\n * Decode an inbound Ably message into MessageNodes via the codec.\n * @param m - The inbound Ably message to decode.\n * @returns The decoded MessageNodes carrying transport headers and serial.\n */\n const decode = (m: Ably.InboundMessage): MessageNode<TMessage>[] => {\n const decoder = codec.createDecoder();\n const headers = getTransportHeaders(m);\n const codecMessageId = headers[HEADER_CODEC_MESSAGE_ID] ?? '';\n const { inputs, outputs } = decoder.decode(m);\n const events: (TInput | TOutput)[] = [...inputs, ...outputs];\n let projection = codec.init();\n for (const event of events) {\n projection = codec.fold(projection, event, { serial: m.serial ?? '', messageId: codecMessageId });\n }\n return codec.getMessages(projection).map(({ message }) => ({\n kind: 'message' as const,\n message,\n codecMessageId,\n parentId: headers[HEADER_PARENT],\n forkOf: headers[HEADER_FORK_OF],\n headers,\n serial: m.serial,\n }));\n };\n\n return new Promise<InputEventLookupResult<TMessage>>((resolve, reject) => {\n let settled = false;\n // Dedupe across rewind-redelivery: rewind may surface a message the\n // listener also saw live. Scoped to the active lookup so it cannot\n // grow unbounded.\n const seenSerials = new Set<string>();\n // Forward-declared so that cleanup() and onCancelled() can reference them\n // before they are assigned. cleanup may run synchronously inside\n // `register(...)` (when buffered input events drain on registration) before\n // `unregister`/`timer` have been assigned — the no-op fallback for\n // unregister and undefined-guard for timer handle that window. The\n // settled-flag re-check after `register` returns reconciles the\n // listener-detach that cleanup couldn't perform inside that window.\n /* eslint-disable prefer-const, unicorn/consistent-function-scoping, @typescript-eslint/no-empty-function -- forward-declared state for the sync-drain reconciliation pattern; see comment above. */\n let unregister: () => void = () => {};\n let timer: ReturnType<typeof setTimeout> | undefined;\n /* eslint-enable */\n const cleanup = (): void => {\n unregister();\n if (timer !== undefined) clearTimeout(timer);\n signal.removeEventListener('abort', onCancelled);\n };\n const onCancelled = (): void => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(\n new Ably.ErrorInfo(`unable to look up input event; run ${runId} was cancelled`, ErrorCode.InvalidArgument, 400),\n );\n };\n signal.addEventListener('abort', onCancelled, { once: true });\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- onCancelled may have settled the promise synchronously above when the signal was already aborted.\n if (settled) return;\n unregister = register((m) => {\n if (settled) return;\n if (m.serial !== undefined && seenSerials.has(m.serial)) return;\n if (m.serial !== undefined) seenSerials.add(m.serial);\n\n const wireHeaders = getTransportHeaders(m);\n\n // Only count messages whose event-id is in the expected set.\n const msgEventId = wireHeaders[HEADER_EVENT_ID];\n if (!msgEventId || !expectedSet.has(msgEventId) || matchedInputEventIds.has(msgEventId)) return;\n matchedInputEventIds.add(msgEventId);\n\n // Capture the trigger event's headers AND its Ably channel-level `clientId`\n // so run-level metadata (parent / forkOf / continuation flag from headers;\n // `inputClientId` from the wire publisher) is available even when the decode\n // produces zero MessageNodes — the case for continuation tool-resolution\n // trigger events whose chunks fold into a fresh empty projection without\n // an assistant to land on.\n if (firstHeaders === undefined) {\n firstHeaders = wireHeaders;\n firstClientId = m.clientId;\n }\n\n let decoded: MessageNode<TMessage>[];\n try {\n decoded = decode(m);\n } catch (error) {\n settled = true;\n cleanup();\n const cause = error instanceof Ably.ErrorInfo ? error : undefined;\n reject(\n new Ably.ErrorInfo(\n `unable to look up input event; decode failed for invocation ${invocationId}: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.InputEventNotFound,\n 504,\n cause,\n ),\n );\n return;\n }\n for (const node of decoded) collected.push(node);\n rawMessages.push(m);\n if (matchedInputEventIds.size < expectedCount) return;\n settled = true;\n cleanup();\n // Sort by Ably serial ascending so callers see publish order regardless\n // of interleaved rewind+live delivery. Null serials sort last (defensive\n // — input events should always carry a serial).\n collected.sort(compareBySerial);\n logger?.debug('lookupInputEvents(); collected input events', {\n runId,\n invocationId,\n count: collected.length,\n });\n resolve({ nodes: collected, firstHeaders, firstClientId, rawMessages });\n });\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the register callback may have settled the promise synchronously during buffered input-event drain.\n if (settled) {\n // Sync drain inside register settled the promise; cleanup ran but\n // could not detach the listener because `unregister` was still the\n // no-op. Detach it now.\n unregister();\n return;\n }\n timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(\n new Ably.ErrorInfo(\n `unable to look up input event; received ${String(collected.length)} of ${String(expectedCount)} input events for invocation ${invocationId} within ${String(timeoutMs)}ms`,\n ErrorCode.InputEventNotFound,\n 504,\n ),\n );\n }, timeoutMs);\n });\n};\n\n// ---------------------------------------------------------------------------\n// Internal run record for cancel routing\n// ---------------------------------------------------------------------------\n\ninterface RegisteredRun {\n runId: string;\n /** Invocation-id this run is associated with, minted by the agent at `createRun` (or the `runtime.invocationId` override). */\n invocationId: string;\n controller: AbortController;\n /** Composite signal that fires when either the internal controller or the external signal aborts. */\n signal: AbortSignal;\n onCancel?: (request: CancelRequest) => Promise<boolean>;\n onError?: (error: Ably.ErrorInfo) => void;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state machines\n// ---------------------------------------------------------------------------\n\nenum SessionState {\n READY = 'ready',\n CLOSED = 'closed',\n}\n\nenum RunState {\n INITIALIZED = 'initialized',\n STARTED = 'started',\n ENDED = 'ended',\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-ST1\nclass DefaultAgentSession<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> implements AgentSession<TOutput, TProjection, TMessage> {\n private readonly _channel: Ably.RealtimeChannel;\n private readonly _codec: AgentSessionOptions<TInput, TOutput, TProjection, TMessage>['codec'];\n private readonly _logger: Logger | undefined;\n private readonly _onError: ((error: Ably.ErrorInfo) => void) | undefined;\n private readonly _runManager: RunManager;\n private readonly _registeredRuns = new Map<string, RegisteredRun>();\n /**\n * Reverse index from a run's triggering input codec-message-id to its\n * run-id, populated once `Run.start()`'s input-event lookup resolves the\n * triggering input. Lets `_handleCancelMessage` route a cancel keyed by the\n * input codec-message-id (a fresh send whose run-id the client doesn't know)\n * to the registered run. Entries are removed when the run ends / suspends /\n * the session closes, alongside `_registeredRuns`.\n */\n private readonly _runIdByInputCodecMessageId = new Map<string, string>();\n /**\n * Cancels buffered by triggering input codec-message-id when they arrived\n * before the run was known — i.e. before `Run.start()`'s input-event lookup\n * resolved that input to a run. A fresh run has no run-id at the client's\n * send time (the agent mints it at run-start), so an early cancel can only be\n * keyed by the input codec-message-id, and the `inputCodecMessageId → run`\n * linkage doesn't exist until the lookup completes. `Run.start()` consults\n * this buffer as a PULL once it resolves its `resolvedInputCodecMessageId`,\n * honouring any cancel that arrived first. Mirrors `_inputEventBuffer`: FIFO\n * eviction at `_inputEventBufferLimit` entries, cleared on `close()`.\n */\n private readonly _deferredCancels = new Map<string, Ably.InboundMessage>();\n /**\n * Active input-event lookups keyed by `event-id`. The channel listener\n * dispatches each input event to the lookup that registered for its\n * `event-id`, so that messages replayed via channel rewind (and live\n * messages alike) reach the right lookup without each lookup having to\n * subscribe separately, and without depending on a client-minted\n * `invocation-id`.\n */\n private readonly _pendingInputEventLookups = new Map<string, (msg: Ably.InboundMessage) => void>();\n /**\n * Input events buffered by `event-id` when no lookup callback was\n * registered at delivery time. Rewind replays user messages on attach —\n * before `run.start()` runs — so without buffering they would be dropped.\n * Each `event-id` maps to an ordered array so rewind redelivery of the\n * same event before registration is preserved (the lookup later dedupes by\n * serial). `_registerInputEventListener` drains the buffer on registration.\n * FIFO eviction at `_inputEventBufferLimit` event entries (each entry counts\n * once regardless of array length).\n */\n private readonly _inputEventBuffer = new Map<string, Ably.InboundMessage[]>();\n private readonly _inputEventBufferLimit: number;\n private readonly _channelListener: (msg: Ably.InboundMessage) => void;\n private readonly _inputEventLookupTimeoutMs: number;\n\n private _state = SessionState.READY;\n private _connectPromise: Promise<void> | undefined;\n private _hasAttachedOnce: boolean;\n private readonly _onChannelStateChange: Ably.channelEventCallback;\n\n constructor(options: AgentSessionOptions<TInput, TOutput, TProjection, TMessage>) {\n this._codec = options.codec;\n // Spec: AIT-ST1a, AIT-ST1a2 — register this SDK on both the connection\n // (options.agents) and channel-attach (params.agent) paths. Idempotent\n // across sessions sharing one client.\n const registerOptions = registerAgent(options.client, options.codec);\n // Attach with a rewind window (default 2m) so a freshly-constructed\n // agent session can locate an input event that was published before it\n // attached (closes the lookup race when a per-request agent is spun\n // up after the client has already POSTed). Tunable via\n // `AgentSessionOptions.rewindWindow`.\n const channelOptions: Ably.ChannelOptions = {\n params: { ...registerOptions.params, rewind: options.rewindWindow ?? '2m' },\n };\n this._channel = options.client.channels.get(options.channelName, channelOptions);\n this._logger = options.logger?.withContext({ component: 'AgentSession' });\n this._onError = options.onError;\n this._runManager = createRunManager(this._channel, this._logger);\n this._inputEventLookupTimeoutMs = options.inputEventLookupTimeoutMs ?? 30000;\n this._inputEventBufferLimit = options.inputEventBufferLimit ?? 200;\n\n this._channelListener = (msg: Ably.InboundMessage) => {\n this._handleChannelMessage(msg);\n };\n\n // Spec: AIT-ST12, AIT-ST12a\n // Listen for channel state changes that break message continuity. The\n // session only consumes cancel messages from the channel, so losing one\n // is survivable — but the developer needs to know so they can decide\n // whether to cancel in-flight work. _hasAttachedOnce is seeded from the\n // channel's current state so pre-attached channels are handled correctly;\n // it distinguishes the initial attach from a genuine discontinuity.\n this._hasAttachedOnce = this._channel.state === 'attached';\n this._onChannelStateChange = (stateChange: Ably.ChannelStateChange) => {\n this._handleChannelStateChange(stateChange);\n };\n this._channel.on(this._onChannelStateChange);\n\n this._logger?.debug('DefaultAgentSession(); session created');\n }\n\n // -------------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------------\n\n // Spec: AIT-ST2\n // eslint-disable-next-line @typescript-eslint/promise-function-async -- preserve reference equality across calls\n connect(): Promise<void> {\n if (this._state === SessionState.CLOSED) {\n return Promise.reject(new Ably.ErrorInfo('unable to connect; session is closed', ErrorCode.SessionClosed, 400));\n }\n if (this._connectPromise) return this._connectPromise;\n\n this._logger?.trace('DefaultAgentSession.connect();');\n // Subscribe unfiltered (before attach, per RTL7g — subscribe implicitly\n // attaches the channel). An unfiltered subscribe ensures that messages\n // replayed via channel rewind reach the dispatcher so input-event\n // lookups can match against them; the dispatcher then routes by name\n // (cancel vs. input event). A name-filtered subscribe would silently\n // drop replayed user messages because rewind delivers them to listeners\n // registered at attach time only.\n this._connectPromise = this._channel.subscribe(this._channelListener).then(\n () => {\n this._logger?.debug('DefaultAgentSession.connect(); subscribed and attached');\n },\n (error: unknown) => {\n const errInfo = new Ably.ErrorInfo(\n `unable to subscribe to channel; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.SessionSubscriptionError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger?.error('DefaultAgentSession.connect(); subscribe failed');\n this._onError?.(errInfo);\n throw errInfo;\n },\n );\n return this._connectPromise;\n }\n\n /**\n * Register a callback to receive the input events carrying any of the\n * given `eventIds`. Lookups must share the session's unfiltered\n * subscription rather than registering their own subscribe — Ably's\n * rewind only delivers to listeners present at attach time.\n *\n * The listener remains registered after the initial buffer drain so a\n * matching event that arrives live (rather than from the buffer) still\n * reaches the lookup until it unregisters itself. Today the only caller\n * registers a single trigger event-id; the array form keeps the\n * registration capable of awaiting several ids without changing callers.\n * @param eventIds - The `event-id`s this listener cares about.\n * @param callback - Invoked once per matching Ably message, in buffer-insertion order for drained entries.\n * @returns Unregister function. Safe to call multiple times.\n */\n private _registerInputEventListener(\n eventIds: readonly string[],\n callback: (msg: Ably.InboundMessage) => void,\n ): () => void {\n for (const eventId of eventIds) {\n this._pendingInputEventLookups.set(eventId, callback);\n }\n // Drain any buffered input events for these event-ids — rewind replays\n // user messages on attach before run.start() can register the callback.\n // Without this drain, the lookup waits the full\n // `inputEventLookupTimeoutMs` for a live arrival that never comes. Set\n // all listeners before draining so a drain that completes the lookup\n // synchronously cannot leave a later event-id unmapped.\n for (const eventId of eventIds) {\n const buffered = this._inputEventBuffer.get(eventId);\n if (buffered) {\n this._inputEventBuffer.delete(eventId);\n for (const m of buffered) callback(m);\n }\n }\n return () => {\n for (const eventId of eventIds) {\n if (this._pendingInputEventLookups.get(eventId) === callback) {\n this._pendingInputEventLookups.delete(eventId);\n }\n }\n };\n }\n\n // Spec: AIT-ST3\n createRun(invocation: Invocation, runtime?: RunRuntime<TOutput>): Run<TOutput, TProjection, TMessage> {\n this._logger?.trace('DefaultAgentSession.createRun();', { inputEventId: invocation.inputEventId });\n return this._createRun(invocation, runtime ?? {});\n }\n\n // Spec: AIT-ST11\n async close(): Promise<void> {\n if (this._state === SessionState.CLOSED) return;\n this._state = SessionState.CLOSED;\n this._logger?.trace('DefaultAgentSession.close();');\n if (this._connectPromise) {\n this._channel.unsubscribe(this._channelListener);\n }\n this._channel.off(this._onChannelStateChange);\n for (const reg of this._registeredRuns.values()) {\n reg.controller.abort();\n }\n this._registeredRuns.clear();\n this._runIdByInputCodecMessageId.clear();\n this._deferredCancels.clear();\n this._pendingInputEventLookups.clear();\n this._inputEventBuffer.clear();\n this._runManager.close();\n\n // Detach the channel this session attached. connect() subscribes (which\n // implicitly attaches), so we only detach when connect() ran. Best-effort:\n // a detach failure (e.g. the channel is already FAILED) must not throw out\n // of close().\n if (this._connectPromise) {\n try {\n await this._channel.detach();\n } catch (error) {\n // Swallowed (see above): a detach failure must not throw out of\n // close(). Logged at debug for observability.\n this._logger?.debug('DefaultAgentSession.close(); channel detach failed', { error });\n }\n }\n\n this._logger?.debug('DefaultAgentSession.close(); session closed');\n }\n\n // -------------------------------------------------------------------------\n // Cancel message routing\n // -------------------------------------------------------------------------\n\n private async _handleCancelMessage(msg: Ably.InboundMessage): Promise<void> {\n const headers = getTransportHeaders(msg);\n const runId = headers[HEADER_RUN_ID];\n const inputCodecMessageId = headers[HEADER_INPUT_CODEC_MESSAGE_ID];\n\n // Malformed cancel: drop with warn. A cancel must identify its target by\n // `run-id` (a continuation, whose run-id the client knows) and/or by\n // `input-codec-message-id` (a fresh send, before the agent minted the\n // run-id). Neither present means there is nothing to route to.\n if (!runId && !inputCodecMessageId) {\n this._logger?.warn('DefaultAgentSession._handleCancelMessage(); missing run-id and input-codec-message-id', {\n serial: msg.serial,\n });\n return;\n }\n\n // Primary path — match by run-id (continuations, whose run-id the client\n // already knows). Resolve the input-codec-message-id to a run-id when the\n // run-id wasn't supplied (a fresh-send cancel that arrived after the run's\n // input-event lookup resolved, so the linkage already exists).\n const resolvedRunId =\n runId ?? (inputCodecMessageId ? this._runIdByInputCodecMessageId.get(inputCodecMessageId) : undefined);\n const reg = resolvedRunId ? this._registeredRuns.get(resolvedRunId) : undefined;\n\n if (!reg) {\n // The run isn't known yet. A fresh-send cancel can race ahead of the\n // run's input-event lookup (which is what establishes the\n // input-codec-message-id → run linkage). Buffer it by\n // input-codec-message-id so `Run.start()` can pull and honour it once it\n // resolves the triggering input. A bare run-id cancel for an unknown run\n // is a no-op (the run never existed here, or already ended).\n if (inputCodecMessageId !== undefined) {\n this._bufferDeferredCancel(inputCodecMessageId, msg);\n }\n return;\n }\n\n await this._cancelRegistration(reg, msg);\n }\n\n /**\n * Buffer a cancel that arrived before its target run was known, keyed by the\n * triggering input's codec-message-id. FIFO-evicts the oldest entry at\n * `_inputEventBufferLimit` (mirroring `_inputEventBuffer`). A later cancel\n * for the same input replaces the earlier one — the intent is identical.\n * @param inputCodecMessageId - The triggering input's codec-message-id.\n * @param msg - The raw cancel message (passed to `onCancel`).\n */\n private _bufferDeferredCancel(inputCodecMessageId: string, msg: Ably.InboundMessage): void {\n const evicted = evictOldestIfFull(this._deferredCancels, inputCodecMessageId, this._inputEventBufferLimit);\n if (evicted !== undefined) {\n this._logger?.warn('DefaultAgentSession._bufferDeferredCancel(); deferred-cancel buffer full, dropping oldest', {\n evictedInputCodecMessageId: evicted,\n limit: this._inputEventBufferLimit,\n });\n }\n this._deferredCancels.set(inputCodecMessageId, msg);\n this._logger?.debug('DefaultAgentSession._bufferDeferredCancel(); buffered early cancel', {\n inputCodecMessageId,\n serial: msg.serial,\n });\n }\n\n /**\n * Pull and honour a cancel buffered before this run was known. Called from\n * `Run.start()` once the input-event lookup resolves the run's triggering\n * input codec-message-id — the point at which the\n * `input-codec-message-id → run` linkage first exists. No-op when no cancel\n * was buffered for that input.\n * @param reg - The now-known run registration.\n * @param inputCodecMessageId - The run's resolved triggering input codec-message-id.\n */\n private async _pullDeferredCancel(reg: RegisteredRun, inputCodecMessageId: string): Promise<void> {\n const buffered = this._deferredCancels.get(inputCodecMessageId);\n if (buffered === undefined) return;\n this._deferredCancels.delete(inputCodecMessageId);\n this._logger?.debug('DefaultAgentSession._pullDeferredCancel(); honouring buffered cancel', {\n runId: reg.runId,\n inputCodecMessageId,\n });\n await this._cancelRegistration(reg, buffered);\n }\n\n /**\n * Fire a cancel against a known run: consult its `onCancel` authorization\n * hook (if any), then abort the run's controller. Shared by the run-id match,\n * the input-codec-message-id match, and the buffered-cancel pull so all three\n * honour `onCancel` and surface handler errors identically.\n * @param reg - The target run registration.\n * @param msg - The raw cancel message (passed to `onCancel`).\n */\n private async _cancelRegistration(reg: RegisteredRun, msg: Ably.InboundMessage): Promise<void> {\n const { runId } = reg;\n this._logger?.debug('DefaultAgentSession._cancelRegistration(); matched run', { runId });\n\n const request: CancelRequest = { message: msg, runId };\n\n try {\n if (reg.onCancel) {\n const allowed = await reg.onCancel(request);\n if (!allowed) {\n this._logger?.debug('DefaultAgentSession._cancelRegistration(); cancel rejected by onCancel', {\n runId,\n });\n return;\n }\n }\n reg.controller.abort();\n this._logger?.debug('DefaultAgentSession._cancelRegistration(); run cancelled', { runId });\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to process cancel for run ${runId}; onCancel handler threw: ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.CancelListenerError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger?.error('DefaultAgentSession._cancelRegistration(); onCancel threw', { runId });\n (reg.onError ?? this._onError)?.(errInfo);\n }\n }\n\n // -------------------------------------------------------------------------\n // Channel state change handler\n // -------------------------------------------------------------------------\n\n // Spec: AIT-ST12, AIT-ST12a\n private _handleChannelStateChange(stateChange: Ably.ChannelStateChange): void {\n if (this._state === SessionState.CLOSED) return;\n\n const { current, resumed } = stateChange;\n\n // Track the initial attach so we don't treat it as a discontinuity\n if (current === 'attached' && !this._hasAttachedOnce) {\n this._hasAttachedOnce = true;\n return;\n }\n\n // Continuity-breaking states:\n // - FAILED, SUSPENDED, DETACHED: no more messages expected (or gap)\n // - ATTACHED with resumed: false (UPDATE): messages were lost\n const continuityLost =\n current === 'failed' || current === 'suspended' || current === 'detached' || (current === 'attached' && !resumed);\n\n if (!continuityLost) return;\n\n this._logger?.error('DefaultAgentSession._handleChannelStateChange(); channel continuity lost', {\n current,\n resumed,\n previous: stateChange.previous,\n });\n\n const err = new Ably.ErrorInfo(\n `unable to deliver cancel messages; channel continuity lost (${current}${current === 'attached' ? ', resumed: false' : ''})`,\n ErrorCode.ChannelContinuityLost,\n 500,\n stateChange.reason,\n );\n\n // Session-level notification only: continuity loss is not scoped to any\n // run. Per-run onError handlers are reserved for errors from that run's\n // own operations (publish failures, encoder errors). Developers that need\n // per-run reaction can iterate active runs from the session handler.\n this._onError?.(err);\n }\n\n // -------------------------------------------------------------------------\n // Channel subscription handler\n // -------------------------------------------------------------------------\n\n private _handleChannelMessage(msg: Ably.InboundMessage): void {\n try {\n if (msg.name === EVENT_CANCEL) {\n // Fire-and-forget async handler — errors are caught internally.\n this._handleCancelMessage(msg).catch((error: unknown) => {\n const errInfo = new Ably.ErrorInfo(\n `unable to route cancel message; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.CancelListenerError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger?.error('DefaultAgentSession._handleChannelMessage(); cancel routing error');\n this._onError?.(errInfo);\n });\n return;\n }\n\n // Dispatch client-published input events to the lookup registered\n // for their `event-id`. Every client-originated event in an\n // invocation (user-message AND amend events such as tool-approval\n // responses and client tool outputs) carries `event-id`; the lookup\n // waits for every promised id to arrive before letting the run start\n // LLM work. Routing by `event-id` rather than `invocation-id` keeps\n // the dispatcher independent of any client-minted invocation\n // identity. Server-side lifecycle messages (run-start, run-end,\n // cancel, error) never stamp `event-id`, so they're naturally\n // excluded.\n const headers = getTransportHeaders(msg);\n const eventId = headers[HEADER_EVENT_ID];\n if (eventId !== undefined) {\n const listener = this._pendingInputEventLookups.get(eventId);\n if (listener) {\n listener(msg);\n } else {\n // Buffer for a future `_registerInputEventListener` call. This is\n // load-bearing for the \"agent attaches after publish\" scenario\n // where channel rewind delivers user messages before\n // `run.start()` runs.\n const existing = this._inputEventBuffer.get(eventId);\n if (existing) {\n existing.push(msg);\n } else {\n // FIFO eviction: drop the oldest event entry (and all its buffered\n // redeliveries). Clients whose input event was evicted will fail\n // their lookup with `InputEventNotFound` — this warn is the only\n // operator-visible signal that capacity caused the failure.\n const evicted = evictOldestIfFull(this._inputEventBuffer, eventId, this._inputEventBufferLimit);\n if (evicted !== undefined) {\n this._logger?.warn(\n 'DefaultAgentSession._handleChannelMessage(); input-event buffer full, dropping oldest entry',\n { evictedEventId: evicted, limit: this._inputEventBufferLimit },\n );\n }\n this._inputEventBuffer.set(eventId, [msg]);\n }\n }\n }\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to process channel message; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.SessionSubscriptionError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger?.error('DefaultAgentSession._handleChannelMessage(); subscription error');\n this._onError?.(errInfo);\n }\n }\n\n // -------------------------------------------------------------------------\n // Connection guard\n // -------------------------------------------------------------------------\n\n private async _requireConnected(method: string): Promise<void> {\n if (!this._connectPromise) {\n throw new Ably.ErrorInfo(\n `unable to ${method}; connect() must be called before ${method}()`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n return this._connectPromise;\n }\n\n // -------------------------------------------------------------------------\n // Run creation\n // -------------------------------------------------------------------------\n\n private _createRun(invocation: Invocation, runtime: RunRuntime<TOutput>): Run<TOutput, TProjection, TMessage> {\n // The run-id is not carried in the invocation body — the agent mints it.\n // Mint a provisional id now (or take the `runtime.runId` override for\n // tests / in-process drivers) — this IS the id for a fresh run. A\n // continuation overrides it in `Run.start()` with the existing run-id read\n // off the triggering input event's wire headers (the run it re-enters).\n // Mirrors the invocationId mint below.\n let runId = runtime.runId ?? crypto.randomUUID();\n // The agent mints the invocation id — one per HTTP request that invokes\n // it. A per-run override (runtime.invocationId) supports deterministic ids\n // in tests and in-process drivers.\n const invocationId = runtime.invocationId ?? crypto.randomUUID();\n const inputEventLookupTimeoutMs = this._inputEventLookupTimeoutMs;\n const { onMessage, onCancelled, onCancel, onError: runOnError, signal: externalSignal } = runtime;\n\n const controller = new AbortController();\n let state = RunState.INITIALIZED;\n\n // Compose the internal controller signal with the external signal (e.g.\n // req.signal) so platform-level cancellation (request cancellation, function\n // timeout) cancels the run through the same path as Ably cancel messages.\n const signal = externalSignal ? AbortSignal.any([controller.signal, externalSignal]) : controller.signal;\n\n // Spec: AIT-ST3a — register immediately so `close()` aborts an in-flight\n // start() and a post-lookup cancel can fire the AbortSignal. Keyed by the\n // provisional run-id; a continuation re-keys to the real id in start()\n // once the triggering input reveals it.\n const registration: RegisteredRun = {\n runId,\n invocationId,\n controller,\n signal,\n onCancel,\n onError: runOnError,\n };\n this._registeredRuns.set(runId, registration);\n\n // Capture instance members as locals so arrow functions close over them\n // without needing `this` (avoids unicorn/no-this-assignment).\n const logger = this._logger;\n const runManager = this._runManager;\n const codec = this._codec;\n const channel = this._channel;\n const registeredRuns = this._registeredRuns;\n const runIdByInputCodecMessageId = this._runIdByInputCodecMessageId;\n const deferredCancels = this._deferredCancels;\n const requireConnected = this._requireConnected.bind(this);\n const registerInputEventListener = this._registerInputEventListener.bind(this);\n const pullDeferredCancel = this._pullDeferredCancel.bind(this);\n const inputEventId = invocation.inputEventId;\n\n // `viewMessages` starts empty. `Run.start()` populates it via the\n // channel-rewind input-event lookup, pulling in user-message MessageNodes\n // as they arrive on the channel.\n const viewMessages: MessageNode<TMessage>[] = [];\n const view: RunView<TMessage> = {\n get messages() {\n return viewMessages;\n },\n };\n\n // Per-run metadata resolved from the input-event lookup result. The first\n // matched wire message's headers carry the run's `clientId`, `parent`, and\n // `forkOf`, and — for a continuation — the `run-id` it re-enters (a fresh\n // input carries none; the client stamps a run-id only when re-entering a\n // run it already knows). Its Ably-level publisher `clientId` becomes the\n // `inputClientId` re-stamped on the agent's own publishes. Captured\n // separately from `viewMessages` because tool-resolution wire messages\n // (`tool-output-available` etc.) decode to chunks and produce zero\n // MessageNodes — the metadata still needs to surface.\n let resolvedClientId: string | undefined;\n let resolvedInputClientId: string | undefined;\n let resolvedParent: string | undefined;\n let resolvedForkOf: string | undefined;\n let resolvedRegenerates: string | undefined;\n let resolvedInputCodecMessageId: string | undefined;\n let resolvedContinuation = false;\n let firstLookupHeaders: Record<string, string> | undefined;\n /**\n * The reply run's structural-parent fallback, computed once in\n * `Run.start()` (after the input-event lookup has populated `viewMessages`)\n * and consumed by every `Run.pipe()` publish. A per-stream\n * `streamOpts.parent` still overrides it. Storing it here keeps it stable\n * across pipes and decouples the assistant's structural parent from the\n * run-start wire's own `parent`.\n */\n let assistantParentFallback: string | undefined;\n /**\n * Raw Ably messages observed live by the input-event lookup. Passed to\n * `loadRunProjection` so the just-published client wires don't need\n * to wait on Ably's channel history indexing window. Empty when no\n * lookup ran or no messages matched.\n */\n let liveLookupMessages: readonly Ably.InboundMessage[] | undefined;\n\n /**\n * Remove this run from the session's routing maps. Drops the\n * `_registeredRuns` entry plus the `input-codec-message-id → run-id`\n * reverse index (and any stale deferred cancel still buffered for that\n * input), keeping the cancel-routing state consistent when the run ends,\n * suspends, or its start fails.\n */\n const deregisterRun = (): void => {\n registeredRuns.delete(runId);\n if (resolvedInputCodecMessageId !== undefined) {\n runIdByInputCodecMessageId.delete(resolvedInputCodecMessageId);\n deferredCancels.delete(resolvedInputCodecMessageId);\n }\n };\n\n // Most recently loaded projection for this run only, cached by\n // `Run.loadProjection()` and `Run.loadConversation()` so the `messages`\n // getter can return the run's folded messages. `undefined` before any\n // load call; the getter then falls back to the live `viewMessages`.\n let cachedProjection: TProjection | undefined;\n\n // Full multi-turn conversation, set by `Run.loadConversation()`. When set,\n // it takes priority over `cachedProjection` in the `messages` getter —\n // the getter then returns the complete ancestor-chain + current-run\n // messages instead of the current run alone.\n let cachedConversation: TMessage[] | undefined;\n\n const run: Run<TOutput, TProjection, TMessage> = {\n get runId() {\n return runId;\n },\n get invocationId() {\n return invocationId;\n },\n get abortSignal() {\n return signal;\n },\n get view() {\n return view;\n },\n get messages() {\n if (cachedConversation !== undefined) {\n return [...cachedConversation];\n }\n if (cachedProjection !== undefined) {\n return codec.getMessages(cachedProjection).map((m) => m.message);\n }\n return viewMessages.map((n) => n.message);\n },\n\n // Spec: AIT-ST4, AIT-ST4a, AIT-ST4b\n start: async (): Promise<void> => {\n logger?.trace('Run.start();', { runId, inputEventId });\n\n await requireConnected('start');\n\n // Spec: AIT-ST4a\n if (signal.aborted) {\n throw new Ably.ErrorInfo(\n `unable to start run; run ${runId} was cancelled before start()`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n if (state !== RunState.INITIALIZED) return;\n state = RunState.STARTED;\n\n // Look up the triggering input event on the channel so the agent\n // can read the user's message and per-run metadata (parent, forkOf,\n // continuation flag) before publishing run-start. Skip when\n // inputEventLookupTimeoutMs === 0 (tests and in-process drivers) or\n // when no inputEventId is set (invocation requires no channel lookup).\n if (inputEventId && inputEventLookupTimeoutMs > 0) {\n try {\n const found = await lookupInputEvents<TInput, TOutput, TProjection, TMessage>({\n register: (callback) => registerInputEventListener([inputEventId], callback),\n codec,\n invocationId,\n runId,\n expectedInputEventIds: [inputEventId],\n timeoutMs: inputEventLookupTimeoutMs,\n signal,\n logger,\n });\n for (const m of found.nodes) viewMessages.push(m);\n if (found.firstHeaders !== undefined) firstLookupHeaders = found.firstHeaders;\n if (found.firstClientId !== undefined) resolvedInputClientId = found.firstClientId;\n liveLookupMessages = found.rawMessages;\n } catch (error) {\n const errInfo =\n error instanceof Ably.ErrorInfo\n ? error\n : new Ably.ErrorInfo(\n `unable to look up input event; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.InputEventNotFound,\n 504,\n );\n // The rejection bubbles up to the developer's HTTP handler,\n // which surfaces the failure as a non-2xx response — that is\n // the signal the client sees. No channel publish: an\n // `ai-run-end` without a preceding `ai-run-start` would break\n // the lifecycle invariant for other channel observers.\n deregisterRun();\n logger?.error('Run.start(); input-event lookup failed', { runId, invocationId });\n throw errInfo;\n }\n }\n\n // Resolve per-run metadata from the first matched wire message's\n // headers — they carry `clientId`, `parent`, and `forkOf`.\n // Continuations of a suspended run pick up the suspended assistant's\n // parent in the same headers (the continuation wire message parents off\n // the assistant). A `run-id` on the triggering input marks a\n // continuation (re-entry via `ai-run-resume`); a fresh input carries\n // none and opens the run with `ai-run-start`. Fall back to the first\n // MessageNode's headers for the path where the lookup ran with\n // `viewMessages` already populated and no `firstHeaders` was captured.\n const sourceHeaders = firstLookupHeaders ?? viewMessages[0]?.headers;\n if (sourceHeaders) {\n resolvedClientId = sourceHeaders[HEADER_RUN_CLIENT_ID];\n resolvedParent = sourceHeaders[HEADER_PARENT];\n resolvedForkOf = sourceHeaders[HEADER_FORK_OF];\n resolvedRegenerates = sourceHeaders[HEADER_MSG_REGENERATE];\n resolvedInputCodecMessageId = sourceHeaders[HEADER_CODEC_MESSAGE_ID];\n\n // The triggering input's run-id (if any) IS this run's identity.\n // Present → a continuation re-entering that run: adopt the id,\n // overriding the provisional one minted at construction, and re-key\n // the registration so cancel routing / deregistration resolve to the\n // real run. Absent → a fresh run: the provisional id stands and the\n // run opens with run-start.\n const wireRunId = sourceHeaders[HEADER_RUN_ID];\n resolvedContinuation = wireRunId !== undefined;\n if (wireRunId !== undefined && wireRunId !== runId) {\n registeredRuns.delete(runId);\n runId = wireRunId;\n registration.runId = runId;\n registeredRuns.set(runId, registration);\n }\n }\n\n // Compute the reply run's structural-parent fallback now that the\n // lookup has populated `viewMessages`: the triggering user message,\n // or — for regenerate wires that match by inputEventId but produce no\n // MessageNodes — the input wire's own `parent`. `Run.pipe()` consumes\n // this for every assistant publish.\n assistantParentFallback = viewMessages.at(-1)?.codecMessageId ?? resolvedParent;\n\n // The triggering input's codec-message-id is now resolved, so the\n // `input-codec-message-id → run` linkage exists: index it for live\n // cancels and pull any cancel that arrived before the run was known\n // (a fresh-send cancel published before the agent minted this run-id).\n // Honouring it here may abort the controller before run-start; that is\n // fine — the abort propagates through the same signal a normal cancel\n // would use.\n if (resolvedInputCodecMessageId !== undefined) {\n runIdByInputCodecMessageId.set(resolvedInputCodecMessageId, runId);\n await pullDeferredCancel(registration, resolvedInputCodecMessageId);\n }\n\n try {\n await runManager.startRun(runId, resolvedClientId, controller, {\n // Stamp the reply run's STRUCTURAL parent (its input node, M_user) —\n // the same value the output path stamps — not the input wire's own\n // parent. Makes `parent` structural on every wire so the Tree's two\n // creation paths agree regardless of arrival order. Valid only now\n // that M_user is a separate input node (the two-node flip).\n parent: assistantParentFallback,\n forkOf: resolvedForkOf,\n regenerates: resolvedRegenerates,\n invocationId,\n inputClientId: resolvedInputClientId,\n inputCodecMessageId: resolvedInputCodecMessageId,\n continuation: resolvedContinuation,\n });\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to publish run-start for run ${runId}; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.RunLifecycleError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n logger?.error('Run.start(); failed to publish run-start', { runId });\n throw errInfo;\n }\n\n logger?.debug('Run.start(); run started', { runId, inputEventId });\n },\n\n // Spec: AIT-ST5c\n addEvents: async (nodes: EventsNode<TOutput>[]): Promise<void> => {\n logger?.trace('Run.addEvents();', { runId, count: nodes.length });\n\n await requireConnected('addEvents');\n\n if (state === RunState.INITIALIZED) {\n throw new Ably.ErrorInfo(\n `unable to add events; start() must be called before addEvents() (run ${runId})`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n const runOwnerClientId = runManager.getClientId(runId);\n\n try {\n for (const node of nodes) {\n const headers = buildTransportHeaders({\n role: 'assistant',\n runId,\n codecMessageId: node.codecMessageId,\n runClientId: runOwnerClientId,\n invocationId,\n inputClientId: resolvedInputClientId,\n inputCodecMessageId: resolvedInputCodecMessageId,\n });\n\n const encoder = codec.createEncoder(channel, {\n extras: { headers },\n onMessage,\n });\n\n for (const event of node.events) {\n await encoder.publishOutput(event);\n }\n\n await encoder.close();\n }\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to publish events for run ${runId}; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.RunLifecycleError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n logger?.error('Run.addEvents(); publish failed', { runId });\n throw errInfo;\n }\n\n logger?.debug('Run.addEvents(); events published', { runId, count: nodes.length });\n },\n\n loadProjection: async (): Promise<TProjection> => {\n logger?.trace('Run.loadProjection();', { runId });\n await requireConnected('loadProjection');\n const projection = await loadRunProjection<TInput, TOutput, TProjection, TMessage>({\n channel,\n codec,\n runId,\n signal,\n logger,\n liveMessages: liveLookupMessages,\n });\n cachedProjection = projection;\n return projection;\n },\n\n loadConversation: async (options?: LoadConversationOptions): Promise<TMessage[]> => {\n logger?.trace('Run.loadConversation();', { runId });\n await requireConnected('loadConversation');\n const { messages, projection } = await loadConversation<TInput, TOutput, TProjection, TMessage>({\n channel,\n codec,\n runId,\n signal,\n logger,\n liveMessages: liveLookupMessages,\n assistantParentFallback,\n pageLimit: options?.pageLimit ?? 200,\n maxMessages: options?.maxMessages ?? 2000,\n });\n cachedProjection = projection;\n cachedConversation = messages;\n return messages;\n },\n\n // Spec: AIT-ST6, AIT-ST6a, AIT-ST6b, AIT-ST6b1, AIT-ST6b2, AIT-ST6b3, AIT-ST6c\n pipe: async (stream: ReadableStream<TOutput>, streamOpts?: PipeOptions<TOutput>): Promise<StreamResult> => {\n logger?.trace('Run.pipe();', { runId });\n\n await requireConnected('pipe');\n\n if (state === RunState.INITIALIZED) {\n throw new Ably.ErrorInfo(\n `unable to pipe stream; start() must be called before pipe() (run ${runId})`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n const runOwnerClientId = runManager.getClientId(runId);\n\n // The assistant message's parent: an explicit per-stream\n // `streamOpts.parent` from the caller, else the reply run's\n // structural-parent fallback computed once at run-start\n // (`assistantParentFallback` — the triggering user message, or the\n // input wire's own parent for regenerate wires that produced no\n // MessageNodes). Owning the default here means agent routes don't have\n // to pass `{ parent: lastUserCodecMessageId }` to keep tree threading\n // correct; edit-then-regenerate sibling resolution relies on the\n // user→assistant chain being explicit.\n const assistantParent = streamOpts?.parent ?? assistantParentFallback;\n const assistantForkOf = streamOpts?.forkOf ?? resolvedForkOf;\n // Echo `msg-regenerate` on the assistant wire so that a\n // client receiving the assistant chunk before `ai-run-start`\n // (e.g. via history pagination across a page boundary, or a lost\n // lifecycle publish) can still populate `RunNode.regeneratesCodecMessageId`\n // when creating the Run from headers. Mirrors the symmetric\n // behaviour for `assistantForkOf` on edit runs.\n const assistantRegenerates = resolvedRegenerates;\n\n const codecMessageId = crypto.randomUUID();\n const defaultHeaders = buildTransportHeaders({\n role: 'assistant',\n runId,\n codecMessageId,\n runClientId: runOwnerClientId,\n parent: assistantParent,\n forkOf: assistantForkOf,\n invocationId,\n inputClientId: resolvedInputClientId,\n inputCodecMessageId: resolvedInputCodecMessageId,\n regenerates: assistantRegenerates,\n });\n const encoder = codec.createEncoder(channel, {\n extras: { headers: defaultHeaders },\n onMessage,\n messageId: codecMessageId,\n });\n\n const result = await pipeStream(stream, encoder, signal, onCancelled, streamOpts?.resolveWriteOptions, logger);\n\n if (result.error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to pipe response for run ${runId}; ${result.error.message}`,\n ErrorCode.StreamError,\n 500,\n result.error instanceof Ably.ErrorInfo ? result.error : undefined,\n );\n logger?.error('Run.pipe(); stream error', { runId });\n runOnError?.(errInfo);\n }\n\n logger?.debug('Run.pipe(); stream finished', { runId, reason: result.reason });\n return result;\n },\n\n suspend: async (): Promise<void> => {\n logger?.trace('Run.suspend();', { runId });\n\n await requireConnected('suspend');\n\n if (state === RunState.INITIALIZED) {\n throw new Ably.ErrorInfo(\n `unable to suspend run; start() must be called before suspend() (run ${runId})`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n // ENDED is the terminal state for either an end or a suspend on this\n // Run instance; a second terminal call is a no-op.\n if (state === RunState.ENDED) return;\n state = RunState.ENDED;\n\n try {\n await runManager.suspendRun(runId, invocationId, resolvedInputClientId, resolvedInputCodecMessageId);\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to publish run-suspend for run ${runId}; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.RunLifecycleError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n logger?.error('Run.suspend(); failed to publish run-suspend', { runId });\n throw errInfo;\n } finally {\n deregisterRun();\n }\n\n logger?.debug('Run.suspend(); run suspended', { runId });\n },\n\n // Spec: AIT-ST7, AIT-ST7a, AIT-ST7b\n end: async (reason: RunEndReason): Promise<void> => {\n logger?.trace('Run.end();', { runId, reason });\n\n await requireConnected('end');\n\n if (state === RunState.INITIALIZED) {\n throw new Ably.ErrorInfo(\n `unable to end run; start() must be called before end() (run ${runId})`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n if (state === RunState.ENDED) return;\n state = RunState.ENDED;\n\n try {\n await runManager.endRun(runId, reason, invocationId, resolvedInputClientId, resolvedInputCodecMessageId);\n } catch (error) {\n const errInfo = new Ably.ErrorInfo(\n `unable to publish run-end for run ${runId}; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.RunLifecycleError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n logger?.error('Run.end(); failed to publish run-end', { runId });\n throw errInfo;\n } finally {\n deregisterRun();\n }\n\n logger?.debug('Run.end(); run ended', { runId, reason });\n },\n };\n\n return run;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create an agent (server-side) session bound to the given Realtime client\n * and channel name. The caller owns the client's lifecycle; the session\n * owns its channel.\n * @param options - Session configuration.\n * @returns A new {@link AgentSession} instance.\n */\nexport const createAgentSession = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(\n options: AgentSessionOptions<TInput, TOutput, TProjection, TMessage>,\n): AgentSession<TOutput, TProjection, TMessage> => new DefaultAgentSession(options);\n","/**\n * Invocation — value object wrapping the JSON body that a client sends to\n * an agent's HTTP endpoint to start a run.\n *\n * The data shape is the wire contract; the {@link Invocation} class is a\n * runtime view of that data with the same fields. {@link Invocation.fromJSON}\n * is the entry point used by agent handlers:\n *\n * ```ts\n * const data = (await req.json()) as InvocationData;\n * const invocation = Invocation.fromJSON(data);\n * const run = session.createRun(invocation, { signal: req.signal });\n * await run.start();\n * await run.loadProjection(); // fetch run projection from the channel\n * const messages = run.messages;\n * ```\n *\n * The body carries only what the agent needs out-of-band before the channel\n * is observable: the session/channel name and the `inputEventId` that triggered\n * the invocation. The agent mints the `invocationId` itself (one per HTTP\n * request) and returns it on the HTTP response, so it is not a body field. Run\n * identity also lives on the channel: the agent mints the `runId` for a fresh\n * run and reads the existing `runId` off the triggering input event for a\n * continuation — so the body carries no run-id either. Per-message metadata —\n * `clientId`, `parent`, `forkOf`, continuation status — likewise lives on the\n * channel and is resolved by the agent from the triggering input event, not\n * from the body. The `inputClientId` the agent re-stamps on its own publishes\n * comes from the publisher's Ably `clientId` on the matched input event, not\n * from a body field.\n */\n\n// ---------------------------------------------------------------------------\n// Wire shape\n// ---------------------------------------------------------------------------\n\n/**\n * Wire shape of a single invocation — the JSON body sent from the client\n * transport's HTTP POST to the agent endpoint.\n */\nexport interface InvocationData {\n /**\n * Identifier for the specific input event on the channel that triggered\n * this invocation. The agent locates the event via the `event-id`\n * header. Its wire headers carry the run-id for a continuation (absent for\n * a fresh run), so run identity is resolved from the channel, not the body.\n */\n inputEventId: string;\n /** Logical name of the session (chat) — used as the Ably channel name. */\n sessionName: string;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime view\n// ---------------------------------------------------------------------------\n\n/**\n * Runtime view of an {@link InvocationData}. Constructed via\n * {@link Invocation.fromJSON}. Read-only; carries no behaviour beyond\n * exposing its fields.\n */\n// Spec: AIT-ST13\nexport class Invocation {\n /**\n * Identifier for the specific input event on the channel that triggered\n * this invocation. Run identity is resolved from that event's wire headers\n * (or minted), not from the body.\n */\n readonly inputEventId: string;\n /** Logical name of the session (chat). Used as the Ably channel name. */\n readonly sessionName: string;\n\n private constructor(data: InvocationData) {\n this.inputEventId = data.inputEventId;\n this.sessionName = data.sessionName;\n }\n\n /**\n * Build an Invocation from its JSON wire shape.\n * @param data - Parsed JSON body matching {@link InvocationData}.\n * @returns A new Invocation exposing the same fields.\n */\n static fromJSON(data: InvocationData): Invocation {\n return new Invocation(data);\n }\n\n /**\n * Serialise this invocation to its JSON wire shape — the body a client\n * POSTs to the agent's endpoint to wake a run. Round-trips through\n * {@link Invocation.fromJSON}.\n * @returns The {@link InvocationData} carrying this invocation's identity.\n */\n toJSON(): InvocationData {\n return {\n inputEventId: this.inputEventId,\n sessionName: this.sessionName,\n };\n }\n}\n","/**\n * Tree — materializes a branching conversation as a forest of nodes. Each turn\n * is two nodes: a user {@link InputNode} keyed by its client-owned\n * codec-message-id and an agent {@link RunNode} keyed by the agent-minted\n * run-id, parented to the input node.\n *\n * Each node holds a per-node codec {@link TProjection} which the Tree folds\n * from inbound events. The Tree owns the complete conversation state across\n * every observed node. The {@link View} walks the parent chain to extract a\n * flat message list for rendering.\n *\n * `applyMessage()` is the entry point for inbound channel messages — it\n * classifies a run-less user input into an input node (keyed by\n * codec-message-id) or routes a run-bearing wire to its reply run (keyed by\n * run-id), folds events into that node's projection, and maintains a secondary\n * `codecMessageId -> nodeKey` index. `applyRunLifecycle()` handles run-start /\n * run-suspend / run-resume / run-end events.\n *\n * Sibling structure: editing a prompt produces a sibling input node linked by\n * {@link InputNode.forkOf}; regenerating a reply produces a sibling reply run\n * sharing the same input-node parent (no fork-of).\n */\n\nimport type * as Ably from 'ably';\n\nimport {\n HEADER_CODEC_MESSAGE_ID,\n HEADER_FORK_OF,\n HEADER_INPUT_CODEC_MESSAGE_ID,\n HEADER_INVOCATION_ID,\n HEADER_MSG_REGENERATE,\n HEADER_PARENT,\n HEADER_ROLE,\n HEADER_RUN_CLIENT_ID,\n HEADER_RUN_ID,\n} from '../../constants.js';\nimport { EventEmitter } from '../../event-emitter.js';\nimport type { Logger } from '../../logger.js';\nimport type { CodecInputEvent, CodecOutputEvent, Reducer } from '../codec/types.js';\nimport type { ConversationNode, InputNode, OutputEvent, RunLifecycleEvent, RunNode, Tree } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Internal node type\n// ---------------------------------------------------------------------------\n\ninterface InternalNode<TProjection> {\n node: ConversationNode<TProjection>;\n /** Insertion sequence — tiebreaker for nodes with no sort serial (optimistic). */\n insertSeq: number;\n}\n\n/**\n * The primary key a node is indexed under: a reply run's `runId`, or an input\n * node's `codecMessageId` (the client owns it before the agent mints a runId).\n * @param node - The node to key.\n * @returns The node's primary key.\n */\nexport const nodeKey = <TProjection>(node: ConversationNode<TProjection>): string =>\n node.kind === 'run' ? node.runId : node.codecMessageId;\n\n/**\n * The serial a node sorts by: a reply run's `startSerial`, an input node's\n * `serial`. Undefined for an optimistic (not-yet-acked) node, which tail-sorts.\n * @param node - The node to read.\n * @returns The sort serial, or undefined for an optimistic node.\n */\nconst sortSerial = <TProjection>(node: ConversationNode<TProjection>): string | undefined =>\n node.kind === 'run' ? node.startSerial : node.serial;\n\n/**\n * Add a value to a `Map<K, Set<V>>`, creating the bucket Set on first use.\n * @param map - The Map to mutate.\n * @param key - The bucket key.\n * @param value - The value to add.\n */\nconst addToSetMap = <K, V>(map: Map<K, Set<V>>, key: K, value: V): void => {\n let set = map.get(key);\n if (!set) {\n set = new Set();\n map.set(key, set);\n }\n set.add(value);\n};\n\n/**\n * Remove a value from a `Map<K, Set<V>>`, dropping the bucket when it empties.\n * @param map - The Map to mutate.\n * @param key - The bucket key.\n * @param value - The value to remove.\n */\nconst deleteFromSetMap = <K, V>(map: Map<K, Set<V>>, key: K, value: V): void => {\n const set = map.get(key);\n if (!set) return;\n set.delete(value);\n if (set.size === 0) map.delete(key);\n};\n\n// ---------------------------------------------------------------------------\n// Internal interface — extended surface consumed by View / ClientSession\n// ---------------------------------------------------------------------------\n\n/** Internal tree surface used by View and ClientSession — not part of the public Tree API. */\nexport interface TreeInternal<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n> extends Tree<TOutput, TProjection> {\n /**\n * Walk the visible node chain (both input nodes and reply runs) along the\n * selected branches, in chronological order. The View renders from this.\n * @param selections - Per-group selected member key, keyed by group root.\n * @returns The visible nodes in chronological order.\n */\n visibleNodes(selections?: Map<string, string>): ConversationNode<TProjection>[];\n\n /**\n * Get the \"group root\" key for a sibling group — the stable key the\n * selection map is keyed by (the earliest edit version for input nodes, the\n * original reply for a regenerate group).\n */\n getGroupRoot(key: string): string;\n\n /**\n * The reply runs parented at an input node (its codec-message-id), in\n * iteration order. Empty when none have been observed. Used to resolve a\n * user prompt to its reply run(s).\n * @param inputCodecMessageId - The input node's codec-message-id.\n * @returns The reply runs parented at that input.\n */\n getReplyRuns(inputCodecMessageId: string): RunNode<TProjection>[];\n\n /**\n * Apply an inbound channel message to the tree.\n *\n * Classifies the message and routes it to the owning node:\n * 1. Run-less user input (no run-id, a `user`-role message carrying a\n * codec-message-id and input events): creates or promotes the input node\n * keyed by that codec-message-id, folds the input events.\n * 2. Run-bearing wire (assistant output, continuation tool-resolution, or a\n * fresh agent-minted run): routes to the reply run by run-id (reconciling\n * an optimistic insert by codec-message-id), folds events.\n * @param events - Decoded codec events, split by wire direction. Both are\n * folded into the node's projection, inputs first.\n * @param events.inputs - Client-published events (`ai-input` wire).\n * @param events.outputs - Agent-published events (`ai-output` wire).\n * @param headers - Transport headers from the inbound Ably message.\n * @param serial - Ably channel serial; undefined for optimistic inserts.\n */\n applyMessage(\n events: { inputs: TInput[]; outputs: TOutput[] },\n headers: Record<string, string>,\n serial?: string,\n ): void;\n\n /**\n * Apply a run-lifecycle event.\n *\n * - `start`: creates the reply run (if missing) or, for an existing run,\n * sets RunNode.status to 'active', promotes startSerial, and backfills\n * structural metadata (parent / forkOf / regenerates / invocationId).\n * - `suspend`: sets RunNode.status to 'suspended' and records `endSerial`.\n * The run stays live so a resume under the same `runId` picks up where it\n * left off.\n * - `resume`: re-activates an existing suspended Run (status back to\n * 'active') without touching its structure or serials — a pure re-entry\n * signal. A no-op if the Run is not yet known.\n * - `end`: sets RunNode.status to the terminal reason and records\n * `endSerial`.\n *\n * Always emits a 'run' event to subscribers.\n * @param event - Lifecycle event payload, including the channel serial.\n */\n applyRunLifecycle(event: RunLifecycleEvent): void;\n\n /**\n * Get the node keyed by `key`, or undefined if `key` names no node. The\n * key is a {@link nodeKey} — a runId (reply run) or an input node's\n * codec-message-id — so the result is a {@link ConversationNode} union:\n * narrow on `kind` before reading kind-specific fields. Pairs with\n * {@link getNodeByCodecMessageId}, which resolves an arbitrary owned\n * codec-message-id (including an assistant message's) to its node.\n * @param key - The node key to look up.\n * @returns The node, or undefined if not found.\n */\n getNode(key: string): ConversationNode<TProjection> | undefined;\n\n /**\n * Remove a node from the tree by its key ({@link nodeKey} — a runId or an\n * input node's codec-message-id). Children become unreachable because their\n * parent is no longer on the active path.\n * @param key - The node key to remove.\n */\n delete(key: string): void;\n\n /** Forward a raw Ably message event to tree subscribers. */\n emitAblyMessage(msg: Ably.InboundMessage): void;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n/** EventEmitter events map for the tree. */\ninterface TreeEventsMap<TOutput extends CodecOutputEvent> {\n update: undefined;\n 'ably-message': Ably.InboundMessage;\n run: RunLifecycleEvent;\n output: OutputEvent<TOutput>;\n}\n\n// Spec: AIT-CT13\nexport class DefaultTree<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n> implements TreeInternal<TInput, TOutput, TProjection> {\n private readonly _codec: Reducer<TInput | TOutput, TProjection>;\n private readonly _logger: Logger;\n private readonly _emitter: EventEmitter<TreeEventsMap<TOutput>>;\n\n /**\n * All nodes indexed by their primary key ({@link nodeKey}): a reply run's\n * runId, or an input node's codec-message-id.\n */\n private readonly _nodeIndex = new Map<string, InternalNode<TProjection>>();\n\n /**\n * Maps every observed `codec-message-id` to its owning node's key\n * ({@link nodeKey}). For a reply run that is the runId of every message the\n * run published; for an input node it is the input's own codec-message-id.\n * Resolves fork-of / parent codec-message-ids to node keys, routes\n * continuation amend wires to existing nodes, and backs UI lookups that hold\n * a codec-message-id.\n */\n private readonly _codecMessageIdToNodeKey = new Map<string, string>();\n\n /**\n * All nodes sorted by their sort serial ({@link sortSerial}: `startSerial`\n * for runs, `serial` for input nodes), lexicographically. Nodes with no sort\n * serial (optimistic) sort after all serial-bearing nodes, ordered among\n * themselves by insertion sequence.\n */\n private readonly _sortedNodes: InternalNode<TProjection>[] = [];\n\n /**\n * Parent index: parent node key (the key its children's\n * `parentCodecMessageId` resolves to) to the set of child node keys. Root\n * nodes (no parent) are indexed under the key `undefined`. Kind-blind — a\n * reply run and an input node parent off each other through the same index.\n */\n private readonly _parentIndex = new Map<string | undefined, Set<string>>();\n\n /**\n * Reverse edge: an input node's codec-message-id to the set of reply-run ids\n * parented at it. Lets the View resolve a user prompt to its (selected) reply\n * run, and groups regenerate siblings (which all parent at the same input\n * node).\n */\n private readonly _replyRunsByInput = new Map<string, Set<string>>();\n\n /** Monotonically increasing counter for insertion sequence. */\n private _seqCounter = 0;\n\n /** Incremented on structural changes; unchanged on projection-only updates. */\n private _structuralVersion = 0;\n\n /**\n * Cached sibling-group lookups keyed by node key. The walk over forkOf\n * chains and the per-parent fan-out are pure functions of the node\n * graph, so the cache is keyed against {@link _structuralVersion}:\n * any topology mutation drops the cache and the next lookup\n * recomputes. Hits matter most during a single render pass where\n * the View calls `getSiblingNodes` once per visible node plus extra\n * per-message branch-anchor probes from React components.\n */\n private _siblingCache = new Map<string, InternalNode<TProjection>[]>();\n private _siblingCacheVersion = -1;\n\n constructor(codec: Reducer<TInput | TOutput, TProjection>, logger: Logger) {\n this._codec = codec;\n this._logger = logger;\n this._emitter = new EventEmitter<TreeEventsMap<TOutput>>(logger);\n }\n\n // -------------------------------------------------------------------------\n // Sorted list maintenance\n // -------------------------------------------------------------------------\n\n /**\n * Compare two nodes (Run or input) for sorted list ordering.\n * Serial-bearing nodes sort by their sort serial (`startSerial` for runs,\n * `serial` for input nodes), lexicographically.\n * Nodes with no sort serial sort after all serial-bearing nodes.\n * Among them, sort by insertion sequence.\n *\n * Optimistic (null-serial) nodes intentionally tail-sort so they reorder\n * into place when the server relay arrives and `applyMessage` promotes\n * startSerial — see {@link applyMessage}'s `_removeSortedNode` /\n * `_insertSortedNode` pair on the promotion path.\n * @param a - First node to compare.\n * @param b - Second node to compare.\n * @returns Negative if a sorts before b, positive if after, zero if equal.\n */\n // Spec: AIT-CT13a\n private _compareNodes(a: InternalNode<TProjection>, b: InternalNode<TProjection>): number {\n const sa = sortSerial(a.node);\n const sb = sortSerial(b.node);\n if (sa === undefined && sb === undefined) return a.insertSeq - b.insertSeq;\n if (sa === undefined) return 1;\n if (sb === undefined) return -1;\n if (sa < sb) return -1;\n if (sa > sb) return 1;\n return a.insertSeq - b.insertSeq;\n }\n\n /**\n * Insert a node into the sorted list at the correct position via binary search.\n * @param internal - The node to insert.\n */\n private _insertSortedNode(internal: InternalNode<TProjection>): void {\n const startSerial = sortSerial(internal.node);\n\n // Fast path: null-startSerial always appends to end.\n if (startSerial === undefined) {\n this._sortedNodes.push(internal);\n return;\n }\n\n let lo = 0;\n let hi = this._sortedNodes.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n const midNode = this._sortedNodes[mid];\n if (!midNode) break; // unreachable\n if (this._compareNodes(midNode, internal) <= 0) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n this._sortedNodes.splice(lo, 0, internal);\n }\n\n /**\n * Remove a node from the sorted list.\n * @param internal - The node to remove.\n */\n private _removeSortedNode(internal: InternalNode<TProjection>): void {\n const idx = this._sortedNodes.indexOf(internal);\n if (idx !== -1) this._sortedNodes.splice(idx, 1);\n }\n\n /**\n * Insert a freshly-created node into the primary store, the parent index, and\n * the sorted list, then bump the structural version. Kind-specific secondary\n * indexing — the codec-message-id map for input nodes, the reply→input edge\n * for reply runs — is the caller's responsibility.\n * @param key - The node's primary key ({@link nodeKey}).\n * @param entry - The internal node to insert.\n * @param parentCodecMessageId - The node's structural parent, or undefined for a root.\n */\n private _insertNode(key: string, entry: InternalNode<TProjection>, parentCodecMessageId: string | undefined): void {\n this._nodeIndex.set(key, entry);\n this._addToParentIndex(parentCodecMessageId, key);\n this._insertSortedNode(entry);\n this._structuralVersion++;\n }\n\n /**\n * Re-sort a node whose sort key just changed and bump the structural version.\n * The caller mutates the serial field (`serial` for input nodes, `startSerial`\n * for runs); this keeps the sorted list and version in step. Used on the\n * optimistic-serial promotion paths when the server relay/echo arrives.\n * @param entry - The internal node whose serial was just promoted.\n */\n private _promoteSerial(entry: InternalNode<TProjection>): void {\n this._removeSortedNode(entry);\n this._insertSortedNode(entry);\n this._structuralVersion++;\n }\n\n /**\n * Fold a batch of events into a node's projection in place, isolating each\n * fold in a try/catch so a throwing reducer can't abort the rest of the batch\n * or the surrounding apply.\n * @param entry - The internal node whose projection is folded in place.\n * @param events - The decoded events to fold, in wire order.\n * @param serial - Ably channel serial; coerced to '' for an optimistic insert.\n * @param messageId - The reducer routing key (codec-message-id), or undefined.\n */\n private _foldInto(\n entry: InternalNode<TProjection>,\n events: (TInput | TOutput)[],\n serial: string | undefined,\n messageId: string | undefined,\n ): void {\n for (const event of events) {\n try {\n entry.node.projection = this._codec.fold(entry.node.projection, event, { serial: serial ?? '', messageId });\n } catch (error) {\n this._logger.error('Tree._foldInto(); fold threw', { key: nodeKey(entry.node), messageId, err: error });\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Parent index maintenance\n // -------------------------------------------------------------------------\n\n private _addToParentIndex(parentNodeKey: string | undefined, childKey: string): void {\n addToSetMap(this._parentIndex, parentNodeKey, childKey);\n }\n\n private _removeFromParentIndex(parentNodeKey: string | undefined, childKey: string): void {\n deleteFromSetMap(this._parentIndex, parentNodeKey, childKey);\n }\n\n /**\n * Resolve a node's structural parent to the parent node's key\n * ({@link nodeKey}), or undefined for a root. The parent is named by a\n * codec-message-id (`parentCodecMessageId`); this maps it through the\n * codec-message-id index to the owning node's key (a runId for a reply run,\n * a codec-message-id for an input node). Returns undefined when the parent\n * hasn't been observed yet (the node is treated as a root until it arrives).\n * @param node - The node whose parent to resolve.\n * @returns The parent node's key, or undefined.\n */\n private _parentKeyOf(node: ConversationNode<TProjection>): string | undefined {\n const parentCodecMessageId = node.parentCodecMessageId;\n return parentCodecMessageId === undefined ? undefined : this._codecMessageIdToNodeKey.get(parentCodecMessageId);\n }\n\n // -------------------------------------------------------------------------\n // Sibling grouping\n // -------------------------------------------------------------------------\n\n /**\n * Walk an input node's `forkOf` chain to the group root — the earliest edit\n * version sharing the same structural parent. Stops at a missing target, a\n * non-input target, a parent mismatch, or a cycle.\n * @param node - The input node to walk from.\n * @returns The group-root input node (the node itself when it is the root).\n */\n private _inputGroupRoot(node: InputNode<TProjection>): InputNode<TProjection> {\n let current = node;\n const visited = new Set<string>([nodeKey(current)]);\n while (current.forkOf !== undefined) {\n if (visited.has(current.forkOf)) break;\n const forkTarget = this._nodeIndex.get(current.forkOf);\n if (forkTarget?.node.kind !== 'input' || forkTarget.node.parentCodecMessageId !== current.parentCodecMessageId) {\n break;\n }\n current = forkTarget.node;\n visited.add(nodeKey(current));\n }\n return current;\n }\n\n /**\n * Get the sibling group that the node keyed by `key` belongs to. Kind-split:\n *\n * - **Reply runs** — every reply run sharing the same input-node parent is a\n * sibling (the original reply + its regenerators all parent at the same\n * input node M_user). No fork-of involved.\n * - **Input nodes** — edit versions: nodes sharing a parent AND linked by a\n * `forkOf` chain to the group root.\n *\n * Returned ordered by startSerial (original/oldest first). A group of one is\n * returned as a single-element array (no branching).\n * @param key - The node key ({@link nodeKey}) to look up the group for.\n * @returns The ordered list of sibling nodes.\n */\n // Spec: AIT-CT13b\n private _getSiblingGroup(key: string): InternalNode<TProjection>[] {\n if (this._siblingCacheVersion !== this._structuralVersion) {\n this._siblingCache.clear();\n this._siblingCacheVersion = this._structuralVersion;\n }\n const cached = this._siblingCache.get(key);\n if (cached) return cached;\n\n const entry = this._nodeIndex.get(key);\n if (!entry) return [];\n\n // The \"original\" anchors the group's parent + kind. For an input node,\n // walk the forkOf chain to the earliest version sharing the parent; for a\n // reply run the node itself anchors (all same-parent runs are siblings).\n let original = entry.node;\n if (original.kind === 'input') {\n original = this._inputGroupRoot(original);\n }\n\n // `_parentIndex` is keyed by the raw structural `parentCodecMessageId` (not\n // the resolved parent node key) so a run observed before its input node\n // still files/groups correctly — the parent codec-message-id is known at\n // creation, the resolved key may not be.\n const parentKey = original.parentCodecMessageId;\n const siblings: InternalNode<TProjection>[] = [];\n const candidateKeys = this._parentIndex.get(parentKey);\n if (candidateKeys) {\n for (const childKey of candidateKeys) {\n const childEntry = this._nodeIndex.get(childKey);\n if (childEntry && this._isSiblingOf(childEntry.node, original)) {\n siblings.push(childEntry);\n }\n }\n }\n\n siblings.sort((a, b) => this._compareNodes(a, b));\n // Cache against the queried key AND every member of the group: a single\n // group is the same array regardless of which member triggered the lookup,\n // so subsequent queries against any member hit without recomputing.\n for (const sib of siblings) {\n this._siblingCache.set(nodeKey(sib.node), siblings);\n }\n this._siblingCache.set(key, siblings);\n return siblings;\n }\n\n /**\n * Whether `node` belongs to the sibling group anchored at `original`.\n * Requires the same kind and the same structural parent; reply runs need\n * nothing more (same-parent runs are regenerate siblings), input nodes must\n * additionally be forkOf-linked to the original (edit versions).\n * @param node - The candidate node.\n * @param original - The group's anchor node.\n * @returns True if `node` is a sibling of `original`.\n */\n private _isSiblingOf(node: ConversationNode<TProjection>, original: ConversationNode<TProjection>): boolean {\n if (node.kind !== original.kind) return false;\n if (node.parentCodecMessageId !== original.parentCodecMessageId) return false;\n // Same-parent reply runs are regenerate siblings — no fork-of needed.\n if (node.kind === 'run') return true;\n // Input nodes: must be forkOf-linked to the original (edit versions).\n const originalKey = nodeKey(original);\n if (nodeKey(node) === originalKey) return true;\n let current: ConversationNode<TProjection> = node;\n const visited = new Set<string>([nodeKey(current)]);\n while (current.kind === 'input' && current.forkOf !== undefined) {\n if (current.forkOf === originalKey) return true;\n if (visited.has(current.forkOf)) break;\n const target = this._nodeIndex.get(current.forkOf);\n if (!target) break;\n current = target.node;\n visited.add(nodeKey(current));\n }\n return false;\n }\n\n /**\n * Get the \"group root\" key for a sibling group — the stable key the\n * selection map is keyed by. For an input node (edit versions) that is the\n * earliest fork-of ancestor; for a reply run (regenerate group) it is the\n * oldest same-parent run (the original reply).\n * @param key - Any node key in the sibling group.\n * @returns The group root's key.\n */\n getGroupRoot(key: string): string {\n const entry = this._nodeIndex.get(key);\n if (!entry) return key;\n\n if (entry.node.kind === 'input') {\n return nodeKey(this._inputGroupRoot(entry.node));\n }\n\n // Reply run: the oldest same-parent run is the original reply.\n const group = this._getSiblingGroup(key);\n const root = group[0]?.node;\n return root ? nodeKey(root) : key;\n }\n\n // -------------------------------------------------------------------------\n // Public query methods\n // -------------------------------------------------------------------------\n\n /**\n * Walk the visible node chain along the selected branches, kind-blind. An\n * input node and a reply run reach each other through the same\n * parent-membership check, so seed-only user→user chains and the\n * input→reply→input weave both resolve here. Sibling groups (edit versions /\n * regenerate runs) collapse to the selected member.\n * @param selections - Per-group selected member key, keyed by group root.\n * @returns The visible nodes (both kinds) in chronological order.\n */\n visibleNodes(selections: Map<string, string> = new Map<string, string>()): ConversationNode<TProjection>[] {\n this._logger.trace('DefaultTree.visibleNodes();');\n const result: ConversationNode<TProjection>[] = [];\n const currentPath = new Set<string>();\n const resolvedGroups = new Map<string, string>(); // groupRootKey -> selected key\n\n for (const internal of this._sortedNodes) {\n const node = internal.node;\n const key = nodeKey(node);\n\n // Step 1: Parent reachability (kind-blind — the parent may be an input\n // node or a reply run; resolve its key and check the active path).\n const parentKey = this._parentKeyOf(node);\n if (parentKey !== undefined && !currentPath.has(parentKey)) {\n continue;\n }\n\n // Step 2: Sibling selection.\n const group = this._getSiblingGroup(key);\n if (group.length > 1) {\n const groupRootKey = this.getGroupRoot(key);\n let selectedKey = resolvedGroups.get(groupRootKey);\n if (selectedKey === undefined) {\n const preferredKey = selections.get(groupRootKey);\n if (preferredKey !== undefined && group.some((n) => nodeKey(n.node) === preferredKey)) {\n selectedKey = preferredKey;\n } else {\n const latest = group.at(-1);\n if (!latest) break; // unreachable: group.length > 1\n selectedKey = nodeKey(latest.node);\n }\n resolvedGroups.set(groupRootKey, selectedKey);\n }\n if (key !== selectedKey) {\n continue;\n }\n }\n\n currentPath.add(key);\n result.push(node);\n }\n\n return result;\n }\n\n getRunNode(runId: string): RunNode<TProjection> | undefined {\n this._logger.trace('DefaultTree.getRunNode();', { runId });\n const node = this._nodeIndex.get(runId)?.node;\n return node?.kind === 'run' ? node : undefined;\n }\n\n getNode(key: string): ConversationNode<TProjection> | undefined {\n this._logger.trace('DefaultTree.getNode();', { key });\n return this._nodeIndex.get(key)?.node;\n }\n\n getNodeByCodecMessageId(codecMessageId: string): ConversationNode<TProjection> | undefined {\n this._logger.trace('DefaultTree.getNodeByCodecMessageId();', { codecMessageId });\n const key = this._codecMessageIdToNodeKey.get(codecMessageId);\n return key === undefined ? undefined : this._nodeIndex.get(key)?.node;\n }\n\n getReplyRuns(inputCodecMessageId: string): RunNode<TProjection>[] {\n const runIds = this._replyRunsByInput.get(inputCodecMessageId);\n if (!runIds) return [];\n const result: RunNode<TProjection>[] = [];\n for (const runId of runIds) {\n const node = this._nodeIndex.get(runId)?.node;\n if (node?.kind === 'run') result.push(node);\n }\n return result;\n }\n\n getSiblingNodes(key: string): ConversationNode<TProjection>[] {\n this._logger.trace('DefaultTree.getSiblingNodes();', { key });\n return this._getSiblingGroup(key).map((n) => n.node);\n }\n\n // -------------------------------------------------------------------------\n // Mutation\n // -------------------------------------------------------------------------\n\n applyMessage(\n events: { inputs: TInput[]; outputs: TOutput[] },\n headers: Record<string, string>,\n serial?: string,\n ): void {\n const wireRunId = headers[HEADER_RUN_ID];\n const codecMessageId = headers[HEADER_CODEC_MESSAGE_ID];\n\n // Classify: with NO run-id, a user message carrying a codec-message-id and\n // at least one input event forms an INPUT node keyed by that\n // codec-message-id — the client owns it; the agent mints the reply run-id\n // separately. Everything else needs a run-id to route to a reply run.\n // Capturing the id (not a boolean) narrows it to `string` for the input path.\n const inputNodeCodecMessageId =\n wireRunId === undefined &&\n codecMessageId !== undefined &&\n headers[HEADER_ROLE] === 'user' &&\n events.inputs.length > 0\n ? codecMessageId\n : undefined;\n\n if (wireRunId === undefined && inputNodeCodecMessageId === undefined) {\n this._logger.warn('Tree.applyMessage(); message has no run-id and is not a user input; skipping');\n return;\n }\n\n // Fold inputs first, then outputs, preserving wire order.\n const all: (TInput | TOutput)[] = [...events.inputs, ...events.outputs];\n\n // Wire-only metadata-carrier messages (e.g. `ait-regenerate`) decode to\n // zero events and don't need a node at the tree level — the eventual reply\n // run is created later by run-start, and any regenerate / parent\n // information the wire carried is reread from the run-start headers.\n // Skipping here avoids a phantom node that would inflate sibling counts.\n const existingKey = inputNodeCodecMessageId ?? wireRunId;\n if (all.length === 0 && existingKey !== undefined && !this._nodeIndex.has(existingKey)) {\n return;\n }\n\n // `update` is the structural channel: emit it only when this apply\n // actually changes the tree shape (new node, startSerial promotion).\n // Content-only folds (streaming chunks into an existing node) flow through\n // `output` instead, so they leave `_structuralVersion` untouched.\n const structuralBefore = this._structuralVersion;\n\n if (inputNodeCodecMessageId !== undefined) {\n this._applyInputMessage(inputNodeCodecMessageId, headers, serial, all);\n } else if (wireRunId !== undefined) {\n this._applyRunMessage(wireRunId, events, headers, serial);\n }\n\n if (this._structuralVersion !== structuralBefore) this._emitter.emit('update');\n }\n\n /**\n * Apply a run-less user input wire: create (or promote the serial of) the\n * input node keyed by its codec-message-id, fold the input events into its\n * own projection, and emit an `output` event (with empty outputs — input\n * folds carry none) so the View observes the optimistic insert.\n * @param codecMessageId - The input node's codec-message-id (its primary key).\n * @param headers - Transport headers from the inbound Ably message.\n * @param serial - Ably channel serial; undefined for an optimistic insert.\n * @param all - The decoded input events to fold, in wire order.\n */\n private _applyInputMessage(\n codecMessageId: string,\n headers: Record<string, string>,\n serial: string | undefined,\n all: (TInput | TOutput)[],\n ): void {\n let entry = this._nodeIndex.get(codecMessageId);\n if (!entry) {\n entry = this._createInputNodeFromHeaders(codecMessageId, headers, serial);\n this._insertNode(codecMessageId, entry, entry.node.parentCodecMessageId);\n this._codecMessageIdToNodeKey.set(codecMessageId, codecMessageId);\n this._logger.debug('Tree.applyMessage(); created input node', { codecMessageId });\n } else if (entry.node.kind === 'input' && serial && !entry.node.serial) {\n // Promote optimistic serial when the relay/echo arrives.\n this._logger.debug('Tree.applyMessage(); promoting input serial', { codecMessageId, serial });\n entry.node.serial = serial;\n this._promoteSerial(entry);\n }\n\n this._foldInto(entry, all, serial, codecMessageId);\n\n // An input node owns no agent outputs; the event still fires (empty\n // outputs) so consumers observe the projection change. It has no run-id —\n // the causal routing key is the input's own codec-message-id.\n this._emitter.emit('output', {\n runId: undefined,\n inputCodecMessageId: codecMessageId,\n codecMessageId,\n serial,\n events: [],\n });\n }\n\n /**\n * Apply a reply-run wire (assistant output, continuation tool-resolution, or\n * a fresh run keyed by the agent-minted run-id): create or reconcile the run\n * node, fold its events, maintain the codec-message-id and reply→input\n * indices, and emit the `output` event. Derives the codec-message-id,\n * triggering-input id, fold list, and outputs from `events`/`headers`,\n * mirroring `applyMessage`.\n * @param wireRunId - The run-id from the inbound wire (the node's primary key).\n * @param events - The decoded inputs and outputs from the wire.\n * @param events.inputs - Client-published events (`ai-input` wire).\n * @param events.outputs - Agent-published events (`ai-output` wire).\n * @param headers - Transport headers from the inbound Ably message.\n * @param serial - Ably channel serial; undefined for an optimistic insert.\n */\n private _applyRunMessage(\n wireRunId: string,\n events: { inputs: TInput[]; outputs: TOutput[] },\n headers: Record<string, string>,\n serial: string | undefined,\n ): void {\n const codecMessageId = headers[HEADER_CODEC_MESSAGE_ID];\n // The triggering input's codec-message-id (the agent's echo), surfaced on\n // the `output` event as the stream's causal routing key.\n const inputCodecMessageId = headers[HEADER_INPUT_CODEC_MESSAGE_ID];\n // Fold inputs first, then outputs, preserving wire order.\n const all: (TInput | TOutput)[] = [...events.inputs, ...events.outputs];\n const outputs = events.outputs;\n\n let run = this._nodeIndex.get(wireRunId);\n\n // Reconcile an optimistic insert with its serial-bearing echo by\n // codec-message-id rather than the wire run-id — covers assistant content\n // that pins a codec-message-id before its run-id is indexed.\n if (!run && codecMessageId !== undefined) {\n const indexedKey = this._codecMessageIdToNodeKey.get(codecMessageId);\n const indexed = indexedKey === undefined ? undefined : this._nodeIndex.get(indexedKey);\n if (indexed?.node.kind === 'run' && indexed.node.startSerial === undefined) run = indexed;\n }\n\n if (!run) {\n run = this._createRunFromHeaders(wireRunId, headers, serial);\n this._insertNode(wireRunId, run, run.node.parentCodecMessageId);\n this._indexReplyRun(run.node, wireRunId);\n this._logger.debug('Tree.applyMessage(); created new Run', { runId: wireRunId });\n } else if (serial && run.node.kind === 'run' && !run.node.startSerial) {\n // Promote optimistic startSerial when the relay/echo arrives.\n this._logger.debug('Tree.applyMessage(); promoting startSerial', { runId: wireRunId, serial });\n run.node.startSerial = serial;\n this._promoteSerial(run);\n }\n\n // Index the codec-message-id against the node that actually owns it.\n const ownerKey = nodeKey(run.node);\n if (codecMessageId) this._codecMessageIdToNodeKey.set(codecMessageId, ownerKey);\n\n this._foldInto(run, all, serial, codecMessageId);\n\n this._emitter.emit('output', { runId: ownerKey, inputCodecMessageId, codecMessageId, serial, events: outputs });\n }\n\n /**\n * Record a reply run against its input-node parent (the reverse edge powering\n * `getReplyRuns` and regenerate sibling grouping). A reply run's\n * `parentCodecMessageId` is its input node's codec-message-id (the master\n * invariant), so no resolution is needed.\n * @param node - The reply run node.\n * @param runId - The run's id.\n */\n private _indexReplyRun(node: ConversationNode<TProjection>, runId: string): void {\n if (node.parentCodecMessageId === undefined) return;\n addToSetMap(this._replyRunsByInput, node.parentCodecMessageId, runId);\n }\n\n applyRunLifecycle(event: RunLifecycleEvent): void {\n this._logger.trace('DefaultTree.applyRunLifecycle();', { type: event.type, runId: event.runId });\n // Structural channel: emit `update` only when the lifecycle event changes\n // the tree shape. Only run-start can do that (a new Run, startSerial\n // promotion, or structural-metadata backfill); suspend/resume/end mutate\n // status/endSerial on an existing node — content, not structure — so the\n // conditional naturally never fires for them.\n const structuralBefore = this._structuralVersion;\n switch (event.type) {\n case 'start': {\n this._applyRunStart(event);\n break;\n }\n case 'suspend': {\n this._applyRunSuspend(event);\n break;\n }\n case 'resume': {\n this._applyRunResume(event);\n break;\n }\n case 'end': {\n this._applyRunEnd(event);\n break;\n }\n }\n this._emitter.emit('run', event);\n if (this._structuralVersion !== structuralBefore) this._emitter.emit('update');\n }\n\n /**\n * Apply a run-start lifecycle event's structural effect: create the reply\n * run if it doesn't exist yet, or backfill an optimistic / wire-created\n * node's structure and metadata from the canonical run-start. Mutates\n * `_structuralVersion` when the tree shape changes; the caller owns the\n * `run`/`update` emits.\n * @param event - The run-start lifecycle event.\n */\n private _applyRunStart(event: RunLifecycleEvent & { type: 'start' }): void {\n const existing = this._nodeIndex.get(event.runId);\n if (existing?.node.kind === 'run') {\n const node = existing.node;\n if (node.status !== 'active') {\n node.status = 'active';\n }\n if (event.serial && !node.startSerial) {\n node.startSerial = event.serial;\n this._promoteSerial(existing);\n }\n // Backfill structural metadata if the Run was created from an\n // assistant wire that arrived before run-start (history pagination\n // boundary or out-of-order delivery). The run-start lifecycle event is\n // the canonical source for parent/forkOf/regenerates; only fill in\n // fields the wire didn't already populate. A run-start is always a\n // first start (continuations re-enter via `ai-run-resume`, which\n // carries no structural metadata), so it is unconditionally\n // authoritative here. `parent` is the run's STRUCTURAL parent (its\n // input node) — reachability and the reply→input edge read it.\n if (node.parentCodecMessageId === undefined && event.parent !== undefined) {\n node.parentCodecMessageId = event.parent;\n this._removeFromParentIndex(undefined, event.runId);\n this._addToParentIndex(node.parentCodecMessageId, event.runId);\n this._indexReplyRun(node, event.runId);\n this._structuralVersion++;\n }\n if (node.forkOf === undefined && event.forkOf !== undefined) {\n const forkOfKey = this._codecMessageIdToNodeKey.get(event.forkOf);\n if (forkOfKey !== undefined && forkOfKey !== event.runId) {\n node.forkOf = forkOfKey;\n this._structuralVersion++;\n }\n }\n if (node.regeneratesCodecMessageId === undefined && event.regenerates !== undefined) {\n node.regeneratesCodecMessageId = event.regenerates;\n this._structuralVersion++;\n }\n // Adopt the agent-minted invocation-id onto the optimistic node. The\n // agent mints it, so a node created from an optimistic insert (or an\n // assistant wire that arrived before run-start) carries an empty id\n // until the agent's run-start delivers it. Metadata, not structure —\n // consumers re-read it on the `run` emit, so no structural-version\n // bump.\n if (node.invocationId === '' && event.invocationId !== '') {\n node.invocationId = event.invocationId;\n }\n } else if (!existing) {\n const run = this._createRunFromLifecycle(event);\n this._insertNode(event.runId, run, run.node.parentCodecMessageId);\n this._indexReplyRun(run.node, event.runId);\n }\n }\n\n /**\n * Apply a run-suspend lifecycle event: pause the run without ending it —\n * mark the node 'suspended' and record the serial it paused at, but keep the\n * Run live so a resume under the same runId resumes it. Status/endSerial are\n * content, not structure, so this never mutates `_structuralVersion`; the\n * caller owns the emits.\n * @param event - The run-suspend lifecycle event.\n */\n private _applyRunSuspend(event: RunLifecycleEvent & { type: 'suspend' }): void {\n const run = this._nodeIndex.get(event.runId);\n if (run?.node.kind === 'run') {\n run.node.status = 'suspended';\n run.node.endSerial = event.serial;\n }\n }\n\n /**\n * Apply a run-resume lifecycle event: re-enter an already-started run by\n * flipping a suspended run back to 'active'. Pure re-entry — it carries no\n * parent/forkOf and does not promote startSerial (the original run-start owns\n * the run's structure). Only a suspended run resumes: a no-op when the run\n * isn't known (e.g. a resume replayed from a newer history page before its\n * run-start) and a no-op for an already-active or terminal\n * (complete/cancelled/error) run — a stray resume must never resurrect a run\n * that has ended. The caller owns the emits.\n * @param event - The run-resume lifecycle event.\n */\n private _applyRunResume(event: RunLifecycleEvent & { type: 'resume' }): void {\n const run = this._nodeIndex.get(event.runId);\n if (run?.node.kind === 'run' && run.node.status === 'suspended') {\n run.node.status = 'active';\n }\n }\n\n /**\n * Apply a run-end lifecycle event: record the terminal reason as the node's\n * status and the serial it ended at. Status/endSerial are content, not\n * structure, so this never mutates `_structuralVersion`; the caller owns the\n * emits.\n * @param event - The run-end lifecycle event.\n */\n private _applyRunEnd(event: RunLifecycleEvent & { type: 'end' }): void {\n const run = this._nodeIndex.get(event.runId);\n if (run?.node.kind === 'run') {\n run.node.status = event.reason;\n run.node.endSerial = event.serial;\n }\n }\n\n delete(key: string): void {\n const entry = this._nodeIndex.get(key);\n if (!entry) return;\n\n this._logger.debug('Tree.delete();', { key });\n\n this._removeFromParentIndex(entry.node.parentCodecMessageId, key);\n this._removeSortedNode(entry);\n this._nodeIndex.delete(key);\n // Drop the reply→input reverse edge.\n if (entry.node.kind === 'run' && entry.node.parentCodecMessageId !== undefined) {\n deleteFromSetMap(this._replyRunsByInput, entry.node.parentCodecMessageId, key);\n }\n // _codecMessageIdToNodeKey entries pointing at this node linger but are\n // harmless; they'll be overwritten if the node is re-created and remain\n // dangling otherwise. Cleanup not worth the index walk.\n\n this._structuralVersion++;\n this._emitter.emit('update');\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n /**\n * Build a fresh RunNode from a wire message's headers. Used when an\n * inbound message arrives before any run-start event for its runId.\n * @param runId - The run-id from the inbound wire.\n * @param headers - Transport headers from the inbound Ably message.\n * @param serial - Ably channel serial; undefined for optimistic inserts.\n * @returns A newly-allocated internal run node ready for insertion.\n */\n private _createRunFromHeaders(\n runId: string,\n headers: Record<string, string>,\n serial: string | undefined,\n ): InternalNode<TProjection> {\n const forkOfMsgId = headers[HEADER_FORK_OF];\n return this._buildRunNode({\n runId,\n parentCodecMessageId: headers[HEADER_PARENT],\n // forkOf is resolved to the fork target's node key (an input node's\n // codec-message-id, or a run's id) — the same space `_isSiblingOf` walks.\n forkOf: forkOfMsgId ? this._codecMessageIdToNodeKey.get(forkOfMsgId) : undefined,\n regeneratesCodecMessageId: headers[HEADER_MSG_REGENERATE],\n clientId: headers[HEADER_RUN_CLIENT_ID] ?? '',\n invocationId: headers[HEADER_INVOCATION_ID] ?? '',\n startSerial: serial,\n });\n }\n\n /**\n * Allocate a RunNode from already-resolved fields. Shared by the\n * header-driven and lifecycle-driven run creators: both build the identical\n * RunNode literal and stamp an insert sequence.\n * @param params - The resolved run fields.\n * @param params.runId - The run's id (its primary key).\n * @param params.parentCodecMessageId - Structural parent codec-message-id, or undefined for a root.\n * @param params.forkOf - The resolved fork target's node key (already mapped through the codec-message-id index), or undefined.\n * @param params.regeneratesCodecMessageId - The codec-message-id this run regenerates, or undefined.\n * @param params.clientId - The publishing client's id.\n * @param params.invocationId - The agent invocation id.\n * @param params.startSerial - Ably channel serial; undefined for optimistic inserts.\n * @returns A newly-allocated internal run node ready for insertion.\n */\n private _buildRunNode(params: {\n runId: string;\n parentCodecMessageId: string | undefined;\n forkOf: string | undefined;\n regeneratesCodecMessageId: string | undefined;\n clientId: string;\n invocationId: string;\n startSerial: string | undefined;\n }): InternalNode<TProjection> {\n const node: RunNode<TProjection> = {\n kind: 'run',\n runId: params.runId,\n parentCodecMessageId: params.parentCodecMessageId,\n forkOf: params.forkOf,\n regeneratesCodecMessageId: params.regeneratesCodecMessageId,\n clientId: params.clientId,\n invocationId: params.invocationId,\n status: 'active',\n projection: this._codec.init(),\n startSerial: params.startSerial,\n endSerial: undefined,\n };\n\n return { node, insertSeq: this._seqCounter++ };\n }\n\n /**\n * Build a fresh InputNode from a run-less user input wire's headers.\n * @param codecMessageId - The input's codec-message-id (its primary key).\n * @param headers - Transport headers from the inbound Ably message.\n * @param serial - Ably channel serial; undefined for optimistic inserts.\n * @returns A newly-allocated internal input node ready for insertion.\n */\n private _createInputNodeFromHeaders(\n codecMessageId: string,\n headers: Record<string, string>,\n serial: string | undefined,\n ): InternalNode<TProjection> {\n const forkOfMsgId = headers[HEADER_FORK_OF];\n const node: InputNode<TProjection> = {\n kind: 'input',\n codecMessageId,\n parentCodecMessageId: headers[HEADER_PARENT],\n // An edit's fork-of names the original prompt's codec-message-id, which\n // IS that input node's key — no resolution needed.\n forkOf: forkOfMsgId,\n projection: this._codec.init(),\n serial,\n };\n return { node, insertSeq: this._seqCounter++ };\n }\n\n /**\n * Build a fresh RunNode from a run-start lifecycle event. Used when a\n * run-start event arrives before any message for its runId.\n * @param event - The run-start lifecycle event from the agent, including\n * its channel serial.\n * @returns A newly-allocated internal run node ready for insertion.\n */\n private _createRunFromLifecycle(event: RunLifecycleEvent & { type: 'start' }): InternalNode<TProjection> {\n const forkOfMsgId = event.forkOf;\n return this._buildRunNode({\n runId: event.runId,\n parentCodecMessageId: event.parent,\n forkOf: forkOfMsgId ? this._codecMessageIdToNodeKey.get(forkOfMsgId) : undefined,\n regeneratesCodecMessageId: event.regenerates,\n clientId: event.clientId,\n invocationId: event.invocationId,\n startSerial: event.serial,\n });\n }\n\n // -------------------------------------------------------------------------\n // Events\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CT8b, AIT-CT8e\n on(event: 'update', handler: () => void): () => void;\n on(event: 'ably-message', handler: (msg: Ably.InboundMessage) => void): () => void;\n on(event: 'run', handler: (event: RunLifecycleEvent) => void): () => void;\n on(event: 'output', handler: (event: OutputEvent<TOutput>) => void): () => void;\n on(\n event: 'update' | 'ably-message' | 'run' | 'output',\n handler:\n | (() => void)\n | ((msg: Ably.InboundMessage) => void)\n | ((event: RunLifecycleEvent) => void)\n | ((event: OutputEvent<TOutput>) => void),\n ): () => void {\n // CAST: overload signatures enforce correct handler types per event name.\n const cb = handler as (arg: TreeEventsMap<TOutput>[keyof TreeEventsMap<TOutput>]) => void;\n this._emitter.on(event, cb);\n return () => {\n this._emitter.off(event, cb);\n };\n }\n\n /**\n * Forward a raw Ably message event to tree subscribers.\n * @param msg - The raw Ably message to emit.\n */\n emitAblyMessage(msg: Ably.InboundMessage): void {\n this._logger.trace('DefaultTree.emitAblyMessage();');\n this._emitter.emit('ably-message', msg);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Tree that materializes branching conversation history from a flat\n * oplog of Ably messages as a two-node-per-turn forest (input node + reply run).\n * @param codec - Codec used to fold inbound events into per-Run projections.\n * @param logger - Logger for diagnostic output.\n * @returns A new {@link DefaultTree} instance. The session uses DefaultTree\n * directly for internal methods (applyMessage, applyRunLifecycle,\n * emitAblyMessage). Public consumers see the narrower {@link Tree} interface.\n */\nexport const createTree = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection>(\n codec: Reducer<TInput | TOutput, TProjection>,\n logger: Logger,\n): DefaultTree<TInput, TOutput, TProjection> => new DefaultTree<TInput, TOutput, TProjection>(codec, logger);\n","/**\n * loadHistory — load conversation history from an Ably channel and return\n * the raw wire messages as a paginated HistoryPage result.\n *\n * This does NOT decode: it pages back through Ably history until `limit`\n * complete messages are present, then hands the raw Ably messages\n * (oldest-first) to the caller. The View re-decodes them into the Tree\n * itself, so load-history only needs a cheap, header-based completion\n * counter to decide when to stop paging — the decoder never runs here.\n *\n * The `limit` option controls the number of complete **messages** per page,\n * not the number of Ably wire messages fetched. A message is complete when\n * its terminal wire signal — `status: \"complete\"` / `\"cancelled\"`, or a\n * `discrete` create — has been seen. Runs that span a\n * page boundary are handled by the counter requiring both a start and a\n * terminal signal before counting a message complete.\n *\n * Because Ably history returns newest-first, each page's `rawMessages` are\n * reversed to chronological (oldest-first) so the caller can fold them in\n * order.\n */\n\nimport type * as Ably from 'ably';\n\nimport { HEADER_CODEC_MESSAGE_ID, HEADER_DISCRETE, HEADER_STATUS, HEADER_STREAM } from '../../constants.js';\nimport type { Logger } from '../../logger.js';\nimport { getTransportHeaders } from '../../utils.js';\nimport type { HistoryPage, LoadHistoryOptions } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Shared state across pages within one history traversal\n// ---------------------------------------------------------------------------\n\ninterface HistoryState {\n /** All raw Ably messages collected so far, in newest-first order (as received from Ably). */\n rawMessages: Ably.InboundMessage[];\n /**\n * How many complete messages have been served to the consumer so far.\n * Drives the buffered-page logic: when a single fetch gathers more than\n * `limit` completions, later pages are served from the buffer without\n * fetching, advancing this counter `limit` at a time.\n */\n returnedCount: number;\n /** How many raw Ably messages have been served to the consumer so far. */\n returnedRawCount: number;\n /** The last Ably page cursor for continued pagination. */\n lastAblyPage: Ably.PaginatedResult<Ably.InboundMessage> | undefined;\n /**\n * `codec-message-id`s for which a start signal has been seen: any\n * `message.create` / `message.update` / `message.append` with\n * `stream: \"true\"` (the decoder establishes a tracker via create or\n * first-contact), or a `message.create` carrying `discrete` (a discrete\n * message, created and terminated in one wire message).\n */\n startedCodecMessageIds: Set<string>;\n /**\n * `codec-message-id`s with a terminal wire signal: either `discrete`\n * on a `message.create` (discrete message) or `status: \"complete\"`\n * / `\"cancelled\"` on any action (closed stream).\n */\n terminatedCodecMessageIds: Set<string>;\n /**\n * `codec-message-id`s that are both started AND terminated — counted as\n * complete. The fetch loop reads this set's size to decide when to stop\n * paging. Maintained incrementally by {@link countNewCompletions}. Grows\n * monotonically.\n */\n completedCodecMessageIds: Set<string>;\n logger: Logger;\n}\n\n// ---------------------------------------------------------------------------\n// Incremental completion counting (header scan, no decode)\n// ---------------------------------------------------------------------------\n\n/**\n * Scan newly-added raw messages and track which `codec-message-id`s have\n * become complete. Used by {@link fetchUntilLimit} to decide when enough\n * completed messages have been collected, without running the decoder.\n *\n * A codec-message-id is considered complete only when BOTH of these have been seen:\n * - a \"start\" signal: either `discrete` on a `message.create`\n * (discrete messages are created and terminated by the same wire\n * message), OR any `message.create` / `message.update` / `message.append`\n * with `stream: \"true\"` (the decoder establishes a tracker via\n * create or first-contact).\n * - a \"terminal\" signal: `discrete` on the create, or\n * `status: \"complete\"` / `\"cancelled\"` on any later action.\n *\n * Why update and append count as starts: Ably history can compact a live\n * `create + append + ... + append{status:complete}` sequence into a single\n * `message.update` with `STREAM=true` and `STATUS=complete`. The decoder\n * handles that via first-contact. Counting only `message.create` as a start\n * would cause the fetch loop to page past a compacted run without ever\n * marking it complete.\n *\n * Requiring both halves matters when a streaming run spans a page\n * boundary: the terminal arrives in the newer page (fetched first) while\n * the start sits in an older page. Counting the terminal alone would stop\n * the fetch loop prematurely - the decoder would have no stream state to\n * resolve, and the message wouldn't make it into the result.\n *\n * Messages skipped for counting:\n * - Missing `codec-message-id`: lifecycle events not tied to a domain message.\n * - `message.delete`: clears the tracker, doesn't produce output.\n *\n * Amend-class wire messages (events targeting an existing message via\n * `HEADER_CODEC_MESSAGE_ID`) flow through the same counter — the Sets naturally\n * dedup so a tool-output amend on an already-seen codec-message-id is idempotent.\n *\n * Known edge case: if Ably history is truncated and a terminal survives\n * while every start signal for its codec-message-id has rolled off, the counter will\n * never mark that `codec-message-id` complete. The loop keeps fetching until it runs\n * out of pages, then returns whatever raw messages it collected.\n * @param state - The shared history traversal state.\n * @param newMessages - The Ably messages just pushed onto `state.rawMessages`.\n */\nconst countNewCompletions = (state: HistoryState, newMessages: readonly Ably.InboundMessage[]): void => {\n for (const msg of newMessages) {\n const headers = getTransportHeaders(msg);\n const codecMessageId = headers[HEADER_CODEC_MESSAGE_ID];\n if (!codecMessageId) continue;\n\n const action = msg.action;\n const isDiscreteCreate = action === 'message.create' && HEADER_DISCRETE in headers;\n // Any content-producing action on a streamed serial counts as a start:\n // the decoder uses create or first-contact (update/append) to establish\n // its tracker. Delete clears tracker state and emits nothing, so it\n // never counts as a start.\n const hasStreamContent =\n headers[HEADER_STREAM] === 'true' &&\n (action === 'message.create' || action === 'message.update' || action === 'message.append');\n const status = headers[HEADER_STATUS];\n const isTerminal = status === 'complete' || status === 'cancelled';\n\n if (isDiscreteCreate || hasStreamContent) state.startedCodecMessageIds.add(codecMessageId);\n if (isDiscreteCreate || isTerminal) state.terminatedCodecMessageIds.add(codecMessageId);\n if (state.startedCodecMessageIds.has(codecMessageId) && state.terminatedCodecMessageIds.has(codecMessageId)) {\n state.completedCodecMessageIds.add(codecMessageId);\n }\n }\n};\n\n// ---------------------------------------------------------------------------\n// Fetch Ably pages until we have enough completed messages\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch Ably history pages until we have enough completed messages.\n *\n * The loop uses {@link countNewCompletions} - a cheap O(new messages) header\n * scan - to decide when to stop, rather than running the decoder per page.\n * @param state - The shared history traversal state.\n * @param ablyPage - The current Ably paginated result to start from.\n * @param limit - Target number of completed messages beyond what has already been returned.\n */\nconst fetchUntilLimit = async (\n state: HistoryState,\n ablyPage: Ably.PaginatedResult<Ably.InboundMessage>,\n limit: number,\n): Promise<void> => {\n state.rawMessages.push(...ablyPage.items);\n state.lastAblyPage = ablyPage;\n countNewCompletions(state, ablyPage.items);\n\n const target = state.returnedCount + limit;\n while (state.completedCodecMessageIds.size < target && ablyPage.hasNext()) {\n state.logger.debug('loadHistory.fetchUntilLimit(); fetching next page', {\n collected: state.rawMessages.length,\n completed: state.completedCodecMessageIds.size,\n });\n const nextPage = await ablyPage.next();\n if (!nextPage) break;\n ablyPage = nextPage;\n state.rawMessages.push(...nextPage.items);\n state.lastAblyPage = nextPage;\n countNewCompletions(state, nextPage.items);\n }\n};\n\n// ---------------------------------------------------------------------------\n// Build HistoryPage result from current state\n// ---------------------------------------------------------------------------\n\n/**\n * Build a HistoryPage of raw wire messages from the current fetch state.\n * @param state - The shared history traversal state.\n * @param limit - Max complete messages per page.\n * @returns A page of raw history messages with a `next()` cursor.\n */\nconst buildResult = (state: HistoryState, limit: number): HistoryPage => {\n // Advance the served-completion counter by up to `limit`, mirroring the\n // page granularity the consumer asked for. `rawMessages` for this page are\n // all wires fetched since the previous page (empty for buffered pages).\n const totalCompleted = state.completedCodecMessageIds.size;\n const served = Math.min(limit, Math.max(0, totalCompleted - state.returnedCount));\n state.returnedCount += served;\n\n const moreCompleted = totalCompleted > state.returnedCount;\n const moreAblyPages = state.lastAblyPage?.hasNext() ?? false;\n\n // Raw Ably messages for this page in chronological order (oldest first).\n const newRawCount = state.rawMessages.length - state.returnedRawCount;\n const rawMessages = newRawCount > 0 ? state.rawMessages.slice(state.returnedRawCount).toReversed() : [];\n state.returnedRawCount = state.rawMessages.length;\n\n return {\n rawMessages,\n hasNext: () => moreCompleted || moreAblyPages,\n next: async () => {\n if (moreCompleted) {\n return buildResult(state, limit);\n }\n if (!moreAblyPages || !state.lastAblyPage) return;\n const nextAbly = await state.lastAblyPage.next();\n if (!nextAbly) return;\n await fetchUntilLimit(state, nextAbly, limit);\n return buildResult(state, limit);\n },\n };\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Load conversation history from a channel and return the raw wire messages.\n *\n * Attaches the channel if not already attached, then calls\n * `channel.history({ untilAttach: true })` to guarantee no gap between\n * historical and live messages. The attach is idempotent.\n *\n * The `limit` option controls the number of complete messages\n * returned per page, not the number of Ably wire messages fetched.\n * @param channel - The Ably channel to load history from.\n * @param options - Pagination options.\n * @param logger - Logger for diagnostic output.\n * @returns The first page of raw history messages.\n */\n// Spec: AIT-CT11, AIT-CT11b\nexport const loadHistory = async (\n channel: Ably.RealtimeChannel,\n options: LoadHistoryOptions | undefined,\n logger: Logger,\n): Promise<HistoryPage> => {\n const limit = options?.limit ?? 100;\n const state: HistoryState = {\n rawMessages: [],\n returnedCount: 0,\n returnedRawCount: 0,\n lastAblyPage: undefined,\n startedCodecMessageIds: new Set<string>(),\n terminatedCodecMessageIds: new Set<string>(),\n completedCodecMessageIds: new Set<string>(),\n logger,\n };\n\n logger.trace('loadHistory();', { limit });\n\n // Request more Ably messages than the domain limit to account for\n // the many-to-one ratio (multiple wire messages per message).\n const wireLimit = limit * 10;\n\n await channel.attach();\n const ablyPage = await channel.history({ untilAttach: true, limit: wireLimit });\n await fetchUntilLimit(state, ablyPage, limit);\n return buildResult(state, limit);\n};\n","/**\n * DefaultView — a paginated, branch-aware projection over the Tree.\n *\n * Wraps a Tree (RunNode-keyed) and manages a pagination window that controls\n * which Runs are visible to the UI. New live Runs appear immediately; older\n * Runs are revealed progressively via `loadOlder()`.\n *\n * `getMessages()` reads the Tree's visible node chain (input nodes + reply\n * runs, with sibling selection applied) and concatenates each node's\n * `codec.getMessages(node.projection)` to produce the flat\n * `CodecMessage<TMessage>[]` the UI renders.\n *\n * Each View owns its own branch selection state and pagination window,\n * allowing multiple independent Views over the same Tree.\n *\n * Events are scoped to the visible window — 'update' only fires when the\n * visible output changes, 'ably-message' only for messages corresponding to\n * visible Runs, and 'run' only for runs with visible content.\n */\n\nimport * as Ably from 'ably';\n\nimport { HEADER_CODEC_MESSAGE_ID, HEADER_RUN_ID } from '../../constants.js';\nimport { ErrorCode } from '../../errors.js';\nimport { EventEmitter } from '../../event-emitter.js';\nimport type { Logger } from '../../logger.js';\nimport { getTransportHeaders } from '../../utils.js';\nimport type { Codec, CodecInputEvent, CodecMessage, CodecOutputEvent } from '../codec/types.js';\nimport { applyWireMessage } from './decode-fold.js';\nimport { loadHistory } from './load-history.js';\nimport { nodeKey, type TreeInternal } from './tree.js';\nimport type {\n ActiveRun,\n BranchSelection,\n ConversationNode,\n HistoryPage,\n OutputEvent,\n RunInfo,\n RunLifecycleEvent,\n RunNode,\n SendOptions,\n View,\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Events map\n// ---------------------------------------------------------------------------\n\ninterface ViewEventsMap {\n update: undefined;\n 'ably-message': Ably.InboundMessage;\n run: RunLifecycleEvent;\n}\n\n// ---------------------------------------------------------------------------\n// Send delegate\n// ---------------------------------------------------------------------------\n\n/**\n * Internal delegate function provided by the session for executing sends.\n * The View pre-computes the visible branch's flat message list and the\n * codec-message-id of its tail (for auto-parent routing) before calling\n * the delegate, so the delegate has no back-reference to the View.\n *\n * Each TInput carries its own routing metadata (`parent` / `target` /\n * `codecMessageId`) via the {@link CodecInputEvent} base; the delegate\n * reads those fields directly without runtime classification.\n *\n * `parentCodecMessageId` is the codec-message-id of the last message in\n * the visible branch (extracted from the tail Run's projection per codec\n * convention), or `undefined` for an empty conversation. The session\n * uses it as the auto-parent for fresh user messages.\n */\nexport type SendDelegate<TInput extends CodecInputEvent> = (\n input: TInput[],\n options: SendOptions | undefined,\n parentCodecMessageId: string | undefined,\n) => Promise<ActiveRun>;\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for creating a View. */\nexport interface ViewOptions<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage> {\n /** The tree to project. */\n tree: TreeInternal<TInput, TOutput, TProjection>;\n /** The Ably channel to load history from. */\n channel: Ably.RealtimeChannel;\n /** The codec used to project messages, mint regenerate inputs, and decode history. */\n codec: Codec<TInput, TOutput, TProjection, TMessage>;\n /** Delegate for executing sends through the session. */\n sendDelegate: SendDelegate<TInput>;\n /** Logger for diagnostic output. */\n logger: Logger;\n /** Called when the view is closed, allowing the owner to clean up references. */\n onClose?: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Branch selection\n// ---------------------------------------------------------------------------\n\n/**\n * Internal tagged union representing why a branch was selected for an\n * edit-fork group. Stored per group-root runId in the View's\n * `_branchSelections` map. Not the public-facing {@link BranchSelection}\n * — that's a UI-facing bundle returned by `view.branchSelection(id)`.\n */\ntype BranchSelectionState =\n /** Explicit navigation via `selectSibling()`. The selected input-node key. */\n | { kind: 'user'; selectedKey: string }\n /** This view initiated an edit fork — auto-selected the new input node. */\n | { kind: 'auto'; selectedKey: string }\n /** An external fork appeared — pinned to the currently-visible sibling to prevent drift. */\n | { kind: 'pinned'; selectedKey: string };\n\n/**\n * Selection state for a regenerate group. Keyed by the anchor codec-message-id (the\n * assistant codec-message-id being regenerated). Distinct from {@link BranchSelectionState}\n * because regenerate groups are message-level (group members share an\n * anchor codec-message-id), not edit forks of the user prompt.\n *\n * Unlike fork-of groups, regenerate groups do not \"pin to current visible\"\n * when a new member appears externally — the default for a regenerate\n * slot is always the latest member, so an external regenerator auto-rolls\n * forward unless the user has explicitly selected an earlier member.\n */\ntype RegenSelection =\n /** Explicit navigation via `selectSibling()`. The selected reply-run id. */\n | { kind: 'user'; selectedRunId: string }\n /** This view initiated a regenerate — auto-selected the new reply run when it arrived. */\n | { kind: 'auto'; selectedRunId: string }\n /**\n * This view's `regenerate()` is in flight. Keyed (in `_regenSelections`) by\n * the regenerate group's root; `carrierCodecMessageId` is the regenerate\n * carrier event's id, used to recognise the new reply run when it appears.\n */\n | { kind: 'pending'; carrierCodecMessageId: string };\n\n/**\n * A resolved branch point: the group `kind` plus the sibling nodes that make\n * up the alternatives. `fork-of` is an edit-style branch anchored at the user\n * input node; `regen` is a regenerate-style branch anchored at the assistant\n * slot. `groupRoot` is the group's key (input group root for fork-of, the\n * original reply's group root for regen).\n */\ntype MessageBranchPoint<TProjection> =\n | { kind: 'fork-of'; groupRoot: string; siblings: ConversationNode<TProjection>[] }\n | { kind: 'regen'; groupRoot: string; siblings: ConversationNode<TProjection>[] };\n\n// ---------------------------------------------------------------------------\n// Send-input normalisation\n// ---------------------------------------------------------------------------\n\n/**\n * Normalise the two input shapes `View.send` accepts (a single TInput\n * or an array) into the array shape the SendDelegate consumes.\n * @param input - The raw input from `View.send`.\n * @returns The normalised input array.\n */\nconst _normaliseSend = <TInput extends CodecInputEvent>(input: TInput | TInput[]): TInput[] =>\n Array.isArray(input) ? input : [input];\n\n// ---------------------------------------------------------------------------\n// Fetch tuning\n// ---------------------------------------------------------------------------\n\n/**\n * Multiplier applied to the user-supplied Run-unit `loadOlder(limit)`\n * when issuing the first `loadHistory` page request. `loadHistory`\n * counts complete domain *messages* per page, not Runs; a typical Run\n * produces ~2 messages (user + assistant). Asking for `limit * factor`\n * messages on the first page reduces extra round-trips when the actual\n * messages-per-Run ratio is around the factor. `_loadUntilVisible`\n * still loops on the Run count regardless, so this is purely a\n * fetch-efficiency hint.\n */\nconst _RUN_TO_MESSAGE_FETCH_FACTOR = 3;\n\n/**\n * Project a Tree `RunNode` down to the View-facing `RunInfo` shape:\n * drop the codec projection and the structural fields that callers\n * reach via `session.tree` when they need them.\n * @param run - The tree's RunNode.\n * @returns A projection-free RunInfo.\n */\nconst _toRunInfo = <TProjection>(run: RunNode<TProjection>): RunInfo => ({\n runId: run.runId,\n clientId: run.clientId,\n status: run.status,\n invocationId: run.invocationId,\n});\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nexport class DefaultView<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> implements View<TInput, TMessage> {\n private readonly _tree: TreeInternal<TInput, TOutput, TProjection>;\n private readonly _channel: Ably.RealtimeChannel;\n private readonly _codec: Codec<TInput, TOutput, TProjection, TMessage>;\n private readonly _sendDelegate: SendDelegate<TInput>;\n private readonly _logger: Logger;\n private readonly _emitter: EventEmitter<ViewEventsMap>;\n private readonly _onClose?: () => void;\n\n /**\n * View-local branch selections: group-root runId → selection intent.\n * Fork points not present here default to the latest sibling.\n */\n private readonly _branchSelections = new Map<string, BranchSelectionState>();\n\n /**\n * View-local regenerate-group selections: anchor codec-message-id (the assistant\n * codec-message-id being regenerated) → selection intent. Distinct from\n * {@link _branchSelections} because a regenerate group is a set of\n * same-parent reply runs — message-level alternatives at a single\n * conversation slot, not edit forks of the prompt. Groups not present here default to the latest\n * member (the most recent regenerator, or the original if no regen has\n * landed).\n */\n private readonly _regenSelections = new Map<string, RegenSelection>();\n\n /** Spec: AIT-CT11c — runIds loaded from history but not yet revealed to the UI. */\n private readonly _withheldRunIds = new Set<string>();\n\n /** Snapshot of visible node keys — used to detect structural changes and for selection pinning. */\n private _lastVisibleNodeKeys: string[] = [];\n\n /**\n * Snapshot of visible projection references — used to detect in-place\n * projection updates (streaming). One entry per visible Run.\n */\n private _lastVisibleProjections: TProjection[] = [];\n\n /**\n * Snapshot of the visible flat message chain with codec-message-ids —\n * exposed verbatim via `getMessages()` and the internal correlation\n * source for parent/branch routing.\n */\n private _lastVisibleMessagePairs: CodecMessage<TMessage>[] = [];\n\n /** Cached visible node-key Set — for O(1) lookup in event scoping. */\n private _lastVisibleNodeKeySet = new Set<string>();\n\n /** Whether there are more history pages to fetch from the channel. */\n private _hasMoreHistory = false;\n\n /** Internal state for continuing history pagination. */\n private _lastHistoryPage: HistoryPage | undefined;\n\n /** Buffer of withheld nodes (input + reply), drained newest-first by successive loadOlder() calls. */\n private readonly _withheldBuffer: ConversationNode<TProjection>[] = [];\n\n /** Unsubscribe functions for tree event subscriptions. */\n private readonly _unsubs: (() => void)[] = [];\n\n /**\n * Cached result of the last flat-nodes computation. Drives the visible\n * message snapshot exposed via `getMessages()`; refreshed by\n * `_computeFlatNodes()` on structural changes, selection changes,\n * and history reveal.\n */\n private _cachedNodes: ConversationNode<TProjection>[] = [];\n\n private _loadingOlder = false;\n private _processingHistory = false;\n private _closed = false;\n\n constructor(options: ViewOptions<TInput, TOutput, TProjection, TMessage>) {\n this._tree = options.tree;\n this._channel = options.channel;\n this._codec = options.codec;\n this._sendDelegate = options.sendDelegate;\n this._onClose = options.onClose;\n this._logger = options.logger.withContext({ component: 'View' });\n this._logger.trace('DefaultView();');\n this._emitter = new EventEmitter<ViewEventsMap>(this._logger);\n\n // Compute initial cache and snapshot visible state\n this._cachedNodes = this._computeFlatNodes();\n this._updateVisibleSnapshot(this._cachedNodes);\n\n // Subscribe to tree events and re-emit scoped versions\n this._unsubs.push(\n this._tree.on('update', () => {\n this._onTreeUpdate();\n }),\n this._tree.on('ably-message', (msg) => {\n this._onTreeAblyMessage(msg);\n }),\n this._tree.on('run', (event) => {\n this._onTreeRun(event);\n }),\n this._tree.on('output', (event) => {\n this._onTreeOutput(event);\n }),\n );\n }\n\n /**\n * Handle decoded outputs folded into a Run (streaming delta). If the run\n * is on the visible chain, recompute the flat message list and emit\n * `update`.\n * @param event - The output event from the Tree.\n */\n private _onTreeOutput(event: OutputEvent<TOutput>): void {\n if (this._processingHistory) return;\n // The fold target may be a reply run (event.runId) or a user input node\n // (event.runId undefined — the agent mints run-ids, so an input fold has\n // none). Gate on whichever key the visible set holds.\n const folded =\n (event.runId !== undefined && this._lastVisibleNodeKeySet.has(event.runId)) ||\n (event.inputCodecMessageId !== undefined && this._lastVisibleNodeKeySet.has(event.inputCodecMessageId));\n if (!folded) return;\n\n // The Tree emits `output` once per inbound message fold (with empty\n // `events` for inputs-only folds), so it fires whenever a visible Run's\n // projection changed and we always re-emit. The Reducer contract permits\n // in-place mutation, which means we cannot use projection-ref or\n // TMessage-ref equality to detect change: a streaming chunk legitimately\n // mutates the same UIMessage object, and a ref-equality short-circuit\n // would suppress every update. React state setters at the subscriber\n // boundary already dedup by array reference, so a redundant emit is a\n // no-op for unchanged hook consumers.\n this._lastVisibleProjections = this._cachedNodes.map((n) => n.projection);\n this._lastVisibleMessagePairs = this._extractMessages(this._cachedNodes);\n this._emitter.emit('update');\n }\n\n // -------------------------------------------------------------------------\n // Public query methods\n // -------------------------------------------------------------------------\n\n getMessages(): CodecMessage<TMessage>[] {\n return this._lastVisibleMessagePairs;\n }\n\n runs(): RunInfo[] {\n // `_cachedNodes` is the visible node chain (inputs + reply runs) with\n // pagination and sibling selection already applied. RunInfo is reply-run\n // shaped, so filter to runs before projecting.\n return this._cachedNodes\n .filter((node): node is RunNode<TProjection> => node.kind === 'run')\n .map((node) => _toRunInfo(node));\n }\n\n /**\n * Compute the fresh visible node chain. The Tree's `visibleNodes` already\n * applies kind-blind reachability and sibling selection (edit versions /\n * regenerate runs collapse to the selected member), so the View only layers\n * its pagination window on top: drop nodes whose key is currently withheld.\n * @returns A fresh array of visible nodes (inputs + reply runs).\n */\n private _computeFlatNodes(): ConversationNode<TProjection>[] {\n const treeNodes = this._treeVisibleNodes();\n if (this._withheldRunIds.size === 0) return treeNodes;\n return treeNodes.filter((node) => !this._withheldRunIds.has(nodeKey(node)));\n }\n\n /**\n * Recompute the visible node chain, refresh the cache + snapshot, and emit\n * `update` unconditionally. Use after a mutation that always changes the\n * visible output (e.g. an explicit selection or a withheld-batch reveal).\n */\n private _recomputeAndEmit(): void {\n this._cachedNodes = this._computeFlatNodes();\n this._updateVisibleSnapshot(this._cachedNodes);\n this._emitter.emit('update');\n }\n\n /**\n * Recompute the visible node chain and, only if it differs from the current\n * snapshot, refresh the cache + snapshot and emit `update`. Use after a\n * mutation that may or may not move the visible window (e.g. a structural\n * tree update, or a deferred regenerate promotion that may already match).\n */\n private _recomputeAndEmitIfChanged(): void {\n const nodes = this._computeFlatNodes();\n if (this._visibleChanged(nodes)) {\n this._cachedNodes = nodes;\n this._updateVisibleSnapshot(nodes);\n this._emitter.emit('update');\n }\n }\n\n /**\n * Resolve the reply Run that owns a codec-message-id, narrowing the Tree's\n * node union to a {@link RunNode}. A user-input codec-message-id resolves to\n * an input node and yields `undefined` here — callers that must handle input\n * nodes use {@link _tree.getNodeByCodecMessageId} directly.\n * @param codecMessageId - The codec-message-id to resolve.\n * @returns The owning RunNode, or undefined if absent or not a reply Run.\n */\n private _runByCodecMessageId(codecMessageId: string): RunNode<TProjection> | undefined {\n const node = this._tree.getNodeByCodecMessageId(codecMessageId);\n return node?.kind === 'run' ? node : undefined;\n }\n\n /**\n * Extract the flat TMessage[] from a visible node chain.\n *\n * In the two-node model the Tree's `visibleNodes` has already selected one\n * member per sibling group (the chosen edit version, the chosen regenerate\n * run), so a regenerate is just a sibling reply run that appears in place of\n * the original. Each visible node contributes its own messages in projection\n * order; the flat list is their concatenation.\n *\n * Deferred caveat: a mid-reply regenerate that replaces a non-head message\n * inside a multi-message reply run is not expressible as a sibling run in\n * this model and is not handled here (see the `regenerate-of-multi-message`\n * golden test).\n * @param nodes - The visible nodes (inputs + reply runs) in chronological order.\n * @returns The flat message list, each message paired with its codec-message-id.\n */\n private _extractMessages(nodes: ConversationNode<TProjection>[]): CodecMessage<TMessage>[] {\n const messages: CodecMessage<TMessage>[] = [];\n for (const node of nodes) {\n for (const m of this._codec.getMessages(node.projection)) {\n messages.push(m);\n }\n }\n return messages;\n }\n\n hasOlder(): boolean {\n return this._withheldBuffer.length > 0 || this._hasMoreHistory;\n }\n\n /**\n * Reveal up to `limit` older Runs in this view.\n *\n * The pagination unit is the **Run**, not the message. A single Run\n * typically materialises into multiple messages (e.g. user + assistant\n * pair) so revealing `limit` Runs may add several messages to the flat\n * list returned by {@link getMessages}. Channel pages don't align to\n * Run boundaries, so {@link _loadUntilVisible} keeps fetching channel\n * pages until at least `limit` Runs are buffered (or the channel is\n * exhausted).\n * @param limit - Maximum number of older Runs to reveal. Defaults to 100.\n */\n async loadOlder(limit = 100): Promise<void> {\n if (this._closed || this._loadingOlder) return;\n this._loadingOlder = true;\n this._logger.trace('DefaultView.loadOlder();', { limit });\n\n try {\n // Drain withheld buffer first (older nodes, released newest-first). The\n // buffer holds a union of input + reply nodes, so this splices the newest\n // `limit` NODES, not `limit` runs. Because an input node travels with the\n // reply run it precedes, a drain may surface fewer than `limit` runs.\n if (this._withheldBuffer.length > 0) {\n const batch = this._withheldBuffer.splice(-limit, limit);\n this._releaseWithheld(batch);\n return;\n }\n\n // Buffer exhausted - load from channel history.\n if (!this._hasMoreHistory && !this._lastHistoryPage) {\n await this._loadFirstPage(limit);\n return;\n }\n\n if (!this._hasMoreHistory) return;\n\n if (!this._lastHistoryPage?.hasNext()) {\n this._hasMoreHistory = false;\n return;\n }\n\n const nextPage = await this._lastHistoryPage.next();\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- close() may be called during await\n if (this._closed || !nextPage) {\n if (!nextPage) this._hasMoreHistory = false;\n return;\n }\n\n await this._revealFromPage(nextPage, limit);\n } catch (error) {\n this._logger.error('DefaultView.loadOlder(); failed', { error });\n throw error;\n } finally {\n this._loadingOlder = false;\n }\n }\n\n // -------------------------------------------------------------------------\n // Run lookup\n // -------------------------------------------------------------------------\n\n runOf(codecMessageId: string): RunInfo | undefined {\n this._logger.trace('DefaultView.runOf();', { codecMessageId });\n const node = this._tree.getNodeByCodecMessageId(codecMessageId);\n if (!node) return undefined;\n if (node.kind === 'run') return _toRunInfo(node);\n // Input node: resolve to its selected reply run (undefined if none started).\n const reply = this._selectedReplyRun(node.codecMessageId);\n return reply ? _toRunInfo(reply) : undefined;\n }\n\n /**\n * Resolve the reply run currently selected for an input node, honouring the\n * View's regenerate selection. Falls back to the latest reply run when no\n * selection has been recorded; undefined when no reply run has started.\n * @param inputCodecMessageId - The input node's codec-message-id.\n * @returns The selected reply RunNode, or undefined.\n */\n private _selectedReplyRun(inputCodecMessageId: string): RunNode<TProjection> | undefined {\n const replies = this._tree.getReplyRuns(inputCodecMessageId);\n if (replies.length === 0) return undefined;\n if (replies.length === 1) return replies[0];\n // Multiple reply runs = a regenerate group. Honour the View's selection\n // (keyed by group root) else default to the latest.\n const groupRoot = this._tree.getGroupRoot(replies[0]?.runId ?? '');\n const sel = this._regenSelections.get(groupRoot);\n const selectedKey = sel && sel.kind !== 'pending' ? sel.selectedRunId : undefined;\n if (selectedKey !== undefined) {\n const chosen = replies.find((r) => r.runId === selectedKey);\n if (chosen) return chosen;\n }\n // Latest by startSerial; getReplyRuns is set-ordered, so sort defensively.\n return replies.toSorted((a, b) => (a.startSerial ?? '￿').localeCompare(b.startSerial ?? '￿')).at(-1);\n }\n\n run(runId: string): RunInfo | undefined {\n this._logger.trace('DefaultView.run();', { runId });\n const run = this._tree.getRunNode(runId);\n return run ? _toRunInfo(run) : undefined;\n }\n\n // -------------------------------------------------------------------------\n // Branch navigation (msg-anchored)\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CT13c, AIT-CT13d — branch points are codec-message-id\n // anchored. The View resolves the anchor (the user prompt for edits,\n // the assistant slot for regens) and routes the selection to the\n // appropriate internal selection map. Tree-level introspection\n // (RunNode access, runId-keyed queries) remains on the {@link Tree}.\n\n branchSelection(codecMessageId: string): BranchSelection<TMessage> {\n const branch = this._resolveMessageBranchPoint(codecMessageId);\n if (branch) {\n // Each sibling contributes its head message as the branch-arrow slot:\n // for an edit fork that is the alternate user prompt; for a regenerate\n // group it is the variant's first (anchor-equivalent) message.\n const siblings = branch.siblings.flatMap((s) => {\n const first = this._codec.getMessages(s.projection).at(0);\n return first ? [first.message] : [];\n });\n\n if (siblings.length > 0) {\n const index = this._resolveSelectedIndex(branch);\n const clamped = Math.max(0, Math.min(index, siblings.length - 1));\n const selected = siblings[clamped];\n return {\n hasSiblings: siblings.length > 1,\n siblings,\n index: clamped,\n selected,\n };\n }\n }\n\n // Known non-anchor message: the bundle's invariant is that\n // `siblings` contains the rendered message itself for any known\n // codec-message-id, so plain bubbles get `siblings.length === 1`\n // (not `0`) and the indexing space matches between read and write.\n // Resolve the owning node kind-blind — a plain user prompt is an input\n // node, an assistant message lives in a reply run; both carry a projection.\n const owner = this._tree.getNodeByCodecMessageId(codecMessageId);\n if (owner) {\n const found = this._codec.getMessages(owner.projection).find((m) => m.codecMessageId === codecMessageId);\n if (found !== undefined) {\n return { hasSiblings: false, siblings: [found.message], index: 0, selected: found.message };\n }\n }\n\n // Unknown id, or the owner Run is known but the codec doesn't surface\n // a message with this id from the projection (e.g. an event-only fold\n // such as a tool result that mutates an assistant in-place without\n // exposing its own TMessage). Treat both as \"no rendered message\",\n // returning the safe empty bundle.\n return { hasSiblings: false, siblings: [], index: 0, selected: undefined };\n }\n\n // Spec: AIT-CT13c, AIT-CT13d\n selectSibling(codecMessageId: string, index: number): void {\n this._logger.trace('DefaultView.selectSibling();', { codecMessageId, index });\n const branch = this._resolveMessageBranchPoint(codecMessageId);\n if (!branch) return;\n const clamped = Math.max(0, Math.min(index, branch.siblings.length - 1));\n const selected = branch.siblings[clamped];\n if (!selected) return; // unreachable: clamped is always in bounds\n if (branch.kind === 'fork-of') {\n this._branchSelections.set(branch.groupRoot, { kind: 'user', selectedKey: nodeKey(selected) });\n this._logger.debug('DefaultView.selectSibling(); fork-of', {\n codecMessageId,\n index: clamped,\n selectedKey: nodeKey(selected),\n });\n } else {\n this._regenSelections.set(branch.groupRoot, { kind: 'user', selectedRunId: nodeKey(selected) });\n this._logger.debug('DefaultView.selectSibling(); regenerate', {\n codecMessageId,\n index: clamped,\n selectedRunId: nodeKey(selected),\n groupRoot: branch.groupRoot,\n });\n }\n this._recomputeAndEmit();\n }\n\n /**\n * Resolve the currently selected sibling's index inside a branch group.\n * Pending selections fall back to the latest sibling. The caller clamps\n * the returned index against any post-extraction filtering.\n * @param branch - Resolved branch-point descriptor from `_resolveMessageBranchPoint`.\n * @returns The selected sibling's index within `branch.siblings`.\n */\n private _resolveSelectedIndex(branch: MessageBranchPoint<TProjection>): number {\n if (branch.kind === 'fork-of') {\n const sel = this._branchSelections.get(branch.groupRoot);\n if (!sel) return branch.siblings.length - 1;\n const idx = branch.siblings.findIndex((n) => nodeKey(n) === sel.selectedKey);\n return idx === -1 ? branch.siblings.length - 1 : idx;\n }\n const sel = this._regenSelections.get(branch.groupRoot);\n if (!sel || sel.kind === 'pending') return branch.siblings.length - 1;\n const idx = branch.siblings.findIndex((n) => nodeKey(n) === sel.selectedRunId);\n return idx === -1 ? branch.siblings.length - 1 : idx;\n }\n\n /**\n * Resolve the branch point anchored at `codecMessageId`, if any.\n *\n * Returns the resolved group `kind` along with the sibling list so the\n * caller can update the correct selection map without re-entering the\n * runId-based `select()` dispatch (which biases to fork-of first and\n * would mis-route a regen-anchor codec-message-id when the owning Run is in\n * BOTH groups — e.g. R1 owns both a user prompt that got edited and\n * an assistant that got regenerated).\n *\n * Two anchor cases:\n * - **fork-of** — `codecMessageId` is the first message of a Run in a fork-of\n * sibling group (edit-style branch point anchored at the user prompt).\n * - **regen** — `codecMessageId` is the regen-anchor itself (in the owner Run)\n * or content of a regenerator Run (regen-style branch point anchored\n * at the assistant slot).\n * @param codecMessageId - The codec-message-id to look up.\n * @returns The kind + sibling list + group key (runId for fork-of,\n * anchor codec-message-id for regen), or undefined when `codecMessageId` is not an\n * anchor in either group type.\n */\n private _resolveMessageBranchPoint(codecMessageId: string): MessageBranchPoint<TProjection> | undefined {\n const node = this._tree.getNodeByCodecMessageId(codecMessageId);\n if (!node) return undefined;\n\n // Edit-fork branch point: `codecMessageId` is a user INPUT node that has\n // sibling input nodes (alternate prompts via fork-of). The anchor is the\n // input node's own codec-message-id.\n if (node.kind === 'input') {\n const siblings = this._tree.getSiblingNodes(node.codecMessageId);\n if (siblings.length > 1) {\n return { kind: 'fork-of', groupRoot: this._tree.getGroupRoot(node.codecMessageId), siblings };\n }\n return undefined;\n }\n\n // Regenerate branch point: `codecMessageId` is owned by a reply run that has\n // sibling reply runs (the original reply + its regenerators, all parented at\n // the same input node). Anchor on the head message of the run so arrows\n // appear once per variant, not on every follow-up message.\n const siblings = this._tree.getSiblingNodes(node.runId);\n if (siblings.length > 1) {\n const firstMsg = this._codec.getMessages(node.projection).at(0);\n if (firstMsg?.codecMessageId === codecMessageId) {\n return { kind: 'regen', groupRoot: this._tree.getGroupRoot(node.runId), siblings };\n }\n }\n\n return undefined;\n }\n\n // -------------------------------------------------------------------------\n // Write operations\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CT3, AIT-CT4\n async send(input: TInput | TInput[], options?: SendOptions): Promise<ActiveRun> {\n this._logger.trace('DefaultView.send();');\n if (this._closed) {\n throw new Ably.ErrorInfo('unable to send; view is closed', ErrorCode.InvalidArgument, 400);\n }\n\n const normalised = _normaliseSend<TInput>(input);\n\n // The codec-message-id of the visible branch tail — the delegate uses it\n // for auto-parent routing on fresh user messages.\n const parentCodecMessageId = this._lastVisibleMessagePairs.at(-1)?.codecMessageId;\n\n const result = await this._sendDelegate(normalised, options, parentCodecMessageId);\n this._applyForkAutoSelect(result, options);\n return result;\n }\n\n /**\n * Auto-select / pin branch selections after a forking send.\n * @param result - The ActiveRun returned by the delegate.\n * @param options - The SendOptions passed by the caller.\n */\n private _applyForkAutoSelect(result: ActiveRun, options: SendOptions | undefined): void {\n // Spec: AIT-CT13e\n if (!options?.forkOf) return;\n\n // An edit inserts a NEW user input node optimistically; its codec-message-id\n // is the (only) optimistic id and IS its node key. Edit forks are input-node\n // sibling groups, so the selection is keyed by the input group root and the\n // selected member is the new input node's key.\n const editedInputKey = result.optimisticCodecMessageIds.at(0);\n if (editedInputKey === undefined) return;\n const groupRoot = this._tree.getGroupRoot(editedInputKey);\n\n this._branchSelections.set(groupRoot, { kind: 'auto', selectedKey: editedInputKey });\n this._recomputeAndEmit();\n }\n\n /**\n * Auto-select / pin the regenerate group anchored at `anchorCodecMessageId` so\n * the new Run's content appears as soon as the agent's run-start lands.\n *\n * `View.regenerate()` calls this with the assistant codec-message-id being\n * regenerated. The Run doesn't exist yet on the channel (the regenerate\n * wire is wire-only); the selection is recorded as `pending` and\n * promoted to `auto` by `_pinRegenSelections` once the corresponding\n * Run is created in the tree.\n * @param result - The ActiveRun returned by the delegate (run-id is the new regenerator's).\n * @param anchorCodecMessageId - The codec-message-id of the assistant being regenerated.\n */\n private _applyRegenerateAutoSelect(result: ActiveRun, anchorCodecMessageId: string): void {\n // A regenerate produces a new reply run parented at the SAME input node as\n // the original reply (the regenerate group). The agent mints the run-id, so\n // we cannot pin by it synchronously. Resolve the group root from the\n // original reply run owning the anchor, and pin a pending selection keyed by\n // that group root, carrying the regenerate carrier's codec-message-id\n // (`result.inputCodecMessageId`) so we can promote when the new reply run lands.\n const anchorRun = this._runByCodecMessageId(anchorCodecMessageId);\n if (!anchorRun) return;\n const groupRoot = this._tree.getGroupRoot(anchorRun.runId);\n\n this._regenSelections.set(groupRoot, {\n kind: 'pending',\n carrierCodecMessageId: result.inputCodecMessageId,\n });\n this._logger.debug('DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection', {\n anchorCodecMessageId,\n groupRoot,\n carrier: result.inputCodecMessageId,\n });\n\n // The new reply run may already be in the tree (run-start raced ahead of the\n // sendDelegate resolution). Promote now and recompute so the visible set\n // catches up without waiting for the next structural change.\n this._resolvePendingRegenSelections();\n this._recomputeAndEmitIfChanged();\n }\n\n // Spec: AIT-CT5, AIT-CT13d\n async regenerate(messageId: string, options?: SendOptions): Promise<ActiveRun> {\n this._logger.trace('DefaultView.regenerate();', { messageId });\n\n if (this._closed) {\n throw new Ably.ErrorInfo('unable to regenerate; view is closed', ErrorCode.InvalidArgument, 400);\n }\n\n // `messageId` is the assistant being regenerated. The new Run is a\n // continuation of the regenerated message's Run, not a fork: the\n // message-level replacement (new assistant supersedes the original)\n // happens at projection extraction time. We still resolve the parent\n // user prompt so the new assistant's wire `parent` is correct,\n // and we send the truncated history (through the parent inclusive)\n // so the LLM re-answers the right message.\n const targetRun = this._runByCodecMessageId(messageId);\n if (!targetRun) {\n throw new Ably.ErrorInfo(\n `unable to regenerate; message not found in tree: ${messageId}`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n const parentCodecMessageId = this._findParentMsgId(targetRun, messageId);\n if (!parentCodecMessageId) {\n throw new Ably.ErrorInfo(\n `unable to regenerate; parent user message not found for ${messageId}`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n\n // Canonical regen anchor: when the user clicks Regenerate on an\n // already-regenerated assistant, the new alternative SHOULD belong\n // to the SAME branch point as the previous regen — but ONLY when\n // the target is the position-equivalent of the group anchor (the\n // head message of the regenerator Run). For a trailing follow-up\n // message inside a regenerator Run (e.g. the LLM text after the\n // regenerated tool call), the user expects the regen to anchor at\n // the specific message they clicked, not roll up to the group root.\n // Rebasing trailing regens to the group root produces a confusing\n // \"N+1 / N+1\" counter on the tool-call bubble and runs the whole\n // turn from scratch instead of just regenerating the text.\n let regenAnchorMsgId = messageId;\n if (targetRun.regeneratesCodecMessageId !== undefined) {\n const firstMsg = this._codec.getMessages(targetRun.projection).at(0);\n if (firstMsg?.codecMessageId === messageId) {\n regenAnchorMsgId = targetRun.regeneratesCodecMessageId;\n }\n }\n\n const sendOptions: SendOptions = {\n ...options,\n parent: parentCodecMessageId,\n };\n\n // Mint a regenerate input via the codec. The codec's well-known\n // `Regenerate` carries `target: regenAnchorMsgId` and `parent:\n // parentCodecMessageId`; the session reads those fields off the input\n // directly when building transport headers (`fork-of` and\n // `parent`). The agent's input-event lookup catches the wire signal;\n // no tree-upsert / projection fold runs locally.\n const regenerate = this._codec.createRegenerate(regenAnchorMsgId, parentCodecMessageId);\n const result = await this._sendDelegate([regenerate], sendOptions, parentCodecMessageId);\n this._applyRegenerateAutoSelect(result, regenAnchorMsgId);\n return result;\n }\n\n // Spec: AIT-CT6\n async edit(messageId: string, inputs: TInput | TInput[], options?: SendOptions): Promise<ActiveRun> {\n this._logger.trace('DefaultView.edit();', { messageId });\n\n if (this._closed) {\n throw new Ably.ErrorInfo('unable to edit; view is closed', ErrorCode.InvalidArgument, 400);\n }\n\n // The edit target is a user prompt — a run-less INPUT node — so resolve\n // it kind-blind, not via the reply-run-only lookup.\n const targetNode = this._tree.getNodeByCodecMessageId(messageId);\n if (!targetNode) {\n throw new Ably.ErrorInfo(\n `unable to edit; message not found in tree: ${messageId}`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n const parentCodecMessageId = this._findParentMsgId(targetNode, messageId);\n\n return this.send(inputs, {\n ...options,\n forkOf: messageId,\n parent: parentCodecMessageId,\n });\n }\n\n /**\n * Find the codec-message-id of the message immediately preceding `targetMsgId` in\n * the visible conversation.\n *\n * Consults the View's visible message chain first so message-level\n * replacements (regenerate) are respected: regenerating an\n * already-regenerated assistant lands the predecessor on the user\n * prompt the regen is responding to, NOT on the hidden original\n * assistant that occupies the same conversation slot. Falls back to a\n * projection-walk for the rare case where `targetMsgId` isn't on the\n * visible chain (e.g. caller is operating on a Run that's selection-\n * hidden by the current branch).\n * @param targetNode - The node (input node or reply run) that owns `targetMsgId`.\n * @param targetMsgId - The codec-message-id to find the parent of.\n * @returns The parent codec-message-id, or undefined if no predecessor exists.\n */\n private _findParentMsgId(targetNode: ConversationNode<TProjection>, targetMsgId: string): string | undefined {\n const visible = this._lastVisibleMessagePairs;\n const visIdx = visible.findIndex((m) => m.codecMessageId === targetMsgId);\n if (visIdx > 0) {\n return visible[visIdx - 1]?.codecMessageId;\n }\n if (visIdx === 0) return undefined;\n\n const messages = this._codec.getMessages(targetNode.projection);\n const idx = messages.findIndex((m) => m.codecMessageId === targetMsgId);\n if (idx > 0) {\n return messages[idx - 1]?.codecMessageId;\n }\n if (idx === 0 && targetNode.parentCodecMessageId !== undefined) {\n // The structural predecessor is the node owning parentCodecMessageId\n // (an input node, or a prior reply run). Its tail message is the parent.\n const parentNode = this._tree.getNodeByCodecMessageId(targetNode.parentCodecMessageId);\n if (parentNode) {\n return this._codec.getMessages(parentNode.projection).at(-1)?.codecMessageId;\n }\n }\n return undefined;\n }\n\n // -------------------------------------------------------------------------\n // Event subscription\n // -------------------------------------------------------------------------\n\n // Spec: AIT-CT8a, AIT-CT8b, AIT-CT8e\n on(event: 'update', handler: () => void): () => void;\n on(event: 'ably-message', handler: (msg: Ably.InboundMessage) => void): () => void;\n on(event: 'run', handler: (event: RunLifecycleEvent) => void): () => void;\n on(\n event: 'update' | 'ably-message' | 'run',\n handler: (() => void) | ((msg: Ably.InboundMessage) => void) | ((event: RunLifecycleEvent) => void),\n ): () => void {\n // CAST: overload signatures enforce correct handler types per event name.\n const cb = handler as (arg: ViewEventsMap[keyof ViewEventsMap]) => void;\n this._emitter.on(event, cb);\n return () => {\n this._emitter.off(event, cb);\n };\n }\n\n // -------------------------------------------------------------------------\n // Lifecycle\n // -------------------------------------------------------------------------\n\n close(): void {\n if (this._closed) return;\n this._logger.info('DefaultView.close();');\n this._closed = true;\n this._loadingOlder = false;\n for (const unsub of this._unsubs) unsub();\n this._unsubs.length = 0;\n this._emitter.off();\n this._branchSelections.clear();\n this._regenSelections.clear();\n this._withheldRunIds.clear();\n this._withheldBuffer.length = 0;\n this._onClose?.();\n }\n\n // -------------------------------------------------------------------------\n // Private: history loading\n // -------------------------------------------------------------------------\n\n private async _loadFirstPage(limit: number): Promise<void> {\n // loadHistory's limit counts complete domain messages per page (not\n // Runs); see `_RUN_TO_MESSAGE_FETCH_FACTOR` for the scaling rationale.\n const messageLimit = limit * _RUN_TO_MESSAGE_FETCH_FACTOR;\n const firstPage = await loadHistory(this._channel, { limit: messageLimit }, this._logger);\n if (this._closed) return;\n await this._revealFromPage(firstPage, limit);\n }\n\n /**\n * Walk channel history from `page` until at least `limit` new Runs are\n * observed (or the channel is exhausted), then reveal the newest batch and\n * withhold the rest. Snapshots the already-visible nodes up front so only\n * newly-observed Runs count toward `limit`. No-op if the view closed during\n * the page walk.\n * @param page - The decoded history page to start from.\n * @param limit - Max Runs to reveal in this batch.\n */\n private async _revealFromPage(page: HistoryPage, limit: number): Promise<void> {\n // Snapshot before loading: every node already in the tree stays visible.\n const beforeRunIds = new Set(this._treeVisibleNodes().map((n) => nodeKey(n)));\n\n const { newVisible, lastPage } = await this._loadUntilVisible(page, limit, beforeRunIds);\n if (this._closed) return;\n this._lastHistoryPage = lastPage;\n this._hasMoreHistory = lastPage.hasNext();\n this._splitReveal(newVisible, limit);\n }\n\n /**\n * Reveal the newest `limit` Runs from `newVisible` and withhold the rest\n * so subsequent `loadOlder` calls can drain them. Called by\n * {@link _revealFromPage} to enforce the Run-unit pagination contract.\n * @param newVisible - Newly observed Runs from the history fetch.\n * @param limit - Max Runs to reveal in this batch.\n */\n private _splitReveal(newVisible: ConversationNode<TProjection>[], limit: number): void {\n // Reveal granularity is the reply RUN; an input node travels with the reply\n // run it precedes. Walk newest-first, counting reply runs toward `limit`,\n // and split the union list at the resulting boundary so an input + its reply\n // are revealed or withheld together.\n let runs = 0;\n let splitIdx = newVisible.length; // index of first revealed node\n for (let i = newVisible.length - 1; i >= 0; i--) {\n const node = newVisible[i];\n if (node?.kind === 'run') {\n if (runs === limit) break;\n runs++;\n }\n splitIdx = i;\n }\n const batch = newVisible.slice(splitIdx);\n const withheld = newVisible.slice(0, splitIdx);\n for (const n of withheld) {\n this._withheldRunIds.add(nodeKey(n));\n }\n this._withheldBuffer.push(...withheld);\n this._releaseWithheld(batch);\n }\n\n /**\n * Replay a history page's raw messages into the Tree. Dispatches by Ably\n * message name to run-lifecycle vs. regular wire messages, mirroring the\n * live `client-session._handleMessage` decode loop. Uses a fresh decoder\n * since the session's live decoder maintains its own stream-tracker state.\n * @param page - The history page returned by `loadHistory`.\n */\n private _processHistoryPage(page: HistoryPage): void {\n this._processingHistory = true;\n try {\n // Reconstruct the tree via the shared decode-fold engine — the same path\n // the client's live loop uses, so history replay can't drift from it.\n const decoder = this._codec.createDecoder();\n for (const rawMsg of page.rawMessages) {\n applyWireMessage(this._tree, decoder, rawMsg);\n }\n\n // Emit ably-message in a batch AFTER the whole page is applied, so a\n // subscriber resolving the owning Run sees the fully-rebuilt tree.\n for (const msg of page.rawMessages) {\n this._tree.emitAblyMessage(msg);\n }\n } finally {\n this._processingHistory = false;\n }\n }\n\n private async _loadUntilVisible(\n firstPage: HistoryPage,\n target: number,\n beforeRunIds: Set<string>,\n ): Promise<{ newVisible: ConversationNode<TProjection>[]; lastPage: HistoryPage }> {\n this._processHistoryPage(firstPage);\n let page = firstPage;\n\n const newVisibleCount = (): number => {\n let count = 0;\n for (const n of this._treeVisibleNodes()) {\n // Pagination counts reply RUNS toward the target (an input node travels\n // with the reply run it precedes — see `_splitReveal`).\n if (n.kind === 'run' && !beforeRunIds.has(nodeKey(n))) count++;\n }\n return count;\n };\n\n while (newVisibleCount() < target && page.hasNext()) {\n const nextPage = await page.next();\n if (!nextPage || this._closed) break;\n this._processHistoryPage(nextPage);\n page = nextPage;\n }\n\n const newVisible = this._treeVisibleNodes().filter((n) => !beforeRunIds.has(nodeKey(n)));\n return { newVisible, lastPage: page };\n }\n\n // Spec: AIT-CT11a\n private _releaseWithheld(nodes: ConversationNode<TProjection>[]): void {\n for (const n of nodes) {\n this._withheldRunIds.delete(nodeKey(n));\n }\n if (nodes.length > 0) {\n this._recomputeAndEmit();\n }\n }\n\n // -------------------------------------------------------------------------\n // Private: scoped event forwarding\n // -------------------------------------------------------------------------\n\n private _updateVisibleSnapshot(nodes?: ConversationNode<TProjection>[]): void {\n const resolved = nodes ?? this._cachedNodes;\n // Identity key = nodeKey (runId for reply runs, codecMessageId for inputs),\n // so the visible set scopes events for both kinds and input-node parents.\n this._lastVisibleNodeKeys = resolved.map((n) => nodeKey(n));\n this._lastVisibleNodeKeySet = new Set(this._lastVisibleNodeKeys);\n this._lastVisibleProjections = resolved.map((n) => n.projection);\n this._lastVisibleMessagePairs = this._extractMessages(resolved);\n }\n\n private _onTreeUpdate(): void {\n // Suppress update forwarding while processing history pages. During\n // _processHistoryPage, each tree.applyMessage() fires this handler\n // synchronously — but _withheldRunIds hasn't been populated yet, so\n // _computeFlatNodes() would return unfiltered history. Without this guard,\n // subscribers briefly see all history Runs before the pagination window\n // is applied. The final update is emitted by _releaseWithheld after\n // withholding is set up.\n if (this._processingHistory) return;\n\n // The Tree emits `update` only on structural change (new/removed Run,\n // sort-reorder, startSerial promotion, run-start backfill), so every\n // update reaching here warrants a full re-walk. Content-only folds flow\n // through `output` (_onTreeOutput) instead.\n\n // Pin selections for previously-visible Runs that now have siblings.\n // This prevents new forks (from other views' edits/regenerates) from\n // shifting this view to a branch the user didn't navigate to.\n this._pinBranchSelections();\n this._resolvePendingRegenSelections();\n\n this._recomputeAndEmitIfChanged();\n }\n\n /**\n * Build the unified selection map the Tree's `visibleNodes` consumes:\n * `groupRootKey -> selectedKey`, covering both edit forks (input-node groups,\n * keyed by the input group root) and regenerate groups (reply-run groups,\n * keyed by the original reply's group root). Pending entries (no chosen\n * member yet) are omitted so the Tree falls back to the latest sibling.\n * @returns The merged group-root → selected-key map.\n */\n private _resolveSelections(): Map<string, string> {\n const resolved = new Map<string, string>();\n for (const [groupRoot, sel] of this._branchSelections) {\n resolved.set(groupRoot, sel.selectedKey);\n }\n for (const [groupRoot, sel] of this._regenSelections) {\n if (sel.kind === 'pending') continue;\n resolved.set(groupRoot, sel.selectedRunId);\n }\n return resolved;\n }\n\n /**\n * The Tree's visible node chain under this view's current selections — the\n * reachable, sibling-resolved nodes before the View's pagination window is\n * applied.\n * @returns The selection-resolved visible node chain.\n */\n private _treeVisibleNodes(): ConversationNode<TProjection>[] {\n return this._tree.visibleNodes(this._resolveSelections());\n }\n\n /**\n * For each previously-visible Run that now has siblings but no explicit\n * selection, pin the selection to that Run's runId. This preserves the\n * current branch when new forks appear from other views or external\n * sources.\n *\n * Exception: if the fork was initiated by this view (tracked as a\n * `pending` BranchSelection), select the newest sibling (the awaited Run)\n * instead of pinning the old one.\n */\n private _pinBranchSelections(): void {\n for (const key of this._lastVisibleNodeKeys) {\n const node = this._tree.getNode(key);\n // Edit forks are INPUT-node sibling groups; only input nodes pin here.\n // Regenerate (reply-run) groups roll forward via _resolvePendingRegenSelections.\n if (node?.kind !== 'input') continue;\n const siblings = this._tree.getSiblingNodes(key);\n if (siblings.length <= 1) continue;\n const groupRoot = this._tree.getGroupRoot(key);\n const existing = this._branchSelections.get(groupRoot);\n\n // Spec: AIT-CT13f — external edit fork: pin to the currently-visible\n // sibling so a fork from another view doesn't drift this view's branch.\n if (existing) continue;\n this._branchSelections.set(groupRoot, { kind: 'pinned', selectedKey: key });\n }\n }\n\n /**\n * Roll `pending` and `auto` regenerate selections forward to the newest\n * group member. A regenerate slot defaults to the latest member, so each\n * new regenerator (this view's awaited run, or an external one) auto-rolls\n * the slot forward — UNLESS the user explicitly selected an earlier member\n * (`user`), which pins and is left untouched. The agent mints the run-id, so\n * we can't match the awaited run by id — once the group grows we adopt the\n * newest as the selected member.\n */\n private _resolvePendingRegenSelections(): void {\n for (const [groupRoot, sel] of this._regenSelections) {\n if (sel.kind === 'user') continue;\n const group = this._tree.getSiblingNodes(groupRoot).filter((n): n is RunNode<TProjection> => n.kind === 'run');\n if (group.length <= 1) continue;\n const newest = group.at(-1);\n if (!newest) continue;\n this._regenSelections.set(groupRoot, { kind: 'auto', selectedRunId: newest.runId });\n }\n }\n\n private _onTreeAblyMessage(msg: Ably.InboundMessage): void {\n // Re-emit only if the message corresponds to a visible Run\n const headers = getTransportHeaders(msg);\n const codecMessageId = headers[HEADER_CODEC_MESSAGE_ID];\n const runId = headers[HEADER_RUN_ID];\n\n if (!codecMessageId && !runId) {\n // Lifecycle / control events with no run/message identity (cancel, error)\n // are always forwarded.\n this._emitter.emit('ably-message', msg);\n return;\n }\n\n if (runId && this._lastVisibleNodeKeySet.has(runId)) {\n this._emitter.emit('ably-message', msg);\n }\n }\n\n private _onTreeRun(event: RunLifecycleEvent): void {\n // Check if the run is already on the visible branch.\n if (this._lastVisibleNodeKeySet.has(event.runId)) {\n this._emitter.emit('run', event);\n return;\n }\n\n // For run-start, use branch metadata to predict visibility before\n // messages arrive. Own runs have optimistic inserts (caught above).\n // Remote runs carry parent/forkOf from the agent.\n if (event.type === 'start' && this._isRunStartVisible(event)) {\n this._lastVisibleNodeKeySet.add(event.runId);\n this._emitter.emit('run', event);\n }\n }\n\n /**\n * Predict whether a run-start's messages will be visible on this view's\n * branch using the parent/forkOf metadata from the event.\n * @param event - The run-start lifecycle event.\n * @returns True if the run is expected to be visible on this view's branch.\n */\n private _isRunStartVisible(event: RunLifecycleEvent & { type: 'start' }): boolean {\n const { parent } = event;\n\n // No parent metadata — can't determine branch, forward as default.\n if (parent === undefined) return true;\n\n // The wire `parent` is a codec-message-id (the prior message). Resolve it\n // kind-blind to its owning NODE — an input node (the user prompt this run\n // replies to) or a prior reply run — and check that node's key against the\n // visible set. Input-node keys are populated into the set by\n // _updateVisibleSnapshot.\n const parentNode = this._tree.getNodeByCodecMessageId(parent);\n if (!parentNode) return true; // unknown parent: forward conservatively\n return this._lastVisibleNodeKeySet.has(nodeKey(parentNode));\n }\n\n private _visibleChanged(newNodes: ConversationNode<TProjection>[]): boolean {\n if (newNodes.length !== this._lastVisibleNodeKeys.length) return true;\n for (const [i, node] of newNodes.entries()) {\n if (nodeKey(node) !== this._lastVisibleNodeKeys[i]) return true;\n if (node.projection !== this._lastVisibleProjections[i]) return true;\n }\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a View that projects a paginated window over a Tree.\n * @param options - The tree, channel, codec, and logger to use.\n * @returns A new {@link DefaultView} instance.\n */\nexport const createView = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>(\n options: ViewOptions<TInput, TOutput, TProjection, TMessage>,\n): DefaultView<TInput, TOutput, TProjection, TMessage> => new DefaultView(options);\n","/**\n * Core client-side session, parameterized by codec.\n *\n * Composes the conversation Tree to handle the full client-side lifecycle.\n * `connect()` subscribes to the Ably channel (which implicitly attaches it).\n * The same subscription, decoder, and channel are reused across runs.\n *\n * The client publishes user messages directly to the channel via the shared\n * codec encoder. It does not send HTTP: waking an agent is the application's\n * concern — it POSTs `run.toInvocation().toJSON()` to its own endpoint if and\n * when it wants one woken (the Vercel ChatTransport does this for useChat\n * parity). The agent locates the triggering input event by its `event-id`\n * header and publishes run lifecycle events (run-start, run-end) plus assistant\n * chunks, minting and stamping the invocation-id itself. The channel is the\n * durable session record; agents that weren't running at publish time can\n * resume by reading channel rewind.\n */\n\nimport * as Ably from 'ably';\n\nimport {\n EVENT_CANCEL,\n EVENT_RUN_END,\n HEADER_CODEC_MESSAGE_ID,\n HEADER_ERROR_CODE,\n HEADER_ERROR_MESSAGE,\n HEADER_EVENT_ID,\n HEADER_INPUT_CODEC_MESSAGE_ID,\n HEADER_INVOCATION_ID,\n HEADER_PARENT,\n HEADER_ROLE,\n HEADER_RUN_ID,\n HEADER_RUN_REASON,\n} from '../../constants.js';\nimport { ErrorCode } from '../../errors.js';\nimport { EventEmitter } from '../../event-emitter.js';\nimport type { Logger } from '../../logger.js';\nimport { LogLevel, makeLogger } from '../../logger.js';\nimport { getTransportHeaders } from '../../utils.js';\nimport { registerAgent } from '../agent.js';\nimport type { CodecInputEvent, CodecOutputEvent, Decoder, Encoder } from '../codec/types.js';\nimport { applyWireMessage } from './decode-fold.js';\nimport { buildTransportHeaders } from './headers.js';\nimport { Invocation } from './invocation.js';\nimport type { DefaultTree } from './tree.js';\nimport { createTree } from './tree.js';\nimport type { ActiveRun, ClientSession, ClientSessionOptions, RunEndReason, SendOptions, Tree, View } from './types.js';\nimport { createView, type DefaultView } from './view.js';\n\n/**\n * Returned from `on()` when the session is already closed — the subscription\n * is silently ignored since no further events will fire.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-function -- intentional no-op\nconst noopUnsubscribe = (): void => {};\n\n// ---------------------------------------------------------------------------\n// Internal state machine\n// ---------------------------------------------------------------------------\n\nenum ClientSessionState {\n READY = 'ready',\n CLOSED = 'closed',\n}\n\n// ---------------------------------------------------------------------------\n// Event map for the session's typed EventEmitter\n// ---------------------------------------------------------------------------\n\ninterface ClientSessionEventsMap {\n error: Ably.ErrorInfo;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\n// Spec: AIT-CT1\nclass DefaultClientSession<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> implements ClientSession<TInput, TOutput, TProjection, TMessage> {\n private readonly _channel: Ably.RealtimeChannel;\n private readonly _codec: ClientSessionOptions<TInput, TOutput, TProjection, TMessage>['codec'];\n private readonly _clientId: string | undefined;\n private readonly _logger: Logger;\n\n // Typed event emitter — the session emits only 'error'; all data events live on Tree/View\n private readonly _emitter: EventEmitter<ClientSessionEventsMap>;\n\n // Sub-components\n private readonly _tree: DefaultTree<TInput, TOutput, TProjection>;\n private readonly _view: DefaultView<TInput, TOutput, TProjection, TMessage>;\n private readonly _views = new Set<DefaultView<TInput, TOutput, TProjection, TMessage>>();\n private readonly _decoder: Decoder<TInput, TOutput>;\n /**\n * Shared encoder for the lifetime of the session. The client only ever\n * uses `publishInput` (input wire), so the encoder's stream tracker map\n * stays empty across the session. Closed once on session close.\n */\n private readonly _encoder: Encoder<TInput, TOutput>;\n\n // Spec: AIT-CT10, AIT-CT10a\n readonly tree: Tree<TOutput, TProjection>;\n readonly view: View<TInput, TMessage>;\n\n // Channel subscription is established lazily on connect()\n private _connectPromise: Promise<void> | undefined;\n private readonly _onMessage: (msg: Ably.InboundMessage) => void;\n\n private _state = ClientSessionState.READY;\n private _hasAttachedOnce: boolean;\n private readonly _onChannelStateChange: Ably.channelEventCallback;\n\n /**\n * Backing settlers for each in-flight run's `ActiveRun.runId` promise.\n * Resolved with the agent-minted run-id when the matching `ai-run-start`\n * (fresh send) or `ai-run-resume` (continuation) is observed; rejected if\n * the session closes first. There is no deadline —\n * `send()` resolves on publish and does not block on run-start.\n *\n * Keyed by the triggering input's codec-message-id — the handle the client\n * owns at send time, which the agent echoes back on run-start as\n * `input-codec-message-id`. This is uniform across fresh sends and\n * continuations (a continuation is itself an input event — tool-approval or\n * tool-result — with its own codec-message-id), so reconciliation never\n * depends on a client-minted run/invocation id.\n */\n private readonly _pendingRunStarts = new Map<\n string,\n { resolve: (runId: string) => void; reject: (e: Ably.ErrorInfo) => void }\n >();\n\n constructor(options: ClientSessionOptions<TInput, TOutput, TProjection, TMessage>) {\n // Spec: AIT-CT1a, AIT-CT1a2 — register this SDK on both the connection\n // (options.agents) and channel-attach (params.agent) paths. Idempotent\n // across sessions sharing one client.\n const channelOptions = registerAgent(options.client, options.codec);\n this._channel = options.client.channels.get(options.channelName, channelOptions);\n this._codec = options.codec;\n this._clientId = options.clientId;\n this._logger = (options.logger ?? makeLogger({ logLevel: LogLevel.Silent })).withContext({\n component: 'ClientSession',\n });\n\n this._emitter = new EventEmitter<ClientSessionEventsMap>(this._logger);\n this._hasAttachedOnce = this._channel.state === 'attached';\n\n // Compose sub-components\n this._tree = createTree<TInput, TOutput, TProjection>(this._codec, this._logger);\n this._view = createView<TInput, TOutput, TProjection, TMessage>({\n tree: this._tree,\n channel: this._channel,\n codec: this._codec,\n sendDelegate: this._internalSend.bind(this),\n logger: this._logger,\n onClose: () => this._views.delete(this._view),\n });\n this._decoder = this._codec.createDecoder();\n this._encoder = this._codec.createEncoder(\n this._channel,\n this._clientId === undefined ? undefined : { clientId: this._clientId },\n );\n\n this._views.add(this._view);\n\n // Public accessors (typed as narrow interfaces)\n this.tree = this._tree;\n this.view = this._view;\n\n // Seed tree with initial messages — the session assigns a codecMessageId\n // per seed message. Each seed becomes a run-less input node (no run-id —\n // the client never mints one); the parent chain mirrors the original seed\n // sequence (a user→user input chain the Tree threads kind-blind).\n if (options.messages) {\n let prevMsgId: string | undefined;\n for (const msg of options.messages) {\n const codecMessageId = crypto.randomUUID();\n const seedHeaders: Record<string, string> = {\n [HEADER_CODEC_MESSAGE_ID]: codecMessageId,\n [HEADER_ROLE]: 'user',\n };\n if (prevMsgId) seedHeaders[HEADER_PARENT] = prevMsgId;\n this._tree.applyMessage({ inputs: [this._codec.createUserMessage(msg)], outputs: [] }, seedHeaders);\n prevMsgId = codecMessageId;\n }\n }\n\n // Spec: AIT-CT2\n // Listener function reference — bound now so it can be unsubscribed on close.\n this._onMessage = (ablyMessage: Ably.InboundMessage) => {\n this._handleMessage(ablyMessage);\n };\n\n // Listen for channel state changes that break message continuity.\n // _hasAttachedOnce is seeded from the channel's current state so that\n // pre-attached channels are handled correctly. It distinguishes the\n // initial attach (expected) from a genuine discontinuity.\n this._onChannelStateChange = (stateChange: Ably.ChannelStateChange) => {\n this._handleChannelStateChange(stateChange);\n };\n this._channel.on(this._onChannelStateChange);\n }\n\n // ---------------------------------------------------------------------------\n // Public connection API\n // ---------------------------------------------------------------------------\n\n // Spec: AIT-CT2\n // eslint-disable-next-line @typescript-eslint/promise-function-async -- preserve reference equality across calls\n connect(): Promise<void> {\n if (this._state === ClientSessionState.CLOSED) {\n return Promise.reject(new Ably.ErrorInfo('unable to connect; session is closed', ErrorCode.SessionClosed, 400));\n }\n if (this._connectPromise) return this._connectPromise;\n\n this._logger.trace('DefaultClientSession.connect();');\n // Subscribe before attach (RTL7g) — subscribe implicitly attaches the channel.\n this._connectPromise = this._channel.subscribe(this._onMessage).then(\n () => {\n this._logger.debug('DefaultClientSession.connect(); subscribed and attached');\n },\n (error: unknown) => {\n const errInfo = new Ably.ErrorInfo(\n `unable to subscribe to channel; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.SessionSubscriptionError,\n 500,\n error instanceof Ably.ErrorInfo ? error : undefined,\n );\n this._logger.error('DefaultClientSession.connect(); subscribe failed');\n this._emitter.emit('error', errInfo);\n throw errInfo;\n },\n );\n return this._connectPromise;\n }\n\n private async _requireConnected(method: string): Promise<void> {\n if (!this._connectPromise) {\n throw new Ably.ErrorInfo(\n `unable to ${method}; connect() must be called before ${method}()`,\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n return this._connectPromise;\n }\n\n // ---------------------------------------------------------------------------\n // Message subscription handler\n // ---------------------------------------------------------------------------\n\n private _handleMessage(ablyMessage: Ably.InboundMessage): void {\n if (this._state === ClientSessionState.CLOSED) return;\n\n try {\n // Spec: AIT-CT16a\n // Live-only: surface an agent error carried on a run-end BEFORE applying\n // it, preserving the original 'error'-before-tree-'run' emit ordering.\n // Consumers that expose a per-run stream (e.g. the Vercel ChatTransport)\n // error their stream off this event. The agent only publishes run-end\n // after run-start, so no pending-run-start tracker is outstanding.\n if (ablyMessage.name === EVENT_RUN_END) {\n const headers = getTransportHeaders(ablyMessage);\n // CAST: agent always writes a valid RunEndReason; default to 'complete' for robustness\n const reason = (headers[HEADER_RUN_REASON] ?? 'complete') as RunEndReason;\n if (reason === 'error') {\n const codeRaw = headers[HEADER_ERROR_CODE];\n const parsedCode = codeRaw === undefined ? Number.NaN : Number(codeRaw);\n const code = Number.isFinite(parsedCode) ? parsedCode : ErrorCode.SessionSubscriptionError;\n const message = headers[HEADER_ERROR_MESSAGE] ?? 'agent reported an error';\n const statusCode = code >= 10000 && code < 60000 ? Math.floor(code / 100) : 500;\n const errInfo = new Ably.ErrorInfo(message, code, statusCode);\n this._logger.error('ClientSession._handleMessage(); agent error received', {\n runId: headers[HEADER_RUN_ID],\n invocationId: headers[HEADER_INVOCATION_ID],\n code,\n });\n this._emitter.emit('error', errInfo);\n }\n }\n\n // Reconstruct the tree via the shared decode-fold engine — the same path\n // the View's history replay uses, so the live loop can't drift from it.\n const event = applyWireMessage(this._tree, this._decoder, ablyMessage);\n\n // Live-only: resolve the pending `runId` promise on a fresh run-start or\n // a continuation run-resume. Key by the echoed `input-codec-message-id`\n // — the mirror of the arming key on `_pendingRunStarts` (see that\n // field's JSDoc). Every send carries at least one input, so the agent\n // always echoes it.\n if (event && (event.type === 'start' || event.type === 'resume')) {\n const startedKey = getTransportHeaders(ablyMessage)[HEADER_INPUT_CODEC_MESSAGE_ID];\n if (startedKey !== undefined) {\n const pending = this._pendingRunStarts.get(startedKey);\n if (pending) {\n this._pendingRunStarts.delete(startedKey);\n // Resolve the run handle's `runId` promise with the agent-minted id.\n pending.resolve(event.runId);\n }\n }\n }\n\n // Emit ably-message AFTER the apply so View subscribers can find the\n // owning node in `_lastVisibleNodeKeySet` (keyed by run-id for reply runs\n // and codec-message-id for inputs), which is refreshed by the tree\n // 'update' events the apply triggers.\n this._tree.emitAblyMessage(ablyMessage);\n } catch (error) {\n const cause = error instanceof Ably.ErrorInfo ? error : undefined;\n this._emitter.emit(\n 'error',\n new Ably.ErrorInfo(\n `unable to process channel message; ${error instanceof Error ? error.message : String(error)}`,\n ErrorCode.SessionSubscriptionError,\n 500,\n cause,\n ),\n );\n }\n }\n\n // ---------------------------------------------------------------------------\n // Channel state change handler\n // ---------------------------------------------------------------------------\n\n // Spec: AIT-CT19, AIT-CT19a\n private _handleChannelStateChange(stateChange: Ably.ChannelStateChange): void {\n if (this._state === ClientSessionState.CLOSED) return;\n\n const { current, resumed } = stateChange;\n\n // Track the initial attach so we don't treat it as a discontinuity\n if (current === 'attached' && !this._hasAttachedOnce) {\n this._hasAttachedOnce = true;\n return;\n }\n\n // Continuity-breaking states:\n // - FAILED, SUSPENDED, DETACHED: no more messages expected (or gap)\n // - ATTACHED with resumed: false (UPDATE): messages were lost\n const continuityLost =\n current === 'failed' || current === 'suspended' || current === 'detached' || (current === 'attached' && !resumed);\n\n if (!continuityLost) return;\n\n this._logger.error('ClientSession._handleChannelStateChange(); channel continuity lost', {\n current,\n resumed,\n previous: stateChange.previous,\n });\n\n const err = new Ably.ErrorInfo(\n `unable to deliver events; channel continuity lost (${current}${current === 'attached' ? ', resumed: false' : ''})`,\n ErrorCode.ChannelContinuityLost,\n 500,\n stateChange.reason,\n );\n\n // Surface the loss via the session `error` event. Consumers that expose a\n // per-run stream (e.g. the Vercel ChatTransport) error their stream off\n // this event; observer-run state lives entirely in the Tree's projection\n // and stays consistent regardless of continuity loss.\n this._emitter.emit('error', err);\n }\n\n // ---------------------------------------------------------------------------\n // Cancel helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Tear down local state for a send whose channel publish failed.\n * Idempotent.\n * @param codecMessageIds - The codec-message-ids of the failed send's\n * optimistic input nodes (the client mints no run-id, so the optimistic\n * inserts are keyed by their codec-message-ids).\n */\n private _cleanupFailedSend(codecMessageIds: string[]): void {\n for (const codecMessageId of codecMessageIds) {\n // Drop the optimistic input node only if the publish never produced a\n // server-assigned serial (i.e. nothing live observed it). A server-acked\n // node is part of the canonical channel state and must stay; the View /\n // observers already see it. A fresh send's optimistic inserts are input\n // nodes (keyed by codec-message-id).\n const node = this._tree.getNodeByCodecMessageId(codecMessageId);\n if (node?.kind === 'input' && node.serial === undefined) {\n // An input node's key is its codec-message-id, so delete by it directly.\n this._tree.delete(node.codecMessageId);\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Public API\n // ---------------------------------------------------------------------------\n\n // Spec: AIT-CT10b\n createView(): View<TInput, TMessage> {\n if (this._state === ClientSessionState.CLOSED) {\n throw new Ably.ErrorInfo('unable to create view; session is closed', ErrorCode.SessionClosed, 400);\n }\n this._logger.trace('DefaultClientSession.createView();');\n const view = createView<TInput, TOutput, TProjection, TMessage>({\n tree: this._tree,\n channel: this._channel,\n codec: this._codec,\n sendDelegate: this._internalSend.bind(this),\n logger: this._logger,\n onClose: () => this._views.delete(view),\n });\n this._views.add(view);\n return view;\n }\n\n // Spec: AIT-CT3, AIT-CT4\n private async _internalSend(\n input: TInput[],\n sendOptions: SendOptions | undefined,\n parentCodecMessageId: string | undefined,\n ): Promise<ActiveRun> {\n if (this._state === ClientSessionState.CLOSED) {\n throw new Ably.ErrorInfo('unable to send; session is closed', ErrorCode.SessionClosed, 400);\n }\n await this._requireConnected('send');\n // CAST: re-check after await — close() may have been called while waiting for connect.\n // TypeScript's control flow narrows _state after the first check, but the\n // await yields and close() can mutate _state concurrently.\n if ((this._state as ClientSessionState) === ClientSessionState.CLOSED) {\n throw new Ably.ErrorInfo('unable to send; session is closed', ErrorCode.SessionClosed, 400);\n }\n\n // Spec: AIT-CT20\n const state = this._channel.state;\n if (state !== 'attached' && state !== 'attaching') {\n throw new Ably.ErrorInfo(`unable to send; channel is ${state}`, ErrorCode.ChannelNotReady, 400);\n }\n\n this._logger.trace('ClientSession._internalSend();');\n\n const isContinuation = sendOptions?.runId !== undefined;\n\n // The agent mints run-ids, not the client. A fresh send carries no run-id\n // (the agent mints it and echoes it on run-start); only a continuation\n // reuses the existing run-id the caller passed.\n const runId = sendOptions?.runId;\n\n // Spec: AIT-CT3d\n // Auto-compute parent from the visible branch tail when not explicitly\n // provided. The View pre-resolves the codec-message-id of the last visible message\n // since the session is codec-agnostic and can't extract it from TMessage.\n let autoParent: string | undefined;\n if (sendOptions?.parent === undefined && !sendOptions?.forkOf) {\n autoParent = parentCodecMessageId;\n }\n\n const codecMessageIds = new Set<string>();\n interface ItemState {\n input: TInput;\n codecMessageId: string;\n inputEventId: string;\n headers: Record<string, string>;\n /** Inputs that reference an existing codec-message without contributing fresh local content (regenerate, tool resolutions) are wire-only — no optimistic projection fold. Fresh user-messages always fold, even when they pin their own codecMessageId. */\n isWireOnly: boolean;\n }\n const items: ItemState[] = [];\n\n // Per-input wire prep: read routing fields off the input directly, then\n // mint per-event ids and build transport headers. Regenerate inputs are\n // wire-only (no optimistic fold); other inputs fold into the projection\n // optimistically.\n for (const entry of input) {\n const inputEventId = crypto.randomUUID();\n // Use the input's `codecMessageId` when set (e.g. tool resolution\n // targeting the prior assistant); otherwise mint a fresh id.\n const codecMessageId = entry.codecMessageId ?? crypto.randomUUID();\n codecMessageIds.add(codecMessageId);\n\n // Inputs that reference an existing message (regenerate, tool\n // resolutions targeting an assistant) are wire-only — no optimistic\n // fold needed because either the receiving content doesn't\n // materialise on this side (regenerate) or the target already exists\n // and will be amended when the wire echoes back.\n //\n // A fresh `user-message` is never wire-only, even on the rare path\n // where it carries an explicit `codecMessageId`: it is new content that\n // must fold into the local projection immediately. Excluding it here\n // keeps the optimistic user bubble from depending on the channel\n // round-trip. (The session mints the codec-message-id for fresh user\n // messages; the caller's `message.id` is preserved but never used as\n // the correlation key.)\n const isWireOnly =\n entry.kind !== 'user-message' && (entry.kind === 'regenerate' || entry.codecMessageId !== undefined);\n\n // The input's own routing fields override the auto-parent /\n // sendOptions defaults. For regenerate inputs, `target` becomes the\n // `msg-regenerate` wire header. The fork anchor comes from\n // `sendOptions.forkOf` (set by `View.edit`). The transport reads\n // these directly without runtime classification.\n const parent = entry.parent ?? (sendOptions?.parent === undefined ? autoParent : sendOptions.parent);\n const forkOf = sendOptions?.forkOf;\n const regenerates = entry.kind === 'regenerate' ? entry.target : undefined;\n\n const headers = buildTransportHeaders({\n role: 'user',\n runId,\n codecMessageId,\n runClientId: this._clientId,\n ...(parent !== undefined && { parent }),\n ...(forkOf !== undefined && { forkOf }),\n ...(regenerates !== undefined && { regenerates }),\n inputEventId,\n });\n\n // Spec: AIT-CT3c — optimistic fold for non-wire-only inputs.\n if (!isWireOnly) {\n this._tree.applyMessage({ inputs: [entry], outputs: [] }, headers);\n }\n\n items.push({ input: entry, codecMessageId, inputEventId, headers, isWireOnly });\n\n // Spec: AIT-CT3e — chain subsequent inputs off the previous one when\n // auto-parenting is in effect.\n if (!isWireOnly && sendOptions?.parent === undefined && !sendOptions?.forkOf && entry.parent === undefined) {\n autoParent = codecMessageId;\n }\n }\n\n // The trigger event is the last input — the one the agent looks up on the\n // channel via `event-id`, surfaced on `ActiveRun` (and via `toInvocation()`)\n // so the application can point an invocation at it. Its codec-message-id is\n // the handle the client owns at send time; the agent echoes it back on\n // run-start as `input-codec-message-id`, and it keys the run-start tracker.\n const triggerItem = items.at(-1);\n if (triggerItem === undefined) {\n // Every send must carry at least one input — only new input starts or\n // continues a run. The loop above produced no items, so nothing was\n // published or folded optimistically.\n throw new Ably.ErrorInfo(\n 'unable to send; inputs array is empty (include at least one input)',\n ErrorCode.InvalidArgument,\n 400,\n );\n }\n const triggerInputEventId = triggerItem.inputEventId;\n const startedKey = triggerItem.codecMessageId;\n\n // Arm the run-start tracker backing the returned `ActiveRun.runId` promise.\n // The run-start handler resolves it with the agent-minted run-id when this\n // send's `ai-run-start` is observed; close() rejects it on teardown. No\n // deadline — `send()` resolves on publish; callers bound the wait by racing\n // `run.runId` against their own timeout.\n //\n // Key on the arming side mirrors the resolve side — see `_pendingRunStarts`\n // for the full keying invariant. The executor runs synchronously, so the\n // tracker entry is registered before `new Promise` returns.\n const runIdPromise = new Promise<string>((resolve, reject) => {\n this._pendingRunStarts.set(startedKey, { resolve, reject });\n });\n // Suppress unhandled-rejection warnings for callers that never await\n // `run.runId`; the caller still observes the rejection if it does await.\n runIdPromise.catch(() => {\n /* observed via run.runId, if at all */\n });\n\n // Publish each input in original order via the shared encoder. The\n // codec routes user-message inputs into a per-part discrete batch and\n // tool-resolution / regenerate inputs into a single discrete write —\n // all on the `ai-input` wire.\n const publishPromise = (async () => {\n try {\n for (const item of items) {\n await this._encoder.publishInput(item.input, {\n extras: { headers: item.headers },\n messageId: item.codecMessageId,\n ...(this._clientId !== undefined && { clientId: this._clientId }),\n });\n }\n } catch (error) {\n const cause = error instanceof Ably.ErrorInfo ? error : undefined;\n const isPermission = cause?.statusCode === 401 || cause?.statusCode === 403;\n const err = new Ably.ErrorInfo(\n isPermission\n ? `unable to publish events; missing publish capability on the channel`\n : `unable to publish events; ${error instanceof Error ? error.message : String(error)}`,\n isPermission ? ErrorCode.InsufficientCapability : ErrorCode.SessionSendFailed,\n isPermission ? 401 : 500,\n cause,\n );\n this._emitter.emit('error', err);\n // The input never reached the channel — there is no run to wait on.\n // Drop the run-start tracker so close() doesn't later reject an orphan.\n this._pendingRunStarts.delete(startedKey);\n // Continuations didn't insert optimistic nodes, so there is nothing to\n // clear for them — only a fresh send's optimistic input nodes need\n // removing, keyed by their codec-message-ids (the client mints no runId).\n if (!isContinuation) this._cleanupFailedSend([...codecMessageIds]);\n throw err;\n }\n })();\n\n // `send()` resolves once the input is published. The core never sends\n // HTTP — waking an agent is the application's concern. Callers POST\n // `run.toInvocation().toJSON()` to their endpoint if they want one woken,\n // and await `run.runId` if they need to know it was picked up.\n await publishPromise;\n\n return {\n inputCodecMessageId: startedKey,\n runId: runIdPromise,\n inputEventId: triggerInputEventId,\n // The agent mints the run-id, so a fresh run has none until run-start.\n // Cancel synchronously by the triggering input's codec-message-id (the\n // handle the client owns at send time, = `inputCodecMessageId`): the\n // agent resolves it to the run once its input-event lookup completes, and\n // buffers a cancel that arrives before then so an early cancel is honoured\n // rather than dropped. A continuation additionally carries its known\n // run-id so the agent can match the run directly.\n cancel: async () => {\n await this._publishCancel({\n inputCodecMessageId: startedKey,\n ...(runId !== undefined && { runId }),\n });\n },\n optimisticCodecMessageIds: [...codecMessageIds],\n toInvocation: () =>\n // The invocation body carries no run-id: run identity lives on the\n // channel (the agent mints a fresh run-id, or reads a continuation's\n // from the triggering input event, which carries the reused run-id).\n Invocation.fromJSON({\n inputEventId: triggerInputEventId,\n sessionName: this._channel.name,\n }),\n };\n }\n\n // Spec: AIT-CT7, AIT-CT7a\n async cancel(runId: string): Promise<void> {\n return this._publishCancel({ runId });\n }\n\n /**\n * Publish an `ai-cancel` signal. The agent resolves the target run by\n * whichever identifier is present:\n *\n * - `runId` — a continuation, whose run-id the caller already knows.\n * - `inputCodecMessageId` — a fresh send, whose run-id the agent mints at\n * run-start. The client can only key the cancel by the triggering input's\n * codec-message-id (the `ActiveRun.inputCodecMessageId`) it owns at send\n * time; the agent resolves it to the run once its input-event lookup\n * completes, buffering a cancel that arrives before then.\n *\n * Both may be present (a continuation knows its run-id AND published an\n * input). An `event-id` is always stamped so channel rewind redelivers the\n * cancel to a per-request / serverless agent that attaches after it was\n * published.\n *\n * Publishing the cancel signal is all the core does. The consumer-facing\n * stream (if any) lives in the layer that built it — e.g. the Vercel\n * ChatTransport closes its stream on cancel — and the Tree's RunNode is left\n * intact so late agent events (a cancel append, a trailing\n * `status: cancelled`) still fold into the Run's projection.\n * @param target - The run identifier(s) to cancel. At least one of `runId` /\n * `inputCodecMessageId` must be set.\n * @param target.runId - The run-id to cancel (continuations).\n * @param target.inputCodecMessageId - The triggering input's\n * codec-message-id to cancel (fresh sends, before run-start).\n */\n private async _publishCancel(target: { runId?: string; inputCodecMessageId?: string }): Promise<void> {\n if (this._state === ClientSessionState.CLOSED) return;\n await this._requireConnected('cancel');\n // CAST: re-check after await — close() may have been called while waiting for connect.\n if ((this._state as ClientSessionState) === ClientSessionState.CLOSED) return;\n this._logger.debug('ClientSession._publishCancel();', {\n runId: target.runId,\n inputCodecMessageId: target.inputCodecMessageId,\n });\n\n const headers: Record<string, string> = {\n // Stamp a per-cancel event-id so channel rewind redelivers this cancel\n // to an agent that attaches after it was published.\n [HEADER_EVENT_ID]: crypto.randomUUID(),\n };\n if (target.runId !== undefined) headers[HEADER_RUN_ID] = target.runId;\n if (target.inputCodecMessageId !== undefined) headers[HEADER_INPUT_CODEC_MESSAGE_ID] = target.inputCodecMessageId;\n\n await this._channel.publish({\n name: EVENT_CANCEL,\n extras: { ai: { transport: headers } },\n });\n }\n\n // Spec: AIT-CT8, AIT-CT8c, AIT-CT8d\n on(event: 'error', handler: (error: Ably.ErrorInfo) => void): () => void {\n if (this._state === ClientSessionState.CLOSED) return noopUnsubscribe;\n // CAST: the overload signature enforces the correct handler type.\n const cb = handler;\n this._emitter.on(event, cb);\n return () => {\n this._emitter.off(event, cb);\n };\n }\n\n // Spec: AIT-CT12, AIT-CT12b, AIT-CT10c\n async close(): Promise<void> {\n if (this._state === ClientSessionState.CLOSED) return;\n this._state = ClientSessionState.CLOSED;\n this._logger.info('ClientSession.close();');\n\n if (this._connectPromise) {\n this._channel.unsubscribe(this._onMessage);\n }\n this._channel.off(this._onChannelStateChange);\n\n this._emitter.off();\n for (const v of this._views) v.close();\n this._views.clear();\n // Reject any in-flight `run.runId` promises so callers awaiting run-start\n // settle rather than hang.\n if (this._pendingRunStarts.size > 0) {\n const closedErr = new Ably.ErrorInfo('unable to await run-start; session closed', ErrorCode.SessionClosed, 400);\n for (const pending of this._pendingRunStarts.values()) {\n pending.reject(closedErr);\n }\n this._pendingRunStarts.clear();\n }\n\n // Best-effort encoder close — flushes any pending stream operations.\n // The client only uses the discrete input path (publishInput), so this is\n // typically a no-op, but it releases any internal resources cleanly.\n try {\n await this._encoder.close();\n } catch {\n // Swallow: encoder close is best-effort during teardown\n }\n\n // Detach the channel this session attached. connect() subscribes (which\n // implicitly attaches), so we only detach when connect() ran. Best-effort:\n // a detach failure (e.g. the channel is already FAILED) must not throw out\n // of close().\n if (this._connectPromise) {\n try {\n await this._channel.detach();\n } catch (error) {\n // Swallowed (see above): a detach failure must not throw out of\n // close(). Logged at debug for observability.\n this._logger.debug('ClientSession.close(); channel detach failed', { error });\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a client-side session that manages conversation state over an Ably channel.\n *\n * The caller owns the client's lifecycle; the session owns its channel.\n * The session is created in a not-yet-connected state — callers must\n * `await session.connect()` before `send`, `regenerate`, `edit`, `update`,\n * or `cancel`.\n * @param options - Configuration for the client session.\n * @returns A new {@link ClientSession} instance.\n */\nexport const createClientSession = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(\n options: ClientSessionOptions<TInput, TOutput, TProjection, TMessage>,\n): ClientSession<TInput, TOutput, TProjection, TMessage> => new DefaultClientSession(options);\n","/**\n * Vercel AI SDK transport wrappers that pre-bind the UIMessageCodec.\n *\n * These are convenience factories so consumers don't need to pass the codec\n * explicitly when using the Vercel AI SDK integration.\n *\n * ```ts\n * import { createClientSession } from '@ably/ai-transport/vercel';\n *\n * const session = createClientSession({ client, channelName: 'ai:demo' });\n * await session.connect();\n * ```\n */\n\n// Chat transport adapter\nexport type { ChatTransport, ChatTransportOptions, SendMessagesRequestContext } from './chat-transport.js';\nexport { createChatTransport, DEFAULT_VERCEL_API } from './chat-transport.js';\n\nimport type * as AI from 'ai';\n\nimport { createAgentSession as createCoreAgentSession } from '../../core/transport/agent-session.js';\nimport { createClientSession as createCoreClientSession } from '../../core/transport/client-session.js';\nimport type {\n AgentSession,\n AgentSessionOptions,\n ClientSession,\n ClientSessionOptions,\n} from '../../core/transport/types.js';\nimport { UIMessageCodec, type VercelInput, type VercelOutput, type VercelProjection } from '../codec/index.js';\n\n/** Core client session options with Vercel AI SDK types pre-applied. */\ntype CoreClientOpts = ClientSessionOptions<VercelInput, VercelOutput, VercelProjection, AI.UIMessage>;\n\n/** Options for creating a Vercel client session. Same as core options but without the codec field. */\nexport type VercelClientSessionOptions = Omit<CoreClientOpts, 'codec'>;\n\n/** Options for creating a Vercel agent session. Same as core options but without the codec field. */\nexport type VercelAgentSessionOptions = Omit<\n AgentSessionOptions<VercelInput, VercelOutput, VercelProjection, AI.UIMessage>,\n 'codec'\n>;\n\n/**\n * Create a client-side session pre-configured with the Vercel AI SDK codec.\n *\n * Equivalent to calling the core `createClientSession` with `codec: UIMessageCodec`.\n * The core session is a pure Ably-channel transport — it never sends HTTP.\n * To wake a serverless agent over HTTP, POST `run.toInvocation().toJSON()`\n * yourself, or use `createChatTransport` (which does it for useChat parity).\n * @param options - Configuration for the client session (codec is provided automatically).\n * @returns A new {@link ClientSession} for Vercel AI SDK UIMessage/UIMessageChunk types.\n */\nexport const createClientSession = (\n options: VercelClientSessionOptions,\n): ClientSession<VercelInput, VercelOutput, VercelProjection, AI.UIMessage> =>\n createCoreClientSession({ ...options, codec: UIMessageCodec });\n\n/**\n * Create an agent (server-side) session pre-configured with the Vercel AI SDK codec.\n *\n * Equivalent to calling the core `createAgentSession` with `codec: UIMessageCodec`.\n * @param options - Configuration for the agent session (codec is provided automatically).\n * @returns A new {@link AgentSession} for Vercel AI SDK UIMessage/UIMessageChunk types.\n */\nexport const createAgentSession = (\n options: VercelAgentSessionOptions,\n): AgentSession<VercelOutput, VercelProjection, AI.UIMessage> =>\n createCoreAgentSession({ ...options, codec: UIMessageCodec });\n","import type * as AI from 'ai';\n\nimport type { RunEndReason, StreamResult } from '../core/transport/types.js';\n\n/**\n * Derive the outcome for a Vercel `streamText` response that was piped through\n * `Run.pipe`: either a terminal {@link RunEndReason} the caller passes to\n * `Run.end`, or the sentinel `'suspend'` telling the caller to call\n * `Run.suspend` instead. Preserves transport-level outcomes (`'cancelled'`,\n * `'error'`) from the pipe result; when the pipe completed naturally, awaits\n * Vercel's `finishReason` and returns `'suspend'` for `'tool-calls'` (the LLM\n * requested tools the SDK did not auto-execute, so the run should suspend\n * rather than end), or `'complete'` otherwise.\n *\n * Tolerates `finishReason` rejection. Vercel AI SDK v6 rejects\n * `streamText().finishReason` with the abort signal's reason when the stream\n * is aborted before any step completes, and rejects with\n * `NoOutputGeneratedError` when the model produced nothing at all. Without\n * this guard the rejection would bubble out of the route handler's `after()`\n * block, skip the developer's `Run.end(...)` call, and leave the run with no\n * `ai-run-end` event on the channel — so observers' UIs stay stuck on\n * `streaming` indefinitely.\n *\n * Saves callers from interpreting Vercel domain semantics inline at the end\n * of every route handler.\n * @param pipeResult - The result returned by `Run.pipe`.\n * @param finishReason - The `finishReason` promise from a `streamText` result.\n * @returns `'suspend'` when the run should suspend awaiting tool input, or the\n * {@link RunEndReason} to pass to `Run.end` otherwise.\n */\nexport const vercelRunOutcome = async (\n pipeResult: StreamResult,\n finishReason: PromiseLike<AI.FinishReason>,\n): Promise<RunEndReason | 'suspend'> => {\n if (pipeResult.reason !== 'complete') {\n // Vercel's `result.finishReason` getter creates the underlying Promise\n // eagerly, before the caller hands it to us. When `streamText` is\n // aborted before any step completes, Vercel rejects that Promise with\n // the abort signal's reason — typically a DOMException whose\n // `.message` is a read-only getter. Returning early without ever\n // attaching a handler lets Node report it as an unhandled rejection;\n // Next.js' dev bundler then tries to mutate `.message` for logging\n // and crashes with a confusing TypeError. Attach a silent handler so\n // the rejection is observed and discarded — the transport-level\n // `pipeResult.reason` is already what we return.\n Promise.resolve(finishReason).catch(() => {\n /* intentionally discarded; reason already known from pipeResult */\n });\n return pipeResult.reason;\n }\n try {\n const finish = await finishReason;\n return finish === 'tool-calls' ? 'suspend' : 'complete';\n } catch (error) {\n // Abort-shaped rejections are surfaced from streamText when the run was\n // cancelled before any step finished — treat the run as cancelled so the\n // observable lifecycle matches the cancel that triggered it. Everything\n // else is a real error (e.g. NoOutputGeneratedError, network blow-ups);\n // surface it as such so the developer sees the failure rather than a\n // silent cancel.\n return _isAbortLikeError(error) ? 'cancelled' : 'error';\n }\n};\n\n/**\n * Heuristic for \"this error came from an AbortSignal aborting\".\n * Covers `DOMException` aborts (browser / Node 20+ `streamText`),\n * plain `Error` objects whose `name` is `'AbortError'`, and anything\n * else carrying that conventional name. Avoids importing\n * `@ai-sdk/provider-utils` just for `isAbortError`.\n * @param error - The error to test.\n * @returns `true` if the error looks like an abort.\n */\nconst _isAbortLikeError = (error: unknown): boolean => {\n if (typeof error !== 'object' || error === null) return false;\n const name = (error as { name?: unknown }).name;\n return name === 'AbortError';\n};\n"],"mappings":";;;AAgBA,IAAa,IAAgB,UAGhB,IAAgB,UAGhB,IAAmB,aAGnB,IAAkB,YAOlB,IAAgB,UAGhB,IAAuB,iBAYvB,IAAkB,YAGlB,IAA0B,oBAG1B,IAAuB,iBAavB,IAAyB,mBAGzB,IAAc,QAOd,IAAgB,UAGhB,IAAiB,WAYjB,IAAwB,kBAOxB,IAAoB,cAYpB,IAAgC,0BAOhC,IAAoB,cAqBpB,IAAe,aAGf,IAAkB,gBAQlB,IAAoB,kBAQpB,IAAmB,iBAGnB,IAAgB,cAQhB,IAAkB,aAQlB,IAAiB,YC5JxB,KAAa,GAA8B,MAAwD;CAEvG,IAAM,IAAS,EAAQ;CACvB,IAAI,CAAC,KAAU,OAAO,KAAW,UAAU,OAAO,CAAC;CACnD,IAAM,IAAM,EAA4B;CACxC,IAAI,CAAC,KAAM,OAAO,KAAO,UAAU,OAAO,CAAC;CAC3C,IAAM,IAAO,EAA+B;CAI5C,OAHI,CAAC,KAAO,OAAO,KAAQ,WAAiB,CAAC,IAGtC;AACT,GASa,KAAuB,MAClC,EAAU,GAAS,WAAW,GASnB,KAAmB,MAAyD,EAAU,GAAS,OAAO,GAOtG,MAAa,MAAuC;CAC3D,UAAU,KAAA,GACd,IAAI;EACF,OAAO,KAAK,MAAM,CAAK;CACzB,QAAQ;EACN;CACF;AACF,GA2Ba,MACX,GACA,OAC4B;CAC5B,GAAG;CACH,GAAG;AACL,IAOa,KAAa,MAAmD;CACvE,UAAU,KAAA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