@ably/ai-transport 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +91 -100
  2. package/dist/ably-ai-transport.js +1553 -1238
  3. package/dist/ably-ai-transport.js.map +1 -1
  4. package/dist/ably-ai-transport.umd.cjs +1 -1
  5. package/dist/ably-ai-transport.umd.cjs.map +1 -1
  6. package/dist/constants.d.ts +116 -42
  7. package/dist/core/agent.d.ts +29 -0
  8. package/dist/core/codec/decoder.d.ts +20 -23
  9. package/dist/core/codec/encoder.d.ts +11 -8
  10. package/dist/core/codec/index.d.ts +1 -2
  11. package/dist/core/codec/lifecycle-tracker.d.ts +10 -9
  12. package/dist/core/codec/types.d.ts +407 -115
  13. package/dist/core/transport/agent-session.d.ts +10 -0
  14. package/dist/core/transport/branch-chain.d.ts +43 -0
  15. package/dist/core/transport/client-session.d.ts +13 -0
  16. package/dist/core/transport/decode-fold.d.ts +47 -0
  17. package/dist/core/transport/headers.d.ts +96 -18
  18. package/dist/core/transport/index.d.ts +5 -6
  19. package/dist/core/transport/internal/bounded-map.d.ts +20 -0
  20. package/dist/core/transport/invocation.d.ts +74 -0
  21. package/dist/core/transport/load-conversation.d.ts +128 -0
  22. package/dist/core/transport/load-history.d.ts +39 -0
  23. package/dist/core/transport/pipe-stream.d.ts +9 -9
  24. package/dist/core/transport/run-manager.d.ts +78 -0
  25. package/dist/core/transport/tree.d.ts +373 -109
  26. package/dist/core/transport/types/agent.d.ts +353 -0
  27. package/dist/core/transport/types/client.d.ts +168 -0
  28. package/dist/core/transport/types/shared.d.ts +24 -0
  29. package/dist/core/transport/types/tree.d.ts +315 -0
  30. package/dist/core/transport/types/view.d.ts +222 -0
  31. package/dist/core/transport/types.d.ts +13 -553
  32. package/dist/core/transport/view.d.ts +272 -84
  33. package/dist/errors.d.ts +21 -10
  34. package/dist/index.d.ts +6 -8
  35. package/dist/logger.d.ts +12 -0
  36. package/dist/react/ably-ai-transport-react.js +976 -990
  37. package/dist/react/ably-ai-transport-react.js.map +1 -1
  38. package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
  39. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
  40. package/dist/react/contexts/client-session-context.d.ts +36 -0
  41. package/dist/react/contexts/client-session-provider.d.ts +53 -0
  42. package/dist/react/create-session-hooks.d.ts +116 -0
  43. package/dist/react/index.d.ts +12 -12
  44. package/dist/react/internal/use-resolved-session.d.ts +36 -0
  45. package/dist/react/use-ably-messages.d.ts +17 -14
  46. package/dist/react/use-client-session.d.ts +81 -0
  47. package/dist/react/use-create-view.d.ts +14 -13
  48. package/dist/react/use-tree.d.ts +30 -15
  49. package/dist/react/use-view.d.ts +82 -51
  50. package/dist/utils.d.ts +32 -23
  51. package/dist/vercel/ably-ai-transport-vercel.js +2573 -2086
  52. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
  53. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
  54. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
  55. package/dist/vercel/codec/decoder.d.ts +5 -18
  56. package/dist/vercel/codec/encoder.d.ts +6 -36
  57. package/dist/vercel/codec/events.d.ts +51 -0
  58. package/dist/vercel/codec/index.d.ts +24 -12
  59. package/dist/vercel/codec/reducer.d.ts +144 -0
  60. package/dist/vercel/codec/tool-transitions.d.ts +2 -2
  61. package/dist/vercel/index.d.ts +4 -5
  62. package/dist/vercel/react/ably-ai-transport-vercel-react.js +3907 -3266
  63. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
  64. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +33 -8
  65. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
  66. package/dist/vercel/react/contexts/chat-transport-context.d.ts +7 -6
  67. package/dist/vercel/react/contexts/chat-transport-provider.d.ts +53 -41
  68. package/dist/vercel/react/index.d.ts +1 -2
  69. package/dist/vercel/react/use-chat-transport.d.ts +30 -26
  70. package/dist/vercel/react/use-message-sync.d.ts +17 -30
  71. package/dist/vercel/run-end-reason.d.ts +29 -0
  72. package/dist/vercel/transport/chat-transport.d.ts +43 -24
  73. package/dist/vercel/transport/index.d.ts +25 -21
  74. package/dist/vercel/transport/run-output-stream.d.ts +56 -0
  75. package/dist/version.d.ts +2 -0
  76. package/package.json +30 -23
  77. package/src/constants.ts +124 -51
  78. package/src/core/agent.ts +68 -0
  79. package/src/core/codec/decoder.ts +71 -98
  80. package/src/core/codec/encoder.ts +113 -65
  81. package/src/core/codec/index.ts +13 -6
  82. package/src/core/codec/lifecycle-tracker.ts +10 -9
  83. package/src/core/codec/types.ts +436 -120
  84. package/src/core/transport/agent-session.ts +1344 -0
  85. package/src/core/transport/branch-chain.ts +58 -0
  86. package/src/core/transport/client-session.ts +775 -0
  87. package/src/core/transport/decode-fold.ts +91 -0
  88. package/src/core/transport/headers.ts +181 -22
  89. package/src/core/transport/index.ts +25 -26
  90. package/src/core/transport/internal/bounded-map.ts +27 -0
  91. package/src/core/transport/invocation.ts +98 -0
  92. package/src/core/transport/load-conversation.ts +355 -0
  93. package/src/core/transport/load-history.ts +269 -0
  94. package/src/core/transport/pipe-stream.ts +54 -39
  95. package/src/core/transport/run-manager.ts +249 -0
  96. package/src/core/transport/tree.ts +926 -308
  97. package/src/core/transport/types/agent.ts +407 -0
  98. package/src/core/transport/types/client.ts +211 -0
  99. package/src/core/transport/types/shared.ts +27 -0
  100. package/src/core/transport/types/tree.ts +344 -0
  101. package/src/core/transport/types/view.ts +259 -0
  102. package/src/core/transport/types.ts +13 -706
  103. package/src/core/transport/view.ts +864 -433
  104. package/src/errors.ts +22 -9
  105. package/src/event-emitter.ts +3 -2
  106. package/src/index.ts +52 -41
  107. package/src/logger.ts +14 -1
  108. package/src/react/contexts/client-session-context.ts +41 -0
  109. package/src/react/contexts/client-session-provider.tsx +186 -0
  110. package/src/react/create-session-hooks.ts +141 -0
  111. package/src/react/index.ts +23 -13
  112. package/src/react/internal/use-resolved-session.ts +63 -0
  113. package/src/react/use-ably-messages.ts +32 -22
  114. package/src/react/use-client-session.ts +201 -0
  115. package/src/react/use-create-view.ts +33 -29
  116. package/src/react/use-tree.ts +61 -30
  117. package/src/react/use-view.ts +139 -97
  118. package/src/utils.ts +63 -45
  119. package/src/vercel/codec/decoder.ts +336 -258
  120. package/src/vercel/codec/encoder.ts +343 -205
  121. package/src/vercel/codec/events.ts +87 -0
  122. package/src/vercel/codec/index.ts +60 -13
  123. package/src/vercel/codec/reducer.ts +977 -0
  124. package/src/vercel/codec/tool-transitions.ts +2 -2
  125. package/src/vercel/index.ts +6 -19
  126. package/src/vercel/react/contexts/chat-transport-context.ts +7 -6
  127. package/src/vercel/react/contexts/chat-transport-provider.tsx +87 -59
  128. package/src/vercel/react/index.ts +3 -5
  129. package/src/vercel/react/use-chat-transport.ts +47 -49
  130. package/src/vercel/react/use-message-sync.ts +80 -39
  131. package/src/vercel/run-end-reason.ts +78 -0
  132. package/src/vercel/transport/chat-transport.ts +392 -98
  133. package/src/vercel/transport/index.ts +39 -38
  134. package/src/vercel/transport/run-output-stream.ts +170 -0
  135. package/src/version.ts +2 -0
  136. package/dist/core/transport/client-transport.d.ts +0 -10
  137. package/dist/core/transport/decode-history.d.ts +0 -43
  138. package/dist/core/transport/server-transport.d.ts +0 -7
  139. package/dist/core/transport/stream-router.d.ts +0 -29
  140. package/dist/core/transport/turn-manager.d.ts +0 -37
  141. package/dist/react/contexts/transport-context.d.ts +0 -31
  142. package/dist/react/contexts/transport-provider.d.ts +0 -49
  143. package/dist/react/create-transport-hooks.d.ts +0 -124
  144. package/dist/react/use-active-turns.d.ts +0 -12
  145. package/dist/react/use-client-transport.d.ts +0 -80
  146. package/dist/vercel/codec/accumulator.d.ts +0 -21
  147. package/dist/vercel/react/use-staged-add-tool-approval-response.d.ts +0 -30
  148. package/dist/vercel/tool-approvals.d.ts +0 -124
  149. package/dist/vercel/tool-events.d.ts +0 -26
  150. package/src/core/transport/client-transport.ts +0 -977
  151. package/src/core/transport/decode-history.ts +0 -485
  152. package/src/core/transport/server-transport.ts +0 -612
  153. package/src/core/transport/stream-router.ts +0 -136
  154. package/src/core/transport/turn-manager.ts +0 -165
  155. package/src/react/contexts/transport-context.ts +0 -37
  156. package/src/react/contexts/transport-provider.tsx +0 -164
  157. package/src/react/create-transport-hooks.ts +0 -144
  158. package/src/react/use-active-turns.ts +0 -72
  159. package/src/react/use-client-transport.ts +0 -197
  160. package/src/vercel/codec/accumulator.ts +0 -588
  161. package/src/vercel/react/use-staged-add-tool-approval-response.ts +0 -87
  162. package/src/vercel/tool-approvals.ts +0 -380
  163. package/src/vercel/tool-events.ts +0 -53
@@ -1,171 +1,435 @@
1
1
  import { Logger } from '../../logger.js';
2
- import { MessageNode, Tree, TurnLifecycleEvent } from './types.js';
2
+ import { CodecInputEvent, CodecOutputEvent, Reducer } from '../codec/types.js';
3
+ import { ConversationNode, OutputEvent, RunLifecycleEvent, RunNode, Tree } from './types.js';
3
4
  /**
4
- * Tree — materializes a branching conversation from a flat
5
- * oplog of Ably messages using serial-first ordering.
5
+ * Tree — materializes a branching conversation as a forest of nodes. Each turn
6
+ * is two nodes: a user {@link InputNode} keyed by its client-owned
7
+ * codec-message-id and an agent {@link RunNode} keyed by the agent-minted
8
+ * run-id, parented to the input node.
6
9
  *
7
- * Serial order (the total order assigned by Ably) is the primary mechanism
8
- * for linear message sequences. `x-ably-parent` and `x-ably-fork-of` headers
9
- * are only structurally meaningful at branch points where the user is
10
- * interacting with a visible message and the client always has it loaded.
10
+ * Each node holds a per-node codec {@link TProjection} which the Tree folds
11
+ * from inbound events. The Tree owns the complete conversation state across
12
+ * every observed node. The {@link View} walks the parent chain to extract a
13
+ * flat message list for rendering.
11
14
  *
12
- * `upsert()` is the sole mutation method. Messages can arrive in any order
13
- * (live subscription, history pages, seed data) and the tree produces the
14
- * correct `flattenNodes()` output once all messages are present.
15
+ * `applyMessage()` is the entry point for inbound channel messages it
16
+ * classifies a run-less user input into an input node (keyed by
17
+ * codec-message-id) or routes a run-bearing wire to its reply run (keyed by
18
+ * run-id), folds events into that node's projection, and maintains a secondary
19
+ * `codecMessageId -> nodeKey` index. `applyRunLifecycle()` handles run-start /
20
+ * run-suspend / run-resume / run-end events.
15
21
  *
16
- * The tree owns conversation state. `flattenNodes()` returns the linear node
17
- * list for the currently selected branches this is what the transport's
18
- * `getMessages()` delegates to.
22
+ * Sibling structure: editing a prompt produces a sibling input node linked by
23
+ * {@link InputNode.forkOf}; regenerating a reply produces a sibling reply run
24
+ * sharing the same input-node parent (no fork-of).
19
25
  */
20
26
  import type * as Ably from 'ably';
21
- /** Internal tree surface used by View — not part of the public Tree API. */
22
- export interface TreeInternal<TMessage> extends Tree<TMessage> {
27
+ /**
28
+ * The primary key a node is indexed under: a reply run's `runId`, or an input
29
+ * node's `codecMessageId` (the client owns it before the agent mints a runId).
30
+ * @param node - The node to key.
31
+ * @returns The node's primary key.
32
+ */
33
+ export declare const nodeKey: <TProjection>(node: ConversationNode<TProjection>) => string;
34
+ /** Internal tree surface used by View and ClientSession — not part of the public Tree API. */
35
+ export interface TreeInternal<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection> extends Tree<TOutput, TProjection> {
36
+ /**
37
+ * Walk the visible node chain (both input nodes and reply runs) along the
38
+ * selected branches, in chronological order. The View renders from this.
39
+ * @param selections - Per-group selected member key, keyed by group root.
40
+ * @returns The visible nodes in chronological order.
41
+ */
42
+ visibleNodes(selections?: Map<string, string>): ConversationNode<TProjection>[];
43
+ /**
44
+ * Get the "group root" key for a sibling group — the stable key the
45
+ * selection map is keyed by (the earliest edit version for input nodes, the
46
+ * original reply for a regenerate group).
47
+ */
48
+ getGroupRoot(key: string): string;
49
+ /**
50
+ * The reply runs parented at an input node (its codec-message-id), in
51
+ * iteration order. Empty when none have been observed. Used to resolve a
52
+ * user prompt to its reply run(s).
53
+ * @param inputCodecMessageId - The input node's codec-message-id.
54
+ * @returns The reply runs parented at that input.
55
+ */
56
+ getReplyRuns(inputCodecMessageId: string): RunNode<TProjection>[];
23
57
  /**
24
- * Monotonic counter that increments on structural changes (node insert,
25
- * delete, serial promotion/reorder) but NOT on content-only updates
26
- * (existing node's message replaced). Allows the View to skip full
27
- * tree walks when only message content changed.
58
+ * Apply an inbound channel message to the tree.
59
+ *
60
+ * Classifies the message and routes it to the owning node:
61
+ * 1. Run-less user input (no run-id, a `user`-role message carrying a
62
+ * codec-message-id and input events): creates or promotes the input node
63
+ * keyed by that codec-message-id, folds the input events.
64
+ * 2. Run-bearing wire (assistant output, continuation tool-resolution, or a
65
+ * fresh agent-minted run): routes to the reply run by run-id (reconciling
66
+ * an optimistic insert by codec-message-id), folds events.
67
+ * @param events - Decoded codec events, split by wire direction. Both are
68
+ * folded into the node's projection, inputs first.
69
+ * @param events.inputs - Client-published events (`ai-input` wire).
70
+ * @param events.outputs - Agent-published events (`ai-output` wire).
71
+ * @param headers - Transport headers from the inbound Ably message.
72
+ * @param serial - Ably channel serial; undefined for optimistic inserts.
28
73
  */
29
- readonly structuralVersion: number;
74
+ applyMessage(events: {
75
+ inputs: TInput[];
76
+ outputs: TOutput[];
77
+ }, headers: Record<string, string>, serial?: string): void;
30
78
  /**
31
- * Flatten the tree along selected branches into a linear node list.
32
- * The `selections` map provides the selected sibling's msgId at each
33
- * fork point, keyed by group root msgId. Fork points not present in
34
- * the map default to the latest sibling. If a selectedMsgId is not
35
- * found in the sibling group (stale/deleted), falls back to latest.
79
+ * Apply a run-lifecycle event.
80
+ *
81
+ * - `start`: creates the reply run (if missing) or, for an existing run,
82
+ * sets RunNode.status to 'active', promotes startSerial, and backfills
83
+ * structural metadata (parent / forkOf / regenerates / invocationId).
84
+ * - `suspend`: sets RunNode.status to 'suspended' and records `endSerial`.
85
+ * The run stays live so a resume under the same `runId` picks up where it
86
+ * left off.
87
+ * - `resume`: re-activates an existing suspended Run (status back to
88
+ * 'active') without touching its structure or serials — a pure re-entry
89
+ * signal. A no-op if the Run is not yet known.
90
+ * - `end`: sets RunNode.status to the terminal reason and records
91
+ * `endSerial`.
92
+ *
93
+ * Always emits a 'run' event to subscribers.
94
+ * @param event - Lifecycle event payload, including the channel serial.
36
95
  */
37
- flattenNodes(selections: Map<string, string>): MessageNode<TMessage>[];
96
+ applyRunLifecycle(event: RunLifecycleEvent): void;
38
97
  /**
39
- * Get the "group root" msgId for a sibling group the original message
40
- * that all forks in the group trace back to.
98
+ * Get the node keyed by `key`, or undefined if `key` names no node. The
99
+ * key is a {@link nodeKey} a runId (reply run) or an input node's
100
+ * codec-message-id — so the result is a {@link ConversationNode} union:
101
+ * narrow on `kind` before reading kind-specific fields. Pairs with
102
+ * {@link getNodeByCodecMessageId}, which resolves an arbitrary owned
103
+ * codec-message-id (including an assistant message's) to its node.
104
+ * @param key - The node key to look up.
105
+ * @returns The node, or undefined if not found.
41
106
  */
42
- getGroupRoot(msgId: string): string;
107
+ getNode(key: string): ConversationNode<TProjection> | undefined;
43
108
  /**
44
- * Get the sibling group that `msgId` belongs to, as full MessageNode objects.
45
- * Allows callers to resolve index msgId without losing identity.
109
+ * Remove a node from the tree by its key ({@link nodeKey} a runId or an
110
+ * input node's codec-message-id). Children become unreachable because their
111
+ * parent is no longer on the active path.
112
+ * @param key - The node key to remove.
46
113
  */
47
- getSiblingNodes(msgId: string): MessageNode<TMessage>[];
114
+ delete(key: string): void;
48
115
  /** Forward a raw Ably message event to tree subscribers. */
49
116
  emitAblyMessage(msg: Ably.InboundMessage): void;
50
- /** Forward a turn lifecycle event to tree subscribers. */
51
- emitTurn(event: TurnLifecycleEvent): void;
52
- /** Register an active turn. */
53
- trackTurn(turnId: string, clientId: string): void;
54
- /** Unregister an active turn. */
55
- untrackTurn(turnId: string): void;
56
117
  }
57
- export declare class DefaultTree<TMessage> implements TreeInternal<TMessage> {
58
- /** All nodes indexed by msgId (x-ably-msg-id). */
118
+ export declare class DefaultTree<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection> implements TreeInternal<TInput, TOutput, TProjection> {
119
+ private readonly _codec;
120
+ private readonly _logger;
121
+ private readonly _emitter;
122
+ /**
123
+ * All nodes indexed by their primary key ({@link nodeKey}): a reply run's
124
+ * runId, or an input node's codec-message-id.
125
+ */
59
126
  private readonly _nodeIndex;
60
127
  /**
61
- * All nodes sorted by serial (lexicographic). Null-serial messages
62
- * (optimistic inserts, seed data) sort after all serial-bearing messages,
63
- * ordered among themselves by insertion sequence.
128
+ * Maps every observed `codec-message-id` to its owning node's key
129
+ * ({@link nodeKey}). For a reply run that is the runId of every message the
130
+ * run published; for an input node it is the input's own codec-message-id.
131
+ * Resolves fork-of / parent codec-message-ids to node keys, routes
132
+ * continuation amend wires to existing nodes, and backs UI lookups that hold
133
+ * a codec-message-id.
134
+ */
135
+ private readonly _codecMessageIdToNodeKey;
136
+ /**
137
+ * All nodes sorted by their sort serial ({@link sortSerial}: `startSerial`
138
+ * for runs, `serial` for input nodes), lexicographically. Nodes with no sort
139
+ * serial (optimistic) sort after all serial-bearing nodes, ordered among
140
+ * themselves by insertion sequence.
64
141
  */
65
- private readonly _sortedList;
142
+ private readonly _sortedNodes;
66
143
  /**
67
- * Parent index: parentId to set of child msgIds.
68
- * Nodes with no parent are indexed under the key `null`.
144
+ * Parent index: parent node key (the key its children's
145
+ * `parentCodecMessageId` resolves to) to the set of child node keys. Root
146
+ * nodes (no parent) are indexed under the key `undefined`. Kind-blind — a
147
+ * reply run and an input node parent off each other through the same index.
69
148
  */
70
149
  private readonly _parentIndex;
71
- private readonly _emitter;
72
- private readonly _logger;
73
- /** Active turns: turnId clientId. */
74
- private readonly _turnClientIds;
150
+ /**
151
+ * Reverse edge: an input node's codec-message-id to the set of reply-run ids
152
+ * parented at it. Lets the View resolve a user prompt to its (selected) reply
153
+ * run, and groups regenerate siblings (which all parent at the same input
154
+ * node).
155
+ */
156
+ private readonly _replyRunsByInput;
75
157
  /** Monotonically increasing counter for insertion sequence. */
76
158
  private _seqCounter;
77
- /** Incremented on structural changes; unchanged on content-only updates. */
159
+ /** Incremented on structural changes; unchanged on projection-only updates. */
78
160
  private _structuralVersion;
79
- get structuralVersion(): number;
80
- constructor(logger: Logger);
81
161
  /**
82
- * Compare two nodes for sorted list ordering.
83
- * Serial-bearing nodes sort by serial (lexicographic).
84
- * Null-serial nodes sort after all serial-bearing nodes.
85
- * Among null-serial nodes, sort by insertion sequence.
162
+ * Cached sibling-group lookups keyed by node key. The walk over forkOf
163
+ * chains and the per-parent fan-out are pure functions of the node
164
+ * graph, so the cache is keyed against {@link _structuralVersion}:
165
+ * any topology mutation drops the cache and the next lookup
166
+ * recomputes. Hits matter most during a single render pass where
167
+ * the View calls `getSiblingNodes` once per visible node plus extra
168
+ * per-message branch-anchor probes from React components.
169
+ */
170
+ private _siblingCache;
171
+ private _siblingCacheVersion;
172
+ constructor(codec: Reducer<TInput | TOutput, TProjection>, logger: Logger);
173
+ /**
174
+ * Compare two nodes (Run or input) for sorted list ordering.
175
+ * Serial-bearing nodes sort by their sort serial (`startSerial` for runs,
176
+ * `serial` for input nodes), lexicographically.
177
+ * Nodes with no sort serial sort after all serial-bearing nodes.
178
+ * Among them, sort by insertion sequence.
179
+ *
180
+ * Optimistic (null-serial) nodes intentionally tail-sort so they reorder
181
+ * into place when the server relay arrives and `applyMessage` promotes
182
+ * startSerial — see {@link applyMessage}'s `_removeSortedNode` /
183
+ * `_insertSortedNode` pair on the promotion path.
86
184
  * @param a - First node to compare.
87
185
  * @param b - Second node to compare.
88
186
  * @returns Negative if a sorts before b, positive if after, zero if equal.
89
187
  */
90
188
  private _compareNodes;
91
189
  /**
92
- * Insert a node into sortedList at the correct position via binary search.
190
+ * Insert a node into the sorted list at the correct position via binary search.
93
191
  * @param internal - The node to insert.
94
192
  */
95
- private _insertSorted;
193
+ private _insertSortedNode;
96
194
  /**
97
- * Remove a node from sortedList.
195
+ * Remove a node from the sorted list.
98
196
  * @param internal - The node to remove.
99
197
  */
100
- private _removeSorted;
198
+ private _removeSortedNode;
199
+ /**
200
+ * Insert a freshly-created node into the primary store, the parent index, and
201
+ * the sorted list, then bump the structural version. Kind-specific secondary
202
+ * indexing — the codec-message-id map for input nodes, the reply→input edge
203
+ * for reply runs — is the caller's responsibility.
204
+ * @param key - The node's primary key ({@link nodeKey}).
205
+ * @param entry - The internal node to insert.
206
+ * @param parentCodecMessageId - The node's structural parent, or undefined for a root.
207
+ */
208
+ private _insertNode;
209
+ /**
210
+ * Re-sort a node whose sort key just changed and bump the structural version.
211
+ * The caller mutates the serial field (`serial` for input nodes, `startSerial`
212
+ * for runs); this keeps the sorted list and version in step. Used on the
213
+ * optimistic-serial promotion paths when the server relay/echo arrives.
214
+ * @param entry - The internal node whose serial was just promoted.
215
+ */
216
+ private _promoteSerial;
217
+ /**
218
+ * Fold a batch of events into a node's projection in place, isolating each
219
+ * fold in a try/catch so a throwing reducer can't abort the rest of the batch
220
+ * or the surrounding apply.
221
+ * @param entry - The internal node whose projection is folded in place.
222
+ * @param events - The decoded events to fold, in wire order.
223
+ * @param serial - Ably channel serial; coerced to '' for an optimistic insert.
224
+ * @param messageId - The reducer routing key (codec-message-id), or undefined.
225
+ */
226
+ private _foldInto;
101
227
  private _addToParentIndex;
102
228
  private _removeFromParentIndex;
103
229
  /**
104
- * Get the sibling group that `msgId` belongs to.
230
+ * Resolve a node's structural parent to the parent node's key
231
+ * ({@link nodeKey}), or undefined for a root. The parent is named by a
232
+ * codec-message-id (`parentCodecMessageId`); this maps it through the
233
+ * codec-message-id index to the owning node's key (a runId for a reply run,
234
+ * a codec-message-id for an input node). Returns undefined when the parent
235
+ * hasn't been observed yet (the node is treated as a root until it arrives).
236
+ * @param node - The node whose parent to resolve.
237
+ * @returns The parent node's key, or undefined.
238
+ */
239
+ private _parentKeyOf;
240
+ /**
241
+ * Walk an input node's `forkOf` chain to the group root — the earliest edit
242
+ * version sharing the same structural parent. Stops at a missing target, a
243
+ * non-input target, a parent mismatch, or a cycle.
244
+ * @param node - The input node to walk from.
245
+ * @returns The group-root input node (the node itself when it is the root).
246
+ */
247
+ private _inputGroupRoot;
248
+ /**
249
+ * Get the sibling group that the node keyed by `key` belongs to. Kind-split:
105
250
  *
106
- * A sibling group is: the original message + all messages whose `forkOf`
107
- * points to the original (or transitively to a sibling). We find the
108
- * group root by following `forkOf` chains to the earliest ancestor that
109
- * has no `forkOf` (or whose `forkOf` target doesn't share the same parent).
110
- * @param msgId - The msg-id to look up the sibling group for.
251
+ * - **Reply runs** every reply run sharing the same input-node parent is a
252
+ * sibling (the original reply + its regenerators all parent at the same
253
+ * input node M_user). No fork-of involved.
254
+ * - **Input nodes** edit versions: nodes sharing a parent AND linked by a
255
+ * `forkOf` chain to the group root.
256
+ *
257
+ * Returned ordered by startSerial (original/oldest first). A group of one is
258
+ * returned as a single-element array (no branching).
259
+ * @param key - The node key ({@link nodeKey}) to look up the group for.
111
260
  * @returns The ordered list of sibling nodes.
112
261
  */
113
262
  private _getSiblingGroup;
114
263
  /**
115
- * Check if `node` belongs to the sibling group rooted at `originalId`.
116
- * A node is a sibling if it IS the original or its forkOf chain leads
117
- * to the original (with the same parentId).
118
- * @param node - The node to check.
119
- * @param originalId - The group root to match against.
120
- * @returns True if the node belongs to the sibling group.
264
+ * Whether `node` belongs to the sibling group anchored at `original`.
265
+ * Requires the same kind and the same structural parent; reply runs need
266
+ * nothing more (same-parent runs are regenerate siblings), input nodes must
267
+ * additionally be forkOf-linked to the original (edit versions).
268
+ * @param node - The candidate node.
269
+ * @param original - The group's anchor node.
270
+ * @returns True if `node` is a sibling of `original`.
121
271
  */
122
272
  private _isSiblingOf;
123
273
  /**
124
- * Get the "group root" msgId for a sibling group — the original message
125
- * that all forks trace back to.
126
- * @param msgId - Any msg-id in the sibling group.
127
- * @returns The msg-id of the group root.
128
- */
129
- getGroupRoot(msgId: string): string;
130
- flattenNodes(selections: Map<string, string>): MessageNode<TMessage>[];
131
- getSiblings(msgId: string): TMessage[];
132
- getSiblingNodes(msgId: string): MessageNode<TMessage>[];
133
- hasSiblings(msgId: string): boolean;
134
- getNode(msgId: string): MessageNode<TMessage> | undefined;
135
- getHeaders(msgId: string): Record<string, string> | undefined;
136
- upsert(msgId: string, message: TMessage, headers: Record<string, string>, serial?: string): void;
137
- delete(msgId: string): void;
138
- getActiveTurnIds(): Map<string, Set<string>>;
139
- on(event: 'update', handler: () => void): () => void;
140
- on(event: 'ably-message', handler: (msg: Ably.InboundMessage) => void): () => void;
141
- on(event: 'turn', handler: (event: TurnLifecycleEvent) => void): () => void;
274
+ * Get the "group root" key for a sibling group — the stable key the
275
+ * selection map is keyed by. For an input node (edit versions) that is the
276
+ * earliest fork-of ancestor; for a reply run (regenerate group) it is the
277
+ * oldest same-parent run (the original reply).
278
+ * @param key - Any node key in the sibling group.
279
+ * @returns The group root's key.
280
+ */
281
+ getGroupRoot(key: string): string;
142
282
  /**
143
- * Forward a raw Ably message event to tree subscribers.
144
- * @param msg - The raw Ably message to emit.
283
+ * Walk the visible node chain along the selected branches, kind-blind. An
284
+ * input node and a reply run reach each other through the same
285
+ * parent-membership check, so seed-only user→user chains and the
286
+ * input→reply→input weave both resolve here. Sibling groups (edit versions /
287
+ * regenerate runs) collapse to the selected member.
288
+ * @param selections - Per-group selected member key, keyed by group root.
289
+ * @returns The visible nodes (both kinds) in chronological order.
145
290
  */
146
- emitAblyMessage(msg: Ably.InboundMessage): void;
291
+ visibleNodes(selections?: Map<string, string>): ConversationNode<TProjection>[];
292
+ getRunNode(runId: string): RunNode<TProjection> | undefined;
293
+ getNode(key: string): ConversationNode<TProjection> | undefined;
294
+ getNodeByCodecMessageId(codecMessageId: string): ConversationNode<TProjection> | undefined;
295
+ getReplyRuns(inputCodecMessageId: string): RunNode<TProjection>[];
296
+ getSiblingNodes(key: string): ConversationNode<TProjection>[];
297
+ applyMessage(events: {
298
+ inputs: TInput[];
299
+ outputs: TOutput[];
300
+ }, headers: Record<string, string>, serial?: string): void;
301
+ /**
302
+ * Apply a run-less user input wire: create (or promote the serial of) the
303
+ * input node keyed by its codec-message-id, fold the input events into its
304
+ * own projection, and emit an `output` event (with empty outputs — input
305
+ * folds carry none) so the View observes the optimistic insert.
306
+ * @param codecMessageId - The input node's codec-message-id (its primary key).
307
+ * @param headers - Transport headers from the inbound Ably message.
308
+ * @param serial - Ably channel serial; undefined for an optimistic insert.
309
+ * @param all - The decoded input events to fold, in wire order.
310
+ */
311
+ private _applyInputMessage;
312
+ /**
313
+ * Apply a reply-run wire (assistant output, continuation tool-resolution, or
314
+ * a fresh run keyed by the agent-minted run-id): create or reconcile the run
315
+ * node, fold its events, maintain the codec-message-id and reply→input
316
+ * indices, and emit the `output` event. Derives the codec-message-id,
317
+ * triggering-input id, fold list, and outputs from `events`/`headers`,
318
+ * mirroring `applyMessage`.
319
+ * @param wireRunId - The run-id from the inbound wire (the node's primary key).
320
+ * @param events - The decoded inputs and outputs from the wire.
321
+ * @param events.inputs - Client-published events (`ai-input` wire).
322
+ * @param events.outputs - Agent-published events (`ai-output` wire).
323
+ * @param headers - Transport headers from the inbound Ably message.
324
+ * @param serial - Ably channel serial; undefined for an optimistic insert.
325
+ */
326
+ private _applyRunMessage;
327
+ /**
328
+ * Record a reply run against its input-node parent (the reverse edge powering
329
+ * `getReplyRuns` and regenerate sibling grouping). A reply run's
330
+ * `parentCodecMessageId` is its input node's codec-message-id (the master
331
+ * invariant), so no resolution is needed.
332
+ * @param node - The reply run node.
333
+ * @param runId - The run's id.
334
+ */
335
+ private _indexReplyRun;
336
+ applyRunLifecycle(event: RunLifecycleEvent): void;
337
+ /**
338
+ * Apply a run-start lifecycle event's structural effect: create the reply
339
+ * run if it doesn't exist yet, or backfill an optimistic / wire-created
340
+ * node's structure and metadata from the canonical run-start. Mutates
341
+ * `_structuralVersion` when the tree shape changes; the caller owns the
342
+ * `run`/`update` emits.
343
+ * @param event - The run-start lifecycle event.
344
+ */
345
+ private _applyRunStart;
346
+ /**
347
+ * Apply a run-suspend lifecycle event: pause the run without ending it —
348
+ * mark the node 'suspended' and record the serial it paused at, but keep the
349
+ * Run live so a resume under the same runId resumes it. Status/endSerial are
350
+ * content, not structure, so this never mutates `_structuralVersion`; the
351
+ * caller owns the emits.
352
+ * @param event - The run-suspend lifecycle event.
353
+ */
354
+ private _applyRunSuspend;
355
+ /**
356
+ * Apply a run-resume lifecycle event: re-enter an already-started run by
357
+ * flipping a suspended run back to 'active'. Pure re-entry — it carries no
358
+ * parent/forkOf and does not promote startSerial (the original run-start owns
359
+ * the run's structure). Only a suspended run resumes: a no-op when the run
360
+ * isn't known (e.g. a resume replayed from a newer history page before its
361
+ * run-start) and a no-op for an already-active or terminal
362
+ * (complete/cancelled/error) run — a stray resume must never resurrect a run
363
+ * that has ended. The caller owns the emits.
364
+ * @param event - The run-resume lifecycle event.
365
+ */
366
+ private _applyRunResume;
367
+ /**
368
+ * Apply a run-end lifecycle event: record the terminal reason as the node's
369
+ * status and the serial it ended at. Status/endSerial are content, not
370
+ * structure, so this never mutates `_structuralVersion`; the caller owns the
371
+ * emits.
372
+ * @param event - The run-end lifecycle event.
373
+ */
374
+ private _applyRunEnd;
375
+ delete(key: string): void;
376
+ /**
377
+ * Build a fresh RunNode from a wire message's headers. Used when an
378
+ * inbound message arrives before any run-start event for its runId.
379
+ * @param runId - The run-id from the inbound wire.
380
+ * @param headers - Transport headers from the inbound Ably message.
381
+ * @param serial - Ably channel serial; undefined for optimistic inserts.
382
+ * @returns A newly-allocated internal run node ready for insertion.
383
+ */
384
+ private _createRunFromHeaders;
385
+ /**
386
+ * Allocate a RunNode from already-resolved fields. Shared by the
387
+ * header-driven and lifecycle-driven run creators: both build the identical
388
+ * RunNode literal and stamp an insert sequence.
389
+ * @param params - The resolved run fields.
390
+ * @param params.runId - The run's id (its primary key).
391
+ * @param params.parentCodecMessageId - Structural parent codec-message-id, or undefined for a root.
392
+ * @param params.forkOf - The resolved fork target's node key (already mapped through the codec-message-id index), or undefined.
393
+ * @param params.regeneratesCodecMessageId - The codec-message-id this run regenerates, or undefined.
394
+ * @param params.clientId - The publishing client's id.
395
+ * @param params.invocationId - The agent invocation id.
396
+ * @param params.startSerial - Ably channel serial; undefined for optimistic inserts.
397
+ * @returns A newly-allocated internal run node ready for insertion.
398
+ */
399
+ private _buildRunNode;
147
400
  /**
148
- * Forward a turn lifecycle event to tree subscribers.
149
- * @param event - The turn lifecycle event to emit.
401
+ * Build a fresh InputNode from a run-less user input wire's headers.
402
+ * @param codecMessageId - The input's codec-message-id (its primary key).
403
+ * @param headers - Transport headers from the inbound Ably message.
404
+ * @param serial - Ably channel serial; undefined for optimistic inserts.
405
+ * @returns A newly-allocated internal input node ready for insertion.
150
406
  */
151
- emitTurn(event: TurnLifecycleEvent): void;
407
+ private _createInputNodeFromHeaders;
152
408
  /**
153
- * Register an active turn.
154
- * @param turnId - The turn's unique identifier.
155
- * @param clientId - The client that owns the turn.
409
+ * Build a fresh RunNode from a run-start lifecycle event. Used when a
410
+ * run-start event arrives before any message for its runId.
411
+ * @param event - The run-start lifecycle event from the agent, including
412
+ * its channel serial.
413
+ * @returns A newly-allocated internal run node ready for insertion.
156
414
  */
157
- trackTurn(turnId: string, clientId: string): void;
415
+ private _createRunFromLifecycle;
416
+ on(event: 'update', handler: () => void): () => void;
417
+ on(event: 'ably-message', handler: (msg: Ably.InboundMessage) => void): () => void;
418
+ on(event: 'run', handler: (event: RunLifecycleEvent) => void): () => void;
419
+ on(event: 'output', handler: (event: OutputEvent<TOutput>) => void): () => void;
158
420
  /**
159
- * Unregister an active turn.
160
- * @param turnId - The turn to untrack.
421
+ * Forward a raw Ably message event to tree subscribers.
422
+ * @param msg - The raw Ably message to emit.
161
423
  */
162
- untrackTurn(turnId: string): void;
424
+ emitAblyMessage(msg: Ably.InboundMessage): void;
163
425
  }
164
426
  /**
165
- * Create a Tree that materializes branching history from a flat oplog.
427
+ * Create a Tree that materializes branching conversation history from a flat
428
+ * oplog of Ably messages as a two-node-per-turn forest (input node + reply run).
429
+ * @param codec - Codec used to fold inbound events into per-Run projections.
166
430
  * @param logger - Logger for diagnostic output.
167
- * @returns A new {@link DefaultTree} instance. The transport uses DefaultTree
168
- * directly for internal methods (emitAblyMessage, emitTurn, trackTurn, untrackTurn).
169
- * Public consumers see the narrower {@link Tree} interface.
431
+ * @returns A new {@link DefaultTree} instance. The session uses DefaultTree
432
+ * directly for internal methods (applyMessage, applyRunLifecycle,
433
+ * emitAblyMessage). Public consumers see the narrower {@link Tree} interface.
170
434
  */
171
- export declare const createTree: <TMessage>(logger: Logger) => DefaultTree<TMessage>;
435
+ export declare const createTree: <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection>(codec: Reducer<TInput | TOutput, TProjection>, logger: Logger) => DefaultTree<TInput, TOutput, TProjection>;