@ably/ai-transport 0.1.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.
Files changed (221) hide show
  1. package/README.md +93 -111
  2. package/dist/ably-ai-transport.js +2401 -1387
  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 +44 -0
  8. package/dist/core/channel-options.d.ts +57 -0
  9. package/dist/core/codec/codec-event.d.ts +9 -0
  10. package/dist/core/codec/decoder.d.ts +24 -24
  11. package/dist/core/codec/define-codec.d.ts +100 -0
  12. package/dist/core/codec/encoder.d.ts +10 -12
  13. package/dist/core/codec/field-bag.d.ts +85 -0
  14. package/dist/core/codec/fields.d.ts +141 -0
  15. package/dist/core/codec/index.d.ts +8 -2
  16. package/dist/core/codec/input-descriptor-decoder.d.ts +19 -0
  17. package/dist/core/codec/input-descriptor-encoder.d.ts +22 -0
  18. package/dist/core/codec/input-descriptors.d.ts +281 -0
  19. package/dist/core/codec/lifecycle-tracker.d.ts +10 -9
  20. package/dist/core/codec/output-descriptor-decoder.d.ts +29 -0
  21. package/dist/core/codec/output-descriptor-encoder.d.ts +31 -0
  22. package/dist/core/codec/output-descriptors.d.ts +237 -0
  23. package/dist/core/codec/types.d.ts +470 -119
  24. package/dist/core/codec/well-known-inputs.d.ts +52 -0
  25. package/dist/core/transport/agent-session.d.ts +10 -0
  26. package/dist/core/transport/agent-view.d.ts +296 -0
  27. package/dist/core/transport/client-session.d.ts +13 -0
  28. package/dist/core/transport/decode-fold.d.ts +55 -0
  29. package/dist/core/transport/headers.d.ts +121 -14
  30. package/dist/core/transport/index.d.ts +5 -6
  31. package/dist/core/transport/internal/bounded-map.d.ts +20 -0
  32. package/dist/core/transport/invocation.d.ts +74 -0
  33. package/dist/core/transport/load-history-pages.d.ts +71 -0
  34. package/dist/core/transport/load-history.d.ts +44 -0
  35. package/dist/core/transport/pipe-stream.d.ts +9 -9
  36. package/dist/core/transport/run-manager.d.ts +76 -0
  37. package/dist/core/transport/session-support.d.ts +55 -0
  38. package/dist/core/transport/tree.d.ts +523 -109
  39. package/dist/core/transport/types/agent.d.ts +375 -0
  40. package/dist/core/transport/types/client.d.ts +201 -0
  41. package/dist/core/transport/types/shared.d.ts +24 -0
  42. package/dist/core/transport/types/tree.d.ts +357 -0
  43. package/dist/core/transport/types/view.d.ts +249 -0
  44. package/dist/core/transport/types.d.ts +13 -553
  45. package/dist/core/transport/view.d.ts +390 -84
  46. package/dist/core/transport/wire-log.d.ts +102 -0
  47. package/dist/errors.d.ts +27 -10
  48. package/dist/index.d.ts +8 -9
  49. package/dist/logger.d.ts +12 -0
  50. package/dist/react/ably-ai-transport-react.js +1365 -1010
  51. package/dist/react/ably-ai-transport-react.js.map +1 -1
  52. package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
  53. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
  54. package/dist/react/contexts/client-session-context.d.ts +37 -0
  55. package/dist/react/contexts/client-session-provider.d.ts +56 -0
  56. package/dist/react/create-session-hooks.d.ts +116 -0
  57. package/dist/react/index.d.ts +13 -12
  58. package/dist/react/internal/skipped-session.d.ts +8 -0
  59. package/dist/react/internal/use-resolved-session.d.ts +36 -0
  60. package/dist/react/use-ably-messages.d.ts +17 -14
  61. package/dist/react/use-client-session.d.ts +81 -0
  62. package/dist/react/use-create-view.d.ts +14 -13
  63. package/dist/react/use-tree.d.ts +30 -15
  64. package/dist/react/use-view.d.ts +81 -50
  65. package/dist/utils.d.ts +48 -71
  66. package/dist/vercel/ably-ai-transport-vercel.js +3257 -2499
  67. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
  68. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
  69. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
  70. package/dist/vercel/codec/decode-lifecycle.d.ts +9 -0
  71. package/dist/vercel/codec/events.d.ts +50 -0
  72. package/dist/vercel/codec/fields.d.ts +44 -0
  73. package/dist/vercel/codec/fold-content.d.ts +16 -0
  74. package/dist/vercel/codec/fold-data.d.ts +16 -0
  75. package/dist/vercel/codec/fold-input.d.ts +67 -0
  76. package/dist/vercel/codec/fold-lifecycle.d.ts +16 -0
  77. package/dist/vercel/codec/fold-text.d.ts +16 -0
  78. package/dist/vercel/codec/fold-tool-input.d.ts +17 -0
  79. package/dist/vercel/codec/fold-tool-output.d.ts +16 -0
  80. package/dist/vercel/codec/index.d.ts +7 -20
  81. package/dist/vercel/codec/inputs.d.ts +11 -0
  82. package/dist/vercel/codec/outputs.d.ts +11 -0
  83. package/dist/vercel/codec/reducer-state.d.ts +121 -0
  84. package/dist/vercel/codec/reducer.d.ts +62 -0
  85. package/dist/vercel/codec/tool-transitions.d.ts +2 -8
  86. package/dist/vercel/codec/wire-data.d.ts +34 -0
  87. package/dist/vercel/index.d.ts +5 -5
  88. package/dist/vercel/react/ably-ai-transport-vercel-react.js +2859 -9705
  89. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
  90. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +1 -45
  91. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
  92. package/dist/vercel/react/contexts/chat-transport-context.d.ts +9 -7
  93. package/dist/vercel/react/contexts/chat-transport-provider.d.ts +53 -41
  94. package/dist/vercel/react/index.d.ts +1 -2
  95. package/dist/vercel/react/use-chat-transport.d.ts +30 -26
  96. package/dist/vercel/react/use-message-sync.d.ts +17 -30
  97. package/dist/vercel/run-end-reason.d.ts +84 -0
  98. package/dist/vercel/tool-part.d.ts +21 -0
  99. package/dist/vercel/transport/chat-transport.d.ts +41 -24
  100. package/dist/vercel/transport/index.d.ts +24 -20
  101. package/dist/vercel/transport/run-output-stream.d.ts +54 -0
  102. package/dist/version.d.ts +2 -0
  103. package/package.json +31 -24
  104. package/src/constants.ts +124 -51
  105. package/src/core/agent.ts +92 -0
  106. package/src/core/channel-options.ts +89 -0
  107. package/src/core/codec/codec-event.ts +27 -0
  108. package/src/core/codec/decoder.ts +202 -105
  109. package/src/core/codec/define-codec.ts +432 -0
  110. package/src/core/codec/encoder.ts +114 -107
  111. package/src/core/codec/field-bag.ts +142 -0
  112. package/src/core/codec/fields.ts +193 -0
  113. package/src/core/codec/index.ts +56 -6
  114. package/src/core/codec/input-descriptor-decoder.ts +97 -0
  115. package/src/core/codec/input-descriptor-encoder.ts +150 -0
  116. package/src/core/codec/input-descriptors.ts +373 -0
  117. package/src/core/codec/lifecycle-tracker.ts +10 -9
  118. package/src/core/codec/output-descriptor-decoder.ts +139 -0
  119. package/src/core/codec/output-descriptor-encoder.ts +101 -0
  120. package/src/core/codec/output-descriptors.ts +307 -0
  121. package/src/core/codec/types.ts +505 -126
  122. package/src/core/codec/well-known-inputs.ts +96 -0
  123. package/src/core/transport/agent-session.ts +1085 -0
  124. package/src/core/transport/agent-view.ts +738 -0
  125. package/src/core/transport/client-session.ts +780 -0
  126. package/src/core/transport/decode-fold.ts +101 -0
  127. package/src/core/transport/headers.ts +234 -22
  128. package/src/core/transport/index.ts +27 -27
  129. package/src/core/transport/internal/bounded-map.ts +27 -0
  130. package/src/core/transport/invocation.ts +98 -0
  131. package/src/core/transport/load-history-pages.ts +220 -0
  132. package/src/core/transport/load-history.ts +271 -0
  133. package/src/core/transport/pipe-stream.ts +63 -39
  134. package/src/core/transport/run-manager.ts +243 -0
  135. package/src/core/transport/session-support.ts +96 -0
  136. package/src/core/transport/tree.ts +1293 -308
  137. package/src/core/transport/types/agent.ts +434 -0
  138. package/src/core/transport/types/client.ts +247 -0
  139. package/src/core/transport/types/shared.ts +27 -0
  140. package/src/core/transport/types/tree.ts +393 -0
  141. package/src/core/transport/types/view.ts +288 -0
  142. package/src/core/transport/types.ts +13 -706
  143. package/src/core/transport/view.ts +1229 -450
  144. package/src/core/transport/wire-log.ts +189 -0
  145. package/src/errors.ts +29 -9
  146. package/src/event-emitter.ts +3 -2
  147. package/src/index.ts +86 -42
  148. package/src/logger.ts +14 -1
  149. package/src/react/contexts/client-session-context.ts +41 -0
  150. package/src/react/contexts/client-session-provider.tsx +222 -0
  151. package/src/react/create-session-hooks.ts +141 -0
  152. package/src/react/index.ts +24 -13
  153. package/src/react/internal/skipped-session.ts +62 -0
  154. package/src/react/internal/use-resolved-session.ts +63 -0
  155. package/src/react/use-ably-messages.ts +32 -22
  156. package/src/react/use-client-session.ts +178 -0
  157. package/src/react/use-create-view.ts +33 -29
  158. package/src/react/use-tree.ts +61 -30
  159. package/src/react/use-view.ts +138 -96
  160. package/src/utils.ts +83 -131
  161. package/src/vercel/codec/decode-lifecycle.ts +70 -0
  162. package/src/vercel/codec/events.ts +85 -0
  163. package/src/vercel/codec/fields.ts +58 -0
  164. package/src/vercel/codec/fold-content.ts +54 -0
  165. package/src/vercel/codec/fold-data.ts +46 -0
  166. package/src/vercel/codec/fold-input.ts +255 -0
  167. package/src/vercel/codec/fold-lifecycle.ts +85 -0
  168. package/src/vercel/codec/fold-text.ts +55 -0
  169. package/src/vercel/codec/fold-tool-input.ts +86 -0
  170. package/src/vercel/codec/fold-tool-output.ts +79 -0
  171. package/src/vercel/codec/index.ts +28 -21
  172. package/src/vercel/codec/inputs.ts +116 -0
  173. package/src/vercel/codec/outputs.ts +207 -0
  174. package/src/vercel/codec/reducer-state.ts +169 -0
  175. package/src/vercel/codec/reducer.ts +191 -0
  176. package/src/vercel/codec/tool-transitions.ts +3 -14
  177. package/src/vercel/codec/wire-data.ts +64 -0
  178. package/src/vercel/index.ts +7 -19
  179. package/src/vercel/react/contexts/chat-transport-context.ts +8 -7
  180. package/src/vercel/react/contexts/chat-transport-provider.tsx +87 -59
  181. package/src/vercel/react/index.ts +3 -5
  182. package/src/vercel/react/use-chat-transport.ts +44 -66
  183. package/src/vercel/react/use-message-sync.ts +75 -39
  184. package/src/vercel/run-end-reason.ts +157 -0
  185. package/src/vercel/tool-part.ts +25 -0
  186. package/src/vercel/transport/chat-transport.ts +380 -98
  187. package/src/vercel/transport/index.ts +38 -37
  188. package/src/vercel/transport/run-output-stream.ts +169 -0
  189. package/src/version.ts +2 -0
  190. package/dist/core/transport/client-transport.d.ts +0 -10
  191. package/dist/core/transport/decode-history.d.ts +0 -43
  192. package/dist/core/transport/server-transport.d.ts +0 -7
  193. package/dist/core/transport/stream-router.d.ts +0 -29
  194. package/dist/core/transport/turn-manager.d.ts +0 -37
  195. package/dist/react/contexts/transport-context.d.ts +0 -31
  196. package/dist/react/contexts/transport-provider.d.ts +0 -49
  197. package/dist/react/create-transport-hooks.d.ts +0 -124
  198. package/dist/react/use-active-turns.d.ts +0 -12
  199. package/dist/react/use-client-transport.d.ts +0 -80
  200. package/dist/vercel/codec/accumulator.d.ts +0 -21
  201. package/dist/vercel/codec/decoder.d.ts +0 -22
  202. package/dist/vercel/codec/encoder.d.ts +0 -41
  203. package/dist/vercel/react/use-staged-add-tool-approval-response.d.ts +0 -30
  204. package/dist/vercel/tool-approvals.d.ts +0 -124
  205. package/dist/vercel/tool-events.d.ts +0 -26
  206. package/src/core/transport/client-transport.ts +0 -977
  207. package/src/core/transport/decode-history.ts +0 -485
  208. package/src/core/transport/server-transport.ts +0 -612
  209. package/src/core/transport/stream-router.ts +0 -136
  210. package/src/core/transport/turn-manager.ts +0 -165
  211. package/src/react/contexts/transport-context.ts +0 -37
  212. package/src/react/contexts/transport-provider.tsx +0 -164
  213. package/src/react/create-transport-hooks.ts +0 -144
  214. package/src/react/use-active-turns.ts +0 -72
  215. package/src/react/use-client-transport.ts +0 -197
  216. package/src/vercel/codec/accumulator.ts +0 -588
  217. package/src/vercel/codec/decoder.ts +0 -618
  218. package/src/vercel/codec/encoder.ts +0 -410
  219. package/src/vercel/react/use-staged-add-tool-approval-response.ts +0 -87
  220. package/src/vercel/tool-approvals.ts +0 -380
  221. package/src/vercel/tool-events.ts +0 -53
@@ -0,0 +1,52 @@
1
+ import { CodecInputEvent, Regenerate, ToolApprovalResponse, ToolApprovalResponsePayloadOf, ToolResult, ToolResultError, ToolResultErrorPayloadOf, ToolResultPayloadOf, UserMessage, UserMessageOf } from './types.js';
2
+ /**
3
+ * The well-known input factory functions, payload-typed for a codec's `TInput`
4
+ * union. A codec spreads these into its definition rather than re-implementing
5
+ * the variant-wrapping boilerplate. Each factory returns the specific variant
6
+ * it builds — a member of the codec's `TInput` union.
7
+ * @template TInput - The codec's input union.
8
+ */
9
+ export interface WellKnownInputFactories<TInput extends CodecInputEvent> {
10
+ /**
11
+ * Wrap a domain message as the codec's {@link UserMessage} variant.
12
+ * @param message - The message in the codec's domain representation.
13
+ * @returns The user-message input.
14
+ */
15
+ createUserMessage(message: UserMessageOf<TInput>): UserMessage<UserMessageOf<TInput>>;
16
+ /**
17
+ * Build a {@link Regenerate} input.
18
+ * @param target - The codec-message-id of the assistant message to regenerate.
19
+ * @param parent - The codec-message-id of the parent user message the new assistant threads under.
20
+ * @returns The regenerate input.
21
+ */
22
+ createRegenerate(target: string, parent: string): Regenerate;
23
+ /**
24
+ * Build a {@link ToolResult} input addressing an assistant codec-message.
25
+ * @param codecMessageId - The assistant codec-message carrying the tool call.
26
+ * @param payload - The codec's domain payload describing the tool result.
27
+ * @returns The tool-result input.
28
+ */
29
+ createToolResult(codecMessageId: string, payload: ToolResultPayloadOf<TInput>): ToolResult<ToolResultPayloadOf<TInput>>;
30
+ /**
31
+ * Build a {@link ToolResultError} input addressing an assistant codec-message.
32
+ * @param codecMessageId - The assistant codec-message carrying the tool call.
33
+ * @param payload - The codec's domain payload describing the failure.
34
+ * @returns The tool-result-error input.
35
+ */
36
+ createToolResultError(codecMessageId: string, payload: ToolResultErrorPayloadOf<TInput>): ToolResultError<ToolResultErrorPayloadOf<TInput>>;
37
+ /**
38
+ * Build a {@link ToolApprovalResponse} input addressing an assistant codec-message.
39
+ * @param codecMessageId - The assistant codec-message carrying the tool call.
40
+ * @param payload - The codec's domain payload describing the approval decision.
41
+ * @returns The tool-approval-response input.
42
+ */
43
+ createToolApprovalResponse(codecMessageId: string, payload: ToolApprovalResponsePayloadOf<TInput>): ToolApprovalResponse<ToolApprovalResponsePayloadOf<TInput>>;
44
+ }
45
+ /**
46
+ * Build the {@link WellKnownInputFactories} for a codec's `TInput` union. The
47
+ * returned factories wrap domain values into the well-known input variants and
48
+ * are typically spread into a codec definition.
49
+ * @template TInput - The codec's input union.
50
+ * @returns The well-known input factory functions, payload-typed to `TInput`.
51
+ */
52
+ export declare const wellKnownInputs: <TInput extends CodecInputEvent>() => WellKnownInputFactories<TInput>;
@@ -0,0 +1,10 @@
1
+ import { CodecInputEvent, CodecOutputEvent } from '../codec/types.js';
2
+ import { AgentSession, AgentSessionOptions } from './types.js';
3
+ /**
4
+ * Create an agent (server-side) session bound to the given Realtime client
5
+ * and channel name. The caller owns the client's lifecycle; the session
6
+ * owns its channel.
7
+ * @param options - Session configuration.
8
+ * @returns A new {@link AgentSession} instance.
9
+ */
10
+ export declare const createAgentSession: <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>(options: AgentSessionOptions<TInput, TOutput, TProjection, TMessage>) => AgentSession<TOutput, TProjection, TMessage>;
@@ -0,0 +1,296 @@
1
+ import { Logger } from '../../logger.js';
2
+ import { Codec, CodecInputEvent, CodecOutputEvent } from '../codec/types.js';
3
+ import { WireApplier } from './decode-fold.js';
4
+ import { TreeInternal } from './tree.js';
5
+ import { ConversationNode, Tree } from './types.js';
6
+ /**
7
+ * AgentView — internal, server-side message-loading + input-event lookup for
8
+ * AgentSession.
9
+ *
10
+ * Encapsulates everything the agent needs to read conversation state off the
11
+ * channel: locating the triggering input event before `run-start`
12
+ * ({@link AgentView.findInputEvent}), and reconstructing the ancestor chain for
13
+ * an LLM prompt ({@link AgentView.loadConversation} / {@link AgentView.messages}).
14
+ *
15
+ * It does NOT own the materialisation Tree — AgentSession owns the Tree and the
16
+ * applier (and swaps them on channel continuity loss) and injects them here as
17
+ * `readonly` fields, the same way ClientSession wires `DefaultView`. Because
18
+ * AgentSession swaps the Tree, it RECREATES the AgentView on continuity loss
19
+ * (a fresh instance bound to the fresh Tree/applier) rather than mutating it —
20
+ * so this class never needs a tree accessor or a reset hook.
21
+ *
22
+ * This is deliberately internal: it is not exported from any entry point and
23
+ * does NOT implement the public `View` interface (that is the client-side
24
+ * `DefaultView`, unrelated to this class).
25
+ *
26
+ * Both `findInputEvent` and `loadConversation` drive ONE history-walk mechanism
27
+ * — the single-flight chain in {@link AgentView._driveHistoryChain} — so a
28
+ * `start()` input scan and a concurrent `loadConversation` share folded pages
29
+ * instead of each scanning the channel.
30
+ */
31
+ import * as Ably from 'ably';
32
+ /**
33
+ * Result of {@link AgentView.findInputEvent}. The lookup races the session's
34
+ * Tree (`findAblyMessageByEventId` pre-scan + `'ably-message'` event for live
35
+ * arrivals) against a bounded history scan; resolves with the matched messages
36
+ * sorted by Ably `serial` ascending.
37
+ *
38
+ * Run.start reads `firstHeaders` / `firstClientId` from the smallest-serial
39
+ * matched message to derive per-run metadata (run-id, parent, forkOf,
40
+ * continuation flag, publisher clientId). The Tree has already folded each
41
+ * message by the time the lookup resolves, so callers do NOT need to decode the
42
+ * raw matched messages themselves.
43
+ */
44
+ export interface InputEventLookupResult {
45
+ /** Raw Ably messages matched by the lookup, sorted by serial ascending. */
46
+ rawMessages: Ably.InboundMessage[];
47
+ /** Transport headers of the smallest-serial matched message (run metadata). */
48
+ firstHeaders?: Record<string, string>;
49
+ /** Publisher's Ably channel-level `clientId` from the smallest-serial message. */
50
+ firstClientId?: string;
51
+ }
52
+ /**
53
+ * Walk parent pointers from an anchor codec-message-id back through the
54
+ * Tree to the conversation root, returning nodes in root-first order. When
55
+ * `maxRuns` is set, the walk stops before the RunNode that would exceed the
56
+ * bound, so the bounding run's own input node(s) are still included (input
57
+ * nodes never count toward the bound). The chain therefore starts with the
58
+ * input that triggered its oldest run, never with an assistant reply.
59
+ *
60
+ * Returns an empty array when the anchor isn't in the Tree.
61
+ * @param tree - The materialisation tree to walk.
62
+ * @param anchor - The codec-message-id to start from (typically the current run's input).
63
+ * @param maxRuns - Optional bound on the number of ancestor reply RunNodes in the chain.
64
+ * @param currentRunId - The current run's id. Its own RunNode (reachable when
65
+ * the anchor's wire carried the run-id) is conversation tail, not ancestor
66
+ * context, so it never counts toward `maxRuns`.
67
+ * @returns Nodes from root to anchor in chronological order.
68
+ */
69
+ export declare const walkAncestorChain: <TOutput extends CodecOutputEvent, TProjection>(tree: Tree<TOutput, TProjection>, anchor: string | undefined, maxRuns?: number, currentRunId?: string) => readonly ConversationNode<TProjection>[];
70
+ /**
71
+ * Constructor dependencies for {@link AgentView}, injected by AgentSession.
72
+ *
73
+ * AgentView holds `tree` + `applier` directly (like `DefaultView`). AgentSession
74
+ * owns them and, because it SWAPS the Tree on continuity loss, recreates the
75
+ * AgentView with the fresh Tree/applier rather than mutating them in place.
76
+ */
77
+ export interface AgentViewOptions<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage> {
78
+ /** The session's materialisation Tree (read for walks; folded into by history). */
79
+ tree: TreeInternal<TInput, TOutput, TProjection>;
80
+ /** The Ably channel to read history from. */
81
+ channel: Ably.RealtimeChannel;
82
+ /** Codec used to project per-node messages. */
83
+ codec: Codec<TInput, TOutput, TProjection, TMessage>;
84
+ /** The Tree's decode-and-apply engine; history pages fold through it. */
85
+ applier: WireApplier;
86
+ /** Logger for diagnostic output. */
87
+ logger?: Logger;
88
+ /**
89
+ * Age bound for the input-event scan: the scan gives up paging once it
90
+ * crosses `Date.now() - inputEventLookbackMs`. Applied only to
91
+ * `findInputEvent`, never to the ancestor-hydration walk.
92
+ */
93
+ inputEventLookbackMs: number;
94
+ }
95
+ /**
96
+ * Internal server-side view: input-event lookup + conversation loading over the
97
+ * session Tree. See the file header for the ownership boundary.
98
+ */
99
+ export declare class AgentView<TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage> {
100
+ private readonly _tree;
101
+ private readonly _channel;
102
+ private readonly _codec;
103
+ private readonly _applier;
104
+ private readonly _logger?;
105
+ private readonly _inputEventLookbackMs;
106
+ /**
107
+ * Tail of the single-flight history-hydration chain. Each walk links behind
108
+ * the current tail and becomes the new tail, so concurrent calls serialise
109
+ * and share each other's folded pages instead of each scanning the channel.
110
+ * A link never rejects (it records its error locally), so a follower awaiting
111
+ * the tail is isolated from a prior link's failure.
112
+ */
113
+ private _hydrationMutex;
114
+ /**
115
+ * Shared history-walk cursor for this AgentView's attach epoch — ONE backward
116
+ * `untilAttach` pagination that both `findInputEvent` and `loadConversation`
117
+ * advance. `findInputEvent` pages it until the trigger is found (or its
118
+ * lookback give-up point) and pauses; `loadConversation` resumes from that
119
+ * position instead of re-paging from newest, so the channel is walked once.
120
+ * Created lazily on first use (no per-caller signal, so it outlives any one
121
+ * caller; no lookback, so it can reach attach). The single-flight chain
122
+ * (`_hydrationMutex`) serialises access so it is never paged concurrently. A
123
+ * continuity-loss swap recreates the whole AgentView, so there is no in-place
124
+ * reset.
125
+ */
126
+ private _cursor;
127
+ /**
128
+ * True once the shared cursor reached attach (channel exhausted). Because the
129
+ * cursor carries no lookback, its exhaustion is always genuine (never a
130
+ * lookback boundary), so either caller may record it; a lookback-bounded
131
+ * `findInputEvent` scan stops via an early `break` that leaves the cursor
132
+ * non-exhausted, so it never sets this.
133
+ */
134
+ private _historyExhausted;
135
+ constructor(options: AgentViewOptions<TInput, TOutput, TProjection, TMessage>);
136
+ /**
137
+ * Fold a single wire message into the Tree: decode-and-apply via the applier,
138
+ * then notify Tree subscribers and populate the event-id index. Mirrors
139
+ * AgentSession's live `_foldWire`; history pages fold through this.
140
+ * @param wire - The inbound Ably message to fold.
141
+ */
142
+ private _foldWire;
143
+ /**
144
+ * Find every message whose `event-id` matches one of `expectedEventIds`,
145
+ * racing three sources:
146
+ *
147
+ * 1. A pre-scan of the Tree via `findAblyMessageByEventId` for messages already
148
+ * folded into it from prior live arrivals.
149
+ * 2. A live listener on the Tree's `ably-message` event for new arrivals
150
+ * during the call.
151
+ * 3. The shared history walk (lookback-bounded) — pages fold into the Tree
152
+ * and surface through the same `ably-message` event.
153
+ *
154
+ * Resolves when every expected event-id has been matched. Per-id race
155
+ * resolution — whichever source surfaces a matched message first wins
156
+ * (dedup by serial). On timeout: cancels the in-flight history scan and
157
+ * rejects with `InputEventNotFound`, wrapping any history-scan failure as
158
+ * `cause` so a broken history fetch isn't masked behind the timeout. On
159
+ * signal abort: rejects with `InvalidArgument`.
160
+ *
161
+ * `firstHeaders` and `firstClientId` are read from the matched message with
162
+ * the smallest serial (`compareBySerial`), giving stable run-level
163
+ * metadata regardless of arrival ordering across sources.
164
+ * @param opts - Lookup parameters.
165
+ * @param opts.invocationId - The invocation id this lookup is for (logging / error messages).
166
+ * @param opts.runId - The run id this lookup is for (logging / error messages).
167
+ * @param opts.expectedEventIds - The set of `event-id`s the lookup must observe before resolving.
168
+ * @param opts.timeoutMs - Maximum total wait across live + history sources.
169
+ * @param opts.signal - AbortSignal that aborts the lookup if the run is cancelled.
170
+ * @returns Raw matched Ably messages sorted by serial ascending, plus the
171
+ * smallest-serial message's headers and clientId for downstream metadata.
172
+ */
173
+ findInputEvent(opts: {
174
+ invocationId: string;
175
+ runId: string;
176
+ expectedEventIds: readonly string[];
177
+ timeoutMs: number;
178
+ signal: AbortSignal;
179
+ }): Promise<InputEventLookupResult>;
180
+ /**
181
+ * Reconstruct the conversation by walking the parent chain from the run's
182
+ * input node back to the conversation root, reading already-folded
183
+ * projections off the Tree's nodes.
184
+ *
185
+ * Hydrates the Tree as needed via the shared history walk
186
+ * ({@link AgentView._hydrateAncestors}), then concatenates
187
+ * `codec.getMessages(node.projection)` per node (root first) and appends the
188
+ * current run's projection at the tail.
189
+ * @param runId - The current run's id (for the tail run's projection lookup).
190
+ * @param assistantParentFallback - The current run's input node codec-message-id.
191
+ * @param signal - AbortSignal; rejects with InvalidArgument when aborted.
192
+ * @param maxRuns - Optional bound on the parent walk; counts reply RunNodes.
193
+ * @param runIdAdopted - True when the run-id came from outside (runtime
194
+ * override or continuation), so its node may exist in channel history;
195
+ * false for agent-minted ids, whose run-start only ever arrives via the
196
+ * live echo.
197
+ * @param regenerateTarget - The codec-message-id being regenerated, or
198
+ * undefined; the run that owns it is flattened only up to that message so
199
+ * the reconstructed history stops before the assistant message being
200
+ * replaced (which the model would otherwise reject).
201
+ * @returns The branch's messages (root-first) and the current run's projection.
202
+ */
203
+ loadConversation(runId: string, assistantParentFallback: string | undefined, signal: AbortSignal, maxRuns: number | undefined, runIdAdopted: boolean, regenerateTarget?: string): Promise<{
204
+ messages: TMessage[];
205
+ projection: TProjection;
206
+ }>;
207
+ /**
208
+ * Walk the parent chain from `anchor` over the current Tree and concatenate
209
+ * each node's projected messages (root-first), then append the current run's
210
+ * own messages when its RunNode isn't already on the chain. Shared by
211
+ * {@link AgentView.loadConversation} and {@link AgentView.messages}. Pure read
212
+ * over whatever is currently folded — no fetching.
213
+ * @param runId - The current run's id (for the tail run's projection lookup).
214
+ * @param anchor - The current run's input node codec-message-id.
215
+ * @param maxRuns - Optional bound on the ancestor walk (counts reply runs).
216
+ * @param regenerateTarget - The codec-message-id being regenerated; when set,
217
+ * the walk stops before that message (a regenerate of a non-head message
218
+ * anchors at the target's predecessor, so flattening its run whole would
219
+ * re-emit the target and end the history on the message being replaced).
220
+ * @returns The conversation messages (root-first) and the current run's
221
+ * projection (the codec's empty init when the run has no node yet).
222
+ */
223
+ private _collectConversation;
224
+ /**
225
+ * Synchronous live read of the conversation messages for `Run.messages`:
226
+ * walk the parent chain from `anchor` (no `maxRuns` bound), concatenate each
227
+ * ancestor's projection, then append the current run's messages if its node
228
+ * isn't already on the chain. No I/O — reflects whatever is currently folded.
229
+ * @param runId - The current run's id (for the tail run's projection lookup).
230
+ * @param anchor - The current run's input node codec-message-id (assistantParentFallback).
231
+ * @param regenerateTarget - The codec-message-id being regenerated; when set,
232
+ * the walk stops before it (see {@link AgentView._collectConversation}).
233
+ * @returns The conversation messages, root-first.
234
+ */
235
+ messages(runId: string, anchor: string | undefined, regenerateTarget?: string): TMessage[];
236
+ /**
237
+ * Single-flight chain entry shared by `findInputEvent` and `loadConversation`.
238
+ * Serialises behind any in-flight walk so the shared cursor is advanced by one
239
+ * caller at a time (never paged concurrently), then runs one
240
+ * {@link AgentView._walkSharedHistory}. A link never rejects (it records its
241
+ * error locally), so a follower awaiting the chain tail is isolated from a
242
+ * prior link's failure; this method rethrows the wrapped error from its own
243
+ * frame after awaiting.
244
+ *
245
+ * Returns `exhausted` but never records `_historyExhausted`; the caller records
246
+ * it (both callers may, since the shared cursor's exhaustion is always genuine
247
+ * — see {@link AgentView._historyExhausted}).
248
+ * @param shouldStop - Polled before each page; true pauses this walk.
249
+ * @param signal - Per-call abort signal (checked between pages).
250
+ * @param lookbackMs - Optional give-up bound for the input scan (early break).
251
+ * @param operationLabel - Verb for the wrapped error message.
252
+ * @returns `{ exhausted }` — true only when the shared cursor reached attach.
253
+ */
254
+ private _driveHistoryChain;
255
+ /**
256
+ * Advance the SHARED history cursor (lazily opening it once per attach epoch)
257
+ * and fold each page into the session Tree via the injected `fold`, stopping
258
+ * when `shouldStop()` returns true, the channel is exhausted, the signal
259
+ * aborts, a continuity-loss Tree swap abandons the walk, or — when `lookbackMs`
260
+ * is given — the walk pages past the lookback window. The cursor is NOT closed
261
+ * on stop: it stays paused at its current position so a later caller resumes
262
+ * from there rather than re-paging from newest. Throws (caller-wrapped) on a
263
+ * fetch failure after `loadHistoryPages`' per-page retries.
264
+ * @param shouldStop - Polled before each page; true pauses the walk.
265
+ * @param signal - Per-call abort signal (checked between pages; the shared cursor carries none).
266
+ * @param lookbackMs - Optional give-up bound: stop paging once a page's oldest
267
+ * message predates `Date.now() - lookbackMs`. An early `break`, NOT a cursor
268
+ * bound, so the cursor stays resumable and exhaustion is never reported here.
269
+ * @returns True only when the cursor genuinely reached attach — NOT when
270
+ * paused by the predicate / lookback, a Tree swap, or signal abort.
271
+ */
272
+ private _walkSharedHistory;
273
+ /**
274
+ * Populate the Tree with enough ancestor coverage to walk from `anchor` to
275
+ * root (or `maxRuns` reply runs back) by driving the shared history walk.
276
+ * Records `_historyExhausted` only when a FULL (no-lookback) walk genuinely
277
+ * exhausts the channel.
278
+ * @param runId - The current run's id (when adopted, its node must be present in the Tree before the walk is complete).
279
+ * @param anchor - The input codec-message-id to walk from. Undefined means no walk is needed (current run only).
280
+ * @param signal - AbortSignal.
281
+ * @param maxRuns - Optional bound on the ancestor walk.
282
+ * @param runIdAdopted - Whether the run-id came from outside (override or continuation) and so may name a run present in channel history.
283
+ * @throws {Ably.ErrorInfo} `InvalidArgument` when `signal` aborts;
284
+ * `HistoryFetchFailed` — or the underlying Ably code when the failure
285
+ * carried one — (original as `cause`) when this caller's own history
286
+ * fetch fails after retries.
287
+ */
288
+ private _hydrateAncestors;
289
+ }
290
+ /**
291
+ * Create an {@link AgentView}. Factory entry point mirroring `createTree`;
292
+ * AgentSession never calls `new AgentView` directly.
293
+ * @param options - Injected dependencies.
294
+ * @returns A new AgentView.
295
+ */
296
+ export declare const createAgentView: <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>(options: AgentViewOptions<TInput, TOutput, TProjection, TMessage>) => AgentView<TInput, TOutput, TProjection, TMessage>;
@@ -0,0 +1,13 @@
1
+ import { CodecInputEvent, CodecOutputEvent } from '../codec/types.js';
2
+ import { ClientSession, ClientSessionOptions } from './types.js';
3
+ /**
4
+ * Create a client-side session that manages conversation state over an Ably channel.
5
+ *
6
+ * The caller owns the client's lifecycle; the session owns its channel.
7
+ * The session is created in a not-yet-connected state — callers must
8
+ * `await session.connect()` before `send`, `regenerate`, `edit`, `update`,
9
+ * or `cancel`.
10
+ * @param options - Configuration for the client session.
11
+ * @returns A new {@link ClientSession} instance.
12
+ */
13
+ export declare const createClientSession: <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection, TMessage>(options: ClientSessionOptions<TInput, TOutput, TProjection, TMessage>) => ClientSession<TInput, TOutput, TProjection, TMessage>;
@@ -0,0 +1,55 @@
1
+ import { CodecInputEvent, CodecOutputEvent, Decoder } from '../codec/types.js';
2
+ import { TreeInternal } from './tree.js';
3
+ import { RunLifecycleEvent } from './types.js';
4
+ /**
5
+ * Shared wire decode-and-apply engine.
6
+ *
7
+ * The client's live decode loop and the View's history replay both reconstruct
8
+ * the conversation Tree from the same raw Ably wire log. This module is the one
9
+ * place that classifies a wire message (run-lifecycle vs codec-decoded), parses
10
+ * or decodes it, and applies it to the Tree — so the two paths can never drift.
11
+ *
12
+ * The engine is exposed as a {@link WireApplier} binding one Tree to one
13
+ * decoder. A Tree has exactly one applier (the session constructs it and hands
14
+ * it to every View), so every route a wire message can arrive by — the live
15
+ * subscription, View history pagination, the agent's hydration walks — feeds
16
+ * the same decoder. The decoder's version-guarded stream trackers then make
17
+ * re-delivery across routes (an attach-boundary in-flight stream, a replayed
18
+ * history page) decode to nothing instead of double-folding. The delivery's
19
+ * `version.serial` is also threaded into the Tree, whose per-entry
20
+ * `decodedThrough` high-water-mark drops whole-wire replays that no decoder
21
+ * state can see (stateless discrete re-decodes).
22
+ */
23
+ import type * as Ably from 'ably';
24
+ /**
25
+ * The decode-and-apply engine for one Tree: a single codec decoder bound to a
26
+ * single Tree, shared by every route that feeds the Tree wire messages.
27
+ */
28
+ export interface WireApplier {
29
+ /**
30
+ * Apply one inbound wire message to the bound tree.
31
+ *
32
+ * Run-lifecycle messages are turned into a {@link RunLifecycleEvent} via
33
+ * {@link parseRunLifecycle} and applied with `applyRunLifecycle`; everything
34
+ * else is decoded with the bound decoder and applied with `applyMessage`,
35
+ * skipping wire-only carriers that decode to no events and carry no run-id
36
+ * (the eventual reply run is created later by its run-start).
37
+ *
38
+ * Does NOT emit the tree's `ably-message` event — the caller owns that,
39
+ * because the live loop emits per message while history replay emits in a
40
+ * batch once the whole page is applied. Returns the parsed lifecycle event
41
+ * so a live caller can run its own side-effects (resolving a pending
42
+ * run-start, surfacing an agent error); returns `undefined` for a
43
+ * codec-decoded message or a lifecycle message that carried no run-id.
44
+ * @param rawMsg - The inbound Ably wire message.
45
+ * @returns The parsed run-lifecycle event, or `undefined`.
46
+ */
47
+ apply(rawMsg: Ably.InboundMessage): RunLifecycleEvent | undefined;
48
+ }
49
+ /**
50
+ * Bind a Tree and a decoder into the Tree's single {@link WireApplier}.
51
+ * @param tree - The tree the applier feeds.
52
+ * @param decoder - The codec decoder shared by every route into the tree.
53
+ * @returns The applier.
54
+ */
55
+ export declare const createWireApplier: <TInput extends CodecInputEvent, TOutput extends CodecOutputEvent, TProjection>(tree: TreeInternal<TInput, TOutput, TProjection>, decoder: Decoder<TInput, TOutput>) => WireApplier;
@@ -1,28 +1,135 @@
1
+ import { EVENT_RUN_END, EVENT_RUN_RESUME, EVENT_RUN_START, EVENT_RUN_SUSPEND } from '../../constants.js';
2
+ import { RunEndReason, RunLifecycleEvent } from './types.js';
1
3
  /**
2
4
  * Transport header builder.
3
5
  *
4
- * Single source of truth for which `x-ably-*` headers every transport
5
- * message carries. Used by the server transport (addMessages, streamResponse)
6
- * and will be used by the client transport (optimistic message stamping).
6
+ * Single source of truth for which transport headers every transport
7
+ * message carries. Used by the agent session (pipe) and by
8
+ * the client session (optimistic message stamping).
7
9
  */
10
+ import * as Ably from 'ably';
8
11
  /**
9
12
  * Build the standard transport header set for a message.
10
13
  * @param opts - The header values to include.
11
14
  * @param opts.role - Message role (e.g. "user", "assistant").
12
- * @param opts.turnId - Turn correlation ID.
13
- * @param opts.msgId - Message identity.
14
- * @param opts.turnClientId - ClientId of the turn initiator.
15
- * @param opts.parent - Preceding message's msg-id (for branching).
16
- * @param opts.forkOf - Forked message's msg-id (for edit/regen).
17
- * @param opts.amend - The msg-id of the existing message this message targets (cross-turn events).
18
- * @returns A headers record with the `x-ably-*` transport headers set.
15
+ * @param opts.runId - Run correlation ID, or `undefined` for a fresh client
16
+ * input (the agent mints run-ids, so it is not known synchronously). Omitted
17
+ * from the headers when undefined; a continuation still carries the known run-id.
18
+ * @param opts.codecMessageId - Message identity — the wire `codec-message-id` for this message.
19
+ * @param opts.runClientId - ClientId of the run initiator.
20
+ * @param opts.parent - Preceding message's codec-message-id (for branching).
21
+ * @param opts.forkOf - Forked user-prompt's codec-message-id (for edits — creates a Run-level fork sibling).
22
+ * @param opts.regenerates - Assistant codec-message-id this run regenerates. Stamps
23
+ * `msg-regenerate`. Distinct from `forkOf`: regenerate is a
24
+ * continuation of the prior run (no Run-level fork), with the message
25
+ * replacement resolved at projection extraction time.
26
+ * @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.
27
+ * @param opts.inputClientId - ClientId of the input event (the `ai-input`) that
28
+ * drove the current invocation. The agent reads it from the publisher's
29
+ * Ably-level `clientId` on the matched input event and re-stamps it on its
30
+ * own publishes (run lifecycle + outputs). Differs from `runClientId` on
31
+ * continuation invocations driven by an input from a non-owner.
32
+ * @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.
33
+ * @param opts.inputCodecMessageId - The codec-message-id of the input event that
34
+ * triggered the current invocation (the one whose `event-id` matched the
35
+ * invocation's `inputEventId`). The agent re-stamps it on every event it
36
+ * publishes for the invocation (run lifecycle + outputs), mirroring
37
+ * `inputClientId`, so the client can correlate any of those events back to
38
+ * the originating input by the id it owned at send time.
39
+ * @returns A headers record with the transport headers set.
19
40
  */
20
41
  export declare const buildTransportHeaders: (opts: {
21
42
  role: string;
22
- turnId: string;
23
- msgId: string;
24
- turnClientId?: string;
43
+ runId?: string;
44
+ codecMessageId: string;
45
+ runClientId?: string;
25
46
  parent?: string;
26
47
  forkOf?: string;
27
- amend?: string;
48
+ regenerates?: string;
49
+ invocationId?: string;
50
+ inputClientId?: string;
51
+ inputCodecMessageId?: string;
52
+ inputEventId?: string;
28
53
  }) => Record<string, string>;
54
+ /**
55
+ * Build the transport header set for a run-lifecycle event (run-start,
56
+ * run-resume, run-suspend, run-end). Single source of truth for lifecycle
57
+ * header stamping, mirroring {@link buildTransportHeaders} for the
58
+ * message-carrier path. Every field except `runId`/`runClientId` is optional
59
+ * and omitted when not provided.
60
+ *
61
+ * A resume suppresses the structural `parent` / `forkOf` / `regenerates`
62
+ * headers — the caller passes them only for a fresh run-start. `reason` is
63
+ * stamped only on run-end.
64
+ * @param opts - The lifecycle header values to include.
65
+ * @param opts.runId - The run's id.
66
+ * @param opts.runClientId - ClientId of the run initiator (empty string when unknown).
67
+ * @param opts.parent - Structural parent codec-message-id (fresh run-start only).
68
+ * @param opts.forkOf - Forked user-prompt codec-message-id (fresh run-start only).
69
+ * @param opts.regenerates - Regenerated assistant codec-message-id (fresh run-start only).
70
+ * @param opts.invocationId - Agent-minted invocation id; carried on every lifecycle event.
71
+ * @param opts.inputClientId - ClientId of the triggering input event.
72
+ * @param opts.inputCodecMessageId - Codec-message-id of the triggering input event.
73
+ * @param opts.reason - Terminal reason; stamped on run-end only.
74
+ * @param opts.errorCode - Numeric error code stamped as `error-code` on
75
+ * run-end. Set only when the run ended in error and the agent supplied an
76
+ * error to surface; gives codec-agnostic consumers a baseline failure detail.
77
+ * @param opts.errorMessage - Error message stamped as `error-message` on
78
+ * run-end. Paired with `errorCode`; set under the same condition.
79
+ * @returns A headers record with the lifecycle headers set.
80
+ */
81
+ export declare const buildLifecycleHeaders: (opts: {
82
+ runId: string;
83
+ runClientId: string;
84
+ parent?: string;
85
+ forkOf?: string;
86
+ regenerates?: string;
87
+ invocationId?: string;
88
+ inputClientId?: string;
89
+ inputCodecMessageId?: string;
90
+ reason?: RunEndReason;
91
+ errorCode?: number;
92
+ errorMessage?: string;
93
+ }) => Record<string, string>;
94
+ /** The four run-lifecycle Ably message names. */
95
+ type RunLifecycleName = typeof EVENT_RUN_START | typeof EVENT_RUN_SUSPEND | typeof EVENT_RUN_RESUME | typeof EVENT_RUN_END;
96
+ /**
97
+ * Whether an Ably message `name` is one of the run-lifecycle event names
98
+ * (run-start / run-suspend / run-resume / run-end). Single source of truth for
99
+ * the classification both decode loops and the agent's history scan use to
100
+ * route lifecycle wires away from the codec decoder. Narrows `name` to a
101
+ * lifecycle name so callers can pass it straight to {@link parseRunLifecycle}.
102
+ * @param name - The inbound Ably message `name`, or undefined.
103
+ * @returns True when `name` is a run-lifecycle event name.
104
+ */
105
+ export declare const isRunLifecycleName: (name: string | undefined) => name is RunLifecycleName;
106
+ /**
107
+ * Reconstruct the terminal `Ably.ErrorInfo` for a run that ended in error, from
108
+ * its run-end transport headers. Reads the `error-code` / `error-message`
109
+ * headers the agent stamps (see {@link buildLifecycleHeaders}); falls back to a
110
+ * generic code/message when a run ended in error without detail. Single source
111
+ * of truth for the header→ErrorInfo derivation, shared by the client session's
112
+ * `on('error')` emit and the Tree's `RunInfo.error`.
113
+ * @param headers - Transport headers from the inbound run-end message.
114
+ * @returns The reconstructed terminal error.
115
+ */
116
+ export declare const buildRunEndError: (headers: Record<string, string>) => Ably.ErrorInfo;
117
+ /**
118
+ * Parse an inbound run-lifecycle Ably message into a {@link RunLifecycleEvent}.
119
+ *
120
+ * Single source of truth for turning the wire run-lifecycle message `name`,
121
+ * transport headers, and channel serial into the structured lifecycle event
122
+ * the Tree consumes. Used by the client decode loop (live) and the View's
123
+ * history replay so both build the event identically.
124
+ * @param name - The inbound Ably message `name`.
125
+ * @param headers - Transport headers from the inbound Ably message.
126
+ * @param serial - Ably channel serial of the message, or `undefined` for an
127
+ * optimistic local event. Stamped onto the returned event.
128
+ * @param timestamp - Ably server timestamp (epoch ms) of the message, or
129
+ * `undefined` for an optimistic local event. Stamped onto the returned
130
+ * event; drives the Tree's event-log retention clock.
131
+ * @returns The lifecycle event, or `undefined` when `name` is not a
132
+ * run-lifecycle event name or the message carries no `run-id`.
133
+ */
134
+ export declare const parseRunLifecycle: (name: string, headers: Record<string, string>, serial: string | undefined, timestamp: number | undefined) => RunLifecycleEvent | undefined;
135
+ export {};
@@ -1,7 +1,6 @@
1
- export type { ActiveTurn, AddMessageOptions, AddMessagesResult, CancelFilter, CancelRequest, ClientTransport, ClientTransportOptions, CloseOptions, EventsNode, MessageNode, NewTurnOptions, SendOptions, ServerTransport, ServerTransportOptions, StreamResponseOptions, StreamResult, Tree, Turn, TurnEndReason, TurnLifecycleEvent, View, } from './types.js';
2
- export type { EventNode } from './types.js';
3
- export type { TreeNode } from './types.js';
4
- export type { TreeInternal } from './tree.js';
5
- export { createServerTransport } from './server-transport.js';
6
- export { createClientTransport } from './client-transport.js';
1
+ export type { ActiveRun, AgentSession, AgentSessionOptions, BranchSelection, CancelRequest, ClientSession, ClientSessionOptions, ConversationNode, InputNode, LoadConversationOptions, MessageNode, OutputEvent, PipeOptions, Run, RunEndParams, RunEndReason, RunInfo, RunLifecycleEvent, RunNode, RunNodeState, RunRuntime, RunView, SendOptions, StreamResult, Tree, View, } from './types.js';
2
+ export type { InvocationData } from './invocation.js';
3
+ export { Invocation } from './invocation.js';
4
+ export { createAgentSession } from './agent-session.js';
5
+ export { createClientSession } from './client-session.js';
7
6
  export { buildTransportHeaders } from './headers.js';
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Helpers for FIFO-bounded `Map`s — Maps used as capacity-limited buffers that
3
+ * must evict their oldest entry when full.
4
+ */
5
+ /**
6
+ * Make room for a new key in a FIFO-bounded map: if `map` is at (or over)
7
+ * `limit` and does not already contain `key`, evict the oldest entry (insertion
8
+ * order) and return its key so the caller can log the eviction. Returns
9
+ * `undefined` when nothing was evicted (the key already exists, the map is
10
+ * below the limit, or it is empty).
11
+ *
12
+ * The caller performs the actual set/append afterwards — this only frees a
13
+ * slot — so it works for maps whose values are replaced and for maps whose
14
+ * values are appended-to lists.
15
+ * @param map - The bounded map to evict from.
16
+ * @param key - The key about to be added; an existing key never evicts.
17
+ * @param limit - The maximum number of entries the map may hold.
18
+ * @returns The evicted key, or `undefined` if nothing was evicted.
19
+ */
20
+ export declare const evictOldestIfFull: <K, V>(map: Map<K, V>, key: K, limit: number) => K | undefined;