@ably/ai-transport 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/README.md +93 -111
  2. package/dist/ably-ai-transport.js +2401 -1387
  3. package/dist/ably-ai-transport.js.map +1 -1
  4. package/dist/ably-ai-transport.umd.cjs +1 -1
  5. package/dist/ably-ai-transport.umd.cjs.map +1 -1
  6. package/dist/constants.d.ts +116 -42
  7. package/dist/core/agent.d.ts +44 -0
  8. package/dist/core/channel-options.d.ts +57 -0
  9. package/dist/core/codec/codec-event.d.ts +9 -0
  10. package/dist/core/codec/decoder.d.ts +24 -24
  11. package/dist/core/codec/define-codec.d.ts +100 -0
  12. package/dist/core/codec/encoder.d.ts +10 -12
  13. package/dist/core/codec/field-bag.d.ts +85 -0
  14. package/dist/core/codec/fields.d.ts +141 -0
  15. package/dist/core/codec/index.d.ts +8 -2
  16. package/dist/core/codec/input-descriptor-decoder.d.ts +19 -0
  17. package/dist/core/codec/input-descriptor-encoder.d.ts +22 -0
  18. package/dist/core/codec/input-descriptors.d.ts +281 -0
  19. package/dist/core/codec/lifecycle-tracker.d.ts +10 -9
  20. package/dist/core/codec/output-descriptor-decoder.d.ts +29 -0
  21. package/dist/core/codec/output-descriptor-encoder.d.ts +31 -0
  22. package/dist/core/codec/output-descriptors.d.ts +237 -0
  23. package/dist/core/codec/types.d.ts +470 -119
  24. package/dist/core/codec/well-known-inputs.d.ts +52 -0
  25. package/dist/core/transport/agent-session.d.ts +10 -0
  26. package/dist/core/transport/agent-view.d.ts +296 -0
  27. package/dist/core/transport/client-session.d.ts +13 -0
  28. package/dist/core/transport/decode-fold.d.ts +55 -0
  29. package/dist/core/transport/headers.d.ts +121 -14
  30. package/dist/core/transport/index.d.ts +5 -6
  31. package/dist/core/transport/internal/bounded-map.d.ts +20 -0
  32. package/dist/core/transport/invocation.d.ts +74 -0
  33. package/dist/core/transport/load-history-pages.d.ts +71 -0
  34. package/dist/core/transport/load-history.d.ts +44 -0
  35. package/dist/core/transport/pipe-stream.d.ts +9 -9
  36. package/dist/core/transport/run-manager.d.ts +76 -0
  37. package/dist/core/transport/session-support.d.ts +55 -0
  38. package/dist/core/transport/tree.d.ts +523 -109
  39. package/dist/core/transport/types/agent.d.ts +375 -0
  40. package/dist/core/transport/types/client.d.ts +201 -0
  41. package/dist/core/transport/types/shared.d.ts +24 -0
  42. package/dist/core/transport/types/tree.d.ts +357 -0
  43. package/dist/core/transport/types/view.d.ts +249 -0
  44. package/dist/core/transport/types.d.ts +13 -553
  45. package/dist/core/transport/view.d.ts +390 -84
  46. package/dist/core/transport/wire-log.d.ts +102 -0
  47. package/dist/errors.d.ts +27 -10
  48. package/dist/index.d.ts +8 -9
  49. package/dist/logger.d.ts +12 -0
  50. package/dist/react/ably-ai-transport-react.js +1365 -1010
  51. package/dist/react/ably-ai-transport-react.js.map +1 -1
  52. package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
  53. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
  54. package/dist/react/contexts/client-session-context.d.ts +37 -0
  55. package/dist/react/contexts/client-session-provider.d.ts +56 -0
  56. package/dist/react/create-session-hooks.d.ts +116 -0
  57. package/dist/react/index.d.ts +13 -12
  58. package/dist/react/internal/skipped-session.d.ts +8 -0
  59. package/dist/react/internal/use-resolved-session.d.ts +36 -0
  60. package/dist/react/use-ably-messages.d.ts +17 -14
  61. package/dist/react/use-client-session.d.ts +81 -0
  62. package/dist/react/use-create-view.d.ts +14 -13
  63. package/dist/react/use-tree.d.ts +30 -15
  64. package/dist/react/use-view.d.ts +81 -50
  65. package/dist/utils.d.ts +48 -71
  66. package/dist/vercel/ably-ai-transport-vercel.js +3257 -2499
  67. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
  68. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
  69. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
  70. package/dist/vercel/codec/decode-lifecycle.d.ts +9 -0
  71. package/dist/vercel/codec/events.d.ts +50 -0
  72. package/dist/vercel/codec/fields.d.ts +44 -0
  73. package/dist/vercel/codec/fold-content.d.ts +16 -0
  74. package/dist/vercel/codec/fold-data.d.ts +16 -0
  75. package/dist/vercel/codec/fold-input.d.ts +67 -0
  76. package/dist/vercel/codec/fold-lifecycle.d.ts +16 -0
  77. package/dist/vercel/codec/fold-text.d.ts +16 -0
  78. package/dist/vercel/codec/fold-tool-input.d.ts +17 -0
  79. package/dist/vercel/codec/fold-tool-output.d.ts +16 -0
  80. package/dist/vercel/codec/index.d.ts +7 -20
  81. package/dist/vercel/codec/inputs.d.ts +11 -0
  82. package/dist/vercel/codec/outputs.d.ts +11 -0
  83. package/dist/vercel/codec/reducer-state.d.ts +121 -0
  84. package/dist/vercel/codec/reducer.d.ts +62 -0
  85. package/dist/vercel/codec/tool-transitions.d.ts +2 -8
  86. package/dist/vercel/codec/wire-data.d.ts +34 -0
  87. package/dist/vercel/index.d.ts +5 -5
  88. package/dist/vercel/react/ably-ai-transport-vercel-react.js +2859 -9705
  89. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
  90. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +1 -45
  91. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
  92. package/dist/vercel/react/contexts/chat-transport-context.d.ts +9 -7
  93. package/dist/vercel/react/contexts/chat-transport-provider.d.ts +53 -41
  94. package/dist/vercel/react/index.d.ts +1 -2
  95. package/dist/vercel/react/use-chat-transport.d.ts +30 -26
  96. package/dist/vercel/react/use-message-sync.d.ts +17 -30
  97. package/dist/vercel/run-end-reason.d.ts +84 -0
  98. package/dist/vercel/tool-part.d.ts +21 -0
  99. package/dist/vercel/transport/chat-transport.d.ts +41 -24
  100. package/dist/vercel/transport/index.d.ts +24 -20
  101. package/dist/vercel/transport/run-output-stream.d.ts +54 -0
  102. package/dist/version.d.ts +2 -0
  103. package/package.json +31 -24
  104. package/src/constants.ts +124 -51
  105. package/src/core/agent.ts +92 -0
  106. package/src/core/channel-options.ts +89 -0
  107. package/src/core/codec/codec-event.ts +27 -0
  108. package/src/core/codec/decoder.ts +202 -105
  109. package/src/core/codec/define-codec.ts +432 -0
  110. package/src/core/codec/encoder.ts +114 -107
  111. package/src/core/codec/field-bag.ts +142 -0
  112. package/src/core/codec/fields.ts +193 -0
  113. package/src/core/codec/index.ts +56 -6
  114. package/src/core/codec/input-descriptor-decoder.ts +97 -0
  115. package/src/core/codec/input-descriptor-encoder.ts +150 -0
  116. package/src/core/codec/input-descriptors.ts +373 -0
  117. package/src/core/codec/lifecycle-tracker.ts +10 -9
  118. package/src/core/codec/output-descriptor-decoder.ts +139 -0
  119. package/src/core/codec/output-descriptor-encoder.ts +101 -0
  120. package/src/core/codec/output-descriptors.ts +307 -0
  121. package/src/core/codec/types.ts +505 -126
  122. package/src/core/codec/well-known-inputs.ts +96 -0
  123. package/src/core/transport/agent-session.ts +1085 -0
  124. package/src/core/transport/agent-view.ts +738 -0
  125. package/src/core/transport/client-session.ts +780 -0
  126. package/src/core/transport/decode-fold.ts +101 -0
  127. package/src/core/transport/headers.ts +234 -22
  128. package/src/core/transport/index.ts +27 -27
  129. package/src/core/transport/internal/bounded-map.ts +27 -0
  130. package/src/core/transport/invocation.ts +98 -0
  131. package/src/core/transport/load-history-pages.ts +220 -0
  132. package/src/core/transport/load-history.ts +271 -0
  133. package/src/core/transport/pipe-stream.ts +63 -39
  134. package/src/core/transport/run-manager.ts +243 -0
  135. package/src/core/transport/session-support.ts +96 -0
  136. package/src/core/transport/tree.ts +1293 -308
  137. package/src/core/transport/types/agent.ts +434 -0
  138. package/src/core/transport/types/client.ts +247 -0
  139. package/src/core/transport/types/shared.ts +27 -0
  140. package/src/core/transport/types/tree.ts +393 -0
  141. package/src/core/transport/types/view.ts +288 -0
  142. package/src/core/transport/types.ts +13 -706
  143. package/src/core/transport/view.ts +1229 -450
  144. package/src/core/transport/wire-log.ts +189 -0
  145. package/src/errors.ts +29 -9
  146. package/src/event-emitter.ts +3 -2
  147. package/src/index.ts +86 -42
  148. package/src/logger.ts +14 -1
  149. package/src/react/contexts/client-session-context.ts +41 -0
  150. package/src/react/contexts/client-session-provider.tsx +222 -0
  151. package/src/react/create-session-hooks.ts +141 -0
  152. package/src/react/index.ts +24 -13
  153. package/src/react/internal/skipped-session.ts +62 -0
  154. package/src/react/internal/use-resolved-session.ts +63 -0
  155. package/src/react/use-ably-messages.ts +32 -22
  156. package/src/react/use-client-session.ts +178 -0
  157. package/src/react/use-create-view.ts +33 -29
  158. package/src/react/use-tree.ts +61 -30
  159. package/src/react/use-view.ts +138 -96
  160. package/src/utils.ts +83 -131
  161. package/src/vercel/codec/decode-lifecycle.ts +70 -0
  162. package/src/vercel/codec/events.ts +85 -0
  163. package/src/vercel/codec/fields.ts +58 -0
  164. package/src/vercel/codec/fold-content.ts +54 -0
  165. package/src/vercel/codec/fold-data.ts +46 -0
  166. package/src/vercel/codec/fold-input.ts +255 -0
  167. package/src/vercel/codec/fold-lifecycle.ts +85 -0
  168. package/src/vercel/codec/fold-text.ts +55 -0
  169. package/src/vercel/codec/fold-tool-input.ts +86 -0
  170. package/src/vercel/codec/fold-tool-output.ts +79 -0
  171. package/src/vercel/codec/index.ts +28 -21
  172. package/src/vercel/codec/inputs.ts +116 -0
  173. package/src/vercel/codec/outputs.ts +207 -0
  174. package/src/vercel/codec/reducer-state.ts +169 -0
  175. package/src/vercel/codec/reducer.ts +191 -0
  176. package/src/vercel/codec/tool-transitions.ts +3 -14
  177. package/src/vercel/codec/wire-data.ts +64 -0
  178. package/src/vercel/index.ts +7 -19
  179. package/src/vercel/react/contexts/chat-transport-context.ts +8 -7
  180. package/src/vercel/react/contexts/chat-transport-provider.tsx +87 -59
  181. package/src/vercel/react/index.ts +3 -5
  182. package/src/vercel/react/use-chat-transport.ts +44 -66
  183. package/src/vercel/react/use-message-sync.ts +75 -39
  184. package/src/vercel/run-end-reason.ts +157 -0
  185. package/src/vercel/tool-part.ts +25 -0
  186. package/src/vercel/transport/chat-transport.ts +380 -98
  187. package/src/vercel/transport/index.ts +38 -37
  188. package/src/vercel/transport/run-output-stream.ts +169 -0
  189. package/src/version.ts +2 -0
  190. package/dist/core/transport/client-transport.d.ts +0 -10
  191. package/dist/core/transport/decode-history.d.ts +0 -43
  192. package/dist/core/transport/server-transport.d.ts +0 -7
  193. package/dist/core/transport/stream-router.d.ts +0 -29
  194. package/dist/core/transport/turn-manager.d.ts +0 -37
  195. package/dist/react/contexts/transport-context.d.ts +0 -31
  196. package/dist/react/contexts/transport-provider.d.ts +0 -49
  197. package/dist/react/create-transport-hooks.d.ts +0 -124
  198. package/dist/react/use-active-turns.d.ts +0 -12
  199. package/dist/react/use-client-transport.d.ts +0 -80
  200. package/dist/vercel/codec/accumulator.d.ts +0 -21
  201. package/dist/vercel/codec/decoder.d.ts +0 -22
  202. package/dist/vercel/codec/encoder.d.ts +0 -41
  203. package/dist/vercel/react/use-staged-add-tool-approval-response.d.ts +0 -30
  204. package/dist/vercel/tool-approvals.d.ts +0 -124
  205. package/dist/vercel/tool-events.d.ts +0 -26
  206. package/src/core/transport/client-transport.ts +0 -977
  207. package/src/core/transport/decode-history.ts +0 -485
  208. package/src/core/transport/server-transport.ts +0 -612
  209. package/src/core/transport/stream-router.ts +0 -136
  210. package/src/core/transport/turn-manager.ts +0 -165
  211. package/src/react/contexts/transport-context.ts +0 -37
  212. package/src/react/contexts/transport-provider.tsx +0 -164
  213. package/src/react/create-transport-hooks.ts +0 -144
  214. package/src/react/use-active-turns.ts +0 -72
  215. package/src/react/use-client-transport.ts +0 -197
  216. package/src/vercel/codec/accumulator.ts +0 -588
  217. package/src/vercel/codec/decoder.ts +0 -618
  218. package/src/vercel/codec/encoder.ts +0 -410
  219. package/src/vercel/react/use-staged-add-tool-approval-response.ts +0 -87
  220. package/src/vercel/tool-approvals.ts +0 -380
  221. package/src/vercel/tool-events.ts +0 -53
@@ -1,585 +1,799 @@
1
1
  import * as e from "ably";
2
- //#region src/constants.ts
3
- var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-ably-discrete", a = "x-ably-turn-id", o = "x-ably-msg-id", s = "x-ably-turn-client-id", c = "x-ably-role", l = "x-ably-amend", u = "x-ably-cancel-turn-id", d = "x-ably-cancel-own", f = "x-ably-cancel-all", p = "x-ably-cancel-client-id", m = "x-ably-parent", h = "x-ably-fork-of", g = "x-ably-turn-reason", _ = "x-ably-cancel", v = "x-ably-turn-start", y = "x-ably-turn-end", b = "x-ably-abort", x = "x-ably-error", S = "x-domain-", C = /* @__PURE__ */ function(e) {
4
- 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;
5
- }({}), ee = (e, t) => e.code === t, w = (e) => {
6
- let t = e.extras;
7
- if (!t || typeof t != "object") return {};
8
- let n = t.headers;
9
- return !n || typeof n != "object" ? {} : n;
10
- }, T = (e) => {
2
+ //#region src/core/transport/invocation.ts
3
+ var t = class e {
4
+ constructor(e) {
5
+ this.inputEventId = e.inputEventId, this.sessionName = e.sessionName;
6
+ }
7
+ static fromJSON(t) {
8
+ return new e(t);
9
+ }
10
+ toJSON() {
11
+ return {
12
+ inputEventId: this.inputEventId,
13
+ sessionName: this.sessionName
14
+ };
15
+ }
16
+ }, n = "stream", r = "status", i = "stream-id", a = "discrete", o = "run-id", s = "invocation-id", c = "event-id", l = "codec-message-id", u = "run-client-id", d = "input-client-id", f = "role", p = "parent", m = "fork-of", h = "msg-regenerate", g = "run-reason", _ = "input-codec-message-id", v = "error-code", y = "error-message", b = "ai-cancel", x = "ai-run-start", S = "ai-run-suspend", C = "ai-run-resume", w = "ai-run-end", ee = "ai-output", T = "ai-input", E = /* @__PURE__ */ function(e) {
17
+ return e[e.BadRequest = 4e4] = "BadRequest", e[e.InvalidArgument = 40003] = "InvalidArgument", e[e.InsufficientCapability = 40160] = "InsufficientCapability", e[e.EncoderRecoveryFailed = 104e3] = "EncoderRecoveryFailed", e[e.SessionSubscriptionError = 104001] = "SessionSubscriptionError", e[e.CancelListenerError = 104002] = "CancelListenerError", e[e.RunLifecycleError = 104003] = "RunLifecycleError", e[e.SessionClosed = 104004] = "SessionClosed", e[e.SessionSendFailed = 104005] = "SessionSendFailed", e[e.ChannelContinuityLost = 104006] = "ChannelContinuityLost", e[e.ChannelNotReady = 104007] = "ChannelNotReady", e[e.StreamError = 104008] = "StreamError", e[e.InputEventNotFound = 104010] = "InputEventNotFound", e[e.HistoryFetchFailed = 104011] = "HistoryFetchFailed", e;
18
+ }({}), te = (e, t) => e.code === t, D = /* @__PURE__ */ function(e) {
19
+ return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
20
+ }({}), O = (e, t, n) => {
21
+ let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
22
+ switch (t) {
23
+ case "trace":
24
+ case "debug":
25
+ console.log(i);
26
+ break;
27
+ case "info":
28
+ console.info(i);
29
+ break;
30
+ case "warn":
31
+ console.warn(i);
32
+ break;
33
+ case "error":
34
+ console.error(i);
35
+ break;
36
+ case "silent": break;
37
+ }
38
+ }, k = (e) => new A(e.logHandler ?? O, e.logLevel), ne = new Map([
39
+ ["trace", 0],
40
+ ["debug", 1],
41
+ ["info", 2],
42
+ ["warn", 3],
43
+ ["error", 4],
44
+ ["silent", 5]
45
+ ]), A = class t {
46
+ constructor(t, n, r) {
47
+ this._handler = t, this._context = r;
48
+ let i = ne.get(n);
49
+ if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, E.InvalidArgument, 400);
50
+ this._levelNumber = i;
51
+ }
52
+ trace(e, t) {
53
+ this._write(e, "trace", 0, t);
54
+ }
55
+ debug(e, t) {
56
+ this._write(e, "debug", 1, t);
57
+ }
58
+ info(e, t) {
59
+ this._write(e, "info", 2, t);
60
+ }
61
+ warn(e, t) {
62
+ this._write(e, "warn", 3, t);
63
+ }
64
+ error(e, t) {
65
+ this._write(e, "error", 4, t);
66
+ }
67
+ withContext(e) {
68
+ let n = [...ne.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? "error";
69
+ return new t(this._handler, n, this._mergeContext(e));
70
+ }
71
+ _write(e, t, n, r) {
72
+ n >= this._levelNumber && this._handler(e, t, this._mergeContext(r));
73
+ }
74
+ _mergeContext(e) {
75
+ return this._context ? e ? {
76
+ ...this._context,
77
+ ...e
78
+ } : this._context : e ?? void 0;
79
+ }
80
+ }, j = (e) => e instanceof Error ? e.message : String(e), M = (t) => t instanceof e.ErrorInfo ? t : void 0, N = (e, t) => {
81
+ let n = e.extras;
82
+ if (!n || typeof n != "object") return {};
83
+ let r = n.ai;
84
+ if (!r || typeof r != "object") return {};
85
+ let i = r[t];
86
+ return !i || typeof i != "object" ? {} : i;
87
+ }, P = (e) => N(e, "transport"), F = (e) => N(e, "codec"), I = (e) => {
11
88
  if (e !== void 0) try {
12
89
  return JSON.parse(e);
13
90
  } catch {
14
91
  return;
15
92
  }
16
- }, E = (e, t) => ({
93
+ }, L = (e, t) => ({
17
94
  ...e,
18
95
  ...t
19
- }), te = (e) => {
96
+ }), R = (e) => {
20
97
  if (e !== void 0) return e === "true";
21
- }, D = (e, t) => e[S + t], O = (e) => {
98
+ }, z = (e, t) => e.serial === void 0 && t.serial === void 0 ? 0 : e.serial === void 0 ? 1 : t.serial === void 0 || e.serial < t.serial ? -1 : +(e.serial > t.serial), B = (e) => {
22
99
  let t = {};
23
100
  for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && e[n] !== void 0 && (t[n] = e[n]);
24
101
  return t;
25
- }, k = (e) => ({
26
- str: (t) => D(e, t),
27
- strOr: (t, n) => D(e, t) ?? n,
28
- bool: (t) => te(D(e, t)),
29
- json: (t) => T(D(e, t))
30
- }), A = () => {
31
- let e = {}, t = {
32
- str: (n, r) => (r !== void 0 && (e[S + n] = r), t),
33
- bool: (n, r) => (r !== void 0 && (e[S + n] = String(r)), t),
34
- json: (n, r) => (r != null && (e[S + n] = JSON.stringify(r)), t),
35
- build: () => e
102
+ }, V = "0.3.0", re = "ai-transport-js", H = (e, t) => {
103
+ let n = e;
104
+ return n.options.agents = {
105
+ ...n.options.agents,
106
+ ...t
107
+ }, { params: { agent: W(t) } };
108
+ }, U = (e) => {
109
+ let t = e?.adapterTag, n = { [re]: V };
110
+ return t && (n[t] = V), n;
111
+ }, W = (e) => Object.entries(e).map(([e, t]) => `${e}/${t}`).join(" "), G = (e, t) => H(e, U(t)), ie = [
112
+ "PUBLISH",
113
+ "SUBSCRIBE",
114
+ "PRESENCE",
115
+ "PRESENCE_SUBSCRIBE",
116
+ "ANNOTATION_PUBLISH"
117
+ ], ae = ["OBJECT_SUBSCRIBE", "OBJECT_PUBLISH"], oe = [
118
+ "PUBLISH",
119
+ "SUBSCRIBE",
120
+ "PRESENCE",
121
+ "PRESENCE_SUBSCRIBE",
122
+ "OBJECT_PUBLISH",
123
+ "OBJECT_SUBSCRIBE",
124
+ "ANNOTATION_PUBLISH",
125
+ "ANNOTATION_SUBSCRIBE"
126
+ ], se = (e) => {
127
+ if (e === void 0 || e.length === 0) return;
128
+ let t = new Set([...ie, ...e]), n = oe.filter((e) => t.has(e)), r = [...t].filter((e) => !oe.includes(e)).toSorted();
129
+ return [...n, ...r];
130
+ }, ce = (t, n) => new Promise((r, i) => {
131
+ if (n?.aborted) {
132
+ i(new e.ErrorInfo("unable to wait; signal aborted", E.InvalidArgument, 400));
133
+ return;
134
+ }
135
+ let a = setTimeout(() => {
136
+ n?.removeEventListener("abort", o), r();
137
+ }, t);
138
+ typeof a == "object" && a.unref();
139
+ let o = () => {
140
+ clearTimeout(a), i(new e.ErrorInfo("unable to wait; signal aborted", E.InvalidArgument, 400));
36
141
  };
37
- return t;
38
- }, j = (e) => {
142
+ n?.addEventListener("abort", o, { once: !0 });
143
+ }), le = async (t, n, r, i, a) => {
144
+ let o;
145
+ for (let s = 0; s <= n; s++) {
146
+ if (i?.aborted) throw new e.ErrorInfo("unable to fetch history page; signal aborted", E.InvalidArgument, 400, M(o));
147
+ try {
148
+ return await t();
149
+ } catch (e) {
150
+ if (o = e, s === n) break;
151
+ let t = r * 2 ** s;
152
+ a?.debug("loadHistoryPages.fetchPageWithRetry(); page fetch failed, retrying", {
153
+ attempt: s + 1,
154
+ maxRetries: n,
155
+ backoff: t
156
+ }), await ce(t, i);
157
+ }
158
+ }
159
+ throw new e.ErrorInfo(`unable to fetch history page; ${j(o)}`, E.HistoryFetchFailed, 500, M(o));
160
+ }, ue = async (t, n) => {
161
+ let { pageLimit: r, untilAttach: i = !0, signal: a, maxRetries: o = 3, retryBackoffMs: s = 100, logger: c } = n;
162
+ if (a?.aborted) throw new e.ErrorInfo("unable to load history; signal aborted", E.InvalidArgument, 400);
163
+ await t.attach();
164
+ let l = {
165
+ limit: r,
166
+ untilAttach: i
167
+ }, u = await le(() => t.history(l), o, s, a, c), d = !1;
168
+ return {
169
+ hasNext: () => u === void 0 || a?.aborted ? !1 : d ? u.hasNext() : !0,
170
+ next: async () => {
171
+ if (u === void 0) return;
172
+ if (a?.aborted) throw new e.ErrorInfo("unable to load history; signal aborted", E.InvalidArgument, 400);
173
+ if (!d) return d = !0, u.items;
174
+ if (!u.hasNext()) {
175
+ u = void 0;
176
+ return;
177
+ }
178
+ let t = await le(async () => await u?.next() ?? void 0, o, s, a, c);
179
+ if (!t) {
180
+ u = void 0;
181
+ return;
182
+ }
183
+ return u = t, t.items;
184
+ }
185
+ };
186
+ }, de = (e, t, n, r) => {
187
+ if (t === void 0) return [];
188
+ let i = [], a = e.getNodeByCodecMessageId(t), o = /* @__PURE__ */ new Set(), s = 0;
189
+ for (; a !== void 0;) {
190
+ let t = a.kind === "run" ? a.runId : a.codecMessageId;
191
+ if (o.has(t)) break;
192
+ if (a.kind === "run" && a.runId !== r) {
193
+ if (n !== void 0 && s >= n) break;
194
+ s += 1;
195
+ }
196
+ o.add(t), i.unshift(a);
197
+ let c = a.parentCodecMessageId;
198
+ if (c === void 0) break;
199
+ a = e.getNodeByCodecMessageId(c);
200
+ }
201
+ return i;
202
+ }, fe = (e, t) => {
203
+ let n = 0;
204
+ for (let r of e) r.kind === "run" && r.runId !== t && n++;
205
+ return n;
206
+ }, pe = (t, n) => {
207
+ let r = M(n);
208
+ return new e.ErrorInfo(`unable to ${t}; ${j(n)}`, r?.code ?? E.HistoryFetchFailed, r?.statusCode ?? 500, r);
209
+ }, me = class {
210
+ constructor(e) {
211
+ this._historyExhausted = !1, this._tree = e.tree, this._channel = e.channel, this._codec = e.codec, this._applier = e.applier, this._inputEventLookbackMs = e.inputEventLookbackMs, this._logger = e.logger?.withContext({ component: "AgentView" });
212
+ }
213
+ _foldWire(e) {
214
+ this._applier.apply(e), this._tree.emitAblyMessage(e);
215
+ }
216
+ findInputEvent(t) {
217
+ let { invocationId: n, runId: r, expectedEventIds: i, timeoutMs: a, signal: o } = t, s = this._logger, l = new Set(i), u = l.size, d = /* @__PURE__ */ new Map(), f = new AbortController();
218
+ return new Promise((t, p) => {
219
+ let m = !1, h, g, _, v = () => {
220
+ g && g(), _ !== void 0 && clearTimeout(_), f.abort(), o.removeEventListener("abort", y);
221
+ }, y = () => {
222
+ m || (m = !0, v(), p(new e.ErrorInfo(`unable to look up input event; run ${r} was cancelled`, E.InvalidArgument, 400)));
223
+ }, b = () => {
224
+ if (m) return;
225
+ m = !0, v();
226
+ let e = [...d.values()].toSorted(z), i, a;
227
+ for (let t of e) if (i === void 0) {
228
+ i = P(t), a = t.clientId;
229
+ break;
230
+ }
231
+ s?.debug("AgentView.findInputEvent(); collected input events", {
232
+ runId: r,
233
+ invocationId: n,
234
+ count: e.length
235
+ }), t({
236
+ rawMessages: e,
237
+ firstHeaders: i,
238
+ firstClientId: a
239
+ });
240
+ }, x = (e) => {
241
+ if (m) return !1;
242
+ let t = P(e)[c];
243
+ return !t || !l.has(t) || d.has(t) ? !1 : (d.set(t, e), d.size >= u);
244
+ };
245
+ if (o.addEventListener("abort", y, { once: !0 }), o.aborted) {
246
+ y();
247
+ return;
248
+ }
249
+ for (let e of i) {
250
+ let t = this._tree.findAblyMessageByEventId(e);
251
+ if (t && x(t) && !m) {
252
+ b();
253
+ return;
254
+ }
255
+ }
256
+ g = this._tree.on("ably-message", (e) => {
257
+ x(e) && !m && b();
258
+ }), this._driveHistoryChain(() => m, f.signal, this._inputEventLookbackMs, "scan history for input event").catch((t) => {
259
+ m || (h = t instanceof e.ErrorInfo ? t : pe("scan history for input event", t), s?.warn("AgentView.findInputEvent(); history scan failed (continuing on live path)", { error: j(t) }));
260
+ }), _ = setTimeout(() => {
261
+ m || (m = !0, v(), p(new e.ErrorInfo(`unable to look up input event; received ${String(d.size)} of ${String(u)} input events for invocation ${n} within ${String(a)}ms`, E.InputEventNotFound, 504, h)));
262
+ }, a), typeof _ == "object" && _.unref();
263
+ });
264
+ }
265
+ async loadConversation(t, n, r, i, a, o) {
266
+ if (r.aborted) throw new e.ErrorInfo(`unable to load conversation; run ${t} was cancelled`, E.InvalidArgument, 400);
267
+ return await this._hydrateAncestors(t, n, r, i, a), this._collectConversation(t, n, i, o);
268
+ }
269
+ _collectConversation(e, t, n, r) {
270
+ let i = this._tree, a = de(i, t, n, e), o = i.getRunNode(e), s = [];
271
+ for (let e of a) for (let t of this._codec.getMessages(e.projection)) {
272
+ if (r !== void 0 && t.codecMessageId === r) return {
273
+ messages: s,
274
+ projection: o?.projection ?? this._codec.init()
275
+ };
276
+ s.push(t.message);
277
+ }
278
+ if (o !== void 0 && !a.some((t) => t.kind === "run" && t.runId === e)) for (let e of this._codec.getMessages(o.projection)) s.push(e.message);
279
+ return {
280
+ messages: s,
281
+ projection: o?.projection ?? this._codec.init()
282
+ };
283
+ }
284
+ messages(e, t, n) {
285
+ return this._collectConversation(e, t, void 0, n).messages;
286
+ }
287
+ async _driveHistoryChain(e, t, n, r) {
288
+ let i = !1, a, o = this._hydrationMutex ?? Promise.resolve(), s = (async () => {
289
+ if (await o.catch(() => {}), !(this._historyExhausted || t.aborted || e())) try {
290
+ i = await this._walkSharedHistory(e, t, n);
291
+ } catch (e) {
292
+ a = pe(r, e);
293
+ }
294
+ })();
295
+ if (this._hydrationMutex = s, await s, a !== void 0) throw a;
296
+ return { exhausted: i };
297
+ }
298
+ async _walkSharedHistory(e, t, n) {
299
+ this._cursor === void 0 && (this._cursor = await ue(this._channel, {
300
+ pageLimit: 200,
301
+ untilAttach: !0,
302
+ logger: this._logger
303
+ }));
304
+ let r = this._cursor;
305
+ for (; r.hasNext() && !e();) {
306
+ if (t.aborted) return !1;
307
+ let e = await r.next();
308
+ if (!e) break;
309
+ for (let t of e.toReversed()) this._foldWire(t);
310
+ if (n !== void 0) {
311
+ let t = e.at(-1);
312
+ if (t?.timestamp !== void 0 && t.timestamp < Date.now() - n) break;
313
+ }
314
+ }
315
+ return !r.hasNext() && !t.aborted;
316
+ }
317
+ async _hydrateAncestors(t, n, r, i, a) {
318
+ let o = () => {
319
+ let e = this._tree;
320
+ if (a && e.getRunNode(t)?.startSerial === void 0) return !0;
321
+ if (n === void 0) return !1;
322
+ if (e.getNodeByCodecMessageId(n) === void 0) return !0;
323
+ let r = de(e, n, i, t), o = r[0], s = o !== void 0 && o.parentCodecMessageId === void 0, c = i !== void 0 && fe(r, t) >= i && o !== void 0 && (o.kind !== "run" || o.runId === t);
324
+ return !s && !c;
325
+ };
326
+ if (!o() || this._historyExhausted) return;
327
+ let s;
328
+ try {
329
+ ({exhausted: s} = await this._driveHistoryChain(() => !o(), r, void 0, "hydrate ancestors"));
330
+ } catch (e) {
331
+ throw this._logger?.error("AgentView._hydrateAncestors(); history fetch failed", {
332
+ runId: t,
333
+ error: j(e)
334
+ }), e;
335
+ }
336
+ if (s && (this._historyExhausted = !0), r.aborted && o()) throw new e.ErrorInfo("unable to hydrate ancestors; signal aborted", E.InvalidArgument, 400);
337
+ }
338
+ }, he = (e) => new me(e), ge = (e) => {
39
339
  let t = {
40
- [c]: e.role,
41
- [a]: e.turnId,
42
- [o]: e.msgId
340
+ [f]: e.role,
341
+ [l]: e.codecMessageId
43
342
  };
44
- return e.turnClientId !== void 0 && (t[s] = e.turnClientId), e.parent && (t[m] = e.parent), e.forkOf && (t[h] = e.forkOf), e.amend && (t[l] = e.amend), t;
45
- }, M = async (e, t, n, r, i, a) => {
46
- a?.trace("pipeStream();");
47
- let o = e.getReader(), s, c = n ? new Promise((e) => {
48
- if (n.aborted) {
49
- e();
50
- return;
343
+ return e.runId !== void 0 && (t[o] = e.runId), e.runClientId !== void 0 && (t[u] = e.runClientId), e.parent && (t[p] = e.parent), e.forkOf && (t[m] = e.forkOf), e.regenerates && (t[h] = e.regenerates), e.invocationId && (t[s] = e.invocationId), e.inputClientId !== void 0 && (t[d] = e.inputClientId), e.inputCodecMessageId !== void 0 && (t[_] = e.inputCodecMessageId), e.inputEventId && (t[c] = e.inputEventId), t;
344
+ }, _e = (e) => {
345
+ let t = {
346
+ [o]: e.runId,
347
+ [u]: e.runClientId
348
+ };
349
+ return e.reason !== void 0 && (t[g] = e.reason), e.parent !== void 0 && (t[p] = e.parent), e.forkOf !== void 0 && (t[m] = e.forkOf), e.regenerates !== void 0 && (t[h] = e.regenerates), e.invocationId !== void 0 && (t[s] = e.invocationId), e.inputClientId !== void 0 && (t[d] = e.inputClientId), e.inputCodecMessageId !== void 0 && (t[_] = e.inputCodecMessageId), e.errorCode !== void 0 && (t[v] = String(e.errorCode)), e.errorMessage !== void 0 && (t[y] = e.errorMessage), t;
350
+ }, ve = (e) => e === "ai-run-start" || e === "ai-run-suspend" || e === "ai-run-resume" || e === "ai-run-end", ye = (t) => {
351
+ let n = t[v], r = n === void 0 ? NaN : Number(n), i = Number.isFinite(r) ? r : E.SessionSubscriptionError, a = t["error-message"] ?? "agent reported an error", o = i >= 1e4 && i < 6e4 ? Math.floor(i / 100) : 500;
352
+ return new e.ErrorInfo(a, i, o);
353
+ }, be = (e, t, n, r) => {
354
+ let i = t[o];
355
+ if (!i) return;
356
+ let a = t["run-client-id"] ?? "", s = r === void 0 ? {} : { timestamp: r };
357
+ if (e === "ai-run-start") {
358
+ let e = t[p], r = t[m], o = t[h];
359
+ return {
360
+ type: "start",
361
+ runId: i,
362
+ clientId: a,
363
+ serial: n,
364
+ invocationId: t["invocation-id"] ?? "",
365
+ ...s,
366
+ ...e !== void 0 && { parent: e },
367
+ ...r !== void 0 && { forkOf: r },
368
+ ...o !== void 0 && { regenerates: o }
369
+ };
370
+ }
371
+ if (e === "ai-run-suspend") return {
372
+ type: "suspend",
373
+ runId: i,
374
+ clientId: a,
375
+ serial: n,
376
+ invocationId: t["invocation-id"] ?? "",
377
+ ...s
378
+ };
379
+ if (e === "ai-run-resume") return {
380
+ type: "resume",
381
+ runId: i,
382
+ clientId: a,
383
+ serial: n,
384
+ invocationId: t["invocation-id"] ?? "",
385
+ ...s
386
+ };
387
+ if (e === "ai-run-end") {
388
+ let e = t["run-reason"] ?? "complete", r = t["invocation-id"] ?? "";
389
+ return e === "error" ? {
390
+ type: "end",
391
+ runId: i,
392
+ clientId: a,
393
+ serial: n,
394
+ invocationId: r,
395
+ reason: e,
396
+ ...s,
397
+ error: ye(t)
398
+ } : {
399
+ type: "end",
400
+ runId: i,
401
+ clientId: a,
402
+ serial: n,
403
+ invocationId: r,
404
+ reason: e,
405
+ ...s
406
+ };
407
+ }
408
+ }, xe = (e, t, n) => {
409
+ let r = P(n), i = n.serial, a = n.timestamp;
410
+ if (ve(n.name)) {
411
+ let t = be(n.name, r, i, a);
412
+ return t && e.applyRunLifecycle(t), t;
413
+ }
414
+ let { inputs: o, outputs: s } = t.decode(n);
415
+ (o.length > 0 || s.length > 0 || r["run-id"]) && e.applyMessage({
416
+ inputs: o,
417
+ outputs: s
418
+ }, r, i, a, n.version.serial);
419
+ }, Se = (e, t) => ({ apply: (n) => xe(e, t, n) }), Ce = (e, t, n) => {
420
+ if (e.has(t) || e.size < n) return;
421
+ let r = e.keys().next().value;
422
+ if (r !== void 0) return e.delete(r), r;
423
+ }, we = (e) => {
424
+ let t;
425
+ return {
426
+ promise: e === void 0 ? new Promise(() => {}) : e.aborted ? Promise.resolve() : new Promise((n) => {
427
+ t = () => {
428
+ n();
429
+ }, e.addEventListener("abort", t, { once: !0 });
430
+ }),
431
+ cleanup: () => {
432
+ t && e && e.removeEventListener("abort", t);
51
433
  }
52
- s = () => {
53
- e();
54
- }, n.addEventListener("abort", s, { once: !0 });
55
- }) : new Promise(() => {}), l = "complete", u;
434
+ };
435
+ }, Te = async (e, t, n, r, i, a) => {
436
+ a?.trace("pipeStream();");
437
+ let o = e.getReader(), s = we(n), c = "complete", l;
56
438
  try {
57
439
  for (;;) {
58
- let e = await Promise.race([o.read(), c.then(() => "aborted")]);
59
- if (e === "aborted") {
60
- l = "cancelled", a?.debug("pipeStream(); stream cancelled by abort signal"), r && await r(async (e) => t.appendEvent(e)), await t.abort("cancelled");
440
+ let e = await Promise.race([o.read(), s.promise.then(() => "cancelled")]);
441
+ if (e === "cancelled") {
442
+ c = "cancelled", a?.debug("pipeStream(); stream cancelled by AbortSignal"), r && await r(async (e) => t.publishOutput(e)), await t.cancelStreams();
61
443
  break;
62
444
  }
63
- let { done: n, value: s } = e;
445
+ let { done: n, value: l } = e;
64
446
  if (n) {
65
- await t.close(), a?.debug("pipeStream(); stream completed");
447
+ await t.cancelStreams(), await t.close(), a?.debug("pipeStream(); stream completed");
66
448
  break;
67
449
  }
68
- await t.appendEvent(s, i?.(s));
450
+ await t.publishOutput(l, i?.(l));
69
451
  }
70
452
  } catch (e) {
71
- l = "error", u = e instanceof Error ? e : Error(String(e)), a?.error("pipeStream(); stream error", { error: u.message });
453
+ c = "error", l = e instanceof Error ? e : Error(String(e)), a?.error("pipeStream(); stream error", { error: l.message });
72
454
  try {
73
455
  await t.close();
74
456
  } catch {}
75
457
  } finally {
76
- s && n?.removeEventListener("abort", s), o.releaseLock();
458
+ s.cleanup(), o.releaseLock();
77
459
  }
78
460
  return {
79
- reason: l,
80
- error: u
461
+ reason: c,
462
+ error: l
81
463
  };
82
- }, ne = class {
464
+ }, Ee = class {
83
465
  constructor(e, t) {
84
- this._activeTurns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "TurnManager" });
466
+ this._activeRuns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "RunManager" });
85
467
  }
86
- async startTurn(e, t, n, r) {
87
- this._logger?.trace("DefaultTurnManager.startTurn();", {
88
- turnId: e,
468
+ async startRun(e, t, n, r) {
469
+ this._logger?.trace("DefaultRunManager.startRun();", {
470
+ runId: e,
89
471
  clientId: t
90
472
  });
91
- let i = n ?? new AbortController(), o = t ?? "";
92
- this._activeTurns.set(e, {
473
+ let i = n ?? new AbortController(), a = t ?? "";
474
+ this._activeRuns.set(e, {
93
475
  controller: i,
94
- clientId: o
476
+ clientId: a
95
477
  });
96
- let c = {
97
- [a]: e,
98
- [s]: o
99
- };
100
- return r?.parent !== void 0 && (c[m] = r.parent), r?.forkOf !== void 0 && (c[h] = r.forkOf), await this._channel.publish({
101
- name: v,
102
- extras: { headers: c }
103
- }), this._logger?.debug("DefaultTurnManager.startTurn(); turn started", { turnId: e }), i.signal;
104
- }
105
- async endTurn(e, t) {
106
- this._logger?.trace("DefaultTurnManager.endTurn();", {
107
- turnId: e,
108
- reason: t
478
+ let o = r?.continuation === !0, s = _e({
479
+ runId: e,
480
+ runClientId: a,
481
+ parent: o ? void 0 : r?.parent,
482
+ forkOf: o ? void 0 : r?.forkOf,
483
+ regenerates: o ? void 0 : r?.regenerates,
484
+ invocationId: r?.invocationId,
485
+ inputClientId: r?.inputClientId,
486
+ inputCodecMessageId: r?.inputCodecMessageId
109
487
  });
110
- let n = this._activeTurns.get(e)?.clientId ?? "";
111
488
  await this._channel.publish({
112
- name: y,
113
- extras: { headers: {
114
- [a]: e,
115
- [s]: n,
116
- [g]: t
117
- } }
118
- }), this._activeTurns.delete(e), this._logger?.debug("DefaultTurnManager.endTurn(); turn ended", {
119
- turnId: e,
489
+ name: o ? C : x,
490
+ extras: { ai: { transport: s } }
491
+ }), this._logger?.debug("DefaultRunManager.startRun(); run started", { runId: e });
492
+ }
493
+ async suspendRun(e, t, n, r) {
494
+ this._logger?.trace("DefaultRunManager.suspendRun();", { runId: e }), await this._publishTerminal(S, e, {
495
+ invocationId: t,
496
+ inputClientId: n,
497
+ inputCodecMessageId: r
498
+ }), this._logger?.debug("DefaultRunManager.suspendRun(); run suspended", { runId: e });
499
+ }
500
+ async endRun(e, t, n, r, i, a) {
501
+ this._logger?.trace("DefaultRunManager.endRun();", {
502
+ runId: e,
503
+ reason: t
504
+ });
505
+ let o = t === "error" && a ? {
506
+ errorCode: a.code,
507
+ errorMessage: a.message
508
+ } : {};
509
+ await this._publishTerminal(w, e, {
510
+ reason: t,
511
+ invocationId: n,
512
+ inputClientId: r,
513
+ inputCodecMessageId: i,
514
+ ...o
515
+ }), this._logger?.debug("DefaultRunManager.endRun(); run ended", {
516
+ runId: e,
120
517
  reason: t
121
518
  });
122
519
  }
123
- getSignal(e) {
124
- return this._activeTurns.get(e)?.controller.signal;
520
+ async _publishTerminal(e, t, n) {
521
+ let r = _e({
522
+ runId: t,
523
+ runClientId: this._activeRuns.get(t)?.clientId ?? "",
524
+ ...n
525
+ });
526
+ await this._channel.publish({
527
+ name: e,
528
+ extras: { ai: { transport: r } }
529
+ }), this._activeRuns.delete(t);
125
530
  }
126
531
  getClientId(e) {
127
- return this._activeTurns.get(e)?.clientId;
128
- }
129
- abort(e) {
130
- this._logger?.debug("DefaultTurnManager.abort();", { turnId: e }), this._activeTurns.get(e)?.controller.abort();
131
- }
132
- getActiveTurnIds() {
133
- return [...this._activeTurns.keys()];
532
+ return this._activeRuns.get(e)?.clientId;
134
533
  }
135
534
  close() {
136
- this._logger?.trace("DefaultTurnManager.close();", { activeTurns: this._activeTurns.size });
137
- for (let e of this._activeTurns.values()) e.controller.abort();
138
- this._activeTurns.clear();
139
- }
140
- }, re = (e, t) => new ne(e, t), N = /* @__PURE__ */ function(e) {
141
- return e.READY = "ready", e.CLOSED = "closed", e;
142
- }(N || {}), P = /* @__PURE__ */ function(e) {
143
- return e.INITIALIZED = "initialized", e.STARTED = "started", e.ENDED = "ended", e;
144
- }(P || {}), ie = class {
145
- constructor(t) {
146
- this._registeredTurns = /* @__PURE__ */ new Map(), this._state = N.READY, this._channel = t.channel, this._codec = t.codec, this._logger = t.logger?.withContext({ component: "ServerTransport" }), this._onError = t.onError, this._turnManager = re(this._channel, this._logger), this._channelListener = (e) => {
147
- this._handleChannelMessage(e);
148
- }, this._attachPromise = this._channel.subscribe(_, this._channelListener).then(() => {}, (t) => {
149
- let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`, C.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
150
- this._logger?.error("DefaultServerTransport(); subscribe failed"), this._onError?.(n);
151
- }), this._hasAttachedOnce = this._channel.state === "attached", this._onChannelStateChange = (e) => {
152
- this._handleChannelStateChange(e);
153
- }, this._channel.on(this._onChannelStateChange), this._logger?.debug("DefaultServerTransport(); transport created");
154
- }
155
- newTurn(e) {
156
- return this._logger?.trace("DefaultServerTransport.newTurn();", { turnId: e.turnId }), this._createTurn(e);
157
- }
158
- close() {
159
- if (this._state !== N.CLOSED) {
160
- this._state = N.CLOSED, this._logger?.trace("DefaultServerTransport.close();"), this._channel.unsubscribe(_, this._channelListener), this._channel.off(this._onChannelStateChange);
161
- for (let e of this._registeredTurns.values()) e.controller.abort();
162
- this._registeredTurns.clear(), this._turnManager.close(), this._logger?.debug("DefaultServerTransport.close(); transport closed");
163
- }
164
- }
165
- _resolveFilter(e, t) {
166
- let n = [...this._registeredTurns.keys()];
167
- return e.all ? n : e.own && t ? n.filter((e) => this._registeredTurns.get(e)?.clientId === t) : e.clientId ? n.filter((t) => this._registeredTurns.get(t)?.clientId === e.clientId) : e.turnId && this._registeredTurns.has(e.turnId) ? [e.turnId] : [];
168
- }
169
- async _handleCancelMessage(t) {
170
- let n = w(t), r = {};
171
- n["x-ably-cancel-turn-id"] ? r.turnId = n[u] : n["x-ably-cancel-own"] === "true" ? r.own = !0 : n["x-ably-cancel-client-id"] ? r.clientId = n[p] : n["x-ably-cancel-all"] === "true" && (r.all = !0);
172
- let i = this._resolveFilter(r, t.clientId);
173
- if (i.length === 0) return;
174
- this._logger?.debug("DefaultServerTransport._handleCancelMessage(); matched turns", {
175
- matchedTurnIds: i,
176
- filter: r
177
- });
178
- let a = /* @__PURE__ */ new Map();
179
- for (let e of i) {
180
- let t = this._registeredTurns.get(e);
181
- a.set(e, t?.clientId ?? "");
182
- }
183
- let o = {
184
- message: t,
185
- filter: r,
186
- matchedTurnIds: i,
187
- turnOwners: a
188
- };
189
- for (let t of i) {
190
- let n = this._registeredTurns.get(t);
191
- if (n) try {
192
- if (n.onCancel && !await n.onCancel(o)) {
193
- this._logger?.debug("DefaultServerTransport._handleCancelMessage(); cancel rejected by onCancel", { turnId: t });
194
- continue;
195
- }
196
- n.controller.abort(), this._logger?.debug("DefaultServerTransport._handleCancelMessage(); turn aborted", { turnId: t });
197
- } catch (r) {
198
- let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`, C.CancelListenerError, 500, r instanceof e.ErrorInfo ? r : void 0);
199
- this._logger?.error("DefaultServerTransport._handleCancelMessage(); onCancel threw", { turnId: t }), (n.onError ?? this._onError)?.(i);
200
- }
201
- }
535
+ this._logger?.trace("DefaultRunManager.close();", { activeRuns: this._activeRuns.size });
536
+ for (let e of this._activeRuns.values()) e.controller.abort();
537
+ this._activeRuns.clear();
202
538
  }
203
- _handleChannelStateChange(t) {
204
- if (this._state === N.CLOSED) return;
205
- let { current: n, resumed: r } = t;
206
- if (n === "attached" && !this._hasAttachedOnce) {
207
- this._hasAttachedOnce = !0;
208
- return;
209
- }
210
- if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
211
- this._logger?.error("DefaultServerTransport._handleChannelStateChange(); channel continuity lost", {
212
- current: n,
213
- resumed: r,
214
- previous: t.previous
215
- });
216
- let i = new e.ErrorInfo(`unable to deliver cancel messages; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, C.ChannelContinuityLost, 500, t.reason);
217
- this._onError?.(i);
218
- }
219
- _handleChannelMessage(t) {
220
- try {
221
- t.name === "x-ably-cancel" && this._handleCancelMessage(t).catch((t) => {
222
- let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`, C.CancelListenerError, 500, t instanceof e.ErrorInfo ? t : void 0);
223
- this._logger?.error("DefaultServerTransport._handleChannelMessage(); cancel routing error"), this._onError?.(n);
224
- });
225
- } catch (t) {
226
- let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, C.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
227
- this._logger?.error("DefaultServerTransport._handleChannelMessage(); subscription error"), this._onError?.(n);
228
- }
229
- }
230
- _createTurn(t) {
231
- let { turnId: n, clientId: r, onMessage: i, onAbort: a, onCancel: o, onError: s, parent: c, forkOf: l, signal: u } = t, d = new AbortController(), f = P.INITIALIZED, p = u ? AbortSignal.any([d.signal, u]) : d.signal, m = {
232
- turnId: n,
233
- clientId: r ?? "",
234
- controller: d,
235
- signal: p,
236
- onCancel: o,
237
- onError: s
238
- };
239
- this._registeredTurns.set(n, m);
240
- let h = this._logger, g = this._turnManager, _ = this._attachPromise, v = this._codec, y = this._channel, b = this._registeredTurns;
241
- return {
242
- get turnId() {
243
- return n;
244
- },
245
- get abortSignal() {
246
- return p;
247
- },
248
- start: async () => {
249
- if (h?.trace("Turn.start();", { turnId: n }), p.aborted) throw new e.ErrorInfo(`unable to start turn; turn ${n} was cancelled before start()`, C.InvalidArgument, 400);
250
- if (f === P.INITIALIZED) {
251
- f = P.STARTED;
252
- try {
253
- await g.startTurn(n, r, d, {
254
- parent: c,
255
- forkOf: l
256
- });
257
- } catch (t) {
258
- let r = new e.ErrorInfo(`unable to publish turn-start for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, C.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
259
- throw h?.error("Turn.start(); failed to publish turn-start", { turnId: n }), r;
260
- }
261
- h?.debug("Turn.start(); turn started", { turnId: n });
262
- }
263
- },
264
- addMessages: async (t, r) => {
265
- if (h?.trace("Turn.addMessages();", {
266
- turnId: n,
267
- count: t.length
268
- }), f === P.INITIALIZED) throw new e.ErrorInfo(`unable to add messages; start() must be called before addMessages() (turn ${n})`, C.InvalidArgument, 400);
269
- await _;
270
- let a = [];
271
- try {
272
- for (let e of t) {
273
- let t = E(j({
274
- role: "user",
275
- turnId: n,
276
- msgId: e.msgId,
277
- turnClientId: r?.clientId,
278
- parent: e.parentId ?? c,
279
- forkOf: e.forkOf ?? l
280
- }), e.headers);
281
- await v.createEncoder(y, {
282
- extras: { headers: t },
283
- onMessage: i
284
- }).writeMessages([e.message], r?.clientId ? { clientId: r.clientId } : void 0), a.push(e.msgId);
285
- }
286
- } catch (t) {
287
- let r = new e.ErrorInfo(`unable to publish messages for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, C.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
288
- throw h?.error("Turn.addMessages(); publish failed", { turnId: n }), r;
289
- }
290
- return h?.debug("Turn.addMessages(); messages published", {
291
- turnId: n,
292
- count: t.length
293
- }), { msgIds: a };
294
- },
295
- addEvents: async (t) => {
296
- if (h?.trace("Turn.addEvents();", {
297
- turnId: n,
298
- count: t.length
299
- }), f === P.INITIALIZED) throw new e.ErrorInfo(`unable to add events; start() must be called before addEvents() (turn ${n})`, C.InvalidArgument, 400);
300
- await _;
301
- let r = g.getClientId(n);
302
- try {
303
- for (let e of t) {
304
- let t = j({
305
- role: "assistant",
306
- turnId: n,
307
- msgId: e.msgId,
308
- turnClientId: r,
309
- amend: e.msgId
310
- }), a = v.createEncoder(y, {
311
- extras: { headers: t },
312
- onMessage: i
313
- });
314
- for (let t of e.events) await a.writeEvent(t);
315
- await a.close();
316
- }
317
- } catch (t) {
318
- let r = new e.ErrorInfo(`unable to publish events for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, C.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
319
- throw h?.error("Turn.addEvents(); publish failed", { turnId: n }), r;
320
- }
321
- h?.debug("Turn.addEvents(); events published", {
322
- turnId: n,
323
- count: t.length
324
- });
325
- },
326
- streamResponse: async (t, r) => {
327
- if (h?.trace("Turn.streamResponse();", { turnId: n }), f === P.INITIALIZED) throw new e.ErrorInfo(`unable to stream response; start() must be called before streamResponse() (turn ${n})`, C.InvalidArgument, 400);
328
- await _;
329
- let o = g.getClientId(n), u = r?.parent === void 0 ? c : r.parent, d = crypto.randomUUID(), m = j({
330
- role: "assistant",
331
- turnId: n,
332
- msgId: d,
333
- turnClientId: o,
334
- parent: u,
335
- forkOf: r?.forkOf ?? l
336
- }), b = await M(t, v.createEncoder(y, {
337
- extras: { headers: m },
338
- onMessage: i,
339
- messageId: d
340
- }), p, a, r?.resolveWriteOptions, h);
341
- if (b.error) {
342
- let t = new e.ErrorInfo(`unable to stream response for turn ${n}; ${b.error.message}`, C.StreamError, 500, b.error instanceof e.ErrorInfo ? b.error : void 0);
343
- h?.error("Turn.streamResponse(); stream error", { turnId: n }), s?.(t);
344
- }
345
- return h?.debug("Turn.streamResponse(); stream finished", {
346
- turnId: n,
347
- reason: b.reason
348
- }), b;
349
- },
350
- end: async (t) => {
351
- if (h?.trace("Turn.end();", {
352
- turnId: n,
353
- reason: t
354
- }), f === P.INITIALIZED) throw new e.ErrorInfo(`unable to end turn; start() must be called before end() (turn ${n})`, C.InvalidArgument, 400);
355
- if (f !== P.ENDED) {
356
- f = P.ENDED;
357
- try {
358
- await g.endTurn(n, t);
359
- } catch (t) {
360
- let r = new e.ErrorInfo(`unable to publish turn-end for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, C.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
361
- throw h?.error("Turn.end(); failed to publish turn-end", { turnId: n }), r;
362
- } finally {
363
- b.delete(n);
364
- }
365
- h?.debug("Turn.end(); turn ended", {
366
- turnId: n,
367
- reason: t
368
- });
369
- }
370
- }
371
- };
372
- }
373
- }, ae = (e) => new ie(e), F = (e) => ({
539
+ }, De = (e, t) => new Ee(e, t), Oe = async (t, n) => {
540
+ if (!t) throw new e.ErrorInfo(`unable to ${n}; connect() must be called before ${n}()`, E.InvalidArgument, 400);
541
+ return t;
542
+ }, ke = async (e, t, n, r) => {
543
+ if (t !== void 0) try {
544
+ await e.detach();
545
+ } catch (e) {
546
+ n?.debug(`${r}.close(); channel detach failed`, { error: e });
547
+ }
548
+ }, Ae = (e) => {
549
+ let { current: t, resumed: n } = e;
550
+ return t === "failed" || t === "suspended" || t === "detached" || t === "attached" && !n;
551
+ }, je = (t, n) => {
552
+ let { current: r } = t;
553
+ return new e.ErrorInfo(`unable to ${n}; channel continuity lost (${r}${r === "attached" ? ", resumed: false" : ""})`, E.ChannelContinuityLost, 500, t.reason);
554
+ }, Me = (e) => ({
374
555
  logAction: (t, n, r) => {
375
556
  e.error(n, { detail: r });
376
557
  },
377
558
  shouldLog: () => !0
378
- }), I = e.Realtime.EventEmitter, L = class extends I {
559
+ }), Ne = e.Realtime.EventEmitter, K = class extends Ne {
379
560
  constructor(e) {
380
- super(F(e));
381
- }
382
- }, R = /* @__PURE__ */ function(e) {
383
- return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
384
- }({}), z = (e, t, n) => {
385
- let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
386
- switch (t) {
387
- case R.Trace:
388
- case R.Debug:
389
- console.log(i);
390
- break;
391
- case R.Info:
392
- console.info(i);
393
- break;
394
- case R.Warn:
395
- console.warn(i);
396
- break;
397
- case R.Error:
398
- console.error(i);
399
- break;
400
- case R.Silent: break;
401
- }
402
- }, B = (e) => new U(e.logHandler ?? z, e.logLevel), V = /* @__PURE__ */ function(e) {
403
- 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;
404
- }(V || {}), H = new Map([
405
- [R.Trace, V.Trace],
406
- [R.Debug, V.Debug],
407
- [R.Info, V.Info],
408
- [R.Warn, V.Warn],
409
- [R.Error, V.Error],
410
- [R.Silent, V.Silent]
411
- ]), U = class t {
412
- constructor(t, n, r) {
413
- this._handler = t, this._context = r;
414
- let i = H.get(n);
415
- if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, C.InvalidArgument, 400);
416
- this._levelNumber = i;
417
- }
418
- trace(e, t) {
419
- this._write(e, R.Trace, V.Trace, t);
420
- }
421
- debug(e, t) {
422
- this._write(e, R.Debug, V.Debug, t);
423
- }
424
- info(e, t) {
425
- this._write(e, R.Info, V.Info, t);
426
- }
427
- warn(e, t) {
428
- this._write(e, R.Warn, V.Warn, t);
429
- }
430
- error(e, t) {
431
- this._write(e, R.Error, V.Error, t);
432
- }
433
- withContext(e) {
434
- let n = [...H.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? R.Error;
435
- return new t(this._handler, n, this._mergeContext(e));
561
+ super(Me(e));
436
562
  }
437
- _write(e, t, n, r) {
438
- n >= this._levelNumber && this._handler(e, t, this._mergeContext(r));
439
- }
440
- _mergeContext(e) {
441
- return this._context ? e ? {
442
- ...this._context,
443
- ...e
444
- } : this._context : e ?? void 0;
445
- }
446
- }, W = class {
563
+ }, Pe = (e) => [...e.inputs.map((e) => ({
564
+ direction: "input",
565
+ event: e
566
+ })), ...e.outputs.map((e) => ({
567
+ direction: "output",
568
+ event: e
569
+ }))], Fe = class {
570
+ constructor() {
571
+ this._entries = [], this._swept = !1;
572
+ }
573
+ get swept() {
574
+ return this._swept;
575
+ }
576
+ record(e, t, n, r, i) {
577
+ let a = this._recordEntry(e, t, this._swept ? [] : n, r, i);
578
+ return a === void 0 ? "dropped" : this._swept || a === this._entries.length - 1 ? "incremental" : "refold";
579
+ }
580
+ replay(e) {
581
+ for (let t of this._entries) for (let n of t.events) e(n, t.serial, t.messageId);
582
+ }
583
+ sweep() {
584
+ this._swept = !0;
585
+ for (let e of this._entries) e.events.length = 0;
586
+ }
587
+ _recordEntry(e, t, n, r, i) {
588
+ for (let a = this._entries.length - 1; a >= 0; a--) {
589
+ let o = this._entries[a];
590
+ if (!o) break;
591
+ if (o.serial === e) return r !== void 0 && (r <= o.decodedThrough || !i) ? void 0 : (o.events.push(...n), r !== void 0 && (o.decodedThrough = r), a);
592
+ if (o.serial < e) return this._entries.splice(a + 1, 0, {
593
+ serial: e,
594
+ messageId: t,
595
+ events: [...n],
596
+ decodedThrough: r ?? e
597
+ }), a + 1;
598
+ }
599
+ return this._entries.unshift({
600
+ serial: e,
601
+ messageId: t,
602
+ events: [...n],
603
+ decodedThrough: r ?? e
604
+ }), 0;
605
+ }
606
+ }, q = (e) => e.kind === "run" ? e.runId : e.codecMessageId, Ie = (e) => e.kind === "run" ? e.startSerial : e.serial, Le = (e, t, n) => {
607
+ let r = e.get(t);
608
+ r || (r = /* @__PURE__ */ new Set(), e.set(t, r)), r.add(n);
609
+ }, Re = (e, t, n) => {
610
+ let r = e.get(t);
611
+ r && (r.delete(n), r.size === 0 && e.delete(t));
612
+ }, ze = class {
447
613
  constructor(e, t) {
448
- this._turns = /* @__PURE__ */ new Map(), this._isTerminal = e, this._logger = t;
449
- }
450
- createStream(t) {
451
- this._logger.trace("StreamRouter.createStream();", { turnId: t });
452
- let n = {}, r = new ReadableStream({ start(e) {
453
- n.controller = e;
454
- } });
455
- if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", C.TransportSubscriptionError, 500);
456
- return this._turns.set(t, {
457
- controller: n.controller,
458
- turnId: t
459
- }), r;
460
- }
461
- closeStream(e) {
462
- let t = this._turns.get(e);
463
- if (!t) return !1;
464
- this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
465
- try {
466
- t.controller.close();
467
- } catch {}
468
- return this._turns.delete(e), !0;
614
+ this._nodeIndex = /* @__PURE__ */ new Map(), this._codecMessageIdToNodeKey = /* @__PURE__ */ new Map(), this._sortedNodes = [], this._parentIndex = /* @__PURE__ */ new Map(), this._replyRunsByInput = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._structuralVersion = 0, this._siblingCache = /* @__PURE__ */ new Map(), this._siblingCacheVersion = -1, this._eventIdIndex = /* @__PURE__ */ new Map(), this._clock = 0, this._sweepQueue = [], this._codec = e, this._logger = t, this._emitter = new K(t);
469
615
  }
470
- errorStream(e, t) {
471
- let n = this._turns.get(e);
472
- if (!n) return !1;
473
- this._logger.debug("StreamRouter.errorStream(); erroring stream", { turnId: e });
474
- try {
475
- n.controller.error(t);
476
- } catch {}
477
- return this._turns.delete(e), !0;
616
+ _compareNodes(e, t) {
617
+ let n = Ie(e.node), r = Ie(t.node);
618
+ 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;
478
619
  }
479
- route(e, t) {
480
- let n = this._turns.get(e);
481
- if (!n) return !1;
482
- try {
483
- n.controller.enqueue(t);
484
- } catch {
485
- return this._turns.delete(e), !1;
620
+ _insertSortedNode(e) {
621
+ if (Ie(e.node) === void 0) {
622
+ this._sortedNodes.push(e);
623
+ return;
624
+ }
625
+ let t = 0, n = this._sortedNodes.length;
626
+ for (; t < n;) {
627
+ let r = t + n >>> 1, i = this._sortedNodes[r];
628
+ if (!i) break;
629
+ this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
486
630
  }
487
- return this._isTerminal(t) && this.closeStream(e), !0;
631
+ this._sortedNodes.splice(t, 0, e);
488
632
  }
489
- has(e) {
490
- return this._turns.has(e);
633
+ _removeSortedNode(e) {
634
+ let t = this._sortedNodes.indexOf(e);
635
+ t !== -1 && this._sortedNodes.splice(t, 1);
491
636
  }
492
- }, G = (e, t) => new W(e, t), K = class {
493
- get structuralVersion() {
494
- return this._structuralVersion;
637
+ _insertNode(e, t, n) {
638
+ this._nodeIndex.set(e, t), this._addToParentIndex(n, e), this._insertSortedNode(t), this._structuralVersion++;
495
639
  }
496
- constructor(e) {
497
- 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 L(e);
640
+ _promoteSerial(e) {
641
+ this._removeSortedNode(e), this._insertSortedNode(e), this._structuralVersion++;
498
642
  }
499
- _compareNodes(e, t) {
500
- let n = e.node.serial, r = t.node.serial;
501
- 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;
643
+ _foldInto(e, t, n, r) {
644
+ for (let i of t) try {
645
+ e.node.projection = this._codec.fold(e.node.projection, i, {
646
+ serial: n ?? "",
647
+ messageId: r
648
+ });
649
+ } catch (t) {
650
+ this._logger.error("Tree._foldInto(); fold threw", {
651
+ key: q(e.node),
652
+ messageId: r,
653
+ err: t
654
+ });
655
+ }
502
656
  }
503
- _insertSorted(e) {
504
- if (e.node.serial === void 0) {
505
- this._sortedList.push(e);
657
+ _recordAndFold(e, t, n, r, i, a) {
658
+ if (n === void 0 || t.length === 0) {
659
+ n === void 0 && t.length > 0 && (e.optimistic = !0), this._foldInto(e, t, n, r);
506
660
  return;
507
661
  }
508
- let t = 0, n = this._sortedList.length;
509
- for (; t < n;) {
510
- let r = t + n >>> 1, i = this._sortedList[r];
511
- if (!i) break;
512
- this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
662
+ let o = e.log.record(n, r, t, i, a);
663
+ if (o === "dropped") {
664
+ this._logger.debug("Tree._recordAndFold(); version guard dropped re-delivered wire", {
665
+ key: q(e.node),
666
+ serial: n,
667
+ version: i,
668
+ swept: e.log.swept
669
+ });
670
+ return;
671
+ }
672
+ if (e.optimistic && !e.log.swept) {
673
+ e.optimistic = !1, this._refold(e);
674
+ return;
675
+ }
676
+ if (o === "refold") {
677
+ this._refold(e);
678
+ return;
513
679
  }
514
- this._sortedList.splice(t, 0, e);
680
+ e.log.swept && this._logger.warn("Tree._recordAndFold(); late wire after log retention window; folding in arrival order", {
681
+ key: q(e.node),
682
+ serial: n
683
+ }), this._foldInto(e, t, n, r);
684
+ }
685
+ _refold(e) {
686
+ let t = this._codec.init();
687
+ e.log.replay((n, r, i) => {
688
+ try {
689
+ t = this._codec.fold(t, n, {
690
+ serial: r,
691
+ messageId: i
692
+ });
693
+ } catch (t) {
694
+ this._logger.error("Tree._refold(); fold threw", {
695
+ key: q(e.node),
696
+ messageId: i,
697
+ err: t
698
+ });
699
+ }
700
+ }), e.node.projection = t;
515
701
  }
516
- _removeSorted(e) {
517
- let t = this._sortedList.indexOf(e);
518
- t !== -1 && this._sortedList.splice(t, 1);
702
+ _recordActivity(e, t) {
703
+ t !== void 0 && (t > e.lastActivityTs && (e.lastActivityTs = t), t > this._clock && (this._clock = t, this._drainSweepQueue()));
704
+ }
705
+ _maybeQueueSweep(e) {
706
+ let t = e.node;
707
+ t.kind === "run" && (e.log.swept || e.sweepQueued || e.runStartSeen && (t.state.status === "active" || t.state.status === "suspended" || (e.sweepQueued = !0, this._sweepQueue.push(t.runId))));
708
+ }
709
+ _drainSweepQueue() {
710
+ for (; this._sweepQueue.length > 0;) {
711
+ let e = this._sweepQueue[0], t = e === void 0 ? void 0 : this._nodeIndex.get(e);
712
+ if (!t || t.log.swept) {
713
+ this._sweepQueue.shift();
714
+ continue;
715
+ }
716
+ if (t.lastActivityTs + 12e4 >= this._clock) return;
717
+ this._sweepQueue.shift(), t.sweepQueued = !1, t.log.sweep(), this._logger.debug("Tree._drainSweepQueue(); dropped event-log payloads, kept replay keys", {
718
+ key: e,
719
+ lastActivityTs: t.lastActivityTs
720
+ });
721
+ }
519
722
  }
520
723
  _addToParentIndex(e, t) {
521
- let n = this._parentIndex.get(e);
522
- n || (n = /* @__PURE__ */ new Set(), this._parentIndex.set(e, n)), n.add(t);
724
+ Le(this._parentIndex, e, t);
523
725
  }
524
726
  _removeFromParentIndex(e, t) {
525
- let n = this._parentIndex.get(e);
526
- n && (n.delete(t), n.size === 0 && this._parentIndex.delete(e));
727
+ Re(this._parentIndex, e, t);
728
+ }
729
+ _parentKeyOf(e) {
730
+ let t = e.parentCodecMessageId;
731
+ return t === void 0 ? void 0 : this._codecMessageIdToNodeKey.get(t);
732
+ }
733
+ _inputGroupRoot(e) {
734
+ let t = e, n = new Set([q(t)]);
735
+ for (; t.forkOf !== void 0 && !n.has(t.forkOf);) {
736
+ let e = this._nodeIndex.get(t.forkOf);
737
+ if (e?.node.kind !== "input" || e.node.parentCodecMessageId !== t.parentCodecMessageId) break;
738
+ t = e.node, n.add(q(t));
739
+ }
740
+ return t;
527
741
  }
528
742
  _getSiblingGroup(e) {
529
- let t = this._nodeIndex.get(e);
530
- if (!t) return [];
531
- let n = t.node, r = new Set([n.msgId]);
532
- for (; n.forkOf && !r.has(n.forkOf);) {
533
- let e = this._nodeIndex.get(n.forkOf);
534
- if (!e || e.node.parentId !== n.parentId) break;
535
- n = e.node, r.add(n.msgId);
536
- }
537
- let i = n.parentId, a = n.msgId, o = [], s = this._parentIndex.get(i);
538
- if (s) for (let e of s) {
743
+ this._siblingCacheVersion !== this._structuralVersion && (this._siblingCache.clear(), this._siblingCacheVersion = this._structuralVersion);
744
+ let t = this._siblingCache.get(e);
745
+ if (t) return t;
746
+ let n = this._nodeIndex.get(e);
747
+ if (!n) return [];
748
+ let r = n.node;
749
+ r.kind === "input" && (r = this._inputGroupRoot(r));
750
+ let i = r.parentCodecMessageId, a = [], o = this._parentIndex.get(i);
751
+ if (o) for (let e of o) {
539
752
  let t = this._nodeIndex.get(e);
540
- t && this._isSiblingOf(t.node, a) && o.push(t);
753
+ t && this._isSiblingOf(t.node, r) && a.push(t);
541
754
  }
542
- return o.sort((e, t) => this._compareNodes(e, t)), o.map((e) => e.node);
755
+ a.sort((e, t) => this._compareNodes(e, t));
756
+ for (let e of a) this._siblingCache.set(q(e.node), a);
757
+ return this._siblingCache.set(e, a), a;
543
758
  }
544
759
  _isSiblingOf(e, t) {
545
- if (e.msgId === t) return !0;
546
- let n = e, r = new Set([n.msgId]);
547
- for (; n.forkOf;) {
548
- if (n.forkOf === t) return !0;
549
- if (r.has(n.forkOf)) break;
550
- let e = this._nodeIndex.get(n.forkOf);
760
+ if (e.kind !== t.kind || e.parentCodecMessageId !== t.parentCodecMessageId) return !1;
761
+ if (e.kind === "run") return !0;
762
+ let n = q(t);
763
+ if (q(e) === n) return !0;
764
+ let r = e, i = new Set([q(r)]);
765
+ for (; r.kind === "input" && r.forkOf !== void 0;) {
766
+ if (r.forkOf === n) return !0;
767
+ if (i.has(r.forkOf)) break;
768
+ let e = this._nodeIndex.get(r.forkOf);
551
769
  if (!e) break;
552
- n = e.node, r.add(n.msgId);
770
+ r = e.node, i.add(q(r));
553
771
  }
554
772
  return !1;
555
773
  }
556
774
  getGroupRoot(e) {
557
775
  let t = this._nodeIndex.get(e);
558
776
  if (!t) return e;
559
- let n = t.node, r = new Set([n.msgId]);
560
- for (; n.forkOf && !r.has(n.forkOf);) {
561
- let e = this._nodeIndex.get(n.forkOf);
562
- if (!e || e.node.parentId !== n.parentId) break;
563
- n = e.node, r.add(n.msgId);
564
- }
565
- return n.msgId;
777
+ if (t.node.kind === "input") return q(this._inputGroupRoot(t.node));
778
+ let n = this._getSiblingGroup(e)[0]?.node;
779
+ return n ? q(n) : e;
566
780
  }
567
- flattenNodes(e) {
568
- this._logger.trace("DefaultTree.flattenNodes();");
781
+ visibleNodes(e = /* @__PURE__ */ new Map()) {
782
+ this._logger.trace("DefaultTree.visibleNodes();");
569
783
  let t = [], n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map();
570
- for (let i of this._sortedList) {
571
- let a = i.node, { msgId: o, parentId: s } = a;
784
+ for (let i of this._sortedNodes) {
785
+ let a = i.node, o = q(a), s = this._parentKeyOf(a);
572
786
  if (s !== void 0 && !n.has(s)) continue;
573
787
  let c = this._getSiblingGroup(o);
574
788
  if (c.length > 1) {
575
789
  let t = this.getGroupRoot(o), n = r.get(t);
576
790
  if (n === void 0) {
577
791
  let i = e.get(t);
578
- if (i && c.some((e) => e.msgId === i)) n = i;
792
+ if (i !== void 0 && c.some((e) => q(e.node) === i)) n = i;
579
793
  else {
580
794
  let e = c.at(-1);
581
795
  if (!e) break;
582
- n = e.msgId;
796
+ n = q(e.node);
583
797
  }
584
798
  r.set(t, n);
585
799
  }
@@ -587,66 +801,198 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
587
801
  }
588
802
  n.add(o), t.push(a);
589
803
  }
590
- return t;
591
- }
592
- getSiblings(e) {
593
- return this._logger.trace("DefaultTree.getSiblings();", { msgId: e }), this._getSiblingGroup(e).map((e) => e.message);
804
+ return t;
805
+ }
806
+ getRunNode(e) {
807
+ this._logger.trace("DefaultTree.getRunNode();", { runId: e });
808
+ let t = this._nodeIndex.get(e)?.node;
809
+ return t?.kind === "run" ? t : void 0;
810
+ }
811
+ getNode(e) {
812
+ return this._logger.trace("DefaultTree.getNode();", { key: e }), this._nodeIndex.get(e)?.node;
813
+ }
814
+ getNodeByCodecMessageId(e) {
815
+ this._logger.trace("DefaultTree.getNodeByCodecMessageId();", { codecMessageId: e });
816
+ let t = this._codecMessageIdToNodeKey.get(e);
817
+ return t === void 0 ? void 0 : this._nodeIndex.get(t)?.node;
818
+ }
819
+ getReplyRuns(e) {
820
+ let t = this._replyRunsByInput.get(e);
821
+ if (!t) return [];
822
+ let n = [];
823
+ for (let e of t) {
824
+ let t = this._nodeIndex.get(e)?.node;
825
+ t?.kind === "run" && n.push(t);
826
+ }
827
+ return n;
594
828
  }
595
829
  getSiblingNodes(e) {
596
- return this._getSiblingGroup(e);
597
- }
598
- hasSiblings(e) {
599
- return this._getSiblingGroup(e).length > 1;
830
+ return this._logger.trace("DefaultTree.getSiblingNodes();", { key: e }), this._getSiblingGroup(e).map((e) => e.node);
600
831
  }
601
- getNode(e) {
602
- return this._logger.trace("DefaultTree.getNode();", { msgId: e }), this._nodeIndex.get(e)?.node;
603
- }
604
- getHeaders(e) {
605
- return this._logger.trace("DefaultTree.getHeaders();", { msgId: e }), this._nodeIndex.get(e)?.node.headers;
606
- }
607
- upsert(e, t, n, r) {
608
- let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0, o = this._nodeIndex.get(e);
609
- if (o) {
610
- o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("Tree.upsert(); promoting serial", {
611
- msgId: e,
612
- serial: r
613
- }), o.node.serial = r, this._removeSorted(o), this._insertSorted(o), this._structuralVersion++), this._emitter.emit("update");
832
+ applyMessage(e, t, n, r, i) {
833
+ let a = t[o], s = t[l], c = a === void 0 && s !== void 0 && t.role === "user" && e.inputs.length > 0 ? s : void 0;
834
+ if (a === void 0 && c === void 0) {
835
+ this._logger.warn("Tree.applyMessage(); message has no run-id and is not a user input; skipping");
614
836
  return;
615
837
  }
616
- this._logger.trace("Tree.upsert(); inserting new node", {
617
- msgId: e,
618
- parentId: i,
619
- forkOf: a
838
+ let u = Pe(e), d = c ?? a;
839
+ if (u.length === 0 && d !== void 0 && !this._nodeIndex.has(d)) return;
840
+ let f = this._structuralVersion;
841
+ c === void 0 ? a !== void 0 && this._applyRunMessage(a, e, t, n, r, i) : this._applyInputMessage(c, t, n, r, i, u), this._structuralVersion !== f && this._emitter.emit("update");
842
+ }
843
+ _applyInputMessage(e, t, r, i, a, o) {
844
+ let s = this._nodeIndex.get(e);
845
+ s ? s.node.kind === "input" && r && !s.node.serial && (this._logger.debug("Tree.applyMessage(); promoting input serial", {
846
+ codecMessageId: e,
847
+ serial: r
848
+ }), s.node.serial = r, this._promoteSerial(s)) : (s = this._createInputNodeFromHeaders(e, t, r), this._insertNode(e, s, s.node.parentCodecMessageId), this._codecMessageIdToNodeKey.set(e, e), this._logger.debug("Tree.applyMessage(); created input node", { codecMessageId: e })), this._recordActivity(s, i), this._recordAndFold(s, o, r, e, a, t[n] === "true"), this._emitter.emit("output", {
849
+ runId: void 0,
850
+ inputCodecMessageId: e,
851
+ codecMessageId: e,
852
+ serial: r,
853
+ events: []
620
854
  });
621
- let s = {
622
- node: {
623
- kind: "message",
624
- message: t,
625
- msgId: e,
626
- parentId: i,
627
- forkOf: a,
628
- headers: { ...n },
629
- serial: r
630
- },
631
- insertSeq: this._seqCounter++
632
- };
633
- this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s), this._structuralVersion++, this._emitter.emit("update");
855
+ }
856
+ _applyRunMessage(e, t, r, i, a, o) {
857
+ let s = r[l], c = r[_], u = Pe(t), d = t.outputs, f = this._nodeIndex.get(e);
858
+ if (!f && s !== void 0) {
859
+ let e = this._codecMessageIdToNodeKey.get(s), t = e === void 0 ? void 0 : this._nodeIndex.get(e);
860
+ t?.node.kind === "run" && t.node.startSerial === void 0 && (f = t);
861
+ }
862
+ f ? i && f.node.kind === "run" && !f.node.startSerial && (this._logger.debug("Tree.applyMessage(); promoting startSerial", {
863
+ runId: e,
864
+ serial: i
865
+ }), f.node.startSerial = i, this._promoteSerial(f)) : (f = this._createRunFromHeaders(e, r, i), this._insertNode(e, f, f.node.parentCodecMessageId), this._indexReplyRun(f.node, e), this._logger.debug("Tree.applyMessage(); created new Run", { runId: e }));
866
+ let p = q(f.node);
867
+ s && this._codecMessageIdToNodeKey.set(s, p), this._recordActivity(f, a), this._recordAndFold(f, u, i, s, o, r[n] === "true"), this._emitter.emit("output", {
868
+ runId: p,
869
+ inputCodecMessageId: c,
870
+ codecMessageId: s,
871
+ serial: i,
872
+ events: d
873
+ });
874
+ }
875
+ _indexReplyRun(e, t) {
876
+ e.parentCodecMessageId !== void 0 && Le(this._replyRunsByInput, e.parentCodecMessageId, t);
877
+ }
878
+ applyRunLifecycle(e) {
879
+ this._logger.trace("DefaultTree.applyRunLifecycle();", {
880
+ type: e.type,
881
+ runId: e.runId
882
+ });
883
+ let t = this._structuralVersion;
884
+ switch (e.type) {
885
+ case "start":
886
+ this._applyRunStart(e);
887
+ break;
888
+ case "suspend":
889
+ this._applyRunSuspend(e);
890
+ break;
891
+ case "resume":
892
+ this._applyRunResume(e);
893
+ break;
894
+ case "end":
895
+ this._applyRunEnd(e);
896
+ break;
897
+ }
898
+ this._emitter.emit("run", e), this._structuralVersion !== t && this._emitter.emit("update");
899
+ }
900
+ _applyRunStart(e) {
901
+ let t = this._nodeIndex.get(e.runId);
902
+ if (t?.node.kind === "run") {
903
+ let n = t.node;
904
+ if (n.state.status === "suspended" && (n.state = { status: "active" }), e.serial && !n.startSerial && (n.startSerial = e.serial, this._promoteSerial(t)), n.parentCodecMessageId === void 0 && e.parent !== void 0 && (n.parentCodecMessageId = e.parent, this._removeFromParentIndex(void 0, e.runId), this._addToParentIndex(n.parentCodecMessageId, e.runId), this._indexReplyRun(n, e.runId), this._structuralVersion++), n.forkOf === void 0 && e.forkOf !== void 0) {
905
+ let t = this._codecMessageIdToNodeKey.get(e.forkOf);
906
+ t !== void 0 && t !== e.runId && (n.forkOf = t, this._structuralVersion++);
907
+ }
908
+ n.regeneratesCodecMessageId === void 0 && e.regenerates !== void 0 && (n.regeneratesCodecMessageId = e.regenerates, this._structuralVersion++), n.invocationId === "" && e.invocationId !== "" && (n.invocationId = e.invocationId), t.runStartSeen = !0, this._recordActivity(t, e.timestamp), this._maybeQueueSweep(t);
909
+ } else if (!t) {
910
+ let t = this._createRunFromLifecycle(e);
911
+ this._insertNode(e.runId, t, t.node.parentCodecMessageId), this._indexReplyRun(t.node, e.runId), this._recordActivity(t, e.timestamp);
912
+ }
913
+ }
914
+ _applyRunSuspend(e) {
915
+ let t = this._nodeIndex.get(e.runId);
916
+ t?.node.kind === "run" && (t.node.state = { status: "suspended" }, t.node.endSerial = e.serial, this._recordActivity(t, e.timestamp));
917
+ }
918
+ _applyRunResume(e) {
919
+ let t = this._nodeIndex.get(e.runId);
920
+ t?.node.kind === "run" && t.node.state.status === "suspended" && (t.node.state = { status: "active" }, this._recordActivity(t, e.timestamp));
921
+ }
922
+ _applyRunEnd(e) {
923
+ let t = this._nodeIndex.get(e.runId);
924
+ t?.node.kind === "run" && (t.node.state = e.reason === "error" ? {
925
+ status: "error",
926
+ error: e.error
927
+ } : { status: e.reason }, t.node.endSerial = e.serial, this._recordActivity(t, e.timestamp), this._maybeQueueSweep(t));
634
928
  }
635
929
  delete(e) {
636
930
  let t = this._nodeIndex.get(e);
637
- if (!t) return;
638
- this._logger.debug("Tree.delete();", { msgId: e });
639
- let { node: n } = t;
640
- this._removeFromParentIndex(n.parentId, e), this._removeSorted(t), this._nodeIndex.delete(e), this._structuralVersion++, this._emitter.emit("update");
931
+ 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 && Re(this._replyRunsByInput, t.node.parentCodecMessageId, e), this._structuralVersion++, this._emitter.emit("update"));
932
+ }
933
+ _createRunFromHeaders(e, t, n) {
934
+ let r = t[m];
935
+ return this._buildRunNode({
936
+ runId: e,
937
+ parentCodecMessageId: t[p],
938
+ forkOf: r ? this._codecMessageIdToNodeKey.get(r) : void 0,
939
+ regeneratesCodecMessageId: t[h],
940
+ clientId: t["run-client-id"] ?? "",
941
+ invocationId: t["invocation-id"] ?? "",
942
+ startSerial: n,
943
+ runStartSeen: !1
944
+ });
641
945
  }
642
- getActiveTurnIds() {
643
- this._logger.trace("DefaultTree.getActiveTurnIds();");
644
- let e = /* @__PURE__ */ new Map();
645
- for (let [t, n] of this._turnClientIds) {
646
- let r = e.get(n);
647
- r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
648
- }
649
- return e;
946
+ _wrapNode(e, t = !1) {
947
+ return {
948
+ node: e,
949
+ insertSeq: this._seqCounter++,
950
+ log: new Fe(),
951
+ lastActivityTs: 0,
952
+ runStartSeen: t,
953
+ sweepQueued: !1,
954
+ optimistic: !1
955
+ };
956
+ }
957
+ _buildRunNode(e) {
958
+ let t = {
959
+ kind: "run",
960
+ runId: e.runId,
961
+ parentCodecMessageId: e.parentCodecMessageId,
962
+ forkOf: e.forkOf,
963
+ regeneratesCodecMessageId: e.regeneratesCodecMessageId,
964
+ clientId: e.clientId,
965
+ invocationId: e.invocationId,
966
+ state: { status: "active" },
967
+ projection: this._codec.init(),
968
+ startSerial: e.startSerial,
969
+ endSerial: void 0
970
+ };
971
+ return this._wrapNode(t, e.runStartSeen);
972
+ }
973
+ _createInputNodeFromHeaders(e, t, n) {
974
+ let r = t[m], i = {
975
+ kind: "input",
976
+ codecMessageId: e,
977
+ parentCodecMessageId: t[p],
978
+ forkOf: r,
979
+ projection: this._codec.init(),
980
+ serial: n
981
+ };
982
+ return this._wrapNode(i);
983
+ }
984
+ _createRunFromLifecycle(e) {
985
+ let t = e.forkOf;
986
+ return this._buildRunNode({
987
+ runId: e.runId,
988
+ parentCodecMessageId: e.parent,
989
+ forkOf: t ? this._codecMessageIdToNodeKey.get(t) : void 0,
990
+ regeneratesCodecMessageId: e.regenerates,
991
+ clientId: e.clientId,
992
+ invocationId: e.invocationId,
993
+ startSerial: e.serial,
994
+ runStartSeen: !0
995
+ });
650
996
  }
651
997
  on(e, t) {
652
998
  let n = t;
@@ -655,195 +1001,462 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
655
1001
  };
656
1002
  }
657
1003
  emitAblyMessage(e) {
658
- this._logger.trace("DefaultTree.emitAblyMessage();"), this._emitter.emit("ably-message", e);
1004
+ this._logger.trace("DefaultTree.emitAblyMessage();");
1005
+ let t = P(e)[c];
1006
+ t !== void 0 && !this._eventIdIndex.has(t) && this._eventIdIndex.set(t, e), this._emitter.emit("ably-message", e);
659
1007
  }
660
- emitTurn(e) {
661
- this._logger.trace("DefaultTree.emitTurn();", { turnId: e.turnId }), this._emitter.emit("turn", e);
1008
+ findAblyMessageByEventId(e) {
1009
+ return this._eventIdIndex.get(e);
662
1010
  }
663
- trackTurn(e, t) {
664
- this._logger.trace("DefaultTree.trackTurn();", {
665
- turnId: e,
666
- clientId: t
667
- }), this._turnClientIds.set(e, t);
668
- }
669
- untrackTurn(e) {
670
- this._logger.trace("DefaultTree.untrackTurn();", { turnId: e }), this._turnClientIds.delete(e);
671
- }
672
- }, q = (e) => new K(e), oe = (e) => {
673
- let t = [...e.rawMessages].toReversed(), n = e.codec.createDecoder(), r = /* @__PURE__ */ new Map(), i = e.codec.createAccumulator(), s = 0, c = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = [], f = [];
674
- for (let p of t) {
675
- let t = n.decode(p), m = w(p), h = m[a], g = m[o], _ = p.serial, v = m[l];
676
- if (v) {
677
- for (let e of r.values()) if (e.msgHeaders.has(v)) {
678
- let n = [...e.msgHeaders.keys()].indexOf(v), r = n === -1 ? void 0 : e.accumulator.messages[n];
679
- r && e.accumulator.initMessage(v, r), e.accumulator.processOutputs(t), f.push({
680
- accumulator: e.accumulator,
681
- messageId: v
682
- });
683
- break;
684
- }
685
- continue;
686
- }
687
- if (h) {
688
- let n = r.get(h);
689
- if (n || (n = {
690
- accumulator: e.codec.createAccumulator(),
691
- firstSeen: s++,
692
- msgHeaders: /* @__PURE__ */ new Map(),
693
- msgSerials: /* @__PURE__ */ new Map()
694
- }, r.set(h, n)), g) {
695
- let e = n.msgHeaders.get(g);
696
- e ? Object.keys(m).length > 0 && Object.assign(e, m) : (n.msgHeaders.set(g, { ...m }), _ && n.msgSerials.set(g, _));
697
- }
698
- n.accumulator.processOutputs(t);
699
- } else {
700
- i.processOutputs(t);
701
- for (let e of t) if (e.kind === "message" && g) {
702
- d.push(g);
703
- let e = c.get(g);
704
- e ? Object.keys(m).length > 0 && Object.assign(e, m) : (c.set(g, { ...m }), _ && u.set(g, _));
1011
+ }, Be = (e, t) => new ze(e, t), Ve = 200, He = class {
1012
+ constructor(e) {
1013
+ this._registeredRuns = /* @__PURE__ */ new Map(), this._runIdByInputCodecMessageId = /* @__PURE__ */ new Map(), this._deferredCancels = /* @__PURE__ */ new Map(), this._state = "ready", this._codec = e.codec;
1014
+ let t = { ...G(e.client, e.codec) }, n = se(e.channelModes);
1015
+ n && (t.modes = n), this._channel = e.client.channels.get(e.channelName, t), this._logger = e.logger?.withContext({ component: "AgentSession" }), this._onError = e.onError, this._runManager = De(this._channel, this._logger), this._inputEventLookupTimeoutMs = e.inputEventLookupTimeoutMs ?? 3e4, this._inputEventLookbackMs = e.inputEventLookbackMs ?? 12e4, this._tree = Be(this._codec, this._logger ?? k({ logLevel: D.Silent })), this._applier = Se(this._tree, this._codec.createDecoder()), this._agentView = this._createAgentView(), this._channelListener = (e) => {
1016
+ this._handleChannelMessage(e);
1017
+ }, this._hasAttachedOnce = this._channel.state === "attached", this._onChannelStateChange = (e) => {
1018
+ this._handleChannelStateChange(e);
1019
+ }, this._channel.on(this._onChannelStateChange), this._logger?.debug("DefaultAgentSession(); session created");
1020
+ }
1021
+ _createAgentView() {
1022
+ return he({
1023
+ tree: this._tree,
1024
+ channel: this._channel,
1025
+ codec: this._codec,
1026
+ applier: this._applier,
1027
+ logger: this._logger,
1028
+ inputEventLookbackMs: this._inputEventLookbackMs
1029
+ });
1030
+ }
1031
+ get presence() {
1032
+ return this._channel.presence;
1033
+ }
1034
+ get object() {
1035
+ return this._channel.object;
1036
+ }
1037
+ connect() {
1038
+ return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", E.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger?.trace("DefaultAgentSession.connect();"), this._connectPromise = this._channel.subscribe(this._channelListener).then(() => {
1039
+ this._logger?.debug("DefaultAgentSession.connect(); subscribed and attached");
1040
+ }, (t) => {
1041
+ let n = new e.ErrorInfo(`unable to subscribe to channel; ${j(t)}`, E.SessionSubscriptionError, 500, M(t));
1042
+ throw this._logger?.error("DefaultAgentSession.connect(); subscribe failed"), this._onError?.(n), n;
1043
+ }), this._connectPromise);
1044
+ }
1045
+ get tree() {
1046
+ return this._tree;
1047
+ }
1048
+ createRun(e, t) {
1049
+ return this._logger?.trace("DefaultAgentSession.createRun();", { inputEventId: e.inputEventId }), this._createRun(e, t ?? {});
1050
+ }
1051
+ async close() {
1052
+ if (this._state !== "closed") {
1053
+ this._state = "closed", this._logger?.trace("DefaultAgentSession.close();"), this._connectPromise && this._channel.unsubscribe(this._channelListener), this._channel.off(this._onChannelStateChange);
1054
+ for (let e of this._registeredRuns.values()) e.controller.abort();
1055
+ this._registeredRuns.clear(), this._runIdByInputCodecMessageId.clear(), this._deferredCancels.clear(), this._runManager.close(), await ke(this._channel, this._connectPromise, this._logger, "DefaultAgentSession"), this._logger?.debug("DefaultAgentSession.close(); session closed");
1056
+ }
1057
+ }
1058
+ async _handleCancelMessage(e) {
1059
+ let t = P(e), n = t[o], r = t[_];
1060
+ if (!n && !r) {
1061
+ this._logger?.warn("DefaultAgentSession._handleCancelMessage(); missing run-id and input-codec-message-id", { serial: e.serial });
1062
+ return;
1063
+ }
1064
+ let i = n ?? (r ? this._runIdByInputCodecMessageId.get(r) : void 0), a = i ? this._registeredRuns.get(i) : void 0;
1065
+ if (!a) {
1066
+ r !== void 0 && this._bufferDeferredCancel(r, e);
1067
+ return;
1068
+ }
1069
+ await this._cancelRegistration(a, e);
1070
+ }
1071
+ _bufferDeferredCancel(e, t) {
1072
+ let n = Ce(this._deferredCancels, e, Ve);
1073
+ n !== void 0 && this._logger?.warn("DefaultAgentSession._bufferDeferredCancel(); deferred-cancel buffer full, dropping oldest", {
1074
+ evictedInputCodecMessageId: n,
1075
+ limit: Ve
1076
+ }), this._deferredCancels.set(e, t), this._logger?.debug("DefaultAgentSession._bufferDeferredCancel(); buffered early cancel", {
1077
+ inputCodecMessageId: e,
1078
+ serial: t.serial
1079
+ });
1080
+ }
1081
+ async _pullDeferredCancel(e, t) {
1082
+ let n = this._deferredCancels.get(t);
1083
+ n !== void 0 && (this._deferredCancels.delete(t), this._logger?.debug("DefaultAgentSession._pullDeferredCancel(); honouring buffered cancel", {
1084
+ runId: e.runId,
1085
+ inputCodecMessageId: t
1086
+ }), await this._cancelRegistration(e, n));
1087
+ }
1088
+ async _cancelRegistration(t, n) {
1089
+ let { runId: r } = t;
1090
+ this._logger?.debug("DefaultAgentSession._cancelRegistration(); matched run", { runId: r });
1091
+ let i = {
1092
+ message: n,
1093
+ runId: r
1094
+ };
1095
+ try {
1096
+ if (t.onCancel && !await t.onCancel(i)) {
1097
+ this._logger?.debug("DefaultAgentSession._cancelRegistration(); cancel rejected by onCancel", { runId: r });
1098
+ return;
705
1099
  }
1100
+ t.controller.abort(), this._logger?.debug("DefaultAgentSession._cancelRegistration(); run cancelled", { runId: r });
1101
+ } catch (n) {
1102
+ let i = new e.ErrorInfo(`unable to process cancel for run ${r}; onCancel handler threw: ${j(n)}`, E.CancelListenerError, 500, M(n));
1103
+ this._logger?.error("DefaultAgentSession._cancelRegistration(); onCancel threw", { runId: r }), (t.onError ?? this._onError)?.(i);
706
1104
  }
707
1105
  }
708
- for (let { accumulator: e, messageId: t } of f) e.completeMessage(t);
709
- let p = [];
710
- for (let [e, t] of i.completedMessages.entries()) {
711
- let n = d[e];
712
- p.push({
713
- message: t,
714
- headers: n ? c.get(n) ?? {} : {},
715
- serial: n ? u.get(n) ?? "" : ""
1106
+ _handleChannelStateChange(e) {
1107
+ if (this._state === "closed") return;
1108
+ let { current: t, resumed: n } = e;
1109
+ if (t === "attached" && !this._hasAttachedOnce) {
1110
+ this._hasAttachedOnce = !0;
1111
+ return;
1112
+ }
1113
+ if (!Ae(e)) return;
1114
+ this._logger?.error("DefaultAgentSession._handleChannelStateChange(); channel continuity lost", {
1115
+ current: t,
1116
+ resumed: n,
1117
+ previous: e.previous
716
1118
  });
1119
+ let r = je(e, "continue");
1120
+ for (let e of this._registeredRuns.values()) e.controller.abort();
1121
+ this._tree = Be(this._codec, this._logger ?? k({ logLevel: D.Silent })), this._applier = Se(this._tree, this._codec.createDecoder()), this._agentView = this._createAgentView(), this._onError?.(r);
717
1122
  }
718
- let m = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
719
- for (let e of m) {
720
- let t = [...e.msgHeaders.entries()], n = 0;
721
- for (let r of e.accumulator.completedMessages) {
722
- let i = t[n];
723
- if (i) {
724
- let [t, a] = i;
725
- p.push({
726
- message: r,
727
- headers: a,
728
- serial: e.msgSerials.get(t) ?? ""
729
- }), n++;
730
- } else p.push({
731
- message: r,
732
- headers: {},
733
- serial: ""
734
- });
1123
+ _foldWire(e) {
1124
+ this._applier.apply(e), this._tree.emitAblyMessage(e);
1125
+ }
1126
+ _handleChannelMessage(t) {
1127
+ try {
1128
+ if (this._foldWire(t), t.name === "ai-cancel") {
1129
+ this._handleCancelMessage(t).catch((t) => {
1130
+ let n = new e.ErrorInfo(`unable to route cancel message; ${j(t)}`, E.CancelListenerError, 500, M(t));
1131
+ this._logger?.error("DefaultAgentSession._handleChannelMessage(); cancel routing error"), this._onError?.(n);
1132
+ });
1133
+ return;
1134
+ }
1135
+ } catch (t) {
1136
+ let n = new e.ErrorInfo(`unable to process channel message; ${j(t)}`, E.SessionSubscriptionError, 500, M(t));
1137
+ this._logger?.error("DefaultAgentSession._handleChannelMessage(); subscription error"), this._onError?.(n);
735
1138
  }
736
1139
  }
737
- return p.toReversed();
738
- }, se = (e) => {
739
- if (e.cachedDecode && e.cachedAtRawLength === e.rawMessages.length) return e.cachedDecode;
740
- let t = oe(e);
741
- return e.cachedDecode = t, e.cachedAtRawLength = e.rawMessages.length, t;
742
- }, J = (e, t) => {
743
- for (let r of t) {
744
- let t = w(r), i = t[o];
745
- if (!i || t["x-ably-amend"]) continue;
746
- let a = r.action, s = a === "message.create" && "x-ably-discrete" in t, c = t["x-ably-stream"] === "true" && (a === "message.create" || a === "message.update" || a === "message.append"), l = t[n], u = l === "finished" || l === "aborted";
747
- (s || c) && e.startedMsgIds.add(i), (s || u) && e.terminatedMsgIds.add(i), e.startedMsgIds.has(i) && e.terminatedMsgIds.has(i) && e.completedMsgIds.add(i);
748
- }
749
- }, Y = async (e, t, n) => {
750
- e.rawMessages.push(...t.items), e.lastAblyPage = t, J(e, t.items);
751
- let r = e.returnedCount + n;
752
- for (; e.completedMsgIds.size < r && t.hasNext();) {
753
- e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
1140
+ async _requireConnected(e) {
1141
+ return Oe(this._connectPromise, e);
1142
+ }
1143
+ _createRun(t, n) {
1144
+ let r = n.runId ?? crypto.randomUUID(), i = n.runId !== void 0, a = n.invocationId ?? crypto.randomUUID(), s = this._inputEventLookupTimeoutMs, { onMessage: c, onCancelled: d, onCancel: f, onError: g, signal: _ } = n, v = new AbortController(), y = "initialized", b = _ ? AbortSignal.any([v.signal, _]) : v.signal, x = {
1145
+ runId: r,
1146
+ invocationId: a,
1147
+ controller: v,
1148
+ signal: b,
1149
+ onCancel: f,
1150
+ onError: g
1151
+ };
1152
+ this._registeredRuns.set(r, x);
1153
+ let S = this._logger, C = this._runManager, w = this._codec, ee = this._channel, T = this._registeredRuns, te = this._runIdByInputCodecMessageId, D = this._deferredCancels, O = this._requireConnected.bind(this), k = () => this._agentView, ne = this._pullDeferredCancel.bind(this), A = t.inputEventId, N, P, F, I, L, R, z = !1, B, V = () => this._tree, re = { get messages() {
1154
+ if (R === void 0) return [];
1155
+ let e = V().getNodeByCodecMessageId(R);
1156
+ if (!e) return [];
1157
+ let t = e.kind === "input" ? e.serial : e.startSerial, n = e.kind === "input" ? e.forkOf : void 0;
1158
+ return w.getMessages(e.projection).map((r) => ({
1159
+ kind: "message",
1160
+ message: r.message,
1161
+ codecMessageId: r.codecMessageId,
1162
+ parentId: e.parentCodecMessageId,
1163
+ forkOf: n,
1164
+ headers: {},
1165
+ serial: t
1166
+ }));
1167
+ } }, H, U = () => {
1168
+ T.delete(r), R !== void 0 && (te.delete(R), D.delete(R));
1169
+ }, W = async (t, n, i) => {
1170
+ try {
1171
+ await i();
1172
+ } catch (i) {
1173
+ let a = new e.ErrorInfo(`unable to publish ${t} for run ${r}; ${j(i)}`, E.RunLifecycleError, 500, M(i));
1174
+ throw S?.error(`Run.${n}(); failed to publish ${t}`, { runId: r }), a;
1175
+ }
1176
+ }, G = {
1177
+ get runId() {
1178
+ return r;
1179
+ },
1180
+ get invocationId() {
1181
+ return a;
1182
+ },
1183
+ get abortSignal() {
1184
+ return b;
1185
+ },
1186
+ get view() {
1187
+ return re;
1188
+ },
1189
+ get messages() {
1190
+ return k().messages(r, H, L);
1191
+ },
1192
+ start: async () => {
1193
+ if (S?.trace("Run.start();", {
1194
+ runId: r,
1195
+ inputEventId: A
1196
+ }), await O("start"), b.aborted) throw new e.ErrorInfo(`unable to start run; run ${r} was cancelled before start()`, E.InvalidArgument, 400);
1197
+ if (y !== "initialized") return;
1198
+ if (y = "started", A && s > 0) try {
1199
+ let e = await k().findInputEvent({
1200
+ invocationId: a,
1201
+ runId: r,
1202
+ expectedEventIds: [A],
1203
+ timeoutMs: s,
1204
+ signal: b
1205
+ });
1206
+ e.firstHeaders !== void 0 && (B = e.firstHeaders), e.firstClientId !== void 0 && (P = e.firstClientId);
1207
+ } catch (t) {
1208
+ let n = t instanceof e.ErrorInfo ? t : new e.ErrorInfo(`unable to look up input event; ${j(t)}`, E.InputEventNotFound, 504);
1209
+ throw U(), S?.error("Run.start(); input-event lookup failed", {
1210
+ runId: r,
1211
+ invocationId: a
1212
+ }), n;
1213
+ }
1214
+ let t = B;
1215
+ if (t) {
1216
+ N = t[u], F = t[p], I = t[m], L = t[h], R = t[l];
1217
+ let e = t[o];
1218
+ z = e !== void 0, e !== void 0 && e !== r && (T.delete(r), r = e, x.runId = r, T.set(r, x));
1219
+ }
1220
+ H = R !== void 0 && this._tree.getNodeByCodecMessageId(R) !== void 0 ? R : F, R !== void 0 && (te.set(R, r), await ne(x, R)), await W("run-start", "start", async () => C.startRun(r, N, v, {
1221
+ parent: H,
1222
+ forkOf: I,
1223
+ regenerates: L,
1224
+ invocationId: a,
1225
+ inputClientId: P,
1226
+ inputCodecMessageId: R,
1227
+ continuation: z
1228
+ })), z || V().applyRunLifecycle({
1229
+ type: "start",
1230
+ runId: r,
1231
+ clientId: N ?? "",
1232
+ serial: void 0,
1233
+ invocationId: a,
1234
+ ...H !== void 0 && { parent: H },
1235
+ ...I !== void 0 && { forkOf: I },
1236
+ ...L !== void 0 && { regenerates: L }
1237
+ }), S?.debug("Run.start(); run started", {
1238
+ runId: r,
1239
+ inputEventId: A
1240
+ });
1241
+ },
1242
+ loadConversation: async (e) => {
1243
+ S?.trace("Run.loadConversation();", { runId: r }), await O("loadConversation");
1244
+ let { messages: t } = await k().loadConversation(r, H, b, e?.maxRuns, i || z, L);
1245
+ return t;
1246
+ },
1247
+ pipe: async (t, n) => {
1248
+ if (S?.trace("Run.pipe();", { runId: r }), await O("pipe"), y === "initialized") throw new e.ErrorInfo(`unable to pipe stream; start() must be called before pipe() (run ${r})`, E.InvalidArgument, 400);
1249
+ let i = C.getClientId(r), o = n?.parent ?? H, s = n?.forkOf ?? I, l = L, u = crypto.randomUUID(), f = ge({
1250
+ role: "assistant",
1251
+ runId: r,
1252
+ codecMessageId: u,
1253
+ runClientId: i,
1254
+ parent: o,
1255
+ forkOf: s,
1256
+ invocationId: a,
1257
+ inputClientId: P,
1258
+ inputCodecMessageId: R,
1259
+ regenerates: l
1260
+ }), p = await Te(t, w.createEncoder(ee, {
1261
+ extras: { headers: f },
1262
+ onMessage: c,
1263
+ messageId: u
1264
+ }), b, d, n?.resolveWriteOptions, S);
1265
+ if (p.error) {
1266
+ let t = new e.ErrorInfo(`unable to pipe response for run ${r}; ${p.error.message}`, E.StreamError, 500, M(p.error));
1267
+ S?.error("Run.pipe(); stream error", { runId: r }), g?.(t);
1268
+ }
1269
+ if (p.reason === "cancelled") try {
1270
+ await G.end({ reason: "cancelled" });
1271
+ } catch {
1272
+ S?.error("Run.pipe(); run-end on cancel failed", { runId: r });
1273
+ }
1274
+ return S?.debug("Run.pipe(); stream finished", {
1275
+ runId: r,
1276
+ reason: p.reason
1277
+ }), p;
1278
+ },
1279
+ suspend: async () => {
1280
+ if (S?.trace("Run.suspend();", { runId: r }), await O("suspend"), y === "initialized") throw new e.ErrorInfo(`unable to suspend run; start() must be called before suspend() (run ${r})`, E.InvalidArgument, 400);
1281
+ if (y !== "ended") {
1282
+ y = "ended";
1283
+ try {
1284
+ await W("run-suspend", "suspend", async () => C.suspendRun(r, a, P, R));
1285
+ } finally {
1286
+ U();
1287
+ }
1288
+ S?.debug("Run.suspend(); run suspended", { runId: r });
1289
+ }
1290
+ },
1291
+ end: async (t) => {
1292
+ let { reason: n } = t, i = t.reason === "error" ? t.error : void 0;
1293
+ if (S?.trace("Run.end();", {
1294
+ runId: r,
1295
+ reason: n
1296
+ }), await O("end"), y === "initialized") throw new e.ErrorInfo(`unable to end run; start() must be called before end() (run ${r})`, E.InvalidArgument, 400);
1297
+ if (y !== "ended") {
1298
+ y = "ended";
1299
+ try {
1300
+ await W("run-end", "end", async () => C.endRun(r, n, a, P, R, i));
1301
+ } finally {
1302
+ U();
1303
+ }
1304
+ S?.debug("Run.end(); run ended", {
1305
+ runId: r,
1306
+ reason: n
1307
+ });
1308
+ }
1309
+ }
1310
+ };
1311
+ return G;
1312
+ }
1313
+ }, Ue = (e) => new He(e), We = (e, t) => {
1314
+ for (let n of t) {
1315
+ let t = P(n), i = t[l];
1316
+ if (!i) continue;
1317
+ let a = n.action, o = a === "message.create" && "discrete" in t, s = t.stream === "true" && (a === "message.create" || a === "message.update" || a === "message.append"), c = t[r], u = c === "complete" || c === "cancelled";
1318
+ (o || s) && e.startedCodecMessageIds.add(i), (o || u) && e.terminatedCodecMessageIds.add(i), e.startedCodecMessageIds.has(i) && e.terminatedCodecMessageIds.has(i) && e.completedCodecMessageIds.add(i);
1319
+ }
1320
+ }, Ge = async (e, t) => {
1321
+ let n = e.returnedCount + t;
1322
+ for (; e.completedCodecMessageIds.size < n && e.cursor.hasNext();) {
1323
+ e.logger.debug("loadHistory.fetchUntilLimit(); pulling next page", {
754
1324
  collected: e.rawMessages.length,
755
- completed: e.completedMsgIds.size
1325
+ completed: e.completedCodecMessageIds.size
756
1326
  });
757
- let n = await t.next();
758
- if (!n) break;
759
- t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, J(e, n.items);
760
- }
761
- }, X = (e, t) => {
762
- let n = se(e), r = n.slice(e.returnedCount, e.returnedCount + t), i = [...r].toReversed();
763
- e.returnedCount += r.length;
764
- let a = n.length > e.returnedCount, o = e.lastAblyPage?.hasNext() ?? !1, s = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
1327
+ let t = await e.cursor.next();
1328
+ if (!t) break;
1329
+ e.rawMessages.push(...t), We(e, t);
1330
+ }
1331
+ }, Ke = (e, t) => {
1332
+ let n = e.completedCodecMessageIds.size, r = Math.min(t, Math.max(0, n - e.returnedCount));
1333
+ e.returnedCount += r;
1334
+ let i = n > e.returnedCount, a = e.cursor.hasNext(), o = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
765
1335
  return e.returnedRawCount = e.rawMessages.length, {
766
- items: i.map((e) => ({
767
- message: e.message,
768
- headers: e.headers,
769
- serial: e.serial
770
- })),
771
- rawMessages: s,
772
- hasNext: () => a || o,
1336
+ rawMessages: o,
1337
+ hasNext: () => i || a,
773
1338
  next: async () => {
774
- if (a) return X(e, t);
775
- if (!o || !e.lastAblyPage) return;
776
- let n = await e.lastAblyPage.next();
777
- if (n) return await Y(e, n, t), X(e, t);
1339
+ if (i) return Ke(e, t);
1340
+ if (a) return await Ge(e, t), Ke(e, t);
778
1341
  }
779
1342
  };
780
- }, ce = async (e, t, n, r) => {
781
- let i = n?.limit ?? 100, a = {
782
- codec: t,
1343
+ }, qe = async (e, t, n) => {
1344
+ let r = t?.limit ?? 100;
1345
+ n.trace("loadHistory();", { limit: r });
1346
+ let i = {
1347
+ cursor: await ue(e, {
1348
+ pageLimit: r * 10,
1349
+ untilAttach: !0,
1350
+ logger: n
1351
+ }),
783
1352
  rawMessages: [],
784
1353
  returnedCount: 0,
785
1354
  returnedRawCount: 0,
786
- lastAblyPage: void 0,
787
- cachedDecode: void 0,
788
- cachedAtRawLength: 0,
789
- startedMsgIds: /* @__PURE__ */ new Set(),
790
- terminatedMsgIds: /* @__PURE__ */ new Set(),
791
- completedMsgIds: /* @__PURE__ */ new Set(),
792
- logger: r
1355
+ startedCodecMessageIds: /* @__PURE__ */ new Set(),
1356
+ terminatedCodecMessageIds: /* @__PURE__ */ new Set(),
1357
+ completedCodecMessageIds: /* @__PURE__ */ new Set(),
1358
+ logger: n
793
1359
  };
794
- r.trace("decodeHistory();", { limit: i });
795
- let o = i * 10;
796
- return await e.attach(), await Y(a, await e.history({
797
- untilAttach: !0,
798
- limit: o
799
- }), i), X(a, i);
800
- }, le = class {
1360
+ return await Ge(i, r), Ke(i, r);
1361
+ }, Je = (e) => Array.isArray(e) ? e : [e], J = (e) => ({
1362
+ runId: e.runId,
1363
+ clientId: e.clientId,
1364
+ invocationId: e.invocationId,
1365
+ ...e.state
1366
+ }), Ye = class {
801
1367
  constructor(e) {
802
- 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 L(this._logger), this._cachedNodes = this._computeFlatNodes(), this._lastStructuralVersion = this._tree.structuralVersion, this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
1368
+ this._branchSelections = /* @__PURE__ */ new Map(), this._regenSelections = /* @__PURE__ */ new Map(), this._nonHeadRegenSelections = /* @__PURE__ */ new Map(), this._withheldRunIds = /* @__PURE__ */ new Set(), this._lastVisibleNodeKeys = [], this._lastVisibleProjections = [], this._lastVisibleMessagePairs = [], this._lastVisibleNodeKeySet = /* @__PURE__ */ new Set(), this._hasMoreHistory = !1, this._withheldBuffer = [], this._hiddenMessageCount = 0, this._unsubs = [], this._cachedNodes = [], this._loadingOlder = !1, this._processingHistory = !1, this._closed = !1, this._tree = e.tree, this._channel = e.channel, this._codec = e.codec, this._applier = e.applier, this._sendDelegate = e.sendDelegate, this._onClose = e.onClose, this._logger = e.logger.withContext({ component: "View" }), this._logger.trace("DefaultView();"), this._emitter = new K(this._logger), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
803
1369
  this._onTreeUpdate();
804
1370
  }), this._tree.on("ably-message", (e) => {
805
1371
  this._onTreeAblyMessage(e);
806
- }), this._tree.on("turn", (e) => {
807
- this._onTreeTurn(e);
1372
+ }), this._tree.on("run", (e) => {
1373
+ this._onTreeRun(e);
1374
+ }), this._tree.on("output", (e) => {
1375
+ this._onTreeOutput(e);
808
1376
  }));
809
1377
  }
1378
+ _onTreeOutput(e) {
1379
+ this._processingHistory || (e.runId !== void 0 && this._lastVisibleNodeKeySet.has(e.runId) || e.inputCodecMessageId !== void 0 && this._lastVisibleNodeKeySet.has(e.inputCodecMessageId)) && (this._lastVisibleProjections = this._cachedNodes.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(this._cachedNodes).slice(this._hiddenMessageCount), this._emitter.emit("update"));
1380
+ }
810
1381
  getMessages() {
811
- return this.flattenNodes().map((e) => e.message);
1382
+ return this._lastVisibleMessagePairs;
812
1383
  }
813
- flattenNodes() {
814
- return this._cachedNodes;
1384
+ runs() {
1385
+ return this._cachedNodes.filter((e) => e.kind === "run").map((e) => J(e));
815
1386
  }
816
1387
  _computeFlatNodes() {
817
- let e = this._tree.flattenNodes(this._resolveSelections());
818
- return this._withheldMsgIds.size === 0 ? e : e.filter((e) => !this._withheldMsgIds.has(e.msgId));
1388
+ let e = this._treeVisibleNodes();
1389
+ return this._withheldRunIds.size === 0 ? e : e.filter((e) => !this._withheldRunIds.has(q(e)));
1390
+ }
1391
+ _recomputeAndEmit() {
1392
+ this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update");
1393
+ }
1394
+ _recomputeAndEmitIfChanged() {
1395
+ let e = this._computeFlatNodes();
1396
+ this._visibleChanged(e) && (this._cachedNodes = e, this._updateVisibleSnapshot(e), this._emitter.emit("update"));
1397
+ }
1398
+ _runByCodecMessageId(e) {
1399
+ let t = this._tree.getNodeByCodecMessageId(e);
1400
+ return t?.kind === "run" ? t : void 0;
1401
+ }
1402
+ _nonHeadRegenerators(e, t) {
1403
+ return this._tree.getReplyRuns(t).filter((t) => t.regeneratesCodecMessageId === e).toSorted((e, t) => (e.startSerial ?? "￿").localeCompare(t.startSerial ?? "￿"));
1404
+ }
1405
+ _selectedNonHeadMember(e, t, n) {
1406
+ let r = this._nonHeadRegenSelections.get(e);
1407
+ return r && r.kind !== "pending" && [t, ...n.map((e) => e.runId)].includes(r.selectedRunId) ? r.selectedRunId : n.at(-1)?.runId ?? t;
1408
+ }
1409
+ _extractMessages(e) {
1410
+ let t = [], n = /* @__PURE__ */ new Set();
1411
+ for (let r of e) r.kind === "run" && n.has(r.runId) || this._emitNodeMessages(r, t, n);
1412
+ return t;
1413
+ }
1414
+ _emitNodeMessages(e, t, n) {
1415
+ let r = this._codec.getMessages(e.projection);
1416
+ if (e.kind !== "run") {
1417
+ t.push(...r);
1418
+ return;
1419
+ }
1420
+ for (let i = 0; i < r.length; i++) {
1421
+ let a = r[i];
1422
+ if (!a) continue;
1423
+ let o = i > 0 ? r[i - 1]?.codecMessageId : void 0;
1424
+ if (o !== void 0) {
1425
+ let r = this._nonHeadRegenerators(a.codecMessageId, o);
1426
+ if (r.length > 0) {
1427
+ for (let e of r) n.add(e.runId);
1428
+ let i = this._selectedNonHeadMember(a.codecMessageId, e.runId, r);
1429
+ if (i !== e.runId) {
1430
+ let e = r.find((e) => e.runId === i);
1431
+ if (e) {
1432
+ this._emitNodeMessages(e, t, n);
1433
+ return;
1434
+ }
1435
+ }
1436
+ }
1437
+ }
1438
+ t.push(a);
1439
+ }
819
1440
  }
820
1441
  hasOlder() {
821
- return this._withheldBuffer.length > 0 || this._hasMoreHistory;
1442
+ return this._hiddenMessageCount > 0 || this._withheldBuffer.length > 0 || this._hasMoreHistory;
822
1443
  }
823
- async loadOlder(e = 100) {
1444
+ async loadOlder(e = 10) {
824
1445
  if (!(this._closed || this._loadingOlder)) {
825
1446
  this._loadingOlder = !0, this._logger.trace("DefaultView.loadOlder();", { limit: e });
826
1447
  try {
827
- if (this._withheldBuffer.length > 0) {
828
- let t = this._withheldBuffer.splice(-e, e);
829
- this._releaseWithheld(t);
1448
+ if (this._hiddenMessageCount >= e) {
1449
+ this._hiddenMessageCount -= e, this._recomputeAndEmit();
830
1450
  return;
831
1451
  }
832
- if (!this._hasMoreHistory && !this._lastHistoryPage) {
833
- await this._loadFirstPage(e);
834
- return;
835
- }
836
- if (!this._hasMoreHistory) return;
837
- if (!this._lastHistoryPage?.hasNext()) {
838
- this._hasMoreHistory = !1;
839
- return;
840
- }
841
- let t = await this._lastHistoryPage.next();
842
- if (this._closed || !t) {
843
- t || (this._hasMoreHistory = !1);
844
- return;
1452
+ let t = e - this._hiddenMessageCount, n = this._extractMessages(this._computeFlatNodes()).length, r = () => this._extractMessages(this._computeFlatNodes()).length - n;
1453
+ if (this._withheldBuffer.length > 0) {
1454
+ let e = this._messageTailSplitIndex(this._withheldBuffer, t), n = this._withheldBuffer.splice(e);
1455
+ this._releaseWithheld(n);
845
1456
  }
846
- await this._loadAndReveal(t, e);
1457
+ if (r() < t && (await this._fetchOlder(t - r()), this._closed)) return;
1458
+ let i = this._extractMessages(this._computeFlatNodes()).length;
1459
+ this._hiddenMessageCount = Math.max(0, this._hiddenMessageCount + (i - n) - e), this._recomputeAndEmit();
847
1460
  } catch (e) {
848
1461
  throw this._logger.error("DefaultView.loadOlder(); failed", { error: e }), e;
849
1462
  } finally {
@@ -851,132 +1464,272 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
851
1464
  }
852
1465
  }
853
1466
  }
854
- select(e, t) {
855
- this._logger.trace("DefaultView.select();", {
856
- msgId: e,
1467
+ async _fetchOlder(e) {
1468
+ if (!this._hasMoreHistory && !this._lastHistoryPage) {
1469
+ await this._loadFirstPage(e);
1470
+ return;
1471
+ }
1472
+ if (!this._hasMoreHistory) return;
1473
+ if (!this._lastHistoryPage?.hasNext()) {
1474
+ this._hasMoreHistory = !1;
1475
+ return;
1476
+ }
1477
+ let t = await this._lastHistoryPage.next();
1478
+ if (this._closed || !t) {
1479
+ t || (this._hasMoreHistory = !1);
1480
+ return;
1481
+ }
1482
+ await this._revealFromPage(t, e);
1483
+ }
1484
+ _messageTailSplitIndex(e, t) {
1485
+ let n = 0;
1486
+ for (let r = e.length - 1; r >= 0; r--) {
1487
+ let i = e[r];
1488
+ if (i && (n += this._codec.getMessages(i.projection).length, n >= t)) return r;
1489
+ }
1490
+ return 0;
1491
+ }
1492
+ runOf(e) {
1493
+ this._logger.trace("DefaultView.runOf();", { codecMessageId: e });
1494
+ let t = this._tree.getNodeByCodecMessageId(e);
1495
+ if (!t) return;
1496
+ if (t.kind === "run") return J(t);
1497
+ let n = this._selectedReplyRun(t.codecMessageId);
1498
+ return n ? J(n) : void 0;
1499
+ }
1500
+ _selectedReplyRun(e) {
1501
+ let t = this._tree.getReplyRuns(e);
1502
+ if (t.length === 0) return;
1503
+ if (t.length === 1) return t[0];
1504
+ let n = this._tree.getGroupRoot(t[0]?.runId ?? ""), r = this._regenSelections.get(n), i = r && r.kind !== "pending" ? r.selectedRunId : void 0;
1505
+ if (i !== void 0) {
1506
+ let e = t.find((e) => e.runId === i);
1507
+ if (e) return e;
1508
+ }
1509
+ return t.toSorted((e, t) => (e.startSerial ?? "￿").localeCompare(t.startSerial ?? "￿")).at(-1);
1510
+ }
1511
+ run(e) {
1512
+ this._logger.trace("DefaultView.run();", { runId: e });
1513
+ let t = this._tree.getRunNode(e);
1514
+ return t ? J(t) : void 0;
1515
+ }
1516
+ branchSelection(e) {
1517
+ let t = this._resolveMessageBranchPoint(e);
1518
+ if (t) {
1519
+ let e = t.members.flatMap((e) => {
1520
+ let t = this._tree.getNodeByCodecMessageId(e.representativeCodecMessageId);
1521
+ if (!t) return [];
1522
+ let n = this._codec.getMessages(t.projection).find((t) => t.codecMessageId === e.representativeCodecMessageId);
1523
+ return n ? [n.message] : [];
1524
+ });
1525
+ if (e.length > 0) {
1526
+ let n = this._resolveSelectedIndex(t), r = Math.max(0, Math.min(n, e.length - 1)), i = e[r];
1527
+ return {
1528
+ hasSiblings: e.length > 1,
1529
+ siblings: e,
1530
+ index: r,
1531
+ selected: i
1532
+ };
1533
+ }
1534
+ }
1535
+ let n = this._tree.getNodeByCodecMessageId(e);
1536
+ if (n) {
1537
+ let t = this._codec.getMessages(n.projection).find((t) => t.codecMessageId === e);
1538
+ if (t !== void 0) return {
1539
+ hasSiblings: !1,
1540
+ siblings: [t.message],
1541
+ index: 0,
1542
+ selected: t.message
1543
+ };
1544
+ }
1545
+ return {
1546
+ hasSiblings: !1,
1547
+ siblings: [],
1548
+ index: 0,
1549
+ selected: void 0
1550
+ };
1551
+ }
1552
+ selectSibling(e, t) {
1553
+ this._logger.trace("DefaultView.selectSibling();", {
1554
+ codecMessageId: e,
857
1555
  index: t
858
1556
  });
859
- let n = this._tree.getSiblingNodes(e);
860
- if (n.length <= 1) return;
861
- let r = this._tree.getGroupRoot(e), i = Math.max(0, Math.min(t, n.length - 1)), a = n[i];
862
- a && (this._branchSelections.set(r, {
1557
+ let n = this._resolveMessageBranchPoint(e);
1558
+ if (!n) return;
1559
+ let r = Math.max(0, Math.min(t, n.members.length - 1)), i = n.members[r];
1560
+ i && (n.kind === "fork-of" ? (this._branchSelections.set(n.groupRoot, {
863
1561
  kind: "user",
864
- selectedId: a.msgId
865
- }), this._logger.debug("DefaultView.select();", {
866
- msgId: e,
867
- index: i,
868
- selectedId: a.msgId
869
- }), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
870
- }
871
- getSelectedIndex(e) {
872
- this._logger.trace("DefaultView.getSelectedIndex();", { msgId: e });
873
- let t = this._tree.getSiblingNodes(e);
874
- if (t.length <= 1) return 0;
875
- let n = this._tree.getGroupRoot(e), r = this._branchSelections.get(n);
876
- if (!r || r.kind === "pending") return t.length - 1;
877
- let i = t.findIndex((e) => e.msgId === r.selectedId);
878
- return i === -1 ? t.length - 1 : i;
879
- }
880
- getSiblings(e) {
881
- return this._tree.getSiblings(e);
882
- }
883
- hasSiblings(e) {
884
- return this._tree.hasSiblings(e);
1562
+ selectedKey: i.memberNodeKey
1563
+ }), this._logger.debug("DefaultView.selectSibling(); fork-of", {
1564
+ codecMessageId: e,
1565
+ index: r,
1566
+ selectedKey: i.memberNodeKey
1567
+ })) : n.kind === "non-head-regen" ? (this._nonHeadRegenSelections.set(n.groupRoot, {
1568
+ kind: "user",
1569
+ selectedRunId: i.memberNodeKey
1570
+ }), this._logger.debug("DefaultView.selectSibling(); non-head-regen", {
1571
+ codecMessageId: e,
1572
+ index: r,
1573
+ selectedRunId: i.memberNodeKey,
1574
+ anchor: n.groupRoot
1575
+ })) : (this._regenSelections.set(n.groupRoot, {
1576
+ kind: "user",
1577
+ selectedRunId: i.memberNodeKey
1578
+ }), this._logger.debug("DefaultView.selectSibling(); regenerate", {
1579
+ codecMessageId: e,
1580
+ index: r,
1581
+ selectedRunId: i.memberNodeKey,
1582
+ groupRoot: n.groupRoot
1583
+ })), this._recomputeAndEmit());
1584
+ }
1585
+ _resolveSelectedIndex(e) {
1586
+ if (e.kind === "fork-of") {
1587
+ let t = this._branchSelections.get(e.groupRoot);
1588
+ if (!t) return e.members.length - 1;
1589
+ let n = e.members.findIndex((e) => e.memberNodeKey === t.selectedKey);
1590
+ return n === -1 ? e.members.length - 1 : n;
1591
+ }
1592
+ let t = e.kind === "non-head-regen" ? this._nonHeadRegenSelections.get(e.groupRoot) : this._regenSelections.get(e.groupRoot);
1593
+ if (!t || t.kind === "pending") return e.members.length - 1;
1594
+ let n = e.members.findIndex((e) => e.memberNodeKey === t.selectedRunId);
1595
+ return n === -1 ? e.members.length - 1 : n;
885
1596
  }
886
- getNode(e) {
887
- return this._tree.getNode(e);
1597
+ _resolveMessageBranchPoint(e) {
1598
+ let t = this._tree.getNodeByCodecMessageId(e);
1599
+ if (!t) return;
1600
+ if (t.kind === "input") {
1601
+ let e = this._tree.getSiblingNodes(t.codecMessageId);
1602
+ return e.length > 1 ? {
1603
+ kind: "fork-of",
1604
+ groupRoot: this._tree.getGroupRoot(t.codecMessageId),
1605
+ members: this._nodeHeadMembers(e)
1606
+ } : void 0;
1607
+ }
1608
+ let n = this._codec.getMessages(t.projection), r = this._resolveNonHeadBranchPoint(t, n, e);
1609
+ if (r) return r;
1610
+ let i = this._tree.getSiblingNodes(t.runId);
1611
+ if (i.length > 1 && n.at(0)?.codecMessageId === e) return {
1612
+ kind: "regen",
1613
+ groupRoot: this._tree.getGroupRoot(t.runId),
1614
+ members: this._nodeHeadMembers(i)
1615
+ };
888
1616
  }
889
- async send(t, n) {
890
- if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", C.InvalidArgument, 400);
891
- let r = this.flattenNodes(), i = await this._sendDelegate(t, n, r);
892
- if (n?.forkOf) {
893
- let e = this._tree.getGroupRoot(n.forkOf);
894
- if (i.optimisticMsgIds.length > 0) {
895
- let t = i.optimisticMsgIds.at(-1);
896
- t && (this._branchSelections.set(e, {
897
- kind: "auto",
898
- selectedId: t
899
- }), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
900
- } else {
901
- this._branchSelections.set(e, {
902
- kind: "pending",
903
- turnId: i.turnId
904
- }), this._logger.debug("DefaultView.send(); deferring fork auto-selection", {
905
- forkOf: n.forkOf,
906
- groupRoot: e,
907
- turnId: i.turnId
908
- });
909
- let t = this._tree.on("turn", (n) => {
910
- if (n.type !== "x-ably-turn-end" || n.turnId !== i.turnId) return;
911
- let r = this._branchSelections.get(e);
912
- r?.kind === "pending" && r.turnId === i.turnId && this._branchSelections.delete(e), t();
913
- let a = this._unsubs.indexOf(t);
914
- a !== -1 && this._unsubs.splice(a, 1);
915
- });
916
- this._unsubs.push(t);
1617
+ _resolveNonHeadBranchPoint(e, t, n) {
1618
+ if (t.at(0)?.codecMessageId === n && e.regeneratesCodecMessageId !== void 0) {
1619
+ let t = e.regeneratesCodecMessageId, n = this._runByCodecMessageId(t);
1620
+ if (n) {
1621
+ let e = this._codec.getMessages(n.projection), r = e.findIndex((e) => e.codecMessageId === t), i = r > 0 ? e[r - 1]?.codecMessageId : void 0;
1622
+ if (i !== void 0) return this._buildNonHeadGroup(t, n.runId, i);
917
1623
  }
1624
+ return;
1625
+ }
1626
+ let r = t.findIndex((e) => e.codecMessageId === n), i = r > 0 ? t[r - 1]?.codecMessageId : void 0;
1627
+ if (i !== void 0) return this._buildNonHeadGroup(n, e.runId, i);
1628
+ }
1629
+ _buildNonHeadGroup(e, t, n) {
1630
+ let r = this._nonHeadRegenerators(e, n);
1631
+ if (r.length === 0) return;
1632
+ let i = [{
1633
+ memberNodeKey: t,
1634
+ representativeCodecMessageId: e
1635
+ }];
1636
+ for (let e of r) {
1637
+ let t = this._codec.getMessages(e.projection).at(0);
1638
+ t && i.push({
1639
+ memberNodeKey: e.runId,
1640
+ representativeCodecMessageId: t.codecMessageId
1641
+ });
1642
+ }
1643
+ return {
1644
+ kind: "non-head-regen",
1645
+ groupRoot: e,
1646
+ members: i
1647
+ };
1648
+ }
1649
+ _nodeHeadMembers(e) {
1650
+ let t = [];
1651
+ for (let n of e) {
1652
+ let e = this._codec.getMessages(n.projection).at(0);
1653
+ e && t.push({
1654
+ memberNodeKey: q(n),
1655
+ representativeCodecMessageId: e.codecMessageId
1656
+ });
1657
+ }
1658
+ return t;
1659
+ }
1660
+ async send(t, n) {
1661
+ if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", E.InvalidArgument, 400);
1662
+ let r = Je(t), i = this._lastVisibleMessagePairs.at(-1)?.codecMessageId, a = await this._sendDelegate(r, n, i);
1663
+ return this._applyForkAutoSelect(a, n), a;
1664
+ }
1665
+ _applyForkAutoSelect(e, t) {
1666
+ if (!t?.forkOf) return;
1667
+ let n = e.optimisticCodecMessageIds.at(0);
1668
+ if (n === void 0) return;
1669
+ let r = this._tree.getGroupRoot(n);
1670
+ this._branchSelections.set(r, {
1671
+ kind: "auto",
1672
+ selectedKey: n
1673
+ }), this._recomputeAndEmit();
1674
+ }
1675
+ _applyRegenerateAutoSelect(e, t) {
1676
+ let n = this._runByCodecMessageId(t);
1677
+ if (!n) return;
1678
+ if (this._codec.getMessages(n.projection).at(0)?.codecMessageId !== t) {
1679
+ this._nonHeadRegenSelections.set(t, {
1680
+ kind: "pending",
1681
+ carrierCodecMessageId: e.inputCodecMessageId
1682
+ }), this._logger.debug("DefaultView._applyRegenerateAutoSelect(); deferring non-head regenerate selection", {
1683
+ anchorCodecMessageId: t,
1684
+ carrier: e.inputCodecMessageId
1685
+ }), this._resolvePendingNonHeadRegenSelections(), this._recomputeAndEmitIfChanged();
1686
+ return;
918
1687
  }
919
- return i;
1688
+ let r = this._tree.getGroupRoot(n.runId);
1689
+ this._regenSelections.set(r, {
1690
+ kind: "pending",
1691
+ carrierCodecMessageId: e.inputCodecMessageId
1692
+ }), this._logger.debug("DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection", {
1693
+ anchorCodecMessageId: t,
1694
+ groupRoot: r,
1695
+ carrier: e.inputCodecMessageId
1696
+ }), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged();
920
1697
  }
921
1698
  async regenerate(t, n) {
922
- this._logger.trace("DefaultView.regenerate();", { messageId: t });
923
- let r = this._tree.getNode(t);
924
- if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, C.InvalidArgument, 400);
925
- let i = r.parentId;
926
- return this.send([], {
1699
+ if (this._logger.trace("DefaultView.regenerate();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to regenerate; view is closed", E.InvalidArgument, 400);
1700
+ let r = this._runByCodecMessageId(t);
1701
+ if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, E.InvalidArgument, 400);
1702
+ let i = this._findParentMsgId(r, t);
1703
+ if (!i) throw new e.ErrorInfo(`unable to regenerate; parent user message not found for ${t}`, E.InvalidArgument, 400);
1704
+ let a = t;
1705
+ r.regeneratesCodecMessageId !== void 0 && this._codec.getMessages(r.projection).at(0)?.codecMessageId === t && (a = r.regeneratesCodecMessageId);
1706
+ let o = {
927
1707
  ...n,
928
- body: {
929
- history: this._getHistoryBefore(t),
930
- ...n?.body
931
- },
932
- forkOf: t,
933
1708
  parent: i
934
- });
1709
+ }, s = this._codec.createRegenerate(a, i), c = await this._sendDelegate([s], o, i);
1710
+ return this._applyRegenerateAutoSelect(c, a), c;
935
1711
  }
936
1712
  async edit(t, n, r) {
937
- this._logger.trace("DefaultView.edit();", { messageId: t });
938
- let i = this._tree.getNode(t);
939
- if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, C.InvalidArgument, 400);
940
- let a = i.parentId;
1713
+ if (this._logger.trace("DefaultView.edit();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to edit; view is closed", E.InvalidArgument, 400);
1714
+ let i = this._tree.getNodeByCodecMessageId(t);
1715
+ if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, E.InvalidArgument, 400);
1716
+ let a = this._findParentMsgId(i, t);
941
1717
  return this.send(n, {
942
1718
  ...r,
943
- body: {
944
- history: this._getHistoryBefore(t),
945
- ...r?.body
946
- },
947
1719
  forkOf: t,
948
1720
  parent: a
949
1721
  });
950
1722
  }
951
- async update(t, n, r) {
952
- if (this._closed) throw new e.ErrorInfo("unable to update; view is closed", C.InvalidArgument, 400);
953
- this._logger.trace("DefaultView.update();", {
954
- msgId: t,
955
- eventCount: n.length
956
- });
957
- let i = [{
958
- kind: "event",
959
- msgId: t,
960
- events: n
961
- }];
962
- return this._sendDelegate([], r, this.flattenNodes(), i);
963
- }
964
- _getHistoryBefore(e) {
965
- this._logger.trace("DefaultView._getHistoryBefore();", { messageId: e });
966
- let t = this.flattenNodes(), n = t.findIndex((t) => t.msgId === e);
967
- return n === -1 ? (this._logger.warn("DefaultView._getHistoryBefore(); target not in visible nodes, returning full list", { messageId: e }), t) : t.slice(0, n);
968
- }
969
- getActiveTurnIds() {
970
- this._logger.trace("DefaultView.getActiveTurnIds();");
971
- let e = this._tree.getActiveTurnIds();
972
- if (this._withheldMsgIds.size === 0) return e;
973
- let t = /* @__PURE__ */ new Map();
974
- for (let [n, r] of e) {
975
- let e = /* @__PURE__ */ new Set();
976
- for (let t of r) this._lastVisibleTurnIds.has(t) && e.add(t);
977
- e.size > 0 && t.set(n, e);
1723
+ _findParentMsgId(e, t) {
1724
+ let n = this._lastVisibleMessagePairs, r = n.findIndex((e) => e.codecMessageId === t);
1725
+ if (r > 0) return n[r - 1]?.codecMessageId;
1726
+ if (r === 0) return;
1727
+ let i = this._codec.getMessages(e.projection), a = i.findIndex((e) => e.codecMessageId === t);
1728
+ if (a > 0) return i[a - 1]?.codecMessageId;
1729
+ if (a === 0 && e.parentCodecMessageId !== void 0) {
1730
+ let t = this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);
1731
+ if (t) return this._codec.getMessages(t.projection).at(-1)?.codecMessageId;
978
1732
  }
979
- return t;
980
1733
  }
981
1734
  on(e, t) {
982
1735
  let n = t;
@@ -985,35 +1738,29 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
985
1738
  };
986
1739
  }
987
1740
  close() {
988
- this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
989
- for (let e of this._unsubs) e();
990
- this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._withheldMsgIds.clear(), this._withheldBuffer.length = 0, this._onClose?.();
1741
+ if (!this._closed) {
1742
+ this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
1743
+ for (let e of this._unsubs) e();
1744
+ this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._regenSelections.clear(), this._nonHeadRegenSelections.clear(), this._withheldRunIds.clear(), this._withheldBuffer.length = 0, this._hiddenMessageCount = 0, this._onClose?.();
1745
+ }
991
1746
  }
992
1747
  async _loadFirstPage(e) {
993
- let t = new Set(this._tree.flattenNodes(this._resolveSelections()).map((e) => e.msgId)), n = await ce(this._channel, this._codec, { limit: e }, this._logger);
994
- if (this._closed) return;
995
- let { newVisible: r, lastPage: i } = await this._loadUntilVisible(n, e, t);
996
- if (this._closed) return;
997
- this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext();
998
- let a = r.slice(-e), o = r.slice(0, -e);
999
- for (let e of o) this._withheldMsgIds.add(e.msgId);
1000
- this._withheldBuffer.push(...o), this._releaseWithheld(a);
1001
- }
1002
- async _loadAndReveal(e, t) {
1003
- let n = new Set(this._tree.flattenNodes(this._resolveSelections()).map((e) => e.msgId)), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
1004
- if (this._closed) return;
1005
- this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext();
1006
- let a = r.slice(-t), o = r.slice(0, -t);
1007
- for (let e of o) this._withheldMsgIds.add(e.msgId);
1008
- this._withheldBuffer.push(...o), this._releaseWithheld(a);
1748
+ let t = await qe(this._channel, { limit: e }, this._logger);
1749
+ this._closed || await this._revealFromPage(t, e);
1750
+ }
1751
+ async _revealFromPage(e, t) {
1752
+ let n = new Set(this._treeVisibleNodes().map((e) => q(e))), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
1753
+ this._closed || (this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext(), this._splitReveal(r, t));
1754
+ }
1755
+ _splitReveal(e, t) {
1756
+ let n = this._messageTailSplitIndex(e, t), r = e.slice(n), i = e.slice(0, n);
1757
+ for (let e of i) this._withheldRunIds.add(q(e));
1758
+ this._withheldBuffer.push(...i), this._releaseWithheld(r);
1009
1759
  }
1010
1760
  _processHistoryPage(e) {
1011
1761
  this._processingHistory = !0;
1012
1762
  try {
1013
- for (let t of e.items) {
1014
- let e = t.headers[o];
1015
- e && this._tree.upsert(e, t.message, t.headers, t.serial);
1016
- }
1763
+ for (let t of e.rawMessages) this._applier.apply(t);
1017
1764
  for (let t of e.rawMessages) this._tree.emitAblyMessage(t);
1018
1765
  } finally {
1019
1766
  this._processingHistory = !1;
@@ -1023,7 +1770,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1023
1770
  this._processHistoryPage(e);
1024
1771
  let r = e, i = () => {
1025
1772
  let e = 0;
1026
- for (let t of this._tree.flattenNodes(this._resolveSelections())) n.has(t.msgId) || e++;
1773
+ for (let t of this._treeVisibleNodes()) n.has(q(t)) || (e += this._codec.getMessages(t.projection).length);
1027
1774
  return e;
1028
1775
  };
1029
1776
  for (; i() < t && r.hasNext();) {
@@ -1032,586 +1779,313 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1032
1779
  this._processHistoryPage(e), r = e;
1033
1780
  }
1034
1781
  return {
1035
- newVisible: this._tree.flattenNodes(this._resolveSelections()).filter((e) => !n.has(e.msgId)),
1782
+ newVisible: this._treeVisibleNodes().filter((e) => !n.has(q(e))),
1036
1783
  lastPage: r
1037
1784
  };
1038
1785
  }
1039
1786
  _releaseWithheld(e) {
1040
- for (let t of e) this._withheldMsgIds.delete(t.msgId);
1041
- e.length > 0 && (this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
1787
+ for (let t of e) this._withheldRunIds.delete(q(t));
1788
+ e.length > 0 && this._recomputeAndEmit();
1042
1789
  }
1043
1790
  _updateVisibleSnapshot(e) {
1044
- let t = e ?? this.flattenNodes();
1045
- this._lastVisibleIds = t.map((e) => e.msgId), this._lastVisibleMessages = t.map((e) => e.message), this._lastVisibleTurnIds = /* @__PURE__ */ new Set();
1046
- for (let e of t) {
1047
- let t = e.headers[a];
1048
- t && this._lastVisibleTurnIds.add(t);
1049
- }
1791
+ let t = e ?? this._cachedNodes;
1792
+ this._lastVisibleNodeKeys = t.map((e) => q(e)), this._lastVisibleNodeKeySet = new Set(this._lastVisibleNodeKeys), this._lastVisibleProjections = t.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(t).slice(this._hiddenMessageCount);
1050
1793
  }
1051
1794
  _onTreeUpdate() {
1052
- if (this._processingHistory) return;
1053
- let e = this._tree.structuralVersion;
1054
- if (e === this._lastStructuralVersion) {
1055
- 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"));
1056
- return;
1057
- }
1058
- this._lastStructuralVersion = e, this._pinBranchSelections(), this._resolvePendingSelections();
1059
- let t = this._computeFlatNodes(), n = t.map((e) => e.msgId), r = t.map((e) => e.message);
1060
- this._visibleChanged(n, r) && (this._cachedNodes = t, this._updateVisibleSnapshot(t), this._emitter.emit("update"));
1795
+ this._processingHistory || (this._pinBranchSelections(), this._resolvePendingRegenSelections(), this._resolvePendingNonHeadRegenSelections(), this._recomputeAndEmitIfChanged());
1061
1796
  }
1062
1797
  _resolveSelections() {
1063
1798
  let e = /* @__PURE__ */ new Map();
1064
- for (let [t, n] of this._branchSelections) n.kind !== "pending" && e.set(t, n.selectedId);
1799
+ for (let [t, n] of this._branchSelections) e.set(t, n.selectedKey);
1800
+ for (let [t, n] of this._regenSelections) n.kind !== "pending" && e.set(t, n.selectedRunId);
1065
1801
  return e;
1066
1802
  }
1803
+ _treeVisibleNodes() {
1804
+ return this._tree.visibleNodes(this._resolveSelections());
1805
+ }
1067
1806
  _pinBranchSelections() {
1068
- for (let e of this._lastVisibleIds) {
1069
- if (!this._tree.hasSiblings(e)) continue;
1070
- let t = this._tree.getGroupRoot(e), n = this._branchSelections.get(t);
1071
- if (n?.kind === "pending") {
1072
- let r = this._tree.getSiblingNodes(e).at(-1);
1073
- r && r.msgId !== e && r.headers["x-ably-turn-id"] === n.turnId && (this._logger.debug("DefaultView._pinBranchSelections(); auto-selecting pending fork", {
1074
- msgId: e,
1075
- newestId: r.msgId,
1076
- turnId: n.turnId
1077
- }), this._branchSelections.set(t, {
1078
- kind: "auto",
1079
- selectedId: r.msgId
1080
- }));
1081
- continue;
1082
- }
1083
- n || this._branchSelections.set(t, {
1807
+ for (let e of this._lastVisibleNodeKeys) {
1808
+ if (this._tree.getNode(e)?.kind !== "input" || this._tree.getSiblingNodes(e).length <= 1) continue;
1809
+ let t = this._tree.getGroupRoot(e);
1810
+ this._branchSelections.get(t) || this._branchSelections.set(t, {
1084
1811
  kind: "pinned",
1085
- selectedId: e
1812
+ selectedKey: e
1086
1813
  });
1087
1814
  }
1088
1815
  }
1089
- _resolvePendingSelections() {
1090
- for (let [e, t] of this._branchSelections) {
1091
- if (t.kind !== "pending") continue;
1092
- let n = this._tree.getSiblingNodes(e);
1816
+ _resolvePendingRegenSelections() {
1817
+ for (let [e, t] of this._regenSelections) {
1818
+ if (t.kind === "user") continue;
1819
+ let n = this._tree.getSiblingNodes(e).filter((e) => e.kind === "run");
1093
1820
  if (n.length <= 1) continue;
1094
1821
  let r = n.at(-1);
1095
- !r || r.msgId === e || r.headers["x-ably-turn-id"] === t.turnId && (this._logger.debug("DefaultView._resolvePendingSelections(); resolving off-branch pending", {
1096
- groupRoot: e,
1097
- newestId: r.msgId,
1098
- turnId: t.turnId
1099
- }), this._branchSelections.set(e, {
1822
+ r && this._regenSelections.set(e, {
1100
1823
  kind: "auto",
1101
- selectedId: r.msgId
1102
- }));
1824
+ selectedRunId: r.runId
1825
+ });
1826
+ }
1827
+ }
1828
+ _resolvePendingNonHeadRegenSelections() {
1829
+ for (let [e, t] of this._nonHeadRegenSelections) {
1830
+ if (t.kind === "user") continue;
1831
+ let n = this._runByCodecMessageId(e);
1832
+ if (!n) continue;
1833
+ let r = this._codec.getMessages(n.projection), i = r.findIndex((t) => t.codecMessageId === e), a = i > 0 ? r[i - 1]?.codecMessageId : void 0;
1834
+ if (a === void 0) continue;
1835
+ let o = this._nonHeadRegenerators(e, a).at(-1);
1836
+ o && this._nonHeadRegenSelections.set(e, {
1837
+ kind: "auto",
1838
+ selectedRunId: o.runId
1839
+ });
1103
1840
  }
1104
1841
  }
1105
1842
  _onTreeAblyMessage(e) {
1106
- let t = w(e)[o];
1107
- if (!t) {
1843
+ let t = P(e), n = t[l], r = t[o];
1844
+ if (!n && !r) {
1108
1845
  this._emitter.emit("ably-message", e);
1109
1846
  return;
1110
1847
  }
1111
- this._lastVisibleIds.includes(t) && this._emitter.emit("ably-message", e);
1848
+ r && this._lastVisibleNodeKeySet.has(r) && this._emitter.emit("ably-message", e);
1112
1849
  }
1113
- _onTreeTurn(e) {
1114
- if (this._lastVisibleTurnIds.has(e.turnId)) {
1115
- this._emitter.emit("turn", e);
1850
+ _onTreeRun(e) {
1851
+ if (this._lastVisibleNodeKeySet.has(e.runId)) {
1852
+ this._emitter.emit("run", e);
1116
1853
  return;
1117
1854
  }
1118
- e.type === "x-ably-turn-start" && this._isTurnStartVisible(e) && (this._lastVisibleTurnIds.add(e.turnId), this._emitter.emit("turn", e));
1855
+ e.type === "start" && this._isRunStartVisible(e) && (this._lastVisibleNodeKeySet.add(e.runId), this._emitter.emit("run", e));
1119
1856
  }
1120
- _isTurnStartVisible(e) {
1857
+ _isRunStartVisible(e) {
1121
1858
  let { parent: t } = e;
1122
- return t === void 0 ? !0 : this._lastVisibleIds.includes(t);
1859
+ if (t === void 0) return !0;
1860
+ let n = this._tree.getNodeByCodecMessageId(t);
1861
+ return n ? this._lastVisibleNodeKeySet.has(q(n)) : !0;
1123
1862
  }
1124
- _visibleChanged(e, t) {
1125
- if (e.length !== this._lastVisibleIds.length) return !0;
1126
- for (let [t, n] of e.entries()) if (n !== this._lastVisibleIds[t]) return !0;
1127
- for (let [e, n] of t.entries()) if (n !== this._lastVisibleMessages[e]) return !0;
1863
+ _visibleChanged(e) {
1864
+ if (e.length !== this._lastVisibleNodeKeys.length) return !0;
1865
+ for (let [t, n] of e.entries()) if (q(n) !== this._lastVisibleNodeKeys[t] || n.projection !== this._lastVisibleProjections[t]) return !0;
1128
1866
  return !1;
1129
1867
  }
1130
- }, Z = (e) => new le(e), ue = () => {}, Q = /* @__PURE__ */ function(e) {
1131
- return e.READY = "ready", e.CLOSED = "closed", e;
1132
- }(Q || {}), de = class {
1868
+ }, Xe = (e) => new Ye(e), Ze = () => {}, Qe = class {
1133
1869
  constructor(e) {
1134
- 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 = Q.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 ?? B({ logLevel: R.Silent })).withContext({ component: "ClientTransport" }), this._emitter = new L(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = q(this._logger), this._view = Z({
1870
+ this._views = /* @__PURE__ */ new Set(), this._state = "ready", this._pendingRunStarts = /* @__PURE__ */ new Map();
1871
+ let t = G(e.client, e.codec), n = se(e.channelModes);
1872
+ if (n && (t.modes = n), this._channel = e.client.channels.get(e.channelName, t), this._client = e.client, this._codec = e.codec, this._logger = (e.logger ?? k({ logLevel: D.Silent })).withContext({ component: "ClientSession" }), this._emitter = new K(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = Be(this._codec, this._logger), this._applier = Se(this._tree, this._codec.createDecoder()), this._view = Xe({
1135
1873
  tree: this._tree,
1136
1874
  channel: this._channel,
1137
1875
  codec: this._codec,
1876
+ applier: this._applier,
1138
1877
  sendDelegate: this._internalSend.bind(this),
1139
1878
  logger: this._logger,
1140
1879
  onClose: () => this._views.delete(this._view)
1141
- }), this._router = G(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) {
1880
+ }), this._encoder = this._codec.createEncoder(this._channel), this._views.add(this._view), this.tree = this._tree, this.view = this._view, e.messages) {
1142
1881
  let t;
1143
1882
  for (let n of e.messages) {
1144
- let e = crypto.randomUUID(), r = { [o]: e };
1145
- t && (r[m] = t), this._tree.upsert(e, n, r), t = e;
1883
+ let e = crypto.randomUUID(), r = {
1884
+ [l]: e,
1885
+ [f]: "user"
1886
+ };
1887
+ t && (r[p] = t), this._tree.applyMessage({
1888
+ inputs: [this._codec.createUserMessage(n)],
1889
+ outputs: []
1890
+ }, r), t = e;
1146
1891
  }
1147
1892
  }
1148
1893
  this._onMessage = (e) => {
1149
1894
  this._handleMessage(e);
1150
- }, this._attachPromise = this._channel.subscribe(this._onMessage), this._onChannelStateChange = (e) => {
1895
+ }, this._onChannelStateChange = (e) => {
1151
1896
  this._handleChannelStateChange(e);
1152
1897
  }, this._channel.on(this._onChannelStateChange);
1153
1898
  }
1899
+ get presence() {
1900
+ return this._channel.presence;
1901
+ }
1902
+ get object() {
1903
+ return this._channel.object;
1904
+ }
1905
+ connect() {
1906
+ return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", E.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger.trace("DefaultClientSession.connect();"), this._connectPromise = this._channel.subscribe(this._onMessage).then(() => {
1907
+ this._logger.debug("DefaultClientSession.connect(); subscribed and attached");
1908
+ }, (t) => {
1909
+ let n = new e.ErrorInfo(`unable to subscribe to channel; ${j(t)}`, E.SessionSubscriptionError, 500, M(t));
1910
+ throw this._logger.error("DefaultClientSession.connect(); subscribe failed"), this._emitter.emit("error", n), n;
1911
+ }), this._connectPromise);
1912
+ }
1913
+ _resolveClientId() {
1914
+ let e = this._client.auth.clientId;
1915
+ return e && e !== "*" ? e : void 0;
1916
+ }
1917
+ async _requireConnected(e) {
1918
+ return Oe(this._connectPromise, e);
1919
+ }
1154
1920
  _handleMessage(t) {
1155
- if (this._state !== Q.CLOSED) try {
1156
- if (t.name === "x-ably-turn-start") {
1157
- let e = w(t), n = e[a], r = e["x-ably-turn-client-id"] ?? "";
1158
- if (n) {
1159
- this._tree.trackTurn(n, r);
1160
- let t = e[m], i = e[h];
1161
- this._tree.emitTurn({
1162
- type: v,
1163
- turnId: n,
1164
- clientId: r,
1165
- ...t !== void 0 && { parent: t },
1166
- ...i !== void 0 && { forkOf: i }
1167
- });
1921
+ if (this._state !== "closed") try {
1922
+ if (t.name === "ai-run-end") {
1923
+ let e = P(t);
1924
+ if ((e["run-reason"] ?? "complete") === "error") {
1925
+ let t = ye(e);
1926
+ this._logger.error("ClientSession._handleMessage(); agent error received", {
1927
+ runId: e[o],
1928
+ invocationId: e[s],
1929
+ code: t.code
1930
+ }), this._emitter.emit("error", t);
1168
1931
  }
1169
- this._tree.emitAblyMessage(t);
1170
- return;
1171
1932
  }
1172
- if (t.name === "x-ably-turn-end") {
1173
- let e = w(t), n = e[a], r = e["x-ably-turn-client-id"] ?? "", i = e["x-ably-turn-reason"] ?? "complete";
1174
- if (n) {
1175
- this._router.closeStream(n), this._turnObservers.delete(n), this._tree.untrackTurn(n);
1176
- let e = this._turnMsgIds.get(n);
1177
- if (e) {
1178
- for (let t of e) this._ownMsgIds.delete(t);
1179
- this._turnMsgIds.delete(n);
1180
- }
1181
- this._ownTurnIds.delete(n), this._tree.emitTurn({
1182
- type: y,
1183
- turnId: n,
1184
- clientId: r,
1185
- reason: i
1186
- });
1933
+ let e = this._applier.apply(t);
1934
+ if (e && (e.type === "start" || e.type === "resume")) {
1935
+ let n = P(t)[_];
1936
+ if (n !== void 0) {
1937
+ let t = this._pendingRunStarts.get(n);
1938
+ t && (this._pendingRunStarts.delete(n), t.resolve(e.runId));
1187
1939
  }
1188
- this._tree.emitAblyMessage(t);
1189
- return;
1190
- }
1191
- let e = this._decoder.decode(t), n = w(t), r = t.serial, i = n[l];
1192
- if (i) {
1193
- for (let t of e) t.kind === "event" && this._handleAmendmentEvent(i, t);
1194
- return;
1195
1940
  }
1196
- let o = n[a];
1197
- o && this._updateTurnObserverHeaders(o, n, r);
1198
- for (let i of e) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, t.action) : this._handleEventOutput(i, n);
1199
1941
  this._tree.emitAblyMessage(t);
1200
1942
  } catch (t) {
1201
- let n = t instanceof e.ErrorInfo ? t : void 0;
1202
- this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, C.TransportSubscriptionError, 500, n));
1203
- }
1204
- }
1205
- _handleMessageOutput(e, t, n, r) {
1206
- let i = t[o];
1207
- if (i && this._ownMsgIds.has(i)) {
1208
- this._upsertAndNotify(e, t, n);
1209
- return;
1210
- }
1211
- r === "message.create" && this._upsertAndNotify(e, t, n);
1212
- }
1213
- _handleEventOutput(e, t) {
1214
- if (e.kind !== "event") return;
1215
- let n = e.event, r = t[a];
1216
- if (r) {
1217
- if (this._router.route(r, n)) {
1218
- this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r);
1219
- return;
1220
- }
1221
- this._ownTurnIds.has(r) && !this._turnObservers.has(r) || (this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r));
1222
- }
1223
- }
1224
- _handleAmendmentEvent(e, t) {
1225
- this._logger.trace("ClientTransport._handleAmendmentEvent();", { targetMsgId: e });
1226
- let n = this._tree.getNode(e);
1227
- if (!n) {
1228
- this._logger.debug("ClientTransport._handleAmendmentEvent(); target not found, dropping", { targetMsgId: e });
1229
- return;
1943
+ this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${j(t)}`, E.SessionSubscriptionError, 500, M(t)));
1230
1944
  }
1231
- let r = this._codec.createAccumulator();
1232
- r.initMessage(e, n.message), r.processOutputs([t]);
1233
- let i = r.messages.at(-1);
1234
- i && this._tree.upsert(e, i, n.headers, n.serial);
1235
1945
  }
1236
- _handleChannelStateChange(t) {
1237
- if (this._state === Q.CLOSED) return;
1238
- let { current: n, resumed: r } = t;
1239
- if (n === "attached" && !this._hasAttachedOnce) {
1946
+ _handleChannelStateChange(e) {
1947
+ if (this._state === "closed") return;
1948
+ let { current: t, resumed: n } = e;
1949
+ if (t === "attached" && !this._hasAttachedOnce) {
1240
1950
  this._hasAttachedOnce = !0;
1241
1951
  return;
1242
1952
  }
1243
- if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
1244
- this._logger.error("ClientTransport._handleChannelStateChange(); channel continuity lost", {
1245
- current: n,
1246
- resumed: r,
1247
- previous: t.previous
1248
- });
1249
- let i = new e.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, C.ChannelContinuityLost, 500, t.reason);
1250
- for (let e of this._ownTurnIds) this._router.errorStream(e, i);
1251
- this._emitter.emit("error", i);
1252
- }
1253
- _upsertAndNotify(e, t, n) {
1254
- let r = t[o];
1255
- r && this._tree.upsert(r, e, t, n);
1256
- }
1257
- _updateTurnObserverHeaders(e, t, n) {
1258
- let r = this._turnObservers.get(e);
1259
- r ? (Object.keys(t).length > 0 && Object.assign(r.headers, t), n !== void 0 && (r.serial = n)) : this._turnObservers.set(e, {
1260
- headers: { ...t },
1261
- serial: n,
1262
- accumulator: this._codec.createAccumulator()
1263
- });
1264
- }
1265
- _accumulateAndEmit(e, t) {
1266
- let n = this._turnObservers.get(e);
1267
- if (!n) return;
1268
- let r = n.headers[o];
1269
- if (r) {
1270
- let e = this._tree.getNode(r);
1271
- e && n.accumulator.initMessage(r, e.message);
1272
- }
1273
- n.accumulator.processOutputs([t]);
1274
- let i = n.accumulator.messages;
1275
- if (i.length === 0) return;
1276
- let a;
1277
- try {
1278
- a = structuredClone(i.at(-1));
1279
- } catch {
1280
- a = i.at(-1);
1281
- }
1282
- if (a) {
1283
- let e = n.headers[o];
1284
- e && this._tree.upsert(e, a, { ...n.headers }, n.serial);
1285
- }
1286
- }
1287
- async _publishCancel(e) {
1288
- this._logger.trace("ClientTransport._publishCancel();", { filter: e });
1289
- let t = {};
1290
- e.turnId ? t[u] = e.turnId : e.own ? t[d] = "true" : e.clientId ? t[p] = e.clientId : e.all && (t[f] = "true"), await this._channel.publish({
1291
- name: _,
1292
- extras: { headers: t }
1953
+ if (!Ae(e)) return;
1954
+ this._logger.error("ClientSession._handleChannelStateChange(); channel continuity lost", {
1955
+ current: t,
1956
+ resumed: n,
1957
+ previous: e.previous
1293
1958
  });
1959
+ let r = je(e, "deliver events");
1960
+ this._emitter.emit("error", r);
1294
1961
  }
1295
- _closeMatchingTurnStreams(e) {
1296
- for (let t of this._getMatchingTurnIds(e)) this._router.closeStream(t);
1297
- }
1298
- _getMatchingTurnIds(e) {
1299
- let t = /* @__PURE__ */ new Set(), n = this._tree.getActiveTurnIds();
1300
- if (e.all) for (let e of n.values()) for (let n of e) t.add(n);
1301
- else if (e.own) {
1302
- let e = n.get(this._clientId ?? "");
1303
- if (e) for (let n of e) t.add(n);
1304
- } else if (e.clientId) {
1305
- let r = n.get(e.clientId);
1306
- if (r) for (let e of r) t.add(e);
1307
- } else if (e.turnId) {
1308
- for (let r of n.values()) if (r.has(e.turnId)) {
1309
- t.add(e.turnId);
1310
- break;
1311
- }
1962
+ _cleanupFailedSend(e) {
1963
+ for (let t of e) {
1964
+ let e = this._tree.getNodeByCodecMessageId(t);
1965
+ e?.kind === "input" && e.serial === void 0 && this._tree.delete(e.codecMessageId);
1312
1966
  }
1313
- return t;
1314
1967
  }
1315
1968
  createView() {
1316
- if (this._state === Q.CLOSED) throw new e.ErrorInfo("unable to create view; transport is closed", C.TransportClosed, 400);
1317
- this._logger.trace("DefaultClientTransport.createView();");
1318
- let t = Z({
1969
+ if (this._state === "closed") throw new e.ErrorInfo("unable to create view; session is closed", E.SessionClosed, 400);
1970
+ this._logger.trace("DefaultClientSession.createView();");
1971
+ let t = Xe({
1319
1972
  tree: this._tree,
1320
1973
  channel: this._channel,
1321
1974
  codec: this._codec,
1975
+ applier: this._applier,
1322
1976
  sendDelegate: this._internalSend.bind(this),
1323
1977
  logger: this._logger,
1324
1978
  onClose: () => this._views.delete(t)
1325
1979
  });
1326
1980
  return this._views.add(t), t;
1327
1981
  }
1328
- async _internalSend(t, n, r, i) {
1329
- if (this._state === Q.CLOSED || (await this._attachPromise, this._state === Q.CLOSED)) throw new e.ErrorInfo("unable to send; transport is closed", C.TransportClosed, 400);
1982
+ async _internalSend(n, r, i) {
1983
+ if (this._state === "closed" || (await this._requireConnected("send"), this._state === "closed")) throw new e.ErrorInfo("unable to send; session is closed", E.SessionClosed, 400);
1330
1984
  let a = this._channel.state;
1331
- if (a !== "attached" && a !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${a}`, C.ChannelNotReady, 400);
1332
- this._logger.trace("ClientTransport._internalSend();");
1333
- let o = Array.isArray(t) ? t : [t], s = crypto.randomUUID();
1334
- this._ownTurnIds.add(s), this._tree.trackTurn(s, this._clientId ?? "");
1335
- let c = this._pendingLocalEvents;
1336
- this._pendingLocalEvents = [], i && i.length > 0 && this._applyEventsToTree(i);
1337
- let l = [...c, ...i ?? []], u = /* @__PURE__ */ new Set(), d = [], f = r, p;
1338
- if (n?.parent === void 0 && !n?.forkOf) {
1339
- let e = f.at(-1);
1340
- e && (p = e.msgId);
1341
- }
1342
- let m = n?.parent === void 0 ? p : n.parent;
1343
- for (let e of o) {
1344
- let t = crypto.randomUUID();
1345
- this._ownMsgIds.add(t), u.add(t);
1346
- let r = n?.parent === void 0 ? p : n.parent, i = j({
1985
+ if (a !== "attached" && a !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${a}`, E.ChannelNotReady, 400);
1986
+ this._logger.trace("ClientSession._internalSend();");
1987
+ let o = r?.runId !== void 0, s = r?.runId, c;
1988
+ r?.parent === void 0 && !r?.forkOf && (c = i);
1989
+ let l = /* @__PURE__ */ new Set(), u = [];
1990
+ for (let e of n) {
1991
+ let t = crypto.randomUUID(), n = e.codecMessageId ?? crypto.randomUUID();
1992
+ l.add(n);
1993
+ let i = e.kind !== "user-message" && (e.kind === "regenerate" || e.codecMessageId !== void 0), a = e.parent ?? (r?.parent === void 0 ? c : r.parent), o = r?.forkOf, d = e.kind === "regenerate" ? e.target : void 0, f = ge({
1347
1994
  role: "user",
1348
- turnId: s,
1349
- msgId: t,
1350
- turnClientId: this._clientId,
1351
- parent: r,
1352
- forkOf: n?.forkOf
1995
+ runId: s,
1996
+ codecMessageId: n,
1997
+ runClientId: this._resolveClientId(),
1998
+ ...a !== void 0 && { parent: a },
1999
+ ...o !== void 0 && { forkOf: o },
2000
+ ...d !== void 0 && { regenerates: d },
2001
+ inputEventId: t
2002
+ });
2003
+ i || this._tree.applyMessage({
2004
+ inputs: [e],
2005
+ outputs: []
2006
+ }, f), u.push({
2007
+ input: e,
2008
+ codecMessageId: n,
2009
+ inputEventId: t,
2010
+ headers: f,
2011
+ isWireOnly: i
2012
+ }), !i && r?.parent === void 0 && !r?.forkOf && e.parent === void 0 && (c = n);
2013
+ }
2014
+ let d = u.at(-1);
2015
+ if (d === void 0) throw new e.ErrorInfo("unable to send; inputs array is empty (include at least one input)", E.InvalidArgument, 400);
2016
+ let f = d.inputEventId, p = d.codecMessageId, m = new Promise((e, t) => {
2017
+ this._pendingRunStarts.set(p, {
2018
+ resolve: e,
2019
+ reject: t
1353
2020
  });
1354
- this._upsertAndNotify(e, i), d.push({
1355
- kind: "message",
1356
- message: e,
1357
- msgId: t,
1358
- parentId: r,
1359
- forkOf: n?.forkOf,
1360
- headers: i,
1361
- serial: void 0
1362
- }), n?.parent === void 0 && !n?.forkOf && (p = t);
1363
- }
1364
- this._turnMsgIds.set(s, u);
1365
- let h = this._router.createStream(s), g = this._headersFn?.() ?? {}, _ = {
1366
- ...this._bodyFn?.() ?? {},
1367
- history: f,
1368
- ...n?.body,
1369
- turnId: s,
1370
- clientId: this._clientId,
1371
- messages: d,
1372
- ...n?.forkOf !== void 0 && { forkOf: n.forkOf },
1373
- ...m !== void 0 && { parent: m },
1374
- ...l.length > 0 && { events: l }
1375
- }, v = {
1376
- ...g,
1377
- ...n?.headers
1378
- };
1379
- return this._fetchFn(this._api, {
1380
- method: "POST",
1381
- headers: {
1382
- "Content-Type": "application/json",
1383
- ...v
1384
- },
1385
- body: JSON.stringify(_),
1386
- ...this._credentials ? { credentials: this._credentials } : {}
1387
- }).then((t) => {
1388
- if (!t.ok) {
1389
- let n = new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(t.status)} ${t.statusText}`, C.TransportSendFailed, t.status);
1390
- this._emitter.emit("error", n), this._router.errorStream(s, n);
2021
+ });
2022
+ return m.catch(() => {}), await (async () => {
2023
+ try {
2024
+ for (let e of u) await this._encoder.publishInput(e.input, {
2025
+ extras: { headers: e.headers },
2026
+ messageId: e.codecMessageId
2027
+ });
2028
+ } catch (t) {
2029
+ let n = M(t), r = n?.statusCode === 401 || n?.statusCode === 403, i = new e.ErrorInfo(r ? "unable to publish events; missing publish capability on the channel" : `unable to publish events; ${j(t)}`, r ? E.InsufficientCapability : E.SessionSendFailed, r ? 401 : 500, n);
2030
+ throw this._emitter.emit("error", i), this._pendingRunStarts.delete(p), o || this._cleanupFailedSend([...l]), i;
1391
2031
  }
1392
- }).catch((t) => {
1393
- let n = t instanceof e.ErrorInfo ? t : void 0, r = new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} failed: ${t instanceof Error ? t.message : String(t)}`, C.TransportSendFailed, 500, n);
1394
- this._emitter.emit("error", r), this._router.errorStream(s, r);
1395
- }), {
1396
- stream: h,
1397
- turnId: s,
1398
- cancel: async () => this.cancel({ turnId: s }),
1399
- optimisticMsgIds: [...u]
2032
+ })(), {
2033
+ inputCodecMessageId: p,
2034
+ runId: m,
2035
+ inputEventId: f,
2036
+ cancel: async () => {
2037
+ await this._publishCancel({
2038
+ inputCodecMessageId: p,
2039
+ ...s !== void 0 && { runId: s }
2040
+ });
2041
+ },
2042
+ optimisticCodecMessageIds: [...l],
2043
+ toInvocation: () => t.fromJSON({
2044
+ inputEventId: f,
2045
+ sessionName: this._channel.name
2046
+ })
1400
2047
  };
1401
2048
  }
1402
2049
  async cancel(e) {
1403
- if (this._state === Q.CLOSED) return;
1404
- let t = e ?? { own: !0 };
1405
- this._logger.debug("ClientTransport.cancel();", { filter: t }), await this._publishCancel(t), this._closeMatchingTurnStreams(t);
1406
- }
1407
- stageEvents(e, t) {
1408
- if (this._logger.trace("ClientTransport.stageEvents();", {
1409
- msgId: e,
1410
- eventCount: t.length
1411
- }), this._state === Q.CLOSED) {
1412
- this._logger.warn("ClientTransport.stageEvents(); transport is closed", { msgId: e });
1413
- return;
1414
- }
1415
- if (!this._tree.getNode(e)) {
1416
- this._logger.warn("ClientTransport.stageEvents(); msgId not found in tree", { msgId: e });
1417
- return;
1418
- }
1419
- if (t.length === 0) return;
1420
- let n = {
1421
- kind: "event",
1422
- msgId: e,
1423
- events: t
1424
- };
1425
- this._applyEventsToTree([n]), this._pendingLocalEvents.push(n);
1426
- }
1427
- stageMessage(e, t) {
1428
- if (this._logger.trace("ClientTransport.stageMessage();", { msgId: e }), this._state === Q.CLOSED) {
1429
- this._logger.warn("ClientTransport.stageMessage(); transport is closed", { msgId: e });
1430
- return;
1431
- }
1432
- let n = this._tree.getNode(e);
1433
- if (!n) {
1434
- this._logger.warn("ClientTransport.stageMessage(); msgId not found in tree", { msgId: e });
1435
- return;
1436
- }
1437
- this._tree.upsert(e, t, n.headers, n.serial);
2050
+ return this._publishCancel({ runId: e });
1438
2051
  }
1439
- _applyEventsToTree(e) {
1440
- for (let t of e) {
1441
- let e = this._tree.getNode(t.msgId);
1442
- if (!e) continue;
1443
- let n = t.events.map((e) => ({
1444
- kind: "event",
1445
- event: e,
1446
- messageId: t.msgId
1447
- })), r = this._codec.createAccumulator();
1448
- r.initMessage(t.msgId, e.message), r.processOutputs(n);
1449
- let i = r.messages.at(-1);
1450
- i && this._tree.upsert(t.msgId, i, e.headers, e.serial);
1451
- }
1452
- }
1453
- async waitForTurn(e) {
1454
- if (this._state === Q.CLOSED) return;
1455
- let t = e ?? { own: !0 }, n = this._getMatchingTurnIds(t);
1456
- if (n.size !== 0) return this._logger.debug("ClientTransport.waitForTurn();", { turnIds: [...n] }), new Promise((e) => {
1457
- let t = !1, r = () => {
1458
- if (t) return;
1459
- t = !0, i();
1460
- let n = this._closeResolvers.indexOf(r);
1461
- n !== -1 && this._closeResolvers.splice(n, 1), e();
1462
- }, i = this._tree.on("turn", (e) => {
1463
- e.type === "x-ably-turn-end" && (n.delete(e.turnId), n.size === 0 && r());
1464
- });
1465
- this._closeResolvers.push(r);
2052
+ async _publishCancel(e) {
2053
+ if (this._state === "closed" || (await this._requireConnected("cancel"), this._state === "closed")) return;
2054
+ this._logger.debug("ClientSession._publishCancel();", {
2055
+ runId: e.runId,
2056
+ inputCodecMessageId: e.inputCodecMessageId
2057
+ });
2058
+ let t = { [c]: crypto.randomUUID() };
2059
+ e.runId !== void 0 && (t[o] = e.runId), e.inputCodecMessageId !== void 0 && (t[_] = e.inputCodecMessageId), await this._channel.publish({
2060
+ name: b,
2061
+ extras: { ai: { transport: t } }
1466
2062
  });
1467
2063
  }
1468
2064
  on(e, t) {
1469
- if (this._state === Q.CLOSED) return ue;
2065
+ if (this._state === "closed") return Ze;
1470
2066
  let n = t;
1471
2067
  return this._emitter.on(e, n), () => {
1472
2068
  this._emitter.off(e, n);
1473
2069
  };
1474
2070
  }
1475
- async close(e) {
1476
- if (this._state !== Q.CLOSED) {
1477
- if (this._state = Q.CLOSED, this._logger.info("ClientTransport.close();"), e?.cancel) {
1478
- try {
1479
- await this._publishCancel(e.cancel);
1480
- } catch {}
1481
- this._closeMatchingTurnStreams(e.cancel);
1482
- }
1483
- this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange);
1484
- for (let e of this._ownTurnIds) this._router.closeStream(e);
1485
- this._turnObservers.clear(), this._emitter.off();
2071
+ async close() {
2072
+ if (this._state !== "closed") {
2073
+ this._state = "closed", this._logger.info("ClientSession.close();"), this._connectPromise && this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange), this._emitter.off();
1486
2074
  for (let e of this._views) e.close();
1487
- this._views.clear();
1488
- for (let e of this._closeResolvers) e();
1489
- this._closeResolvers.length = 0, this._ownTurnIds.clear(), this._ownMsgIds.clear(), this._turnMsgIds.clear();
1490
- }
1491
- }
1492
- }, fe = (e) => new de(e), pe = (e) => [{
1493
- kind: "event",
1494
- event: e
1495
- }], me = class {
1496
- constructor(e, t = {}) {
1497
- this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
1498
- }
1499
- decode(e) {
1500
- let t = e.action;
1501
- this._logger?.trace("DefaultDecoderCore.decode();", {
1502
- action: t,
1503
- serial: e.serial,
1504
- name: e.name
1505
- });
1506
- let n;
1507
- switch (t) {
1508
- case "message.create": {
1509
- let t = this._toPayload(e);
1510
- n = t.headers?.["x-ably-stream"] === "true" ? this._decodeStreamedCreate(t, e.serial) : this._hooks.decodeDiscrete(t);
1511
- break;
2075
+ if (this._views.clear(), this._pendingRunStarts.size > 0) {
2076
+ let t = new e.ErrorInfo("unable to await run-start; session closed", E.SessionClosed, 400);
2077
+ for (let e of this._pendingRunStarts.values()) e.reject(t);
2078
+ this._pendingRunStarts.clear();
1512
2079
  }
1513
- case "message.append":
1514
- n = this._decodeAppend(e);
1515
- break;
1516
- case "message.update":
1517
- n = this._decodeUpdate(e);
1518
- break;
1519
- case "message.delete":
1520
- n = this._decodeDelete(e);
1521
- break;
1522
- default: return [];
1523
- }
1524
- let r = w(e)[o];
1525
- if (r) for (let e of n) e.kind === "event" && (e.messageId = r);
1526
- return n;
1527
- }
1528
- _toPayload(e) {
1529
- return {
1530
- name: e.name ?? "",
1531
- data: e.data,
1532
- headers: w(e)
1533
- };
1534
- }
1535
- _stringData(e) {
1536
- return typeof e.data == "string" ? e.data : "";
1537
- }
1538
- _invokeOnStreamUpdate(e) {
1539
- if (this._onStreamUpdate) try {
1540
- this._onStreamUpdate(e);
1541
- } catch (e) {
1542
- this._logger?.error("DefaultDecoderCore._invokeOnStreamUpdate(); callback threw", { error: e });
1543
- }
1544
- }
1545
- _invokeOnStreamDelete(e, t) {
1546
- if (this._onStreamDelete) try {
1547
- this._onStreamDelete(e, t);
1548
- } catch (e) {
1549
- this._logger?.error("DefaultDecoderCore._invokeOnStreamDelete(); callback threw", { error: e });
1550
- }
1551
- }
1552
- _decodeStreamedCreate(e, t) {
1553
- if (!t) return [];
1554
- let n = e.headers?.["x-ably-stream-id"] ?? "", r = e.headers ?? {}, i = {
1555
- name: e.name,
1556
- streamId: n,
1557
- accumulated: "",
1558
- headers: { ...r },
1559
- closed: !1
1560
- };
1561
- return this._serialState.set(t, i), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
1562
- name: e.name,
1563
- streamId: n,
1564
- serial: t
1565
- }), this._hooks.buildStartEvents(i);
1566
- }
1567
- _decodeAppend(e) {
1568
- let t = e.serial;
1569
- if (!t) return [];
1570
- let r = this._serialState.get(t);
1571
- if (!r) return this._decodeUpdate(e);
1572
- let i = w(e), a = typeof e.data == "string" ? e.data : "", o = i[n], s = [];
1573
- return a.length > 0 && (r.accumulated += a, s.push(...this._hooks.buildDeltaEvents(r, a))), o === "finished" && !r.closed ? (r.closed = !0, s.push(...this._hooks.buildEndEvents(r, i)), this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream finished", { streamId: r.streamId })) : o === "aborted" && !r.closed && (r.closed = !0, this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream aborted", { streamId: r.streamId })), s;
1574
- }
1575
- _decodeUpdate(e) {
1576
- let r = e.serial;
1577
- if (!r) return [];
1578
- let i = this._toPayload(e), a = i.headers ?? {}, o = a[t] === "true", s = a[n], c = this._serialState.get(r);
1579
- if (!c) return this._decodeFirstContact(i, o, s, r);
1580
- let l = this._stringData(e);
1581
- if (l.startsWith(c.accumulated)) {
1582
- let e = l.slice(c.accumulated.length), t = [];
1583
- return e.length > 0 && (c.accumulated = l, t.push(...this._hooks.buildDeltaEvents(c, e))), s === "finished" && !c.closed ? (c.closed = !0, t.push(...this._hooks.buildEndEvents(c, a))) : s === "aborted" && !c.closed && (c.closed = !0), t;
2080
+ try {
2081
+ await this._encoder.close();
2082
+ } catch {}
2083
+ await ke(this._channel, this._connectPromise, this._logger, "ClientSession");
1584
2084
  }
1585
- return c.accumulated = l, c.headers = { ...a }, this._invokeOnStreamUpdate(c), [];
1586
- }
1587
- _decodeFirstContact(e, t, n, r) {
1588
- if (!t) return this._hooks.decodeDiscrete(e);
1589
- let i = e.headers?.["x-ably-stream-id"] ?? "", a = e.headers ?? {}, o = typeof e.data == "string" ? e.data : "";
1590
- this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
1591
- name: e.name,
1592
- streamId: i,
1593
- serial: r
1594
- });
1595
- let s = {
1596
- name: e.name,
1597
- streamId: i,
1598
- accumulated: o,
1599
- headers: { ...a },
1600
- closed: n === "finished" || n === "aborted"
1601
- };
1602
- this._serialState.set(r, s);
1603
- let c = this._hooks.buildStartEvents(s);
1604
- return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "finished" && c.push(...this._hooks.buildEndEvents(s, a)), c;
1605
- }
1606
- _decodeDelete(e) {
1607
- let t = e.serial;
1608
- if (!t) return [];
1609
- let n = this._serialState.get(t);
1610
- return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
1611
2085
  }
1612
- }, he = (e, t = {}) => new me(e, t), ge = class {
2086
+ }, $e = (e) => new Qe(e), et = class {
1613
2087
  constructor(e, t = {}) {
1614
- this._trackers = /* @__PURE__ */ new Map(), this._pending = [], this._closed = !1, this._writer = e, this._defaultClientId = t.clientId, this._defaultExtras = t.extras, this._onMessageHook = t.onMessage ?? (() => {}), this._logger = t.logger?.withContext({ component: "EncoderCore" });
2088
+ this._trackers = /* @__PURE__ */ new Map(), this._pending = [], this._closed = !1, this._writer = e, this._defaultExtras = t.extras, this._onMessageHook = t.onMessage ?? (() => {}), this._logger = t.logger?.withContext({ component: "EncoderCore" });
1615
2089
  }
1616
2090
  async publishDiscrete(e, t) {
1617
2091
  this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscrete();", { name: e.name });
@@ -1620,48 +2094,48 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1620
2094
  }
1621
2095
  async publishDiscreteBatch(e, t) {
1622
2096
  this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscreteBatch();", { count: e.length });
1623
- let n = e.map((e) => this._buildDiscreteMessage(e, t));
1624
- for (let e of n) e.extras.headers[i] = "true";
2097
+ let n = e.map((e) => this._buildDiscreteMessage(e, t, !0));
1625
2098
  return this._writer.publish(n);
1626
2099
  }
1627
- async startStream(i, a, o) {
2100
+ async startStream(t, a, o) {
1628
2101
  this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.startStream();", {
1629
2102
  name: a.name,
1630
- streamId: i
2103
+ streamId: t
1631
2104
  });
1632
- let s = this._buildHeaders(a.headers ?? {}, o);
1633
- s[t] = "true", s[n] = "streaming", s[r] = i;
1634
- let c = this._resolveClientId(o), l = {
2105
+ let s = this._buildTransport(a.transportHeaders, o);
2106
+ s[n] = "true", s[r] = "streaming", s[i] = t;
2107
+ let c = a.codecHeaders ?? {}, l = {
1635
2108
  name: a.name,
1636
2109
  data: a.data,
1637
- extras: { headers: s },
1638
- ...c ? { clientId: c } : {}
2110
+ extras: { ai: this._aiExtras(s, c) }
1639
2111
  };
1640
2112
  this._invokeOnMessage(l);
1641
2113
  let u = (await this._writer.publish(l)).serials[0];
1642
- if (!u) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${i})`, C.BadRequest, 400);
1643
- this._trackers.set(i, {
2114
+ if (!u) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${t})`, E.BadRequest, 400);
2115
+ this._trackers.set(t, {
1644
2116
  serial: u,
1645
2117
  name: a.name,
1646
- streamId: i,
2118
+ streamId: t,
1647
2119
  accumulated: a.data,
1648
- persistentHeaders: s,
1649
- aborted: !1
2120
+ persistentTransport: s,
2121
+ persistentCodec: c,
2122
+ cancelled: !1,
2123
+ completed: !1
1650
2124
  }), this._logger?.debug("DefaultEncoderCore.startStream(); stream started", {
1651
2125
  name: a.name,
1652
- streamId: i,
2126
+ streamId: t,
1653
2127
  serial: u
1654
2128
  });
1655
2129
  }
1656
2130
  appendStream(t, n) {
1657
2131
  this._assertNotClosed();
1658
2132
  let r = this._trackers.get(t);
1659
- if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`, C.InvalidArgument, 400);
2133
+ if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`, E.InvalidArgument, 400);
1660
2134
  r.accumulated += n;
1661
2135
  let i = {
1662
2136
  serial: r.serial,
1663
2137
  data: n,
1664
- extras: { headers: { ...r.persistentHeaders } }
2138
+ extras: { ai: this._aiExtras({ ...r.persistentTransport }, { ...r.persistentCodec }) }
1665
2139
  };
1666
2140
  this._invokeOnMessage(i);
1667
2141
  let a = this._writer.appendMessage(i);
@@ -1670,59 +2144,41 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1670
2144
  streamId: t
1671
2145
  });
1672
2146
  }
1673
- async closeStream(t, r) {
2147
+ async closeStream(t, n) {
1674
2148
  this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.closeStream();", { streamId: t });
1675
2149
  let i = this._trackers.get(t);
1676
- if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, C.InvalidArgument, 400);
1677
- i.accumulated += r.data;
1678
- let a = this._buildClosingHeaders(i, r.headers ?? {});
1679
- a[n] = "finished";
1680
- let o = {
2150
+ if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, E.InvalidArgument, 400);
2151
+ i.accumulated += n.data, i.completed = !0;
2152
+ let { transport: a, codec: o } = this._buildClosing(i, n);
2153
+ a[r] = "complete";
2154
+ let s = {
1681
2155
  serial: i.serial,
1682
- data: r.data,
1683
- extras: { headers: a }
2156
+ data: n.data,
2157
+ extras: { ai: this._aiExtras(a, o) }
1684
2158
  };
1685
- this._invokeOnMessage(o);
1686
- let s = this._writer.appendMessage(o);
2159
+ this._invokeOnMessage(s);
2160
+ let c = this._writer.appendMessage(s);
1687
2161
  this._pending.push({
1688
- promise: s,
2162
+ promise: c,
1689
2163
  streamId: t
1690
2164
  }), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.closeStream(); stream closed", { streamId: t });
1691
2165
  }
1692
- async abortStream(t, r) {
1693
- this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortStream();", { streamId: t });
1694
- let i = this._trackers.get(t);
1695
- if (!i) throw new e.ErrorInfo(`unable to abort stream; no active stream for streamId '${t}'`, C.InvalidArgument, 400);
1696
- i.aborted = !0;
1697
- let a = this._buildClosingHeaders(i, {}, r);
1698
- a[n] = "aborted";
1699
- let o = {
1700
- serial: i.serial,
1701
- data: "",
1702
- extras: { headers: a }
1703
- };
1704
- this._invokeOnMessage(o);
1705
- let s = this._writer.appendMessage(o);
1706
- this._pending.push({
1707
- promise: s,
1708
- streamId: t
1709
- }), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.abortStream(); stream aborted", { streamId: t });
1710
- }
1711
- async abortAllStreams(e) {
1712
- this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortAllStreams();", { streamCount: this._trackers.size });
2166
+ async cancelAllStreams(e) {
2167
+ this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.cancelAllStreams();", { streamCount: this._trackers.size });
1713
2168
  for (let t of this._trackers.values()) {
1714
- t.aborted = !0;
1715
- let r = this._buildClosingHeaders(t, {}, e);
1716
- r[n] = "aborted";
1717
- let i = {
2169
+ if (t.cancelled || t.completed) continue;
2170
+ t.cancelled = !0;
2171
+ let { transport: n, codec: i } = this._buildClosing(t, void 0, e);
2172
+ n[r] = "cancelled";
2173
+ let a = {
1718
2174
  serial: t.serial,
1719
2175
  data: "",
1720
- extras: { headers: r }
2176
+ extras: { ai: this._aiExtras(n, i) }
1721
2177
  };
1722
- this._invokeOnMessage(i);
1723
- let a = this._writer.appendMessage(i);
2178
+ this._invokeOnMessage(a);
2179
+ let o = this._writer.appendMessage(a);
1724
2180
  this._pending.push({
1725
- promise: a,
2181
+ promise: o,
1726
2182
  streamId: t.streamId
1727
2183
  });
1728
2184
  }
@@ -1741,10 +2197,10 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1741
2197
  }
1742
2198
  }
1743
2199
  async _doFlush(t) {
1744
- let r = await Promise.allSettled(t.map(async (e) => e.promise)), i = /* @__PURE__ */ new Set();
1745
- for (let [e, n] of r.entries()) {
1746
- let r = t[e];
1747
- r && n.status === "rejected" && i.add(r.streamId);
2200
+ let n = await Promise.allSettled(t.map(async (e) => e.promise)), i = /* @__PURE__ */ new Set();
2201
+ for (let [e, r] of n.entries()) {
2202
+ let n = t[e];
2203
+ n && r.status === "rejected" && i.add(n.streamId);
1748
2204
  }
1749
2205
  if (i.size === 0) {
1750
2206
  this._logger?.debug("DefaultEncoderCore._flushPending(); all appends succeeded");
@@ -1755,13 +2211,13 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1755
2211
  for (let e of i) {
1756
2212
  let t = this._trackers.get(e);
1757
2213
  if (!t) continue;
1758
- let r = t.aborted ? "aborted" : "finished", i = {
2214
+ let n = t.cancelled ? "cancelled" : "complete", i = {
1759
2215
  serial: t.serial,
1760
2216
  data: t.accumulated,
1761
- extras: { headers: {
1762
- ...t.persistentHeaders,
1763
- [n]: r
1764
- } }
2217
+ extras: { ai: this._aiExtras({
2218
+ ...t.persistentTransport,
2219
+ [r]: n
2220
+ }, { ...t.persistentCodec }) }
1765
2221
  };
1766
2222
  try {
1767
2223
  await this._writer.updateMessage(i);
@@ -1774,7 +2230,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1774
2230
  }
1775
2231
  if (a.length > 0) {
1776
2232
  let t = a.map((e) => e.streamId).join(", ");
1777
- throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`, C.EncoderRecoveryFailed, 500);
2233
+ throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`, E.EncoderRecoveryFailed, 500);
1778
2234
  }
1779
2235
  }
1780
2236
  async close() {
@@ -1796,37 +2252,178 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1796
2252
  }
1797
2253
  }
1798
2254
  _assertNotClosed() {
1799
- if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed", C.InvalidArgument, 400);
1800
- }
1801
- _resolveClientId(e) {
1802
- return e?.clientId ?? this._defaultClientId;
2255
+ if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed", E.InvalidArgument, 400);
1803
2256
  }
1804
- _buildHeaders(e, t) {
2257
+ _buildTransport(e, t) {
1805
2258
  let n = {
1806
- ...E(this._defaultExtras?.headers, t?.extras?.headers),
2259
+ ...L(this._defaultExtras?.headers, t?.extras?.headers),
1807
2260
  ...e
1808
2261
  };
1809
- return t?.messageId !== void 0 && (n[o] = t.messageId), n;
2262
+ return t?.messageId !== void 0 && (n[l] = t.messageId), n;
1810
2263
  }
1811
- _buildDiscreteMessage(e, n) {
1812
- let r = this._buildHeaders(e.headers ?? {}, n);
1813
- r[t] = "false";
1814
- let i = this._resolveClientId(n), a = {
2264
+ _aiExtras(e, t) {
2265
+ return Object.keys(t).length > 0 ? {
2266
+ transport: e,
2267
+ codec: t
2268
+ } : { transport: e };
2269
+ }
2270
+ _buildDiscreteMessage(e, t, r = !1) {
2271
+ let i = this._buildTransport(e.transportHeaders, t);
2272
+ i[n] = "false", r && (i[a] = "true");
2273
+ let o = {
1815
2274
  name: e.name,
1816
2275
  data: e.data,
1817
2276
  extras: {
1818
- headers: r,
2277
+ ai: this._aiExtras(i, e.codecHeaders ?? {}),
1819
2278
  ...e.ephemeral ? { ephemeral: !0 } : {}
2279
+ }
2280
+ };
2281
+ return this._invokeOnMessage(o), o;
2282
+ }
2283
+ _buildClosing(e, t, n) {
2284
+ let r = L(this._defaultExtras?.headers, n?.extras?.headers);
2285
+ return {
2286
+ transport: {
2287
+ ...e.persistentTransport,
2288
+ ...r,
2289
+ ...t?.transportHeaders
1820
2290
  },
1821
- ...i ? { clientId: i } : {}
2291
+ codec: {
2292
+ ...e.persistentCodec,
2293
+ ...t?.codecHeaders
2294
+ }
2295
+ };
2296
+ }
2297
+ }, tt = (e, t = {}) => new et(e, t), nt = class {
2298
+ constructor(e, t = {}) {
2299
+ this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
2300
+ }
2301
+ decode(e) {
2302
+ let t = e.action;
2303
+ switch (this._logger?.trace("DefaultDecoderCore.decode();", {
2304
+ action: t,
2305
+ serial: e.serial,
2306
+ name: e.name
2307
+ }), t) {
2308
+ case "message.create": {
2309
+ let t = this._toPayload(e);
2310
+ return t.transportHeaders?.stream === "true" ? this._decodeStreamedCreate(t, e.serial, e.version.serial) : this._hooks.decodeDiscrete(t);
2311
+ }
2312
+ case "message.append": return this._decodeAppend(e);
2313
+ case "message.update": return this._decodeUpdate(e);
2314
+ case "message.delete": return this._decodeDelete(e);
2315
+ default: return [];
2316
+ }
2317
+ }
2318
+ _toPayload(e) {
2319
+ return {
2320
+ name: e.name ?? "",
2321
+ data: e.data,
2322
+ transportHeaders: P(e),
2323
+ codecHeaders: F(e)
2324
+ };
2325
+ }
2326
+ _stringData(e) {
2327
+ return typeof e.data == "string" ? e.data : "";
2328
+ }
2329
+ _invokeOnStreamUpdate(e) {
2330
+ if (this._onStreamUpdate) try {
2331
+ this._onStreamUpdate(e);
2332
+ } catch (e) {
2333
+ this._logger?.error("DefaultDecoderCore._invokeOnStreamUpdate(); callback threw", { error: e });
2334
+ }
2335
+ }
2336
+ _invokeOnStreamDelete(e, t) {
2337
+ if (this._onStreamDelete) try {
2338
+ this._onStreamDelete(e, t);
2339
+ } catch (e) {
2340
+ this._logger?.error("DefaultDecoderCore._invokeOnStreamDelete(); callback threw", { error: e });
2341
+ }
2342
+ }
2343
+ _alreadyIncorporated(e, t, n, r) {
2344
+ return r !== void 0 && r <= n.version ? (this._logger?.debug(`DefaultDecoderCore.${e}(); delivery already incorporated`, {
2345
+ serial: t,
2346
+ version: r,
2347
+ trackerVersion: n.version
2348
+ }), !0) : n.closed ? (this._logger?.debug(`DefaultDecoderCore.${e}(); stream closed, dropping delivery`, {
2349
+ serial: t,
2350
+ version: r
2351
+ }), !0) : (r !== void 0 && (n.version = r), !1);
2352
+ }
2353
+ _closeTracker(e) {
2354
+ e.closed = !0, e.accumulated = "";
2355
+ }
2356
+ _applyTerminalStatus(e, t, n, r) {
2357
+ return t === "complete" ? (r.push(...this._hooks.buildEndEvents(e, n)), this._closeTracker(e), !0) : t === "cancelled" ? (this._closeTracker(e), !0) : !1;
2358
+ }
2359
+ _decodeStreamedCreate(e, t, n) {
2360
+ if (!t) return [];
2361
+ if (this._serialState.get(t)) return this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); duplicate create for tracked stream", { serial: t }), [];
2362
+ let r = e.transportHeaders?.["stream-id"] ?? "", i = {
2363
+ name: e.name,
2364
+ streamId: r,
2365
+ accumulated: "",
2366
+ codecHeaders: { ...e.codecHeaders },
2367
+ transportHeaders: { ...e.transportHeaders },
2368
+ version: n ?? t,
2369
+ closed: !1
2370
+ };
2371
+ return this._serialState.set(t, i), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
2372
+ name: e.name,
2373
+ streamId: r,
2374
+ serial: t
2375
+ }), this._hooks.buildStartEvents(i);
2376
+ }
2377
+ _decodeAppend(e) {
2378
+ let t = e.serial;
2379
+ if (!t) return [];
2380
+ let n = this._serialState.get(t);
2381
+ if (!n) return this._logger?.warn("DefaultDecoderCore._decodeAppend(); append with no tracker, treating as first contact", { serial: t }), this._decodeUpdate(e);
2382
+ if (this._alreadyIncorporated("_decodeAppend", t, n, e.version.serial)) return [];
2383
+ let i = P(e), a = F(e), o = typeof e.data == "string" ? e.data : "", s = i[r], c = [];
2384
+ return o.length > 0 && (n.accumulated += o, c.push(...this._hooks.buildDeltaEvents(n, o))), this._applyTerminalStatus(n, s, a, c) && this._logger?.debug(`DefaultDecoderCore._decodeAppend(); stream ${s === "complete" ? "complete" : "cancelled"}`, { streamId: n.streamId }), c;
2385
+ }
2386
+ _decodeUpdate(e) {
2387
+ let t = e.serial;
2388
+ if (!t) return [];
2389
+ let i = this._toPayload(e), a = i.transportHeaders ?? {}, o = i.codecHeaders ?? {}, s = a[n] === "true", c = a[r], l = this._serialState.get(t);
2390
+ if (!l) return this._decodeFirstContact(i, s, c, t, e.version.serial);
2391
+ if (this._alreadyIncorporated("_decodeUpdate", t, l, e.version.serial)) return [];
2392
+ let u = this._stringData(e);
2393
+ if (u.startsWith(l.accumulated)) {
2394
+ let e = u.slice(l.accumulated.length), t = [];
2395
+ return e.length > 0 && (l.accumulated = u, t.push(...this._hooks.buildDeltaEvents(l, e))), this._applyTerminalStatus(l, c, o, t), t;
2396
+ }
2397
+ return l.accumulated = u, l.codecHeaders = { ...o }, l.transportHeaders = { ...a }, this._invokeOnStreamUpdate(l), [];
2398
+ }
2399
+ _decodeFirstContact(e, t, n, r, i) {
2400
+ if (!t) return this._hooks.decodeDiscrete(e);
2401
+ let a = e.transportHeaders?.["stream-id"] ?? "", o = e.codecHeaders ?? {}, s = typeof e.data == "string" ? e.data : "";
2402
+ this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
2403
+ name: e.name,
2404
+ streamId: a,
2405
+ serial: r
2406
+ });
2407
+ let c = {
2408
+ name: e.name,
2409
+ streamId: a,
2410
+ accumulated: s,
2411
+ codecHeaders: { ...o },
2412
+ transportHeaders: { ...e.transportHeaders },
2413
+ version: i ?? r,
2414
+ closed: !1
1822
2415
  };
1823
- return this._invokeOnMessage(a), a;
2416
+ this._serialState.set(r, c);
2417
+ let l = this._hooks.buildStartEvents(c);
2418
+ return s.length > 0 && l.push(...this._hooks.buildDeltaEvents(c, s)), n === "complete" && l.push(...this._hooks.buildEndEvents(c, o)), (n === "complete" || n === "cancelled") && this._closeTracker(c), l;
1824
2419
  }
1825
- _buildClosingHeaders(e, t, n) {
1826
- let r = { ...e.persistentHeaders }, i = E(this._defaultExtras?.headers, n?.extras?.headers);
1827
- return Object.assign(r, i), Object.assign(r, t), r;
2420
+ _decodeDelete(e) {
2421
+ let t = e.serial;
2422
+ if (!t) return [];
2423
+ let n = this._serialState.get(t);
2424
+ return this._invokeOnStreamDelete(t, n), n && this._closeTracker(n), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
1828
2425
  }
1829
- }, $ = (e, t = {}) => new ge(e, t), _e = class {
2426
+ }, rt = (e, t = {}) => new nt(e, t), it = class {
1830
2427
  constructor(e) {
1831
2428
  this._emitted = /* @__PURE__ */ new Map(), this._phases = e;
1832
2429
  }
@@ -1848,8 +2445,425 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1848
2445
  let t = this._emitted.get(e);
1849
2446
  return t || (t = /* @__PURE__ */ new Set(), this._emitted.set(e, t)), t;
1850
2447
  }
1851
- }, ve = (e) => new _e(e);
2448
+ }, at = (e) => new it(e);
2449
+ //#endregion
2450
+ //#region src/core/codec/fields.ts
2451
+ function ot(e, t) {
2452
+ return {
2453
+ key: e,
2454
+ read: (n) => n[e] ?? t,
2455
+ write: (t, n) => {
2456
+ typeof n == "string" && (t[e] = n);
2457
+ }
2458
+ };
2459
+ }
2460
+ function st(e, t) {
2461
+ return {
2462
+ key: e,
2463
+ read: (n) => R(n[e]) ?? t,
2464
+ write: (t, n) => {
2465
+ typeof n == "boolean" && (t[e] = String(n));
2466
+ }
2467
+ };
2468
+ }
2469
+ var ct = (e) => ({
2470
+ key: e,
2471
+ read: (t) => I(t[e]),
2472
+ write: (t, n) => {
2473
+ n != null && (t[e] = JSON.stringify(n));
2474
+ }
2475
+ }), lt = (e, t, n) => ({
2476
+ key: e,
2477
+ read: (r) => {
2478
+ let i = r[e];
2479
+ return t.find((e) => e === i) ?? n;
2480
+ },
2481
+ write: (t, n) => {
2482
+ typeof n == "string" && (t[e] = n);
2483
+ }
2484
+ }), ut = "kind", dt = "-*", ft = (e) => e.endsWith(dt) ? (t) => t.startsWith(e.slice(0, -1)) : void 0, pt = "partType", Y = (e, t) => e[t], X = (e, t, n, r) => {
2485
+ let i = { [ut]: t };
2486
+ for (let t of e) r && !r.includes(t.key) || t.write(i, Y(n, t.key));
2487
+ return i;
2488
+ }, mt = (e, t) => e.find((e) => !e.match && e.partType === t) ?? e.find((e) => e.match?.(t)), ht = (e) => {
2489
+ let t = /* @__PURE__ */ new Map(), n = [];
2490
+ for (let r of e) r.construct === "event" && (r.match ? n.push(r) : t.set(r.type, r));
2491
+ return {
2492
+ discreteByType: t,
2493
+ wildcards: n
2494
+ };
2495
+ }, Z = (e, t) => {
2496
+ let n = {};
2497
+ for (let r of e) {
2498
+ let e = r.read(t);
2499
+ e !== void 0 && (n[r.key] = e);
2500
+ }
2501
+ return n;
2502
+ }, gt = (e) => {
2503
+ let t = /* @__PURE__ */ new Map();
2504
+ for (let n of e) t.set(n.kind, n);
2505
+ let n = (e, t) => {
2506
+ if (e.wireOnly) return [];
2507
+ let n = Z(e.fields, t.codecHeaders);
2508
+ e.data && Object.assign(n, e.data.decode(t.data));
2509
+ let r = t.transportHeaders["codec-message-id"] ?? "";
2510
+ return [{
2511
+ kind: e.kind,
2512
+ codecMessageId: r,
2513
+ payload: B(n)
2514
+ }];
2515
+ }, r = (e, t) => {
2516
+ let n = t.codecHeaders.partType ?? "", r = mt(e.parts, n);
2517
+ if (!r) return [];
2518
+ let i = Z(r.fields, t.codecHeaders);
2519
+ r.data && Object.assign(i, r.data.decode(t.data)), i.type = n;
2520
+ let a = e.assemble(B(i), {
2521
+ codecHeaders: t.codecHeaders,
2522
+ transportHeaders: t.transportHeaders
2523
+ });
2524
+ return [{
2525
+ kind: e.kind,
2526
+ ...a
2527
+ }];
2528
+ };
2529
+ return { decode: (e) => {
2530
+ let i = t.get(e.codecKind);
2531
+ return i ? i.construct === "event" ? n(i, e) : r(i, e) : [];
2532
+ } };
2533
+ }, _t = (e, t) => t?.transportHeaders === void 0 ? e : {
2534
+ ...e,
2535
+ transportHeaders: {
2536
+ ...e.transportHeaders,
2537
+ ...t.transportHeaders
2538
+ }
2539
+ }, vt = (t, n) => {
2540
+ let r = /* @__PURE__ */ new Map();
2541
+ for (let e of t) r.set(e.kind, e);
2542
+ let i = async (t, r, i, a) => {
2543
+ if (t.wireOnly) {
2544
+ await i.publishDiscrete({
2545
+ name: n,
2546
+ data: "",
2547
+ codecHeaders: { [ut]: t.kind }
2548
+ }, a.opts);
2549
+ return;
2550
+ }
2551
+ let o = Y(r, "payload");
2552
+ if (typeof o != "object" || !o) throw new e.ErrorInfo(`unable to encode input; event '${t.kind}' carries no payload object — declare it wireOnly or use an encode escape hatch`, E.InvalidArgument, 400);
2553
+ let s = X(t.fields, t.kind, o), c = t.data ? t.data.encode(o) : "";
2554
+ await i.publishDiscrete({
2555
+ name: n,
2556
+ data: c,
2557
+ codecHeaders: s
2558
+ }, a.opts);
2559
+ }, a = async (e, t, r, i) => {
2560
+ let a = e.messageHeaders?.(t), o = [];
2561
+ for (let r of e.explode(t)) {
2562
+ let t = e.partTypeOf(r), i = mt(e.parts, t);
2563
+ if (!i) continue;
2564
+ let s = r, c = {
2565
+ ...X(i.fields, e.kind, s),
2566
+ ...a?.codecHeaders,
2567
+ [pt]: t
2568
+ }, l = i.data ? i.data.encode(r) : "";
2569
+ o.push(_t({
2570
+ name: n,
2571
+ data: l,
2572
+ codecHeaders: c
2573
+ }, a));
2574
+ }
2575
+ o.length === 0 && o.push(_t({
2576
+ name: n,
2577
+ data: "",
2578
+ codecHeaders: {
2579
+ [ut]: e.kind,
2580
+ ...a?.codecHeaders
2581
+ }
2582
+ }, a)), await r.publishDiscreteBatch(o, i.opts);
2583
+ };
2584
+ return { encode: async (t, n, o) => {
2585
+ let s = r.get(t.kind);
2586
+ if (!s) throw new e.ErrorInfo(`unable to publish; unsupported input kind '${t.kind}'`, E.InvalidArgument, 400);
2587
+ await (s.construct === "event" ? i(s, t, n, o) : a(s, t, n, o));
2588
+ } };
2589
+ }, yt = () => {
2590
+ let e = (e, t) => {
2591
+ let n = ft(e);
2592
+ return {
2593
+ partType: e,
2594
+ ...n ? { match: n } : {},
2595
+ fields: t.fields ?? [],
2596
+ data: t.data
2597
+ };
2598
+ };
2599
+ return {
2600
+ event: (e, t) => {
2601
+ let n = t;
2602
+ return {
2603
+ construct: "event",
2604
+ kind: e,
2605
+ fields: n?.fields ?? [],
2606
+ data: n?.data,
2607
+ wireOnly: n?.wireOnly ?? !1
2608
+ };
2609
+ },
2610
+ batch: (t, n) => {
2611
+ let r = n.parts(e);
2612
+ return {
2613
+ construct: "batch",
2614
+ kind: t,
2615
+ explode: n.explode,
2616
+ partTypeOf: n.partTypeOf,
2617
+ parts: r,
2618
+ messageHeaders: n.messageHeaders,
2619
+ assemble: n.assemble
2620
+ };
2621
+ }
2622
+ };
2623
+ }, bt = "type", xt = (e) => {
2624
+ let { discreteByType: t, wildcards: n } = ht(e), r = /* @__PURE__ */ new Map();
2625
+ for (let t of e) t.construct === "stream" && r.set(t.kind, t);
2626
+ let i = (e, t) => (t[bt] = e, B(t)), a = (e, t, n) => {
2627
+ let r = Z(e.fields, n.codecHeaders);
2628
+ return e.data && Object.assign(r, e.data.decode(n.data)), [i(t, r)];
2629
+ }, o = (e) => r.get(e.codecHeaders.kind ?? "");
2630
+ return {
2631
+ buildStart: (e) => {
2632
+ let t = o(e);
2633
+ if (!t) return [];
2634
+ let n = Z(t.fields, e.codecHeaders);
2635
+ return n[t.idField] = e.streamId, [i(t.start, n)];
2636
+ },
2637
+ buildDelta: (e, t) => {
2638
+ let n = o(e);
2639
+ if (!n) return [];
2640
+ let r = {
2641
+ [n.idField]: e.streamId,
2642
+ [n.deltaField]: t
2643
+ };
2644
+ return [i(n.delta, r)];
2645
+ },
2646
+ buildEnd: (e, t) => {
2647
+ let n = o(e);
2648
+ if (!n) return [];
2649
+ if (n.decodeEnd) return n.decodeEnd({
2650
+ streamId: e.streamId,
2651
+ accumulated: e.accumulated,
2652
+ codecHeaders: e.codecHeaders,
2653
+ closingCodecHeaders: t
2654
+ });
2655
+ let r = Z(n.fields, t);
2656
+ return r[n.idField] = e.streamId, [i(n.end, r)];
2657
+ },
2658
+ decodeDiscrete: (e, i, o, s) => {
2659
+ let c = {
2660
+ codecKind: e,
2661
+ codecHeaders: i,
2662
+ transportHeaders: o,
2663
+ data: s
2664
+ }, l = t.get(e);
2665
+ if (l) return a(l, e, c);
2666
+ let u = r.get(e);
2667
+ if (u?.decodeDiscrete) return u.decodeDiscrete(c);
2668
+ let d = n.find((t) => t.match?.(e));
2669
+ return d ? a(d, e, c) : [];
2670
+ }
2671
+ };
2672
+ }, St = (t, n) => {
2673
+ let { discreteByType: r, wildcards: i } = ht(t), a = /* @__PURE__ */ new Map();
2674
+ for (let e of t) e.construct === "stream" && (a.set(e.start, {
2675
+ descriptor: e,
2676
+ phase: "start"
2677
+ }), a.set(e.delta, {
2678
+ descriptor: e,
2679
+ phase: "delta"
2680
+ }), a.set(e.end, {
2681
+ descriptor: e,
2682
+ phase: "end"
2683
+ }));
2684
+ return { encode: async (t, o, s) => {
2685
+ let { type: c } = t, l = a.get(c);
2686
+ if (l) {
2687
+ let { descriptor: e, phase: r } = l, i = (t, n) => X(e.fields, e.kind, t, n), a = Y(t, e.idField);
2688
+ r === "start" ? await o.startStream(a, {
2689
+ name: n,
2690
+ data: "",
2691
+ codecHeaders: i(t)
2692
+ }, s.opts) : r === "delta" ? o.appendStream(a, Y(t, e.deltaField)) : e.onEnd ? await e.onEnd(t, o, {
2693
+ h: i,
2694
+ name: n,
2695
+ messageId: s.messageId,
2696
+ opts: s.opts
2697
+ }) : await o.closeStream(a, {
2698
+ name: n,
2699
+ data: "",
2700
+ codecHeaders: i(t)
2701
+ });
2702
+ return;
2703
+ }
2704
+ let u = r.get(c) ?? i.find((e) => e.match?.(c));
2705
+ if (!u) throw new e.ErrorInfo(`unable to publish; unsupported event type '${c}'`, E.InvalidArgument, 400);
2706
+ let d = (e, t) => X(u.fields, e.type, e, t);
2707
+ if (u.encode) {
2708
+ await u.encode(t, o, {
2709
+ h: d,
2710
+ name: n,
2711
+ messageId: s.messageId,
2712
+ opts: s.opts
2713
+ });
2714
+ return;
2715
+ }
2716
+ let f = u.data ? u.data.encode(t) : "";
2717
+ await o.publishDiscrete({
2718
+ name: n,
2719
+ data: f,
2720
+ codecHeaders: d(t),
2721
+ ephemeral: u.ephemeral?.(t)
2722
+ }, s.opts);
2723
+ } };
2724
+ }, Ct = () => ({
2725
+ event: (e, t) => ({
2726
+ construct: "event",
2727
+ type: e,
2728
+ fields: t?.fields ?? [],
2729
+ data: t?.data,
2730
+ ephemeral: t?.ephemeral,
2731
+ match: ft(e),
2732
+ encode: t?.encode
2733
+ }),
2734
+ stream: (e, t) => ({
2735
+ construct: "stream",
2736
+ kind: e,
2737
+ ...t
2738
+ })
2739
+ }), wt = () => ({
2740
+ createUserMessage: (e) => ({
2741
+ kind: "user-message",
2742
+ message: e
2743
+ }),
2744
+ createRegenerate: (e, t) => ({
2745
+ kind: "regenerate",
2746
+ target: e,
2747
+ parent: t
2748
+ }),
2749
+ createToolResult: (e, t) => ({
2750
+ kind: "tool-result",
2751
+ codecMessageId: e,
2752
+ payload: t
2753
+ }),
2754
+ createToolResultError: (e, t) => ({
2755
+ kind: "tool-result-error",
2756
+ codecMessageId: e,
2757
+ payload: t
2758
+ }),
2759
+ createToolApprovalResponse: (e, t) => ({
2760
+ kind: "tool-approval-response",
2761
+ codecMessageId: e,
2762
+ payload: t
2763
+ })
2764
+ }), Tt = class {
2765
+ constructor(e, t, n, r) {
2766
+ this._core = tt(e, t), this._messageId = t.messageId, this._outputEncoder = n, this._inputEncoder = r;
2767
+ }
2768
+ async publishInput(e, t) {
2769
+ await this._inputEncoder.encode(e, this._core, { opts: t });
2770
+ }
2771
+ async publishOutput(e, t) {
2772
+ await this._outputEncoder.encode(e, this._core, {
2773
+ messageId: this._messageId,
2774
+ opts: t
2775
+ });
2776
+ }
2777
+ async cancelStreams() {
2778
+ await this._core.cancelAllStreams();
2779
+ }
2780
+ async close() {
2781
+ await this._core.close();
2782
+ }
2783
+ }, Et = (e, t, n, r) => {
2784
+ let i = e.codecHeaders ?? {}, a = e.transportHeaders ?? {}, o = i.kind ?? "";
2785
+ if (e.name === "ai-input") return n.decode({
2786
+ codecKind: o,
2787
+ data: e.data,
2788
+ codecHeaders: i,
2789
+ transportHeaders: a
2790
+ });
2791
+ if (e.name === "ai-output") {
2792
+ let n = a["run-id"] ?? "", s = r?.onDiscrete;
2793
+ return [...(s !== void 0 && Object.hasOwn(s, o) ? s[o] : void 0)?.(n, { codecHeaders: i }) ?? [], ...t.decodeDiscrete(o, i, a, e.data)];
2794
+ }
2795
+ return [];
2796
+ }, Dt = (e) => e.name === ee, Ot = (e, t, n) => ({
2797
+ buildStartEvents: (t) => {
2798
+ if (!Dt(t)) return [];
2799
+ let r = t.transportHeaders["run-id"] ?? "";
2800
+ return [...n?.onStreamStart?.(r, t) ?? [], ...e.buildStart(t)];
2801
+ },
2802
+ buildDeltaEvents: (t, n) => Dt(t) ? e.buildDelta(t, n) : [],
2803
+ buildEndEvents: (t, n) => Dt(t) ? e.buildEnd(t, n) : [],
2804
+ decodeDiscrete: (r) => Et(r, e, t, n)
2805
+ }), kt = class {
2806
+ constructor(e) {
2807
+ this._core = e;
2808
+ }
2809
+ decode(e) {
2810
+ let t = this._core.decode(e);
2811
+ return e.name === "ai-input" ? {
2812
+ inputs: t,
2813
+ outputs: []
2814
+ } : {
2815
+ inputs: [],
2816
+ outputs: t
2817
+ };
2818
+ }
2819
+ }, Q = (t, n, r) => {
2820
+ let i = t.get(n);
2821
+ if (i !== void 0) throw new e.ErrorInfo(`unable to define codec; dispatch literal '${n}' is declared by both ${i} and ${r}`, E.InvalidArgument, 400);
2822
+ t.set(n, r);
2823
+ }, $ = (t, n) => {
2824
+ for (let r of t) if (r.key === "kind" || r.key === "partType") throw new e.ErrorInfo(`unable to define codec; ${n} binds the driver-reserved header key '${r.key}'`, E.InvalidArgument, 400);
2825
+ }, At = (e, t) => {
2826
+ let n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map();
2827
+ for (let t of e) if (t.construct === "event") {
2828
+ let e = `output event '${t.type}'`;
2829
+ Q(n, t.type, e), Q(r, t.type, e), $(t.fields, e);
2830
+ } else {
2831
+ let e = `output stream '${t.kind}'`;
2832
+ Q(r, t.kind, e);
2833
+ for (let r of [
2834
+ t.start,
2835
+ t.delta,
2836
+ t.end
2837
+ ]) Q(n, r, e);
2838
+ $(t.fields, e);
2839
+ }
2840
+ let i = /* @__PURE__ */ new Map();
2841
+ for (let e of t) {
2842
+ let t = `input ${e.construct} '${e.kind}'`;
2843
+ if (Q(i, e.kind, t), e.construct === "event") $(e.fields, t);
2844
+ else {
2845
+ let n = /* @__PURE__ */ new Map();
2846
+ for (let r of e.parts) {
2847
+ let e = `${t} part '${r.partType}'`;
2848
+ Q(n, r.partType, e), $(r.fields, e);
2849
+ }
2850
+ }
2851
+ }
2852
+ }, jt = () => (e) => {
2853
+ let { reducer: t, decodeLifecycle: n } = e, r = e.output(Ct()), i = e.input(yt());
2854
+ At(r, i);
2855
+ let a = St(r, ee), o = vt(i, T), s = xt(r), c = gt(i);
2856
+ return {
2857
+ ...e.adapterTag === void 0 ? {} : { adapterTag: e.adapterTag },
2858
+ init: t.init,
2859
+ fold: t.fold,
2860
+ getMessages: t.getMessages,
2861
+ createEncoder: (e, t = {}) => new Tt(e, t, a, o),
2862
+ createDecoder: () => new kt(rt(Ot(s, c, n?.()), {})),
2863
+ ...wt()
2864
+ };
2865
+ };
1852
2866
  //#endregion
1853
- export { S as DOMAIN_HEADER_PREFIX, b as EVENT_ABORT, _ as EVENT_CANCEL, x as EVENT_ERROR, y as EVENT_TURN_END, v as EVENT_TURN_START, C as ErrorCode, L as EventEmitter, f as HEADER_CANCEL_ALL, p as HEADER_CANCEL_CLIENT_ID, d as HEADER_CANCEL_OWN, u as HEADER_CANCEL_TURN_ID, h as HEADER_FORK_OF, o as HEADER_MSG_ID, m as HEADER_PARENT, c as HEADER_ROLE, n as HEADER_STATUS, t as HEADER_STREAM, r as HEADER_STREAM_ID, s as HEADER_TURN_CLIENT_ID, a as HEADER_TURN_ID, g as HEADER_TURN_REASON, R as LogLevel, j as buildTransportHeaders, z as consoleLogger, fe as createClientTransport, he as createDecoderCore, $ as createEncoderCore, ve as createLifecycleTracker, ae as createServerTransport, ee as errorInfoIs, pe as eventOutput, w as getHeaders, k as headerReader, A as headerWriter, B as makeLogger, E as mergeHeaders, O as stripUndefined };
2867
+ export { b as EVENT_CANCEL, w as EVENT_RUN_END, x as EVENT_RUN_START, E as ErrorCode, K as EventEmitter, l as HEADER_CODEC_MESSAGE_ID, v as HEADER_ERROR_CODE, y as HEADER_ERROR_MESSAGE, m as HEADER_FORK_OF, d as HEADER_INPUT_CLIENT_ID, h as HEADER_MSG_REGENERATE, p as HEADER_PARENT, f as HEADER_ROLE, u as HEADER_RUN_CLIENT_ID, o as HEADER_RUN_ID, g as HEADER_RUN_REASON, r as HEADER_STATUS, n as HEADER_STREAM, i as HEADER_STREAM_ID, t as Invocation, D as LogLevel, ae as OBJECT_MODES, st as boolField, ge as buildTransportHeaders, O as consoleLogger, Ue as createAgentSession, $e as createClientSession, rt as createDecoderCore, tt as createEncoderCore, at as createLifecycleTracker, jt as defineCodec, lt as enumField, te as errorInfoIs, F as getCodecHeaders, P as getTransportHeaders, ct as jsonField, k as makeLogger, L as mergeHeaders, ot as strField, B as stripUndefined };
1854
2868
 
1855
2869
  //# sourceMappingURL=ably-ai-transport.js.map