@ably/ai-transport 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +91 -100
  2. package/dist/ably-ai-transport.js +1553 -1238
  3. package/dist/ably-ai-transport.js.map +1 -1
  4. package/dist/ably-ai-transport.umd.cjs +1 -1
  5. package/dist/ably-ai-transport.umd.cjs.map +1 -1
  6. package/dist/constants.d.ts +116 -42
  7. package/dist/core/agent.d.ts +29 -0
  8. package/dist/core/codec/decoder.d.ts +20 -23
  9. package/dist/core/codec/encoder.d.ts +11 -8
  10. package/dist/core/codec/index.d.ts +1 -2
  11. package/dist/core/codec/lifecycle-tracker.d.ts +10 -9
  12. package/dist/core/codec/types.d.ts +407 -115
  13. package/dist/core/transport/agent-session.d.ts +10 -0
  14. package/dist/core/transport/branch-chain.d.ts +43 -0
  15. package/dist/core/transport/client-session.d.ts +13 -0
  16. package/dist/core/transport/decode-fold.d.ts +47 -0
  17. package/dist/core/transport/headers.d.ts +96 -18
  18. package/dist/core/transport/index.d.ts +5 -6
  19. package/dist/core/transport/internal/bounded-map.d.ts +20 -0
  20. package/dist/core/transport/invocation.d.ts +74 -0
  21. package/dist/core/transport/load-conversation.d.ts +128 -0
  22. package/dist/core/transport/load-history.d.ts +39 -0
  23. package/dist/core/transport/pipe-stream.d.ts +9 -9
  24. package/dist/core/transport/run-manager.d.ts +78 -0
  25. package/dist/core/transport/tree.d.ts +373 -109
  26. package/dist/core/transport/types/agent.d.ts +353 -0
  27. package/dist/core/transport/types/client.d.ts +168 -0
  28. package/dist/core/transport/types/shared.d.ts +24 -0
  29. package/dist/core/transport/types/tree.d.ts +315 -0
  30. package/dist/core/transport/types/view.d.ts +222 -0
  31. package/dist/core/transport/types.d.ts +13 -553
  32. package/dist/core/transport/view.d.ts +272 -84
  33. package/dist/errors.d.ts +21 -10
  34. package/dist/index.d.ts +6 -8
  35. package/dist/logger.d.ts +12 -0
  36. package/dist/react/ably-ai-transport-react.js +976 -990
  37. package/dist/react/ably-ai-transport-react.js.map +1 -1
  38. package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
  39. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
  40. package/dist/react/contexts/client-session-context.d.ts +36 -0
  41. package/dist/react/contexts/client-session-provider.d.ts +53 -0
  42. package/dist/react/create-session-hooks.d.ts +116 -0
  43. package/dist/react/index.d.ts +12 -12
  44. package/dist/react/internal/use-resolved-session.d.ts +36 -0
  45. package/dist/react/use-ably-messages.d.ts +17 -14
  46. package/dist/react/use-client-session.d.ts +81 -0
  47. package/dist/react/use-create-view.d.ts +14 -13
  48. package/dist/react/use-tree.d.ts +30 -15
  49. package/dist/react/use-view.d.ts +82 -51
  50. package/dist/utils.d.ts +32 -23
  51. package/dist/vercel/ably-ai-transport-vercel.js +2573 -2086
  52. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
  53. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
  54. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
  55. package/dist/vercel/codec/decoder.d.ts +5 -18
  56. package/dist/vercel/codec/encoder.d.ts +6 -36
  57. package/dist/vercel/codec/events.d.ts +51 -0
  58. package/dist/vercel/codec/index.d.ts +24 -12
  59. package/dist/vercel/codec/reducer.d.ts +144 -0
  60. package/dist/vercel/codec/tool-transitions.d.ts +2 -2
  61. package/dist/vercel/index.d.ts +4 -5
  62. package/dist/vercel/react/ably-ai-transport-vercel-react.js +3907 -3266
  63. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
  64. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +33 -8
  65. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
  66. package/dist/vercel/react/contexts/chat-transport-context.d.ts +7 -6
  67. package/dist/vercel/react/contexts/chat-transport-provider.d.ts +53 -41
  68. package/dist/vercel/react/index.d.ts +1 -2
  69. package/dist/vercel/react/use-chat-transport.d.ts +30 -26
  70. package/dist/vercel/react/use-message-sync.d.ts +17 -30
  71. package/dist/vercel/run-end-reason.d.ts +29 -0
  72. package/dist/vercel/transport/chat-transport.d.ts +43 -24
  73. package/dist/vercel/transport/index.d.ts +25 -21
  74. package/dist/vercel/transport/run-output-stream.d.ts +56 -0
  75. package/dist/version.d.ts +2 -0
  76. package/package.json +30 -23
  77. package/src/constants.ts +124 -51
  78. package/src/core/agent.ts +68 -0
  79. package/src/core/codec/decoder.ts +71 -98
  80. package/src/core/codec/encoder.ts +113 -65
  81. package/src/core/codec/index.ts +13 -6
  82. package/src/core/codec/lifecycle-tracker.ts +10 -9
  83. package/src/core/codec/types.ts +436 -120
  84. package/src/core/transport/agent-session.ts +1344 -0
  85. package/src/core/transport/branch-chain.ts +58 -0
  86. package/src/core/transport/client-session.ts +775 -0
  87. package/src/core/transport/decode-fold.ts +91 -0
  88. package/src/core/transport/headers.ts +181 -22
  89. package/src/core/transport/index.ts +25 -26
  90. package/src/core/transport/internal/bounded-map.ts +27 -0
  91. package/src/core/transport/invocation.ts +98 -0
  92. package/src/core/transport/load-conversation.ts +355 -0
  93. package/src/core/transport/load-history.ts +269 -0
  94. package/src/core/transport/pipe-stream.ts +54 -39
  95. package/src/core/transport/run-manager.ts +249 -0
  96. package/src/core/transport/tree.ts +926 -308
  97. package/src/core/transport/types/agent.ts +407 -0
  98. package/src/core/transport/types/client.ts +211 -0
  99. package/src/core/transport/types/shared.ts +27 -0
  100. package/src/core/transport/types/tree.ts +344 -0
  101. package/src/core/transport/types/view.ts +259 -0
  102. package/src/core/transport/types.ts +13 -706
  103. package/src/core/transport/view.ts +864 -433
  104. package/src/errors.ts +22 -9
  105. package/src/event-emitter.ts +3 -2
  106. package/src/index.ts +52 -41
  107. package/src/logger.ts +14 -1
  108. package/src/react/contexts/client-session-context.ts +41 -0
  109. package/src/react/contexts/client-session-provider.tsx +186 -0
  110. package/src/react/create-session-hooks.ts +141 -0
  111. package/src/react/index.ts +23 -13
  112. package/src/react/internal/use-resolved-session.ts +63 -0
  113. package/src/react/use-ably-messages.ts +32 -22
  114. package/src/react/use-client-session.ts +201 -0
  115. package/src/react/use-create-view.ts +33 -29
  116. package/src/react/use-tree.ts +61 -30
  117. package/src/react/use-view.ts +139 -97
  118. package/src/utils.ts +63 -45
  119. package/src/vercel/codec/decoder.ts +336 -258
  120. package/src/vercel/codec/encoder.ts +343 -205
  121. package/src/vercel/codec/events.ts +87 -0
  122. package/src/vercel/codec/index.ts +60 -13
  123. package/src/vercel/codec/reducer.ts +977 -0
  124. package/src/vercel/codec/tool-transitions.ts +2 -2
  125. package/src/vercel/index.ts +6 -19
  126. package/src/vercel/react/contexts/chat-transport-context.ts +7 -6
  127. package/src/vercel/react/contexts/chat-transport-provider.tsx +87 -59
  128. package/src/vercel/react/index.ts +3 -5
  129. package/src/vercel/react/use-chat-transport.ts +47 -49
  130. package/src/vercel/react/use-message-sync.ts +80 -39
  131. package/src/vercel/run-end-reason.ts +78 -0
  132. package/src/vercel/transport/chat-transport.ts +392 -98
  133. package/src/vercel/transport/index.ts +39 -38
  134. package/src/vercel/transport/run-output-stream.ts +170 -0
  135. package/src/version.ts +2 -0
  136. package/dist/core/transport/client-transport.d.ts +0 -10
  137. package/dist/core/transport/decode-history.d.ts +0 -43
  138. package/dist/core/transport/server-transport.d.ts +0 -7
  139. package/dist/core/transport/stream-router.d.ts +0 -29
  140. package/dist/core/transport/turn-manager.d.ts +0 -37
  141. package/dist/react/contexts/transport-context.d.ts +0 -31
  142. package/dist/react/contexts/transport-provider.d.ts +0 -49
  143. package/dist/react/create-transport-hooks.d.ts +0 -124
  144. package/dist/react/use-active-turns.d.ts +0 -12
  145. package/dist/react/use-client-transport.d.ts +0 -80
  146. package/dist/vercel/codec/accumulator.d.ts +0 -21
  147. package/dist/vercel/react/use-staged-add-tool-approval-response.d.ts +0 -30
  148. package/dist/vercel/tool-approvals.d.ts +0 -124
  149. package/dist/vercel/tool-events.d.ts +0 -26
  150. package/src/core/transport/client-transport.ts +0 -977
  151. package/src/core/transport/decode-history.ts +0 -485
  152. package/src/core/transport/server-transport.ts +0 -612
  153. package/src/core/transport/stream-router.ts +0 -136
  154. package/src/core/transport/turn-manager.ts +0 -165
  155. package/src/react/contexts/transport-context.ts +0 -37
  156. package/src/react/contexts/transport-provider.tsx +0 -164
  157. package/src/react/create-transport-hooks.ts +0 -144
  158. package/src/react/use-active-turns.ts +0 -72
  159. package/src/react/use-client-transport.ts +0 -197
  160. package/src/vercel/codec/accumulator.ts +0 -588
  161. package/src/vercel/react/use-staged-add-tool-approval-response.ts +0 -87
  162. package/src/vercel/tool-approvals.ts +0 -380
  163. package/src/vercel/tool-events.ts +0 -53
@@ -1,73 +1,70 @@
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";
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) => ({
1
+ import * as e from "ably";
2
+ import { useAbly as t } from "ably/react";
3
+ import { createContext as n, useCallback as r, useContext as i, useEffect as a, useMemo as o, useRef as s, useState as c } from "react";
4
+ import { jsx as l } from "react/jsx-runtime";
5
+ var u = "status", d = "run-id", f = "invocation-id", p = "event-id", m = "codec-message-id", h = "run-client-id", g = "input-client-id", _ = "role", v = "parent", y = "fork-of", b = "msg-regenerate", x = "input-codec-message-id", S = "error-code", ee = "ai-cancel", C = /* @__PURE__ */ function(e) {
6
+ 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;
7
+ }({}), te = (e) => ({
9
8
  logAction: (t, n, r) => {
10
9
  e.error(n, { detail: r });
11
10
  },
12
11
  shouldLog: () => !0
13
- }), te = s.Realtime.EventEmitter, k = class extends te {
12
+ }), ne = e.Realtime.EventEmitter, w = class extends ne {
14
13
  constructor(e) {
15
- super(ee(e));
14
+ super(te(e));
16
15
  }
17
- }, A = /* @__PURE__ */ function(e) {
16
+ }, T = /* @__PURE__ */ function(e) {
18
17
  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) => {
18
+ }({}), re = (e, t, n) => {
20
19
  let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
21
20
  switch (t) {
22
- case A.Trace:
23
- case A.Debug:
21
+ case "trace":
22
+ case "debug":
24
23
  console.log(i);
25
24
  break;
26
- case A.Info:
25
+ case "info":
27
26
  console.info(i);
28
27
  break;
29
- case A.Warn:
28
+ case "warn":
30
29
  console.warn(i);
31
30
  break;
32
- case A.Error:
31
+ case "error":
33
32
  console.error(i);
34
33
  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;
34
+ case "silent": break;
35
+ }
36
+ }, ie = (e) => new ae(e.logHandler ?? re, e.logLevel), E = new Map([
37
+ ["trace", 0],
38
+ ["debug", 1],
39
+ ["info", 2],
40
+ ["warn", 3],
41
+ ["error", 4],
42
+ ["silent", 5]
43
+ ]), ae = class t {
44
+ constructor(t, n, r) {
45
+ this._handler = t, this._context = r;
46
+ let i = E.get(n);
47
+ if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, C.InvalidArgument, 400);
48
+ this._levelNumber = i;
52
49
  }
53
50
  trace(e, t) {
54
- this._write(e, A.Trace, j.Trace, t);
51
+ this._write(e, "trace", 0, t);
55
52
  }
56
53
  debug(e, t) {
57
- this._write(e, A.Debug, j.Debug, t);
54
+ this._write(e, "debug", 1, t);
58
55
  }
59
56
  info(e, t) {
60
- this._write(e, A.Info, j.Info, t);
57
+ this._write(e, "info", 2, t);
61
58
  }
62
59
  warn(e, t) {
63
- this._write(e, A.Warn, j.Warn, t);
60
+ this._write(e, "warn", 3, t);
64
61
  }
65
62
  error(e, t) {
66
- this._write(e, A.Error, j.Error, t);
63
+ this._write(e, "error", 4, t);
67
64
  }
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));
65
+ withContext(e) {
66
+ let n = [...E.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? "error";
67
+ return new t(this._handler, n, this._mergeContext(e));
71
68
  }
72
69
  _write(e, t, n, r) {
73
70
  n >= this._levelNumber && this._handler(e, t, this._mergeContext(r));
@@ -78,155 +75,219 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
78
75
  ...e
79
76
  } : this._context : e ?? void 0;
80
77
  }
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) => {
78
+ }, oe = (e, t) => {
79
+ let n = e.extras;
80
+ if (!n || typeof n != "object") return {};
81
+ let r = n.ai;
82
+ if (!r || typeof r != "object") return {};
83
+ let i = r[t];
84
+ return !i || typeof i != "object" ? {} : i;
85
+ }, D = (e) => oe(e, "transport"), O = "0.2.0", k = "ai-transport-js", se = (e, t) => {
86
+ let n = e;
87
+ return n.options.agents = {
88
+ ...n.options.agents,
89
+ ...t
90
+ }, { params: { agent: Object.entries(t).map(([e, t]) => `${e}/${t}`).join(" ") } };
91
+ }, ce = (e, t) => {
92
+ let n = t?.adapterTag, r = { [k]: O };
93
+ return n && (r[n] = O), se(e, r);
94
+ }, le = (e) => {
87
95
  let t = {
88
96
  [_]: e.role,
89
- [m]: e.turnId,
90
- [h]: e.msgId
97
+ [m]: e.codecMessageId
91
98
  };
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;
99
+ return e.runId !== void 0 && (t[d] = e.runId), e.runClientId !== void 0 && (t[h] = e.runClientId), e.parent && (t[v] = e.parent), e.forkOf && (t[y] = e.forkOf), e.regenerates && (t[b] = e.regenerates), e.invocationId && (t[f] = e.invocationId), e.inputClientId !== void 0 && (t[g] = e.inputClientId), e.inputCodecMessageId !== void 0 && (t[x] = e.inputCodecMessageId), e.inputEventId && (t[p] = e.inputEventId), t;
100
+ }, A = (e) => e === "ai-run-start" || e === "ai-run-suspend" || e === "ai-run-resume" || e === "ai-run-end", j = (e, t, n) => {
101
+ let r = t[d];
102
+ if (!r) return;
103
+ let i = t["run-client-id"] ?? "";
104
+ if (e === "ai-run-start") {
105
+ let e = t[v], a = t[y], o = t[b];
106
+ return {
107
+ type: "start",
108
+ runId: r,
109
+ clientId: i,
110
+ serial: n,
111
+ invocationId: t["invocation-id"] ?? "",
112
+ ...e !== void 0 && { parent: e },
113
+ ...a !== void 0 && { forkOf: a },
114
+ ...o !== void 0 && { regenerates: o }
115
+ };
125
116
  }
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;
117
+ if (e === "ai-run-suspend") return {
118
+ type: "suspend",
119
+ runId: r,
120
+ clientId: i,
121
+ serial: n,
122
+ invocationId: t["invocation-id"] ?? ""
123
+ };
124
+ if (e === "ai-run-resume") return {
125
+ type: "resume",
126
+ runId: r,
127
+ clientId: i,
128
+ serial: n,
129
+ invocationId: t["invocation-id"] ?? ""
130
+ };
131
+ if (e === "ai-run-end") {
132
+ let e = t["run-reason"] ?? "complete";
133
+ return {
134
+ type: "end",
135
+ runId: r,
136
+ clientId: i,
137
+ serial: n,
138
+ invocationId: t["invocation-id"] ?? "",
139
+ reason: e
140
+ };
135
141
  }
136
- has(e) {
137
- return this._turns.has(e);
142
+ }, M = (e, t, n) => {
143
+ let r = D(n), i = n.serial;
144
+ if (A(n.name)) {
145
+ let t = j(n.name, r, i);
146
+ return t && e.applyRunLifecycle(t), t;
147
+ }
148
+ let { inputs: a, outputs: o } = t.decode(n);
149
+ (a.length > 0 || o.length > 0 || r["run-id"]) && e.applyMessage({
150
+ inputs: a,
151
+ outputs: o
152
+ }, r, i);
153
+ }, ue = class e {
154
+ constructor(e) {
155
+ this.inputEventId = e.inputEventId, this.sessionName = e.sessionName;
138
156
  }
139
- }, L = (e, t) => new I(e, t), R = class {
140
- get structuralVersion() {
141
- return this._structuralVersion;
157
+ static fromJSON(t) {
158
+ return new e(t);
142
159
  }
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);
160
+ toJSON() {
161
+ return {
162
+ inputEventId: this.inputEventId,
163
+ sessionName: this.sessionName
164
+ };
165
+ }
166
+ }, N = (e) => e.kind === "run" ? e.runId : e.codecMessageId, P = (e) => e.kind === "run" ? e.startSerial : e.serial, F = (e, t, n) => {
167
+ let r = e.get(t);
168
+ r || (r = /* @__PURE__ */ new Set(), e.set(t, r)), r.add(n);
169
+ }, I = (e, t, n) => {
170
+ let r = e.get(t);
171
+ r && (r.delete(n), r.size === 0 && e.delete(t));
172
+ }, L = class {
173
+ constructor(e, t) {
174
+ 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._codec = e, this._logger = t, this._emitter = new w(t);
145
175
  }
146
176
  _compareNodes(e, t) {
147
- let n = e.node.serial, r = t.node.serial;
177
+ let n = P(e.node), r = P(t.node);
148
178
  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
179
  }
150
- _insertSorted(e) {
151
- if (e.node.serial === void 0) {
152
- this._sortedList.push(e);
180
+ _insertSortedNode(e) {
181
+ if (P(e.node) === void 0) {
182
+ this._sortedNodes.push(e);
153
183
  return;
154
184
  }
155
- let t = 0, n = this._sortedList.length;
185
+ let t = 0, n = this._sortedNodes.length;
156
186
  for (; t < n;) {
157
- let r = t + n >>> 1, i = this._sortedList[r];
187
+ let r = t + n >>> 1, i = this._sortedNodes[r];
158
188
  if (!i) break;
159
189
  this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
160
190
  }
161
- this._sortedList.splice(t, 0, e);
191
+ this._sortedNodes.splice(t, 0, e);
192
+ }
193
+ _removeSortedNode(e) {
194
+ let t = this._sortedNodes.indexOf(e);
195
+ t !== -1 && this._sortedNodes.splice(t, 1);
162
196
  }
163
- _removeSorted(e) {
164
- let t = this._sortedList.indexOf(e);
165
- t !== -1 && this._sortedList.splice(t, 1);
197
+ _insertNode(e, t, n) {
198
+ this._nodeIndex.set(e, t), this._addToParentIndex(n, e), this._insertSortedNode(t), this._structuralVersion++;
199
+ }
200
+ _promoteSerial(e) {
201
+ this._removeSortedNode(e), this._insertSortedNode(e), this._structuralVersion++;
202
+ }
203
+ _foldInto(e, t, n, r) {
204
+ for (let i of t) try {
205
+ e.node.projection = this._codec.fold(e.node.projection, i, {
206
+ serial: n ?? "",
207
+ messageId: r
208
+ });
209
+ } catch (t) {
210
+ this._logger.error("Tree._foldInto(); fold threw", {
211
+ key: N(e.node),
212
+ messageId: r,
213
+ err: t
214
+ });
215
+ }
166
216
  }
167
217
  _addToParentIndex(e, t) {
168
- let n = this._parentIndex.get(e);
169
- n || (n = /* @__PURE__ */ new Set(), this._parentIndex.set(e, n)), n.add(t);
218
+ F(this._parentIndex, e, t);
170
219
  }
171
220
  _removeFromParentIndex(e, t) {
172
- let n = this._parentIndex.get(e);
173
- n && (n.delete(t), n.size === 0 && this._parentIndex.delete(e));
221
+ I(this._parentIndex, e, t);
222
+ }
223
+ _parentKeyOf(e) {
224
+ let t = e.parentCodecMessageId;
225
+ return t === void 0 ? void 0 : this._codecMessageIdToNodeKey.get(t);
226
+ }
227
+ _inputGroupRoot(e) {
228
+ let t = e, n = new Set([N(t)]);
229
+ for (; t.forkOf !== void 0 && !n.has(t.forkOf);) {
230
+ let e = this._nodeIndex.get(t.forkOf);
231
+ if (e?.node.kind !== "input" || e.node.parentCodecMessageId !== t.parentCodecMessageId) break;
232
+ t = e.node, n.add(N(t));
233
+ }
234
+ return t;
174
235
  }
175
236
  _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) {
237
+ this._siblingCacheVersion !== this._structuralVersion && (this._siblingCache.clear(), this._siblingCacheVersion = this._structuralVersion);
238
+ let t = this._siblingCache.get(e);
239
+ if (t) return t;
240
+ let n = this._nodeIndex.get(e);
241
+ if (!n) return [];
242
+ let r = n.node;
243
+ r.kind === "input" && (r = this._inputGroupRoot(r));
244
+ let i = r.parentCodecMessageId, a = [], o = this._parentIndex.get(i);
245
+ if (o) for (let e of o) {
186
246
  let t = this._nodeIndex.get(e);
187
- t && this._isSiblingOf(t.node, a) && o.push(t);
247
+ t && this._isSiblingOf(t.node, r) && a.push(t);
188
248
  }
189
- return o.sort((e, t) => this._compareNodes(e, t)), o.map((e) => e.node);
249
+ a.sort((e, t) => this._compareNodes(e, t));
250
+ for (let e of a) this._siblingCache.set(N(e.node), a);
251
+ return this._siblingCache.set(e, a), a;
190
252
  }
191
253
  _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);
254
+ if (e.kind !== t.kind || e.parentCodecMessageId !== t.parentCodecMessageId) return !1;
255
+ if (e.kind === "run") return !0;
256
+ let n = N(t);
257
+ if (N(e) === n) return !0;
258
+ let r = e, i = new Set([N(r)]);
259
+ for (; r.kind === "input" && r.forkOf !== void 0;) {
260
+ if (r.forkOf === n) return !0;
261
+ if (i.has(r.forkOf)) break;
262
+ let e = this._nodeIndex.get(r.forkOf);
198
263
  if (!e) break;
199
- n = e.node, r.add(n.msgId);
264
+ r = e.node, i.add(N(r));
200
265
  }
201
266
  return !1;
202
267
  }
203
268
  getGroupRoot(e) {
204
269
  let t = this._nodeIndex.get(e);
205
270
  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;
271
+ if (t.node.kind === "input") return N(this._inputGroupRoot(t.node));
272
+ let n = this._getSiblingGroup(e)[0]?.node;
273
+ return n ? N(n) : e;
213
274
  }
214
- flattenNodes(e) {
215
- this._logger.trace("DefaultTree.flattenNodes();");
275
+ visibleNodes(e = /* @__PURE__ */ new Map()) {
276
+ this._logger.trace("DefaultTree.visibleNodes();");
216
277
  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;
278
+ for (let i of this._sortedNodes) {
279
+ let a = i.node, o = N(a), s = this._parentKeyOf(a);
219
280
  if (s !== void 0 && !n.has(s)) continue;
220
281
  let c = this._getSiblingGroup(o);
221
282
  if (c.length > 1) {
222
283
  let t = this.getGroupRoot(o), n = r.get(t);
223
284
  if (n === void 0) {
224
285
  let i = e.get(t);
225
- if (i && c.some((e) => e.msgId === i)) n = i;
286
+ if (i !== void 0 && c.some((e) => N(e.node) === i)) n = i;
226
287
  else {
227
288
  let e = c.at(-1);
228
289
  if (!e) break;
229
- n = e.msgId;
290
+ n = N(e.node);
230
291
  }
231
292
  r.set(t, n);
232
293
  }
@@ -236,64 +297,185 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
236
297
  }
237
298
  return t;
238
299
  }
239
- getSiblings(e) {
240
- return this._logger.trace("DefaultTree.getSiblings();", { msgId: e }), this._getSiblingGroup(e).map((e) => e.message);
300
+ getRunNode(e) {
301
+ this._logger.trace("DefaultTree.getRunNode();", { runId: e });
302
+ let t = this._nodeIndex.get(e)?.node;
303
+ return t?.kind === "run" ? t : void 0;
241
304
  }
242
- getSiblingNodes(e) {
243
- return this._getSiblingGroup(e);
305
+ getNode(e) {
306
+ return this._logger.trace("DefaultTree.getNode();", { key: e }), this._nodeIndex.get(e)?.node;
244
307
  }
245
- hasSiblings(e) {
246
- return this._getSiblingGroup(e).length > 1;
308
+ getNodeByCodecMessageId(e) {
309
+ this._logger.trace("DefaultTree.getNodeByCodecMessageId();", { codecMessageId: e });
310
+ let t = this._codecMessageIdToNodeKey.get(e);
311
+ return t === void 0 ? void 0 : this._nodeIndex.get(t)?.node;
247
312
  }
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");
313
+ getReplyRuns(e) {
314
+ let t = this._replyRunsByInput.get(e);
315
+ if (!t) return [];
316
+ let n = [];
317
+ for (let e of t) {
318
+ let t = this._nodeIndex.get(e)?.node;
319
+ t?.kind === "run" && n.push(t);
320
+ }
321
+ return n;
322
+ }
323
+ getSiblingNodes(e) {
324
+ return this._logger.trace("DefaultTree.getSiblingNodes();", { key: e }), this._getSiblingGroup(e).map((e) => e.node);
325
+ }
326
+ applyMessage(e, t, n) {
327
+ let r = t[d], i = t[m], a = r === void 0 && i !== void 0 && t.role === "user" && e.inputs.length > 0 ? i : void 0;
328
+ if (r === void 0 && a === void 0) {
329
+ this._logger.warn("Tree.applyMessage(); message has no run-id and is not a user input; skipping");
261
330
  return;
262
331
  }
263
- this._logger.trace("Tree.upsert(); inserting new node", {
264
- msgId: e,
265
- parentId: i,
266
- forkOf: a
332
+ let o = [...e.inputs, ...e.outputs], s = a ?? r;
333
+ if (o.length === 0 && s !== void 0 && !this._nodeIndex.has(s)) return;
334
+ let c = this._structuralVersion;
335
+ a === void 0 ? r !== void 0 && this._applyRunMessage(r, e, t, n) : this._applyInputMessage(a, t, n, o), this._structuralVersion !== c && this._emitter.emit("update");
336
+ }
337
+ _applyInputMessage(e, t, n, r) {
338
+ let i = this._nodeIndex.get(e);
339
+ i ? i.node.kind === "input" && n && !i.node.serial && (this._logger.debug("Tree.applyMessage(); promoting input serial", {
340
+ codecMessageId: e,
341
+ serial: n
342
+ }), i.node.serial = n, this._promoteSerial(i)) : (i = this._createInputNodeFromHeaders(e, t, n), this._insertNode(e, i, i.node.parentCodecMessageId), this._codecMessageIdToNodeKey.set(e, e), this._logger.debug("Tree.applyMessage(); created input node", { codecMessageId: e })), this._foldInto(i, r, n, e), this._emitter.emit("output", {
343
+ runId: void 0,
344
+ inputCodecMessageId: e,
345
+ codecMessageId: e,
346
+ serial: n,
347
+ events: []
348
+ });
349
+ }
350
+ _applyRunMessage(e, t, n, r) {
351
+ let i = n[m], a = n[x], o = [...t.inputs, ...t.outputs], s = t.outputs, c = this._nodeIndex.get(e);
352
+ if (!c && i !== void 0) {
353
+ let e = this._codecMessageIdToNodeKey.get(i), t = e === void 0 ? void 0 : this._nodeIndex.get(e);
354
+ t?.node.kind === "run" && t.node.startSerial === void 0 && (c = t);
355
+ }
356
+ c ? r && c.node.kind === "run" && !c.node.startSerial && (this._logger.debug("Tree.applyMessage(); promoting startSerial", {
357
+ runId: e,
358
+ serial: r
359
+ }), c.node.startSerial = r, this._promoteSerial(c)) : (c = this._createRunFromHeaders(e, n, r), this._insertNode(e, c, c.node.parentCodecMessageId), this._indexReplyRun(c.node, e), this._logger.debug("Tree.applyMessage(); created new Run", { runId: e }));
360
+ let l = N(c.node);
361
+ i && this._codecMessageIdToNodeKey.set(i, l), this._foldInto(c, o, r, i), this._emitter.emit("output", {
362
+ runId: l,
363
+ inputCodecMessageId: a,
364
+ codecMessageId: i,
365
+ serial: r,
366
+ events: s
367
+ });
368
+ }
369
+ _indexReplyRun(e, t) {
370
+ e.parentCodecMessageId !== void 0 && F(this._replyRunsByInput, e.parentCodecMessageId, t);
371
+ }
372
+ applyRunLifecycle(e) {
373
+ this._logger.trace("DefaultTree.applyRunLifecycle();", {
374
+ type: e.type,
375
+ runId: e.runId
267
376
  });
268
- let s = {
377
+ let t = this._structuralVersion;
378
+ switch (e.type) {
379
+ case "start":
380
+ this._applyRunStart(e);
381
+ break;
382
+ case "suspend":
383
+ this._applyRunSuspend(e);
384
+ break;
385
+ case "resume":
386
+ this._applyRunResume(e);
387
+ break;
388
+ case "end":
389
+ this._applyRunEnd(e);
390
+ break;
391
+ }
392
+ this._emitter.emit("run", e), this._structuralVersion !== t && this._emitter.emit("update");
393
+ }
394
+ _applyRunStart(e) {
395
+ let t = this._nodeIndex.get(e.runId);
396
+ if (t?.node.kind === "run") {
397
+ let n = t.node;
398
+ if (n.status !== "active" && (n.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) {
399
+ let t = this._codecMessageIdToNodeKey.get(e.forkOf);
400
+ t !== void 0 && t !== e.runId && (n.forkOf = t, this._structuralVersion++);
401
+ }
402
+ n.regeneratesCodecMessageId === void 0 && e.regenerates !== void 0 && (n.regeneratesCodecMessageId = e.regenerates, this._structuralVersion++), n.invocationId === "" && e.invocationId !== "" && (n.invocationId = e.invocationId);
403
+ } else if (!t) {
404
+ let t = this._createRunFromLifecycle(e);
405
+ this._insertNode(e.runId, t, t.node.parentCodecMessageId), this._indexReplyRun(t.node, e.runId);
406
+ }
407
+ }
408
+ _applyRunSuspend(e) {
409
+ let t = this._nodeIndex.get(e.runId);
410
+ t?.node.kind === "run" && (t.node.status = "suspended", t.node.endSerial = e.serial);
411
+ }
412
+ _applyRunResume(e) {
413
+ let t = this._nodeIndex.get(e.runId);
414
+ t?.node.kind === "run" && t.node.status === "suspended" && (t.node.status = "active");
415
+ }
416
+ _applyRunEnd(e) {
417
+ let t = this._nodeIndex.get(e.runId);
418
+ t?.node.kind === "run" && (t.node.status = e.reason, t.node.endSerial = e.serial);
419
+ }
420
+ delete(e) {
421
+ let t = this._nodeIndex.get(e);
422
+ 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 && I(this._replyRunsByInput, t.node.parentCodecMessageId, e), this._structuralVersion++, this._emitter.emit("update"));
423
+ }
424
+ _createRunFromHeaders(e, t, n) {
425
+ let r = t[y];
426
+ return this._buildRunNode({
427
+ runId: e,
428
+ parentCodecMessageId: t[v],
429
+ forkOf: r ? this._codecMessageIdToNodeKey.get(r) : void 0,
430
+ regeneratesCodecMessageId: t[b],
431
+ clientId: t["run-client-id"] ?? "",
432
+ invocationId: t["invocation-id"] ?? "",
433
+ startSerial: n
434
+ });
435
+ }
436
+ _buildRunNode(e) {
437
+ return {
269
438
  node: {
270
- kind: "message",
271
- message: t,
272
- msgId: e,
273
- parentId: i,
274
- forkOf: a,
275
- headers: { ...n },
276
- serial: r
439
+ kind: "run",
440
+ runId: e.runId,
441
+ parentCodecMessageId: e.parentCodecMessageId,
442
+ forkOf: e.forkOf,
443
+ regeneratesCodecMessageId: e.regeneratesCodecMessageId,
444
+ clientId: e.clientId,
445
+ invocationId: e.invocationId,
446
+ status: "active",
447
+ projection: this._codec.init(),
448
+ startSerial: e.startSerial,
449
+ endSerial: void 0
277
450
  },
278
451
  insertSeq: this._seqCounter++
279
452
  };
280
- this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s), this._structuralVersion++, this._emitter.emit("update");
281
453
  }
282
- delete(e) {
283
- 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");
454
+ _createInputNodeFromHeaders(e, t, n) {
455
+ let r = t[y];
456
+ return {
457
+ node: {
458
+ kind: "input",
459
+ codecMessageId: e,
460
+ parentCodecMessageId: t[v],
461
+ forkOf: r,
462
+ projection: this._codec.init(),
463
+ serial: n
464
+ },
465
+ insertSeq: this._seqCounter++
466
+ };
288
467
  }
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;
468
+ _createRunFromLifecycle(e) {
469
+ let t = e.forkOf;
470
+ return this._buildRunNode({
471
+ runId: e.runId,
472
+ parentCodecMessageId: e.parent,
473
+ forkOf: t ? this._codecMessageIdToNodeKey.get(t) : void 0,
474
+ regeneratesCodecMessageId: e.regenerates,
475
+ clientId: e.clientId,
476
+ invocationId: e.invocationId,
477
+ startSerial: e.serial
478
+ });
297
479
  }
298
480
  on(e, t) {
299
481
  let n = t;
@@ -304,165 +486,101 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
304
486
  emitAblyMessage(e) {
305
487
  this._logger.trace("DefaultTree.emitAblyMessage();"), this._emitter.emit("ably-message", e);
306
488
  }
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;
333
- }
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));
344
- }
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));
352
- }
353
- }
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) => {
489
+ }, R = (e, t) => new L(e, t), z = (e, t) => {
390
490
  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);
491
+ let t = D(n), r = t[m];
492
+ if (!r) continue;
493
+ 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[u], c = s === "complete" || s === "cancelled";
494
+ (a || o) && e.startedCodecMessageIds.add(r), (a || c) && e.terminatedCodecMessageIds.add(r), e.startedCodecMessageIds.has(r) && e.terminatedCodecMessageIds.has(r) && e.completedCodecMessageIds.add(r);
395
495
  }
396
- }, H = async (e, t, n) => {
397
- e.rawMessages.push(...t.items), e.lastAblyPage = t, V(e, t.items);
496
+ }, B = async (e, t, n) => {
497
+ e.rawMessages.push(...t.items), e.lastAblyPage = t, z(e, t.items);
398
498
  let r = e.returnedCount + n;
399
- for (; e.completedMsgIds.size < r && t.hasNext();) {
400
- e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
499
+ for (; e.completedCodecMessageIds.size < r && t.hasNext();) {
500
+ e.logger.debug("loadHistory.fetchUntilLimit(); fetching next page", {
401
501
  collected: e.rawMessages.length,
402
- completed: e.completedMsgIds.size
502
+ completed: e.completedCodecMessageIds.size
403
503
  });
404
504
  let n = await t.next();
405
505
  if (!n) break;
406
- t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, V(e, n.items);
506
+ t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, z(e, n.items);
407
507
  }
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() : [];
508
+ }, V = (e, t) => {
509
+ let n = e.completedCodecMessageIds.size, r = Math.min(t, Math.max(0, n - e.returnedCount));
510
+ e.returnedCount += r;
511
+ let i = n > e.returnedCount, a = e.lastAblyPage?.hasNext() ?? !1, o = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
412
512
  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,
513
+ rawMessages: o,
514
+ hasNext: () => i || a,
420
515
  next: async () => {
421
- if (a) return U(e, t);
422
- if (!o || !e.lastAblyPage) return;
516
+ if (i) return V(e, t);
517
+ if (!a || !e.lastAblyPage) return;
423
518
  let n = await e.lastAblyPage.next();
424
- if (n) return await H(e, n, t), U(e, t);
519
+ if (n) return await B(e, n, t), V(e, t);
425
520
  }
426
521
  };
427
- }, ae = async (e, t, n, r) => {
428
- let i = n?.limit ?? 100, a = {
429
- codec: t,
522
+ }, H = async (e, t, n) => {
523
+ let r = t?.limit ?? 100, i = {
430
524
  rawMessages: [],
431
525
  returnedCount: 0,
432
526
  returnedRawCount: 0,
433
527
  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
528
+ startedCodecMessageIds: /* @__PURE__ */ new Set(),
529
+ terminatedCodecMessageIds: /* @__PURE__ */ new Set(),
530
+ completedCodecMessageIds: /* @__PURE__ */ new Set(),
531
+ logger: n
440
532
  };
441
- r.trace("decodeHistory();", { limit: i });
442
- let o = i * 10;
443
- return await e.attach(), await H(a, await e.history({
533
+ n.trace("loadHistory();", { limit: r });
534
+ let a = r * 10;
535
+ return await e.attach(), await B(i, await e.history({
444
536
  untilAttach: !0,
445
- limit: o
446
- }), i), U(a, i);
447
- }, oe = class {
537
+ limit: a
538
+ }), r), V(i, r);
539
+ }, de = (e) => Array.isArray(e) ? e : [e], fe = 3, U = (e) => ({
540
+ runId: e.runId,
541
+ clientId: e.clientId,
542
+ status: e.status,
543
+ invocationId: e.invocationId
544
+ }), pe = class {
448
545
  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", () => {
546
+ this._branchSelections = /* @__PURE__ */ new Map(), this._regenSelections = /* @__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._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._sendDelegate = e.sendDelegate, this._onClose = e.onClose, this._logger = e.logger.withContext({ component: "View" }), this._logger.trace("DefaultView();"), this._emitter = new w(this._logger), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
450
547
  this._onTreeUpdate();
451
548
  }), this._tree.on("ably-message", (e) => {
452
549
  this._onTreeAblyMessage(e);
453
- }), this._tree.on("turn", (e) => {
454
- this._onTreeTurn(e);
550
+ }), this._tree.on("run", (e) => {
551
+ this._onTreeRun(e);
552
+ }), this._tree.on("output", (e) => {
553
+ this._onTreeOutput(e);
455
554
  }));
456
555
  }
556
+ _onTreeOutput(e) {
557
+ 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), this._emitter.emit("update"));
558
+ }
457
559
  getMessages() {
458
- return this.flattenNodes().map((e) => e.message);
560
+ return this._lastVisibleMessagePairs;
459
561
  }
460
- flattenNodes() {
461
- return this._cachedNodes;
562
+ runs() {
563
+ return this._cachedNodes.filter((e) => e.kind === "run").map((e) => U(e));
462
564
  }
463
565
  _computeFlatNodes() {
464
- let e = this._tree.flattenNodes(this._resolveSelections());
465
- return this._withheldMsgIds.size === 0 ? e : e.filter((e) => !this._withheldMsgIds.has(e.msgId));
566
+ let e = this._treeVisibleNodes();
567
+ return this._withheldRunIds.size === 0 ? e : e.filter((e) => !this._withheldRunIds.has(N(e)));
568
+ }
569
+ _recomputeAndEmit() {
570
+ this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update");
571
+ }
572
+ _recomputeAndEmitIfChanged() {
573
+ let e = this._computeFlatNodes();
574
+ this._visibleChanged(e) && (this._cachedNodes = e, this._updateVisibleSnapshot(e), this._emitter.emit("update"));
575
+ }
576
+ _runByCodecMessageId(e) {
577
+ let t = this._tree.getNodeByCodecMessageId(e);
578
+ return t?.kind === "run" ? t : void 0;
579
+ }
580
+ _extractMessages(e) {
581
+ let t = [];
582
+ for (let n of e) for (let e of this._codec.getMessages(n.projection)) t.push(e);
583
+ return t;
466
584
  }
467
585
  hasOlder() {
468
586
  return this._withheldBuffer.length > 0 || this._hasMoreHistory;
@@ -490,7 +608,7 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
490
608
  t || (this._hasMoreHistory = !1);
491
609
  return;
492
610
  }
493
- await this._loadAndReveal(t, e);
611
+ await this._revealFromPage(t, e);
494
612
  } catch (e) {
495
613
  throw this._logger.error("DefaultView.loadOlder(); failed", { error: e }), e;
496
614
  } finally {
@@ -498,132 +616,182 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
498
616
  }
499
617
  }
500
618
  }
501
- select(e, t) {
502
- this._logger.trace("DefaultView.select();", {
503
- msgId: e,
619
+ runOf(e) {
620
+ this._logger.trace("DefaultView.runOf();", { codecMessageId: e });
621
+ let t = this._tree.getNodeByCodecMessageId(e);
622
+ if (!t) return;
623
+ if (t.kind === "run") return U(t);
624
+ let n = this._selectedReplyRun(t.codecMessageId);
625
+ return n ? U(n) : void 0;
626
+ }
627
+ _selectedReplyRun(e) {
628
+ let t = this._tree.getReplyRuns(e);
629
+ if (t.length === 0) return;
630
+ if (t.length === 1) return t[0];
631
+ let n = this._tree.getGroupRoot(t[0]?.runId ?? ""), r = this._regenSelections.get(n), i = r && r.kind !== "pending" ? r.selectedRunId : void 0;
632
+ if (i !== void 0) {
633
+ let e = t.find((e) => e.runId === i);
634
+ if (e) return e;
635
+ }
636
+ return t.toSorted((e, t) => (e.startSerial ?? "￿").localeCompare(t.startSerial ?? "￿")).at(-1);
637
+ }
638
+ run(e) {
639
+ this._logger.trace("DefaultView.run();", { runId: e });
640
+ let t = this._tree.getRunNode(e);
641
+ return t ? U(t) : void 0;
642
+ }
643
+ branchSelection(e) {
644
+ let t = this._resolveMessageBranchPoint(e);
645
+ if (t) {
646
+ let e = t.siblings.flatMap((e) => {
647
+ let t = this._codec.getMessages(e.projection).at(0);
648
+ return t ? [t.message] : [];
649
+ });
650
+ if (e.length > 0) {
651
+ let n = this._resolveSelectedIndex(t), r = Math.max(0, Math.min(n, e.length - 1)), i = e[r];
652
+ return {
653
+ hasSiblings: e.length > 1,
654
+ siblings: e,
655
+ index: r,
656
+ selected: i
657
+ };
658
+ }
659
+ }
660
+ let n = this._tree.getNodeByCodecMessageId(e);
661
+ if (n) {
662
+ let t = this._codec.getMessages(n.projection).find((t) => t.codecMessageId === e);
663
+ if (t !== void 0) return {
664
+ hasSiblings: !1,
665
+ siblings: [t.message],
666
+ index: 0,
667
+ selected: t.message
668
+ };
669
+ }
670
+ return {
671
+ hasSiblings: !1,
672
+ siblings: [],
673
+ index: 0,
674
+ selected: void 0
675
+ };
676
+ }
677
+ selectSibling(e, t) {
678
+ this._logger.trace("DefaultView.selectSibling();", {
679
+ codecMessageId: e,
504
680
  index: t
505
681
  });
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, {
682
+ let n = this._resolveMessageBranchPoint(e);
683
+ if (!n) return;
684
+ let r = Math.max(0, Math.min(t, n.siblings.length - 1)), i = n.siblings[r];
685
+ i && (n.kind === "fork-of" ? (this._branchSelections.set(n.groupRoot, {
686
+ kind: "user",
687
+ selectedKey: N(i)
688
+ }), this._logger.debug("DefaultView.selectSibling(); fork-of", {
689
+ codecMessageId: e,
690
+ index: r,
691
+ selectedKey: N(i)
692
+ })) : (this._regenSelections.set(n.groupRoot, {
510
693
  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);
694
+ selectedRunId: N(i)
695
+ }), this._logger.debug("DefaultView.selectSibling(); regenerate", {
696
+ codecMessageId: e,
697
+ index: r,
698
+ selectedRunId: N(i),
699
+ groupRoot: n.groupRoot
700
+ })), this._recomputeAndEmit());
701
+ }
702
+ _resolveSelectedIndex(e) {
703
+ if (e.kind === "fork-of") {
704
+ let t = this._branchSelections.get(e.groupRoot);
705
+ if (!t) return e.siblings.length - 1;
706
+ let n = e.siblings.findIndex((e) => N(e) === t.selectedKey);
707
+ return n === -1 ? e.siblings.length - 1 : n;
708
+ }
709
+ let t = this._regenSelections.get(e.groupRoot);
710
+ if (!t || t.kind === "pending") return e.siblings.length - 1;
711
+ let n = e.siblings.findIndex((e) => N(e) === t.selectedRunId);
712
+ return n === -1 ? e.siblings.length - 1 : n;
532
713
  }
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);
564
- }
714
+ _resolveMessageBranchPoint(e) {
715
+ let t = this._tree.getNodeByCodecMessageId(e);
716
+ if (!t) return;
717
+ if (t.kind === "input") {
718
+ let e = this._tree.getSiblingNodes(t.codecMessageId);
719
+ return e.length > 1 ? {
720
+ kind: "fork-of",
721
+ groupRoot: this._tree.getGroupRoot(t.codecMessageId),
722
+ siblings: e
723
+ } : void 0;
565
724
  }
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
- });
725
+ let n = this._tree.getSiblingNodes(t.runId);
726
+ if (n.length > 1 && this._codec.getMessages(t.projection).at(0)?.codecMessageId === e) return {
727
+ kind: "regen",
728
+ groupRoot: this._tree.getGroupRoot(t.runId),
729
+ siblings: n
730
+ };
582
731
  }
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, {
732
+ async send(t, n) {
733
+ if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", C.InvalidArgument, 400);
734
+ let r = de(t), i = this._lastVisibleMessagePairs.at(-1)?.codecMessageId, a = await this._sendDelegate(r, n, i);
735
+ return this._applyForkAutoSelect(a, n), a;
736
+ }
737
+ _applyForkAutoSelect(e, t) {
738
+ if (!t?.forkOf) return;
739
+ let n = e.optimisticCodecMessageIds.at(0);
740
+ if (n === void 0) return;
741
+ let r = this._tree.getGroupRoot(n);
742
+ this._branchSelections.set(r, {
743
+ kind: "auto",
744
+ selectedKey: n
745
+ }), this._recomputeAndEmit();
746
+ }
747
+ _applyRegenerateAutoSelect(e, t) {
748
+ let n = this._runByCodecMessageId(t);
749
+ if (!n) return;
750
+ let r = this._tree.getGroupRoot(n.runId);
751
+ this._regenSelections.set(r, {
752
+ kind: "pending",
753
+ carrierCodecMessageId: e.inputCodecMessageId
754
+ }), this._logger.debug("DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection", {
755
+ anchorCodecMessageId: t,
756
+ groupRoot: r,
757
+ carrier: e.inputCodecMessageId
758
+ }), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged();
759
+ }
760
+ async regenerate(t, n) {
761
+ if (this._logger.trace("DefaultView.regenerate();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to regenerate; view is closed", C.InvalidArgument, 400);
762
+ let r = this._runByCodecMessageId(t);
763
+ if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, C.InvalidArgument, 400);
764
+ let i = this._findParentMsgId(r, t);
765
+ if (!i) throw new e.ErrorInfo(`unable to regenerate; parent user message not found for ${t}`, C.InvalidArgument, 400);
766
+ let a = t;
767
+ r.regeneratesCodecMessageId !== void 0 && this._codec.getMessages(r.projection).at(0)?.codecMessageId === t && (a = r.regeneratesCodecMessageId);
768
+ let o = {
589
769
  ...n,
590
- body: {
591
- history: this._getHistoryBefore(e),
592
- ...n?.body
593
- },
594
- forkOf: e,
595
770
  parent: i
771
+ }, s = this._codec.createRegenerate(a, i), c = await this._sendDelegate([s], o, i);
772
+ return this._applyRegenerateAutoSelect(c, a), c;
773
+ }
774
+ async edit(t, n, r) {
775
+ if (this._logger.trace("DefaultView.edit();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to edit; view is closed", C.InvalidArgument, 400);
776
+ let i = this._tree.getNodeByCodecMessageId(t);
777
+ if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, C.InvalidArgument, 400);
778
+ let a = this._findParentMsgId(i, t);
779
+ return this.send(n, {
780
+ ...r,
781
+ forkOf: t,
782
+ parent: a
596
783
  });
597
784
  }
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);
785
+ _findParentMsgId(e, t) {
786
+ let n = this._lastVisibleMessagePairs, r = n.findIndex((e) => e.codecMessageId === t);
787
+ if (r > 0) return n[r - 1]?.codecMessageId;
788
+ if (r === 0) return;
789
+ let i = this._codec.getMessages(e.projection), a = i.findIndex((e) => e.codecMessageId === t);
790
+ if (a > 0) return i[a - 1]?.codecMessageId;
791
+ if (a === 0 && e.parentCodecMessageId !== void 0) {
792
+ let t = this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);
793
+ if (t) return this._codec.getMessages(t.projection).at(-1)?.codecMessageId;
625
794
  }
626
- return t;
627
795
  }
628
796
  on(e, t) {
629
797
  let n = t;
@@ -632,35 +800,38 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
632
800
  };
633
801
  }
634
802
  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?.();
803
+ if (!this._closed) {
804
+ this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
805
+ for (let e of this._unsubs) e();
806
+ this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._regenSelections.clear(), this._withheldRunIds.clear(), this._withheldBuffer.length = 0, this._onClose?.();
807
+ }
638
808
  }
639
809
  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);
810
+ let t = e * fe, n = await H(this._channel, { limit: t }, this._logger);
811
+ this._closed || await this._revealFromPage(n, e);
812
+ }
813
+ async _revealFromPage(e, t) {
814
+ let n = new Set(this._treeVisibleNodes().map((e) => N(e))), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
815
+ this._closed || (this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext(), this._splitReveal(r, t));
816
+ }
817
+ _splitReveal(e, t) {
818
+ let n = 0, r = e.length;
819
+ for (let i = e.length - 1; i >= 0; i--) {
820
+ if (e[i]?.kind === "run") {
821
+ if (n === t) break;
822
+ n++;
823
+ }
824
+ r = i;
825
+ }
826
+ let i = e.slice(r), a = e.slice(0, r);
827
+ for (let e of a) this._withheldRunIds.add(N(e));
828
+ this._withheldBuffer.push(...a), this._releaseWithheld(i);
656
829
  }
657
830
  _processHistoryPage(e) {
658
831
  this._processingHistory = !0;
659
832
  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
- }
833
+ let t = this._codec.createDecoder();
834
+ for (let n of e.rawMessages) M(this._tree, t, n);
664
835
  for (let t of e.rawMessages) this._tree.emitAblyMessage(t);
665
836
  } finally {
666
837
  this._processingHistory = !1;
@@ -670,7 +841,7 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
670
841
  this._processHistoryPage(e);
671
842
  let r = e, i = () => {
672
843
  let e = 0;
673
- for (let t of this._tree.flattenNodes(this._resolveSelections())) n.has(t.msgId) || e++;
844
+ for (let t of this._treeVisibleNodes()) t.kind === "run" && !n.has(N(t)) && e++;
674
845
  return e;
675
846
  };
676
847
  for (; i() < t && r.hasNext();) {
@@ -679,678 +850,493 @@ var d = e({}), f = e(void 0), p = "x-ably-status", m = "x-ably-turn-id", h = "x-
679
850
  this._processHistoryPage(e), r = e;
680
851
  }
681
852
  return {
682
- newVisible: this._tree.flattenNodes(this._resolveSelections()).filter((e) => !n.has(e.msgId)),
853
+ newVisible: this._treeVisibleNodes().filter((e) => !n.has(N(e))),
683
854
  lastPage: r
684
855
  };
685
856
  }
686
857
  _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"));
858
+ for (let t of e) this._withheldRunIds.delete(N(t));
859
+ e.length > 0 && this._recomputeAndEmit();
689
860
  }
690
861
  _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
- }
862
+ let t = e ?? this._cachedNodes;
863
+ this._lastVisibleNodeKeys = t.map((e) => N(e)), this._lastVisibleNodeKeySet = new Set(this._lastVisibleNodeKeys), this._lastVisibleProjections = t.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(t);
697
864
  }
698
865
  _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"));
866
+ this._processingHistory || (this._pinBranchSelections(), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged());
708
867
  }
709
868
  _resolveSelections() {
710
869
  let e = /* @__PURE__ */ new Map();
711
- for (let [t, n] of this._branchSelections) n.kind !== "pending" && e.set(t, n.selectedId);
870
+ for (let [t, n] of this._branchSelections) e.set(t, n.selectedKey);
871
+ for (let [t, n] of this._regenSelections) n.kind !== "pending" && e.set(t, n.selectedRunId);
712
872
  return e;
713
873
  }
874
+ _treeVisibleNodes() {
875
+ return this._tree.visibleNodes(this._resolveSelections());
876
+ }
714
877
  _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, {
878
+ for (let e of this._lastVisibleNodeKeys) {
879
+ if (this._tree.getNode(e)?.kind !== "input" || this._tree.getSiblingNodes(e).length <= 1) continue;
880
+ let t = this._tree.getGroupRoot(e);
881
+ this._branchSelections.get(t) || this._branchSelections.set(t, {
731
882
  kind: "pinned",
732
- selectedId: e
883
+ selectedKey: e
733
884
  });
734
885
  }
735
886
  }
736
- _resolvePendingSelections() {
737
- for (let [e, t] of this._branchSelections) {
738
- if (t.kind !== "pending") continue;
739
- let n = this._tree.getSiblingNodes(e);
887
+ _resolvePendingRegenSelections() {
888
+ for (let [e, t] of this._regenSelections) {
889
+ if (t.kind === "user") continue;
890
+ let n = this._tree.getSiblingNodes(e).filter((e) => e.kind === "run");
740
891
  if (n.length <= 1) continue;
741
892
  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, {
893
+ r && this._regenSelections.set(e, {
747
894
  kind: "auto",
748
- selectedId: r.msgId
749
- }));
895
+ selectedRunId: r.runId
896
+ });
750
897
  }
751
898
  }
752
899
  _onTreeAblyMessage(e) {
753
- let t = P(e)[h];
754
- if (!t) {
900
+ let t = D(e), n = t[m], r = t[d];
901
+ if (!n && !r) {
755
902
  this._emitter.emit("ably-message", e);
756
903
  return;
757
904
  }
758
- this._lastVisibleIds.includes(t) && this._emitter.emit("ably-message", e);
905
+ r && this._lastVisibleNodeKeySet.has(r) && this._emitter.emit("ably-message", e);
759
906
  }
760
- _onTreeTurn(e) {
761
- if (this._lastVisibleTurnIds.has(e.turnId)) {
762
- this._emitter.emit("turn", e);
907
+ _onTreeRun(e) {
908
+ if (this._lastVisibleNodeKeySet.has(e.runId)) {
909
+ this._emitter.emit("run", e);
763
910
  return;
764
911
  }
765
- e.type === "x-ably-turn-start" && this._isTurnStartVisible(e) && (this._lastVisibleTurnIds.add(e.turnId), this._emitter.emit("turn", e));
912
+ e.type === "start" && this._isRunStartVisible(e) && (this._lastVisibleNodeKeySet.add(e.runId), this._emitter.emit("run", e));
766
913
  }
767
- _isTurnStartVisible(e) {
914
+ _isRunStartVisible(e) {
768
915
  let { parent: t } = e;
769
- return t === void 0 ? !0 : this._lastVisibleIds.includes(t);
916
+ if (t === void 0) return !0;
917
+ let n = this._tree.getNodeByCodecMessageId(t);
918
+ return n ? this._lastVisibleNodeKeySet.has(N(n)) : !0;
770
919
  }
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;
920
+ _visibleChanged(e) {
921
+ if (e.length !== this._lastVisibleNodeKeys.length) return !0;
922
+ for (let [t, n] of e.entries()) if (N(n) !== this._lastVisibleNodeKeys[t] || n.projection !== this._lastVisibleProjections[t]) return !0;
775
923
  return !1;
776
924
  }
777
- }, W = (e) => new oe(e), se = () => {}, G = /* @__PURE__ */ function(e) {
778
- return e.READY = "ready", e.CLOSED = "closed", e;
779
- }(G || {}), ce = class {
925
+ }, W = (e) => new pe(e), me = () => {}, he = class {
780
926
  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({
927
+ this._views = /* @__PURE__ */ new Set(), this._state = "ready", this._pendingRunStarts = /* @__PURE__ */ new Map();
928
+ let t = ce(e.client, e.codec);
929
+ if (this._channel = e.client.channels.get(e.channelName, t), this._codec = e.codec, this._clientId = e.clientId, this._logger = (e.logger ?? ie({ logLevel: T.Silent })).withContext({ component: "ClientSession" }), this._emitter = new w(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = R(this._codec, this._logger), this._view = W({
782
930
  tree: this._tree,
783
931
  channel: this._channel,
784
932
  codec: this._codec,
785
933
  sendDelegate: this._internalSend.bind(this),
786
934
  logger: this._logger,
787
935
  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) {
936
+ }), this._decoder = this._codec.createDecoder(), this._encoder = this._codec.createEncoder(this._channel, this._clientId === void 0 ? void 0 : { clientId: this._clientId }), this._views.add(this._view), this.tree = this._tree, this.view = this._view, e.messages) {
789
937
  let t;
790
938
  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;
939
+ let e = crypto.randomUUID(), r = {
940
+ [m]: e,
941
+ [_]: "user"
942
+ };
943
+ t && (r[v] = t), this._tree.applyMessage({
944
+ inputs: [this._codec.createUserMessage(n)],
945
+ outputs: []
946
+ }, r), t = e;
793
947
  }
794
948
  }
795
949
  this._onMessage = (e) => {
796
950
  this._handleMessage(e);
797
- }, this._attachPromise = this._channel.subscribe(this._onMessage), this._onChannelStateChange = (e) => {
951
+ }, this._onChannelStateChange = (e) => {
798
952
  this._handleChannelStateChange(e);
799
953
  }, this._channel.on(this._onChannelStateChange);
800
954
  }
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
- });
955
+ connect() {
956
+ return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", C.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger.trace("DefaultClientSession.connect();"), this._connectPromise = this._channel.subscribe(this._onMessage).then(() => {
957
+ this._logger.debug("DefaultClientSession.connect(); subscribed and attached");
958
+ }, (t) => {
959
+ let n = new e.ErrorInfo(`unable to subscribe to channel; ${t instanceof Error ? t.message : String(t)}`, C.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
960
+ throw this._logger.error("DefaultClientSession.connect(); subscribe failed"), this._emitter.emit("error", n), n;
961
+ }), this._connectPromise);
962
+ }
963
+ async _requireConnected(t) {
964
+ if (!this._connectPromise) throw new e.ErrorInfo(`unable to ${t}; connect() must be called before ${t}()`, C.InvalidArgument, 400);
965
+ return this._connectPromise;
966
+ }
967
+ _handleMessage(t) {
968
+ if (this._state !== "closed") try {
969
+ if (t.name === "ai-run-end") {
970
+ let n = D(t);
971
+ if ((n["run-reason"] ?? "complete") === "error") {
972
+ let t = n[S], r = t === void 0 ? NaN : Number(t), i = Number.isFinite(r) ? r : C.SessionSubscriptionError, a = n["error-message"] ?? "agent reported an error", o = i >= 1e4 && i < 6e4 ? Math.floor(i / 100) : 500, s = new e.ErrorInfo(a, i, o);
973
+ this._logger.error("ClientSession._handleMessage(); agent error received", {
974
+ runId: n[d],
975
+ invocationId: n[f],
976
+ code: i
977
+ }), this._emitter.emit("error", s);
815
978
  }
816
- this._tree.emitAblyMessage(e);
817
- return;
818
979
  }
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
- });
980
+ let n = M(this._tree, this._decoder, t);
981
+ if (n && (n.type === "start" || n.type === "resume")) {
982
+ let e = D(t)[x];
983
+ if (e !== void 0) {
984
+ let t = this._pendingRunStarts.get(e);
985
+ t && (this._pendingRunStarts.delete(e), t.resolve(n.runId));
834
986
  }
835
- this._tree.emitAblyMessage(e);
836
- return;
837
987
  }
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
- }
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));
988
+ this._tree.emitAblyMessage(t);
989
+ } catch (t) {
990
+ let n = t instanceof e.ErrorInfo ? t : void 0;
991
+ this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, C.SessionSubscriptionError, 500, n));
850
992
  }
851
993
  }
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
- _handleChannelStateChange(e) {
884
- if (this._state === G.CLOSED) return;
885
- let { current: t, resumed: n } = e;
886
- if (t === "attached" && !this._hasAttachedOnce) {
994
+ _handleChannelStateChange(t) {
995
+ if (this._state === "closed") return;
996
+ let { current: n, resumed: r } = t;
997
+ if (n === "attached" && !this._hasAttachedOnce) {
887
998
  this._hasAttachedOnce = !0;
888
999
  return;
889
1000
  }
890
- if (!(t === "failed" || t === "suspended" || t === "detached" || t === "attached" && !n)) return;
891
- this._logger.error("ClientTransport._handleChannelStateChange(); channel continuity lost", {
892
- current: t,
893
- resumed: n,
894
- previous: e.previous
895
- });
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);
898
- this._emitter.emit("error", r);
899
- }
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 }
1001
+ if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
1002
+ this._logger.error("ClientSession._handleChannelStateChange(); channel continuity lost", {
1003
+ current: n,
1004
+ resumed: r,
1005
+ previous: t.previous
940
1006
  });
1007
+ let i = new e.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, C.ChannelContinuityLost, 500, t.reason);
1008
+ this._emitter.emit("error", i);
941
1009
  }
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
- }
1010
+ _cleanupFailedSend(e) {
1011
+ for (let t of e) {
1012
+ let e = this._tree.getNodeByCodecMessageId(t);
1013
+ e?.kind === "input" && e.serial === void 0 && this._tree.delete(e.codecMessageId);
959
1014
  }
960
- return t;
961
1015
  }
962
1016
  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({
1017
+ if (this._state === "closed") throw new e.ErrorInfo("unable to create view; session is closed", C.SessionClosed, 400);
1018
+ this._logger.trace("DefaultClientSession.createView();");
1019
+ let t = W({
966
1020
  tree: this._tree,
967
1021
  channel: this._channel,
968
1022
  codec: this._codec,
969
1023
  sendDelegate: this._internalSend.bind(this),
970
1024
  logger: this._logger,
971
- onClose: () => this._views.delete(e)
1025
+ onClose: () => this._views.delete(t)
972
1026
  });
973
- return this._views.add(e), e;
1027
+ return this._views.add(t), t;
974
1028
  }
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);
1029
+ async _internalSend(t, n, r) {
1030
+ if (this._state === "closed" || (await this._requireConnected("send"), this._state === "closed")) throw new e.ErrorInfo("unable to send; session is closed", C.SessionClosed, 400);
977
1031
  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({
1032
+ if (i !== "attached" && i !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${i}`, C.ChannelNotReady, 400);
1033
+ this._logger.trace("ClientSession._internalSend();");
1034
+ let a = n?.runId !== void 0, o = n?.runId, s;
1035
+ n?.parent === void 0 && !n?.forkOf && (s = r);
1036
+ let c = /* @__PURE__ */ new Set(), l = [];
1037
+ for (let e of t) {
1038
+ let t = crypto.randomUUID(), r = e.codecMessageId ?? crypto.randomUUID();
1039
+ c.add(r);
1040
+ 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 = le({
994
1041
  role: "user",
995
- turnId: o,
996
- msgId: n,
997
- turnClientId: this._clientId,
998
- parent: r,
999
- forkOf: t?.forkOf
1042
+ runId: o,
1043
+ codecMessageId: r,
1044
+ runClientId: this._clientId,
1045
+ ...a !== void 0 && { parent: a },
1046
+ ...u !== void 0 && { forkOf: u },
1047
+ ...d !== void 0 && { regenerates: d },
1048
+ inputEventId: t
1000
1049
  });
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);
1050
+ i || this._tree.applyMessage({
1051
+ inputs: [e],
1052
+ outputs: []
1053
+ }, f), l.push({
1054
+ input: e,
1055
+ codecMessageId: r,
1056
+ inputEventId: t,
1057
+ headers: f,
1058
+ isWireOnly: i
1059
+ }), !i && n?.parent === void 0 && !n?.forkOf && e.parent === void 0 && (s = r);
1010
1060
  }
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);
1061
+ let u = l.at(-1);
1062
+ if (u === void 0) throw new e.ErrorInfo("unable to send; inputs array is empty (include at least one input)", C.InvalidArgument, 400);
1063
+ let d = u.inputEventId, f = u.codecMessageId, p = new Promise((e, t) => {
1064
+ this._pendingRunStarts.set(f, {
1065
+ resolve: e,
1066
+ reject: t
1067
+ });
1068
+ });
1069
+ return p.catch(() => {}), await (async () => {
1070
+ try {
1071
+ for (let e of l) await this._encoder.publishInput(e.input, {
1072
+ extras: { headers: e.headers },
1073
+ messageId: e.codecMessageId,
1074
+ ...this._clientId !== void 0 && { clientId: this._clientId }
1075
+ });
1076
+ } catch (t) {
1077
+ let n = t instanceof e.ErrorInfo ? t : void 0, 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; ${t instanceof Error ? t.message : String(t)}`, r ? C.InsufficientCapability : C.SessionSendFailed, r ? 401 : 500, n);
1078
+ throw this._emitter.emit("error", i), this._pendingRunStarts.delete(f), a || this._cleanupFailedSend([...c]), i;
1038
1079
  }
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]
1080
+ })(), {
1081
+ inputCodecMessageId: f,
1082
+ runId: p,
1083
+ inputEventId: d,
1084
+ cancel: async () => {
1085
+ await this._publishCancel({
1086
+ inputCodecMessageId: f,
1087
+ ...o !== void 0 && { runId: o }
1088
+ });
1089
+ },
1090
+ optimisticCodecMessageIds: [...c],
1091
+ toInvocation: () => ue.fromJSON({
1092
+ inputEventId: d,
1093
+ sessionName: this._channel.name
1094
+ })
1047
1095
  };
1048
1096
  }
1049
1097
  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
- }
1098
+ return this._publishCancel({ runId: e });
1099
1099
  }
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);
1100
+ async _publishCancel(e) {
1101
+ if (this._state === "closed" || (await this._requireConnected("cancel"), this._state === "closed")) return;
1102
+ this._logger.debug("ClientSession._publishCancel();", {
1103
+ runId: e.runId,
1104
+ inputCodecMessageId: e.inputCodecMessageId
1105
+ });
1106
+ let t = { [p]: crypto.randomUUID() };
1107
+ e.runId !== void 0 && (t[d] = e.runId), e.inputCodecMessageId !== void 0 && (t[x] = e.inputCodecMessageId), await this._channel.publish({
1108
+ name: ee,
1109
+ extras: { ai: { transport: t } }
1113
1110
  });
1114
1111
  }
1115
1112
  on(e, t) {
1116
- if (this._state === G.CLOSED) return se;
1113
+ if (this._state === "closed") return me;
1117
1114
  let n = t;
1118
1115
  return this._emitter.on(e, n), () => {
1119
1116
  this._emitter.off(e, n);
1120
1117
  };
1121
1118
  }
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();
1119
+ async close() {
1120
+ if (this._state !== "closed") {
1121
+ this._state = "closed", this._logger.info("ClientSession.close();"), this._connectPromise && this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange), this._emitter.off();
1133
1122
  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();
1123
+ if (this._views.clear(), this._pendingRunStarts.size > 0) {
1124
+ let t = new e.ErrorInfo("unable to await run-start; session closed", C.SessionClosed, 400);
1125
+ for (let e of this._pendingRunStarts.values()) e.reject(t);
1126
+ this._pendingRunStarts.clear();
1127
+ }
1128
+ try {
1129
+ await this._encoder.close();
1130
+ } catch {}
1131
+ if (this._connectPromise) try {
1132
+ await this._channel.detach();
1133
+ } catch (e) {
1134
+ this._logger.debug("ClientSession.close(); channel detach failed", { error: e });
1135
+ }
1137
1136
  }
1138
1137
  }
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);
1138
+ }, ge = (e) => new he(e), G = n({
1139
+ nearest: void 0,
1140
+ providers: {}
1141
+ }), K = ({ children: n, ...r }) => {
1142
+ let c = t(), { channelName: u } = r, d = s(void 0), f = s(u), p = s([]), m = s(!1), h = s(void 0);
1143
+ if (!(d.current || h.current) || f.current !== u) {
1144
+ f.current = u, d.current && p.current.push(d.current);
1143
1145
  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);
1146
+ d.current = ge({
1147
+ ...r,
1148
+ client: c
1149
+ }), h.current = void 0;
1150
+ } catch (t) {
1151
+ d.current = void 0, h.current = t instanceof e.ErrorInfo ? t : new e.ErrorInfo("Unknown error while creating client session", C.BadRequest, 400);
1150
1152
  }
1151
1153
  }
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
1154
+ let g = i(G), _ = d.current, v = h.current, y = o(() => ({
1155
+ session: _,
1156
+ sessionError: v
1157
+ }), [_, v]), b = o(() => ({
1158
+ nearest: y,
1159
+ providers: {
1160
+ ...g.providers,
1161
+ [u]: y
1162
+ }
1158
1163
  }), [
1159
- e,
1160
- v,
1161
- x
1164
+ u,
1165
+ g,
1166
+ y
1162
1167
  ]);
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();
1168
+ return a(() => () => {
1169
+ for (let e of p.current) e.close();
1170
+ }, [u]), a(() => {
1171
+ d.current?.connect();
1172
+ }, [u]), a(() => (m.current = !1, () => {
1173
+ m.current = !0, Promise.resolve().then(() => {
1174
+ m.current && d.current?.close();
1168
1175
  });
1169
- }), []), /* @__PURE__ */ u(d.Provider, {
1170
- value: S,
1171
- children: /* @__PURE__ */ u(f.Provider, {
1172
- value: x,
1173
- children: t
1174
- })
1176
+ }), []), /* @__PURE__ */ l(G.Provider, {
1177
+ value: b,
1178
+ children: n
1175
1179
  });
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);
1185
- });
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
- });
1180
+ }, q = ({ session: e, skip: t } = {}) => {
1181
+ let { nearest: n } = i(G), r = n?.session;
1182
+ if (!t && e !== null) return e ?? r;
1183
+ }, J = ({ session: e, skip: t } = {}) => {
1184
+ let n = q({
1185
+ session: e,
1186
+ skip: t
1187
+ }), [r, i] = c([]), o = s([]);
1188
+ return a(() => {
1189
+ if (o.current = [], i([]), n) return n.tree.on("ably-message", (e) => {
1190
+ let t = [...o.current, e];
1191
+ o.current = t, i(t);
1205
1192
  });
1206
- }, [i]), a;
1193
+ }, [n]), r;
1207
1194
  }, Y = {
1208
1195
  get tree() {
1209
- throw new s.ErrorInfo("unable to access tree; hook is skipped", O.InvalidArgument, 400);
1196
+ throw new e.ErrorInfo("unable to access tree; hook is skipped", C.InvalidArgument, 400);
1210
1197
  },
1211
1198
  get view() {
1212
- throw new s.ErrorInfo("unable to access view; hook is skipped", O.InvalidArgument, 400);
1199
+ throw new e.ErrorInfo("unable to access view; hook is skipped", C.InvalidArgument, 400);
1200
+ },
1201
+ connect: () => {
1202
+ throw new e.ErrorInfo("unable to connect; hook is skipped", C.InvalidArgument, 400);
1213
1203
  },
1214
1204
  createView: () => {
1215
- throw new s.ErrorInfo("unable to create view; hook is skipped", O.InvalidArgument, 400);
1205
+ throw new e.ErrorInfo("unable to create view; hook is skipped", C.InvalidArgument, 400);
1216
1206
  },
1217
1207
  cancel: () => {
1218
- throw new s.ErrorInfo("unable to cancel; hook is skipped", O.InvalidArgument, 400);
1219
- },
1220
- stageEvents: () => {
1221
- throw new s.ErrorInfo("unable to stage events; hook is skipped", O.InvalidArgument, 400);
1222
- },
1223
- stageMessage: () => {
1224
- throw new s.ErrorInfo("unable to stage message; hook is skipped", O.InvalidArgument, 400);
1225
- },
1226
- waitForTurn: () => {
1227
- throw new s.ErrorInfo("unable to wait for turn; hook is skipped", O.InvalidArgument, 400);
1208
+ throw new e.ErrorInfo("unable to cancel; hook is skipped", C.InvalidArgument, 400);
1228
1209
  },
1229
1210
  on: () => {
1230
- throw new s.ErrorInfo("unable to subscribe; hook is skipped", O.InvalidArgument, 400);
1211
+ throw new e.ErrorInfo("unable to subscribe; hook is skipped", C.InvalidArgument, 400);
1231
1212
  },
1232
1213
  close: () => {
1233
- throw new s.ErrorInfo("unable to close; hook is skipped", O.InvalidArgument, 400);
1214
+ throw new e.ErrorInfo("unable to close; hook is skipped", C.InvalidArgument, 400);
1234
1215
  }
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(() => {
1216
+ }, X = ({ channelName: t, skip: n, onError: r } = {}) => {
1217
+ let { nearest: o, providers: c } = i(G), l = s(r);
1218
+ l.current = r;
1219
+ let u = n ? void 0 : t === void 0 ? o?.session : c[t]?.session;
1220
+ if (a(() => {
1240
1221
  if (u) return u.on("error", (e) => {
1241
1222
  l.current?.(e);
1242
1223
  });
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
1224
+ }, [u]), n) return { session: Y };
1225
+ if (t !== void 0) {
1226
+ let n = c[t];
1227
+ return n ? n.session ? { session: n.session } : {
1228
+ session: Y,
1229
+ sessionError: n.sessionError
1249
1230
  } : {
1250
- transport: Y,
1251
- transportError: new s.ErrorInfo(`unable to use transport; no TransportProvider found for channelName "${e}"`, O.BadRequest, 400)
1231
+ session: Y,
1232
+ sessionError: new e.ErrorInfo(`unable to use session; no ClientSessionProvider found for channelName "${t}"`, C.BadRequest, 400)
1252
1233
  };
1253
1234
  }
1254
- return c ? c.transport ? { transport: c.transport } : {
1255
- transport: Y,
1256
- transportError: c.error
1235
+ return o ? o.session ? { session: o.session } : {
1236
+ session: Y,
1237
+ sessionError: o.sessionError
1257
1238
  } : {
1258
- transport: Y,
1259
- transportError: new s.ErrorInfo("unable to use transport; no TransportProvider found in the tree", O.BadRequest, 400)
1239
+ session: Y,
1240
+ sessionError: new e.ErrorInfo("unable to use session; no ClientSessionProvider found in the tree", C.BadRequest, 400)
1260
1241
  };
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);
1242
+ }, _e = {
1243
+ hasSiblings: !1,
1244
+ siblings: [],
1245
+ index: 0,
1246
+ selected: void 0
1247
+ }, Z = ({ session: t, view: n, limit: i, skip: o } = {}) => {
1248
+ let l = q({
1249
+ session: t,
1250
+ skip: o
1251
+ }), u = o ? void 0 : n ?? l?.view, [d, f] = c(() => u?.getMessages() ?? []), [p, m] = c(() => u?.hasOlder() ?? !1), [h, g] = c(!1), [_, v] = c(), y = s(!1), b = i !== void 0, x = s(!1);
1252
+ a(() => {
1253
+ if (!u) {
1254
+ f([]), m(!1), v(void 0);
1266
1255
  return;
1267
1256
  }
1268
- return T.current = !1, g(m.flattenNodes()), v(m.hasOlder()), S(void 0), m.on("update", () => {
1269
- g(m.flattenNodes()), v(m.hasOlder());
1257
+ return x.current = !1, f(u.getMessages()), m(u.hasOlder()), v(void 0), u.on("update", () => {
1258
+ f(u.getMessages()), m(u.hasOlder());
1270
1259
  });
1271
- }, [m]);
1272
- let E = t(async () => {
1273
- if (!(!m || C.current)) {
1274
- C.current = !0, b(!0);
1260
+ }, [u]);
1261
+ let S = r(async () => {
1262
+ if (!(!u || y.current)) {
1263
+ y.current = !0, g(!0);
1275
1264
  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));
1265
+ await u.loadOlder(i), v(void 0);
1266
+ } catch (t) {
1267
+ t instanceof e.ErrorInfo ? v(t) : v(new e.ErrorInfo("Unknown error loading older messages", C.BadRequest, 400));
1279
1268
  } finally {
1280
- C.current = !1, b(!1);
1269
+ y.current = !1, g(!1);
1281
1270
  }
1282
1271
  }
1283
- }, [m, l]);
1284
- return r(() => {
1285
- !w || T.current || !m || (T.current = !0, E());
1272
+ }, [u, i]);
1273
+ return a(() => {
1274
+ !b || x.current || !u || (x.current = !0, S());
1286
1275
  }, [
1287
- w,
1288
- m,
1289
- E
1276
+ b,
1277
+ u,
1278
+ S
1290
1279
  ]), {
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])
1280
+ messages: d,
1281
+ hasOlder: p,
1282
+ loading: h,
1283
+ loadError: _,
1284
+ loadOlder: S,
1285
+ runOf: r((e) => u?.runOf(e), [u]),
1286
+ run: r((e) => u?.run(e), [u]),
1287
+ runs: r(() => u?.runs() ?? [], [u]),
1288
+ branchSelection: r((e) => u?.branchSelection(e) ?? _e, [u]),
1289
+ selectSibling: r((e, t) => {
1290
+ u?.selectSibling(e, t);
1291
+ }, [u]),
1292
+ send: r(async (t, n) => {
1293
+ if (!u) throw new e.ErrorInfo("unable to send; view is not available", C.InvalidArgument, 400);
1294
+ return u.send(t, n);
1295
+ }, [u]),
1296
+ regenerate: r(async (t, n) => {
1297
+ if (!u) throw new e.ErrorInfo("unable to regenerate; view is not available", C.InvalidArgument, 400);
1298
+ return u.regenerate(t, n);
1299
+ }, [u]),
1300
+ edit: r(async (t, n, r) => {
1301
+ if (!u) throw new e.ErrorInfo("unable to edit; view is not available", C.InvalidArgument, 400);
1302
+ return u.edit(t, n, r);
1303
+ }, [u])
1320
1304
  };
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);
1305
+ }, Q = ({ session: e, limit: t, skip: n } = {}) => {
1306
+ let r = q({
1307
+ session: e,
1308
+ skip: n
1309
+ }), [i, o] = c();
1310
+ return a(() => {
1311
+ if (!r) {
1312
+ o(void 0);
1326
1313
  return;
1327
1314
  }
1328
- let e = s.createView();
1329
- return l(e), () => {
1315
+ let e = r.createView();
1316
+ return o(e), () => {
1330
1317
  e.close();
1331
1318
  };
1332
- }, [s]), Z({
1333
- view: c,
1319
+ }, [r]), Z({
1320
+ view: i,
1334
1321
  limit: t,
1335
- skip: i
1322
+ skip: n
1336
1323
  });
1337
- }, $ = ({ transport: e } = {}) => {
1338
- let r = n(f), i = e ?? r?.transport;
1324
+ }, $ = ({ session: e } = {}) => {
1325
+ let t = q({ session: e });
1339
1326
  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])
1327
+ getRunNode: r((e) => t?.tree.getRunNode(e), [t]),
1328
+ getNodeByCodecMessageId: r((e) => t?.tree.getNodeByCodecMessageId(e), [t]),
1329
+ getSiblingNodes: r((e) => t?.tree.getSiblingNodes(e) ?? [], [t])
1343
1330
  };
1344
- }, de = () => ({
1345
- TransportProvider: K,
1346
- useClientTransport: (e) => X(e ?? {}),
1331
+ }, ve = () => ({
1332
+ ClientSessionProvider: K,
1333
+ useClientSession: (e) => X(e ?? {}),
1347
1334
  useView: (e) => Z(e ?? {}),
1348
- useActiveTurns: (e) => J(e ?? {}),
1349
1335
  useTree: (e) => $(e ?? {}),
1350
- useAblyMessages: (e) => q(e ?? {}),
1336
+ useAblyMessages: (e) => J(e ?? {}),
1351
1337
  useCreateView: (e) => Q(e ?? {})
1352
1338
  });
1353
1339
  //#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 };
1340
+ export { K as ClientSessionProvider, ve as createSessionHooks, J as useAblyMessages, X as useClientSession, Q as useCreateView, $ as useTree, Z as useView };
1355
1341
 
1356
1342
  //# sourceMappingURL=ably-ai-transport-react.js.map