@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
@@ -1,73 +1,99 @@
1
- import { createContext as e, useCallback as t, useContext as n, useEffect as r, useMemo as i, useRef as a, useState as o } from "react";
2
- import * as s from "ably";
3
- import { ChannelProvider as c, useChannel as l } from "ably/react";
1
+ import * as e from "ably";
2
+ import { ChannelProvider as t, useAbly as n } from "ably/react";
3
+ import { createContext as r, useCallback as i, useContext as a, useEffect as o, useMemo as s, useRef as c, useState as l } from "react";
4
4
  import { jsx as u } from "react/jsx-runtime";
5
- //#region src/react/contexts/transport-context.ts
6
- var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-ably-msg-id", g = "x-ably-turn-client-id", _ = "x-ably-role", v = "x-ably-amend", y = "x-ably-cancel-turn-id", b = "x-ably-cancel-own", x = "x-ably-cancel-all", S = "x-ably-cancel-client-id", C = "x-ably-parent", w = "x-ably-fork-of", T = "x-ably-cancel", E = "x-ably-turn-start", D = "x-ably-turn-end", O = /* @__PURE__ */ function(e) {
7
- return e[e.BadRequest = 4e4] = "BadRequest", e[e.InvalidArgument = 40003] = "InvalidArgument", e[e.EncoderRecoveryFailed = 104e3] = "EncoderRecoveryFailed", e[e.TransportSubscriptionError = 104001] = "TransportSubscriptionError", e[e.CancelListenerError = 104002] = "CancelListenerError", e[e.TurnLifecycleError = 104003] = "TurnLifecycleError", e[e.TransportClosed = 104004] = "TransportClosed", e[e.TransportSendFailed = 104005] = "TransportSendFailed", e[e.ChannelContinuityLost = 104006] = "ChannelContinuityLost", e[e.ChannelNotReady = 104007] = "ChannelNotReady", e[e.StreamError = 104008] = "StreamError", e;
8
- }({}), ee = (e) => ({
5
+ //#region src/core/channel-options.ts
6
+ var d = [
7
+ "PUBLISH",
8
+ "SUBSCRIBE",
9
+ "PRESENCE",
10
+ "PRESENCE_SUBSCRIBE",
11
+ "ANNOTATION_PUBLISH"
12
+ ], f = ["OBJECT_SUBSCRIBE", "OBJECT_PUBLISH"], p = [
13
+ "PUBLISH",
14
+ "SUBSCRIBE",
15
+ "PRESENCE",
16
+ "PRESENCE_SUBSCRIBE",
17
+ "OBJECT_PUBLISH",
18
+ "OBJECT_SUBSCRIBE",
19
+ "ANNOTATION_PUBLISH",
20
+ "ANNOTATION_SUBSCRIBE"
21
+ ], m = (e) => {
22
+ if (e === void 0 || e.length === 0) return;
23
+ let t = new Set([...d, ...e]), n = p.filter((e) => t.has(e)), r = [...t].filter((e) => !p.includes(e)).toSorted();
24
+ return [...n, ...r];
25
+ }, h = "0.3.0", g = "ai-transport-js", _ = (e, t) => {
26
+ let n = e;
27
+ return n.options.agents = {
28
+ ...n.options.agents,
29
+ ...t
30
+ }, { params: { agent: y(t) } };
31
+ }, v = (e) => {
32
+ let t = e?.adapterTag, n = { [g]: h };
33
+ return t && (n[t] = h), n;
34
+ }, y = (e) => Object.entries(e).map(([e, t]) => `${e}/${t}`).join(" "), b = (e) => y(v(e)), x = (e, t) => _(e, v(t)), S = "stream", C = "status", w = "run-id", T = "invocation-id", E = "event-id", D = "codec-message-id", ee = "run-client-id", te = "input-client-id", O = "role", k = "parent", A = "fork-of", j = "msg-regenerate", M = "input-codec-message-id", ne = "error-code", re = "ai-cancel", N = /* @__PURE__ */ function(e) {
35
+ return e[e.BadRequest = 4e4] = "BadRequest", e[e.InvalidArgument = 40003] = "InvalidArgument", e[e.InsufficientCapability = 40160] = "InsufficientCapability", e[e.EncoderRecoveryFailed = 104e3] = "EncoderRecoveryFailed", e[e.SessionSubscriptionError = 104001] = "SessionSubscriptionError", e[e.CancelListenerError = 104002] = "CancelListenerError", e[e.RunLifecycleError = 104003] = "RunLifecycleError", e[e.SessionClosed = 104004] = "SessionClosed", e[e.SessionSendFailed = 104005] = "SessionSendFailed", e[e.ChannelContinuityLost = 104006] = "ChannelContinuityLost", e[e.ChannelNotReady = 104007] = "ChannelNotReady", e[e.StreamError = 104008] = "StreamError", e[e.InputEventNotFound = 104010] = "InputEventNotFound", e[e.HistoryFetchFailed = 104011] = "HistoryFetchFailed", e;
36
+ }({}), ie = (e) => ({
9
37
  logAction: (t, n, r) => {
10
38
  e.error(n, { detail: r });
11
39
  },
12
40
  shouldLog: () => !0
13
- }), te = s.Realtime.EventEmitter, k = class extends te {
41
+ }), ae = e.Realtime.EventEmitter, P = class extends ae {
14
42
  constructor(e) {
15
- super(ee(e));
43
+ super(ie(e));
16
44
  }
17
- }, A = /* @__PURE__ */ function(e) {
45
+ }, oe = /* @__PURE__ */ function(e) {
18
46
  return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
19
- }({}), ne = (e, t, n) => {
47
+ }({}), se = (e, t, n) => {
20
48
  let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
21
49
  switch (t) {
22
- case A.Trace:
23
- case A.Debug:
50
+ case "trace":
51
+ case "debug":
24
52
  console.log(i);
25
53
  break;
26
- case A.Info:
54
+ case "info":
27
55
  console.info(i);
28
56
  break;
29
- case A.Warn:
57
+ case "warn":
30
58
  console.warn(i);
31
59
  break;
32
- case A.Error:
60
+ case "error":
33
61
  console.error(i);
34
62
  break;
35
- case A.Silent: break;
36
- }
37
- }, re = (e) => new N(e.logHandler ?? ne, e.logLevel), j = /* @__PURE__ */ function(e) {
38
- return e[e.Trace = 0] = "Trace", e[e.Debug = 1] = "Debug", e[e.Info = 2] = "Info", e[e.Warn = 3] = "Warn", e[e.Error = 4] = "Error", e[e.Silent = 5] = "Silent", e;
39
- }(j || {}), M = new Map([
40
- [A.Trace, j.Trace],
41
- [A.Debug, j.Debug],
42
- [A.Info, j.Info],
43
- [A.Warn, j.Warn],
44
- [A.Error, j.Error],
45
- [A.Silent, j.Silent]
46
- ]), N = class e {
47
- constructor(e, t, n) {
48
- this._handler = e, this._context = n;
49
- let r = M.get(t);
50
- if (r === void 0) throw new s.ErrorInfo(`unable to create logger; invalid log level: ${t}`, O.InvalidArgument, 400);
51
- this._levelNumber = r;
63
+ case "silent": break;
64
+ }
65
+ }, ce = (e) => new ue(e.logHandler ?? se, e.logLevel), le = new Map([
66
+ ["trace", 0],
67
+ ["debug", 1],
68
+ ["info", 2],
69
+ ["warn", 3],
70
+ ["error", 4],
71
+ ["silent", 5]
72
+ ]), ue = class t {
73
+ constructor(t, n, r) {
74
+ this._handler = t, this._context = r;
75
+ let i = le.get(n);
76
+ if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, N.InvalidArgument, 400);
77
+ this._levelNumber = i;
52
78
  }
53
79
  trace(e, t) {
54
- this._write(e, A.Trace, j.Trace, t);
80
+ this._write(e, "trace", 0, t);
55
81
  }
56
82
  debug(e, t) {
57
- this._write(e, A.Debug, j.Debug, t);
83
+ this._write(e, "debug", 1, t);
58
84
  }
59
85
  info(e, t) {
60
- this._write(e, A.Info, j.Info, t);
86
+ this._write(e, "info", 2, t);
61
87
  }
62
88
  warn(e, t) {
63
- this._write(e, A.Warn, j.Warn, t);
89
+ this._write(e, "warn", 3, t);
64
90
  }
65
91
  error(e, t) {
66
- this._write(e, A.Error, j.Error, t);
92
+ this._write(e, "error", 4, t);
67
93
  }
68
- withContext(t) {
69
- let n = [...M.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? A.Error;
70
- return new e(this._handler, n, this._mergeContext(t));
94
+ withContext(e) {
95
+ let n = [...le.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? "error";
96
+ return new t(this._handler, n, this._mergeContext(e));
71
97
  }
72
98
  _write(e, t, n, r) {
73
99
  n >= this._levelNumber && this._handler(e, t, this._mergeContext(r));
@@ -78,155 +104,350 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
78
104
  ...e
79
105
  } : this._context : e ?? void 0;
80
106
  }
81
- }, P = (e) => {
82
- let t = e.extras;
83
- if (!t || typeof t != "object") return {};
84
- let n = t.headers;
85
- return !n || typeof n != "object" ? {} : n;
86
- }, F = (e) => {
107
+ }, F = (e) => e instanceof Error ? e.message : String(e), I = (t) => t instanceof e.ErrorInfo ? t : void 0, de = (e, t) => {
108
+ let n = e.extras;
109
+ if (!n || typeof n != "object") return {};
110
+ let r = n.ai;
111
+ if (!r || typeof r != "object") return {};
112
+ let i = r[t];
113
+ return !i || typeof i != "object" ? {} : i;
114
+ }, L = (e) => de(e, "transport"), fe = (e) => {
87
115
  let t = {
88
- [_]: e.role,
89
- [m]: e.turnId,
90
- [h]: e.msgId
116
+ [O]: e.role,
117
+ [D]: e.codecMessageId
91
118
  };
92
- return e.turnClientId !== void 0 && (t[g] = e.turnClientId), e.parent && (t[C] = e.parent), e.forkOf && (t[w] = e.forkOf), e.amend && (t[v] = e.amend), t;
93
- }, I = class {
94
- constructor(e, t) {
95
- this._turns = /* @__PURE__ */ new Map(), this._isTerminal = e, this._logger = t;
96
- }
97
- createStream(e) {
98
- this._logger.trace("StreamRouter.createStream();", { turnId: e });
99
- let t = {}, n = new ReadableStream({ start(e) {
100
- t.controller = e;
101
- } });
102
- if (!t.controller) throw new s.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", O.TransportSubscriptionError, 500);
103
- return this._turns.set(e, {
104
- controller: t.controller,
105
- turnId: e
106
- }), n;
107
- }
108
- closeStream(e) {
109
- let t = this._turns.get(e);
110
- if (!t) return !1;
111
- this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
112
- try {
113
- t.controller.close();
114
- } catch {}
115
- return this._turns.delete(e), !0;
116
- }
117
- errorStream(e, t) {
118
- let n = this._turns.get(e);
119
- if (!n) return !1;
120
- this._logger.debug("StreamRouter.errorStream(); erroring stream", { turnId: e });
121
- try {
122
- n.controller.error(t);
123
- } catch {}
124
- return this._turns.delete(e), !0;
119
+ return e.runId !== void 0 && (t[w] = e.runId), e.runClientId !== void 0 && (t[ee] = e.runClientId), e.parent && (t[k] = e.parent), e.forkOf && (t[A] = e.forkOf), e.regenerates && (t[j] = e.regenerates), e.invocationId && (t[T] = e.invocationId), e.inputClientId !== void 0 && (t[te] = e.inputClientId), e.inputCodecMessageId !== void 0 && (t[M] = e.inputCodecMessageId), e.inputEventId && (t[E] = e.inputEventId), t;
120
+ }, pe = (e) => e === "ai-run-start" || e === "ai-run-suspend" || e === "ai-run-resume" || e === "ai-run-end", R = (t) => {
121
+ let n = t[ne], r = n === void 0 ? NaN : Number(n), i = Number.isFinite(r) ? r : N.SessionSubscriptionError, a = t["error-message"] ?? "agent reported an error", o = i >= 1e4 && i < 6e4 ? Math.floor(i / 100) : 500;
122
+ return new e.ErrorInfo(a, i, o);
123
+ }, me = (e, t, n, r) => {
124
+ let i = t[w];
125
+ if (!i) return;
126
+ let a = t["run-client-id"] ?? "", o = r === void 0 ? {} : { timestamp: r };
127
+ if (e === "ai-run-start") {
128
+ let e = t[k], r = t[A], s = t[j];
129
+ return {
130
+ type: "start",
131
+ runId: i,
132
+ clientId: a,
133
+ serial: n,
134
+ invocationId: t["invocation-id"] ?? "",
135
+ ...o,
136
+ ...e !== void 0 && { parent: e },
137
+ ...r !== void 0 && { forkOf: r },
138
+ ...s !== void 0 && { regenerates: s }
139
+ };
125
140
  }
126
- route(e, t) {
127
- let n = this._turns.get(e);
128
- if (!n) return !1;
129
- try {
130
- n.controller.enqueue(t);
131
- } catch {
132
- return this._turns.delete(e), !1;
133
- }
134
- return this._isTerminal(t) && this.closeStream(e), !0;
141
+ if (e === "ai-run-suspend") return {
142
+ type: "suspend",
143
+ runId: i,
144
+ clientId: a,
145
+ serial: n,
146
+ invocationId: t["invocation-id"] ?? "",
147
+ ...o
148
+ };
149
+ if (e === "ai-run-resume") return {
150
+ type: "resume",
151
+ runId: i,
152
+ clientId: a,
153
+ serial: n,
154
+ invocationId: t["invocation-id"] ?? "",
155
+ ...o
156
+ };
157
+ if (e === "ai-run-end") {
158
+ let e = t["run-reason"] ?? "complete", r = t["invocation-id"] ?? "";
159
+ return e === "error" ? {
160
+ type: "end",
161
+ runId: i,
162
+ clientId: a,
163
+ serial: n,
164
+ invocationId: r,
165
+ reason: e,
166
+ ...o,
167
+ error: R(t)
168
+ } : {
169
+ type: "end",
170
+ runId: i,
171
+ clientId: a,
172
+ serial: n,
173
+ invocationId: r,
174
+ reason: e,
175
+ ...o
176
+ };
135
177
  }
136
- has(e) {
137
- return this._turns.has(e);
178
+ }, he = (e, t, n) => {
179
+ let r = L(n), i = n.serial, a = n.timestamp;
180
+ if (pe(n.name)) {
181
+ let t = me(n.name, r, i, a);
182
+ return t && e.applyRunLifecycle(t), t;
183
+ }
184
+ let { inputs: o, outputs: s } = t.decode(n);
185
+ (o.length > 0 || s.length > 0 || r["run-id"]) && e.applyMessage({
186
+ inputs: o,
187
+ outputs: s
188
+ }, r, i, a, n.version.serial);
189
+ }, ge = (e, t) => ({ apply: (n) => he(e, t, n) }), _e = class e {
190
+ constructor(e) {
191
+ this.inputEventId = e.inputEventId, this.sessionName = e.sessionName;
138
192
  }
139
- }, L = (e, t) => new I(e, t), R = class {
140
- get structuralVersion() {
141
- return this._structuralVersion;
193
+ static fromJSON(t) {
194
+ return new e(t);
142
195
  }
143
- constructor(e) {
144
- this._nodeIndex = /* @__PURE__ */ new Map(), this._sortedList = [], this._parentIndex = /* @__PURE__ */ new Map(), this._turnClientIds = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._structuralVersion = 0, this._logger = e, this._emitter = new k(e);
196
+ toJSON() {
197
+ return {
198
+ inputEventId: this.inputEventId,
199
+ sessionName: this.sessionName
200
+ };
201
+ }
202
+ }, ve = async (t, n) => {
203
+ if (!t) throw new e.ErrorInfo(`unable to ${n}; connect() must be called before ${n}()`, N.InvalidArgument, 400);
204
+ return t;
205
+ }, ye = async (e, t, n, r) => {
206
+ if (t !== void 0) try {
207
+ await e.detach();
208
+ } catch (e) {
209
+ n?.debug(`${r}.close(); channel detach failed`, { error: e });
210
+ }
211
+ }, be = (e) => {
212
+ let { current: t, resumed: n } = e;
213
+ return t === "failed" || t === "suspended" || t === "detached" || t === "attached" && !n;
214
+ }, xe = (t, n) => {
215
+ let { current: r } = t;
216
+ return new e.ErrorInfo(`unable to ${n}; channel continuity lost (${r}${r === "attached" ? ", resumed: false" : ""})`, N.ChannelContinuityLost, 500, t.reason);
217
+ }, z = (e) => [...e.inputs.map((e) => ({
218
+ direction: "input",
219
+ event: e
220
+ })), ...e.outputs.map((e) => ({
221
+ direction: "output",
222
+ event: e
223
+ }))], Se = class {
224
+ constructor() {
225
+ this._entries = [], this._swept = !1;
226
+ }
227
+ get swept() {
228
+ return this._swept;
229
+ }
230
+ record(e, t, n, r, i) {
231
+ let a = this._recordEntry(e, t, this._swept ? [] : n, r, i);
232
+ return a === void 0 ? "dropped" : this._swept || a === this._entries.length - 1 ? "incremental" : "refold";
233
+ }
234
+ replay(e) {
235
+ for (let t of this._entries) for (let n of t.events) e(n, t.serial, t.messageId);
236
+ }
237
+ sweep() {
238
+ this._swept = !0;
239
+ for (let e of this._entries) e.events.length = 0;
240
+ }
241
+ _recordEntry(e, t, n, r, i) {
242
+ for (let a = this._entries.length - 1; a >= 0; a--) {
243
+ let o = this._entries[a];
244
+ if (!o) break;
245
+ if (o.serial === e) return r !== void 0 && (r <= o.decodedThrough || !i) ? void 0 : (o.events.push(...n), r !== void 0 && (o.decodedThrough = r), a);
246
+ if (o.serial < e) return this._entries.splice(a + 1, 0, {
247
+ serial: e,
248
+ messageId: t,
249
+ events: [...n],
250
+ decodedThrough: r ?? e
251
+ }), a + 1;
252
+ }
253
+ return this._entries.unshift({
254
+ serial: e,
255
+ messageId: t,
256
+ events: [...n],
257
+ decodedThrough: r ?? e
258
+ }), 0;
259
+ }
260
+ }, B = (e) => e.kind === "run" ? e.runId : e.codecMessageId, V = (e) => e.kind === "run" ? e.startSerial : e.serial, H = (e, t, n) => {
261
+ let r = e.get(t);
262
+ r || (r = /* @__PURE__ */ new Set(), e.set(t, r)), r.add(n);
263
+ }, U = (e, t, n) => {
264
+ let r = e.get(t);
265
+ r && (r.delete(n), r.size === 0 && e.delete(t));
266
+ }, Ce = class {
267
+ constructor(e, t) {
268
+ this._nodeIndex = /* @__PURE__ */ new Map(), this._codecMessageIdToNodeKey = /* @__PURE__ */ new Map(), this._sortedNodes = [], this._parentIndex = /* @__PURE__ */ new Map(), this._replyRunsByInput = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._structuralVersion = 0, this._siblingCache = /* @__PURE__ */ new Map(), this._siblingCacheVersion = -1, this._eventIdIndex = /* @__PURE__ */ new Map(), this._clock = 0, this._sweepQueue = [], this._codec = e, this._logger = t, this._emitter = new P(t);
145
269
  }
146
270
  _compareNodes(e, t) {
147
- let n = e.node.serial, r = t.node.serial;
271
+ let n = V(e.node), r = V(t.node);
148
272
  return n === void 0 && r === void 0 ? e.insertSeq - t.insertSeq : n === void 0 ? 1 : r === void 0 || n < r ? -1 : n > r ? 1 : e.insertSeq - t.insertSeq;
149
273
  }
150
- _insertSorted(e) {
151
- if (e.node.serial === void 0) {
152
- this._sortedList.push(e);
274
+ _insertSortedNode(e) {
275
+ if (V(e.node) === void 0) {
276
+ this._sortedNodes.push(e);
153
277
  return;
154
278
  }
155
- let t = 0, n = this._sortedList.length;
279
+ let t = 0, n = this._sortedNodes.length;
156
280
  for (; t < n;) {
157
- let r = t + n >>> 1, i = this._sortedList[r];
281
+ let r = t + n >>> 1, i = this._sortedNodes[r];
158
282
  if (!i) break;
159
283
  this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
160
284
  }
161
- this._sortedList.splice(t, 0, e);
285
+ this._sortedNodes.splice(t, 0, e);
286
+ }
287
+ _removeSortedNode(e) {
288
+ let t = this._sortedNodes.indexOf(e);
289
+ t !== -1 && this._sortedNodes.splice(t, 1);
290
+ }
291
+ _insertNode(e, t, n) {
292
+ this._nodeIndex.set(e, t), this._addToParentIndex(n, e), this._insertSortedNode(t), this._structuralVersion++;
293
+ }
294
+ _promoteSerial(e) {
295
+ this._removeSortedNode(e), this._insertSortedNode(e), this._structuralVersion++;
296
+ }
297
+ _foldInto(e, t, n, r) {
298
+ for (let i of t) try {
299
+ e.node.projection = this._codec.fold(e.node.projection, i, {
300
+ serial: n ?? "",
301
+ messageId: r
302
+ });
303
+ } catch (t) {
304
+ this._logger.error("Tree._foldInto(); fold threw", {
305
+ key: B(e.node),
306
+ messageId: r,
307
+ err: t
308
+ });
309
+ }
310
+ }
311
+ _recordAndFold(e, t, n, r, i, a) {
312
+ if (n === void 0 || t.length === 0) {
313
+ n === void 0 && t.length > 0 && (e.optimistic = !0), this._foldInto(e, t, n, r);
314
+ return;
315
+ }
316
+ let o = e.log.record(n, r, t, i, a);
317
+ if (o === "dropped") {
318
+ this._logger.debug("Tree._recordAndFold(); version guard dropped re-delivered wire", {
319
+ key: B(e.node),
320
+ serial: n,
321
+ version: i,
322
+ swept: e.log.swept
323
+ });
324
+ return;
325
+ }
326
+ if (e.optimistic && !e.log.swept) {
327
+ e.optimistic = !1, this._refold(e);
328
+ return;
329
+ }
330
+ if (o === "refold") {
331
+ this._refold(e);
332
+ return;
333
+ }
334
+ e.log.swept && this._logger.warn("Tree._recordAndFold(); late wire after log retention window; folding in arrival order", {
335
+ key: B(e.node),
336
+ serial: n
337
+ }), this._foldInto(e, t, n, r);
338
+ }
339
+ _refold(e) {
340
+ let t = this._codec.init();
341
+ e.log.replay((n, r, i) => {
342
+ try {
343
+ t = this._codec.fold(t, n, {
344
+ serial: r,
345
+ messageId: i
346
+ });
347
+ } catch (t) {
348
+ this._logger.error("Tree._refold(); fold threw", {
349
+ key: B(e.node),
350
+ messageId: i,
351
+ err: t
352
+ });
353
+ }
354
+ }), e.node.projection = t;
355
+ }
356
+ _recordActivity(e, t) {
357
+ t !== void 0 && (t > e.lastActivityTs && (e.lastActivityTs = t), t > this._clock && (this._clock = t, this._drainSweepQueue()));
162
358
  }
163
- _removeSorted(e) {
164
- let t = this._sortedList.indexOf(e);
165
- t !== -1 && this._sortedList.splice(t, 1);
359
+ _maybeQueueSweep(e) {
360
+ let t = e.node;
361
+ t.kind === "run" && (e.log.swept || e.sweepQueued || e.runStartSeen && (t.state.status === "active" || t.state.status === "suspended" || (e.sweepQueued = !0, this._sweepQueue.push(t.runId))));
362
+ }
363
+ _drainSweepQueue() {
364
+ for (; this._sweepQueue.length > 0;) {
365
+ let e = this._sweepQueue[0], t = e === void 0 ? void 0 : this._nodeIndex.get(e);
366
+ if (!t || t.log.swept) {
367
+ this._sweepQueue.shift();
368
+ continue;
369
+ }
370
+ if (t.lastActivityTs + 12e4 >= this._clock) return;
371
+ this._sweepQueue.shift(), t.sweepQueued = !1, t.log.sweep(), this._logger.debug("Tree._drainSweepQueue(); dropped event-log payloads, kept replay keys", {
372
+ key: e,
373
+ lastActivityTs: t.lastActivityTs
374
+ });
375
+ }
166
376
  }
167
377
  _addToParentIndex(e, t) {
168
- let n = this._parentIndex.get(e);
169
- n || (n = /* @__PURE__ */ new Set(), this._parentIndex.set(e, n)), n.add(t);
378
+ H(this._parentIndex, e, t);
170
379
  }
171
380
  _removeFromParentIndex(e, t) {
172
- let n = this._parentIndex.get(e);
173
- n && (n.delete(t), n.size === 0 && this._parentIndex.delete(e));
381
+ U(this._parentIndex, e, t);
382
+ }
383
+ _parentKeyOf(e) {
384
+ let t = e.parentCodecMessageId;
385
+ return t === void 0 ? void 0 : this._codecMessageIdToNodeKey.get(t);
386
+ }
387
+ _inputGroupRoot(e) {
388
+ let t = e, n = new Set([B(t)]);
389
+ for (; t.forkOf !== void 0 && !n.has(t.forkOf);) {
390
+ let e = this._nodeIndex.get(t.forkOf);
391
+ if (e?.node.kind !== "input" || e.node.parentCodecMessageId !== t.parentCodecMessageId) break;
392
+ t = e.node, n.add(B(t));
393
+ }
394
+ return t;
174
395
  }
175
396
  _getSiblingGroup(e) {
176
- let t = this._nodeIndex.get(e);
177
- if (!t) return [];
178
- let n = t.node, r = new Set([n.msgId]);
179
- for (; n.forkOf && !r.has(n.forkOf);) {
180
- let e = this._nodeIndex.get(n.forkOf);
181
- if (!e || e.node.parentId !== n.parentId) break;
182
- n = e.node, r.add(n.msgId);
183
- }
184
- let i = n.parentId, a = n.msgId, o = [], s = this._parentIndex.get(i);
185
- if (s) for (let e of s) {
397
+ this._siblingCacheVersion !== this._structuralVersion && (this._siblingCache.clear(), this._siblingCacheVersion = this._structuralVersion);
398
+ let t = this._siblingCache.get(e);
399
+ if (t) return t;
400
+ let n = this._nodeIndex.get(e);
401
+ if (!n) return [];
402
+ let r = n.node;
403
+ r.kind === "input" && (r = this._inputGroupRoot(r));
404
+ let i = r.parentCodecMessageId, a = [], o = this._parentIndex.get(i);
405
+ if (o) for (let e of o) {
186
406
  let t = this._nodeIndex.get(e);
187
- t && this._isSiblingOf(t.node, a) && o.push(t);
407
+ t && this._isSiblingOf(t.node, r) && a.push(t);
188
408
  }
189
- return o.sort((e, t) => this._compareNodes(e, t)), o.map((e) => e.node);
409
+ a.sort((e, t) => this._compareNodes(e, t));
410
+ for (let e of a) this._siblingCache.set(B(e.node), a);
411
+ return this._siblingCache.set(e, a), a;
190
412
  }
191
413
  _isSiblingOf(e, t) {
192
- if (e.msgId === t) return !0;
193
- let n = e, r = new Set([n.msgId]);
194
- for (; n.forkOf;) {
195
- if (n.forkOf === t) return !0;
196
- if (r.has(n.forkOf)) break;
197
- let e = this._nodeIndex.get(n.forkOf);
414
+ if (e.kind !== t.kind || e.parentCodecMessageId !== t.parentCodecMessageId) return !1;
415
+ if (e.kind === "run") return !0;
416
+ let n = B(t);
417
+ if (B(e) === n) return !0;
418
+ let r = e, i = new Set([B(r)]);
419
+ for (; r.kind === "input" && r.forkOf !== void 0;) {
420
+ if (r.forkOf === n) return !0;
421
+ if (i.has(r.forkOf)) break;
422
+ let e = this._nodeIndex.get(r.forkOf);
198
423
  if (!e) break;
199
- n = e.node, r.add(n.msgId);
424
+ r = e.node, i.add(B(r));
200
425
  }
201
426
  return !1;
202
427
  }
203
428
  getGroupRoot(e) {
204
429
  let t = this._nodeIndex.get(e);
205
430
  if (!t) return e;
206
- let n = t.node, r = new Set([n.msgId]);
207
- for (; n.forkOf && !r.has(n.forkOf);) {
208
- let e = this._nodeIndex.get(n.forkOf);
209
- if (!e || e.node.parentId !== n.parentId) break;
210
- n = e.node, r.add(n.msgId);
211
- }
212
- return n.msgId;
431
+ if (t.node.kind === "input") return B(this._inputGroupRoot(t.node));
432
+ let n = this._getSiblingGroup(e)[0]?.node;
433
+ return n ? B(n) : e;
213
434
  }
214
- flattenNodes(e) {
215
- this._logger.trace("DefaultTree.flattenNodes();");
435
+ visibleNodes(e = /* @__PURE__ */ new Map()) {
436
+ this._logger.trace("DefaultTree.visibleNodes();");
216
437
  let t = [], n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map();
217
- for (let i of this._sortedList) {
218
- let a = i.node, { msgId: o, parentId: s } = a;
438
+ for (let i of this._sortedNodes) {
439
+ let a = i.node, o = B(a), s = this._parentKeyOf(a);
219
440
  if (s !== void 0 && !n.has(s)) continue;
220
441
  let c = this._getSiblingGroup(o);
221
442
  if (c.length > 1) {
222
443
  let t = this.getGroupRoot(o), n = r.get(t);
223
444
  if (n === void 0) {
224
445
  let i = e.get(t);
225
- if (i && c.some((e) => e.msgId === i)) n = i;
446
+ if (i !== void 0 && c.some((e) => B(e.node) === i)) n = i;
226
447
  else {
227
448
  let e = c.at(-1);
228
449
  if (!e) break;
229
- n = e.msgId;
450
+ n = B(e.node);
230
451
  }
231
452
  r.set(t, n);
232
453
  }
@@ -236,64 +457,196 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
236
457
  }
237
458
  return t;
238
459
  }
239
- getSiblings(e) {
240
- return this._logger.trace("DefaultTree.getSiblings();", { msgId: e }), this._getSiblingGroup(e).map((e) => e.message);
460
+ getRunNode(e) {
461
+ this._logger.trace("DefaultTree.getRunNode();", { runId: e });
462
+ let t = this._nodeIndex.get(e)?.node;
463
+ return t?.kind === "run" ? t : void 0;
241
464
  }
242
- getSiblingNodes(e) {
243
- return this._getSiblingGroup(e);
465
+ getNode(e) {
466
+ return this._logger.trace("DefaultTree.getNode();", { key: e }), this._nodeIndex.get(e)?.node;
244
467
  }
245
- hasSiblings(e) {
246
- return this._getSiblingGroup(e).length > 1;
468
+ getNodeByCodecMessageId(e) {
469
+ this._logger.trace("DefaultTree.getNodeByCodecMessageId();", { codecMessageId: e });
470
+ let t = this._codecMessageIdToNodeKey.get(e);
471
+ return t === void 0 ? void 0 : this._nodeIndex.get(t)?.node;
247
472
  }
248
- getNode(e) {
249
- return this._logger.trace("DefaultTree.getNode();", { msgId: e }), this._nodeIndex.get(e)?.node;
250
- }
251
- getHeaders(e) {
252
- return this._logger.trace("DefaultTree.getHeaders();", { msgId: e }), this._nodeIndex.get(e)?.node.headers;
253
- }
254
- upsert(e, t, n, r) {
255
- let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0, o = this._nodeIndex.get(e);
256
- if (o) {
257
- o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("Tree.upsert(); promoting serial", {
258
- msgId: e,
259
- serial: r
260
- }), o.node.serial = r, this._removeSorted(o), this._insertSorted(o), this._structuralVersion++), this._emitter.emit("update");
473
+ getReplyRuns(e) {
474
+ let t = this._replyRunsByInput.get(e);
475
+ if (!t) return [];
476
+ let n = [];
477
+ for (let e of t) {
478
+ let t = this._nodeIndex.get(e)?.node;
479
+ t?.kind === "run" && n.push(t);
480
+ }
481
+ return n;
482
+ }
483
+ getSiblingNodes(e) {
484
+ return this._logger.trace("DefaultTree.getSiblingNodes();", { key: e }), this._getSiblingGroup(e).map((e) => e.node);
485
+ }
486
+ applyMessage(e, t, n, r, i) {
487
+ let a = t[w], o = t[D], s = a === void 0 && o !== void 0 && t.role === "user" && e.inputs.length > 0 ? o : void 0;
488
+ if (a === void 0 && s === void 0) {
489
+ this._logger.warn("Tree.applyMessage(); message has no run-id and is not a user input; skipping");
261
490
  return;
262
491
  }
263
- this._logger.trace("Tree.upsert(); inserting new node", {
264
- msgId: e,
265
- parentId: i,
266
- forkOf: a
492
+ let c = z(e), l = s ?? a;
493
+ if (c.length === 0 && l !== void 0 && !this._nodeIndex.has(l)) return;
494
+ let u = this._structuralVersion;
495
+ s === void 0 ? a !== void 0 && this._applyRunMessage(a, e, t, n, r, i) : this._applyInputMessage(s, t, n, r, i, c), this._structuralVersion !== u && this._emitter.emit("update");
496
+ }
497
+ _applyInputMessage(e, t, n, r, i, a) {
498
+ let o = this._nodeIndex.get(e);
499
+ o ? o.node.kind === "input" && n && !o.node.serial && (this._logger.debug("Tree.applyMessage(); promoting input serial", {
500
+ codecMessageId: e,
501
+ serial: n
502
+ }), o.node.serial = n, this._promoteSerial(o)) : (o = this._createInputNodeFromHeaders(e, t, n), this._insertNode(e, o, o.node.parentCodecMessageId), this._codecMessageIdToNodeKey.set(e, e), this._logger.debug("Tree.applyMessage(); created input node", { codecMessageId: e })), this._recordActivity(o, r), this._recordAndFold(o, a, n, e, i, t[S] === "true"), this._emitter.emit("output", {
503
+ runId: void 0,
504
+ inputCodecMessageId: e,
505
+ codecMessageId: e,
506
+ serial: n,
507
+ events: []
267
508
  });
268
- let s = {
269
- node: {
270
- kind: "message",
271
- message: t,
272
- msgId: e,
273
- parentId: i,
274
- forkOf: a,
275
- headers: { ...n },
276
- serial: r
277
- },
278
- insertSeq: this._seqCounter++
279
- };
280
- this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s), this._structuralVersion++, this._emitter.emit("update");
509
+ }
510
+ _applyRunMessage(e, t, n, r, i, a) {
511
+ let o = n[D], s = n[M], c = z(t), l = t.outputs, u = this._nodeIndex.get(e);
512
+ if (!u && o !== void 0) {
513
+ let e = this._codecMessageIdToNodeKey.get(o), t = e === void 0 ? void 0 : this._nodeIndex.get(e);
514
+ t?.node.kind === "run" && t.node.startSerial === void 0 && (u = t);
515
+ }
516
+ u ? r && u.node.kind === "run" && !u.node.startSerial && (this._logger.debug("Tree.applyMessage(); promoting startSerial", {
517
+ runId: e,
518
+ serial: r
519
+ }), u.node.startSerial = r, this._promoteSerial(u)) : (u = this._createRunFromHeaders(e, n, r), this._insertNode(e, u, u.node.parentCodecMessageId), this._indexReplyRun(u.node, e), this._logger.debug("Tree.applyMessage(); created new Run", { runId: e }));
520
+ let d = B(u.node);
521
+ o && this._codecMessageIdToNodeKey.set(o, d), this._recordActivity(u, i), this._recordAndFold(u, c, r, o, a, n[S] === "true"), this._emitter.emit("output", {
522
+ runId: d,
523
+ inputCodecMessageId: s,
524
+ codecMessageId: o,
525
+ serial: r,
526
+ events: l
527
+ });
528
+ }
529
+ _indexReplyRun(e, t) {
530
+ e.parentCodecMessageId !== void 0 && H(this._replyRunsByInput, e.parentCodecMessageId, t);
531
+ }
532
+ applyRunLifecycle(e) {
533
+ this._logger.trace("DefaultTree.applyRunLifecycle();", {
534
+ type: e.type,
535
+ runId: e.runId
536
+ });
537
+ let t = this._structuralVersion;
538
+ switch (e.type) {
539
+ case "start":
540
+ this._applyRunStart(e);
541
+ break;
542
+ case "suspend":
543
+ this._applyRunSuspend(e);
544
+ break;
545
+ case "resume":
546
+ this._applyRunResume(e);
547
+ break;
548
+ case "end":
549
+ this._applyRunEnd(e);
550
+ break;
551
+ }
552
+ this._emitter.emit("run", e), this._structuralVersion !== t && this._emitter.emit("update");
553
+ }
554
+ _applyRunStart(e) {
555
+ let t = this._nodeIndex.get(e.runId);
556
+ if (t?.node.kind === "run") {
557
+ let n = t.node;
558
+ if (n.state.status === "suspended" && (n.state = { status: "active" }), e.serial && !n.startSerial && (n.startSerial = e.serial, this._promoteSerial(t)), n.parentCodecMessageId === void 0 && e.parent !== void 0 && (n.parentCodecMessageId = e.parent, this._removeFromParentIndex(void 0, e.runId), this._addToParentIndex(n.parentCodecMessageId, e.runId), this._indexReplyRun(n, e.runId), this._structuralVersion++), n.forkOf === void 0 && e.forkOf !== void 0) {
559
+ let t = this._codecMessageIdToNodeKey.get(e.forkOf);
560
+ t !== void 0 && t !== e.runId && (n.forkOf = t, this._structuralVersion++);
561
+ }
562
+ n.regeneratesCodecMessageId === void 0 && e.regenerates !== void 0 && (n.regeneratesCodecMessageId = e.regenerates, this._structuralVersion++), n.invocationId === "" && e.invocationId !== "" && (n.invocationId = e.invocationId), t.runStartSeen = !0, this._recordActivity(t, e.timestamp), this._maybeQueueSweep(t);
563
+ } else if (!t) {
564
+ let t = this._createRunFromLifecycle(e);
565
+ this._insertNode(e.runId, t, t.node.parentCodecMessageId), this._indexReplyRun(t.node, e.runId), this._recordActivity(t, e.timestamp);
566
+ }
567
+ }
568
+ _applyRunSuspend(e) {
569
+ let t = this._nodeIndex.get(e.runId);
570
+ t?.node.kind === "run" && (t.node.state = { status: "suspended" }, t.node.endSerial = e.serial, this._recordActivity(t, e.timestamp));
571
+ }
572
+ _applyRunResume(e) {
573
+ let t = this._nodeIndex.get(e.runId);
574
+ t?.node.kind === "run" && t.node.state.status === "suspended" && (t.node.state = { status: "active" }, this._recordActivity(t, e.timestamp));
575
+ }
576
+ _applyRunEnd(e) {
577
+ let t = this._nodeIndex.get(e.runId);
578
+ t?.node.kind === "run" && (t.node.state = e.reason === "error" ? {
579
+ status: "error",
580
+ error: e.error
581
+ } : { status: e.reason }, t.node.endSerial = e.serial, this._recordActivity(t, e.timestamp), this._maybeQueueSweep(t));
281
582
  }
282
583
  delete(e) {
283
584
  let t = this._nodeIndex.get(e);
284
- if (!t) return;
285
- this._logger.debug("Tree.delete();", { msgId: e });
286
- let { node: n } = t;
287
- this._removeFromParentIndex(n.parentId, e), this._removeSorted(t), this._nodeIndex.delete(e), this._structuralVersion++, this._emitter.emit("update");
585
+ t && (this._logger.debug("Tree.delete();", { key: e }), this._removeFromParentIndex(t.node.parentCodecMessageId, e), this._removeSortedNode(t), this._nodeIndex.delete(e), t.node.kind === "run" && t.node.parentCodecMessageId !== void 0 && U(this._replyRunsByInput, t.node.parentCodecMessageId, e), this._structuralVersion++, this._emitter.emit("update"));
586
+ }
587
+ _createRunFromHeaders(e, t, n) {
588
+ let r = t[A];
589
+ return this._buildRunNode({
590
+ runId: e,
591
+ parentCodecMessageId: t[k],
592
+ forkOf: r ? this._codecMessageIdToNodeKey.get(r) : void 0,
593
+ regeneratesCodecMessageId: t[j],
594
+ clientId: t["run-client-id"] ?? "",
595
+ invocationId: t["invocation-id"] ?? "",
596
+ startSerial: n,
597
+ runStartSeen: !1
598
+ });
288
599
  }
289
- getActiveTurnIds() {
290
- this._logger.trace("DefaultTree.getActiveTurnIds();");
291
- let e = /* @__PURE__ */ new Map();
292
- for (let [t, n] of this._turnClientIds) {
293
- let r = e.get(n);
294
- r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
295
- }
296
- return e;
600
+ _wrapNode(e, t = !1) {
601
+ return {
602
+ node: e,
603
+ insertSeq: this._seqCounter++,
604
+ log: new Se(),
605
+ lastActivityTs: 0,
606
+ runStartSeen: t,
607
+ sweepQueued: !1,
608
+ optimistic: !1
609
+ };
610
+ }
611
+ _buildRunNode(e) {
612
+ let t = {
613
+ kind: "run",
614
+ runId: e.runId,
615
+ parentCodecMessageId: e.parentCodecMessageId,
616
+ forkOf: e.forkOf,
617
+ regeneratesCodecMessageId: e.regeneratesCodecMessageId,
618
+ clientId: e.clientId,
619
+ invocationId: e.invocationId,
620
+ state: { status: "active" },
621
+ projection: this._codec.init(),
622
+ startSerial: e.startSerial,
623
+ endSerial: void 0
624
+ };
625
+ return this._wrapNode(t, e.runStartSeen);
626
+ }
627
+ _createInputNodeFromHeaders(e, t, n) {
628
+ let r = t[A], i = {
629
+ kind: "input",
630
+ codecMessageId: e,
631
+ parentCodecMessageId: t[k],
632
+ forkOf: r,
633
+ projection: this._codec.init(),
634
+ serial: n
635
+ };
636
+ return this._wrapNode(i);
637
+ }
638
+ _createRunFromLifecycle(e) {
639
+ let t = e.forkOf;
640
+ return this._buildRunNode({
641
+ runId: e.runId,
642
+ parentCodecMessageId: e.parent,
643
+ forkOf: t ? this._codecMessageIdToNodeKey.get(t) : void 0,
644
+ regeneratesCodecMessageId: e.regenerates,
645
+ clientId: e.clientId,
646
+ invocationId: e.invocationId,
647
+ startSerial: e.serial,
648
+ runStartSeen: !0
649
+ });
297
650
  }
298
651
  on(e, t) {
299
652
  let n = t;
@@ -302,195 +655,216 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
302
655
  };
303
656
  }
304
657
  emitAblyMessage(e) {
305
- this._logger.trace("DefaultTree.emitAblyMessage();"), this._emitter.emit("ably-message", e);
306
- }
307
- emitTurn(e) {
308
- this._logger.trace("DefaultTree.emitTurn();", { turnId: e.turnId }), this._emitter.emit("turn", e);
309
- }
310
- trackTurn(e, t) {
311
- this._logger.trace("DefaultTree.trackTurn();", {
312
- turnId: e,
313
- clientId: t
314
- }), this._turnClientIds.set(e, t);
315
- }
316
- untrackTurn(e) {
317
- this._logger.trace("DefaultTree.untrackTurn();", { turnId: e }), this._turnClientIds.delete(e);
318
- }
319
- }, z = (e) => new R(e), B = (e) => {
320
- let t = [...e.rawMessages].toReversed(), n = e.codec.createDecoder(), r = /* @__PURE__ */ new Map(), i = e.codec.createAccumulator(), a = 0, o = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map(), c = [], l = [];
321
- for (let u of t) {
322
- let t = n.decode(u), d = P(u), f = d[m], p = d[h], g = u.serial, _ = d[v];
323
- if (_) {
324
- for (let e of r.values()) if (e.msgHeaders.has(_)) {
325
- let n = [...e.msgHeaders.keys()].indexOf(_), r = n === -1 ? void 0 : e.accumulator.messages[n];
326
- r && e.accumulator.initMessage(_, r), e.accumulator.processOutputs(t), l.push({
327
- accumulator: e.accumulator,
328
- messageId: _
329
- });
330
- break;
331
- }
332
- continue;
658
+ this._logger.trace("DefaultTree.emitAblyMessage();");
659
+ let t = L(e)[E];
660
+ t !== void 0 && !this._eventIdIndex.has(t) && this._eventIdIndex.set(t, e), this._emitter.emit("ably-message", e);
661
+ }
662
+ findAblyMessageByEventId(e) {
663
+ return this._eventIdIndex.get(e);
664
+ }
665
+ }, we = (e, t) => new Ce(e, t), Te = (t, n) => new Promise((r, i) => {
666
+ if (n?.aborted) {
667
+ i(new e.ErrorInfo("unable to wait; signal aborted", N.InvalidArgument, 400));
668
+ return;
669
+ }
670
+ let a = setTimeout(() => {
671
+ n?.removeEventListener("abort", o), r();
672
+ }, t);
673
+ typeof a == "object" && a.unref();
674
+ let o = () => {
675
+ clearTimeout(a), i(new e.ErrorInfo("unable to wait; signal aborted", N.InvalidArgument, 400));
676
+ };
677
+ n?.addEventListener("abort", o, { once: !0 });
678
+ }), Ee = async (t, n, r, i, a) => {
679
+ let o;
680
+ for (let s = 0; s <= n; s++) {
681
+ if (i?.aborted) throw new e.ErrorInfo("unable to fetch history page; signal aborted", N.InvalidArgument, 400, I(o));
682
+ try {
683
+ return await t();
684
+ } catch (e) {
685
+ if (o = e, s === n) break;
686
+ let t = r * 2 ** s;
687
+ a?.debug("loadHistoryPages.fetchPageWithRetry(); page fetch failed, retrying", {
688
+ attempt: s + 1,
689
+ maxRetries: n,
690
+ backoff: t
691
+ }), await Te(t, i);
333
692
  }
334
- if (f) {
335
- let n = r.get(f);
336
- if (n || (n = {
337
- accumulator: e.codec.createAccumulator(),
338
- firstSeen: a++,
339
- msgHeaders: /* @__PURE__ */ new Map(),
340
- msgSerials: /* @__PURE__ */ new Map()
341
- }, r.set(f, n)), p) {
342
- let e = n.msgHeaders.get(p);
343
- e ? Object.keys(d).length > 0 && Object.assign(e, d) : (n.msgHeaders.set(p, { ...d }), g && n.msgSerials.set(p, g));
693
+ }
694
+ throw new e.ErrorInfo(`unable to fetch history page; ${F(o)}`, N.HistoryFetchFailed, 500, I(o));
695
+ }, De = async (t, n) => {
696
+ let { pageLimit: r, untilAttach: i = !0, signal: a, maxRetries: o = 3, retryBackoffMs: s = 100, logger: c } = n;
697
+ if (a?.aborted) throw new e.ErrorInfo("unable to load history; signal aborted", N.InvalidArgument, 400);
698
+ await t.attach();
699
+ let l = {
700
+ limit: r,
701
+ untilAttach: i
702
+ }, u = await Ee(() => t.history(l), o, s, a, c), d = !1;
703
+ return {
704
+ hasNext: () => u === void 0 || a?.aborted ? !1 : d ? u.hasNext() : !0,
705
+ next: async () => {
706
+ if (u === void 0) return;
707
+ if (a?.aborted) throw new e.ErrorInfo("unable to load history; signal aborted", N.InvalidArgument, 400);
708
+ if (!d) return d = !0, u.items;
709
+ if (!u.hasNext()) {
710
+ u = void 0;
711
+ return;
344
712
  }
345
- n.accumulator.processOutputs(t);
346
- } else {
347
- i.processOutputs(t);
348
- for (let e of t) if (e.kind === "message" && p) {
349
- c.push(p);
350
- let e = o.get(p);
351
- e ? Object.keys(d).length > 0 && Object.assign(e, d) : (o.set(p, { ...d }), g && s.set(p, g));
713
+ let t = await Ee(async () => await u?.next() ?? void 0, o, s, a, c);
714
+ if (!t) {
715
+ u = void 0;
716
+ return;
352
717
  }
718
+ return u = t, t.items;
353
719
  }
354
- }
355
- for (let { accumulator: e, messageId: t } of l) e.completeMessage(t);
356
- let u = [];
357
- for (let [e, t] of i.completedMessages.entries()) {
358
- let n = c[e];
359
- u.push({
360
- message: t,
361
- headers: n ? o.get(n) ?? {} : {},
362
- serial: n ? s.get(n) ?? "" : ""
363
- });
364
- }
365
- let d = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
366
- for (let e of d) {
367
- let t = [...e.msgHeaders.entries()], n = 0;
368
- for (let r of e.accumulator.completedMessages) {
369
- let i = t[n];
370
- if (i) {
371
- let [t, a] = i;
372
- u.push({
373
- message: r,
374
- headers: a,
375
- serial: e.msgSerials.get(t) ?? ""
376
- }), n++;
377
- } else u.push({
378
- message: r,
379
- headers: {},
380
- serial: ""
381
- });
382
- }
383
- }
384
- return u.toReversed();
385
- }, ie = (e) => {
386
- if (e.cachedDecode && e.cachedAtRawLength === e.rawMessages.length) return e.cachedDecode;
387
- let t = B(e);
388
- return e.cachedDecode = t, e.cachedAtRawLength = e.rawMessages.length, t;
389
- }, V = (e, t) => {
720
+ };
721
+ }, Oe = (e, t) => {
390
722
  for (let n of t) {
391
- let t = P(n), r = t[h];
392
- if (!r || t["x-ably-amend"]) continue;
393
- let i = n.action, a = i === "message.create" && "x-ably-discrete" in t, o = t["x-ably-stream"] === "true" && (i === "message.create" || i === "message.update" || i === "message.append"), s = t[p], c = s === "finished" || s === "aborted";
394
- (a || o) && e.startedMsgIds.add(r), (a || c) && e.terminatedMsgIds.add(r), e.startedMsgIds.has(r) && e.terminatedMsgIds.has(r) && e.completedMsgIds.add(r);
395
- }
396
- }, H = async (e, t, n) => {
397
- e.rawMessages.push(...t.items), e.lastAblyPage = t, V(e, t.items);
398
- let r = e.returnedCount + n;
399
- for (; e.completedMsgIds.size < r && t.hasNext();) {
400
- e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
723
+ let t = L(n), r = t[D];
724
+ if (!r) continue;
725
+ let i = n.action, a = i === "message.create" && "discrete" in t, o = t.stream === "true" && (i === "message.create" || i === "message.update" || i === "message.append"), s = t[C], c = s === "complete" || s === "cancelled";
726
+ (a || o) && e.startedCodecMessageIds.add(r), (a || c) && e.terminatedCodecMessageIds.add(r), e.startedCodecMessageIds.has(r) && e.terminatedCodecMessageIds.has(r) && e.completedCodecMessageIds.add(r);
727
+ }
728
+ }, W = async (e, t) => {
729
+ let n = e.returnedCount + t;
730
+ for (; e.completedCodecMessageIds.size < n && e.cursor.hasNext();) {
731
+ e.logger.debug("loadHistory.fetchUntilLimit(); pulling next page", {
401
732
  collected: e.rawMessages.length,
402
- completed: e.completedMsgIds.size
733
+ completed: e.completedCodecMessageIds.size
403
734
  });
404
- let n = await t.next();
405
- if (!n) break;
406
- t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, V(e, n.items);
407
- }
408
- }, U = (e, t) => {
409
- let n = ie(e), r = n.slice(e.returnedCount, e.returnedCount + t), i = [...r].toReversed();
410
- e.returnedCount += r.length;
411
- let a = n.length > e.returnedCount, o = e.lastAblyPage?.hasNext() ?? !1, s = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
735
+ let t = await e.cursor.next();
736
+ if (!t) break;
737
+ e.rawMessages.push(...t), Oe(e, t);
738
+ }
739
+ }, G = (e, t) => {
740
+ let n = e.completedCodecMessageIds.size, r = Math.min(t, Math.max(0, n - e.returnedCount));
741
+ e.returnedCount += r;
742
+ let i = n > e.returnedCount, a = e.cursor.hasNext(), o = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
412
743
  return e.returnedRawCount = e.rawMessages.length, {
413
- items: i.map((e) => ({
414
- message: e.message,
415
- headers: e.headers,
416
- serial: e.serial
417
- })),
418
- rawMessages: s,
419
- hasNext: () => a || o,
744
+ rawMessages: o,
745
+ hasNext: () => i || a,
420
746
  next: async () => {
421
- if (a) return U(e, t);
422
- if (!o || !e.lastAblyPage) return;
423
- let n = await e.lastAblyPage.next();
424
- if (n) return await H(e, n, t), U(e, t);
747
+ if (i) return G(e, t);
748
+ if (a) return await W(e, t), G(e, t);
425
749
  }
426
750
  };
427
- }, ae = async (e, t, n, r) => {
428
- let i = n?.limit ?? 100, a = {
429
- codec: t,
751
+ }, ke = async (e, t, n) => {
752
+ let r = t?.limit ?? 100;
753
+ n.trace("loadHistory();", { limit: r });
754
+ let i = {
755
+ cursor: await De(e, {
756
+ pageLimit: r * 10,
757
+ untilAttach: !0,
758
+ logger: n
759
+ }),
430
760
  rawMessages: [],
431
761
  returnedCount: 0,
432
762
  returnedRawCount: 0,
433
- lastAblyPage: void 0,
434
- cachedDecode: void 0,
435
- cachedAtRawLength: 0,
436
- startedMsgIds: /* @__PURE__ */ new Set(),
437
- terminatedMsgIds: /* @__PURE__ */ new Set(),
438
- completedMsgIds: /* @__PURE__ */ new Set(),
439
- logger: r
763
+ startedCodecMessageIds: /* @__PURE__ */ new Set(),
764
+ terminatedCodecMessageIds: /* @__PURE__ */ new Set(),
765
+ completedCodecMessageIds: /* @__PURE__ */ new Set(),
766
+ logger: n
440
767
  };
441
- r.trace("decodeHistory();", { limit: i });
442
- let o = i * 10;
443
- return await e.attach(), await H(a, await e.history({
444
- untilAttach: !0,
445
- limit: o
446
- }), i), U(a, i);
447
- }, oe = class {
768
+ return await W(i, r), G(i, r);
769
+ }, Ae = (e) => Array.isArray(e) ? e : [e], K = (e) => ({
770
+ runId: e.runId,
771
+ clientId: e.clientId,
772
+ invocationId: e.invocationId,
773
+ ...e.state
774
+ }), je = class {
448
775
  constructor(e) {
449
- this._branchSelections = /* @__PURE__ */ new Map(), this._withheldMsgIds = /* @__PURE__ */ new Set(), this._lastVisibleIds = [], this._lastVisibleMessages = [], this._lastVisibleTurnIds = /* @__PURE__ */ new Set(), this._hasMoreHistory = !1, this._withheldBuffer = [], this._unsubs = [], this._cachedNodes = [], this._lastStructuralVersion = -1, this._loadingOlder = !1, this._processingHistory = !1, this._closed = !1, this._tree = e.tree, this._channel = e.channel, this._codec = e.codec, this._sendDelegate = e.sendDelegate, this._onClose = e.onClose, this._logger = e.logger.withContext({ component: "View" }), this._logger.trace("DefaultView();"), this._emitter = new k(this._logger), this._cachedNodes = this._computeFlatNodes(), this._lastStructuralVersion = this._tree.structuralVersion, this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
776
+ this._branchSelections = /* @__PURE__ */ new Map(), this._regenSelections = /* @__PURE__ */ new Map(), this._nonHeadRegenSelections = /* @__PURE__ */ new Map(), this._withheldRunIds = /* @__PURE__ */ new Set(), this._lastVisibleNodeKeys = [], this._lastVisibleProjections = [], this._lastVisibleMessagePairs = [], this._lastVisibleNodeKeySet = /* @__PURE__ */ new Set(), this._hasMoreHistory = !1, this._withheldBuffer = [], this._hiddenMessageCount = 0, this._unsubs = [], this._cachedNodes = [], this._loadingOlder = !1, this._processingHistory = !1, this._closed = !1, this._tree = e.tree, this._channel = e.channel, this._codec = e.codec, this._applier = e.applier, this._sendDelegate = e.sendDelegate, this._onClose = e.onClose, this._logger = e.logger.withContext({ component: "View" }), this._logger.trace("DefaultView();"), this._emitter = new P(this._logger), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
450
777
  this._onTreeUpdate();
451
778
  }), this._tree.on("ably-message", (e) => {
452
779
  this._onTreeAblyMessage(e);
453
- }), this._tree.on("turn", (e) => {
454
- this._onTreeTurn(e);
780
+ }), this._tree.on("run", (e) => {
781
+ this._onTreeRun(e);
782
+ }), this._tree.on("output", (e) => {
783
+ this._onTreeOutput(e);
455
784
  }));
456
785
  }
786
+ _onTreeOutput(e) {
787
+ this._processingHistory || (e.runId !== void 0 && this._lastVisibleNodeKeySet.has(e.runId) || e.inputCodecMessageId !== void 0 && this._lastVisibleNodeKeySet.has(e.inputCodecMessageId)) && (this._lastVisibleProjections = this._cachedNodes.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(this._cachedNodes).slice(this._hiddenMessageCount), this._emitter.emit("update"));
788
+ }
457
789
  getMessages() {
458
- return this.flattenNodes().map((e) => e.message);
790
+ return this._lastVisibleMessagePairs;
459
791
  }
460
- flattenNodes() {
461
- return this._cachedNodes;
792
+ runs() {
793
+ return this._cachedNodes.filter((e) => e.kind === "run").map((e) => K(e));
462
794
  }
463
795
  _computeFlatNodes() {
464
- let e = this._tree.flattenNodes(this._resolveSelections());
465
- return this._withheldMsgIds.size === 0 ? e : e.filter((e) => !this._withheldMsgIds.has(e.msgId));
796
+ let e = this._treeVisibleNodes();
797
+ return this._withheldRunIds.size === 0 ? e : e.filter((e) => !this._withheldRunIds.has(B(e)));
798
+ }
799
+ _recomputeAndEmit() {
800
+ this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update");
801
+ }
802
+ _recomputeAndEmitIfChanged() {
803
+ let e = this._computeFlatNodes();
804
+ this._visibleChanged(e) && (this._cachedNodes = e, this._updateVisibleSnapshot(e), this._emitter.emit("update"));
805
+ }
806
+ _runByCodecMessageId(e) {
807
+ let t = this._tree.getNodeByCodecMessageId(e);
808
+ return t?.kind === "run" ? t : void 0;
809
+ }
810
+ _nonHeadRegenerators(e, t) {
811
+ return this._tree.getReplyRuns(t).filter((t) => t.regeneratesCodecMessageId === e).toSorted((e, t) => (e.startSerial ?? "￿").localeCompare(t.startSerial ?? "￿"));
812
+ }
813
+ _selectedNonHeadMember(e, t, n) {
814
+ let r = this._nonHeadRegenSelections.get(e);
815
+ return r && r.kind !== "pending" && [t, ...n.map((e) => e.runId)].includes(r.selectedRunId) ? r.selectedRunId : n.at(-1)?.runId ?? t;
816
+ }
817
+ _extractMessages(e) {
818
+ let t = [], n = /* @__PURE__ */ new Set();
819
+ for (let r of e) r.kind === "run" && n.has(r.runId) || this._emitNodeMessages(r, t, n);
820
+ return t;
821
+ }
822
+ _emitNodeMessages(e, t, n) {
823
+ let r = this._codec.getMessages(e.projection);
824
+ if (e.kind !== "run") {
825
+ t.push(...r);
826
+ return;
827
+ }
828
+ for (let i = 0; i < r.length; i++) {
829
+ let a = r[i];
830
+ if (!a) continue;
831
+ let o = i > 0 ? r[i - 1]?.codecMessageId : void 0;
832
+ if (o !== void 0) {
833
+ let r = this._nonHeadRegenerators(a.codecMessageId, o);
834
+ if (r.length > 0) {
835
+ for (let e of r) n.add(e.runId);
836
+ let i = this._selectedNonHeadMember(a.codecMessageId, e.runId, r);
837
+ if (i !== e.runId) {
838
+ let e = r.find((e) => e.runId === i);
839
+ if (e) {
840
+ this._emitNodeMessages(e, t, n);
841
+ return;
842
+ }
843
+ }
844
+ }
845
+ }
846
+ t.push(a);
847
+ }
466
848
  }
467
849
  hasOlder() {
468
- return this._withheldBuffer.length > 0 || this._hasMoreHistory;
850
+ return this._hiddenMessageCount > 0 || this._withheldBuffer.length > 0 || this._hasMoreHistory;
469
851
  }
470
- async loadOlder(e = 100) {
852
+ async loadOlder(e = 10) {
471
853
  if (!(this._closed || this._loadingOlder)) {
472
854
  this._loadingOlder = !0, this._logger.trace("DefaultView.loadOlder();", { limit: e });
473
855
  try {
474
- if (this._withheldBuffer.length > 0) {
475
- let t = this._withheldBuffer.splice(-e, e);
476
- this._releaseWithheld(t);
856
+ if (this._hiddenMessageCount >= e) {
857
+ this._hiddenMessageCount -= e, this._recomputeAndEmit();
477
858
  return;
478
859
  }
479
- if (!this._hasMoreHistory && !this._lastHistoryPage) {
480
- await this._loadFirstPage(e);
481
- return;
482
- }
483
- if (!this._hasMoreHistory) return;
484
- if (!this._lastHistoryPage?.hasNext()) {
485
- this._hasMoreHistory = !1;
486
- return;
487
- }
488
- let t = await this._lastHistoryPage.next();
489
- if (this._closed || !t) {
490
- t || (this._hasMoreHistory = !1);
491
- return;
860
+ let t = e - this._hiddenMessageCount, n = this._extractMessages(this._computeFlatNodes()).length, r = () => this._extractMessages(this._computeFlatNodes()).length - n;
861
+ if (this._withheldBuffer.length > 0) {
862
+ let e = this._messageTailSplitIndex(this._withheldBuffer, t), n = this._withheldBuffer.splice(e);
863
+ this._releaseWithheld(n);
492
864
  }
493
- await this._loadAndReveal(t, e);
865
+ if (r() < t && (await this._fetchOlder(t - r()), this._closed)) return;
866
+ let i = this._extractMessages(this._computeFlatNodes()).length;
867
+ this._hiddenMessageCount = Math.max(0, this._hiddenMessageCount + (i - n) - e), this._recomputeAndEmit();
494
868
  } catch (e) {
495
869
  throw this._logger.error("DefaultView.loadOlder(); failed", { error: e }), e;
496
870
  } finally {
@@ -498,132 +872,272 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
498
872
  }
499
873
  }
500
874
  }
501
- select(e, t) {
502
- this._logger.trace("DefaultView.select();", {
503
- msgId: e,
875
+ async _fetchOlder(e) {
876
+ if (!this._hasMoreHistory && !this._lastHistoryPage) {
877
+ await this._loadFirstPage(e);
878
+ return;
879
+ }
880
+ if (!this._hasMoreHistory) return;
881
+ if (!this._lastHistoryPage?.hasNext()) {
882
+ this._hasMoreHistory = !1;
883
+ return;
884
+ }
885
+ let t = await this._lastHistoryPage.next();
886
+ if (this._closed || !t) {
887
+ t || (this._hasMoreHistory = !1);
888
+ return;
889
+ }
890
+ await this._revealFromPage(t, e);
891
+ }
892
+ _messageTailSplitIndex(e, t) {
893
+ let n = 0;
894
+ for (let r = e.length - 1; r >= 0; r--) {
895
+ let i = e[r];
896
+ if (i && (n += this._codec.getMessages(i.projection).length, n >= t)) return r;
897
+ }
898
+ return 0;
899
+ }
900
+ runOf(e) {
901
+ this._logger.trace("DefaultView.runOf();", { codecMessageId: e });
902
+ let t = this._tree.getNodeByCodecMessageId(e);
903
+ if (!t) return;
904
+ if (t.kind === "run") return K(t);
905
+ let n = this._selectedReplyRun(t.codecMessageId);
906
+ return n ? K(n) : void 0;
907
+ }
908
+ _selectedReplyRun(e) {
909
+ let t = this._tree.getReplyRuns(e);
910
+ if (t.length === 0) return;
911
+ if (t.length === 1) return t[0];
912
+ let n = this._tree.getGroupRoot(t[0]?.runId ?? ""), r = this._regenSelections.get(n), i = r && r.kind !== "pending" ? r.selectedRunId : void 0;
913
+ if (i !== void 0) {
914
+ let e = t.find((e) => e.runId === i);
915
+ if (e) return e;
916
+ }
917
+ return t.toSorted((e, t) => (e.startSerial ?? "￿").localeCompare(t.startSerial ?? "￿")).at(-1);
918
+ }
919
+ run(e) {
920
+ this._logger.trace("DefaultView.run();", { runId: e });
921
+ let t = this._tree.getRunNode(e);
922
+ return t ? K(t) : void 0;
923
+ }
924
+ branchSelection(e) {
925
+ let t = this._resolveMessageBranchPoint(e);
926
+ if (t) {
927
+ let e = t.members.flatMap((e) => {
928
+ let t = this._tree.getNodeByCodecMessageId(e.representativeCodecMessageId);
929
+ if (!t) return [];
930
+ let n = this._codec.getMessages(t.projection).find((t) => t.codecMessageId === e.representativeCodecMessageId);
931
+ return n ? [n.message] : [];
932
+ });
933
+ if (e.length > 0) {
934
+ let n = this._resolveSelectedIndex(t), r = Math.max(0, Math.min(n, e.length - 1)), i = e[r];
935
+ return {
936
+ hasSiblings: e.length > 1,
937
+ siblings: e,
938
+ index: r,
939
+ selected: i
940
+ };
941
+ }
942
+ }
943
+ let n = this._tree.getNodeByCodecMessageId(e);
944
+ if (n) {
945
+ let t = this._codec.getMessages(n.projection).find((t) => t.codecMessageId === e);
946
+ if (t !== void 0) return {
947
+ hasSiblings: !1,
948
+ siblings: [t.message],
949
+ index: 0,
950
+ selected: t.message
951
+ };
952
+ }
953
+ return {
954
+ hasSiblings: !1,
955
+ siblings: [],
956
+ index: 0,
957
+ selected: void 0
958
+ };
959
+ }
960
+ selectSibling(e, t) {
961
+ this._logger.trace("DefaultView.selectSibling();", {
962
+ codecMessageId: e,
504
963
  index: t
505
964
  });
506
- let n = this._tree.getSiblingNodes(e);
507
- if (n.length <= 1) return;
508
- let r = this._tree.getGroupRoot(e), i = Math.max(0, Math.min(t, n.length - 1)), a = n[i];
509
- a && (this._branchSelections.set(r, {
965
+ let n = this._resolveMessageBranchPoint(e);
966
+ if (!n) return;
967
+ let r = Math.max(0, Math.min(t, n.members.length - 1)), i = n.members[r];
968
+ i && (n.kind === "fork-of" ? (this._branchSelections.set(n.groupRoot, {
969
+ kind: "user",
970
+ selectedKey: i.memberNodeKey
971
+ }), this._logger.debug("DefaultView.selectSibling(); fork-of", {
972
+ codecMessageId: e,
973
+ index: r,
974
+ selectedKey: i.memberNodeKey
975
+ })) : n.kind === "non-head-regen" ? (this._nonHeadRegenSelections.set(n.groupRoot, {
976
+ kind: "user",
977
+ selectedRunId: i.memberNodeKey
978
+ }), this._logger.debug("DefaultView.selectSibling(); non-head-regen", {
979
+ codecMessageId: e,
980
+ index: r,
981
+ selectedRunId: i.memberNodeKey,
982
+ anchor: n.groupRoot
983
+ })) : (this._regenSelections.set(n.groupRoot, {
510
984
  kind: "user",
511
- selectedId: a.msgId
512
- }), this._logger.debug("DefaultView.select();", {
513
- msgId: e,
514
- index: i,
515
- selectedId: a.msgId
516
- }), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
517
- }
518
- getSelectedIndex(e) {
519
- this._logger.trace("DefaultView.getSelectedIndex();", { msgId: e });
520
- let t = this._tree.getSiblingNodes(e);
521
- if (t.length <= 1) return 0;
522
- let n = this._tree.getGroupRoot(e), r = this._branchSelections.get(n);
523
- if (!r || r.kind === "pending") return t.length - 1;
524
- let i = t.findIndex((e) => e.msgId === r.selectedId);
525
- return i === -1 ? t.length - 1 : i;
526
- }
527
- getSiblings(e) {
528
- return this._tree.getSiblings(e);
529
- }
530
- hasSiblings(e) {
531
- return this._tree.hasSiblings(e);
985
+ selectedRunId: i.memberNodeKey
986
+ }), this._logger.debug("DefaultView.selectSibling(); regenerate", {
987
+ codecMessageId: e,
988
+ index: r,
989
+ selectedRunId: i.memberNodeKey,
990
+ groupRoot: n.groupRoot
991
+ })), this._recomputeAndEmit());
992
+ }
993
+ _resolveSelectedIndex(e) {
994
+ if (e.kind === "fork-of") {
995
+ let t = this._branchSelections.get(e.groupRoot);
996
+ if (!t) return e.members.length - 1;
997
+ let n = e.members.findIndex((e) => e.memberNodeKey === t.selectedKey);
998
+ return n === -1 ? e.members.length - 1 : n;
999
+ }
1000
+ let t = e.kind === "non-head-regen" ? this._nonHeadRegenSelections.get(e.groupRoot) : this._regenSelections.get(e.groupRoot);
1001
+ if (!t || t.kind === "pending") return e.members.length - 1;
1002
+ let n = e.members.findIndex((e) => e.memberNodeKey === t.selectedRunId);
1003
+ return n === -1 ? e.members.length - 1 : n;
532
1004
  }
533
- getNode(e) {
534
- return this._tree.getNode(e);
535
- }
536
- async send(e, t) {
537
- if (this._logger.trace("DefaultView.send();"), this._closed) throw new s.ErrorInfo("unable to send; view is closed", O.InvalidArgument, 400);
538
- let n = this.flattenNodes(), r = await this._sendDelegate(e, t, n);
539
- if (t?.forkOf) {
540
- let e = this._tree.getGroupRoot(t.forkOf);
541
- if (r.optimisticMsgIds.length > 0) {
542
- let t = r.optimisticMsgIds.at(-1);
543
- t && (this._branchSelections.set(e, {
544
- kind: "auto",
545
- selectedId: t
546
- }), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
547
- } else {
548
- this._branchSelections.set(e, {
549
- kind: "pending",
550
- turnId: r.turnId
551
- }), this._logger.debug("DefaultView.send(); deferring fork auto-selection", {
552
- forkOf: t.forkOf,
553
- groupRoot: e,
554
- turnId: r.turnId
555
- });
556
- let n = this._tree.on("turn", (t) => {
557
- if (t.type !== "x-ably-turn-end" || t.turnId !== r.turnId) return;
558
- let i = this._branchSelections.get(e);
559
- i?.kind === "pending" && i.turnId === r.turnId && this._branchSelections.delete(e), n();
560
- let a = this._unsubs.indexOf(n);
561
- a !== -1 && this._unsubs.splice(a, 1);
562
- });
563
- this._unsubs.push(n);
1005
+ _resolveMessageBranchPoint(e) {
1006
+ let t = this._tree.getNodeByCodecMessageId(e);
1007
+ if (!t) return;
1008
+ if (t.kind === "input") {
1009
+ let e = this._tree.getSiblingNodes(t.codecMessageId);
1010
+ return e.length > 1 ? {
1011
+ kind: "fork-of",
1012
+ groupRoot: this._tree.getGroupRoot(t.codecMessageId),
1013
+ members: this._nodeHeadMembers(e)
1014
+ } : void 0;
1015
+ }
1016
+ let n = this._codec.getMessages(t.projection), r = this._resolveNonHeadBranchPoint(t, n, e);
1017
+ if (r) return r;
1018
+ let i = this._tree.getSiblingNodes(t.runId);
1019
+ if (i.length > 1 && n.at(0)?.codecMessageId === e) return {
1020
+ kind: "regen",
1021
+ groupRoot: this._tree.getGroupRoot(t.runId),
1022
+ members: this._nodeHeadMembers(i)
1023
+ };
1024
+ }
1025
+ _resolveNonHeadBranchPoint(e, t, n) {
1026
+ if (t.at(0)?.codecMessageId === n && e.regeneratesCodecMessageId !== void 0) {
1027
+ let t = e.regeneratesCodecMessageId, n = this._runByCodecMessageId(t);
1028
+ if (n) {
1029
+ let e = this._codec.getMessages(n.projection), r = e.findIndex((e) => e.codecMessageId === t), i = r > 0 ? e[r - 1]?.codecMessageId : void 0;
1030
+ if (i !== void 0) return this._buildNonHeadGroup(t, n.runId, i);
564
1031
  }
1032
+ return;
565
1033
  }
566
- return r;
567
- }
568
- async regenerate(e, t) {
569
- this._logger.trace("DefaultView.regenerate();", { messageId: e });
570
- let n = this._tree.getNode(e);
571
- if (!n) throw new s.ErrorInfo(`unable to regenerate; message not found in tree: ${e}`, O.InvalidArgument, 400);
572
- let r = n.parentId;
573
- return this.send([], {
574
- ...t,
575
- body: {
576
- history: this._getHistoryBefore(e),
577
- ...t?.body
578
- },
579
- forkOf: e,
580
- parent: r
581
- });
1034
+ let r = t.findIndex((e) => e.codecMessageId === n), i = r > 0 ? t[r - 1]?.codecMessageId : void 0;
1035
+ if (i !== void 0) return this._buildNonHeadGroup(n, e.runId, i);
1036
+ }
1037
+ _buildNonHeadGroup(e, t, n) {
1038
+ let r = this._nonHeadRegenerators(e, n);
1039
+ if (r.length === 0) return;
1040
+ let i = [{
1041
+ memberNodeKey: t,
1042
+ representativeCodecMessageId: e
1043
+ }];
1044
+ for (let e of r) {
1045
+ let t = this._codec.getMessages(e.projection).at(0);
1046
+ t && i.push({
1047
+ memberNodeKey: e.runId,
1048
+ representativeCodecMessageId: t.codecMessageId
1049
+ });
1050
+ }
1051
+ return {
1052
+ kind: "non-head-regen",
1053
+ groupRoot: e,
1054
+ members: i
1055
+ };
582
1056
  }
583
- async edit(e, t, n) {
584
- this._logger.trace("DefaultView.edit();", { messageId: e });
585
- let r = this._tree.getNode(e);
586
- if (!r) throw new s.ErrorInfo(`unable to edit; message not found in tree: ${e}`, O.InvalidArgument, 400);
587
- let i = r.parentId;
588
- return this.send(t, {
1057
+ _nodeHeadMembers(e) {
1058
+ let t = [];
1059
+ for (let n of e) {
1060
+ let e = this._codec.getMessages(n.projection).at(0);
1061
+ e && t.push({
1062
+ memberNodeKey: B(n),
1063
+ representativeCodecMessageId: e.codecMessageId
1064
+ });
1065
+ }
1066
+ return t;
1067
+ }
1068
+ async send(t, n) {
1069
+ if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", N.InvalidArgument, 400);
1070
+ let r = Ae(t), i = this._lastVisibleMessagePairs.at(-1)?.codecMessageId, a = await this._sendDelegate(r, n, i);
1071
+ return this._applyForkAutoSelect(a, n), a;
1072
+ }
1073
+ _applyForkAutoSelect(e, t) {
1074
+ if (!t?.forkOf) return;
1075
+ let n = e.optimisticCodecMessageIds.at(0);
1076
+ if (n === void 0) return;
1077
+ let r = this._tree.getGroupRoot(n);
1078
+ this._branchSelections.set(r, {
1079
+ kind: "auto",
1080
+ selectedKey: n
1081
+ }), this._recomputeAndEmit();
1082
+ }
1083
+ _applyRegenerateAutoSelect(e, t) {
1084
+ let n = this._runByCodecMessageId(t);
1085
+ if (!n) return;
1086
+ if (this._codec.getMessages(n.projection).at(0)?.codecMessageId !== t) {
1087
+ this._nonHeadRegenSelections.set(t, {
1088
+ kind: "pending",
1089
+ carrierCodecMessageId: e.inputCodecMessageId
1090
+ }), this._logger.debug("DefaultView._applyRegenerateAutoSelect(); deferring non-head regenerate selection", {
1091
+ anchorCodecMessageId: t,
1092
+ carrier: e.inputCodecMessageId
1093
+ }), this._resolvePendingNonHeadRegenSelections(), this._recomputeAndEmitIfChanged();
1094
+ return;
1095
+ }
1096
+ let r = this._tree.getGroupRoot(n.runId);
1097
+ this._regenSelections.set(r, {
1098
+ kind: "pending",
1099
+ carrierCodecMessageId: e.inputCodecMessageId
1100
+ }), this._logger.debug("DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection", {
1101
+ anchorCodecMessageId: t,
1102
+ groupRoot: r,
1103
+ carrier: e.inputCodecMessageId
1104
+ }), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged();
1105
+ }
1106
+ async regenerate(t, n) {
1107
+ if (this._logger.trace("DefaultView.regenerate();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to regenerate; view is closed", N.InvalidArgument, 400);
1108
+ let r = this._runByCodecMessageId(t);
1109
+ if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, N.InvalidArgument, 400);
1110
+ let i = this._findParentMsgId(r, t);
1111
+ if (!i) throw new e.ErrorInfo(`unable to regenerate; parent user message not found for ${t}`, N.InvalidArgument, 400);
1112
+ let a = t;
1113
+ r.regeneratesCodecMessageId !== void 0 && this._codec.getMessages(r.projection).at(0)?.codecMessageId === t && (a = r.regeneratesCodecMessageId);
1114
+ let o = {
589
1115
  ...n,
590
- body: {
591
- history: this._getHistoryBefore(e),
592
- ...n?.body
593
- },
594
- forkOf: e,
595
1116
  parent: i
1117
+ }, s = this._codec.createRegenerate(a, i), c = await this._sendDelegate([s], o, i);
1118
+ return this._applyRegenerateAutoSelect(c, a), c;
1119
+ }
1120
+ async edit(t, n, r) {
1121
+ if (this._logger.trace("DefaultView.edit();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to edit; view is closed", N.InvalidArgument, 400);
1122
+ let i = this._tree.getNodeByCodecMessageId(t);
1123
+ if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, N.InvalidArgument, 400);
1124
+ let a = this._findParentMsgId(i, t);
1125
+ return this.send(n, {
1126
+ ...r,
1127
+ forkOf: t,
1128
+ parent: a
596
1129
  });
597
1130
  }
598
- async update(e, t, n) {
599
- if (this._closed) throw new s.ErrorInfo("unable to update; view is closed", O.InvalidArgument, 400);
600
- this._logger.trace("DefaultView.update();", {
601
- msgId: e,
602
- eventCount: t.length
603
- });
604
- let r = [{
605
- kind: "event",
606
- msgId: e,
607
- events: t
608
- }];
609
- return this._sendDelegate([], n, this.flattenNodes(), r);
610
- }
611
- _getHistoryBefore(e) {
612
- this._logger.trace("DefaultView._getHistoryBefore();", { messageId: e });
613
- let t = this.flattenNodes(), n = t.findIndex((t) => t.msgId === e);
614
- return n === -1 ? (this._logger.warn("DefaultView._getHistoryBefore(); target not in visible nodes, returning full list", { messageId: e }), t) : t.slice(0, n);
615
- }
616
- getActiveTurnIds() {
617
- this._logger.trace("DefaultView.getActiveTurnIds();");
618
- let e = this._tree.getActiveTurnIds();
619
- if (this._withheldMsgIds.size === 0) return e;
620
- let t = /* @__PURE__ */ new Map();
621
- for (let [n, r] of e) {
622
- let e = /* @__PURE__ */ new Set();
623
- for (let t of r) this._lastVisibleTurnIds.has(t) && e.add(t);
624
- e.size > 0 && t.set(n, e);
1131
+ _findParentMsgId(e, t) {
1132
+ let n = this._lastVisibleMessagePairs, r = n.findIndex((e) => e.codecMessageId === t);
1133
+ if (r > 0) return n[r - 1]?.codecMessageId;
1134
+ if (r === 0) return;
1135
+ let i = this._codec.getMessages(e.projection), a = i.findIndex((e) => e.codecMessageId === t);
1136
+ if (a > 0) return i[a - 1]?.codecMessageId;
1137
+ if (a === 0 && e.parentCodecMessageId !== void 0) {
1138
+ let t = this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);
1139
+ if (t) return this._codec.getMessages(t.projection).at(-1)?.codecMessageId;
625
1140
  }
626
- return t;
627
1141
  }
628
1142
  on(e, t) {
629
1143
  let n = t;
@@ -632,35 +1146,29 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
632
1146
  };
633
1147
  }
634
1148
  close() {
635
- this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
636
- for (let e of this._unsubs) e();
637
- this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._withheldMsgIds.clear(), this._withheldBuffer.length = 0, this._onClose?.();
1149
+ if (!this._closed) {
1150
+ this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
1151
+ for (let e of this._unsubs) e();
1152
+ this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._regenSelections.clear(), this._nonHeadRegenSelections.clear(), this._withheldRunIds.clear(), this._withheldBuffer.length = 0, this._hiddenMessageCount = 0, this._onClose?.();
1153
+ }
638
1154
  }
639
1155
  async _loadFirstPage(e) {
640
- let t = new Set(this._tree.flattenNodes(this._resolveSelections()).map((e) => e.msgId)), n = await ae(this._channel, this._codec, { limit: e }, this._logger);
641
- if (this._closed) return;
642
- let { newVisible: r, lastPage: i } = await this._loadUntilVisible(n, e, t);
643
- if (this._closed) return;
644
- this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext();
645
- let a = r.slice(-e), o = r.slice(0, -e);
646
- for (let e of o) this._withheldMsgIds.add(e.msgId);
647
- this._withheldBuffer.push(...o), this._releaseWithheld(a);
648
- }
649
- async _loadAndReveal(e, t) {
650
- let n = new Set(this._tree.flattenNodes(this._resolveSelections()).map((e) => e.msgId)), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
651
- if (this._closed) return;
652
- this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext();
653
- let a = r.slice(-t), o = r.slice(0, -t);
654
- for (let e of o) this._withheldMsgIds.add(e.msgId);
655
- this._withheldBuffer.push(...o), this._releaseWithheld(a);
1156
+ let t = await ke(this._channel, { limit: e }, this._logger);
1157
+ this._closed || await this._revealFromPage(t, e);
1158
+ }
1159
+ async _revealFromPage(e, t) {
1160
+ let n = new Set(this._treeVisibleNodes().map((e) => B(e))), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
1161
+ this._closed || (this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext(), this._splitReveal(r, t));
1162
+ }
1163
+ _splitReveal(e, t) {
1164
+ let n = this._messageTailSplitIndex(e, t), r = e.slice(n), i = e.slice(0, n);
1165
+ for (let e of i) this._withheldRunIds.add(B(e));
1166
+ this._withheldBuffer.push(...i), this._releaseWithheld(r);
656
1167
  }
657
1168
  _processHistoryPage(e) {
658
1169
  this._processingHistory = !0;
659
1170
  try {
660
- for (let t of e.items) {
661
- let e = t.headers[h];
662
- e && this._tree.upsert(e, t.message, t.headers, t.serial);
663
- }
1171
+ for (let t of e.rawMessages) this._applier.apply(t);
664
1172
  for (let t of e.rawMessages) this._tree.emitAblyMessage(t);
665
1173
  } finally {
666
1174
  this._processingHistory = !1;
@@ -670,7 +1178,7 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
670
1178
  this._processHistoryPage(e);
671
1179
  let r = e, i = () => {
672
1180
  let e = 0;
673
- for (let t of this._tree.flattenNodes(this._resolveSelections())) n.has(t.msgId) || e++;
1181
+ for (let t of this._treeVisibleNodes()) n.has(B(t)) || (e += this._codec.getMessages(t.projection).length);
674
1182
  return e;
675
1183
  };
676
1184
  for (; i() < t && r.hasNext();) {
@@ -679,678 +1187,525 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
679
1187
  this._processHistoryPage(e), r = e;
680
1188
  }
681
1189
  return {
682
- newVisible: this._tree.flattenNodes(this._resolveSelections()).filter((e) => !n.has(e.msgId)),
1190
+ newVisible: this._treeVisibleNodes().filter((e) => !n.has(B(e))),
683
1191
  lastPage: r
684
1192
  };
685
1193
  }
686
1194
  _releaseWithheld(e) {
687
- for (let t of e) this._withheldMsgIds.delete(t.msgId);
688
- e.length > 0 && (this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
1195
+ for (let t of e) this._withheldRunIds.delete(B(t));
1196
+ e.length > 0 && this._recomputeAndEmit();
689
1197
  }
690
1198
  _updateVisibleSnapshot(e) {
691
- let t = e ?? this.flattenNodes();
692
- this._lastVisibleIds = t.map((e) => e.msgId), this._lastVisibleMessages = t.map((e) => e.message), this._lastVisibleTurnIds = /* @__PURE__ */ new Set();
693
- for (let e of t) {
694
- let t = e.headers[m];
695
- t && this._lastVisibleTurnIds.add(t);
696
- }
1199
+ let t = e ?? this._cachedNodes;
1200
+ this._lastVisibleNodeKeys = t.map((e) => B(e)), this._lastVisibleNodeKeySet = new Set(this._lastVisibleNodeKeys), this._lastVisibleProjections = t.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(t).slice(this._hiddenMessageCount);
697
1201
  }
698
1202
  _onTreeUpdate() {
699
- if (this._processingHistory) return;
700
- let e = this._tree.structuralVersion;
701
- if (e === this._lastStructuralVersion) {
702
- this._cachedNodes.some((e, t) => e.message !== this._lastVisibleMessages[t]) && (this._lastVisibleMessages = this._cachedNodes.map((e) => e.message), this._cachedNodes = [...this._cachedNodes], this._emitter.emit("update"));
703
- return;
704
- }
705
- this._lastStructuralVersion = e, this._pinBranchSelections(), this._resolvePendingSelections();
706
- let t = this._computeFlatNodes(), n = t.map((e) => e.msgId), r = t.map((e) => e.message);
707
- this._visibleChanged(n, r) && (this._cachedNodes = t, this._updateVisibleSnapshot(t), this._emitter.emit("update"));
1203
+ this._processingHistory || (this._pinBranchSelections(), this._resolvePendingRegenSelections(), this._resolvePendingNonHeadRegenSelections(), this._recomputeAndEmitIfChanged());
708
1204
  }
709
1205
  _resolveSelections() {
710
1206
  let e = /* @__PURE__ */ new Map();
711
- for (let [t, n] of this._branchSelections) n.kind !== "pending" && e.set(t, n.selectedId);
1207
+ for (let [t, n] of this._branchSelections) e.set(t, n.selectedKey);
1208
+ for (let [t, n] of this._regenSelections) n.kind !== "pending" && e.set(t, n.selectedRunId);
712
1209
  return e;
713
1210
  }
1211
+ _treeVisibleNodes() {
1212
+ return this._tree.visibleNodes(this._resolveSelections());
1213
+ }
714
1214
  _pinBranchSelections() {
715
- for (let e of this._lastVisibleIds) {
716
- if (!this._tree.hasSiblings(e)) continue;
717
- let t = this._tree.getGroupRoot(e), n = this._branchSelections.get(t);
718
- if (n?.kind === "pending") {
719
- let r = this._tree.getSiblingNodes(e).at(-1);
720
- r && r.msgId !== e && r.headers["x-ably-turn-id"] === n.turnId && (this._logger.debug("DefaultView._pinBranchSelections(); auto-selecting pending fork", {
721
- msgId: e,
722
- newestId: r.msgId,
723
- turnId: n.turnId
724
- }), this._branchSelections.set(t, {
725
- kind: "auto",
726
- selectedId: r.msgId
727
- }));
728
- continue;
729
- }
730
- n || this._branchSelections.set(t, {
1215
+ for (let e of this._lastVisibleNodeKeys) {
1216
+ if (this._tree.getNode(e)?.kind !== "input" || this._tree.getSiblingNodes(e).length <= 1) continue;
1217
+ let t = this._tree.getGroupRoot(e);
1218
+ this._branchSelections.get(t) || this._branchSelections.set(t, {
731
1219
  kind: "pinned",
732
- selectedId: e
1220
+ selectedKey: e
733
1221
  });
734
1222
  }
735
1223
  }
736
- _resolvePendingSelections() {
737
- for (let [e, t] of this._branchSelections) {
738
- if (t.kind !== "pending") continue;
739
- let n = this._tree.getSiblingNodes(e);
1224
+ _resolvePendingRegenSelections() {
1225
+ for (let [e, t] of this._regenSelections) {
1226
+ if (t.kind === "user") continue;
1227
+ let n = this._tree.getSiblingNodes(e).filter((e) => e.kind === "run");
740
1228
  if (n.length <= 1) continue;
741
1229
  let r = n.at(-1);
742
- !r || r.msgId === e || r.headers["x-ably-turn-id"] === t.turnId && (this._logger.debug("DefaultView._resolvePendingSelections(); resolving off-branch pending", {
743
- groupRoot: e,
744
- newestId: r.msgId,
745
- turnId: t.turnId
746
- }), this._branchSelections.set(e, {
1230
+ r && this._regenSelections.set(e, {
747
1231
  kind: "auto",
748
- selectedId: r.msgId
749
- }));
1232
+ selectedRunId: r.runId
1233
+ });
1234
+ }
1235
+ }
1236
+ _resolvePendingNonHeadRegenSelections() {
1237
+ for (let [e, t] of this._nonHeadRegenSelections) {
1238
+ if (t.kind === "user") continue;
1239
+ let n = this._runByCodecMessageId(e);
1240
+ if (!n) continue;
1241
+ let r = this._codec.getMessages(n.projection), i = r.findIndex((t) => t.codecMessageId === e), a = i > 0 ? r[i - 1]?.codecMessageId : void 0;
1242
+ if (a === void 0) continue;
1243
+ let o = this._nonHeadRegenerators(e, a).at(-1);
1244
+ o && this._nonHeadRegenSelections.set(e, {
1245
+ kind: "auto",
1246
+ selectedRunId: o.runId
1247
+ });
750
1248
  }
751
1249
  }
752
1250
  _onTreeAblyMessage(e) {
753
- let t = P(e)[h];
754
- if (!t) {
1251
+ let t = L(e), n = t[D], r = t[w];
1252
+ if (!n && !r) {
755
1253
  this._emitter.emit("ably-message", e);
756
1254
  return;
757
1255
  }
758
- this._lastVisibleIds.includes(t) && this._emitter.emit("ably-message", e);
1256
+ r && this._lastVisibleNodeKeySet.has(r) && this._emitter.emit("ably-message", e);
759
1257
  }
760
- _onTreeTurn(e) {
761
- if (this._lastVisibleTurnIds.has(e.turnId)) {
762
- this._emitter.emit("turn", e);
1258
+ _onTreeRun(e) {
1259
+ if (this._lastVisibleNodeKeySet.has(e.runId)) {
1260
+ this._emitter.emit("run", e);
763
1261
  return;
764
1262
  }
765
- e.type === "x-ably-turn-start" && this._isTurnStartVisible(e) && (this._lastVisibleTurnIds.add(e.turnId), this._emitter.emit("turn", e));
1263
+ e.type === "start" && this._isRunStartVisible(e) && (this._lastVisibleNodeKeySet.add(e.runId), this._emitter.emit("run", e));
766
1264
  }
767
- _isTurnStartVisible(e) {
1265
+ _isRunStartVisible(e) {
768
1266
  let { parent: t } = e;
769
- return t === void 0 ? !0 : this._lastVisibleIds.includes(t);
1267
+ if (t === void 0) return !0;
1268
+ let n = this._tree.getNodeByCodecMessageId(t);
1269
+ return n ? this._lastVisibleNodeKeySet.has(B(n)) : !0;
770
1270
  }
771
- _visibleChanged(e, t) {
772
- if (e.length !== this._lastVisibleIds.length) return !0;
773
- for (let [t, n] of e.entries()) if (n !== this._lastVisibleIds[t]) return !0;
774
- for (let [e, n] of t.entries()) if (n !== this._lastVisibleMessages[e]) return !0;
1271
+ _visibleChanged(e) {
1272
+ if (e.length !== this._lastVisibleNodeKeys.length) return !0;
1273
+ for (let [t, n] of e.entries()) if (B(n) !== this._lastVisibleNodeKeys[t] || n.projection !== this._lastVisibleProjections[t]) return !0;
775
1274
  return !1;
776
1275
  }
777
- }, W = (e) => new oe(e), se = () => {}, G = /* @__PURE__ */ function(e) {
778
- return e.READY = "ready", e.CLOSED = "closed", e;
779
- }(G || {}), ce = class {
1276
+ }, q = (e) => new je(e), Me = () => {}, Ne = class {
780
1277
  constructor(e) {
781
- if (this._ownMsgIds = /* @__PURE__ */ new Set(), this._ownTurnIds = /* @__PURE__ */ new Set(), this._turnMsgIds = /* @__PURE__ */ new Map(), this._turnObservers = /* @__PURE__ */ new Map(), this._closeResolvers = [], this._views = /* @__PURE__ */ new Set(), this._state = G.READY, this._pendingLocalEvents = [], this._channel = e.channel, this._codec = e.codec, this._clientId = e.clientId, this._api = e.api, this._credentials = e.credentials, this._headersFn = typeof e.headers == "function" ? e.headers : e.headers ? () => e.headers : void 0, this._bodyFn = typeof e.body == "function" ? e.body : e.body ? () => e.body : void 0, this._fetchFn = e.fetch ?? globalThis.fetch.bind(globalThis), this._logger = (e.logger ?? re({ logLevel: A.Silent })).withContext({ component: "ClientTransport" }), this._emitter = new k(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = z(this._logger), this._view = W({
1278
+ this._views = /* @__PURE__ */ new Set(), this._state = "ready", this._pendingRunStarts = /* @__PURE__ */ new Map();
1279
+ let t = x(e.client, e.codec), n = m(e.channelModes);
1280
+ if (n && (t.modes = n), this._channel = e.client.channels.get(e.channelName, t), this._client = e.client, this._codec = e.codec, this._logger = (e.logger ?? ce({ logLevel: oe.Silent })).withContext({ component: "ClientSession" }), this._emitter = new P(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = we(this._codec, this._logger), this._applier = ge(this._tree, this._codec.createDecoder()), this._view = q({
782
1281
  tree: this._tree,
783
1282
  channel: this._channel,
784
1283
  codec: this._codec,
1284
+ applier: this._applier,
785
1285
  sendDelegate: this._internalSend.bind(this),
786
1286
  logger: this._logger,
787
1287
  onClose: () => this._views.delete(this._view)
788
- }), this._router = L(this._codec.isTerminal.bind(this._codec), this._logger), this._decoder = this._codec.createDecoder(), this._views.add(this._view), this.tree = this._tree, this.view = this._view, e.messages) {
1288
+ }), this._encoder = this._codec.createEncoder(this._channel), this._views.add(this._view), this.tree = this._tree, this.view = this._view, e.messages) {
789
1289
  let t;
790
1290
  for (let n of e.messages) {
791
- let e = crypto.randomUUID(), r = { [h]: e };
792
- t && (r[C] = t), this._tree.upsert(e, n, r), t = e;
1291
+ let e = crypto.randomUUID(), r = {
1292
+ [D]: e,
1293
+ [O]: "user"
1294
+ };
1295
+ t && (r[k] = t), this._tree.applyMessage({
1296
+ inputs: [this._codec.createUserMessage(n)],
1297
+ outputs: []
1298
+ }, r), t = e;
793
1299
  }
794
1300
  }
795
1301
  this._onMessage = (e) => {
796
1302
  this._handleMessage(e);
797
- }, this._attachPromise = this._channel.subscribe(this._onMessage), this._onChannelStateChange = (e) => {
1303
+ }, this._onChannelStateChange = (e) => {
798
1304
  this._handleChannelStateChange(e);
799
1305
  }, this._channel.on(this._onChannelStateChange);
800
1306
  }
801
- _handleMessage(e) {
802
- if (this._state !== G.CLOSED) try {
803
- if (e.name === "x-ably-turn-start") {
804
- let t = P(e), n = t[m], r = t["x-ably-turn-client-id"] ?? "";
805
- if (n) {
806
- this._tree.trackTurn(n, r);
807
- let e = t[C], i = t[w];
808
- this._tree.emitTurn({
809
- type: E,
810
- turnId: n,
811
- clientId: r,
812
- ...e !== void 0 && { parent: e },
813
- ...i !== void 0 && { forkOf: i }
814
- });
1307
+ get presence() {
1308
+ return this._channel.presence;
1309
+ }
1310
+ get object() {
1311
+ return this._channel.object;
1312
+ }
1313
+ connect() {
1314
+ return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", N.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger.trace("DefaultClientSession.connect();"), this._connectPromise = this._channel.subscribe(this._onMessage).then(() => {
1315
+ this._logger.debug("DefaultClientSession.connect(); subscribed and attached");
1316
+ }, (t) => {
1317
+ let n = new e.ErrorInfo(`unable to subscribe to channel; ${F(t)}`, N.SessionSubscriptionError, 500, I(t));
1318
+ throw this._logger.error("DefaultClientSession.connect(); subscribe failed"), this._emitter.emit("error", n), n;
1319
+ }), this._connectPromise);
1320
+ }
1321
+ _resolveClientId() {
1322
+ let e = this._client.auth.clientId;
1323
+ return e && e !== "*" ? e : void 0;
1324
+ }
1325
+ async _requireConnected(e) {
1326
+ return ve(this._connectPromise, e);
1327
+ }
1328
+ _handleMessage(t) {
1329
+ if (this._state !== "closed") try {
1330
+ if (t.name === "ai-run-end") {
1331
+ let e = L(t);
1332
+ if ((e["run-reason"] ?? "complete") === "error") {
1333
+ let t = R(e);
1334
+ this._logger.error("ClientSession._handleMessage(); agent error received", {
1335
+ runId: e[w],
1336
+ invocationId: e[T],
1337
+ code: t.code
1338
+ }), this._emitter.emit("error", t);
815
1339
  }
816
- this._tree.emitAblyMessage(e);
817
- return;
818
1340
  }
819
- if (e.name === "x-ably-turn-end") {
820
- let t = P(e), n = t[m], r = t["x-ably-turn-client-id"] ?? "", i = t["x-ably-turn-reason"] ?? "complete";
821
- if (n) {
822
- this._router.closeStream(n), this._turnObservers.delete(n), this._tree.untrackTurn(n);
823
- let e = this._turnMsgIds.get(n);
824
- if (e) {
825
- for (let t of e) this._ownMsgIds.delete(t);
826
- this._turnMsgIds.delete(n);
827
- }
828
- this._ownTurnIds.delete(n), this._tree.emitTurn({
829
- type: D,
830
- turnId: n,
831
- clientId: r,
832
- reason: i
833
- });
1341
+ let e = this._applier.apply(t);
1342
+ if (e && (e.type === "start" || e.type === "resume")) {
1343
+ let n = L(t)[M];
1344
+ if (n !== void 0) {
1345
+ let t = this._pendingRunStarts.get(n);
1346
+ t && (this._pendingRunStarts.delete(n), t.resolve(e.runId));
834
1347
  }
835
- this._tree.emitAblyMessage(e);
836
- return;
837
- }
838
- let t = this._decoder.decode(e), n = P(e), r = e.serial, i = n[v];
839
- if (i) {
840
- for (let e of t) e.kind === "event" && this._handleAmendmentEvent(i, e);
841
- return;
842
1348
  }
843
- let a = n[m];
844
- a && this._updateTurnObserverHeaders(a, n, r);
845
- for (let i of t) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, e.action) : this._handleEventOutput(i, n);
846
- this._tree.emitAblyMessage(e);
847
- } catch (e) {
848
- let t = e instanceof s.ErrorInfo ? e : void 0;
849
- this._emitter.emit("error", new s.ErrorInfo(`unable to process channel message; ${e instanceof Error ? e.message : String(e)}`, O.TransportSubscriptionError, 500, t));
1349
+ this._tree.emitAblyMessage(t);
1350
+ } catch (t) {
1351
+ this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${F(t)}`, N.SessionSubscriptionError, 500, I(t)));
850
1352
  }
851
1353
  }
852
- _handleMessageOutput(e, t, n, r) {
853
- let i = t[h];
854
- if (i && this._ownMsgIds.has(i)) {
855
- this._upsertAndNotify(e, t, n);
856
- return;
857
- }
858
- r === "message.create" && this._upsertAndNotify(e, t, n);
859
- }
860
- _handleEventOutput(e, t) {
861
- if (e.kind !== "event") return;
862
- let n = e.event, r = t[m];
863
- if (r) {
864
- if (this._router.route(r, n)) {
865
- this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r);
866
- return;
867
- }
868
- this._ownTurnIds.has(r) && !this._turnObservers.has(r) || (this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r));
869
- }
870
- }
871
- _handleAmendmentEvent(e, t) {
872
- this._logger.trace("ClientTransport._handleAmendmentEvent();", { targetMsgId: e });
873
- let n = this._tree.getNode(e);
874
- if (!n) {
875
- this._logger.debug("ClientTransport._handleAmendmentEvent(); target not found, dropping", { targetMsgId: e });
876
- return;
877
- }
878
- let r = this._codec.createAccumulator();
879
- r.initMessage(e, n.message), r.processOutputs([t]);
880
- let i = r.messages.at(-1);
881
- i && this._tree.upsert(e, i, n.headers, n.serial);
882
- }
883
1354
  _handleChannelStateChange(e) {
884
- if (this._state === G.CLOSED) return;
1355
+ if (this._state === "closed") return;
885
1356
  let { current: t, resumed: n } = e;
886
1357
  if (t === "attached" && !this._hasAttachedOnce) {
887
1358
  this._hasAttachedOnce = !0;
888
1359
  return;
889
1360
  }
890
- if (!(t === "failed" || t === "suspended" || t === "detached" || t === "attached" && !n)) return;
891
- this._logger.error("ClientTransport._handleChannelStateChange(); channel continuity lost", {
1361
+ if (!be(e)) return;
1362
+ this._logger.error("ClientSession._handleChannelStateChange(); channel continuity lost", {
892
1363
  current: t,
893
1364
  resumed: n,
894
1365
  previous: e.previous
895
1366
  });
896
- let r = new s.ErrorInfo(`unable to deliver events; channel continuity lost (${t}${t === "attached" ? ", resumed: false" : ""})`, O.ChannelContinuityLost, 500, e.reason);
897
- for (let e of this._ownTurnIds) this._router.errorStream(e, r);
1367
+ let r = xe(e, "deliver events");
898
1368
  this._emitter.emit("error", r);
899
1369
  }
900
- _upsertAndNotify(e, t, n) {
901
- let r = t[h];
902
- r && this._tree.upsert(r, e, t, n);
903
- }
904
- _updateTurnObserverHeaders(e, t, n) {
905
- let r = this._turnObservers.get(e);
906
- r ? (Object.keys(t).length > 0 && Object.assign(r.headers, t), n !== void 0 && (r.serial = n)) : this._turnObservers.set(e, {
907
- headers: { ...t },
908
- serial: n,
909
- accumulator: this._codec.createAccumulator()
910
- });
911
- }
912
- _accumulateAndEmit(e, t) {
913
- let n = this._turnObservers.get(e);
914
- if (!n) return;
915
- let r = n.headers[h];
916
- if (r) {
917
- let e = this._tree.getNode(r);
918
- e && n.accumulator.initMessage(r, e.message);
919
- }
920
- n.accumulator.processOutputs([t]);
921
- let i = n.accumulator.messages;
922
- if (i.length === 0) return;
923
- let a;
924
- try {
925
- a = structuredClone(i.at(-1));
926
- } catch {
927
- a = i.at(-1);
928
- }
929
- if (a) {
930
- let e = n.headers[h];
931
- e && this._tree.upsert(e, a, { ...n.headers }, n.serial);
932
- }
933
- }
934
- async _publishCancel(e) {
935
- this._logger.trace("ClientTransport._publishCancel();", { filter: e });
936
- let t = {};
937
- e.turnId ? t[y] = e.turnId : e.own ? t[b] = "true" : e.clientId ? t[S] = e.clientId : e.all && (t[x] = "true"), await this._channel.publish({
938
- name: T,
939
- extras: { headers: t }
940
- });
941
- }
942
- _closeMatchingTurnStreams(e) {
943
- for (let t of this._getMatchingTurnIds(e)) this._router.closeStream(t);
944
- }
945
- _getMatchingTurnIds(e) {
946
- let t = /* @__PURE__ */ new Set(), n = this._tree.getActiveTurnIds();
947
- if (e.all) for (let e of n.values()) for (let n of e) t.add(n);
948
- else if (e.own) {
949
- let e = n.get(this._clientId ?? "");
950
- if (e) for (let n of e) t.add(n);
951
- } else if (e.clientId) {
952
- let r = n.get(e.clientId);
953
- if (r) for (let e of r) t.add(e);
954
- } else if (e.turnId) {
955
- for (let r of n.values()) if (r.has(e.turnId)) {
956
- t.add(e.turnId);
957
- break;
958
- }
1370
+ _cleanupFailedSend(e) {
1371
+ for (let t of e) {
1372
+ let e = this._tree.getNodeByCodecMessageId(t);
1373
+ e?.kind === "input" && e.serial === void 0 && this._tree.delete(e.codecMessageId);
959
1374
  }
960
- return t;
961
1375
  }
962
1376
  createView() {
963
- if (this._state === G.CLOSED) throw new s.ErrorInfo("unable to create view; transport is closed", O.TransportClosed, 400);
964
- this._logger.trace("DefaultClientTransport.createView();");
965
- let e = W({
1377
+ if (this._state === "closed") throw new e.ErrorInfo("unable to create view; session is closed", N.SessionClosed, 400);
1378
+ this._logger.trace("DefaultClientSession.createView();");
1379
+ let t = q({
966
1380
  tree: this._tree,
967
1381
  channel: this._channel,
968
1382
  codec: this._codec,
1383
+ applier: this._applier,
969
1384
  sendDelegate: this._internalSend.bind(this),
970
1385
  logger: this._logger,
971
- onClose: () => this._views.delete(e)
1386
+ onClose: () => this._views.delete(t)
972
1387
  });
973
- return this._views.add(e), e;
1388
+ return this._views.add(t), t;
974
1389
  }
975
- async _internalSend(e, t, n, r) {
976
- if (this._state === G.CLOSED || (await this._attachPromise, this._state === G.CLOSED)) throw new s.ErrorInfo("unable to send; transport is closed", O.TransportClosed, 400);
1390
+ async _internalSend(t, n, r) {
1391
+ if (this._state === "closed" || (await this._requireConnected("send"), this._state === "closed")) throw new e.ErrorInfo("unable to send; session is closed", N.SessionClosed, 400);
977
1392
  let i = this._channel.state;
978
- if (i !== "attached" && i !== "attaching") throw new s.ErrorInfo(`unable to send; channel is ${i}`, O.ChannelNotReady, 400);
979
- this._logger.trace("ClientTransport._internalSend();");
980
- let a = Array.isArray(e) ? e : [e], o = crypto.randomUUID();
981
- this._ownTurnIds.add(o), this._tree.trackTurn(o, this._clientId ?? "");
982
- let c = this._pendingLocalEvents;
983
- this._pendingLocalEvents = [], r && r.length > 0 && this._applyEventsToTree(r);
984
- let l = [...c, ...r ?? []], u = /* @__PURE__ */ new Set(), d = [], f = n, p;
985
- if (t?.parent === void 0 && !t?.forkOf) {
986
- let e = f.at(-1);
987
- e && (p = e.msgId);
988
- }
989
- let m = t?.parent === void 0 ? p : t.parent;
990
- for (let e of a) {
991
- let n = crypto.randomUUID();
992
- this._ownMsgIds.add(n), u.add(n);
993
- let r = t?.parent === void 0 ? p : t.parent, i = F({
1393
+ if (i !== "attached" && i !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${i}`, N.ChannelNotReady, 400);
1394
+ this._logger.trace("ClientSession._internalSend();");
1395
+ let a = n?.runId !== void 0, o = n?.runId, s;
1396
+ n?.parent === void 0 && !n?.forkOf && (s = r);
1397
+ let c = /* @__PURE__ */ new Set(), l = [];
1398
+ for (let e of t) {
1399
+ let t = crypto.randomUUID(), r = e.codecMessageId ?? crypto.randomUUID();
1400
+ c.add(r);
1401
+ let i = e.kind !== "user-message" && (e.kind === "regenerate" || e.codecMessageId !== void 0), a = e.parent ?? (n?.parent === void 0 ? s : n.parent), u = n?.forkOf, d = e.kind === "regenerate" ? e.target : void 0, f = fe({
994
1402
  role: "user",
995
- turnId: o,
996
- msgId: n,
997
- turnClientId: this._clientId,
998
- parent: r,
999
- forkOf: t?.forkOf
1403
+ runId: o,
1404
+ codecMessageId: r,
1405
+ runClientId: this._resolveClientId(),
1406
+ ...a !== void 0 && { parent: a },
1407
+ ...u !== void 0 && { forkOf: u },
1408
+ ...d !== void 0 && { regenerates: d },
1409
+ inputEventId: t
1000
1410
  });
1001
- this._upsertAndNotify(e, i), d.push({
1002
- kind: "message",
1003
- message: e,
1004
- msgId: n,
1005
- parentId: r,
1006
- forkOf: t?.forkOf,
1007
- headers: i,
1008
- serial: void 0
1009
- }), t?.parent === void 0 && !t?.forkOf && (p = n);
1411
+ i || this._tree.applyMessage({
1412
+ inputs: [e],
1413
+ outputs: []
1414
+ }, f), l.push({
1415
+ input: e,
1416
+ codecMessageId: r,
1417
+ inputEventId: t,
1418
+ headers: f,
1419
+ isWireOnly: i
1420
+ }), !i && n?.parent === void 0 && !n?.forkOf && e.parent === void 0 && (s = r);
1010
1421
  }
1011
- this._turnMsgIds.set(o, u);
1012
- let h = this._router.createStream(o), g = this._headersFn?.() ?? {}, _ = {
1013
- ...this._bodyFn?.() ?? {},
1014
- history: f,
1015
- ...t?.body,
1016
- turnId: o,
1017
- clientId: this._clientId,
1018
- messages: d,
1019
- ...t?.forkOf !== void 0 && { forkOf: t.forkOf },
1020
- ...m !== void 0 && { parent: m },
1021
- ...l.length > 0 && { events: l }
1022
- }, v = {
1023
- ...g,
1024
- ...t?.headers
1025
- };
1026
- return this._fetchFn(this._api, {
1027
- method: "POST",
1028
- headers: {
1029
- "Content-Type": "application/json",
1030
- ...v
1031
- },
1032
- body: JSON.stringify(_),
1033
- ...this._credentials ? { credentials: this._credentials } : {}
1034
- }).then((e) => {
1035
- if (!e.ok) {
1036
- let t = new s.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(e.status)} ${e.statusText}`, O.TransportSendFailed, e.status);
1037
- this._emitter.emit("error", t), this._router.errorStream(o, t);
1422
+ let u = l.at(-1);
1423
+ if (u === void 0) throw new e.ErrorInfo("unable to send; inputs array is empty (include at least one input)", N.InvalidArgument, 400);
1424
+ let d = u.inputEventId, f = u.codecMessageId, p = new Promise((e, t) => {
1425
+ this._pendingRunStarts.set(f, {
1426
+ resolve: e,
1427
+ reject: t
1428
+ });
1429
+ });
1430
+ return p.catch(() => {}), await (async () => {
1431
+ try {
1432
+ for (let e of l) await this._encoder.publishInput(e.input, {
1433
+ extras: { headers: e.headers },
1434
+ messageId: e.codecMessageId
1435
+ });
1436
+ } catch (t) {
1437
+ let n = I(t), r = n?.statusCode === 401 || n?.statusCode === 403, i = new e.ErrorInfo(r ? "unable to publish events; missing publish capability on the channel" : `unable to publish events; ${F(t)}`, r ? N.InsufficientCapability : N.SessionSendFailed, r ? 401 : 500, n);
1438
+ throw this._emitter.emit("error", i), this._pendingRunStarts.delete(f), a || this._cleanupFailedSend([...c]), i;
1038
1439
  }
1039
- }).catch((e) => {
1040
- let t = e instanceof s.ErrorInfo ? e : void 0, n = new s.ErrorInfo(`unable to send; HTTP POST to ${this._api} failed: ${e instanceof Error ? e.message : String(e)}`, O.TransportSendFailed, 500, t);
1041
- this._emitter.emit("error", n), this._router.errorStream(o, n);
1042
- }), {
1043
- stream: h,
1044
- turnId: o,
1045
- cancel: async () => this.cancel({ turnId: o }),
1046
- optimisticMsgIds: [...u]
1440
+ })(), {
1441
+ inputCodecMessageId: f,
1442
+ runId: p,
1443
+ inputEventId: d,
1444
+ cancel: async () => {
1445
+ await this._publishCancel({
1446
+ inputCodecMessageId: f,
1447
+ ...o !== void 0 && { runId: o }
1448
+ });
1449
+ },
1450
+ optimisticCodecMessageIds: [...c],
1451
+ toInvocation: () => _e.fromJSON({
1452
+ inputEventId: d,
1453
+ sessionName: this._channel.name
1454
+ })
1047
1455
  };
1048
1456
  }
1049
1457
  async cancel(e) {
1050
- if (this._state === G.CLOSED) return;
1051
- let t = e ?? { own: !0 };
1052
- this._logger.debug("ClientTransport.cancel();", { filter: t }), await this._publishCancel(t), this._closeMatchingTurnStreams(t);
1053
- }
1054
- stageEvents(e, t) {
1055
- if (this._logger.trace("ClientTransport.stageEvents();", {
1056
- msgId: e,
1057
- eventCount: t.length
1058
- }), this._state === G.CLOSED) {
1059
- this._logger.warn("ClientTransport.stageEvents(); transport is closed", { msgId: e });
1060
- return;
1061
- }
1062
- if (!this._tree.getNode(e)) {
1063
- this._logger.warn("ClientTransport.stageEvents(); msgId not found in tree", { msgId: e });
1064
- return;
1065
- }
1066
- if (t.length === 0) return;
1067
- let n = {
1068
- kind: "event",
1069
- msgId: e,
1070
- events: t
1071
- };
1072
- this._applyEventsToTree([n]), this._pendingLocalEvents.push(n);
1073
- }
1074
- stageMessage(e, t) {
1075
- if (this._logger.trace("ClientTransport.stageMessage();", { msgId: e }), this._state === G.CLOSED) {
1076
- this._logger.warn("ClientTransport.stageMessage(); transport is closed", { msgId: e });
1077
- return;
1078
- }
1079
- let n = this._tree.getNode(e);
1080
- if (!n) {
1081
- this._logger.warn("ClientTransport.stageMessage(); msgId not found in tree", { msgId: e });
1082
- return;
1083
- }
1084
- this._tree.upsert(e, t, n.headers, n.serial);
1085
- }
1086
- _applyEventsToTree(e) {
1087
- for (let t of e) {
1088
- let e = this._tree.getNode(t.msgId);
1089
- if (!e) continue;
1090
- let n = t.events.map((e) => ({
1091
- kind: "event",
1092
- event: e,
1093
- messageId: t.msgId
1094
- })), r = this._codec.createAccumulator();
1095
- r.initMessage(t.msgId, e.message), r.processOutputs(n);
1096
- let i = r.messages.at(-1);
1097
- i && this._tree.upsert(t.msgId, i, e.headers, e.serial);
1098
- }
1458
+ return this._publishCancel({ runId: e });
1099
1459
  }
1100
- async waitForTurn(e) {
1101
- if (this._state === G.CLOSED) return;
1102
- let t = e ?? { own: !0 }, n = this._getMatchingTurnIds(t);
1103
- if (n.size !== 0) return this._logger.debug("ClientTransport.waitForTurn();", { turnIds: [...n] }), new Promise((e) => {
1104
- let t = !1, r = () => {
1105
- if (t) return;
1106
- t = !0, i();
1107
- let n = this._closeResolvers.indexOf(r);
1108
- n !== -1 && this._closeResolvers.splice(n, 1), e();
1109
- }, i = this._tree.on("turn", (e) => {
1110
- e.type === "x-ably-turn-end" && (n.delete(e.turnId), n.size === 0 && r());
1111
- });
1112
- this._closeResolvers.push(r);
1460
+ async _publishCancel(e) {
1461
+ if (this._state === "closed" || (await this._requireConnected("cancel"), this._state === "closed")) return;
1462
+ this._logger.debug("ClientSession._publishCancel();", {
1463
+ runId: e.runId,
1464
+ inputCodecMessageId: e.inputCodecMessageId
1465
+ });
1466
+ let t = { [E]: crypto.randomUUID() };
1467
+ e.runId !== void 0 && (t[w] = e.runId), e.inputCodecMessageId !== void 0 && (t[M] = e.inputCodecMessageId), await this._channel.publish({
1468
+ name: re,
1469
+ extras: { ai: { transport: t } }
1113
1470
  });
1114
1471
  }
1115
1472
  on(e, t) {
1116
- if (this._state === G.CLOSED) return se;
1473
+ if (this._state === "closed") return Me;
1117
1474
  let n = t;
1118
1475
  return this._emitter.on(e, n), () => {
1119
1476
  this._emitter.off(e, n);
1120
1477
  };
1121
1478
  }
1122
- async close(e) {
1123
- if (this._state !== G.CLOSED) {
1124
- if (this._state = G.CLOSED, this._logger.info("ClientTransport.close();"), e?.cancel) {
1125
- try {
1126
- await this._publishCancel(e.cancel);
1127
- } catch {}
1128
- this._closeMatchingTurnStreams(e.cancel);
1129
- }
1130
- this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange);
1131
- for (let e of this._ownTurnIds) this._router.closeStream(e);
1132
- this._turnObservers.clear(), this._emitter.off();
1479
+ async close() {
1480
+ if (this._state !== "closed") {
1481
+ this._state = "closed", this._logger.info("ClientSession.close();"), this._connectPromise && this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange), this._emitter.off();
1133
1482
  for (let e of this._views) e.close();
1134
- this._views.clear();
1135
- for (let e of this._closeResolvers) e();
1136
- this._closeResolvers.length = 0, this._ownTurnIds.clear(), this._ownMsgIds.clear(), this._turnMsgIds.clear();
1483
+ if (this._views.clear(), this._pendingRunStarts.size > 0) {
1484
+ let t = new e.ErrorInfo("unable to await run-start; session closed", N.SessionClosed, 400);
1485
+ for (let e of this._pendingRunStarts.values()) e.reject(t);
1486
+ this._pendingRunStarts.clear();
1487
+ }
1488
+ try {
1489
+ await this._encoder.close();
1490
+ } catch {}
1491
+ await ye(this._channel, this._connectPromise, this._logger, "ClientSession");
1137
1492
  }
1138
1493
  }
1139
- }, le = (e) => new ce(e), ue = ({ channelName: e, children: t, ...o }) => {
1140
- let { channel: c } = l({ channelName: e }), p = a(void 0), m = a(e), h = a([]), g = a(!1), _ = a(void 0);
1141
- if (!(p.current || _.current) || m.current !== e) {
1142
- m.current = e, p.current && h.current.push(p.current);
1494
+ }, Pe = (e) => new Ne(e), J = r({
1495
+ nearest: void 0,
1496
+ providers: {}
1497
+ }), Y = ({ children: r, ...i }) => {
1498
+ let l = n(), { channelName: d } = i, f = s(() => {
1499
+ let e = { params: { agent: b(i.codec) } }, t = m(i.channelModes);
1500
+ return t && (e.modes = t), e;
1501
+ }, [i.codec, i.channelModes]), p = c(void 0), h = c(d), g = c([]), _ = c(!1), v = c(void 0);
1502
+ if (!(p.current || v.current) || h.current !== d) {
1503
+ h.current = d, p.current && g.current.push(p.current);
1143
1504
  try {
1144
- p.current = le({
1145
- ...o,
1146
- channel: c
1147
- }), _.current = void 0;
1148
- } catch (e) {
1149
- p.current = void 0, _.current = e instanceof s.ErrorInfo ? e : new s.ErrorInfo("Unknown error while creating transport", O.BadRequest, 400);
1505
+ p.current = Pe({
1506
+ ...i,
1507
+ client: l
1508
+ }), v.current = void 0;
1509
+ } catch (t) {
1510
+ p.current = void 0, v.current = t instanceof e.ErrorInfo ? t : new e.ErrorInfo("Unknown error while creating client session", N.BadRequest, 400);
1150
1511
  }
1151
1512
  }
1152
- let v = n(d), y = p.current, b = _.current, x = i(() => ({
1153
- transport: y,
1154
- error: b
1155
- }), [y, b]), S = i(() => ({
1156
- ...v,
1157
- [e]: x
1513
+ let y = a(J), x = p.current, S = v.current, C = s(() => ({
1514
+ session: x,
1515
+ sessionError: S
1516
+ }), [x, S]), w = s(() => ({
1517
+ nearest: C,
1518
+ providers: {
1519
+ ...y.providers,
1520
+ [d]: C
1521
+ }
1158
1522
  }), [
1159
- e,
1160
- v,
1161
- x
1523
+ d,
1524
+ y,
1525
+ C
1162
1526
  ]);
1163
- return r(() => () => {
1164
- for (let e of h.current) e.close();
1165
- }, [e]), r(() => (g.current = !1, () => {
1166
- g.current = !0, Promise.resolve().then(() => {
1167
- g.current && p.current?.close();
1527
+ return o(() => () => {
1528
+ for (let e of g.current) e.close();
1529
+ }, [d]), o(() => {
1530
+ p.current?.connect();
1531
+ }, [d]), o(() => (_.current = !1, () => {
1532
+ _.current = !0, Promise.resolve().then(() => {
1533
+ _.current && p.current?.close();
1168
1534
  });
1169
- }), []), /* @__PURE__ */ u(d.Provider, {
1170
- value: S,
1171
- children: /* @__PURE__ */ u(f.Provider, {
1172
- value: x,
1173
- children: t
1535
+ }), []), /* @__PURE__ */ u(J.Provider, {
1536
+ value: w,
1537
+ children: /* @__PURE__ */ u(t, {
1538
+ channelName: d,
1539
+ options: f,
1540
+ children: r
1174
1541
  })
1175
1542
  });
1176
- }, K = (e) => /* @__PURE__ */ u(c, {
1177
- channelName: e.channelName,
1178
- children: /* @__PURE__ */ u(ue, { ...e })
1179
- }), q = ({ transport: e, skip: t } = {}) => {
1180
- let i = n(f), s = t ? void 0 : e ?? i?.transport, [c, l] = o([]), u = a([]);
1181
- return r(() => {
1182
- if (u.current = [], l([]), s) return s.tree.on("ably-message", (e) => {
1183
- let t = [...u.current, e];
1184
- u.current = t, l(t);
1543
+ }, X = ({ session: e, skip: t } = {}) => {
1544
+ let { nearest: n } = a(J), r = n?.session;
1545
+ if (!t && e !== null) return e ?? r;
1546
+ }, Fe = ({ session: e, skip: t } = {}) => {
1547
+ let n = X({
1548
+ session: e,
1549
+ skip: t
1550
+ }), [r, i] = l([]), a = c([]);
1551
+ return o(() => {
1552
+ if (a.current = [], i([]), n) return n.tree.on("ably-message", (e) => {
1553
+ let t = [...a.current, e];
1554
+ a.current = t, i(t);
1185
1555
  });
1186
- }, [s]), c;
1187
- }, J = ({ transport: e } = {}) => {
1188
- let t = n(f), i = e ?? t?.transport, [a, s] = o(() => /* @__PURE__ */ new Map());
1189
- return r(() => {
1190
- if (i) return s(i.tree.getActiveTurnIds()), i.tree.on("turn", (e) => {
1191
- s((t) => {
1192
- let n = new Map(t);
1193
- if (e.type === "x-ably-turn-start") {
1194
- let t = new Set(n.get(e.clientId));
1195
- t.add(e.turnId), n.set(e.clientId, t);
1196
- } else {
1197
- let t = n.get(e.clientId);
1198
- if (t) {
1199
- let r = new Set(t);
1200
- r.delete(e.turnId), r.size === 0 ? n.delete(e.clientId) : n.set(e.clientId, r);
1201
- }
1202
- }
1203
- return n;
1204
- });
1205
- });
1206
- }, [i]), a;
1207
- }, Y = {
1556
+ }, [n]), r;
1557
+ }, Z = (t) => new e.ErrorInfo(`unable to ${t}; hook is skipped`, N.InvalidArgument, 400), Q = () => ({
1208
1558
  get tree() {
1209
- throw new s.ErrorInfo("unable to access tree; hook is skipped", O.InvalidArgument, 400);
1559
+ throw Z("access tree");
1210
1560
  },
1211
1561
  get view() {
1212
- throw new s.ErrorInfo("unable to access view; hook is skipped", O.InvalidArgument, 400);
1562
+ throw Z("access view");
1213
1563
  },
1214
- createView: () => {
1215
- throw new s.ErrorInfo("unable to create view; hook is skipped", O.InvalidArgument, 400);
1564
+ get presence() {
1565
+ throw Z("access presence");
1216
1566
  },
1217
- cancel: () => {
1218
- throw new s.ErrorInfo("unable to cancel; hook is skipped", O.InvalidArgument, 400);
1567
+ get object() {
1568
+ throw Z("access object");
1219
1569
  },
1220
- stageEvents: () => {
1221
- throw new s.ErrorInfo("unable to stage events; hook is skipped", O.InvalidArgument, 400);
1570
+ connect: () => {
1571
+ throw Z("connect");
1222
1572
  },
1223
- stageMessage: () => {
1224
- throw new s.ErrorInfo("unable to stage message; hook is skipped", O.InvalidArgument, 400);
1573
+ createView: () => {
1574
+ throw Z("create view");
1225
1575
  },
1226
- waitForTurn: () => {
1227
- throw new s.ErrorInfo("unable to wait for turn; hook is skipped", O.InvalidArgument, 400);
1576
+ cancel: () => {
1577
+ throw Z("cancel");
1228
1578
  },
1229
1579
  on: () => {
1230
- throw new s.ErrorInfo("unable to subscribe; hook is skipped", O.InvalidArgument, 400);
1580
+ throw Z("subscribe");
1231
1581
  },
1232
1582
  close: () => {
1233
- throw new s.ErrorInfo("unable to close; hook is skipped", O.InvalidArgument, 400);
1583
+ throw Z("close");
1234
1584
  }
1235
- }, X = ({ channelName: e, skip: t, onError: i } = {}) => {
1236
- let o = n(d), c = n(f), l = a(i);
1237
- l.current = i;
1238
- let u = t ? void 0 : e === void 0 ? c?.transport : o[e]?.transport;
1239
- if (r(() => {
1585
+ }), Ie = ({ channelName: t, skip: n, onError: r } = {}) => {
1586
+ let { nearest: i, providers: s } = a(J), l = c(r);
1587
+ l.current = r;
1588
+ let u = n ? void 0 : t === void 0 ? i?.session : s[t]?.session;
1589
+ if (o(() => {
1240
1590
  if (u) return u.on("error", (e) => {
1241
1591
  l.current?.(e);
1242
1592
  });
1243
- }, [u]), t) return { transport: Y };
1244
- if (e !== void 0) {
1245
- let t = o[e];
1246
- return t ? t.transport ? { transport: t.transport } : {
1247
- transport: Y,
1248
- transportError: t.error
1593
+ }, [u]), n) return { session: Q() };
1594
+ if (t !== void 0) {
1595
+ let n = s[t];
1596
+ return n ? n.session ? { session: n.session } : {
1597
+ session: Q(),
1598
+ sessionError: n.sessionError
1249
1599
  } : {
1250
- transport: Y,
1251
- transportError: new s.ErrorInfo(`unable to use transport; no TransportProvider found for channelName "${e}"`, O.BadRequest, 400)
1600
+ session: Q(),
1601
+ sessionError: new e.ErrorInfo(`unable to use session; no ClientSessionProvider found for channelName "${t}"`, N.BadRequest, 400)
1252
1602
  };
1253
1603
  }
1254
- return c ? c.transport ? { transport: c.transport } : {
1255
- transport: Y,
1256
- transportError: c.error
1604
+ return i ? i.session ? { session: i.session } : {
1605
+ session: Q(),
1606
+ sessionError: i.sessionError
1257
1607
  } : {
1258
- transport: Y,
1259
- transportError: new s.ErrorInfo("unable to use transport; no TransportProvider found in the tree", O.BadRequest, 400)
1608
+ session: Q(),
1609
+ sessionError: new e.ErrorInfo("unable to use session; no ClientSessionProvider found in the tree", N.BadRequest, 400)
1260
1610
  };
1261
- }, Z = ({ transport: e, view: c, limit: l, skip: u } = {}) => {
1262
- let d = n(f), p = u ? void 0 : e ?? d?.transport, m = u ? void 0 : c ?? p?.view, [h, g] = o(() => m?.flattenNodes() ?? []), [_, v] = o(() => m?.hasOlder() ?? !1), [y, b] = o(!1), [x, S] = o(), C = a(!1), w = l !== void 0, T = a(!1);
1263
- r(() => {
1264
- if (!m) {
1265
- g([]), v(!1), S(void 0);
1611
+ }, Le = {
1612
+ hasSiblings: !1,
1613
+ siblings: [],
1614
+ index: 0,
1615
+ selected: void 0
1616
+ }, $ = ({ session: t, view: n, limit: r, skip: a } = {}) => {
1617
+ let s = X({
1618
+ session: t,
1619
+ skip: a
1620
+ }), u = a ? void 0 : n ?? s?.view, [d, f] = l(() => u?.getMessages() ?? []), [p, m] = l(() => u?.hasOlder() ?? !1), [h, g] = l(!1), [_, v] = l(), y = c(!1), b = r !== void 0, x = c(!1);
1621
+ o(() => {
1622
+ if (!u) {
1623
+ f([]), m(!1), v(void 0);
1266
1624
  return;
1267
1625
  }
1268
- return T.current = !1, g(m.flattenNodes()), v(m.hasOlder()), S(void 0), m.on("update", () => {
1269
- g(m.flattenNodes()), v(m.hasOlder());
1626
+ return x.current = !1, f(u.getMessages()), m(u.hasOlder()), v(void 0), u.on("update", () => {
1627
+ f(u.getMessages()), m(u.hasOlder());
1270
1628
  });
1271
- }, [m]);
1272
- let E = t(async () => {
1273
- if (!(!m || C.current)) {
1274
- C.current = !0, b(!0);
1629
+ }, [u]);
1630
+ let S = i(async () => {
1631
+ if (!(!u || y.current)) {
1632
+ y.current = !0, g(!0);
1275
1633
  try {
1276
- await m.loadOlder(l), S(void 0);
1277
- } catch (e) {
1278
- e instanceof s.ErrorInfo ? S(e) : S(new s.ErrorInfo("Unknown error loading older messages", O.BadRequest, 400));
1634
+ await u.loadOlder(r), v(void 0);
1635
+ } catch (t) {
1636
+ t instanceof e.ErrorInfo ? v(t) : v(new e.ErrorInfo("Unknown error loading older messages", N.BadRequest, 400));
1279
1637
  } finally {
1280
- C.current = !1, b(!1);
1638
+ y.current = !1, g(!1);
1281
1639
  }
1282
1640
  }
1283
- }, [m, l]);
1284
- return r(() => {
1285
- !w || T.current || !m || (T.current = !0, E());
1641
+ }, [u, r]);
1642
+ return o(() => {
1643
+ !b || x.current || !u || (x.current = !0, S());
1286
1644
  }, [
1287
- w,
1288
- m,
1289
- E
1645
+ b,
1646
+ u,
1647
+ S
1290
1648
  ]), {
1291
- messages: i(() => h.map((e) => e.message), [h]),
1292
- nodes: h,
1293
- hasOlder: _,
1294
- loading: y,
1295
- loadError: x,
1296
- loadOlder: E,
1297
- select: t((e, t) => {
1298
- m?.select(e, t);
1299
- }, [m]),
1300
- getSelectedIndex: t((e) => m?.getSelectedIndex(e) ?? 0, [m]),
1301
- getSiblings: t((e) => m?.getSiblings(e) ?? [], [m]),
1302
- hasSiblings: t((e) => m?.hasSiblings(e) ?? !1, [m]),
1303
- getNode: t((e) => m?.getNode(e), [m]),
1304
- send: t(async (e, t) => {
1305
- if (!m) throw new s.ErrorInfo("unable to send; view is not available", O.InvalidArgument, 400);
1306
- return m.send(e, t);
1307
- }, [m]),
1308
- regenerate: t(async (e, t) => {
1309
- if (!m) throw new s.ErrorInfo("unable to regenerate; view is not available", O.InvalidArgument, 400);
1310
- return m.regenerate(e, t);
1311
- }, [m]),
1312
- edit: t(async (e, t, n) => {
1313
- if (!m) throw new s.ErrorInfo("unable to edit; view is not available", O.InvalidArgument, 400);
1314
- return m.edit(e, t, n);
1315
- }, [m]),
1316
- update: t(async (e, t, n) => {
1317
- if (!m) throw new s.ErrorInfo("unable to update; view is not available", O.InvalidArgument, 400);
1318
- return m.update(e, t, n);
1319
- }, [m])
1649
+ messages: d,
1650
+ hasOlder: p,
1651
+ loading: h,
1652
+ loadError: _,
1653
+ loadOlder: S,
1654
+ runOf: i((e) => u?.runOf(e), [u]),
1655
+ run: i((e) => u?.run(e), [u]),
1656
+ runs: i(() => u?.runs() ?? [], [u]),
1657
+ branchSelection: i((e) => u?.branchSelection(e) ?? Le, [u]),
1658
+ selectSibling: i((e, t) => {
1659
+ u?.selectSibling(e, t);
1660
+ }, [u]),
1661
+ send: i(async (t, n) => {
1662
+ if (!u) throw new e.ErrorInfo("unable to send; view is not available", N.InvalidArgument, 400);
1663
+ return u.send(t, n);
1664
+ }, [u]),
1665
+ regenerate: i(async (t, n) => {
1666
+ if (!u) throw new e.ErrorInfo("unable to regenerate; view is not available", N.InvalidArgument, 400);
1667
+ return u.regenerate(t, n);
1668
+ }, [u]),
1669
+ edit: i(async (t, n, r) => {
1670
+ if (!u) throw new e.ErrorInfo("unable to edit; view is not available", N.InvalidArgument, 400);
1671
+ return u.edit(t, n, r);
1672
+ }, [u])
1320
1673
  };
1321
- }, Q = ({ transport: e, limit: t, skip: i } = {}) => {
1322
- let a = n(f), s = i ? void 0 : e ?? a?.transport, [c, l] = o();
1323
- return r(() => {
1324
- if (!s) {
1325
- l(void 0);
1674
+ }, Re = ({ session: e, limit: t, skip: n } = {}) => {
1675
+ let r = X({
1676
+ session: e,
1677
+ skip: n
1678
+ }), [i, a] = l();
1679
+ return o(() => {
1680
+ if (!r) {
1681
+ a(void 0);
1326
1682
  return;
1327
1683
  }
1328
- let e = s.createView();
1329
- return l(e), () => {
1684
+ let e = r.createView();
1685
+ return a(e), () => {
1330
1686
  e.close();
1331
1687
  };
1332
- }, [s]), Z({
1333
- view: c,
1688
+ }, [r]), $({
1689
+ view: i,
1334
1690
  limit: t,
1335
- skip: i
1691
+ skip: n
1336
1692
  });
1337
- }, $ = ({ transport: e } = {}) => {
1338
- let r = n(f), i = e ?? r?.transport;
1693
+ }, ze = ({ session: e } = {}) => {
1694
+ let t = X({ session: e });
1339
1695
  return {
1340
- getSiblings: t((e) => i?.tree.getSiblings(e) ?? [], [i]),
1341
- hasSiblings: t((e) => i?.tree.hasSiblings(e) ?? !1, [i]),
1342
- getNode: t((e) => i?.tree.getNode(e), [i])
1696
+ getRunNode: i((e) => t?.tree.getRunNode(e), [t]),
1697
+ getNodeByCodecMessageId: i((e) => t?.tree.getNodeByCodecMessageId(e), [t]),
1698
+ getSiblingNodes: i((e) => t?.tree.getSiblingNodes(e) ?? [], [t])
1343
1699
  };
1344
- }, de = () => ({
1345
- TransportProvider: K,
1346
- useClientTransport: (e) => X(e ?? {}),
1347
- useView: (e) => Z(e ?? {}),
1348
- useActiveTurns: (e) => J(e ?? {}),
1349
- useTree: (e) => $(e ?? {}),
1350
- useAblyMessages: (e) => q(e ?? {}),
1351
- useCreateView: (e) => Q(e ?? {})
1700
+ }, Be = () => ({
1701
+ ClientSessionProvider: Y,
1702
+ useClientSession: (e) => Ie(e ?? {}),
1703
+ useView: (e) => $(e ?? {}),
1704
+ useTree: (e) => ze(e ?? {}),
1705
+ useAblyMessages: (e) => Fe(e ?? {}),
1706
+ useCreateView: (e) => Re(e ?? {})
1352
1707
  });
1353
1708
  //#endregion
1354
- export { f as NearestTransportContext, K as TransportProvider, de as createTransportHooks, q as useAblyMessages, J as useActiveTurns, X as useClientTransport, Q as useCreateView, $ as useTree, Z as useView };
1709
+ export { Y as ClientSessionProvider, f as OBJECT_MODES, Be as createSessionHooks, Fe as useAblyMessages, Ie as useClientSession, Re as useCreateView, ze as useTree, $ as useView };
1355
1710
 
1356
1711
  //# sourceMappingURL=ably-ai-transport-react.js.map