@ably/ai-transport 0.2.0 → 0.3.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.
- package/README.md +10 -19
- package/dist/ably-ai-transport.js +1790 -1091
- package/dist/ably-ai-transport.js.map +1 -1
- package/dist/ably-ai-transport.umd.cjs +1 -1
- package/dist/ably-ai-transport.umd.cjs.map +1 -1
- package/dist/constants.d.ts +2 -2
- package/dist/core/agent.d.ts +20 -5
- package/dist/core/channel-options.d.ts +57 -0
- package/dist/core/codec/codec-event.d.ts +9 -0
- package/dist/core/codec/decoder.d.ts +4 -1
- package/dist/core/codec/define-codec.d.ts +100 -0
- package/dist/core/codec/encoder.d.ts +2 -7
- package/dist/core/codec/field-bag.d.ts +85 -0
- package/dist/core/codec/fields.d.ts +141 -0
- package/dist/core/codec/index.d.ts +8 -1
- package/dist/core/codec/input-descriptor-decoder.d.ts +19 -0
- package/dist/core/codec/input-descriptor-encoder.d.ts +22 -0
- package/dist/core/codec/input-descriptors.d.ts +281 -0
- package/dist/core/codec/output-descriptor-decoder.d.ts +29 -0
- package/dist/core/codec/output-descriptor-encoder.d.ts +31 -0
- package/dist/core/codec/output-descriptors.d.ts +237 -0
- package/dist/core/codec/types.d.ts +95 -36
- package/dist/core/codec/well-known-inputs.d.ts +52 -0
- package/dist/core/transport/agent-view.d.ts +296 -0
- package/dist/core/transport/decode-fold.d.ts +40 -32
- package/dist/core/transport/headers.d.ts +30 -1
- package/dist/core/transport/index.d.ts +1 -1
- package/dist/core/transport/invocation.d.ts +1 -1
- package/dist/core/transport/load-history-pages.d.ts +71 -0
- package/dist/core/transport/load-history.d.ts +21 -16
- package/dist/core/transport/run-manager.d.ts +9 -11
- package/dist/core/transport/session-support.d.ts +55 -0
- package/dist/core/transport/tree.d.ts +165 -15
- package/dist/core/transport/types/agent.d.ts +120 -98
- package/dist/core/transport/types/client.d.ts +45 -12
- package/dist/core/transport/types/tree.d.ts +52 -10
- package/dist/core/transport/types/view.d.ts +55 -28
- package/dist/core/transport/view.d.ts +176 -58
- package/dist/core/transport/wire-log.d.ts +102 -0
- package/dist/errors.d.ts +10 -4
- package/dist/index.d.ts +6 -5
- package/dist/react/ably-ai-transport-react.js +784 -415
- package/dist/react/ably-ai-transport-react.js.map +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
- package/dist/react/contexts/client-session-context.d.ts +2 -1
- package/dist/react/contexts/client-session-provider.d.ts +3 -0
- package/dist/react/index.d.ts +2 -1
- package/dist/react/internal/skipped-session.d.ts +8 -0
- package/dist/react/use-view.d.ts +3 -3
- package/dist/utils.d.ts +22 -54
- package/dist/vercel/ably-ai-transport-vercel.js +2297 -2026
- package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
- package/dist/vercel/codec/decode-lifecycle.d.ts +9 -0
- package/dist/vercel/codec/events.d.ts +1 -2
- package/dist/vercel/codec/fields.d.ts +44 -0
- package/dist/vercel/codec/fold-content.d.ts +16 -0
- package/dist/vercel/codec/fold-data.d.ts +16 -0
- package/dist/vercel/codec/fold-input.d.ts +67 -0
- package/dist/vercel/codec/fold-lifecycle.d.ts +16 -0
- package/dist/vercel/codec/fold-text.d.ts +16 -0
- package/dist/vercel/codec/fold-tool-input.d.ts +17 -0
- package/dist/vercel/codec/fold-tool-output.d.ts +16 -0
- package/dist/vercel/codec/index.d.ts +5 -30
- package/dist/vercel/codec/inputs.d.ts +11 -0
- package/dist/vercel/codec/outputs.d.ts +11 -0
- package/dist/vercel/codec/reducer-state.d.ts +121 -0
- package/dist/vercel/codec/reducer.d.ts +20 -102
- package/dist/vercel/codec/tool-transitions.d.ts +0 -6
- package/dist/vercel/codec/wire-data.d.ts +34 -0
- package/dist/vercel/index.d.ts +1 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +2013 -9500
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +1 -70
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
- package/dist/vercel/react/contexts/chat-transport-context.d.ts +2 -1
- package/dist/vercel/run-end-reason.d.ts +66 -11
- package/dist/vercel/tool-part.d.ts +21 -0
- package/dist/vercel/transport/chat-transport.d.ts +0 -2
- package/dist/vercel/transport/index.d.ts +1 -1
- package/dist/vercel/transport/run-output-stream.d.ts +6 -8
- package/dist/version.d.ts +1 -1
- package/package.json +2 -2
- package/src/constants.ts +2 -2
- package/src/core/agent.ts +43 -19
- package/src/core/channel-options.ts +89 -0
- package/src/core/codec/codec-event.ts +27 -0
- package/src/core/codec/decoder.ts +145 -21
- package/src/core/codec/define-codec.ts +432 -0
- package/src/core/codec/encoder.ts +13 -54
- package/src/core/codec/field-bag.ts +142 -0
- package/src/core/codec/fields.ts +193 -0
- package/src/core/codec/index.ts +43 -0
- package/src/core/codec/input-descriptor-decoder.ts +97 -0
- package/src/core/codec/input-descriptor-encoder.ts +150 -0
- package/src/core/codec/input-descriptors.ts +373 -0
- package/src/core/codec/output-descriptor-decoder.ts +139 -0
- package/src/core/codec/output-descriptor-encoder.ts +101 -0
- package/src/core/codec/output-descriptors.ts +307 -0
- package/src/core/codec/types.ts +99 -36
- package/src/core/codec/well-known-inputs.ts +96 -0
- package/src/core/transport/agent-session.ts +330 -589
- package/src/core/transport/agent-view.ts +738 -0
- package/src/core/transport/client-session.ts +74 -69
- package/src/core/transport/decode-fold.ts +57 -47
- package/src/core/transport/headers.ts +57 -4
- package/src/core/transport/index.ts +2 -1
- package/src/core/transport/invocation.ts +1 -1
- package/src/core/transport/load-history-pages.ts +220 -0
- package/src/core/transport/load-history.ts +63 -61
- package/src/core/transport/pipe-stream.ts +10 -1
- package/src/core/transport/run-manager.ts +25 -31
- package/src/core/transport/session-support.ts +96 -0
- package/src/core/transport/tree.ts +414 -47
- package/src/core/transport/types/agent.ts +129 -102
- package/src/core/transport/types/client.ts +49 -13
- package/src/core/transport/types/tree.ts +61 -12
- package/src/core/transport/types/view.ts +57 -28
- package/src/core/transport/view.ts +520 -172
- package/src/core/transport/wire-log.ts +189 -0
- package/src/errors.ts +10 -3
- package/src/index.ts +44 -11
- package/src/react/contexts/client-session-context.ts +1 -1
- package/src/react/contexts/client-session-provider.tsx +38 -2
- package/src/react/index.ts +2 -1
- package/src/react/internal/skipped-session.ts +62 -0
- package/src/react/use-client-session.ts +7 -30
- package/src/react/use-view.ts +3 -3
- package/src/utils.ts +31 -97
- package/src/vercel/codec/decode-lifecycle.ts +70 -0
- package/src/vercel/codec/events.ts +1 -3
- package/src/vercel/codec/fields.ts +58 -0
- package/src/vercel/codec/fold-content.ts +54 -0
- package/src/vercel/codec/fold-data.ts +46 -0
- package/src/vercel/codec/fold-input.ts +255 -0
- package/src/vercel/codec/fold-lifecycle.ts +85 -0
- package/src/vercel/codec/fold-text.ts +55 -0
- package/src/vercel/codec/fold-tool-input.ts +86 -0
- package/src/vercel/codec/fold-tool-output.ts +79 -0
- package/src/vercel/codec/index.ts +23 -63
- package/src/vercel/codec/inputs.ts +116 -0
- package/src/vercel/codec/outputs.ts +207 -0
- package/src/vercel/codec/reducer-state.ts +169 -0
- package/src/vercel/codec/reducer.ts +52 -838
- package/src/vercel/codec/tool-transitions.ts +1 -12
- package/src/vercel/codec/wire-data.ts +64 -0
- package/src/vercel/index.ts +1 -0
- package/src/vercel/react/contexts/chat-transport-context.ts +1 -1
- package/src/vercel/react/use-chat-transport.ts +8 -28
- package/src/vercel/react/use-message-sync.ts +5 -10
- package/src/vercel/run-end-reason.ts +95 -16
- package/src/vercel/tool-part.ts +25 -0
- package/src/vercel/transport/chat-transport.ts +10 -22
- package/src/vercel/transport/index.ts +1 -1
- package/src/vercel/transport/run-output-stream.ts +7 -8
- package/src/version.ts +1 -1
- package/dist/core/transport/branch-chain.d.ts +0 -43
- package/dist/core/transport/load-conversation.d.ts +0 -128
- package/dist/vercel/codec/decoder.d.ts +0 -9
- package/dist/vercel/codec/encoder.d.ts +0 -11
- package/src/core/transport/branch-chain.ts +0 -58
- package/src/core/transport/load-conversation.ts +0 -355
- package/src/vercel/codec/decoder.ts +0 -696
- package/src/vercel/codec/encoder.ts +0 -548
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ably-ai-transport-react.umd.cjs","names":[],"sources":["../../src/constants.ts","../../src/errors.ts","../../src/event-emitter.ts","../../src/logger.ts","../../src/utils.ts","../../src/version.ts","../../src/core/agent.ts","../../src/core/transport/headers.ts","../../src/core/transport/decode-fold.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/react/contexts/client-session-context.ts","../../src/react/contexts/client-session-provider.tsx","../../src/react/internal/use-resolved-session.ts","../../src/react/use-ably-messages.ts","../../src/react/use-client-session.ts","../../src/react/use-view.ts","../../src/react/use-create-view.ts","../../src/react/use-tree.ts","../../src/react/create-session-hooks.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","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 * 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 * 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","/** 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 * 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 * 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","import type * as Ably from 'ably';\nimport { createContext } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../../core/codec/types.js';\nimport type { ClientSession } from '../../core/transport/types.js';\n\n/**\n * A single entry in the client-session registry, holding the session and any\n * error that occurred during its construction.\n *\n * `session` is `undefined` when construction failed.\n * `sessionError` is set when `createClientSession` threw during provider render.\n */\nexport interface ClientSessionSlot {\n /** The constructed session, or `undefined` if construction failed. */\n session: ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown> | undefined;\n /** Construction error from `createClientSession`, or `undefined` on success. */\n sessionError?: Ably.ErrorInfo | undefined;\n}\n\n/**\n * The shape of the {@link ClientSessionContext} value.\n *\n * `nearest` is the slot from the innermost enclosing {@link ClientSessionProvider}.\n * `providers` is the full registry of all enclosing providers, keyed by channelName.\n */\nexport interface ClientSessionContextValue {\n /** The innermost {@link ClientSessionProvider}'s slot. `undefined` when no provider is present. */\n nearest: ClientSessionSlot | undefined;\n /** All registered session slots from enclosing providers, keyed by channelName. */\n providers: Readonly<Record<string, ClientSessionSlot>>;\n}\n\n/**\n * Unified client-session context.\n *\n * Holds the nearest client-session slot and the full registry of all registered\n * slots keyed by channelName. Populated by {@link ClientSessionProvider};\n * read by {@link useClientSession} and internal hooks.\n */\nexport const ClientSessionContext = createContext<ClientSessionContextValue>({ nearest: undefined, providers: {} });\n","/**\n * ClientSessionProvider: creates a ClientSession and makes it available to\n * descendants via ClientSessionContext.\n *\n * Reads the Ably Realtime client from the surrounding `<AblyProvider>` and\n * forwards it to `createClientSession` along with the supplied `channelName`.\n *\n * The session is created on first render (via useRef) and recreated when\n * `channelName` changes; the previous session is queued for disposal.\n * `connect()` is invoked from a `useEffect` so the session is\n * subscribed/attached before the first descendant operation. If\n * `createClientSession` throws,\n * the error is stored in the ClientSessionSlot (alongside an undefined\n * session) so that useClientSession can surface it as `sessionError`\n * without crashing the component tree.\n *\n * The session is closed when the provider truly unmounts. The close is\n * scheduled as a microtask so that React Strict Mode's synchronous\n * remount cycle (mount → fake-unmount → remount) can cancel it before it\n * fires, avoiding unnecessary session teardown in development.\n *\n * Multiple ClientSessionProviders can be nested using distinct channelNames.\n * Each provider merges its slot into the parent record so descendants\n * can access all registered sessions via useClientSession(channelName).\n */\n\nimport * as Ably from 'ably';\nimport { useAbly } from 'ably/react';\nimport { type PropsWithChildren, type ReactNode, useContext, useEffect, useMemo, useRef } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../../core/codec/types.js';\nimport { createClientSession } from '../../core/transport/client-session.js';\nimport type { ClientSession, ClientSessionOptions } from '../../core/transport/types.js';\nimport { ErrorCode } from '../../errors.js';\nimport type { ClientSessionSlot } from './client-session-context.js';\nimport { ClientSessionContext } from './client-session-context.js';\n\n/**\n * Props for {@link ClientSessionProvider}.\n *\n * All {@link ClientSessionOptions} except `client` (read from the surrounding\n * `<AblyProvider>`).\n */\nexport interface ClientSessionProviderProps<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>\n extends Omit<ClientSessionOptions<TInput, TOutput, TProjection, TMessage>, 'client'>, PropsWithChildren {}\n\n/**\n * Provide a {@link ClientSession} to descendant components.\n *\n * Reads the Ably Realtime client from the surrounding `<AblyProvider>`,\n * creates a session bound to `channelName`, calls `connect()` on mount,\n * and registers it in `ClientSessionContext` under `channelName`.\n * Descendants call {@link useClientSession} with the same `channelName` to\n * access the session.\n *\n * If `createClientSession` throws during construction, the error is surfaced\n * through `useClientSession` as `sessionError` — the component tree does not\n * crash and children are still rendered.\n *\n * ```tsx\n * <AblyProvider client={ably}>\n * <ClientSessionProvider channelName=\"ai:demo\" codec={UIMessageCodec}>\n * <Chat />\n * </ClientSessionProvider>\n * </AblyProvider>\n *\n * // Inside Chat:\n * const { session, sessionError } = useClientSession({ channelName: 'ai:demo' });\n * ```\n *\n * For multiple sessions, nest providers with distinct channelNames:\n *\n * ```tsx\n * <ClientSessionProvider channelName=\"ai:main\" codec={UIMessageCodec}>\n * <ClientSessionProvider channelName=\"ai:aux\" codec={UIMessageCodec}>\n * <App />\n * </ClientSessionProvider>\n * </ClientSessionProvider>\n *\n * // Inside App:\n * const { session: main } = useClientSession({ channelName: 'ai:main' });\n * const { session: aux } = useClientSession({ channelName: 'ai:aux' });\n * ```\n * @param props - Provider configuration including `channelName`, `codec`, and all other {@link ClientSessionOptions} except `client`.\n * @param props.children - Descendant components that consume the session via {@link useClientSession}.\n * @returns A React element wrapping children with ClientSessionContext.\n */\nexport const ClientSessionProvider = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>({\n children,\n ...sessionOptions\n}: ClientSessionProviderProps<TInput, TOutput, TProjection, TMessage>): ReactNode => {\n const client = useAbly();\n const { channelName } = sessionOptions;\n const sessionRef = useRef<ClientSession<TInput, TOutput, TProjection, TMessage> | undefined>(undefined);\n const sessionChannelRef = useRef<string>(channelName);\n const sessionsToDisposeRef = useRef<ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown>[]>([]);\n const pendingCloseRef = useRef(false);\n const constructionErrorRef = useRef<Ably.ErrorInfo | undefined>(undefined);\n\n const alreadyCreatedOrFailed = !!sessionRef.current || !!constructionErrorRef.current;\n\n if (!alreadyCreatedOrFailed || sessionChannelRef.current !== channelName) {\n sessionChannelRef.current = channelName;\n if (sessionRef.current) sessionsToDisposeRef.current.push(sessionRef.current);\n try {\n sessionRef.current = createClientSession({ ...sessionOptions, client });\n constructionErrorRef.current = undefined;\n } catch (error) {\n sessionRef.current = undefined;\n constructionErrorRef.current =\n error instanceof Ably.ErrorInfo\n ? error\n : new Ably.ErrorInfo('Unknown error while creating client session', ErrorCode.BadRequest, 400);\n }\n }\n\n const parentContext = useContext(ClientSessionContext);\n\n // Capture ref values as locals so useMemo deps track changes correctly.\n // CAST: ClientSessionContext stores sessions with erased generics.\n // The generic types are fixed at the ClientSessionProvider<TInput, TOutput, TProjection, TMessage> boundary.\n const currentSession = sessionRef.current as\n | ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown>\n | undefined;\n const currentError = constructionErrorRef.current;\n\n const slot = useMemo<ClientSessionSlot>(\n () => ({ session: currentSession, sessionError: currentError }),\n [currentSession, currentError],\n );\n\n const contextValue = useMemo(\n () => ({ nearest: slot, providers: { ...parentContext.providers, [channelName]: slot } }),\n [channelName, parentContext, slot],\n );\n\n // Dispose sessions superseded by a channelName change. When channelName\n // changes, the render path above pushes the now-stale session into\n // sessionsToDisposeRef and creates a replacement. This effect's cleanup —\n // which runs on the next channelName change or on unmount — closes every\n // queued session.\n useEffect(\n () => () => {\n for (const session of sessionsToDisposeRef.current) void session.close();\n },\n [channelName],\n );\n\n // Trigger connect() once the session is created. Re-runs when channelName\n // changes so the freshly-recreated session connects too. Any error is\n // stored on the session's emitter and surfaced via on('error');\n // useClientSession doesn't need to await this.\n useEffect(() => {\n void sessionRef.current?.connect();\n }, [channelName]);\n\n // Close the session when the component truly unmounts. The close is\n // scheduled as a microtask: in React Strict Mode (dev) the component\n // remounts synchronously before any microtask can drain, so the remount's\n // effect setup resets pendingCloseRef.current = false and cancels the\n // close. On a real unmount no remount follows, the microtask fires, and\n // the session is closed.\n useEffect(() => {\n pendingCloseRef.current = false;\n return () => {\n pendingCloseRef.current = true;\n void Promise.resolve().then(() => {\n if (pendingCloseRef.current) {\n void sessionRef.current?.close();\n }\n });\n };\n }, []);\n\n return <ClientSessionContext.Provider value={contextValue}>{children}</ClientSessionContext.Provider>;\n};\n","import { useContext } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../../core/codec/types.js';\nimport type { ClientSession } from '../../core/transport/types.js';\nimport { ClientSessionContext } from '../contexts/client-session-context.js';\n\n/**\n * Shared base for hook options that accept an explicit session override.\n * Extend this interface for any hook whose `session` option defaults to the\n * nearest {@link ClientSessionProvider} when omitted. Pass `null` to defer\n * resolution (e.g. when a split pane is collapsed) — the helper returns\n * `undefined` rather than falling back to the nearest provider.\n */\nexport interface BaseSessionOption<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> {\n /**\n * Session to operate on; defaults to the nearest {@link ClientSessionProvider}.\n * Pass `null` to defer (returns undefined; nearest provider is not used).\n */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage> | null;\n}\n\n/**\n * Resolve the active `ClientSession` for a hook.\n *\n * Reads `ClientSessionContext` and applies the standard three-way\n * priority: explicit `session` argument → nearest provider → `undefined`.\n * When `skip` is `true`, returns `undefined` regardless of context.\n * When `session` is `null`, returns `undefined` (caller is deferring).\n *\n * Internal — not part of the public API.\n * @param root0 - Options.\n * @param root0.session - Explicit session; takes priority over the nearest provider. `null` to defer.\n * @param root0.skip - When `true`, returns `undefined` immediately; context is still read but its value is ignored.\n * @returns The resolved session, or `undefined` if none is available or `skip` is `true`.\n */\nexport const useResolvedSession = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>({\n session,\n skip,\n}: {\n /** Explicit session; takes priority over the nearest provider. `null` to defer. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage> | null;\n /** When `true`, return `undefined` immediately (context is still read, but ignored). */\n skip?: boolean;\n} = {}): ClientSession<TInput, TOutput, TProjection, TMessage> | undefined => {\n const { nearest } = useContext(ClientSessionContext);\n // CAST: ClientSessionContext stores session with erased generics; types fixed at call site.\n const nearestSession = nearest?.session as unknown as\n | ClientSession<TInput, TOutput, TProjection, TMessage>\n | undefined;\n if (skip) return undefined;\n if (session === null) return undefined;\n return session ?? nearestSession;\n};\n","/**\n * useAblyMessages — reactive raw Ably message log from a ClientSession.\n *\n * Accumulates raw Ably InboundMessages from the session's tree\n * 'ably-message' event. Messages are appended in arrival order.\n *\n * When `session` is omitted, defaults to the nearest\n * {@link ClientSessionProvider}'s session via context.\n * Pass `skip: true` to bypass all subscriptions and return an empty array.\n */\n\nimport type * as Ably from 'ably';\nimport { useEffect, useRef, useState } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { BaseSessionOption } from './internal/use-resolved-session.js';\nimport { useResolvedSession } from './internal/use-resolved-session.js';\n\n/** Options for {@link useAblyMessages}. */\nexport interface UseAblyMessagesOptions<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> extends BaseSessionOption<TInput, TOutput, TProjection, TMessage> {\n /** When `true`, skip all subscriptions and return an empty array. */\n skip?: boolean;\n}\n\n/**\n * Subscribe to raw Ably message updates from a client session's tree.\n * When `session` is omitted, uses the nearest {@link ClientSessionProvider}'s session via context.\n * @param props - Options including optional `session` and `skip`.\n * @param props.session - Session to subscribe to; defaults to the nearest provider.\n * @param props.skip - When `true`, skip all subscriptions and return an empty array.\n * @returns The accumulated raw Ably messages in event-arrival order — older history messages loaded later are appended after the live messages already present, so this is not strictly chronological.\n */\nexport const useAblyMessages = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>({ session, skip }: UseAblyMessagesOptions<TInput, TOutput, TProjection, TMessage> = {}): Ably.InboundMessage[] => {\n const resolved = useResolvedSession({ session, skip });\n\n const [messages, setMessages] = useState<Ably.InboundMessage[]>([]);\n const messagesRef = useRef<Ably.InboundMessage[]>([]);\n\n useEffect(() => {\n // Reset on session change\n messagesRef.current = [];\n setMessages([]);\n\n if (!resolved) return;\n\n const unsub = resolved.tree.on('ably-message', (msg: Ably.InboundMessage) => {\n const next = [...messagesRef.current, msg];\n messagesRef.current = next;\n setMessages(next);\n });\n return unsub;\n }, [resolved]);\n\n return messages;\n};\n","/**\n * useClientSession — read a ClientSession from the nearest ClientSessionProvider.\n *\n * The session is created by {@link ClientSessionProvider}, which reads the Ably\n * Realtime client from the surrounding `<AblyProvider>`. This hook is a thin\n * context reader — it does not create or manage session state.\n *\n * **Provider lookup**\n * - Omit `channelName` to use the innermost `ClientSessionProvider` in the tree.\n * - Pass `channelName` to look up a specific provider by name.\n * - Pass `skip: true` to receive a stub session that throws on any access —\n * safe to hold in state before auth or other conditions are ready.\n *\n * **Error handling**\n * - When no matching provider is found, or when the provider's `createClientSession`\n * call threw, `sessionError` is set on the returned object instead of throwing.\n * The component can render an error state without an error boundary.\n * - Pass `onError` to receive post-construction session errors (e.g. send failures,\n * channel continuity loss) without wiring `session.on('error', ...)` manually.\n */\n\nimport * as Ably from 'ably';\nimport { useContext, useEffect, useRef } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { ClientSession, Tree, View } from '../core/transport/types.js';\nimport { ErrorCode } from '../errors.js';\nimport { ClientSessionContext } from './contexts/client-session-context.js';\n\nconst SKIPPED_SESSION: ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown> = {\n get tree(): Tree<CodecOutputEvent, unknown> {\n throw new Ably.ErrorInfo('unable to access tree; hook is skipped', ErrorCode.InvalidArgument, 400);\n },\n get view(): View<CodecInputEvent, unknown> {\n throw new Ably.ErrorInfo('unable to access view; hook is skipped', ErrorCode.InvalidArgument, 400);\n },\n connect: () => {\n throw new Ably.ErrorInfo('unable to connect; hook is skipped', ErrorCode.InvalidArgument, 400);\n },\n createView: (): View<CodecInputEvent, unknown> => {\n throw new Ably.ErrorInfo('unable to create view; hook is skipped', ErrorCode.InvalidArgument, 400);\n },\n cancel: () => {\n throw new Ably.ErrorInfo('unable to cancel; hook is skipped', ErrorCode.InvalidArgument, 400);\n },\n on: () => {\n throw new Ably.ErrorInfo('unable to subscribe; hook is skipped', ErrorCode.InvalidArgument, 400);\n },\n close: () => {\n throw new Ably.ErrorInfo('unable to close; hook is skipped', ErrorCode.InvalidArgument, 400);\n },\n};\n\n/**\n * Return value of {@link useClientSession}.\n *\n * `session` is always a valid object. When `skip` is `true`, when no provider was\n * found, or when the provider's session construction failed, `session` is a stub\n * that throws {@link Ably.ErrorInfo} on every access.\n * Check `sessionError` before using `session` to avoid those throws.\n */\nexport interface ClientSessionHandle<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> {\n /**\n * The resolved session.\n *\n * A throwing stub when `skip` is `true`, when no matching {@link ClientSessionProvider}\n * was found in the tree, or when session construction failed.\n */\n session: ClientSession<TInput, TOutput, TProjection, TMessage>;\n /**\n * Set when no matching {@link ClientSessionProvider} was found, when session\n * construction failed, and `skip` is `false`.\n * `undefined` when the session resolved successfully or when `skip` is `true`.\n */\n sessionError?: Ably.ErrorInfo | undefined;\n}\n\n/**\n * Read a {@link ClientSession} from the nearest {@link ClientSessionProvider}.\n *\n * Returns `{ session, sessionError }`. When no provider is found or session\n * construction failed, `sessionError` is set and `session` is a stub that throws\n * on access — the hook never throws during render.\n *\n * Pass `onError` to subscribe to post-construction session errors\n * (e.g. {@link ErrorCode.SessionSendFailed}, {@link ErrorCode.ChannelContinuityLost})\n * without calling `session.on('error', …)` manually. The subscription is\n * created when the session resolves and removed on unmount.\n * @param props - Hook options.\n * @param props.channelName - Look up a specific provider by channel name; omit for the nearest.\n * @param props.skip - When `true`, return the stub session immediately without resolving a provider slot.\n * @param props.onError - Called whenever the resolved session emits an error event.\n * @returns `{ session, sessionError }`.\n */\nexport const useClientSession = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>({\n channelName,\n skip,\n onError,\n}: {\n /**\n * Channel name passed to the enclosing {@link ClientSessionProvider}.\n * Omit to use the nearest provider in the tree.\n */\n channelName?: string;\n /**\n * When `true`, skip context lookup and return a stub session that throws on\n * any access. Use when a condition (auth, feature flag) is not yet resolved.\n */\n skip?: boolean;\n /**\n * Called whenever the resolved session emits an error event.\n * The subscription is established once the session resolves and\n * automatically removed on unmount or when the session changes.\n */\n onError?: (error: Ably.ErrorInfo) => void;\n} = {}): ClientSessionHandle<TInput, TOutput, TProjection, TMessage> => {\n const { nearest: nearestSlot, providers } = useContext(ClientSessionContext);\n const errorCallbackRef = useRef(onError);\n errorCallbackRef.current = onError;\n\n // Compute the session for the onError subscription *before* any conditional\n // returns to satisfy React's rules of hooks (no hooks in branches).\n // Erased generics — this local is only used in the useEffect below.\n const resolvedForEffect: ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown> | undefined = skip\n ? undefined\n : channelName === undefined\n ? nearestSlot?.session\n : providers[channelName]?.session;\n\n useEffect(() => {\n if (!resolvedForEffect) return;\n return resolvedForEffect.on('error', (errorInfo: Ably.ErrorInfo) => {\n errorCallbackRef.current?.(errorInfo);\n });\n }, [resolvedForEffect]);\n\n if (skip) {\n return {\n session: SKIPPED_SESSION as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n };\n }\n\n if (channelName !== undefined) {\n const slot = providers[channelName];\n if (slot) {\n if (slot.session) {\n // CAST: ClientSessionContext stores sessions with erased generics.\n // The caller is responsible for using type parameters matching those of the ClientSessionProvider.\n return {\n session: slot.session as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n };\n }\n // Provider exists but construction failed.\n return {\n session: SKIPPED_SESSION as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n sessionError: slot.sessionError,\n };\n }\n return {\n session: SKIPPED_SESSION as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n sessionError: new Ably.ErrorInfo(\n `unable to use session; no ClientSessionProvider found for channelName \"${channelName}\"`,\n ErrorCode.BadRequest,\n 400,\n ),\n };\n }\n\n if (nearestSlot) {\n if (nearestSlot.session) {\n // CAST: ClientSessionContext stores session with erased generics; types fixed at call site.\n return {\n session: nearestSlot.session as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n };\n }\n // Nearest provider exists but construction failed.\n return {\n session: SKIPPED_SESSION as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n sessionError: nearestSlot.sessionError,\n };\n }\n\n return {\n session: SKIPPED_SESSION as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n sessionError: new Ably.ErrorInfo(\n 'unable to use session; no ClientSessionProvider found in the tree',\n ErrorCode.BadRequest,\n 400,\n ),\n };\n};\n","/**\n * useView — reactive paginated view of the conversation.\n *\n * Subscribes to view updates and exposes the visible messages, msg-anchored\n * branch navigation, write operations, pagination state, and a `loadOlder`\n * callback. Pass `session` to use a session's default view, or `view` to\n * subscribe to a specific {@link View} directly. When both are omitted,\n * defaults to the nearest {@link ClientSessionProvider}'s session via context.\n */\n\nimport * as Ably from 'ably';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport type { CodecInputEvent, CodecMessage, CodecOutputEvent } from '../core/codec/types.js';\nimport type { ActiveRun, BranchSelection, RunInfo, SendOptions, View } from '../core/transport/types.js';\nimport { ErrorCode } from '../errors.js';\nimport type { BaseSessionOption } from './internal/use-resolved-session.js';\nimport { useResolvedSession } from './internal/use-resolved-session.js';\n\n/** Options for {@link useView}. */\nexport interface UseViewOptions<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> extends BaseSessionOption<TInput, TOutput, TProjection, TMessage> {\n /** A specific {@link View} to subscribe to directly. Takes priority over `session`. */\n view?: View<TInput, TMessage> | null;\n /** Maximum number of older Runs to reveal per page (the pagination unit is the Run, not the message). When provided, auto-loads the first page on mount. */\n limit?: number;\n /** When `true`, skip all subscriptions and return an empty handle immediately. */\n skip?: boolean;\n}\n\n/** Handle for the paginated, branch-aware conversation view. */\nexport interface ViewHandle<TInput extends CodecInputEvent, TMessage> {\n /**\n * The visible messages along the selected branch, concatenated across all\n * visible Runs, each paired with its codec-message-id (see\n * {@link CodecMessage}). Read the domain object from each entry's\n * `message` field.\n *\n * Correlate a rendered message back to the View — `runOf`,\n * `branchSelection`, `selectSibling`, `regenerate`, or `edit` — via its\n * `codecMessageId`, which the SDK assigns and tracks independently of any\n * identity the domain `message` may carry. See {@link View.getMessages}.\n */\n messages: CodecMessage<TMessage>[];\n /** Whether there are older Runs that can be revealed via `loadOlder`. */\n hasOlder: boolean;\n /** Whether a page load is currently in progress. */\n loading: boolean;\n /**\n * Set when the most recent `loadOlder` call failed.\n * Cleared automatically on the next successful load.\n * `undefined` when no error has occurred or when `skip` is `true`.\n */\n loadError: Ably.ErrorInfo | undefined;\n /**\n * Load older messages into the view. No-op if already loading.\n * On failure, `loadError` is set; on success, `loadError` is cleared.\n */\n loadOlder: () => Promise<void>;\n /**\n * Look up the {@link RunInfo} for the Run that owns `codecMessageId`.\n * Returns `undefined` when the codec-message-id hasn't been observed.\n * See {@link View.runOf}.\n */\n runOf: (codecMessageId: string) => RunInfo | undefined;\n /**\n * Direct lookup by runId. Returns `undefined` when the Run hasn't been\n * observed. See {@link View.run}.\n */\n run: (runId: string) => RunInfo | undefined;\n /**\n * Snapshot of the visible Runs along the selected branch, in\n * chronological order. Returns `[]` when the view isn't resolved.\n * See {@link View.runs}.\n */\n runs: () => RunInfo[];\n /**\n * Resolve the {@link BranchSelection} bundle anchored at\n * `codecMessageId`. Always returns a safe object — see\n * {@link BranchSelection}. See {@link View.branchSelection}.\n */\n branchSelection: (codecMessageId: string) => BranchSelection<TMessage>;\n /**\n * Select a sibling at the branch point anchored at `codecMessageId`.\n * `index` is clamped to `[0, siblings.length - 1]`. Silent no-op when\n * `codecMessageId` isn't a branch anchor. See {@link View.selectSibling}.\n */\n selectSibling: (codecMessageId: string, index: number) => void;\n /**\n * Send one or more TInputs on the channel and fire a POST. See {@link View.send}.\n * @throws Ably.ErrorInfo with code {@link ErrorCode.InvalidArgument} when no view is resolved (before the session is available, or when `skip` is `true`).\n */\n send: (events: TInput | TInput[], options?: SendOptions) => Promise<ActiveRun>;\n /**\n * Regenerate an assistant message, using this view's branch for history.\n * @throws Ably.ErrorInfo with code {@link ErrorCode.InvalidArgument} when no view is resolved (before the session is available, or when `skip` is `true`).\n */\n regenerate: (messageId: string, options?: SendOptions) => Promise<ActiveRun>;\n /**\n * Edit a user message, forking from this view's branch.\n * Rejects with an `Ably.ErrorInfo` (code {@link ErrorCode.InvalidArgument}) if no view is resolved — e.g. before the session is available, or when `skip` is `true`.\n */\n edit: (messageId: string, inputs: TInput | TInput[], options?: SendOptions) => Promise<ActiveRun>;\n}\n\n/**\n * Fallback returned by `branchSelection` when the view isn't resolved.\n * Same shape the view returns for an unknown codec-message-id, so callers\n * can destructure uniformly.\n */\nconst EMPTY_BRANCH_SELECTION: BranchSelection<never> = {\n hasSiblings: false,\n siblings: [],\n index: 0,\n selected: undefined,\n};\n\n/**\n * Subscribe to a view and return the visible messages with pagination, navigation, and write operations.\n *\n * `view` takes priority over `session`. When neither is provided, the nearest\n * {@link ClientSessionProvider}'s session is used. When `limit` is provided, auto-loads\n * the first page on mount (SWR-style).\n * @param props - Options for selecting the view source and configuring auto-load.\n * @param props.session - Client session whose default view to subscribe to; defaults to the nearest provider.\n * @param props.view - A specific {@link View} to subscribe to directly. Takes priority over `session`.\n * @param props.limit - Max older Runs to reveal per page; when provided, auto-loads the first page on mount.\n * @param props.skip - When `true`, skip all subscriptions and return an empty handle.\n * @returns A {@link ViewHandle} with messages, pagination state, navigation, write operations, and loadOlder.\n */\nexport const useView = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>({\n session,\n view,\n limit,\n skip,\n}: UseViewOptions<TInput, TOutput, TProjection, TMessage> = {}): ViewHandle<TInput, TMessage> => {\n const resolvedSession = useResolvedSession({ session, skip });\n const resolvedView = skip ? undefined : (view ?? resolvedSession?.view);\n\n const [messages, setMessages] = useState<CodecMessage<TMessage>[]>(() => resolvedView?.getMessages() ?? []);\n const [hasOlder, setHasOlder] = useState(() => resolvedView?.hasOlder() ?? false);\n const [loading, setLoading] = useState(false);\n const [loadError, setLoadError] = useState<Ably.ErrorInfo | undefined>();\n const loadingRef = useRef(false);\n\n // Auto-load first page on mount when limit is provided (SWR-style).\n // Fires once per view instance — subsequent changes to limit\n // only affect manual loadOlder() calls, not the initial auto-load.\n const autoLoad = limit !== undefined;\n const autoLoadedRef = useRef(false);\n\n // Subscribe to view updates\n useEffect(() => {\n if (!resolvedView) {\n setMessages([]);\n setHasOlder(false);\n setLoadError(undefined);\n return;\n }\n\n // Reset auto-load flag so the new view gets its first page loaded\n autoLoadedRef.current = false;\n\n // Sync initial state\n setMessages(resolvedView.getMessages());\n setHasOlder(resolvedView.hasOlder());\n setLoadError(undefined);\n\n const unsub = resolvedView.on('update', () => {\n setMessages(resolvedView.getMessages());\n setHasOlder(resolvedView.hasOlder());\n });\n return unsub;\n }, [resolvedView]);\n\n const loadOlder = useCallback(async () => {\n if (!resolvedView || loadingRef.current) return;\n loadingRef.current = true;\n setLoading(true);\n try {\n await resolvedView.loadOlder(limit);\n setLoadError(undefined);\n } catch (error) {\n if (error instanceof Ably.ErrorInfo) {\n setLoadError(error);\n } else {\n setLoadError(new Ably.ErrorInfo('Unknown error loading older messages', ErrorCode.BadRequest, 400));\n }\n } finally {\n loadingRef.current = false;\n setLoading(false);\n }\n }, [resolvedView, limit]);\n\n useEffect(() => {\n if (!autoLoad || autoLoadedRef.current || !resolvedView) return;\n autoLoadedRef.current = true;\n void loadOlder();\n }, [autoLoad, resolvedView, loadOlder]);\n\n // Run lookups\n const runOf = useCallback(\n (codecMessageId: string): RunInfo | undefined => resolvedView?.runOf(codecMessageId),\n [resolvedView],\n );\n\n const run = useCallback((runId: string): RunInfo | undefined => resolvedView?.run(runId), [resolvedView]);\n\n const runs = useCallback((): RunInfo[] => resolvedView?.runs() ?? [], [resolvedView]);\n\n // Branch navigation\n const branchSelection = useCallback(\n (codecMessageId: string): BranchSelection<TMessage> =>\n // CAST: `EMPTY_BRANCH_SELECTION` is typed `BranchSelection<never>`; `never` is\n // assignable to any `TMessage`, so the empty bundle is a valid fallback for\n // the not-yet-resolved view case.\n resolvedView?.branchSelection(codecMessageId) ?? (EMPTY_BRANCH_SELECTION as BranchSelection<TMessage>),\n [resolvedView],\n );\n\n const selectSibling = useCallback(\n (codecMessageId: string, index: number) => {\n resolvedView?.selectSibling(codecMessageId, index);\n },\n [resolvedView],\n );\n\n // Write operation callbacks\n const send = useCallback(\n async (events: TInput | TInput[], opts?: SendOptions) => {\n if (!resolvedView)\n throw new Ably.ErrorInfo('unable to send; view is not available', ErrorCode.InvalidArgument, 400);\n return resolvedView.send(events, opts);\n },\n [resolvedView],\n );\n\n const regenerate = useCallback(\n async (messageId: string, opts?: SendOptions) => {\n if (!resolvedView)\n throw new Ably.ErrorInfo('unable to regenerate; view is not available', ErrorCode.InvalidArgument, 400);\n return resolvedView.regenerate(messageId, opts);\n },\n [resolvedView],\n );\n\n const edit = useCallback(\n async (messageId: string, inputs: TInput | TInput[], opts?: SendOptions) => {\n if (!resolvedView)\n throw new Ably.ErrorInfo('unable to edit; view is not available', ErrorCode.InvalidArgument, 400);\n return resolvedView.edit(messageId, inputs, opts);\n },\n [resolvedView],\n );\n\n return {\n messages,\n hasOlder,\n loading,\n loadError,\n loadOlder,\n runOf,\n run,\n runs,\n branchSelection,\n selectSibling,\n send,\n regenerate,\n edit,\n };\n};\n","/**\n * useCreateView — create an independent view with the same API as useView.\n *\n * Calls {@link ClientSession.createView} to create an independent view over\n * the same conversation tree, then subscribes to it exactly like\n * {@link useView}. The view is closed automatically on unmount or when the\n * session reference changes.\n *\n * Pass `null` or omit `session` to defer creation (e.g. when a split pane is\n * collapsed). The returned handle has empty state until a session is provided.\n * When `session` is omitted entirely, defaults to the nearest\n * {@link ClientSessionProvider}'s session via context.\n * Pass `skip: true` to bypass all context reads and view creation entirely.\n */\n\nimport { useEffect, useState } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { View } from '../core/transport/types.js';\nimport type { BaseSessionOption } from './internal/use-resolved-session.js';\nimport { useResolvedSession } from './internal/use-resolved-session.js';\nimport type { ViewHandle } from './use-view.js';\nimport { useView } from './use-view.js';\n\n/** Options for {@link useCreateView}. */\nexport interface UseCreateViewOptions<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> extends BaseSessionOption<TInput, TOutput, TProjection, TMessage> {\n /** When provided, auto-loads the first page on mount. Omit for manual load. */\n limit?: number;\n /** When `true`, skip view creation and return an empty handle immediately. */\n skip?: boolean;\n}\n\n/**\n * Create an independent {@link View} and subscribe to it.\n * Returns the same {@link ViewHandle} as {@link useView}, but backed by a\n * newly created view with its own branch selections and pagination state.\n * The view is closed on unmount or when the session changes.\n * When `session` is omitted, uses the nearest {@link ClientSessionProvider}'s session via context.\n * @param props - Options including optional `session`, `limit` for auto-load, and `skip`.\n * @param props.session - Session to create a view from; defaults to the nearest provider.\n * @param props.limit - Max older messages per page; when provided, auto-loads on mount.\n * @param props.skip - When `true`, skip view creation and return an empty handle.\n * @returns A {@link ViewHandle} with nodes, pagination, navigation, and write operations.\n */\nexport const useCreateView = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>({\n session,\n limit,\n skip,\n}: UseCreateViewOptions<TInput, TOutput, TProjection, TMessage> = {}): ViewHandle<TInput, TMessage> => {\n const resolved = useResolvedSession({ session, skip });\n\n const [view, setView] = useState<View<TInput, TMessage> | undefined>();\n\n useEffect(() => {\n if (!resolved) {\n setView(undefined);\n return;\n }\n const v = resolved.createView();\n setView(v);\n return () => {\n v.close();\n };\n }, [resolved]);\n\n return useView({ view, limit, skip });\n};\n","/**\n * useTree — stable structural query callbacks for a ClientSession's tree.\n *\n * Returns a {@link TreeHandle} with methods to inspect the tree structure.\n * These are thin `useCallback` wrappers around `session.tree` — no local\n * state or subscriptions. Branch navigation (select, getSelectedIndex) is\n * on {@link ViewHandle} from {@link useView}.\n *\n * When `session` is omitted, defaults to the nearest\n * {@link ClientSessionProvider}'s session via context.\n */\n\nimport { useCallback } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { ConversationNode, RunNode } from '../core/transport/types.js';\nimport type { BaseSessionOption } from './internal/use-resolved-session.js';\nimport { useResolvedSession } from './internal/use-resolved-session.js';\n\n/** Handle for querying the conversation tree structure. */\nexport interface TreeHandle<TProjection> {\n /**\n * Get the RunNode for `runId`, or undefined if no node is keyed by `runId`\n * (or the keyed node is an input node, not a reply run).\n */\n getRunNode: (runId: string) => RunNode<TProjection> | undefined;\n /**\n * Get the node that owns a given codec-message-id, or undefined if not\n * observed. Returns a {@link ConversationNode} union — narrow on `kind`\n * (`'input'` vs `'run'`) before reading kind-specific fields.\n */\n getNodeByCodecMessageId: (codecMessageId: string) => ConversationNode<TProjection> | undefined;\n /**\n * Get the sibling group (both kinds) the node keyed by `key` belongs to —\n * edit versions for an input node, regenerate runs for a reply run — ordered\n * oldest-first. A single-element array when the node has no siblings; empty\n * when `key` is unknown. `key` is a {@link RunNode.runId} or an\n * {@link InputNode.codecMessageId}.\n */\n getSiblingNodes: (key: string) => ConversationNode<TProjection>[];\n}\n\n/** Options for {@link useTree}. */\nexport type UseTreeOptions<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> = BaseSessionOption<TInput, TOutput, TProjection, TMessage>;\n\n/**\n * Provide stable structural query callbacks backed by the session's tree.\n * When `session` is omitted, uses the nearest {@link ClientSessionProvider}'s session via context.\n * @param props - Options including optional `session`.\n * @param props.session - Session to read tree structure from; defaults to the nearest provider.\n * @returns A {@link TreeHandle} with structural query methods.\n */\nexport const useTree = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>({\n session,\n}: UseTreeOptions<TInput, TOutput, TProjection, TMessage> = {}): TreeHandle<TProjection> => {\n const resolved = useResolvedSession({ session });\n\n const getRunNode = useCallback(\n (runId: string): RunNode<TProjection> | undefined => resolved?.tree.getRunNode(runId),\n [resolved],\n );\n\n const getNodeByCodecMessageId = useCallback(\n (codecMessageId: string): ConversationNode<TProjection> | undefined =>\n resolved?.tree.getNodeByCodecMessageId(codecMessageId),\n [resolved],\n );\n\n const getSiblingNodes = useCallback(\n (key: string): ConversationNode<TProjection>[] => resolved?.tree.getSiblingNodes(key) ?? [],\n [resolved],\n );\n\n return {\n getRunNode,\n getNodeByCodecMessageId,\n getSiblingNodes,\n };\n};\n","/**\n * createSessionHooks: factory that captures the codec's type parameters once and\n * returns a bundle of type-safe hooks + ClientSessionProvider. Hook call sites need\n * no type parameters at every use — just call the hooks directly.\n * @example\n * // Once per app (e.g. in a shared session.ts):\n * export const {\n * ClientSessionProvider,\n * useClientSession,\n * useView,\n * } = createSessionHooks<VercelInput, VercelOutput, VercelProjection, UIMessage>();\n *\n * // In page:\n * <ClientSessionProvider channelName=\"ai:demo\" codec={UIMessageCodec}>\n * <Chat />\n * </ClientSessionProvider>\n *\n * // In Chat — no type params needed, session is implicit from nearest provider:\n * const { nodes } = useView({ limit: 30 });\n */\n\nimport type * as Ably from 'ably';\nimport type { ComponentType } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { ClientSession, View } from '../core/transport/types.js';\nimport type { ClientSessionProviderProps } from './contexts/client-session-provider.js';\nimport { ClientSessionProvider as _ClientSessionProvider } from './contexts/client-session-provider.js';\nimport { useAblyMessages as _useAblyMessages } from './use-ably-messages.js';\nimport type { ClientSessionHandle } from './use-client-session.js';\nimport { useClientSession as _useClientSession } from './use-client-session.js';\nimport { useCreateView as _useCreateView } from './use-create-view.js';\nimport type { TreeHandle } from './use-tree.js';\nimport { useTree as _useTree } from './use-tree.js';\nimport type { ViewHandle } from './use-view.js';\nimport { useView as _useView } from './use-view.js';\n\n/**\n * Bundle of type-safe hooks and provider returned by {@link createSessionHooks}.\n *\n * The codec's `TInput`, `TOutput`, `TProjection`, and `TMessage` are baked in at\n * factory creation time so no type params are needed at hook call sites.\n */\nexport interface SessionHooks<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage> {\n /**\n * `ClientSessionProvider` narrowed to the codec's `TInput`/`TOutput`/`TMessage`. No JSX type params needed.\n */\n ClientSessionProvider: ComponentType<ClientSessionProviderProps<TInput, TOutput, TProjection, TMessage>>;\n /**\n * Read the session from context. No type params needed.\n *\n * Returns `{ session, sessionError }`. When no provider is found (or session\n * construction failed), `sessionError` is set and `session` is a stub that\n * throws on access — the hook never throws during render.\n *\n * Pass `onError` to subscribe to post-construction session errors\n * (e.g. send failures, channel continuity loss) without wiring\n * `session.on('error', …)` manually.\n */\n useClientSession: (props?: {\n /** Channel name to look up; omit to use the nearest {@link ClientSessionProvider}. */\n channelName?: string;\n /** When `true`, return a stub session that throws on any access. */\n skip?: boolean;\n /** Called whenever the resolved session emits an error event. */\n onError?: (error: Ably.ErrorInfo) => void;\n }) => ClientSessionHandle<TInput, TOutput, TProjection, TMessage>;\n /**\n * Subscribe to the nearest session's view and return the visible message list with pagination.\n * Pass `session` to use a session's default view, `view` to subscribe to a specific view\n * directly. Pass `limit` to auto-load on mount. Pass `skip: true` for an empty handle.\n */\n useView: (props?: {\n /** Client session whose default view to subscribe to; defaults to the nearest {@link ClientSessionProvider}. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage> | null;\n /** A specific {@link View} to subscribe to directly. Takes priority over `session`. */\n view?: View<TInput, TMessage> | null;\n /** When provided, auto-loads the first page on mount. */\n limit?: number;\n /** When `true`, skip all subscriptions and return an empty handle. */\n skip?: boolean;\n }) => ViewHandle<TInput, TMessage>;\n /**\n * Navigate conversation branches in the session tree.\n * Pass `session` to override; defaults to the nearest {@link ClientSessionProvider}.\n */\n useTree: (props?: {\n /** Override session; defaults to the nearest {@link ClientSessionProvider}. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage>;\n }) => TreeHandle<TProjection>;\n /**\n * Subscribe to raw Ably messages on the session channel.\n * Pass `session` to override; defaults to the nearest {@link ClientSessionProvider}.\n * Pass `skip: true` to return an empty array without subscribing.\n */\n useAblyMessages: (props?: {\n /** Override session; defaults to the nearest {@link ClientSessionProvider}. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage>;\n /** When `true`, skip all subscriptions and return an empty array. */\n skip?: boolean;\n }) => Ably.InboundMessage[];\n /**\n * Create an independent view over the same tree.\n * Pass `session` to override; defaults to the nearest {@link ClientSessionProvider}.\n * Pass `skip: true` to return an empty handle without creating a view.\n */\n useCreateView: (props?: {\n /** Override session; defaults to the nearest {@link ClientSessionProvider}. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage> | null;\n /** When provided, auto-loads the first page on mount. */\n limit?: number;\n /** When `true`, skip view creation and return an empty handle. */\n skip?: boolean;\n }) => ViewHandle<TInput, TMessage>;\n}\n\n/**\n * Create a bundle of type-safe hooks and provider for a given codec's\n * `TInput`/`TOutput`/`TProjection`/`TMessage`.\n *\n * These type parameters are captured at factory creation time; hook call sites need\n * no type parameters. The returned hooks are thin wrappers around the standalone hooks\n * with the types resolved.\n * @returns A {@link SessionHooks} bundle.\n */\nexport const createSessionHooks = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(): SessionHooks<TInput, TOutput, TProjection, TMessage> => ({\n // CAST: ClientSessionProvider is generic; factory narrows it to the codec's TInput/TOutput/TProjection/TMessage.\n ClientSessionProvider: _ClientSessionProvider as ComponentType<\n ClientSessionProviderProps<TInput, TOutput, TProjection, TMessage>\n >,\n useClientSession: (props) => _useClientSession<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n useView: (props) => _useView<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n useTree: (props) => _useTree<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n useAblyMessages: (props) => _useAblyMessages<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n useCreateView: (props) => _useCreateView<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n});\n"],"mappings":"07BAmBA,IAAa,EAAgB,SAahB,EAAgB,SAGhB,EAAuB,gBAYvB,EAAkB,WAGlB,EAA0B,mBAG1B,EAAuB,gBAavB,EAAyB,kBAGzB,EAAc,OAOd,EAAgB,SAGhB,EAAiB,UAYjB,EAAwB,iBAmBxB,EAAgC,yBAOhC,EAAoB,aAqBpB,GAAe,YCrIhB,EAAL,SAAA,EAAA,OAIL,GAAA,EAAA,WAAA,KAAA,aAKA,EAAA,EAAA,gBAAA,OAAA,kBAMA,EAAA,EAAA,uBAAA,OAAA,yBAQA,EAAA,EAAA,sBAAA,OAAA,wBAKA,EAAA,EAAA,yBAAA,QAAA,2BAKA,EAAA,EAAA,oBAAA,QAAA,sBAKA,EAAA,EAAA,kBAAA,QAAA,oBAKA,EAAA,EAAA,cAAA,QAAA,gBAKA,EAAA,EAAA,kBAAA,QAAA,oBAOA,EAAA,EAAA,sBAAA,QAAA,wBAMA,EAAA,EAAA,gBAAA,QAAA,kBAOA,EAAA,EAAA,YAAA,QAAA,cAOA,EAAA,EAAA,mBAAA,QAAA,sBACF,EAAA,CAAA,CAAA,ECXM,GAAgB,IAA6B,CACjD,WAAY,EAAgB,EAAgB,IAAqB,CAC/D,EAAO,MAAM,EAAQ,CAAE,OAAQ,CAAQ,CAAC,CAC1C,EACA,cAAiB,EACnB,GAMM,GACJ,EAAK,SACL,aAYW,EAAb,cAA6C,EAAgC,CAK3E,YAAY,EAAgB,CAC1B,MAAM,GAAa,CAAM,CAAC,CAC5B,CACF,EC/CY,GAAL,SAAA,EAAA,OAKL,GAAA,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,IAAA,EAAA,EAAA,UAAwD,EAcrE,OAZA,EAAA,EAAA,eAAgB,CACd,GAAI,CAAC,EAAU,CACb,EAAQ,IAAA,EAAS,EACjB,MACF,CACA,IAAM,EAAI,EAAS,WAAW,EAE9B,OADA,EAAQ,CAAC,MACI,CACX,EAAE,MAAM,CACV,CACF,EAAG,CAAC,CAAQ,CAAC,EAEN,EAAQ,CAAE,OAAM,QAAO,MAAK,CAAC,CACtC,ECda,GAAoG,CAC/G,WAC0D,CAAC,IAA+B,CAC1F,IAAM,EAAW,EAAmB,CAAE,SAAQ,CAAC,EAkB/C,MAAO,CACL,YAAA,EAAA,EAAA,aAhBC,GAAoD,GAAU,KAAK,WAAW,CAAK,EACpF,CAAC,CAAQ,CAeT,EACA,yBAAA,EAAA,EAAA,aAZC,GACC,GAAU,KAAK,wBAAwB,CAAc,EACvD,CAAC,CAAQ,CAUT,EACA,iBAAA,EAAA,EAAA,aAPC,GAAiD,GAAU,KAAK,gBAAgB,CAAG,GAAK,CAAC,EAC1F,CAAC,CAAQ,CAMT,CACF,CACF,sDC+C8D,CAErC,wBAGvB,iBAAmB,GAAU,EAA0D,GAAS,CAAC,CAAC,EAClG,QAAU,GAAU,EAAiD,GAAS,CAAC,CAAC,EAChF,QAAU,GAAU,EAAiD,GAAS,CAAC,CAAC,EAChF,gBAAkB,GAAU,EAAyD,GAAS,CAAC,CAAC,EAChG,cAAgB,GAAU,EAAuD,GAAS,CAAC,CAAC,CAC9F"}
|
|
1
|
+
{"version":3,"file":"ably-ai-transport-react.umd.cjs","names":[],"sources":["../../src/core/channel-options.ts","../../src/version.ts","../../src/core/agent.ts","../../src/constants.ts","../../src/errors.ts","../../src/event-emitter.ts","../../src/logger.ts","../../src/utils.ts","../../src/core/transport/headers.ts","../../src/core/transport/decode-fold.ts","../../src/core/transport/invocation.ts","../../src/core/transport/session-support.ts","../../src/core/codec/codec-event.ts","../../src/core/transport/wire-log.ts","../../src/core/transport/tree.ts","../../src/core/transport/load-history-pages.ts","../../src/core/transport/load-history.ts","../../src/core/transport/view.ts","../../src/core/transport/client-session.ts","../../src/react/contexts/client-session-context.ts","../../src/react/contexts/client-session-provider.tsx","../../src/react/internal/use-resolved-session.ts","../../src/react/use-ably-messages.ts","../../src/react/internal/skipped-session.ts","../../src/react/use-client-session.ts","../../src/react/use-view.ts","../../src/react/use-create-view.ts","../../src/react/use-tree.ts","../../src/react/create-session-hooks.ts"],"sourcesContent":["/**\n * Channel-mode resolution shared by the sessions and the React provider.\n *\n * Presence, pub/sub, and annotation publishing are all part of the server's\n * default channel-mode set, so a channel attached with no mode flags is granted\n * them automatically. LiveObjects is different: object operations require the\n * `object_subscribe` / `object_publish` modes, which are NOT in the default\n * set, so the channel must be attached with explicit modes to use them.\n *\n * Setting `modes` on the wire is a full replacement, not additive: the moment\n * an ATTACH carries any mode flag the server takes that bitfield verbatim and\n * never falls back to its default set. So requesting object modes means also\n * requesting everything the default set would grant, plus the object modes.\n * {@link AIT_BASE_MODES} is exactly the server default, so opting into extra\n * modes adds the extras and changes nothing else.\n *\n * Every place that resolves the session's channel options — both session\n * constructors and the React `<ChannelProvider>` — must funnel through\n * {@link resolveChannelModes} so they all request the SAME modes in the SAME\n * order. ably-js compares modes order- and duplicate-sensitively when deciding\n * whether a `setOptions` call needs a reattach; identical arrays compare equal,\n * so consistent resolution avoids both spurious reattaches and silent mode\n * reversion when one writer omits modes another set.\n */\n\nimport type * as Ably from 'ably';\n\n/**\n * The modes AI Transport always needs — byte-for-byte the server's default\n * channel-mode set (`PUBLISH | SUBSCRIBE | PRESENCE | PRESENCE_SUBSCRIBE |\n * ANNOTATION_PUBLISH`). Because this equals the default, requesting it plus\n * extra modes (e.g. {@link OBJECT_MODES}) grants the same access as the default\n * set plus those extras.\n */\nexport const AIT_BASE_MODES: readonly Ably.ChannelMode[] = [\n 'PUBLISH',\n 'SUBSCRIBE',\n 'PRESENCE',\n 'PRESENCE_SUBSCRIBE',\n 'ANNOTATION_PUBLISH',\n];\n\n/**\n * The channel modes required to read and write Ably LiveObjects. Pass as the\n * session's `channelModes` option (`channelModes: OBJECT_MODES`) to enable the\n * `object` accessor on a session and the LiveObjects channel hooks under a\n * `<ClientSessionProvider>`.\n */\nexport const OBJECT_MODES: readonly Ably.ChannelMode[] = ['OBJECT_SUBSCRIBE', 'OBJECT_PUBLISH'];\n\n/**\n * Canonical ordering for every known channel mode. {@link resolveChannelModes}\n * emits modes in this order so two resolutions of the same mode set produce\n * identical arrays, which ably-js treats as equal (no reattach churn).\n */\nconst MODE_ORDER: readonly Ably.ChannelMode[] = [\n 'PUBLISH',\n 'SUBSCRIBE',\n 'PRESENCE',\n 'PRESENCE_SUBSCRIBE',\n 'OBJECT_PUBLISH',\n 'OBJECT_SUBSCRIBE',\n 'ANNOTATION_PUBLISH',\n 'ANNOTATION_SUBSCRIBE',\n];\n\n/**\n * Resolve the channel modes AI Transport should request on its channel.\n *\n * Returns `undefined` when the caller asks for no extra modes, so the channel\n * attaches with no mode flags and the server applies its default set. When\n * extra modes are supplied (e.g. {@link OBJECT_MODES}),\n * returns {@link AIT_BASE_MODES} unioned with them, de-duplicated and in a\n * fixed canonical order so repeated resolutions compare equal.\n *\n * Modes outside {@link MODE_ORDER} (which should not occur for a valid\n * {@link Ably.ChannelMode}, but is possible with the type's lowercase aliases)\n * are appended after the canonical modes, sorted alphabetically, so the result\n * is still deterministic.\n * @param extraModes - Additional modes to request on top of {@link AIT_BASE_MODES}. Omit or pass an empty array to request no modes at all.\n * @returns The canonically-ordered, de-duplicated mode set, or `undefined` when no extra modes were requested.\n */\nexport const resolveChannelModes = (extraModes?: readonly Ably.ChannelMode[]): Ably.ChannelMode[] | undefined => {\n if (extraModes === undefined || extraModes.length === 0) return undefined;\n const requested = new Set<Ably.ChannelMode>([...AIT_BASE_MODES, ...extraModes]);\n const ordered = MODE_ORDER.filter((mode) => requested.has(mode));\n const unknown = [...requested].filter((mode) => !MODE_ORDER.includes(mode)).toSorted();\n return [...ordered, ...unknown];\n};\n","/** SDK version. Kept in sync with `package.json` by the `/release` workflow. */\nexport const VERSION = '0.3.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/**\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 return { params: { agent: joinAgents(agents) } };\n};\n\n/**\n * Build the agent-name → version map this SDK registers for the given codec.\n * @param codec - The codec instance whose optional identifier opts into registration.\n * @param codec.adapterTag - The optional Ably-Agent identifier; registered as an agent when present.\n * @returns Map of agent name to version, always including this SDK.\n */\nconst buildAgents = (codec?: { readonly adapterTag?: string }): Record<string, string> => {\n const adapterTag = codec?.adapterTag;\n const agents: Record<string, string> = { [SDK_NAME]: VERSION };\n if (adapterTag) agents[adapterTag] = VERSION;\n return agents;\n};\n\n/**\n * Render an agents map as the space-separated `name/version` string Ably expects.\n * @param agents - Map of agent name to version.\n * @returns The space-separated `name/version` agent string.\n */\nconst joinAgents = (agents: Record<string, string>): string =>\n Object.entries(agents)\n .map(([name, version]) => `${name}/${version}`)\n .join(' ');\n\n/**\n * The space-separated `params.agent` string this SDK stamps on channel ATTACH —\n * `ai-transport-js/<version>` plus the codec's adapter tag when present. Pure:\n * unlike {@link registerAgent} it does not mutate the client. Use it to seed a\n * `<ChannelProvider options>` so ably-js's React hooks append their own agent\n * additively (`channelOptionsForReactHooks`) rather than overwriting this SDK's.\n * @param codec - The codec instance whose optional identifier opts into registration.\n * @param codec.adapterTag - The optional Ably-Agent identifier; registered as an agent when present.\n * @returns The channel `params.agent` string.\n */\nexport const channelAgent = (codec?: { readonly adapterTag?: string }): string => joinAgents(buildAgents(codec));\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 an\n * `adapterTag`, also sets `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 whose optional identifier opts into registration.\n * @param codec.adapterTag - The optional Ably-Agent identifier; registered as an agent when present.\n * @returns Channel options containing `params.agent` for `channels.get`.\n */\nexport const registerAgent = (\n client: Ably.Realtime,\n codec?: { readonly adapterTag?: string },\n): { params: { agent: string } } => injectAgents(client, buildAgents(codec));\n","/**\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 * SDK-controlled codec-level `kind` 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 `kind`\n * header so the decoder can dispatch.\n */\nexport const EVENT_AI_INPUT = 'ai-input';\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 waited for the input event(s) the invocation points at —\n * across the bounded history scan and the live subscription — but\n * `inputEventLookupTimeoutMs` lapsed without seeing them.\n */\n InputEventNotFound = 104010,\n\n /**\n * Channel history pagination failed after bounded retry — either the initial\n * `channel.history()` call or a subsequent `page.next()` exhausted its\n * retry budget. The original failure is preserved as `cause`.\n */\n HistoryFetchFailed = 104011,\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 * 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 * 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 * as Ably from 'ably';\n\n/**\n * Extract a human-readable message from an unknown thrown value.\n * @param error - The thrown value.\n * @returns The error's `message` when it is an `Error`, otherwise its string form.\n */\nexport const errorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * Narrow an unknown thrown value to an `Ably.ErrorInfo` for use as a wrapping\n * `cause`, returning `undefined` when it is not one. Pass the result as the\n * fourth argument to the `Ably.ErrorInfo` constructor to preserve the error\n * chain without asserting a type the value may not have.\n * @param error - The thrown value.\n * @returns The value when it is an `Ably.ErrorInfo`, otherwise `undefined`.\n */\nexport const errorCause = (error: unknown): Ably.ErrorInfo | undefined =>\n error instanceof Ably.ErrorInfo ? error : undefined;\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 * Parse a string as JSON, falling back to the raw string when it isn't valid\n * JSON. An empty string yields `undefined`. Used for accumulated stream text\n * whose payload may be JSON or a plain string.\n * @param value - The string to parse.\n * @returns The parsed value, the raw string on parse failure, or undefined if empty.\n */\nexport const 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 * 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 * 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 * Transport header builder.\n *\n * Single source of truth for which transport headers every transport\n * message carries. Used by the agent session (pipe) and by\n * the client session (optimistic message stamping).\n */\n\nimport * as Ably from 'ably';\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_ERROR_CODE,\n HEADER_ERROR_MESSAGE,\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 { ErrorCode } from '../../errors.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 * @param opts.errorCode - Numeric error code stamped as `error-code` on\n * run-end. Set only when the run ended in error and the agent supplied an\n * error to surface; gives codec-agnostic consumers a baseline failure detail.\n * @param opts.errorMessage - Error message stamped as `error-message` on\n * run-end. Paired with `errorCode`; set under the same condition.\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 errorCode?: number;\n errorMessage?: string;\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 if (opts.errorCode !== undefined) h[HEADER_ERROR_CODE] = String(opts.errorCode);\n if (opts.errorMessage !== undefined) h[HEADER_ERROR_MESSAGE] = opts.errorMessage;\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 * Reconstruct the terminal `Ably.ErrorInfo` for a run that ended in error, from\n * its run-end transport headers. Reads the `error-code` / `error-message`\n * headers the agent stamps (see {@link buildLifecycleHeaders}); falls back to a\n * generic code/message when a run ended in error without detail. Single source\n * of truth for the header→ErrorInfo derivation, shared by the client session's\n * `on('error')` emit and the Tree's `RunInfo.error`.\n * @param headers - Transport headers from the inbound run-end message.\n * @returns The reconstructed terminal error.\n */\nexport const buildRunEndError = (headers: Record<string, string>): Ably.ErrorInfo => {\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 // 5-digit codes encode their HTTP status in the leading 3 digits; otherwise 500.\n const statusCode = code >= 10000 && code < 60000 ? Math.floor(code / 100) : 500;\n return new Ably.ErrorInfo(message, code, statusCode);\n};\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 * @param timestamp - Ably server timestamp (epoch ms) of the message, or\n * `undefined` for an optimistic local event. Stamped onto the returned\n * event; drives the Tree's event-log retention clock.\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 timestamp: number | 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 const stamped = timestamp === undefined ? {} : { timestamp };\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 ...stamped,\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] ?? '', ...stamped };\n }\n\n if (name === EVENT_RUN_RESUME) {\n return { type: 'resume', runId, clientId, serial, invocationId: headers[HEADER_INVOCATION_ID] ?? '', ...stamped };\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 const invocationId = headers[HEADER_INVOCATION_ID] ?? '';\n if (reason === 'error') {\n return {\n type: 'end',\n runId,\n clientId,\n serial,\n invocationId,\n reason,\n ...stamped,\n error: buildRunEndError(headers),\n };\n }\n return { type: 'end', runId, clientId, serial, invocationId, reason, ...stamped };\n }\n\n return undefined;\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 * The engine is exposed as a {@link WireApplier} binding one Tree to one\n * decoder. A Tree has exactly one applier (the session constructs it and hands\n * it to every View), so every route a wire message can arrive by — the live\n * subscription, View history pagination, the agent's hydration walks — feeds\n * the same decoder. The decoder's version-guarded stream trackers then make\n * re-delivery across routes (an attach-boundary in-flight stream, a replayed\n * history page) decode to nothing instead of double-folding. The delivery's\n * `version.serial` is also threaded into the Tree, whose per-entry\n * `decodedThrough` high-water-mark drops whole-wire replays that no decoder\n * state can see (stateless discrete re-decodes).\n */\n\nimport type * as Ably from 'ably';\n\nimport { HEADER_RUN_ID } from '../../constants.js';\nimport { getTransportHeaders } from '../../utils.js';\nimport type { 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 * The decode-and-apply engine for one Tree: a single codec decoder bound to a\n * single Tree, shared by every route that feeds the Tree wire messages.\n */\nexport interface WireApplier {\n /**\n * Apply one inbound wire message to the bound 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 the bound decoder and applied with `applyMessage`,\n * skipping wire-only carriers that decode to no events and carry no run-id\n * (the eventual reply run is created later by its run-start).\n *\n * Does NOT emit the tree's `ably-message` event — the caller owns that,\n * because the live loop emits per message while history replay emits in a\n * batch once the whole page is applied. Returns the parsed lifecycle event\n * so a live caller can run its own side-effects (resolving a pending\n * run-start, surfacing an agent error); returns `undefined` for a\n * codec-decoded message or a lifecycle message that carried no run-id.\n * @param rawMsg - The inbound Ably wire message.\n * @returns The parsed run-lifecycle event, or `undefined`.\n */\n apply(rawMsg: Ably.InboundMessage): RunLifecycleEvent | undefined;\n}\n\n/**\n * Classify, decode, and apply one inbound wire message to the tree. See\n * {@link WireApplier.apply} for the contract.\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 */\nconst 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 // Top-level timestamp — the message's create time on every delivery (an\n // append's own receive time lives in `version.timestamp`). The retention\n // clock is sound on this timeline because run-end, a fresh create published\n // after every wire of its run, bounds the node's last activity.\n const timestamp = rawMsg.timestamp;\n\n if (isRunLifecycleName(rawMsg.name)) {\n const event = parseRunLifecycle(rawMsg.name, headers, serial, timestamp);\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, timestamp, rawMsg.version.serial);\n }\n return undefined;\n};\n\n/**\n * Bind a Tree and a decoder into the Tree's single {@link WireApplier}.\n * @param tree - The tree the applier feeds.\n * @param decoder - The codec decoder shared by every route into the tree.\n * @returns The applier.\n */\nexport const createWireApplier = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection>(\n tree: TreeInternal<TInput, TOutput, TProjection>,\n decoder: Decoder<TInput, TOutput>,\n): WireApplier => ({\n apply: (rawMsg: Ably.InboundMessage): RunLifecycleEvent | undefined => applyWireMessage(tree, decoder, rawMsg),\n});\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.loadConversation(); // walk channel history into the session tree\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 * Shared lifecycle plumbing for the client and agent sessions.\n *\n * Both `DefaultClientSession` and `DefaultAgentSession` gate their writes on\n * `connect()` having run, detach their channel best-effort on close, and react\n * to channel continuity loss with the same detection rule and error shape.\n * These helpers own that common machinery so the two sessions cannot drift on\n * the connection guard, the detach-swallow behaviour, or — most importantly —\n * the continuity-loss predicate, which encodes channel protocol semantics\n * (Spec AIT-CT19 / AIT-ST12). Each session keeps its own divergent reaction to\n * continuity loss (the client emits; the agent aborts runs and swaps its Tree).\n */\n\nimport * as Ably from 'ably';\n\nimport { ErrorCode } from '../../errors.js';\nimport type { Logger } from '../../logger.js';\n\n/**\n * Resolve a session's connect guard: return the in-flight/settled connect\n * promise, or reject with `InvalidArgument` when `connect()` has not been\n * called. Callers `await` the result before any write.\n * @param connectPromise - The session's connect promise, or `undefined` when not yet connected.\n * @param method - The method name being guarded, for the error message.\n * @returns The connect promise.\n * @throws {Ably.ErrorInfo} `InvalidArgument` when `connectPromise` is `undefined`.\n */\nexport const requireConnected = async (connectPromise: Promise<void> | undefined, method: string): Promise<void> => {\n if (!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 connectPromise;\n};\n\n/**\n * Detach the session's channel on close, best-effort. `connect()` subscribes\n * (which implicitly attaches), so a detach is only attempted when `connect()`\n * ran. A detach failure (e.g. the channel is already FAILED) must not throw out\n * of `close()`, so it is swallowed and logged at debug.\n * @param channel - The session's channel.\n * @param connectPromise - The session's connect promise; detach is skipped when `undefined`.\n * @param logger - Logger for the swallowed-failure debug line, or `undefined`.\n * @param component - The owning class name, used as the log message prefix.\n */\nexport const bestEffortDetach = async (\n channel: Ably.RealtimeChannel,\n connectPromise: Promise<void> | undefined,\n logger: Logger | undefined,\n component: string,\n): Promise<void> => {\n if (connectPromise === undefined) return;\n try {\n await channel.detach();\n } catch (error) {\n logger?.debug(`${component}.close(); channel detach failed`, { error });\n }\n};\n\n/**\n * Whether a channel state change breaks message continuity:\n * - FAILED, SUSPENDED, DETACHED — no more messages expected (or a gap)\n * - ATTACHED with `resumed: false` (an UPDATE) — messages were lost\n *\n * The initial attach (ATTACHED with no prior attach) is the caller's concern\n * and is not handled here.\n * @param stateChange - The channel state change to classify.\n * @returns True when continuity was lost.\n */\nexport const isContinuityLost = (stateChange: Ably.ChannelStateChange): boolean => {\n const { current, resumed } = stateChange;\n return (\n current === 'failed' || current === 'suspended' || current === 'detached' || (current === 'attached' && !resumed)\n );\n};\n\n/**\n * Build the `ChannelContinuityLost` error for a continuity-breaking state\n * change, attaching the state change's `reason` as `cause`.\n * @param stateChange - The continuity-breaking state change.\n * @param verb - The operation that can no longer proceed, for the\n * `unable to <verb>; ...` message (e.g. \"deliver events\", \"continue\").\n * @returns The continuity-loss error.\n */\nexport const continuityLostError = (stateChange: Ably.ChannelStateChange, verb: string): Ably.ErrorInfo => {\n const { current } = stateChange;\n return new Ably.ErrorInfo(\n `unable to ${verb}; channel continuity lost (${current}${current === 'attached' ? ', resumed: false' : ''})`,\n ErrorCode.ChannelContinuityLost,\n 500,\n stateChange.reason,\n );\n};\n","/**\n * `toCodecEvents` — tag a decoded message's events with their wire direction.\n *\n * A decoded message is already split into inputs and outputs by the decoder\n * (driven by the Ably message name — the authoritative direction signal). This\n * helper folds that split into the ordered {@link CodecEvent} stream the reducer\n * consumes, so the direction is carried explicitly rather than re-inferred from\n * each event's shape. Inputs are tagged before outputs, preserving the wire\n * order within a single message (a message is single-direction, so the relative\n * order of the two groups is immaterial).\n */\n\nimport type { CodecEvent, CodecInputEvent, CodecOutputEvent, DecodedMessage } from './types.js';\n\n/**\n * Tag a decoded message's events with their wire direction.\n * @template TInput - The codec's input union.\n * @template TOutput - The codec's output union.\n * @param decoded - The decoder's input/output split for one inbound message.\n * @returns The events as a direction-tagged {@link CodecEvent} list, inputs first.\n */\nexport const toCodecEvents = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent>(\n decoded: DecodedMessage<TInput, TOutput>,\n): CodecEvent<TInput, TOutput>[] => [\n ...decoded.inputs.map((event): CodecEvent<TInput, TOutput> => ({ direction: 'input', event })),\n ...decoded.outputs.map((event): CodecEvent<TInput, TOutput> => ({ direction: 'output', event })),\n];\n","/**\n * Per-node event log.\n *\n * Each node retains the decoded events it was folded from, grouped by\n * wire-message serial and ordered ascending by serial. The log captures\n * canonical serial order regardless of delivery order, so a node's event\n * sequence can be re-derived in that order even when wires arrive late\n * (cross-publisher reordering) or out of order (history pages applying older\n * messages after newer ones).\n *\n * Within one serial, deliveries are sequenced by `Message.version.serial`\n * (lexicographically ordered per mutation — platform guarantee): each entry\n * records the highest version decoded into it, so a delivery the entry has\n * already incorporated — a whole-wire replay from a second hydration, a\n * remount, or an agent re-walk — is recognised and dropped at the transport.\n *\n * {@link WireLog} encapsulates the entry list and all of its mutation: the\n * caller hands it a wire and is told only how to fold (see {@link WireLogFold}).\n */\n\n/** One wire message in a node's event log: a serial and its decoded events. */\ninterface WireLogEntry<TEvent> {\n /** Ably channel serial of the wire message. */\n serial: string;\n /**\n * The wire's codec-message-id — the reducer routing key the events were\n * folded alongside; undefined when the wire carried none.\n */\n messageId: string | undefined;\n /**\n * The decoded events from this wire message's deliveries, in arrival order.\n * Same-serial deliveries (the create plus each append/update) extend the\n * entry, so the list accumulates across deliveries.\n */\n events: TEvent[];\n /**\n * The highest `Message.version.serial` decoded into this entry. Versions\n * are lexicographically comparable within one serial, so a delivery at or\n * below this value is already incorporated and must not fold again. In\n * practice every delivery carries a version (a never-mutated message's\n * version serial equals its serial); the message serial is used as the floor\n * only as a defensive fallback for the type-optional absent case.\n */\n decodedThrough: string;\n}\n\n/** How a {@link WireLog.record} call tells the caller to fold the wire's events. */\nexport type WireLogFold =\n /**\n * The version guard rejected a re-delivery the log already incorporated — a\n * whole-wire replay, or a newer version of a non-streamed wire (an edited\n * discrete). Nothing was recorded; fold nothing.\n */\n | 'dropped'\n /**\n * The events extend the log tail (in-order delivery) or landed on a swept\n * log; fold them onto the node's existing projection.\n */\n | 'incremental'\n /**\n * An earlier-serial wire arrived late, so incremental folding would corrupt\n * serial order; rebuild the projection from the whole log via {@link replay}.\n */\n | 'refold';\n\n/**\n * A node's event log: one entry per wire-message serial, kept ascending by\n * serial, each accumulating that serial's decoded events in arrival order.\n */\nexport class WireLog<TEvent> {\n private readonly _entries: WireLogEntry<TEvent>[] = [];\n private _swept = false;\n\n /**\n * Whether the retention sweep has dropped this log's decoded payloads. A\n * swept log keeps each entry's replay key (serial + `decodedThrough`) so it\n * still recognises whole-wire replays, but it can no longer be refolded.\n * @returns True once {@link sweep} has run.\n */\n get swept(): boolean {\n return this._swept;\n }\n\n /**\n * Record a wire message's decoded events and report how to fold them.\n *\n * Events for an already-logged serial are guarded by the entry's\n * `decodedThrough` version before being recorded; a new serial is inserted\n * at the position that keeps the log ascending by serial (Ably serials order\n * lexicographically). The version guard fires only for deliveries carrying\n * an explicit `version.serial`: in-contract mutations always do, while a\n * version-less delivery records unguarded (and never advances\n * `decodedThrough`), matching the decoder's convention.\n *\n * On a swept log the payload is not retained (only the replay key is), so\n * the fold is never `refold` — a genuinely-new wire there is outside the\n * reorder window and folds incrementally in arrival order.\n * @param serial - The Ably channel serial of the wire message.\n * @param messageId - The wire's codec-message-id, or undefined.\n * @param events - The decoded events to record, in arrival order.\n * @param version - The delivery's `Message.version.serial`, or undefined\n * when the delivery carried none (guard disabled for this delivery).\n * @param streamed - Whether the delivery is part of a streamed wire; a\n * guarded newer delivery for a non-streamed wire is an edited discrete and\n * is dropped.\n * @returns How the caller should fold the events.\n */\n record(\n serial: string,\n messageId: string | undefined,\n events: TEvent[],\n version: string | undefined,\n streamed: boolean,\n ): WireLogFold {\n // A swept log retains replay keys but not payloads: record an empty event\n // list so the key advances while nothing is stored. The caller folds the\n // events it already holds.\n const index = this._recordEntry(serial, messageId, this._swept ? [] : events, version, streamed);\n if (index === undefined) return 'dropped';\n if (this._swept) return 'incremental';\n return index === this._entries.length - 1 ? 'incremental' : 'refold';\n }\n\n /**\n * Replay every recorded event in canonical order — wire messages ascending\n * by serial, events within a wire in arrival order — each with its wire's\n * routing metadata, for a refold.\n * @param visit - Called once per event, in canonical order.\n */\n replay(visit: (event: TEvent, serial: string, messageId: string | undefined) => void): void {\n for (const entry of this._entries) {\n for (const event of entry.events) visit(event, entry.serial, entry.messageId);\n }\n }\n\n /**\n * Drop the decoded payloads (the unbounded cost) but keep each entry's\n * replay key, so a post-sweep whole-wire replay is still recognised and\n * dropped rather than re-folded. The log becomes {@link swept}; a refold can\n * no longer rebuild the dropped events, which `swept` reflects.\n */\n sweep(): void {\n this._swept = true;\n for (const entry of this._entries) entry.events.length = 0;\n }\n\n /**\n * Insert or extend the entry for `serial`, guarding replays by version.\n * @param serial - The Ably channel serial of the wire message.\n * @param messageId - The wire's codec-message-id, or undefined.\n * @param events - The decoded events to store (empty on a swept log).\n * @param version - The delivery's `Message.version.serial`, or undefined.\n * @param streamed - Whether the delivery is part of a streamed wire.\n * @returns The index of the entry the events landed in, or `undefined` when\n * the version guard dropped the delivery.\n */\n private _recordEntry(\n serial: string,\n messageId: string | undefined,\n events: TEvent[],\n version: string | undefined,\n streamed: boolean,\n ): number | undefined {\n // Scan from the tail: live delivery appends at (or extends) the end, so the\n // match is almost always within the last entry or two.\n for (let i = this._entries.length - 1; i >= 0; i--) {\n const entry = this._entries[i];\n if (!entry) break; // unreachable\n if (entry.serial === serial) {\n // Version guard: drop a re-delivery the entry already incorporated — a\n // replay (version at or below the high-water-mark) or an edit to a\n // discrete (a newer version of a non-streamed wire, not propagated).\n if (version !== undefined && (version <= entry.decodedThrough || !streamed)) {\n return undefined;\n }\n entry.events.push(...events);\n if (version !== undefined) entry.decodedThrough = version;\n return i;\n }\n if (entry.serial < serial) {\n this._entries.splice(i + 1, 0, { serial, messageId, events: [...events], decodedThrough: version ?? serial });\n return i + 1;\n }\n }\n // Lower than every logged serial (or the log is empty): insert at the head.\n this._entries.unshift({ serial, messageId, events: [...events], decodedThrough: version ?? serial });\n return 0;\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_EVENT_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 HEADER_STREAM,\n} from '../../constants.js';\nimport { EventEmitter } from '../../event-emitter.js';\nimport type { Logger } from '../../logger.js';\nimport { getTransportHeaders } from '../../utils.js';\nimport { toCodecEvents } from '../codec/codec-event.js';\nimport type { CodecEvent, CodecInputEvent, CodecOutputEvent, Reducer } from '../codec/types.js';\nimport type { ConversationNode, InputNode, OutputEvent, RunLifecycleEvent, RunNode, Tree } from './types.js';\nimport { WireLog } from './wire-log.js';\n\n// ---------------------------------------------------------------------------\n// Internal node type\n// ---------------------------------------------------------------------------\n\n/**\n * How long (in ms, on the Ably message-timestamp timeline) a structurally\n * complete run's event log is retained after the node's last observed\n * activity. Bounds cross-publisher live delivery reorder: a wire can be\n * delivered after a higher-serial wire by at most this window. Conservative\n * placeholder pending confirmation of the actual cross-region bound.\n */\nexport const REORDER_WINDOW_MS = 120_000;\n\ninterface InternalNode<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection> {\n node: ConversationNode<TProjection>;\n /** Insertion sequence — tiebreaker for nodes with no sort serial (optimistic). */\n insertSeq: number;\n /**\n * The node's event log: every serial-bearing wire applied to this node, in\n * canonical serial order. Owns its own record/refold/replay-guard/sweep\n * mutation (see {@link WireLog}). Optimistic (serial-less) applies are not\n * recorded.\n */\n log: WireLog<CodecEvent<TInput, TOutput>>;\n /**\n * Max Ably message timestamp (epoch ms) of everything applied to this node,\n * including its run lifecycle events; 0 until a timestamped apply. The\n * retention sweep measures {@link REORDER_WINDOW_MS} from here.\n */\n lastActivityTs: number;\n /**\n * Whether this run's `ai-run-start` has been observed (run nodes only —\n * always false for input nodes). The structural half of log retention:\n * run-start is the run's serial floor, so once it is observed no older\n * history page can deliver further wires for this node.\n */\n runStartSeen: boolean;\n /** Whether this node is already queued for sweeping (guards double-enqueue). */\n sweepQueued: boolean;\n /**\n * Whether an optimistic (serial-less) seed has been folded into the\n * projection but not into the log. The first serial-bearing wire (the echo)\n * refolds the node from the log alone, discarding the seed, then clears\n * this — so a codec needs no seed-replacement logic of its own.\n */\n optimistic: boolean;\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 * @param timestamp - Ably server timestamp (epoch ms) of the message —\n * top-level `Message.timestamp`, the message's create time on every\n * delivery (an append's own receive time lives in `version.timestamp`) —\n * or undefined for optimistic inserts. Advances the Tree's event-log\n * retention clock and the owning node's last-activity time.\n * @param version - The delivery's `Message.version.serial`, or undefined\n * when the delivery carried none (optimistic inserts, never-mutated\n * deliveries from sources that omit it). Guards the node's event log\n * against whole-wire replays: a delivery at or below the version already\n * decoded into its log entry is dropped.\n */\n applyMessage(\n events: { inputs: TInput[]; outputs: TOutput[] },\n headers: Record<string, string>,\n serial?: string,\n timestamp?: number,\n version?: 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.state to 'active', promotes startSerial, and backfills\n * structural metadata (parent / forkOf / regenerates / invocationId).\n * - `suspend`: sets RunNode.state 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 (state 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.state 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<CodecEvent<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<TInput, TOutput, 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<TInput, TOutput, 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<TInput, TOutput, TProjection>[]>();\n private _siblingCacheVersion = -1;\n\n /**\n * Index from `event-id` header to the raw Ably message that carried it.\n * Populated incrementally as messages arrive via {@link emitAblyMessage};\n * reads back the raw message for the agent's input-event lookup\n * ({@link findAblyMessageByEventId}). Bounded by the Tree's lifetime — cleared\n * when the Tree is replaced on continuity loss / session close.\n */\n private readonly _eventIdIndex = new Map<string, Ably.InboundMessage>();\n\n /**\n * Event-log retention logical clock: the max Ably message timestamp (epoch\n * ms) observed across every apply, 0 until the first timestamped one. Only\n * ever advances — older-page history application carries smaller timestamps\n * and leaves it (and therefore the sweep) untouched.\n */\n private _clock = 0;\n\n /**\n * Keys of structurally complete run nodes (run-start and run-end both\n * observed) whose event logs await the retention window, in completion\n * order. Drained from the front whenever {@link _clock} advances; sweeping\n * only at clock advances keeps a history page's batch atomic — applying an\n * older page can never advance the clock, so a node cannot be swept between\n * its run-start and the rest of its wires in the same page.\n */\n private readonly _sweepQueue: string[] = [];\n\n constructor(codec: Reducer<CodecEvent<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(\n a: InternalNode<TInput, TOutput, TProjection>,\n b: InternalNode<TInput, TOutput, TProjection>,\n ): 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<TInput, TOutput, 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<TInput, TOutput, 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(\n key: string,\n entry: InternalNode<TInput, TOutput, TProjection>,\n parentCodecMessageId: string | undefined,\n ): 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<TInput, TOutput, 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<TInput, TOutput, TProjection>,\n events: CodecEvent<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 * Record a serial-bearing wire in the node's event log and fold it. Events\n * extending the log tail (the common case — in-order live delivery) fold\n * incrementally onto the existing projection, identical to a bare\n * {@link _foldInto}. Events that land earlier in the log (an earlier-serial\n * wire delivered late — cross-publisher reorder, or a history page applying\n * an older message after a newer one) cannot be folded incrementally without\n * corrupting serial order, so the node is refolded from the whole log via\n * {@link _refold}.\n *\n * Optimistic (serial-less) applies and empty event batches are not logged;\n * an optimistic seed folds into the projection but never into the log, and\n * marks the node `optimistic`. The first serial-bearing wire (the echo of\n * the optimistic input, which re-delivers the seeded content) refolds the\n * node from the log alone — rebuilding the projection without the seed\n * rather than folding the echo on top of it. The codec therefore never sees\n * the seed and its echo in one projection, and needs no seed-replacement\n * logic. The seed must be a faithful preview of the echo, since the echo's\n * content is what survives.\n *\n * Whole-wire replays are dropped at the log: each entry records the highest\n * `Message.version.serial` decoded into it (`decodedThrough`), so a\n * version-bearing delivery the entry has already incorporated — a second\n * hydration over a populated Tree, a remounted View's re-fetch, an agent\n * re-walk — records nothing and folds nothing. A newer version of a\n * discrete wire (an edited discrete) is likewise dropped; propagating edits\n * into projections is deliberately out of scope.\n * @param entry - The internal node whose log and projection are updated.\n * @param events - The decoded events to fold, in wire order.\n * @param serial - Ably channel serial; undefined for an optimistic insert.\n * @param messageId - The reducer routing key (codec-message-id), or undefined.\n * @param version - The delivery's `Message.version.serial`, or undefined.\n * @param streamed - Whether the delivery is part of a streamed wire.\n */\n private _recordAndFold(\n entry: InternalNode<TInput, TOutput, TProjection>,\n events: CodecEvent<TInput, TOutput>[],\n serial: string | undefined,\n messageId: string | undefined,\n version: string | undefined,\n streamed: boolean,\n ): void {\n // A serial-less optimistic seed (or an empty batch) is not logged. Fold it\n // in; a non-empty seed marks the node so its echo refolds the seed away.\n if (serial === undefined || events.length === 0) {\n if (serial === undefined && events.length > 0) entry.optimistic = true;\n this._foldInto(entry, events, serial, messageId);\n return;\n }\n\n const fold = entry.log.record(serial, messageId, events, version, streamed);\n if (fold === 'dropped') {\n // The version guard rejected a re-delivery the log already incorporated —\n // a whole-wire replay (second hydration, remount, agent re-walk, or a\n // `loadOlder()` re-applying a swept run's history) or an edit to a\n // discrete. Nothing to fold.\n this._logger.debug('Tree._recordAndFold(); version guard dropped re-delivered wire', {\n key: nodeKey(entry.node),\n serial,\n version,\n swept: entry.log.swept,\n });\n return;\n }\n if (entry.optimistic && !entry.log.swept) {\n // First serial-bearing wire (the echo) on a node that carries an\n // optimistic seed. The seed is in the projection but not the log, so\n // refold from the log alone — the echo re-delivers the seeded content —\n // rebuilding the projection without the seed instead of folding the echo\n // on top of it.\n entry.optimistic = false;\n this._refold(entry);\n return;\n }\n if (fold === 'refold') {\n this._refold(entry);\n return;\n }\n // 'incremental'. On a swept log this is a genuinely-new wire outside the\n // reorder window (it should not occur) folding in arrival order — the log\n // could not refold it.\n if (entry.log.swept) {\n this._logger.warn('Tree._recordAndFold(); late wire after log retention window; folding in arrival order', {\n key: nodeKey(entry.node),\n serial,\n });\n }\n this._foldInto(entry, events, serial, messageId);\n }\n\n /**\n * Rebuild a node's projection from its event log in canonical serial order:\n * a fresh {@link Reducer.init} folded through every logged event, each with\n * its own wire's serial and messageId. Used when a late, earlier-serial wire\n * makes incremental folding unsound. Reducer purity (a fold is a function of\n * its inputs alone) is what makes the rebuild faithful; the per-fold\n * try/catch mirrors {@link _foldInto} so one throwing event can't abort the\n * rebuild.\n *\n * Rebuilds the projection only; the surrounding apply emits its usual\n * `output` event carrying just the triggering wire's events. Consumers read\n * the rebuilt state from `node.projection` (the View recomputes its message\n * list from it), so on the refold path the event's `events` payload is not a\n * delta of the full projection change.\n * @param entry - The internal node whose projection is rebuilt in place.\n */\n private _refold(entry: InternalNode<TInput, TOutput, TProjection>): void {\n let projection = this._codec.init();\n entry.log.replay((event, serial, messageId) => {\n try {\n projection = this._codec.fold(projection, event, { serial, messageId });\n } catch (error) {\n this._logger.error('Tree._refold(); fold threw', { key: nodeKey(entry.node), messageId, err: error });\n }\n });\n entry.node.projection = projection;\n }\n\n // -------------------------------------------------------------------------\n // Event-log retention\n // -------------------------------------------------------------------------\n\n /**\n * Record activity on a node and advance the retention clock. Updates the\n * node's `lastActivityTs` and the Tree-wide `_clock` to the given timestamp\n * when it is newer; a clock advance drains the sweep queue. `undefined`\n * (an optimistic local apply) advances nothing.\n * @param entry - The node the activity belongs to.\n * @param timestamp - Ably message timestamp (epoch ms), or undefined.\n */\n private _recordActivity(entry: InternalNode<TInput, TOutput, TProjection>, timestamp: number | undefined): void {\n if (timestamp === undefined) return;\n if (timestamp > entry.lastActivityTs) entry.lastActivityTs = timestamp;\n if (timestamp > this._clock) {\n this._clock = timestamp;\n this._drainSweepQueue();\n }\n }\n\n /**\n * Queue a run node's event log for retention sweeping once the node is\n * structurally complete: its run-start (serial floor — no older history page\n * can add to it) and its run-end (no further agent output) have both been\n * observed. The actual drop happens in {@link _drainSweepQueue} once the\n * reorder window has also lapsed. No-op for input nodes (never swept — no\n * floor marker, and their logs are bounded by one user message), for nodes\n * already queued or swept, and while either marker is missing.\n * @param entry - The node to consider for sweeping.\n */\n private _maybeQueueSweep(entry: InternalNode<TInput, TOutput, TProjection>): void {\n const node = entry.node;\n if (node.kind !== 'run') return;\n if (entry.log.swept || entry.sweepQueued) return;\n if (!entry.runStartSeen) return;\n if (node.state.status === 'active' || node.state.status === 'suspended') return;\n entry.sweepQueued = true;\n this._sweepQueue.push(node.runId);\n }\n\n /**\n * Drop the event logs of queued nodes whose retention window has lapsed:\n * `lastActivityTs + REORDER_WINDOW_MS < _clock`. Drains from the front and\n * stops at the first node still inside the window — completion order is\n * time-ordered for live traffic, so this is amortised O(1) per apply, and\n * stopping early only ever over-retains (memory, never correctness). Called\n * only when the clock advances, so applying an older history page (smaller\n * timestamps) can never sweep mid-batch. Deleted nodes are skipped.\n */\n private _drainSweepQueue(): void {\n while (this._sweepQueue.length > 0) {\n const key = this._sweepQueue[0];\n const entry = key === undefined ? undefined : this._nodeIndex.get(key);\n if (!entry || entry.log.swept) {\n this._sweepQueue.shift();\n continue;\n }\n if (entry.lastActivityTs + REORDER_WINDOW_MS >= this._clock) return;\n this._sweepQueue.shift();\n entry.sweepQueued = false;\n // Drop the decoded payloads (the unbounded cost) but keep each entry's\n // replay key, so a post-sweep whole-wire replay is still recognised and\n // dropped rather than re-folded (a refold can no longer rebuild them).\n entry.log.sweep();\n this._logger.debug('Tree._drainSweepQueue(); dropped event-log payloads, kept replay keys', {\n key,\n lastActivityTs: entry.lastActivityTs,\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<TInput, TOutput, 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<TInput, TOutput, 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 timestamp?: number,\n version?: 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: CodecEvent<TInput, TOutput>[] = toCodecEvents(events);\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, timestamp, version, all);\n } else if (wireRunId !== undefined) {\n this._applyRunMessage(wireRunId, events, headers, serial, timestamp, version);\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 timestamp - Ably server timestamp (epoch ms); undefined for an optimistic insert.\n * @param version - The delivery's `Message.version.serial`, or undefined.\n * @param all - The direction-tagged input events to fold, in wire order.\n */\n private _applyInputMessage(\n codecMessageId: string,\n headers: Record<string, string>,\n serial: string | undefined,\n timestamp: number | undefined,\n version: string | undefined,\n all: CodecEvent<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._recordActivity(entry, timestamp);\n\n // Log the wire and fold it — incrementally onto the tail in the common\n // case, or by refolding the node if this wire arrived out of serial order.\n this._recordAndFold(entry, all, serial, codecMessageId, version, headers[HEADER_STREAM] === 'true');\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 * @param timestamp - Ably server timestamp (epoch ms); undefined for an optimistic insert.\n * @param version - The delivery's `Message.version.serial`, or undefined.\n */\n private _applyRunMessage(\n wireRunId: string,\n events: { inputs: TInput[]; outputs: TOutput[] },\n headers: Record<string, string>,\n serial: string | undefined,\n timestamp: number | undefined,\n version: 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: CodecEvent<TInput, TOutput>[] = toCodecEvents(events);\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._recordActivity(run, timestamp);\n\n // Log the wire and fold it — incrementally onto the tail in the common\n // case, or by refolding the node if this wire arrived out of serial order.\n // `run` may be a reconciled optimistic node: record on whichever entry\n // owns the fold.\n this._recordAndFold(run, all, serial, codecMessageId, version, headers[HEADER_STREAM] === 'true');\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 // Activate only a suspended run. A run-start can be observed AFTER the\n // run's terminal event (history pages replay newest-first, so an older\n // page delivers the start last) — like a stray resume, it must never\n // resurrect a run that has ended.\n if (node.state.status === 'suspended') {\n node.state = { 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 // The run's serial floor is now observed: no older history page can\n // deliver further wires for this node. With a terminal status this\n // makes the node structurally complete — eligible for log retention\n // sweeping once the reorder window lapses.\n existing.runStartSeen = true;\n this._recordActivity(existing, event.timestamp);\n this._maybeQueueSweep(existing);\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 this._recordActivity(run, event.timestamp);\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.state = { status: 'suspended' };\n run.node.endSerial = event.serial;\n this._recordActivity(run, event.timestamp);\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.state.status === 'suspended') {\n run.node.state = { status: 'active' };\n this._recordActivity(run, event.timestamp);\n }\n }\n\n /**\n * Apply a run-end lifecycle event: record the terminal reason (and, for an\n * error end, the error) as the node's state, plus the serial it ended at.\n * State/endSerial are content, not structure, so this never mutates\n * `_structuralVersion`; the caller owns the emits.\n *\n * A run-end for an unknown runId is a no-op: nothing else is known about the\n * run yet, so there is no node to mark. When that happens during history\n * replay (a page boundary falling just before the run-end, so the run's\n * other wires arrive in later pages), the run is never marked terminal and\n * its event log is retained for the Tree's lifetime — over-retention, never\n * corruption.\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.state = event.reason === 'error' ? { status: 'error', error: event.error } : { status: event.reason };\n run.node.endSerial = event.serial;\n this._recordActivity(run, event.timestamp);\n this._maybeQueueSweep(run);\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<TInput, TOutput, 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 // Created from a content wire — the run's ai-run-start has not been\n // observed (it may still be in an unloaded older history page).\n runStartSeen: false,\n });\n }\n\n /**\n * Wrap a freshly-built conversation node in its internal envelope — sort\n * sequence, event log, and retention/promotion state. The single home for\n * those per-node fields, so a new field is added in one place rather than at\n * every node-construction site.\n * @param node - The conversation node to wrap.\n * @param runStartSeen - Whether the run's ai-run-start has been observed\n * (run nodes only; always false for input nodes).\n * @returns A newly-allocated internal node ready for insertion.\n */\n private _wrapNode(\n node: ConversationNode<TProjection>,\n runStartSeen = false,\n ): InternalNode<TInput, TOutput, TProjection> {\n return {\n node,\n insertSeq: this._seqCounter++,\n log: new WireLog<CodecEvent<TInput, TOutput>>(),\n lastActivityTs: 0,\n runStartSeen,\n sweepQueued: false,\n optimistic: false,\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 * @param params.runStartSeen - Whether the run's ai-run-start has been observed (true only for lifecycle-created runs).\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 runStartSeen: boolean;\n }): InternalNode<TInput, TOutput, 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 state: { status: 'active' },\n projection: this._codec.init(),\n startSerial: params.startSerial,\n endSerial: undefined,\n };\n\n return this._wrapNode(node, params.runStartSeen);\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<TInput, TOutput, 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 this._wrapNode(node);\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(\n event: RunLifecycleEvent & { type: 'start' },\n ): InternalNode<TInput, TOutput, 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 // Created from the run-start itself — the serial floor is observed.\n runStartSeen: true,\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. Also indexes the\n * Ably message by `event-id` header (if present) for\n * {@link findAblyMessageByEventId} lookups.\n * @param msg - The raw Ably message to emit.\n */\n emitAblyMessage(msg: Ably.InboundMessage): void {\n this._logger.trace('DefaultTree.emitAblyMessage();');\n const headers = getTransportHeaders(msg);\n const eventId = headers[HEADER_EVENT_ID];\n if (eventId !== undefined && !this._eventIdIndex.has(eventId)) {\n this._eventIdIndex.set(eventId, msg);\n }\n this._emitter.emit('ably-message', msg);\n }\n\n findAblyMessageByEventId(eventId: string): Ably.InboundMessage | undefined {\n return this._eventIdIndex.get(eventId);\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<CodecEvent<TInput, TOutput>, TProjection>,\n logger: Logger,\n): DefaultTree<TInput, TOutput, TProjection> => new DefaultTree<TInput, TOutput, TProjection>(codec, logger);\n","/**\n * loadHistoryPages — shared low-level history pagination primitive.\n *\n * Consumed by both client (via `load-history.ts`, which layers a complete-\n * domain-message counter on top) and agent (directly, for input-event lookup\n * and conversation hydration). Returns raw Ably messages; does NOT decode.\n *\n * Behaviour:\n * - Attaches the channel (idempotent) then pages via `channel.history()`,\n * using `untilAttach: true` for gapless continuity with any live subscription.\n * - Exposes the underlying pagination as a cursor with `hasNext()` (cheap,\n * no network) and `next()` (one Ably page per call, newest-first within\n * the page).\n * - Per-page failures are retried with bounded exponential backoff; on\n * exhaustion throws `Ably.ErrorInfo` with code `HistoryFetchFailed`.\n * - `signal.aborted` is checked between pages; rejects with\n * `Ably.ErrorInfo` (InvalidArgument) when aborted.\n *\n * Spec: AIT-CT11 / AIT-ST hydration.\n */\n\nimport * as Ably from 'ably';\n\nimport { ErrorCode } from '../../errors.js';\nimport type { Logger } from '../../logger.js';\nimport { errorCause, errorMessage } from '../../utils.js';\n\n/** Options for {@link loadHistoryPages}. */\nexport interface LoadHistoryPagesOptions {\n /** Wire-message limit per Ably page. */\n pageLimit: number;\n /** Set `untilAttach: true` on the underlying history query for gapless continuity with live subscriptions. Default: true. */\n untilAttach?: boolean;\n /** AbortSignal checked between pages. Rejects with InvalidArgument when aborted. */\n signal?: AbortSignal;\n /** Max retries per `page.next()` / initial `history()` failure. Default: 3. */\n maxRetries?: number;\n /** Initial retry backoff in ms (doubled per attempt). Default: 100. */\n retryBackoffMs?: number;\n /** Logger for diagnostic output. */\n logger?: Logger;\n}\n\n/**\n * Cursor over the channel's history pages.\n *\n * `hasNext()` is cheap (cursor-only, no network); `next()` issues one Ably\n * page fetch (with retry/backoff) and returns its messages. Once `next()`\n * returns `undefined` the cursor is exhausted.\n */\nexport interface HistoryPagesCursor {\n /** True when another Ably page is available (cheap to check; no network). */\n hasNext(): boolean;\n /**\n * Fetch the next Ably page's messages (newest-first within the page).\n * Returns `undefined` when no more pages are available or the abort\n * signal has fired.\n */\n next(): Promise<readonly Ably.InboundMessage[] | undefined>;\n}\n\n/**\n * Sleep for `ms` milliseconds, honouring an AbortSignal.\n * @param ms - Milliseconds to wait.\n * @param signal - Optional abort signal; rejects when fired.\n */\n// eslint-disable-next-line @typescript-eslint/promise-function-async -- the function body is the Promise constructor; async would wrap it in an extra Promise\nconst sleep = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Ably.ErrorInfo('unable to wait; signal aborted', ErrorCode.InvalidArgument, 400));\n return;\n }\n const timer: ReturnType<typeof setTimeout> | number = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n // Node returns an unref-able Timeout; browsers return a number. Unref so\n // a retry backoff cannot keep a Node process alive by itself.\n if (typeof timer === 'object') timer.unref();\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(new Ably.ErrorInfo('unable to wait; signal aborted', ErrorCode.InvalidArgument, 400));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n\n/**\n * Invoke `fetchPage`, retrying on failure with exponential backoff. Throws\n * the last failure wrapped as `HistoryFetchFailed` once retries are\n * exhausted.\n * @param fetchPage - The page fetch to retry (initial `channel.history()` call or a `page.next()`).\n * @param maxRetries - Maximum number of attempts after the initial call.\n * @param initialBackoffMs - Starting backoff delay (doubled per attempt).\n * @param signal - Optional abort signal; cancels remaining retries.\n * @param logger - Optional logger.\n * @returns The fetched page, or `undefined` when pagination is exhausted.\n */\nconst fetchPageWithRetry = async (\n fetchPage: () => Promise<Ably.PaginatedResult<Ably.InboundMessage> | undefined>,\n maxRetries: number,\n initialBackoffMs: number,\n signal: AbortSignal | undefined,\n logger: Logger | undefined,\n): Promise<Ably.PaginatedResult<Ably.InboundMessage> | undefined> => {\n let lastError: unknown;\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n if (signal?.aborted) {\n throw new Ably.ErrorInfo(\n 'unable to fetch history page; signal aborted',\n ErrorCode.InvalidArgument,\n 400,\n errorCause(lastError),\n );\n }\n try {\n return await fetchPage();\n } catch (error) {\n lastError = error;\n if (attempt === maxRetries) break;\n const backoff = initialBackoffMs * 2 ** attempt;\n logger?.debug('loadHistoryPages.fetchPageWithRetry(); page fetch failed, retrying', {\n attempt: attempt + 1,\n maxRetries,\n backoff,\n });\n await sleep(backoff, signal);\n }\n }\n throw new Ably.ErrorInfo(\n `unable to fetch history page; ${errorMessage(lastError)}`,\n ErrorCode.HistoryFetchFailed,\n 500,\n errorCause(lastError),\n );\n};\n\n/**\n * Page through channel history, returning a cursor over Ably pages.\n *\n * Newest-first within each yielded page (matching Ably's native ordering).\n * Caller drives the cursor — calling `next()` until it returns `undefined`\n * or stopping early when a domain-specific stop condition is met\n * (e.g. complete-message counter satisfied, target codec-message-id found,\n * parent chain walk reaches root).\n *\n * The initial Ably history call is awaited eagerly so the returned cursor\n * already knows whether there are pages available (via `hasNext()`).\n * @param channel - The Ably channel to read history from.\n * @param options - Pagination options.\n * @returns A cursor with `hasNext()` (cheap, cursor-only) and `next()` (fetches one page with retry).\n * @throws {Ably.ErrorInfo} `HistoryFetchFailed` on exhausted retry of the initial fetch, or `InvalidArgument` on signal abort.\n */\nexport const loadHistoryPages = async (\n channel: Ably.RealtimeChannel,\n options: LoadHistoryPagesOptions,\n): Promise<HistoryPagesCursor> => {\n const { pageLimit, untilAttach = true, signal, maxRetries = 3, retryBackoffMs = 100, logger } = options;\n\n if (signal?.aborted) {\n throw new Ably.ErrorInfo('unable to load history; signal aborted', ErrorCode.InvalidArgument, 400);\n }\n\n await channel.attach();\n\n const historyParams: Ably.RealtimeHistoryParams = { limit: pageLimit, untilAttach };\n\n let currentPage: Ably.PaginatedResult<Ably.InboundMessage> | undefined = await fetchPageWithRetry(\n // eslint-disable-next-line @typescript-eslint/promise-function-async -- channel.history returns a real Promise\n () => channel.history(historyParams),\n maxRetries,\n retryBackoffMs,\n signal,\n logger,\n );\n let firstYielded = false;\n\n // Compute whether the cursor has another page available. Cheap — no\n // network. Reflects the latest fetched page's `hasNext()` plus the signal\n // check.\n const hasNext = (): boolean => {\n if (currentPage === undefined) return false;\n if (signal?.aborted) return false;\n if (!firstYielded) return true;\n return currentPage.hasNext();\n };\n\n const next = async (): Promise<readonly Ably.InboundMessage[] | undefined> => {\n if (currentPage === undefined) return undefined;\n if (signal?.aborted) {\n throw new Ably.ErrorInfo('unable to load history; signal aborted', ErrorCode.InvalidArgument, 400);\n }\n\n if (!firstYielded) {\n firstYielded = true;\n return currentPage.items;\n }\n\n if (!currentPage.hasNext()) {\n currentPage = undefined;\n return undefined;\n }\n\n const nextPage: Ably.PaginatedResult<Ably.InboundMessage> | undefined = await fetchPageWithRetry(\n async () => (await currentPage?.next()) ?? undefined,\n maxRetries,\n retryBackoffMs,\n signal,\n logger,\n );\n if (!nextPage) {\n currentPage = undefined;\n return undefined;\n }\n currentPage = nextPage;\n return nextPage.items;\n };\n\n return { hasNext, next };\n};\n","/**\n * loadHistory — load conversation history from an Ably channel and return\n * the raw Ably messages as a paginated HistoryPage result.\n *\n * This does NOT decode: it pages back through Ably history via the shared\n * {@link loadHistoryPages} primitive until `limit` complete messages are\n * present, then hands the raw Ably messages (oldest-first) to the caller.\n * The View re-decodes them into the Tree itself, so load-history only needs\n * a cheap, header-based completion counter to decide when to stop paging.\n *\n * The `limit` option controls the number of complete **messages** per page,\n * not the number of Ably 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 page boundary are\n * handled by the counter requiring both a start and a terminal signal\n * 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 * Spec: AIT-CT11, AIT-CT11b.\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 HistoryPagesCursor, loadHistoryPages } from './load-history-pages.js';\nimport type { HistoryPage, LoadHistoryOptions } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Shared state across pages within one history traversal\n// ---------------------------------------------------------------------------\n\ninterface HistoryState {\n /** Cursor over the shared `loadHistoryPages` primitive; each `next()` returns one Ably page's messages (newest-first within the page). */\n cursor: HistoryPagesCursor;\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 /**\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 Ably 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 Ably message\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 Ably 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// Pull pages from the shared iterator until we have enough completions\n// ---------------------------------------------------------------------------\n\n/**\n * Pull chunks from the shared {@link loadHistoryPages} iterator until enough\n * completed messages have been collected (target = already-returned +\n * `limit`) or the iterator is exhausted.\n *\n * Uses {@link countNewCompletions} — a cheap O(new messages) header scan —\n * to decide when to stop, rather than running the decoder per page.\n * @param state - The shared history traversal state.\n * @param limit - Target number of completed messages beyond what has already been returned.\n */\nconst fetchUntilLimit = async (state: HistoryState, limit: number): Promise<void> => {\n const target = state.returnedCount + limit;\n while (state.completedCodecMessageIds.size < target && state.cursor.hasNext()) {\n state.logger.debug('loadHistory.fetchUntilLimit(); pulling next page', {\n collected: state.rawMessages.length,\n completed: state.completedCodecMessageIds.size,\n });\n const chunk = await state.cursor.next();\n if (!chunk) break;\n state.rawMessages.push(...chunk);\n countNewCompletions(state, chunk);\n }\n};\n\n// ---------------------------------------------------------------------------\n// Build HistoryPage result from current state\n// ---------------------------------------------------------------------------\n\n/**\n * Build a HistoryPage of raw Ably 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 messages 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 moreFromCursor = state.cursor.hasNext();\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 || moreFromCursor,\n next: async () => {\n if (moreCompleted) {\n return buildResult(state, limit);\n }\n if (!moreFromCursor) return;\n await fetchUntilLimit(state, 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 Ably messages.\n *\n * Drives the shared {@link loadHistoryPages} primitive with\n * `untilAttach: true` (gapless continuity with the live subscription) and a\n * Ably message page limit that overprovisions for the many-Ably-messages-per-domain-message\n * ratio. Each `HistoryPage` returned covers up to `limit` complete domain\n * messages; subsequent pages drain over-collected messages from the buffer\n * before pulling more from the iterator.\n *\n * The `limit` option controls the number of complete messages returned per\n * page, not the number of Ably 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\n logger.trace('loadHistory();', { limit });\n\n // Request more Ably messages per page than the domain-message limit to\n // account for the many-to-one ratio (multiple Ably messages per domain message).\n // The wire pagination is internal to the iterator; the consumer-visible\n // pagination is by complete domain messages.\n const wireLimit = limit * 10;\n\n const cursor = await loadHistoryPages(channel, {\n pageLimit: wireLimit,\n untilAttach: true,\n logger,\n });\n\n const state: HistoryState = {\n cursor,\n rawMessages: [],\n returnedCount: 0,\n returnedRawCount: 0,\n startedCodecMessageIds: new Set<string>(),\n terminatedCodecMessageIds: new Set<string>(),\n completedCodecMessageIds: new Set<string>(),\n logger,\n };\n\n await fetchUntilLimit(state, 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 type { WireApplier } 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. */\ninterface 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 and mint regenerate inputs. */\n codec: Codec<TInput, TOutput, TProjection, TMessage>;\n /**\n * The Tree's single decode-and-apply engine, owned by the session and\n * shared with the live decode loop. History replay feeds pages through it\n * so the one decoder instance sees every route into the Tree.\n */\n applier: WireApplier;\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 * One alternative inside a {@link MessageBranchPoint}. The representative is the\n * member's own head message for fork-of and whole-reply regen groups, but the\n * *regenerate target* (a non-head message) for a non-head regen group - so it is\n * tracked explicitly rather than re-derived from the node's head.\n */\ninterface BranchMember {\n /**\n * The member node's `nodeKey` (tree.ts): a runId for a reply/regenerator run,\n * a codecMessageId for an input node. Matched by `_resolveSelectedIndex`.\n */\n memberNodeKey: string;\n /** The codec-message-id rendered in this member's branch-arrow slot. */\n representativeCodecMessageId: string;\n}\n\n/**\n * A resolved branch point: the group `kind` plus the member alternatives.\n *\n * Terms: \"regenerate target\" = the message being replaced; \"regenerator run\" =\n * the run that replaces it; \"non-head message\" = any message after a run's\n * first (index > 0, includes the tail).\n *\n * The three kinds, by anchor:\n * - `fork-of` — edit-style branch anchored at the user input node; members are\n * the alternate prompts (input-node sibling group).\n * - `regen` — whole-reply regenerate branch anchored at the assistant slot;\n * members are the original reply + its regenerator runs (same-input-node\n * sibling reply runs).\n * - `non-head-regen` — a regenerate that replaced a non-head message inside a\n * multi-message reply run; members are the owner run (the regenerate target in\n * place) plus each regenerator run. Not expressible as a same-parent\n * sibling-run group, so the View resolves and renders it itself (see\n * `_extractMessages`).\n *\n * `groupRoot` is the selection-map key: the input group root for fork-of, the\n * original reply's group root for regen, and the regenerate target's\n * codec-message-id for non-head-regen.\n */\ntype MessageBranchPoint =\n | { kind: 'fork-of'; groupRoot: string; members: BranchMember[] }\n | { kind: 'regen'; groupRoot: string; members: BranchMember[] }\n | { kind: 'non-head-regen'; groupRoot: string; members: BranchMember[] };\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 * 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 invocationId: run.invocationId,\n ...run.state,\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 _applier: WireApplier;\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 /**\n * Non-head regenerate selections, keyed by the regenerate target's\n * codec-message-id. Separate from {@link _regenSelections} because a non-head\n * regenerator parents inside the owner run rather than as a same-parent\n * sibling, so it lives outside the Tree's `visibleNodes` selection space and\n * is resolved at extraction (see `_extractMessages`). Value is the selected\n * member's nodeKey (the owner run id, or a regenerator run id); absent groups\n * default to the newest regenerator.\n */\n private readonly _nonHeadRegenSelections = 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 /**\n * Message-level trim on top of the run-level pagination window. Runs are\n * revealed whole (via `_withheldRunIds`/`_withheldBuffer`), so a `loadOlder`\n * may surface more messages than asked; this is the count of OLDEST messages\n * of the visible node chain to hide from `getMessages()` so a page lands on\n * exactly `limit` messages. The boundary run still appears in `runs()` (it's\n * a revealed node); only its oldest messages are trimmed from the flat list.\n * Live messages append at the newest end and are never trimmed.\n */\n private _hiddenMessageCount = 0;\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._applier = options.applier;\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).slice(this._hiddenMessageCount);\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 * The regenerator runs that replaced a non-head message of a reply run. They\n * file under the target's predecessor (not the owner run's input node), so the\n * Tree's `visibleNodes` cannot collapse them into the owner's slot; this\n * surfaces them for the View to resolve and render. Head-message (index 0)\n * regenerates are excluded - those are whole-reply sibling runs the Tree\n * already groups.\n * @param targetCodecMessageId - The regenerate target's (non-head) message id.\n * @param predecessorCodecMessageId - The codec-message-id immediately before it in the owner run.\n * @returns The regenerator runs in startSerial order (oldest first).\n */\n private _nonHeadRegenerators(\n targetCodecMessageId: string,\n predecessorCodecMessageId: string,\n ): RunNode<TProjection>[] {\n return this._tree\n .getReplyRuns(predecessorCodecMessageId)\n .filter((r) => r.regeneratesCodecMessageId === targetCodecMessageId)\n .toSorted((a, b) => (a.startSerial ?? '').localeCompare(b.startSerial ?? ''));\n }\n\n /**\n * Resolve the selected member of a non-head regenerate group anchored at\n * `targetCodecMessageId`. Members are the owner run `O` (memberNodeKey =\n * `ownerRunId`, the regenerate target in place) followed by each regenerator\n * run. Honours an explicit {@link _nonHeadRegenSelections} entry, else\n * defaults to the latest member (newest regenerator), mirroring the\n * whole-reply regenerate default.\n * @param targetCodecMessageId - The regenerate target's message id (the group anchor).\n * @param ownerRunId - The runId of the run that owns the regenerate target.\n * @param regenerators - The regenerator runs (oldest first) from `_nonHeadRegenerators`.\n * @returns The selected member's node key (`ownerRunId` or a regenerator runId).\n */\n private _selectedNonHeadMember(\n targetCodecMessageId: string,\n ownerRunId: string,\n regenerators: RunNode<TProjection>[],\n ): string {\n const sel = this._nonHeadRegenSelections.get(targetCodecMessageId);\n if (sel && sel.kind !== 'pending') {\n const keys = [ownerRunId, ...regenerators.map((r) => r.runId)];\n if (keys.includes(sel.selectedRunId)) return sel.selectedRunId;\n }\n // Default: latest member = newest regenerator (regenerators is oldest-first).\n return regenerators.at(-1)?.runId ?? ownerRunId;\n }\n\n /**\n * Flatten visible nodes to messages, collapsing a non-head regenerate into the\n * slot it replaces: while emitting a reply run, at each non-head message that\n * has a selected regenerator, drop that message and the run's tail and emit the\n * selected regenerator instead (recursive for regen-of-regen). Whole-reply\n * regenerates need nothing here - visibleNodes already picks the sibling.\n * @param nodes - Visible nodes (inputs + reply runs), chronological.\n * @returns The flat message list, each paired with its codec-message-id.\n */\n private _extractMessages(nodes: ConversationNode<TProjection>[]): CodecMessage<TMessage>[] {\n const messages: CodecMessage<TMessage>[] = [];\n // Regenerator runs already emitted via substitution at their anchor — skip\n // them when the node walk reaches them directly.\n const consumedRunIds = new Set<string>();\n\n for (const node of nodes) {\n if (node.kind === 'run' && consumedRunIds.has(node.runId)) continue;\n this._emitNodeMessages(node, messages, consumedRunIds);\n }\n return messages;\n }\n\n /**\n * Emit one visible node's messages into `out`, applying non-head regenerate\n * substitution for a reply run (see `_extractMessages`). Input nodes and runs\n * with no non-head regenerators emit their projection verbatim.\n * @param node - The node to emit.\n * @param out - The accumulating flat message list (mutated in place).\n * @param consumedRunIds - Set of regenerator runIds already emitted via substitution (mutated in place).\n */\n private _emitNodeMessages(\n node: ConversationNode<TProjection>,\n out: CodecMessage<TMessage>[],\n consumedRunIds: Set<string>,\n ): void {\n const own = this._codec.getMessages(node.projection);\n if (node.kind !== 'run') {\n out.push(...own);\n return;\n }\n for (let i = 0; i < own.length; i++) {\n const m = own[i];\n if (!m) continue;\n // Head message (i === 0) regenerates are whole-reply sibling runs, already\n // resolved by visibleNodes — only non-head messages anchor a non-head group.\n const predecessor = i > 0 ? own[i - 1]?.codecMessageId : undefined;\n if (predecessor !== undefined) {\n const regenerators = this._nonHeadRegenerators(m.codecMessageId, predecessor);\n if (regenerators.length > 0) {\n // Every regenerator (and any same-anchor sibling the Tree already\n // collapsed in `visibleNodes`) is an alternative at THIS one slot, so\n // mark them all consumed up front — the node walk must not re-emit the\n // Tree's default-latest sibling once we render a different member here.\n for (const r of regenerators) consumedRunIds.add(r.runId);\n const selectedKey = this._selectedNonHeadMember(m.codecMessageId, node.runId, regenerators);\n if (selectedKey !== node.runId) {\n // A regenerator is selected: drop M and the rest of O, emit the\n // selected regenerator in M's place (recursively for nested regen).\n const chosen = regenerators.find((r) => r.runId === selectedKey);\n if (chosen) {\n this._emitNodeMessages(chosen, out, consumedRunIds);\n return;\n }\n }\n // Original (owner run) selected: fall through and emit M from O.\n }\n }\n out.push(m);\n }\n }\n\n hasOlder(): boolean {\n return this._hiddenMessageCount > 0 || this._withheldBuffer.length > 0 || this._hasMoreHistory;\n }\n\n /**\n * Reveal `limit` more older codecMessages in this view — fewer only when\n * channel history is exhausted.\n *\n * Internally runs are revealed WHOLE (run-granular withholding), counting\n * codecMessages to decide how many runs to bring in, then the flat list\n * returned by {@link getMessages} is trimmed to exactly `limit` more\n * messages. So a run straddling the boundary still appears in {@link runs}\n * (it's a revealed node) while only its newest messages show in\n * `getMessages`. Live messages append at the newest end and are never\n * trimmed.\n * @param limit - Number of older codecMessages to reveal. Defaults to 10.\n */\n async loadOlder(limit = 10): Promise<void> {\n if (this._closed || this._loadingOlder) return;\n this._loadingOlder = true;\n this._logger.trace('DefaultView.loadOlder();', { limit });\n\n try {\n // Phase A: the boundary run is already revealed (a previous loadOlder\n // pulled in a whole run that overshot the message limit); reveal more of\n // its trimmed-off oldest messages without fetching or revealing new runs.\n if (this._hiddenMessageCount >= limit) {\n this._hiddenMessageCount -= limit;\n this._recomputeAndEmit();\n return;\n }\n\n // Phase B: reveal whole older runs covering the remaining message budget,\n // then re-trim so exactly `limit` new messages surface. Runs are revealed\n // whole (node granularity); the trim makes the message count exact.\n const need = limit - this._hiddenMessageCount;\n const before = this._extractMessages(this._computeFlatNodes()).length;\n const revealedSoFar = (): number => this._extractMessages(this._computeFlatNodes()).length - before;\n\n // Drain the withheld buffer toward `need` (whole older runs, newest-first).\n if (this._withheldBuffer.length > 0) {\n const splitIdx = this._messageTailSplitIndex(this._withheldBuffer, need);\n const batch = this._withheldBuffer.splice(splitIdx);\n this._releaseWithheld(batch);\n }\n\n // If the buffer was empty or fell short of `need` (e.g. it held a\n // zero-message run), fetch channel history for the remainder. The fetch\n // path loops over pages internally until it covers its target or history\n // is exhausted, so a single call here suffices.\n if (revealedSoFar() < need) {\n await this._fetchOlder(need - revealedSoFar());\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- close() may be set during the await above\n if (this._closed) return;\n }\n\n const after = this._extractMessages(this._computeFlatNodes()).length;\n // `after - before` whole-run messages were added at the oldest end; show\n // `limit` of them (newest), hiding the overshoot plus what was already\n // trimmed. `<= 0` when history is exhausted before `limit` is reached.\n this._hiddenMessageCount = Math.max(0, this._hiddenMessageCount + (after - before) - limit);\n this._recomputeAndEmit();\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 * Fetch older channel history covering at least `target` more codecMessages,\n * buffering the older nodes and revealing whole runs. The withheld buffer is\n * assumed already drained by the caller. Loads the first page when no history\n * has been fetched yet, otherwise advances to the next older page; the\n * page-walk inside {@link _revealFromPage} loops until `target` messages are\n * covered or history runs out. No-op (leaving `_hasMoreHistory` false) once\n * channel history is exhausted.\n * @param target - Minimum additional codecMessages this fetch aims to cover.\n */\n private async _fetchOlder(target: number): Promise<void> {\n if (!this._hasMoreHistory && !this._lastHistoryPage) {\n await this._loadFirstPage(target);\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 if (this._closed || !nextPage) {\n if (!nextPage) this._hasMoreHistory = false;\n return;\n }\n\n await this._revealFromPage(nextPage, target);\n }\n\n /**\n * Find the index in `nodes` (chronological, oldest-first) at which the newest\n * whole runs covering at least `target` codecMessages begin. Walks newest-first\n * summing each node's `codec.getMessages(projection)` count; once the running\n * total reaches `target`, the current node (and everything newer) is the\n * revealed batch — so whole runs are revealed and the batch may overshoot\n * `target` (the caller trims). Returns `0` when the nodes hold fewer than\n * `target` messages — reveal everything.\n *\n * Shared by the buffer-drain and history-fetch reveal paths so they agree on\n * \"covering `target` messages\".\n * @param nodes - Candidate nodes, oldest-first.\n * @param target - Minimum codecMessages the revealed batch must cover.\n * @returns The split index; `nodes[splitIdx..]` is the revealed batch.\n */\n private _messageTailSplitIndex(nodes: ConversationNode<TProjection>[], target: number): number {\n let messages = 0;\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i];\n if (!node) continue;\n messages += this._codec.getMessages(node.projection).length;\n if (messages >= target) return i; // reveal nodes[i..]\n }\n return 0; // fewer than `target` messages — reveal everything\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 member contributes its representative message as the branch-arrow\n // slot: for an edit fork that is the alternate user prompt; for a\n // whole-reply regenerate group the variant's first message; for a non-head\n // regenerate group the regenerate target (original) or the regenerator's\n // first message.\n const siblings = branch.members.flatMap((member) => {\n const owner = this._tree.getNodeByCodecMessageId(member.representativeCodecMessageId);\n if (!owner) return [];\n const found = this._codec\n .getMessages(owner.projection)\n .find((m) => m.codecMessageId === member.representativeCodecMessageId);\n return found ? [found.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.members.length - 1));\n const selected = branch.members[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: selected.memberNodeKey });\n this._logger.debug('DefaultView.selectSibling(); fork-of', {\n codecMessageId,\n index: clamped,\n selectedKey: selected.memberNodeKey,\n });\n } else if (branch.kind === 'non-head-regen') {\n // Non-head groups live outside the visibleNodes sibling space — store in\n // the dedicated map the message-extraction substitution reads.\n this._nonHeadRegenSelections.set(branch.groupRoot, { kind: 'user', selectedRunId: selected.memberNodeKey });\n this._logger.debug('DefaultView.selectSibling(); non-head-regen', {\n codecMessageId,\n index: clamped,\n selectedRunId: selected.memberNodeKey,\n anchor: branch.groupRoot,\n });\n } else {\n this._regenSelections.set(branch.groupRoot, { kind: 'user', selectedRunId: selected.memberNodeKey });\n this._logger.debug('DefaultView.selectSibling(); regenerate', {\n codecMessageId,\n index: clamped,\n selectedRunId: selected.memberNodeKey,\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): number {\n if (branch.kind === 'fork-of') {\n const sel = this._branchSelections.get(branch.groupRoot);\n if (!sel) return branch.members.length - 1;\n const idx = branch.members.findIndex((m) => m.memberNodeKey === sel.selectedKey);\n return idx === -1 ? branch.members.length - 1 : idx;\n }\n const sel =\n branch.kind === 'non-head-regen'\n ? this._nonHeadRegenSelections.get(branch.groupRoot)\n : this._regenSelections.get(branch.groupRoot);\n if (!sel || sel.kind === 'pending') return branch.members.length - 1;\n const idx = branch.members.findIndex((m) => m.memberNodeKey === sel.selectedRunId);\n return idx === -1 ? branch.members.length - 1 : idx;\n }\n\n /**\n * Resolve the branch point anchored at `codecMessageId`, if any, returning the\n * group `kind` + members + groupRoot so the caller routes to the correct\n * selection map directly (not via a runId dispatch that would mis-route when\n * the owning Run is in both a fork-of and a regen group).\n * @param codecMessageId - The codec-message-id to look up.\n * @returns The resolved branch point, or undefined when `codecMessageId`\n * anchors no group.\n */\n private _resolveMessageBranchPoint(codecMessageId: string): MessageBranchPoint | 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 {\n kind: 'fork-of',\n groupRoot: this._tree.getGroupRoot(node.codecMessageId),\n members: this._nodeHeadMembers(siblings),\n };\n }\n return undefined;\n }\n\n // Non-head regenerate branch point: `codecMessageId` is the rendered slot for\n // a regenerate that replaced a non-head message inside a multi-message reply\n // run. Resolved BEFORE the same-parent `regen` group below: several non-head\n // regenerators of one anchor share a parent (the anchor's predecessor), so\n // the Tree files them as their own sibling group excluding the owner run; the\n // non-head resolver instead gathers the owner plus every regenerator into one\n // anchor-keyed group.\n const ownMessages = this._codec.getMessages(node.projection);\n const nonHead = this._resolveNonHeadBranchPoint(node, ownMessages, codecMessageId);\n if (nonHead) return nonHead;\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 && ownMessages.at(0)?.codecMessageId === codecMessageId) {\n return {\n kind: 'regen',\n groupRoot: this._tree.getGroupRoot(node.runId),\n members: this._nodeHeadMembers(siblings),\n };\n }\n\n return undefined;\n }\n\n /**\n * Resolve a non-head regenerate branch point from a reply-run message, if any.\n * `codecMessageId` is either (a) a non-head message `M` of its owner run with\n * regenerators, or (b) a regenerator run's head; both resolve to the same group\n * anchored at `M` (key matching {@link _nonHeadRegenSelections}).\n * @param node - The reply run owning `codecMessageId`.\n * @param ownMessages - That run's projected messages (already extracted).\n * @param codecMessageId - The slot's codec-message-id (an `M`, or a regenerator head).\n * @returns The non-head branch point, or undefined when `codecMessageId` anchors none.\n */\n private _resolveNonHeadBranchPoint(\n node: RunNode<TProjection>,\n ownMessages: CodecMessage<TMessage>[],\n codecMessageId: string,\n ): MessageBranchPoint | undefined {\n // Case (b): `codecMessageId` is a regenerator run's head. Re-anchor on the\n // message it regenerates and resolve from the owner run's perspective.\n const isHead = ownMessages.at(0)?.codecMessageId === codecMessageId;\n if (isHead && node.regeneratesCodecMessageId !== undefined) {\n const anchorId = node.regeneratesCodecMessageId;\n const owner = this._runByCodecMessageId(anchorId);\n if (owner) {\n const ownerMsgs = this._codec.getMessages(owner.projection);\n const idx = ownerMsgs.findIndex((mm) => mm.codecMessageId === anchorId);\n const predecessor = idx > 0 ? ownerMsgs[idx - 1]?.codecMessageId : undefined;\n if (predecessor !== undefined) {\n return this._buildNonHeadGroup(anchorId, owner.runId, predecessor);\n }\n }\n return undefined;\n }\n\n // Case (a): `codecMessageId` is a non-head message of its owner run.\n const idx = ownMessages.findIndex((mm) => mm.codecMessageId === codecMessageId);\n const predecessor = idx > 0 ? ownMessages[idx - 1]?.codecMessageId : undefined;\n if (predecessor === undefined) return undefined;\n return this._buildNonHeadGroup(codecMessageId, node.runId, predecessor);\n }\n\n /**\n * Build the {@link MessageBranchPoint} for a non-head regenerate group, or\n * undefined when the anchor has no regenerators. The owner member's\n * representative is the anchor message (the regenerate target); each\n * regenerator's is its head message.\n * @param anchorCodecMessageId - The regenerate target's (non-head) message id.\n * @param ownerRunId - The runId owning the regenerate target.\n * @param predecessorCodecMessageId - The codec-message-id immediately before the anchor in the owner run.\n * @returns The non-head branch point, or undefined when there are no regenerators.\n */\n private _buildNonHeadGroup(\n anchorCodecMessageId: string,\n ownerRunId: string,\n predecessorCodecMessageId: string,\n ): MessageBranchPoint | undefined {\n const regenerators = this._nonHeadRegenerators(anchorCodecMessageId, predecessorCodecMessageId);\n if (regenerators.length === 0) return undefined;\n const members: BranchMember[] = [{ memberNodeKey: ownerRunId, representativeCodecMessageId: anchorCodecMessageId }];\n for (const r of regenerators) {\n const head = this._codec.getMessages(r.projection).at(0);\n if (head) members.push({ memberNodeKey: r.runId, representativeCodecMessageId: head.codecMessageId });\n }\n return { kind: 'non-head-regen', groupRoot: anchorCodecMessageId, members };\n }\n\n /**\n * Project nodes to {@link BranchMember}s for fork-of / whole-reply regen\n * groups, where each member's branch-arrow representative is its own head\n * message and its memberNodeKey is its node key.\n * @param nodes - The sibling nodes.\n * @returns One member per node that has a head message.\n */\n private _nodeHeadMembers(nodes: ConversationNode<TProjection>[]): BranchMember[] {\n const members: BranchMember[] = [];\n for (const n of nodes) {\n const head = this._codec.getMessages(n.projection).at(0);\n if (head) members.push({ memberNodeKey: nodeKey(n), representativeCodecMessageId: head.codecMessageId });\n }\n return members;\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\n // Non-head regenerate: the anchor is a non-head message of its owner run, so\n // the new run won't be a same-parent sibling — it parents at the anchor's\n // predecessor. Defer in the dedicated non-head map (keyed by the anchor\n // message), not the sibling-group regen map.\n const anchorMsgs = this._codec.getMessages(anchorRun.projection);\n if (anchorMsgs.at(0)?.codecMessageId !== anchorCodecMessageId) {\n this._nonHeadRegenSelections.set(anchorCodecMessageId, {\n kind: 'pending',\n carrierCodecMessageId: result.inputCodecMessageId,\n });\n this._logger.debug('DefaultView._applyRegenerateAutoSelect(); deferring non-head regenerate selection', {\n anchorCodecMessageId,\n carrier: result.inputCodecMessageId,\n });\n this._resolvePendingNonHeadRegenSelections();\n this._recomputeAndEmitIfChanged();\n return;\n }\n\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._nonHeadRegenSelections.clear();\n this._withheldRunIds.clear();\n this._withheldBuffer.length = 0;\n this._hiddenMessageCount = 0;\n this._onClose?.();\n }\n\n // -------------------------------------------------------------------------\n // Private: history loading\n // -------------------------------------------------------------------------\n\n private async _loadFirstPage(target: number): Promise<void> {\n // `loadHistory`'s limit and this view's reveal target both count complete\n // domain messages (codecMessages), so the target passes straight through.\n const firstPage = await loadHistory(this._channel, { limit: target }, this._logger);\n if (this._closed) return;\n await this._revealFromPage(firstPage, target);\n }\n\n /**\n * Walk channel history from `page` until the newly-observed nodes hold at\n * least `target` codecMessages (or the channel is exhausted), then reveal the\n * newest whole runs covering `target` and withhold the rest. Snapshots the\n * already-visible nodes up front so only newly-observed nodes count toward\n * `target`. No-op if the view closed during the page walk.\n * @param page - The decoded history page to start from.\n * @param target - Minimum codecMessages to reveal in this batch.\n */\n private async _revealFromPage(page: HistoryPage, target: 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, target, beforeRunIds);\n if (this._closed) return;\n this._lastHistoryPage = lastPage;\n this._hasMoreHistory = lastPage.hasNext();\n this._splitReveal(newVisible, target);\n }\n\n /**\n * Reveal the newest whole runs covering `target` codecMessages from\n * `newVisible` and withhold the rest so subsequent `loadOlder` calls can\n * drain them. Reveal granularity is the whole run; the caller trims the flat\n * message list (via `_hiddenMessageCount`) to make the visible message count\n * exact. Called by {@link _revealFromPage}.\n * @param newVisible - Newly observed nodes (inputs + reply runs) from the history fetch, chronological.\n * @param target - Minimum codecMessages the revealed batch must cover.\n */\n private _splitReveal(newVisible: ConversationNode<TProjection>[], target: number): void {\n const splitIdx = this._messageTailSplitIndex(newVisible, target);\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 through the Tree's\n * single decode-and-apply engine — the same applier (and decoder instance)\n * the client's live loop uses, so history replay can't drift from it. The\n * shared decoder's version-guarded trackers make the overlap between the\n * two routes safe: an in-flight stream that spans the attach boundary is\n * continued rather than re-started, and content the live route already\n * incorporated decodes to nothing.\n * @param page - The history page returned by `loadHistory`.\n */\n private _processHistoryPage(page: HistoryPage): void {\n this._processingHistory = true;\n try {\n for (const rawMsg of page.rawMessages) {\n this._applier.apply(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 // Count newly-visible codecMessages toward the target (whole runs are\n // revealed; the caller trims to the exact message count).\n if (!beforeRunIds.has(nodeKey(n))) count += this._codec.getMessages(n.projection).length;\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 // Run-level reveal, message-level trim: drop the oldest `_hiddenMessageCount`\n // messages so a `loadOlder` page lands on exactly `limit` messages even\n // though whole runs were revealed.\n this._lastVisibleMessagePairs = this._extractMessages(resolved).slice(this._hiddenMessageCount);\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 this._resolvePendingNonHeadRegenSelections();\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 /**\n * Roll `pending` and `auto` non-head regenerate selections forward to the\n * newest regenerator of their anchor message. Mirrors\n * {@link _resolvePendingRegenSelections} for the non-head group, which lives in\n * a separate selection map (anchored by the regenerate target rather than a\n * sibling-group root): a `user` selection pins and is left untouched; a\n * `pending`/`auto` slot adopts the newest regenerator once one lands. The\n * anchor's predecessor — the key the regenerators file under — is recovered\n * from the owning run's projection.\n */\n private _resolvePendingNonHeadRegenSelections(): void {\n for (const [anchorId, sel] of this._nonHeadRegenSelections) {\n if (sel.kind === 'user') continue;\n const owner = this._runByCodecMessageId(anchorId);\n if (!owner) continue;\n const ownerMsgs = this._codec.getMessages(owner.projection);\n const idx = ownerMsgs.findIndex((m) => m.codecMessageId === anchorId);\n const predecessor = idx > 0 ? ownerMsgs[idx - 1]?.codecMessageId : undefined;\n if (predecessor === undefined) continue;\n const newest = this._nonHeadRegenerators(anchorId, predecessor).at(-1);\n if (!newest) continue;\n this._nonHeadRegenSelections.set(anchorId, { 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// Also augments RealtimeChannel with `.object` (ably/liveobjects side-effect).\nimport type * as AblyObjects from 'ably/liveobjects';\n\nimport {\n EVENT_CANCEL,\n EVENT_RUN_END,\n HEADER_CODEC_MESSAGE_ID,\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 { errorCause, errorMessage, getTransportHeaders } from '../../utils.js';\nimport { registerAgent } from '../agent.js';\nimport { resolveChannelModes } from '../channel-options.js';\nimport type { Codec, CodecInputEvent, CodecOutputEvent, Encoder } from '../codec/types.js';\nimport { createWireApplier, type WireApplier } from './decode-fold.js';\nimport { buildRunEndError, buildTransportHeaders } from './headers.js';\nimport { Invocation } from './invocation.js';\nimport { bestEffortDetach, continuityLostError, isContinuityLost, requireConnected } from './session-support.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 _client: Ably.Realtime;\n private readonly _codec: Codec<TInput, TOutput, TProjection, TMessage>;\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 /**\n * The Tree's single decode-and-apply engine, binding the session's one\n * decoder instance. Shared by the live decode loop and every View's history\n * replay so an attach-boundary in-flight stream is continued (not\n * re-started) by hydration, and re-delivered content decodes to nothing.\n */\n private readonly _applier: WireApplier;\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: Ably.ChannelOptions = registerAgent(options.client, options.codec);\n // Spec: AIT-CT23 — request object modes etc. when channelModes opts in.\n const modes = resolveChannelModes(options.channelModes);\n if (modes) channelOptions.modes = modes;\n this._channel = options.client.channels.get(options.channelName, channelOptions);\n this._client = options.client;\n this._codec = options.codec;\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._applier = createWireApplier(this._tree, this._codec.createDecoder());\n this._view = createView<TInput, TOutput, TProjection, TMessage>({\n tree: this._tree,\n channel: this._channel,\n codec: this._codec,\n applier: this._applier,\n sendDelegate: this._internalSend.bind(this),\n logger: this._logger,\n onClose: () => this._views.delete(this._view),\n });\n this._encoder = this._codec.createEncoder(this._channel);\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 accessors\n // ---------------------------------------------------------------------------\n\n // Spec: AIT-CT21\n get presence(): Ably.RealtimePresence {\n return this._channel.presence;\n }\n\n // Spec: AIT-CT22\n get object(): AblyObjects.RealtimeObject {\n return this._channel.object;\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; ${errorMessage(error)}`,\n ErrorCode.SessionSubscriptionError,\n 500,\n errorCause(error),\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 /**\n * The session's identity, read from the Ably client's `auth.clientId`. Read\n * lazily (never cached at construction): under token auth the client only\n * learns its clientId once the connection reaches CONNECTED, which is\n * guaranteed by the time any write runs — every write awaits `connect()`,\n * and the channel cannot attach before the connection is CONNECTED. A\n * connection with no concrete identity (anonymous, or a wildcard `*` token)\n * resolves to `undefined`, so no run/input client id is stamped.\n * @returns The client's concrete identity, or `undefined` if it has none.\n */\n // Spec: AIT-CT1b\n private _resolveClientId(): string | undefined {\n const clientId = this._client.auth.clientId;\n return clientId && clientId !== '*' ? clientId : undefined;\n }\n\n private async _requireConnected(method: string): Promise<void> {\n return requireConnected(this._connectPromise, method);\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 errInfo = buildRunEndError(headers);\n this._logger.error('ClientSession._handleMessage(); agent error received', {\n runId: headers[HEADER_RUN_ID],\n invocationId: headers[HEADER_INVOCATION_ID],\n code: errInfo.code,\n });\n this._emitter.emit('error', errInfo);\n }\n }\n\n // Reconstruct the tree via the Tree's single decode-and-apply engine —\n // the same applier (and decoder instance) the Views' history replay\n // uses, so the live loop can't drift from it and an attach-boundary\n // stream isn't double-decoded.\n const event = this._applier.apply(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 this._emitter.emit(\n 'error',\n new Ably.ErrorInfo(\n `unable to process channel message; ${errorMessage(error)}`,\n ErrorCode.SessionSubscriptionError,\n 500,\n errorCause(error),\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 if (!isContinuityLost(stateChange)) return;\n\n this._logger.error('ClientSession._handleChannelStateChange(); channel continuity lost', {\n current,\n resumed,\n previous: stateChange.previous,\n });\n\n const err = continuityLostError(stateChange, 'deliver events');\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 applier: this._applier,\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._resolveClientId(),\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 });\n }\n } catch (error) {\n const cause = errorCause(error);\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; ${errorMessage(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 await bestEffortDetach(this._channel, this._connectPromise, this._logger, 'ClientSession');\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","import type * as Ably from 'ably';\nimport { createContext } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../../core/codec/types.js';\nimport type { ClientSession } from '../../core/transport/types.js';\n\n/**\n * A single entry in the client-session registry, holding the session and any\n * error that occurred during its construction.\n *\n * `session` is `undefined` when construction failed.\n * `sessionError` is set when `createClientSession` threw during provider render.\n */\nexport interface ClientSessionSlot {\n /** The constructed session, or `undefined` if construction failed. */\n session: ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown> | undefined;\n /** Construction error from `createClientSession`, or `undefined` on success. */\n sessionError?: Ably.ErrorInfo | undefined;\n}\n\n/**\n * The shape of the {@link ClientSessionContext} value.\n *\n * `nearest` is the slot from the innermost enclosing {@link ClientSessionProvider}.\n * `providers` is the full registry of all enclosing providers, keyed by channelName.\n */\ninterface ClientSessionContextValue {\n /** The innermost {@link ClientSessionProvider}'s slot. `undefined` when no provider is present. */\n nearest: ClientSessionSlot | undefined;\n /** All registered session slots from enclosing providers, keyed by channelName. */\n providers: Readonly<Record<string, ClientSessionSlot>>;\n}\n\n/**\n * Unified client-session context.\n *\n * Holds the nearest client-session slot and the full registry of all registered\n * slots keyed by channelName. Populated by {@link ClientSessionProvider};\n * read by {@link useClientSession} and internal hooks.\n */\nexport const ClientSessionContext = createContext<ClientSessionContextValue>({ nearest: undefined, providers: {} });\n","/**\n * ClientSessionProvider: creates a ClientSession and makes it available to\n * descendants via ClientSessionContext.\n *\n * Reads the Ably Realtime client from the surrounding `<AblyProvider>` and\n * forwards it to `createClientSession` along with the supplied `channelName`.\n *\n * The session is created on first render (via useRef) and recreated when\n * `channelName` changes; the previous session is queued for disposal.\n * `connect()` is invoked from a `useEffect` so the session is\n * subscribed/attached before the first descendant operation. If\n * `createClientSession` throws,\n * the error is stored in the ClientSessionSlot (alongside an undefined\n * session) so that useClientSession can surface it as `sessionError`\n * without crashing the component tree.\n *\n * The session is closed when the provider truly unmounts. The close is\n * scheduled as a microtask so that React Strict Mode's synchronous\n * remount cycle (mount → fake-unmount → remount) can cancel it before it\n * fires, avoiding unnecessary session teardown in development.\n *\n * Multiple ClientSessionProviders can be nested using distinct channelNames.\n * Each provider merges its slot into the parent record so descendants\n * can access all registered sessions via useClientSession(channelName).\n *\n * The provider also wraps its children in ably-js's `<ChannelProvider>` for the\n * session's channel, so descendants can use ably-js channel hooks\n * (`usePresence`, `useChannel`, etc.) against it without adding their own. It\n * seeds the ChannelProvider's `options` with this SDK's channel agent so the\n * hooks' agent is appended rather than overwriting it (ably-js >= 2.22).\n */\n\nimport * as Ably from 'ably';\nimport { ChannelProvider, useAbly } from 'ably/react';\nimport { type PropsWithChildren, type ReactNode, useContext, useEffect, useMemo, useRef } from 'react';\n\nimport { channelAgent } from '../../core/agent.js';\nimport { resolveChannelModes } from '../../core/channel-options.js';\nimport type { CodecInputEvent, CodecOutputEvent } from '../../core/codec/types.js';\nimport { createClientSession } from '../../core/transport/client-session.js';\nimport type { ClientSession, ClientSessionOptions } from '../../core/transport/types.js';\nimport { ErrorCode } from '../../errors.js';\nimport type { ClientSessionSlot } from './client-session-context.js';\nimport { ClientSessionContext } from './client-session-context.js';\n\n/**\n * Props for {@link ClientSessionProvider}.\n *\n * All {@link ClientSessionOptions} except `client` (read from the surrounding\n * `<AblyProvider>`).\n */\nexport interface ClientSessionProviderProps<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>\n extends Omit<ClientSessionOptions<TInput, TOutput, TProjection, TMessage>, 'client'>, PropsWithChildren {}\n\n/**\n * Provide a {@link ClientSession} to descendant components.\n *\n * Reads the Ably Realtime client from the surrounding `<AblyProvider>`,\n * creates a session bound to `channelName`, calls `connect()` on mount,\n * and registers it in `ClientSessionContext` under `channelName`.\n * Descendants call {@link useClientSession} with the same `channelName` to\n * access the session.\n *\n * If `createClientSession` throws during construction, the error is surfaced\n * through `useClientSession` as `sessionError` — the component tree does not\n * crash and children are still rendered.\n *\n * ```tsx\n * <AblyProvider client={ably}>\n * <ClientSessionProvider channelName=\"ai:demo\" codec={UIMessageCodec}>\n * <Chat />\n * </ClientSessionProvider>\n * </AblyProvider>\n *\n * // Inside Chat:\n * const { session, sessionError } = useClientSession({ channelName: 'ai:demo' });\n * ```\n *\n * For multiple sessions, nest providers with distinct channelNames:\n *\n * ```tsx\n * <ClientSessionProvider channelName=\"ai:main\" codec={UIMessageCodec}>\n * <ClientSessionProvider channelName=\"ai:aux\" codec={UIMessageCodec}>\n * <App />\n * </ClientSessionProvider>\n * </ClientSessionProvider>\n *\n * // Inside App:\n * const { session: main } = useClientSession({ channelName: 'ai:main' });\n * const { session: aux } = useClientSession({ channelName: 'ai:aux' });\n * ```\n * `channelModes` must stay constant for the provider's lifetime: the session is\n * only recreated when `channelName` changes, and removing the modes after mount\n * silently reverts the channel's mode set without a reattach.\n * @param props - Provider configuration including `channelName`, `codec`, and all other {@link ClientSessionOptions} except `client`.\n * @param props.children - Descendant components that consume the session via {@link useClientSession}.\n * @returns A React element wrapping children with ClientSessionContext.\n */\nexport const ClientSessionProvider = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>({\n children,\n ...sessionOptions\n}: ClientSessionProviderProps<TInput, TOutput, TProjection, TMessage>): ReactNode => {\n const client = useAbly();\n const { channelName } = sessionOptions;\n\n // Seed the ChannelProvider with this SDK's channel agent so ably-js's React\n // hooks append their agent (`channelOptionsForReactHooks`) rather than\n // overwriting it. Memoised on the codec, which determines the agent string.\n //\n // Spec: AIT-CT23 — resolve the channel modes through the same helper the\n // session uses so the provider and the session request an identical,\n // identically-ordered mode set. ably-js compares modes order- and\n // duplicate-sensitively, so matching arrays mean the provider's setOptions\n // never triggers a reattach and never silently reverts the session's modes.\n const channelOptions = useMemo<Ably.ChannelOptions>(() => {\n const options: Ably.ChannelOptions = { params: { agent: channelAgent(sessionOptions.codec) } };\n const modes = resolveChannelModes(sessionOptions.channelModes);\n if (modes) options.modes = modes;\n return options;\n }, [sessionOptions.codec, sessionOptions.channelModes]);\n const sessionRef = useRef<ClientSession<TInput, TOutput, TProjection, TMessage> | undefined>(undefined);\n const sessionChannelRef = useRef<string>(channelName);\n const sessionsToDisposeRef = useRef<ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown>[]>([]);\n const pendingCloseRef = useRef(false);\n const constructionErrorRef = useRef<Ably.ErrorInfo | undefined>(undefined);\n\n const alreadyCreatedOrFailed = !!sessionRef.current || !!constructionErrorRef.current;\n\n if (!alreadyCreatedOrFailed || sessionChannelRef.current !== channelName) {\n sessionChannelRef.current = channelName;\n if (sessionRef.current) sessionsToDisposeRef.current.push(sessionRef.current);\n try {\n sessionRef.current = createClientSession({ ...sessionOptions, client });\n constructionErrorRef.current = undefined;\n } catch (error) {\n sessionRef.current = undefined;\n constructionErrorRef.current =\n error instanceof Ably.ErrorInfo\n ? error\n : new Ably.ErrorInfo('Unknown error while creating client session', ErrorCode.BadRequest, 400);\n }\n }\n\n const parentContext = useContext(ClientSessionContext);\n\n // Capture ref values as locals so useMemo deps track changes correctly.\n // CAST: ClientSessionContext stores sessions with erased generics.\n // The generic types are fixed at the ClientSessionProvider<TInput, TOutput, TProjection, TMessage> boundary.\n const currentSession = sessionRef.current as\n | ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown>\n | undefined;\n const currentError = constructionErrorRef.current;\n\n const slot = useMemo<ClientSessionSlot>(\n () => ({ session: currentSession, sessionError: currentError }),\n [currentSession, currentError],\n );\n\n const contextValue = useMemo(\n () => ({ nearest: slot, providers: { ...parentContext.providers, [channelName]: slot } }),\n [channelName, parentContext, slot],\n );\n\n // Dispose sessions superseded by a channelName change. When channelName\n // changes, the render path above pushes the now-stale session into\n // sessionsToDisposeRef and creates a replacement. This effect's cleanup —\n // which runs on the next channelName change or on unmount — closes every\n // queued session.\n useEffect(\n () => () => {\n for (const session of sessionsToDisposeRef.current) void session.close();\n },\n [channelName],\n );\n\n // Trigger connect() once the session is created. Re-runs when channelName\n // changes so the freshly-recreated session connects too. Any error is\n // stored on the session's emitter and surfaced via on('error');\n // useClientSession doesn't need to await this.\n useEffect(() => {\n void sessionRef.current?.connect();\n }, [channelName]);\n\n // Close the session when the component truly unmounts. The close is\n // scheduled as a microtask: in React Strict Mode (dev) the component\n // remounts synchronously before any microtask can drain, so the remount's\n // effect setup resets pendingCloseRef.current = false and cancels the\n // close. On a real unmount no remount follows, the microtask fires, and\n // the session is closed.\n useEffect(() => {\n pendingCloseRef.current = false;\n return () => {\n pendingCloseRef.current = true;\n void Promise.resolve().then(() => {\n if (pendingCloseRef.current) {\n void sessionRef.current?.close();\n }\n });\n };\n }, []);\n\n return (\n <ClientSessionContext.Provider value={contextValue}>\n <ChannelProvider\n channelName={channelName}\n options={channelOptions}\n >\n {children}\n </ChannelProvider>\n </ClientSessionContext.Provider>\n );\n};\n","import { useContext } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../../core/codec/types.js';\nimport type { ClientSession } from '../../core/transport/types.js';\nimport { ClientSessionContext } from '../contexts/client-session-context.js';\n\n/**\n * Shared base for hook options that accept an explicit session override.\n * Extend this interface for any hook whose `session` option defaults to the\n * nearest {@link ClientSessionProvider} when omitted. Pass `null` to defer\n * resolution (e.g. when a split pane is collapsed) — the helper returns\n * `undefined` rather than falling back to the nearest provider.\n */\nexport interface BaseSessionOption<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> {\n /**\n * Session to operate on; defaults to the nearest {@link ClientSessionProvider}.\n * Pass `null` to defer (returns undefined; nearest provider is not used).\n */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage> | null;\n}\n\n/**\n * Resolve the active `ClientSession` for a hook.\n *\n * Reads `ClientSessionContext` and applies the standard three-way\n * priority: explicit `session` argument → nearest provider → `undefined`.\n * When `skip` is `true`, returns `undefined` regardless of context.\n * When `session` is `null`, returns `undefined` (caller is deferring).\n *\n * Internal — not part of the public API.\n * @param root0 - Options.\n * @param root0.session - Explicit session; takes priority over the nearest provider. `null` to defer.\n * @param root0.skip - When `true`, returns `undefined` immediately; context is still read but its value is ignored.\n * @returns The resolved session, or `undefined` if none is available or `skip` is `true`.\n */\nexport const useResolvedSession = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>({\n session,\n skip,\n}: {\n /** Explicit session; takes priority over the nearest provider. `null` to defer. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage> | null;\n /** When `true`, return `undefined` immediately (context is still read, but ignored). */\n skip?: boolean;\n} = {}): ClientSession<TInput, TOutput, TProjection, TMessage> | undefined => {\n const { nearest } = useContext(ClientSessionContext);\n // CAST: ClientSessionContext stores session with erased generics; types fixed at call site.\n const nearestSession = nearest?.session as unknown as\n | ClientSession<TInput, TOutput, TProjection, TMessage>\n | undefined;\n if (skip) return undefined;\n if (session === null) return undefined;\n return session ?? nearestSession;\n};\n","/**\n * useAblyMessages — reactive raw Ably message log from a ClientSession.\n *\n * Accumulates raw Ably InboundMessages from the session's tree\n * 'ably-message' event. Messages are appended in arrival order.\n *\n * When `session` is omitted, defaults to the nearest\n * {@link ClientSessionProvider}'s session via context.\n * Pass `skip: true` to bypass all subscriptions and return an empty array.\n */\n\nimport type * as Ably from 'ably';\nimport { useEffect, useRef, useState } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { BaseSessionOption } from './internal/use-resolved-session.js';\nimport { useResolvedSession } from './internal/use-resolved-session.js';\n\n/** Options for {@link useAblyMessages}. */\nexport interface UseAblyMessagesOptions<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> extends BaseSessionOption<TInput, TOutput, TProjection, TMessage> {\n /** When `true`, skip all subscriptions and return an empty array. */\n skip?: boolean;\n}\n\n/**\n * Subscribe to raw Ably message updates from a client session's tree.\n * When `session` is omitted, uses the nearest {@link ClientSessionProvider}'s session via context.\n * @param props - Options including optional `session` and `skip`.\n * @param props.session - Session to subscribe to; defaults to the nearest provider.\n * @param props.skip - When `true`, skip all subscriptions and return an empty array.\n * @returns The accumulated raw Ably messages in event-arrival order — older history messages loaded later are appended after the live messages already present, so this is not strictly chronological.\n */\nexport const useAblyMessages = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>({ session, skip }: UseAblyMessagesOptions<TInput, TOutput, TProjection, TMessage> = {}): Ably.InboundMessage[] => {\n const resolved = useResolvedSession({ session, skip });\n\n const [messages, setMessages] = useState<Ably.InboundMessage[]>([]);\n const messagesRef = useRef<Ably.InboundMessage[]>([]);\n\n useEffect(() => {\n // Reset on session change\n messagesRef.current = [];\n setMessages([]);\n\n if (!resolved) return;\n\n const unsub = resolved.tree.on('ably-message', (msg: Ably.InboundMessage) => {\n const next = [...messagesRef.current, msg];\n messagesRef.current = next;\n setMessages(next);\n });\n return unsub;\n }, [resolved]);\n\n return messages;\n};\n","/**\n * The stub {@link ClientSession} returned by the context-reader hooks when they\n * are skipped, when no provider is found, or when session construction failed.\n * Every member throws so a held-but-unusable session fails loudly rather than\n * silently no-ops. Generic so each consumer gets a session typed to its own\n * codec parameters without a cast — the throwing bodies satisfy any instantiation.\n */\n\nimport * as Ably from 'ably';\nimport type * as AblyObjects from 'ably/liveobjects';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../../core/codec/types.js';\nimport type { ClientSession, Tree, View } from '../../core/transport/types.js';\nimport { ErrorCode } from '../../errors.js';\n\n/**\n * Build the `hook is skipped` error for a stub member.\n * @param operation - The attempted operation, phrased for the `unable to <operation>; hook is skipped` message.\n * @returns The skipped-hook error.\n */\nconst skipped = (operation: string): Ably.ErrorInfo =>\n new Ably.ErrorInfo(`unable to ${operation}; hook is skipped`, ErrorCode.InvalidArgument, 400);\n\n/**\n * Create a throwing stub {@link ClientSession}. Held safely in state before a\n * provider resolves; any access throws {@link Ably.ErrorInfo}.\n * @returns A stub session whose every member throws.\n */\nexport const makeSkippedClientSession = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(): ClientSession<TInput, TOutput, TProjection, TMessage> => ({\n get tree(): Tree<TOutput, TProjection> {\n throw skipped('access tree');\n },\n get view(): View<TInput, TMessage> {\n throw skipped('access view');\n },\n get presence(): Ably.RealtimePresence {\n throw skipped('access presence');\n },\n get object(): AblyObjects.RealtimeObject {\n throw skipped('access object');\n },\n connect: () => {\n throw skipped('connect');\n },\n createView: (): View<TInput, TMessage> => {\n throw skipped('create view');\n },\n cancel: () => {\n throw skipped('cancel');\n },\n on: () => {\n throw skipped('subscribe');\n },\n close: () => {\n throw skipped('close');\n },\n});\n","/**\n * useClientSession — read a ClientSession from the nearest ClientSessionProvider.\n *\n * The session is created by {@link ClientSessionProvider}, which reads the Ably\n * Realtime client from the surrounding `<AblyProvider>`. This hook is a thin\n * context reader — it does not create or manage session state.\n *\n * **Provider lookup**\n * - Omit `channelName` to use the innermost `ClientSessionProvider` in the tree.\n * - Pass `channelName` to look up a specific provider by name.\n * - Pass `skip: true` to receive a stub session that throws on any access —\n * safe to hold in state before auth or other conditions are ready.\n *\n * **Error handling**\n * - When no matching provider is found, or when the provider's `createClientSession`\n * call threw, `sessionError` is set on the returned object instead of throwing.\n * The component can render an error state without an error boundary.\n * - Pass `onError` to receive post-construction session errors (e.g. send failures,\n * channel continuity loss) without wiring `session.on('error', ...)` manually.\n */\n\nimport * as Ably from 'ably';\nimport { useContext, useEffect, useRef } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { ClientSession } from '../core/transport/types.js';\nimport { ErrorCode } from '../errors.js';\nimport { ClientSessionContext } from './contexts/client-session-context.js';\nimport { makeSkippedClientSession } from './internal/skipped-session.js';\n\n/**\n * Return value of {@link useClientSession}.\n *\n * `session` is always a valid object. When `skip` is `true`, when no provider was\n * found, or when the provider's session construction failed, `session` is a stub\n * that throws {@link Ably.ErrorInfo} on every access.\n * Check `sessionError` before using `session` to avoid those throws.\n */\nexport interface ClientSessionHandle<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> {\n /**\n * The resolved session.\n *\n * A throwing stub when `skip` is `true`, when no matching {@link ClientSessionProvider}\n * was found in the tree, or when session construction failed.\n */\n session: ClientSession<TInput, TOutput, TProjection, TMessage>;\n /**\n * Set when no matching {@link ClientSessionProvider} was found, when session\n * construction failed, and `skip` is `false`.\n * `undefined` when the session resolved successfully or when `skip` is `true`.\n */\n sessionError?: Ably.ErrorInfo | undefined;\n}\n\n/**\n * Read a {@link ClientSession} from the nearest {@link ClientSessionProvider}.\n *\n * Returns `{ session, sessionError }`. When no provider is found or session\n * construction failed, `sessionError` is set and `session` is a stub that throws\n * on access — the hook never throws during render.\n *\n * Pass `onError` to subscribe to post-construction session errors\n * (e.g. {@link ErrorCode.SessionSendFailed}, {@link ErrorCode.ChannelContinuityLost})\n * without calling `session.on('error', …)` manually. The subscription is\n * created when the session resolves and removed on unmount.\n * @param props - Hook options.\n * @param props.channelName - Look up a specific provider by channel name; omit for the nearest.\n * @param props.skip - When `true`, return the stub session immediately without resolving a provider slot.\n * @param props.onError - Called whenever the resolved session emits an error event.\n * @returns `{ session, sessionError }`.\n */\nexport const useClientSession = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>({\n channelName,\n skip,\n onError,\n}: {\n /**\n * Channel name passed to the enclosing {@link ClientSessionProvider}.\n * Omit to use the nearest provider in the tree.\n */\n channelName?: string;\n /**\n * When `true`, skip context lookup and return a stub session that throws on\n * any access. Use when a condition (auth, feature flag) is not yet resolved.\n */\n skip?: boolean;\n /**\n * Called whenever the resolved session emits an error event.\n * The subscription is established once the session resolves and\n * automatically removed on unmount or when the session changes.\n */\n onError?: (error: Ably.ErrorInfo) => void;\n} = {}): ClientSessionHandle<TInput, TOutput, TProjection, TMessage> => {\n const { nearest: nearestSlot, providers } = useContext(ClientSessionContext);\n const errorCallbackRef = useRef(onError);\n errorCallbackRef.current = onError;\n\n // Compute the session for the onError subscription *before* any conditional\n // returns to satisfy React's rules of hooks (no hooks in branches).\n // Erased generics — this local is only used in the useEffect below.\n const resolvedForEffect: ClientSession<CodecInputEvent, CodecOutputEvent, unknown, unknown> | undefined = skip\n ? undefined\n : channelName === undefined\n ? nearestSlot?.session\n : providers[channelName]?.session;\n\n useEffect(() => {\n if (!resolvedForEffect) return;\n return resolvedForEffect.on('error', (errorInfo: Ably.ErrorInfo) => {\n errorCallbackRef.current?.(errorInfo);\n });\n }, [resolvedForEffect]);\n\n if (skip) {\n return {\n session: makeSkippedClientSession<TInput, TOutput, TProjection, TMessage>(),\n };\n }\n\n if (channelName !== undefined) {\n const slot = providers[channelName];\n if (slot) {\n if (slot.session) {\n // CAST: ClientSessionContext stores sessions with erased generics.\n // The caller is responsible for using type parameters matching those of the ClientSessionProvider.\n return {\n session: slot.session as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n };\n }\n // Provider exists but construction failed.\n return {\n session: makeSkippedClientSession<TInput, TOutput, TProjection, TMessage>(),\n sessionError: slot.sessionError,\n };\n }\n return {\n session: makeSkippedClientSession<TInput, TOutput, TProjection, TMessage>(),\n sessionError: new Ably.ErrorInfo(\n `unable to use session; no ClientSessionProvider found for channelName \"${channelName}\"`,\n ErrorCode.BadRequest,\n 400,\n ),\n };\n }\n\n if (nearestSlot) {\n if (nearestSlot.session) {\n // CAST: ClientSessionContext stores session with erased generics; types fixed at call site.\n return {\n session: nearestSlot.session as unknown as ClientSession<TInput, TOutput, TProjection, TMessage>,\n };\n }\n // Nearest provider exists but construction failed.\n return {\n session: makeSkippedClientSession<TInput, TOutput, TProjection, TMessage>(),\n sessionError: nearestSlot.sessionError,\n };\n }\n\n return {\n session: makeSkippedClientSession<TInput, TOutput, TProjection, TMessage>(),\n sessionError: new Ably.ErrorInfo(\n 'unable to use session; no ClientSessionProvider found in the tree',\n ErrorCode.BadRequest,\n 400,\n ),\n };\n};\n","/**\n * useView — reactive paginated view of the conversation.\n *\n * Subscribes to view updates and exposes the visible messages, msg-anchored\n * branch navigation, write operations, pagination state, and a `loadOlder`\n * callback. Pass `session` to use a session's default view, or `view` to\n * subscribe to a specific {@link View} directly. When both are omitted,\n * defaults to the nearest {@link ClientSessionProvider}'s session via context.\n */\n\nimport * as Ably from 'ably';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport type { CodecInputEvent, CodecMessage, CodecOutputEvent } from '../core/codec/types.js';\nimport type { ActiveRun, BranchSelection, RunInfo, SendOptions, View } from '../core/transport/types.js';\nimport { ErrorCode } from '../errors.js';\nimport type { BaseSessionOption } from './internal/use-resolved-session.js';\nimport { useResolvedSession } from './internal/use-resolved-session.js';\n\n/** Options for {@link useView}. */\nexport interface UseViewOptions<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> extends BaseSessionOption<TInput, TOutput, TProjection, TMessage> {\n /** A specific {@link View} to subscribe to directly. Takes priority over `session`. */\n view?: View<TInput, TMessage> | null;\n /** Number of older codecMessages to reveal per page (exactly `limit`, fewer only at the end of history). When provided, auto-loads the first page on mount. */\n limit?: number;\n /** When `true`, skip all subscriptions and return an empty handle immediately. */\n skip?: boolean;\n}\n\n/** Handle for the paginated, branch-aware conversation view. */\nexport interface ViewHandle<TInput extends CodecInputEvent, TMessage> {\n /**\n * The visible messages along the selected branch, concatenated across all\n * visible Runs, each paired with its codec-message-id (see\n * {@link CodecMessage}). Read the domain object from each entry's\n * `message` field.\n *\n * Correlate a rendered message back to the View — `runOf`,\n * `branchSelection`, `selectSibling`, `regenerate`, or `edit` — via its\n * `codecMessageId`, which the SDK assigns and tracks independently of any\n * identity the domain `message` may carry. See {@link View.getMessages}.\n */\n messages: CodecMessage<TMessage>[];\n /** Whether there are older messages that can be revealed via `loadOlder`. */\n hasOlder: boolean;\n /** Whether a page load is currently in progress. */\n loading: boolean;\n /**\n * Set when the most recent `loadOlder` call failed.\n * Cleared automatically on the next successful load.\n * `undefined` when no error has occurred or when `skip` is `true`.\n */\n loadError: Ably.ErrorInfo | undefined;\n /**\n * Load older messages into the view. No-op if already loading.\n * On failure, `loadError` is set; on success, `loadError` is cleared.\n */\n loadOlder: () => Promise<void>;\n /**\n * Look up the {@link RunInfo} for the Run that owns `codecMessageId`.\n * Returns `undefined` when the codec-message-id hasn't been observed.\n * See {@link View.runOf}.\n */\n runOf: (codecMessageId: string) => RunInfo | undefined;\n /**\n * Direct lookup by runId. Returns `undefined` when the Run hasn't been\n * observed. See {@link View.run}.\n */\n run: (runId: string) => RunInfo | undefined;\n /**\n * Snapshot of the visible Runs along the selected branch, in\n * chronological order. Returns `[]` when the view isn't resolved.\n * See {@link View.runs}.\n */\n runs: () => RunInfo[];\n /**\n * Resolve the {@link BranchSelection} bundle anchored at\n * `codecMessageId`. Always returns a safe object — see\n * {@link BranchSelection}. See {@link View.branchSelection}.\n */\n branchSelection: (codecMessageId: string) => BranchSelection<TMessage>;\n /**\n * Select a sibling at the branch point anchored at `codecMessageId`.\n * `index` is clamped to `[0, siblings.length - 1]`. Silent no-op when\n * `codecMessageId` isn't a branch anchor. See {@link View.selectSibling}.\n */\n selectSibling: (codecMessageId: string, index: number) => void;\n /**\n * Send one or more TInputs on the channel and fire a POST. See {@link View.send}.\n * @throws Ably.ErrorInfo with code {@link ErrorCode.InvalidArgument} when no view is resolved (before the session is available, or when `skip` is `true`).\n */\n send: (events: TInput | TInput[], options?: SendOptions) => Promise<ActiveRun>;\n /**\n * Regenerate an assistant message, using this view's branch for history.\n * @throws Ably.ErrorInfo with code {@link ErrorCode.InvalidArgument} when no view is resolved (before the session is available, or when `skip` is `true`).\n */\n regenerate: (messageId: string, options?: SendOptions) => Promise<ActiveRun>;\n /**\n * Edit a user message, forking from this view's branch.\n * Rejects with an `Ably.ErrorInfo` (code {@link ErrorCode.InvalidArgument}) if no view is resolved — e.g. before the session is available, or when `skip` is `true`.\n */\n edit: (messageId: string, inputs: TInput | TInput[], options?: SendOptions) => Promise<ActiveRun>;\n}\n\n/**\n * Fallback returned by `branchSelection` when the view isn't resolved.\n * Same shape the view returns for an unknown codec-message-id, so callers\n * can destructure uniformly.\n */\nconst EMPTY_BRANCH_SELECTION: BranchSelection<never> = {\n hasSiblings: false,\n siblings: [],\n index: 0,\n selected: undefined,\n};\n\n/**\n * Subscribe to a view and return the visible messages with pagination, navigation, and write operations.\n *\n * `view` takes priority over `session`. When neither is provided, the nearest\n * {@link ClientSessionProvider}'s session is used. When `limit` is provided, auto-loads\n * the first page on mount (SWR-style).\n * @param props - Options for selecting the view source and configuring auto-load.\n * @param props.session - Client session whose default view to subscribe to; defaults to the nearest provider.\n * @param props.view - A specific {@link View} to subscribe to directly. Takes priority over `session`.\n * @param props.limit - Number of older codecMessages to reveal per page (exactly `limit`, fewer only at end of history); when provided, auto-loads the first page on mount.\n * @param props.skip - When `true`, skip all subscriptions and return an empty handle.\n * @returns A {@link ViewHandle} with messages, pagination state, navigation, write operations, and loadOlder.\n */\nexport const useView = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>({\n session,\n view,\n limit,\n skip,\n}: UseViewOptions<TInput, TOutput, TProjection, TMessage> = {}): ViewHandle<TInput, TMessage> => {\n const resolvedSession = useResolvedSession({ session, skip });\n const resolvedView = skip ? undefined : (view ?? resolvedSession?.view);\n\n const [messages, setMessages] = useState<CodecMessage<TMessage>[]>(() => resolvedView?.getMessages() ?? []);\n const [hasOlder, setHasOlder] = useState(() => resolvedView?.hasOlder() ?? false);\n const [loading, setLoading] = useState(false);\n const [loadError, setLoadError] = useState<Ably.ErrorInfo | undefined>();\n const loadingRef = useRef(false);\n\n // Auto-load first page on mount when limit is provided (SWR-style).\n // Fires once per view instance — subsequent changes to limit\n // only affect manual loadOlder() calls, not the initial auto-load.\n const autoLoad = limit !== undefined;\n const autoLoadedRef = useRef(false);\n\n // Subscribe to view updates\n useEffect(() => {\n if (!resolvedView) {\n setMessages([]);\n setHasOlder(false);\n setLoadError(undefined);\n return;\n }\n\n // Reset auto-load flag so the new view gets its first page loaded\n autoLoadedRef.current = false;\n\n // Sync initial state\n setMessages(resolvedView.getMessages());\n setHasOlder(resolvedView.hasOlder());\n setLoadError(undefined);\n\n const unsub = resolvedView.on('update', () => {\n setMessages(resolvedView.getMessages());\n setHasOlder(resolvedView.hasOlder());\n });\n return unsub;\n }, [resolvedView]);\n\n const loadOlder = useCallback(async () => {\n if (!resolvedView || loadingRef.current) return;\n loadingRef.current = true;\n setLoading(true);\n try {\n await resolvedView.loadOlder(limit);\n setLoadError(undefined);\n } catch (error) {\n if (error instanceof Ably.ErrorInfo) {\n setLoadError(error);\n } else {\n setLoadError(new Ably.ErrorInfo('Unknown error loading older messages', ErrorCode.BadRequest, 400));\n }\n } finally {\n loadingRef.current = false;\n setLoading(false);\n }\n }, [resolvedView, limit]);\n\n useEffect(() => {\n if (!autoLoad || autoLoadedRef.current || !resolvedView) return;\n autoLoadedRef.current = true;\n void loadOlder();\n }, [autoLoad, resolvedView, loadOlder]);\n\n // Run lookups\n const runOf = useCallback(\n (codecMessageId: string): RunInfo | undefined => resolvedView?.runOf(codecMessageId),\n [resolvedView],\n );\n\n const run = useCallback((runId: string): RunInfo | undefined => resolvedView?.run(runId), [resolvedView]);\n\n const runs = useCallback((): RunInfo[] => resolvedView?.runs() ?? [], [resolvedView]);\n\n // Branch navigation\n const branchSelection = useCallback(\n (codecMessageId: string): BranchSelection<TMessage> =>\n // CAST: `EMPTY_BRANCH_SELECTION` is typed `BranchSelection<never>`; `never` is\n // assignable to any `TMessage`, so the empty bundle is a valid fallback for\n // the not-yet-resolved view case.\n resolvedView?.branchSelection(codecMessageId) ?? (EMPTY_BRANCH_SELECTION as BranchSelection<TMessage>),\n [resolvedView],\n );\n\n const selectSibling = useCallback(\n (codecMessageId: string, index: number) => {\n resolvedView?.selectSibling(codecMessageId, index);\n },\n [resolvedView],\n );\n\n // Write operation callbacks\n const send = useCallback(\n async (events: TInput | TInput[], opts?: SendOptions) => {\n if (!resolvedView)\n throw new Ably.ErrorInfo('unable to send; view is not available', ErrorCode.InvalidArgument, 400);\n return resolvedView.send(events, opts);\n },\n [resolvedView],\n );\n\n const regenerate = useCallback(\n async (messageId: string, opts?: SendOptions) => {\n if (!resolvedView)\n throw new Ably.ErrorInfo('unable to regenerate; view is not available', ErrorCode.InvalidArgument, 400);\n return resolvedView.regenerate(messageId, opts);\n },\n [resolvedView],\n );\n\n const edit = useCallback(\n async (messageId: string, inputs: TInput | TInput[], opts?: SendOptions) => {\n if (!resolvedView)\n throw new Ably.ErrorInfo('unable to edit; view is not available', ErrorCode.InvalidArgument, 400);\n return resolvedView.edit(messageId, inputs, opts);\n },\n [resolvedView],\n );\n\n return {\n messages,\n hasOlder,\n loading,\n loadError,\n loadOlder,\n runOf,\n run,\n runs,\n branchSelection,\n selectSibling,\n send,\n regenerate,\n edit,\n };\n};\n","/**\n * useCreateView — create an independent view with the same API as useView.\n *\n * Calls {@link ClientSession.createView} to create an independent view over\n * the same conversation tree, then subscribes to it exactly like\n * {@link useView}. The view is closed automatically on unmount or when the\n * session reference changes.\n *\n * Pass `null` or omit `session` to defer creation (e.g. when a split pane is\n * collapsed). The returned handle has empty state until a session is provided.\n * When `session` is omitted entirely, defaults to the nearest\n * {@link ClientSessionProvider}'s session via context.\n * Pass `skip: true` to bypass all context reads and view creation entirely.\n */\n\nimport { useEffect, useState } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { View } from '../core/transport/types.js';\nimport type { BaseSessionOption } from './internal/use-resolved-session.js';\nimport { useResolvedSession } from './internal/use-resolved-session.js';\nimport type { ViewHandle } from './use-view.js';\nimport { useView } from './use-view.js';\n\n/** Options for {@link useCreateView}. */\nexport interface UseCreateViewOptions<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> extends BaseSessionOption<TInput, TOutput, TProjection, TMessage> {\n /** When provided, auto-loads the first page on mount. Omit for manual load. */\n limit?: number;\n /** When `true`, skip view creation and return an empty handle immediately. */\n skip?: boolean;\n}\n\n/**\n * Create an independent {@link View} and subscribe to it.\n * Returns the same {@link ViewHandle} as {@link useView}, but backed by a\n * newly created view with its own branch selections and pagination state.\n * The view is closed on unmount or when the session changes.\n * When `session` is omitted, uses the nearest {@link ClientSessionProvider}'s session via context.\n * @param props - Options including optional `session`, `limit` for auto-load, and `skip`.\n * @param props.session - Session to create a view from; defaults to the nearest provider.\n * @param props.limit - Max older messages per page; when provided, auto-loads on mount.\n * @param props.skip - When `true`, skip view creation and return an empty handle.\n * @returns A {@link ViewHandle} with nodes, pagination, navigation, and write operations.\n */\nexport const useCreateView = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>({\n session,\n limit,\n skip,\n}: UseCreateViewOptions<TInput, TOutput, TProjection, TMessage> = {}): ViewHandle<TInput, TMessage> => {\n const resolved = useResolvedSession({ session, skip });\n\n const [view, setView] = useState<View<TInput, TMessage> | undefined>();\n\n useEffect(() => {\n if (!resolved) {\n setView(undefined);\n return;\n }\n const v = resolved.createView();\n setView(v);\n return () => {\n v.close();\n };\n }, [resolved]);\n\n return useView({ view, limit, skip });\n};\n","/**\n * useTree — stable structural query callbacks for a ClientSession's tree.\n *\n * Returns a {@link TreeHandle} with methods to inspect the tree structure.\n * These are thin `useCallback` wrappers around `session.tree` — no local\n * state or subscriptions. Branch navigation (select, getSelectedIndex) is\n * on {@link ViewHandle} from {@link useView}.\n *\n * When `session` is omitted, defaults to the nearest\n * {@link ClientSessionProvider}'s session via context.\n */\n\nimport { useCallback } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { ConversationNode, RunNode } from '../core/transport/types.js';\nimport type { BaseSessionOption } from './internal/use-resolved-session.js';\nimport { useResolvedSession } from './internal/use-resolved-session.js';\n\n/** Handle for querying the conversation tree structure. */\nexport interface TreeHandle<TProjection> {\n /**\n * Get the RunNode for `runId`, or undefined if no node is keyed by `runId`\n * (or the keyed node is an input node, not a reply run).\n */\n getRunNode: (runId: string) => RunNode<TProjection> | undefined;\n /**\n * Get the node that owns a given codec-message-id, or undefined if not\n * observed. Returns a {@link ConversationNode} union — narrow on `kind`\n * (`'input'` vs `'run'`) before reading kind-specific fields.\n */\n getNodeByCodecMessageId: (codecMessageId: string) => ConversationNode<TProjection> | undefined;\n /**\n * Get the sibling group (both kinds) the node keyed by `key` belongs to —\n * edit versions for an input node, regenerate runs for a reply run — ordered\n * oldest-first. A single-element array when the node has no siblings; empty\n * when `key` is unknown. `key` is a {@link RunNode.runId} or an\n * {@link InputNode.codecMessageId}.\n */\n getSiblingNodes: (key: string) => ConversationNode<TProjection>[];\n}\n\n/** Options for {@link useTree}. */\nexport type UseTreeOptions<\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n> = BaseSessionOption<TInput, TOutput, TProjection, TMessage>;\n\n/**\n * Provide stable structural query callbacks backed by the session's tree.\n * When `session` is omitted, uses the nearest {@link ClientSessionProvider}'s session via context.\n * @param props - Options including optional `session`.\n * @param props.session - Session to read tree structure from; defaults to the nearest provider.\n * @returns A {@link TreeHandle} with structural query methods.\n */\nexport const useTree = <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>({\n session,\n}: UseTreeOptions<TInput, TOutput, TProjection, TMessage> = {}): TreeHandle<TProjection> => {\n const resolved = useResolvedSession({ session });\n\n const getRunNode = useCallback(\n (runId: string): RunNode<TProjection> | undefined => resolved?.tree.getRunNode(runId),\n [resolved],\n );\n\n const getNodeByCodecMessageId = useCallback(\n (codecMessageId: string): ConversationNode<TProjection> | undefined =>\n resolved?.tree.getNodeByCodecMessageId(codecMessageId),\n [resolved],\n );\n\n const getSiblingNodes = useCallback(\n (key: string): ConversationNode<TProjection>[] => resolved?.tree.getSiblingNodes(key) ?? [],\n [resolved],\n );\n\n return {\n getRunNode,\n getNodeByCodecMessageId,\n getSiblingNodes,\n };\n};\n","/**\n * createSessionHooks: factory that captures the codec's type parameters once and\n * returns a bundle of type-safe hooks + ClientSessionProvider. Hook call sites need\n * no type parameters at every use — just call the hooks directly.\n * @example\n * // Once per app (e.g. in a shared session.ts):\n * export const {\n * ClientSessionProvider,\n * useClientSession,\n * useView,\n * } = createSessionHooks<VercelInput, VercelOutput, VercelProjection, UIMessage>();\n *\n * // In page:\n * <ClientSessionProvider channelName=\"ai:demo\" codec={UIMessageCodec}>\n * <Chat />\n * </ClientSessionProvider>\n *\n * // In Chat — no type params needed, session is implicit from nearest provider:\n * const { nodes } = useView({ limit: 30 });\n */\n\nimport type * as Ably from 'ably';\nimport type { ComponentType } from 'react';\n\nimport type { CodecInputEvent, CodecOutputEvent } from '../core/codec/types.js';\nimport type { ClientSession, View } from '../core/transport/types.js';\nimport type { ClientSessionProviderProps } from './contexts/client-session-provider.js';\nimport { ClientSessionProvider as _ClientSessionProvider } from './contexts/client-session-provider.js';\nimport { useAblyMessages as _useAblyMessages } from './use-ably-messages.js';\nimport type { ClientSessionHandle } from './use-client-session.js';\nimport { useClientSession as _useClientSession } from './use-client-session.js';\nimport { useCreateView as _useCreateView } from './use-create-view.js';\nimport type { TreeHandle } from './use-tree.js';\nimport { useTree as _useTree } from './use-tree.js';\nimport type { ViewHandle } from './use-view.js';\nimport { useView as _useView } from './use-view.js';\n\n/**\n * Bundle of type-safe hooks and provider returned by {@link createSessionHooks}.\n *\n * The codec's `TInput`, `TOutput`, `TProjection`, and `TMessage` are baked in at\n * factory creation time so no type params are needed at hook call sites.\n */\nexport interface SessionHooks<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage> {\n /**\n * `ClientSessionProvider` narrowed to the codec's `TInput`/`TOutput`/`TMessage`. No JSX type params needed.\n */\n ClientSessionProvider: ComponentType<ClientSessionProviderProps<TInput, TOutput, TProjection, TMessage>>;\n /**\n * Read the session from context. No type params needed.\n *\n * Returns `{ session, sessionError }`. When no provider is found (or session\n * construction failed), `sessionError` is set and `session` is a stub that\n * throws on access — the hook never throws during render.\n *\n * Pass `onError` to subscribe to post-construction session errors\n * (e.g. send failures, channel continuity loss) without wiring\n * `session.on('error', …)` manually.\n */\n useClientSession: (props?: {\n /** Channel name to look up; omit to use the nearest {@link ClientSessionProvider}. */\n channelName?: string;\n /** When `true`, return a stub session that throws on any access. */\n skip?: boolean;\n /** Called whenever the resolved session emits an error event. */\n onError?: (error: Ably.ErrorInfo) => void;\n }) => ClientSessionHandle<TInput, TOutput, TProjection, TMessage>;\n /**\n * Subscribe to the nearest session's view and return the visible message list with pagination.\n * Pass `session` to use a session's default view, `view` to subscribe to a specific view\n * directly. Pass `limit` to auto-load on mount. Pass `skip: true` for an empty handle.\n */\n useView: (props?: {\n /** Client session whose default view to subscribe to; defaults to the nearest {@link ClientSessionProvider}. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage> | null;\n /** A specific {@link View} to subscribe to directly. Takes priority over `session`. */\n view?: View<TInput, TMessage> | null;\n /** When provided, auto-loads the first page on mount. */\n limit?: number;\n /** When `true`, skip all subscriptions and return an empty handle. */\n skip?: boolean;\n }) => ViewHandle<TInput, TMessage>;\n /**\n * Navigate conversation branches in the session tree.\n * Pass `session` to override; defaults to the nearest {@link ClientSessionProvider}.\n */\n useTree: (props?: {\n /** Override session; defaults to the nearest {@link ClientSessionProvider}. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage>;\n }) => TreeHandle<TProjection>;\n /**\n * Subscribe to raw Ably messages on the session channel.\n * Pass `session` to override; defaults to the nearest {@link ClientSessionProvider}.\n * Pass `skip: true` to return an empty array without subscribing.\n */\n useAblyMessages: (props?: {\n /** Override session; defaults to the nearest {@link ClientSessionProvider}. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage>;\n /** When `true`, skip all subscriptions and return an empty array. */\n skip?: boolean;\n }) => Ably.InboundMessage[];\n /**\n * Create an independent view over the same tree.\n * Pass `session` to override; defaults to the nearest {@link ClientSessionProvider}.\n * Pass `skip: true` to return an empty handle without creating a view.\n */\n useCreateView: (props?: {\n /** Override session; defaults to the nearest {@link ClientSessionProvider}. */\n session?: ClientSession<TInput, TOutput, TProjection, TMessage> | null;\n /** When provided, auto-loads the first page on mount. */\n limit?: number;\n /** When `true`, skip view creation and return an empty handle. */\n skip?: boolean;\n }) => ViewHandle<TInput, TMessage>;\n}\n\n/**\n * Create a bundle of type-safe hooks and provider for a given codec's\n * `TInput`/`TOutput`/`TProjection`/`TMessage`.\n *\n * These type parameters are captured at factory creation time; hook call sites need\n * no type parameters. The returned hooks are thin wrappers around the standalone hooks\n * with the types resolved.\n * @returns A {@link SessionHooks} bundle.\n */\nexport const createSessionHooks = <\n TInput extends CodecInputEvent,\n TOutput extends CodecOutputEvent,\n TProjection,\n TMessage,\n>(): SessionHooks<TInput, TOutput, TProjection, TMessage> => ({\n // CAST: ClientSessionProvider is generic; factory narrows it to the codec's TInput/TOutput/TProjection/TMessage.\n ClientSessionProvider: _ClientSessionProvider as ComponentType<\n ClientSessionProviderProps<TInput, TOutput, TProjection, TMessage>\n >,\n useClientSession: (props) => _useClientSession<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n useView: (props) => _useView<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n useTree: (props) => _useTree<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n useAblyMessages: (props) => _useAblyMessages<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n useCreateView: (props) => _useCreateView<TInput, TOutput, TProjection, TMessage>(props ?? {}),\n});\n"],"mappings":"07BAkCA,IAAa,EAA8C,CACzD,UACA,YACA,WACA,qBACA,oBACF,EAQa,EAA4C,CAAC,mBAAoB,gBAAgB,EAOxF,EAA0C,CAC9C,UACA,YACA,WACA,qBACA,iBACA,mBACA,qBACA,sBACF,EAkBa,EAAuB,GAA6E,CAC/G,GAAI,IAAe,IAAA,IAAa,EAAW,SAAW,EAAG,OACzD,IAAM,EAAY,IAAI,IAAsB,CAAC,GAAG,EAAgB,GAAG,CAAU,CAAC,EACxE,EAAU,EAAW,OAAQ,GAAS,EAAU,IAAI,CAAI,CAAC,EACzD,EAAU,CAAC,GAAG,CAAS,EAAE,OAAQ,GAAS,CAAC,EAAW,SAAS,CAAI,CAAC,EAAE,SAAS,EACrF,MAAO,CAAC,GAAG,EAAS,GAAG,CAAO,CAChC,ECvFa,EAAU,QCkBjB,EAAW,kBASX,GACJ,EAIA,IACkC,CAClC,IAAM,EAAW,EAEjB,MADA,GAAS,QAAQ,OAAS,CAAE,GAAG,EAAS,QAAQ,OAAQ,GAAG,CAAO,EAC3D,CAAE,OAAQ,CAAE,MAAO,EAAW,CAAM,CAAE,CAAE,CACjD,EAQM,EAAe,GAAqE,CACxF,IAAM,EAAa,GAAO,WACpB,EAAiC,EAAG,GAAW,CAAQ,EAE7D,OADI,IAAY,EAAO,GAAc,GAC9B,CACT,EAOM,EAAc,GAClB,OAAO,QAAQ,CAAM,EAClB,KAAK,CAAC,EAAM,KAAa,GAAG,EAAK,GAAG,GAAS,EAC7C,KAAK,GAAG,EAYA,GAAgB,GAAqD,EAAW,EAAY,CAAK,CAAC,EAelG,IACX,EACA,IACkC,EAAa,EAAQ,EAAY,CAAK,CAAC,EC3E9D,EAAgB,SAGhB,GAAgB,SAah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