@ably/ai-transport 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +114 -116
  2. package/dist/ably-ai-transport.js +1743 -961
  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 +117 -39
  7. package/dist/core/agent.d.ts +29 -0
  8. package/dist/core/codec/decoder.d.ts +20 -23
  9. package/dist/core/codec/encoder.d.ts +11 -8
  10. package/dist/core/codec/index.d.ts +1 -2
  11. package/dist/core/codec/lifecycle-tracker.d.ts +10 -9
  12. package/dist/core/codec/types.d.ts +410 -101
  13. package/dist/core/transport/agent-session.d.ts +10 -0
  14. package/dist/core/transport/branch-chain.d.ts +43 -0
  15. package/dist/core/transport/client-session.d.ts +13 -0
  16. package/dist/core/transport/decode-fold.d.ts +47 -0
  17. package/dist/core/transport/headers.d.ts +97 -17
  18. package/dist/core/transport/index.d.ts +5 -3
  19. package/dist/core/transport/internal/bounded-map.d.ts +20 -0
  20. package/dist/core/transport/invocation.d.ts +74 -0
  21. package/dist/core/transport/load-conversation.d.ts +128 -0
  22. package/dist/core/transport/load-history.d.ts +39 -0
  23. package/dist/core/transport/pipe-stream.d.ts +9 -8
  24. package/dist/core/transport/run-manager.d.ts +78 -0
  25. package/dist/core/transport/tree.d.ts +435 -0
  26. package/dist/core/transport/types/agent.d.ts +353 -0
  27. package/dist/core/transport/types/client.d.ts +168 -0
  28. package/dist/core/transport/types/shared.d.ts +24 -0
  29. package/dist/core/transport/types/tree.d.ts +315 -0
  30. package/dist/core/transport/types/view.d.ts +222 -0
  31. package/dist/core/transport/types.d.ts +13 -402
  32. package/dist/core/transport/view.d.ts +354 -0
  33. package/dist/errors.d.ts +37 -9
  34. package/dist/index.d.ts +6 -6
  35. package/dist/logger.d.ts +12 -0
  36. package/dist/react/ably-ai-transport-react.js +1164 -645
  37. package/dist/react/ably-ai-transport-react.js.map +1 -1
  38. package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
  39. package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
  40. package/dist/react/contexts/client-session-context.d.ts +36 -0
  41. package/dist/react/contexts/client-session-provider.d.ts +53 -0
  42. package/dist/react/create-session-hooks.d.ts +116 -0
  43. package/dist/react/index.d.ts +16 -10
  44. package/dist/react/internal/use-resolved-session.d.ts +36 -0
  45. package/dist/react/use-ably-messages.d.ts +20 -11
  46. package/dist/react/use-client-session.d.ts +81 -0
  47. package/dist/react/use-create-view.d.ts +23 -0
  48. package/dist/react/use-tree.d.ts +35 -0
  49. package/dist/react/use-view.d.ts +110 -0
  50. package/dist/utils.d.ts +32 -23
  51. package/dist/vercel/ably-ai-transport-vercel.js +2748 -1625
  52. package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
  53. package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
  54. package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
  55. package/dist/vercel/codec/decoder.d.ts +5 -18
  56. package/dist/vercel/codec/encoder.d.ts +6 -36
  57. package/dist/vercel/codec/events.d.ts +51 -0
  58. package/dist/vercel/codec/index.d.ts +24 -12
  59. package/dist/vercel/codec/reducer.d.ts +144 -0
  60. package/dist/vercel/codec/tool-transitions.d.ts +50 -0
  61. package/dist/vercel/index.d.ts +4 -2
  62. package/dist/vercel/react/ably-ai-transport-vercel-react.js +10298 -1410
  63. package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
  64. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +70 -1
  65. package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
  66. package/dist/vercel/react/contexts/chat-transport-context.d.ts +33 -0
  67. package/dist/vercel/react/contexts/chat-transport-provider.d.ts +96 -0
  68. package/dist/vercel/react/index.d.ts +4 -0
  69. package/dist/vercel/react/use-chat-transport.d.ts +66 -21
  70. package/dist/vercel/react/use-message-sync.d.ts +31 -12
  71. package/dist/vercel/run-end-reason.d.ts +29 -0
  72. package/dist/vercel/transport/chat-transport.d.ts +71 -30
  73. package/dist/vercel/transport/index.d.ts +25 -18
  74. package/dist/vercel/transport/run-output-stream.d.ts +56 -0
  75. package/dist/version.d.ts +2 -0
  76. package/package.json +47 -34
  77. package/src/constants.ts +126 -47
  78. package/src/core/agent.ts +68 -0
  79. package/src/core/codec/decoder.ts +71 -98
  80. package/src/core/codec/encoder.ts +115 -58
  81. package/src/core/codec/index.ts +13 -6
  82. package/src/core/codec/lifecycle-tracker.ts +10 -9
  83. package/src/core/codec/types.ts +438 -106
  84. package/src/core/transport/agent-session.ts +1344 -0
  85. package/src/core/transport/branch-chain.ts +58 -0
  86. package/src/core/transport/client-session.ts +775 -0
  87. package/src/core/transport/decode-fold.ts +91 -0
  88. package/src/core/transport/headers.ts +182 -19
  89. package/src/core/transport/index.ts +29 -22
  90. package/src/core/transport/internal/bounded-map.ts +27 -0
  91. package/src/core/transport/invocation.ts +98 -0
  92. package/src/core/transport/load-conversation.ts +355 -0
  93. package/src/core/transport/load-history.ts +269 -0
  94. package/src/core/transport/pipe-stream.ts +58 -40
  95. package/src/core/transport/run-manager.ts +249 -0
  96. package/src/core/transport/tree.ts +1167 -0
  97. package/src/core/transport/types/agent.ts +407 -0
  98. package/src/core/transport/types/client.ts +211 -0
  99. package/src/core/transport/types/shared.ts +27 -0
  100. package/src/core/transport/types/tree.ts +344 -0
  101. package/src/core/transport/types/view.ts +259 -0
  102. package/src/core/transport/types.ts +13 -527
  103. package/src/core/transport/view.ts +1271 -0
  104. package/src/errors.ts +42 -9
  105. package/src/event-emitter.ts +3 -2
  106. package/src/index.ts +55 -39
  107. package/src/logger.ts +14 -1
  108. package/src/react/contexts/client-session-context.ts +41 -0
  109. package/src/react/contexts/client-session-provider.tsx +186 -0
  110. package/src/react/create-session-hooks.ts +141 -0
  111. package/src/react/index.ts +27 -10
  112. package/src/react/internal/use-resolved-session.ts +63 -0
  113. package/src/react/use-ably-messages.ts +47 -19
  114. package/src/react/use-client-session.ts +201 -0
  115. package/src/react/use-create-view.ts +72 -0
  116. package/src/react/use-tree.ts +84 -0
  117. package/src/react/use-view.ts +275 -0
  118. package/src/react/vite.config.ts +4 -1
  119. package/src/utils.ts +63 -45
  120. package/src/vercel/codec/decoder.ts +336 -255
  121. package/src/vercel/codec/encoder.ts +348 -196
  122. package/src/vercel/codec/events.ts +87 -0
  123. package/src/vercel/codec/index.ts +59 -14
  124. package/src/vercel/codec/reducer.ts +977 -0
  125. package/src/vercel/codec/tool-transitions.ts +122 -0
  126. package/src/vercel/index.ts +7 -3
  127. package/src/vercel/react/contexts/chat-transport-context.ts +41 -0
  128. package/src/vercel/react/contexts/chat-transport-provider.tsx +150 -0
  129. package/src/vercel/react/index.ts +13 -1
  130. package/src/vercel/react/use-chat-transport.ts +162 -42
  131. package/src/vercel/react/use-message-sync.ts +121 -22
  132. package/src/vercel/react/vite.config.ts +4 -2
  133. package/src/vercel/run-end-reason.ts +78 -0
  134. package/src/vercel/transport/chat-transport.ts +553 -113
  135. package/src/vercel/transport/index.ts +40 -28
  136. package/src/vercel/transport/run-output-stream.ts +170 -0
  137. package/src/version.ts +2 -0
  138. package/dist/core/transport/client-transport.d.ts +0 -10
  139. package/dist/core/transport/conversation-tree.d.ts +0 -9
  140. package/dist/core/transport/decode-history.d.ts +0 -41
  141. package/dist/core/transport/server-transport.d.ts +0 -7
  142. package/dist/core/transport/stream-router.d.ts +0 -19
  143. package/dist/core/transport/turn-manager.d.ts +0 -34
  144. package/dist/react/use-active-turns.d.ts +0 -8
  145. package/dist/react/use-client-transport.d.ts +0 -7
  146. package/dist/react/use-conversation-tree.d.ts +0 -20
  147. package/dist/react/use-edit.d.ts +0 -7
  148. package/dist/react/use-history.d.ts +0 -19
  149. package/dist/react/use-messages.d.ts +0 -7
  150. package/dist/react/use-regenerate.d.ts +0 -7
  151. package/dist/react/use-send.d.ts +0 -7
  152. package/dist/vercel/codec/accumulator.d.ts +0 -21
  153. package/src/core/transport/client-transport.ts +0 -959
  154. package/src/core/transport/conversation-tree.ts +0 -434
  155. package/src/core/transport/decode-history.ts +0 -337
  156. package/src/core/transport/server-transport.ts +0 -458
  157. package/src/core/transport/stream-router.ts +0 -118
  158. package/src/core/transport/turn-manager.ts +0 -147
  159. package/src/react/use-active-turns.ts +0 -61
  160. package/src/react/use-client-transport.ts +0 -37
  161. package/src/react/use-conversation-tree.ts +0 -71
  162. package/src/react/use-edit.ts +0 -24
  163. package/src/react/use-history.ts +0 -111
  164. package/src/react/use-messages.ts +0 -32
  165. package/src/react/use-regenerate.ts +0 -24
  166. package/src/react/use-send.ts +0 -25
  167. package/src/vercel/codec/accumulator.ts +0 -603
@@ -1,365 +1,822 @@
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-turn-id", a = "x-ably-msg-id", o = "x-ably-turn-client-id", s = "x-ably-role", c = "x-ably-cancel-turn-id", l = "x-ably-cancel-own", u = "x-ably-cancel-all", d = "x-ably-cancel-client-id", f = "x-ably-parent", p = "x-ably-fork-of", m = "x-ably-turn-reason", h = "x-ably-cancel", g = "x-ably-turn-start", _ = "x-ably-turn-end", v = "x-ably-abort", y = "x-ably-error", b = "x-domain-", x = /* @__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;
5
- }({}), S = (e, t) => e.code === t, C = (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
- }, w = (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", T = /* @__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;
18
+ }({}), E = (e, t) => e.code === t, D = (e, t) => {
19
+ let n = e.extras;
20
+ if (!n || typeof n != "object") return {};
21
+ let r = n.ai;
22
+ if (!r || typeof r != "object") return {};
23
+ let i = r[t];
24
+ return !i || typeof i != "object" ? {} : i;
25
+ }, O = (e) => D(e, "transport"), k = (e) => D(e, "codec"), ee = (e) => {
11
26
  if (e !== void 0) try {
12
27
  return JSON.parse(e);
13
28
  } catch {
14
29
  return;
15
30
  }
16
- }, T = (e, t) => ({
31
+ }, A = (e, t) => ({
17
32
  ...e,
18
33
  ...t
19
- }), E = (e) => {
34
+ }), j = (e) => {
20
35
  if (e !== void 0) return e === "true";
21
- }, D = (e, t) => e[b + t], O = (e) => {
36
+ }, M = (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), N = (e, t) => e[t], P = (e) => {
22
37
  let t = {};
23
38
  for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && e[n] !== void 0 && (t[n] = e[n]);
24
39
  return t;
25
- }, k = (e) => ({
26
- str: (t) => D(e, t),
27
- strOr: (t, n) => D(e, t) ?? n,
28
- bool: (t) => E(D(e, t)),
29
- json: (t) => w(D(e, t))
30
- }), A = () => {
40
+ }, F = (e) => ({
41
+ str: (t) => N(e, t),
42
+ strOr: (t, n) => N(e, t) ?? n,
43
+ bool: (t) => j(N(e, t)),
44
+ json: (t) => ee(N(e, t))
45
+ }), I = () => {
31
46
  let e = {}, t = {
32
- str: (n, r) => (r !== void 0 && (e[b + n] = r), t),
33
- bool: (n, r) => (r !== void 0 && (e[b + n] = String(r)), t),
34
- json: (n, r) => (r != null && (e[b + n] = JSON.stringify(r)), t),
47
+ str: (n, r) => (r !== void 0 && (e[n] = r), t),
48
+ bool: (n, r) => (r !== void 0 && (e[n] = String(r)), t),
49
+ json: (n, r) => (r != null && (e[n] = JSON.stringify(r)), t),
35
50
  build: () => e
36
51
  };
37
52
  return t;
38
- }, j = (e) => {
53
+ }, L = "0.2.0", R = "ai-transport-js", z = (e, t) => {
54
+ let n = e;
55
+ return n.options.agents = {
56
+ ...n.options.agents,
57
+ ...t
58
+ }, { params: { agent: Object.entries(t).map(([e, t]) => `${e}/${t}`).join(" ") } };
59
+ }, B = (e, t) => {
60
+ let n = t?.adapterTag, r = { [R]: L };
61
+ return n && (r[n] = L), z(e, r);
62
+ }, V = (e) => {
39
63
  let t = {
40
- [s]: e.role,
41
- [i]: e.turnId,
42
- [a]: e.msgId
64
+ [f]: e.role,
65
+ [l]: e.codecMessageId
43
66
  };
44
- return e.turnClientId !== void 0 && (t[o] = e.turnClientId), e.parent && (t[f] = e.parent), e.forkOf && (t[p] = e.forkOf), t;
45
- }, M = async (e, t, n, r, i) => {
46
- i?.trace("pipeStream();");
47
- let a = e.getReader(), o, s = n ? new Promise((e) => {
48
- if (n.aborted) {
49
- e();
50
- return;
67
+ 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;
68
+ }, H = (e) => {
69
+ let t = {
70
+ [o]: e.runId,
71
+ [u]: e.runClientId
72
+ };
73
+ 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), t;
74
+ }, U = (e) => e === "ai-run-start" || e === "ai-run-suspend" || e === "ai-run-resume" || e === "ai-run-end", W = (e, t, n) => {
75
+ let r = t[o];
76
+ if (!r) return;
77
+ let i = t["run-client-id"] ?? "";
78
+ if (e === "ai-run-start") {
79
+ let e = t[p], a = t[m], o = t[h];
80
+ return {
81
+ type: "start",
82
+ runId: r,
83
+ clientId: i,
84
+ serial: n,
85
+ invocationId: t["invocation-id"] ?? "",
86
+ ...e !== void 0 && { parent: e },
87
+ ...a !== void 0 && { forkOf: a },
88
+ ...o !== void 0 && { regenerates: o }
89
+ };
90
+ }
91
+ if (e === "ai-run-suspend") return {
92
+ type: "suspend",
93
+ runId: r,
94
+ clientId: i,
95
+ serial: n,
96
+ invocationId: t["invocation-id"] ?? ""
97
+ };
98
+ if (e === "ai-run-resume") return {
99
+ type: "resume",
100
+ runId: r,
101
+ clientId: i,
102
+ serial: n,
103
+ invocationId: t["invocation-id"] ?? ""
104
+ };
105
+ if (e === "ai-run-end") {
106
+ let e = t["run-reason"] ?? "complete";
107
+ return {
108
+ type: "end",
109
+ runId: r,
110
+ clientId: i,
111
+ serial: n,
112
+ invocationId: t["invocation-id"] ?? "",
113
+ reason: e
114
+ };
115
+ }
116
+ }, G = (e, t, n) => {
117
+ if (e.has(t) || e.size < n) return;
118
+ let r = e.keys().next().value;
119
+ if (r !== void 0) return e.delete(r), r;
120
+ }, K = (e, t) => {
121
+ let n = [], r = /* @__PURE__ */ new Set(), i = t;
122
+ for (; i !== void 0 && !r.has(i);) r.add(i), n.push(i), i = e.get(i)?.parentCodecMessageId;
123
+ return n.toReversed();
124
+ }, q = (e, t, n) => {
125
+ let r = O(n), i = n.serial;
126
+ if (U(n.name)) {
127
+ let t = W(n.name, r, i);
128
+ return t && e.applyRunLifecycle(t), t;
129
+ }
130
+ let { inputs: a, outputs: o } = t.decode(n);
131
+ (a.length > 0 || o.length > 0 || r["run-id"]) && e.applyMessage({
132
+ inputs: a,
133
+ outputs: o
134
+ }, r, i);
135
+ }, te = (e, t, n, r, i) => {
136
+ let { inputs: a, outputs: o } = t.decode(r), s = n;
137
+ for (let t of [...a, ...o]) s = e.fold(s, t, {
138
+ serial: r.serial ?? "",
139
+ messageId: i
140
+ });
141
+ return s;
142
+ }, ne = (e, t) => {
143
+ let n = /* @__PURE__ */ new Set(), r = [];
144
+ for (let t of e) t.serial !== void 0 && !n.has(t.serial) && (n.add(t.serial), r.push(t));
145
+ if (t !== void 0) for (let e of t) e.serial !== void 0 && !n.has(e.serial) && (n.add(e.serial), r.push(e));
146
+ return r.toSorted(M);
147
+ }, re = async (e, t, n) => {
148
+ let r = [], i = await e.history({ limit: t });
149
+ for (r.push(...i.items); i.hasNext() && r.length < n;) {
150
+ let e = await i.next();
151
+ if (!e) break;
152
+ r.push(...e.items), i = e;
153
+ }
154
+ return r;
155
+ }, J = (e, t, n, r) => {
156
+ let i = e.createDecoder(), a = e.init(), o = 0;
157
+ for (let s of t) {
158
+ let t = O(s);
159
+ if (t["run-id"] !== n || U(s.name)) continue;
160
+ let c = t[l];
161
+ if (r !== void 0 && c === r) break;
162
+ a = te(e, i, a, s, c ?? ""), o++;
163
+ }
164
+ return {
165
+ projection: a,
166
+ folded: o
167
+ };
168
+ }, ie = (e, t, n) => {
169
+ let r = e.createDecoder(), i = e.init();
170
+ for (let a of t) {
171
+ let t = O(a);
172
+ t["run-id"] === void 0 && t["codec-message-id"] === n && (i = te(e, r, i, a, n));
173
+ }
174
+ return i;
175
+ }, ae = async (t) => {
176
+ let { channel: n, codec: r, runId: i, signal: a, logger: o, liveMessages: s } = t;
177
+ if (a.aborted) throw new e.ErrorInfo(`unable to load run projection; run ${i} was cancelled`, T.InvalidArgument, 400);
178
+ await n.attach();
179
+ let { projection: c, folded: l } = J(r, ne(await re(n, 200, 2e3), s), i);
180
+ return o?.debug("loadRunProjection(); folded run events", {
181
+ runId: i,
182
+ folded: l
183
+ }), c;
184
+ }, oe = async (t) => {
185
+ let { channel: n, codec: r, runId: i, signal: a, logger: s, liveMessages: c, assistantParentFallback: u, pageLimit: d, maxMessages: f } = t;
186
+ if (a.aborted) throw new e.ErrorInfo(`unable to load conversation; run ${i} was cancelled`, T.InvalidArgument, 400);
187
+ let m = ne(await re(n, d, f), c), h = /* @__PURE__ */ new Map(), g = /* @__PURE__ */ new Map();
188
+ for (let e of m) {
189
+ if (U(e.name)) continue;
190
+ let t = O(e), n = t[l];
191
+ if (n === void 0) continue;
192
+ let r = t[o];
193
+ r !== void 0 && g.set(r, n), h.has(n) || h.set(n, {
194
+ runId: r,
195
+ parentCodecMessageId: t[p]
196
+ });
197
+ }
198
+ for (let e of m) {
199
+ if (e.name !== "ai-run-start") continue;
200
+ let t = O(e), n = t[o];
201
+ if (n === void 0) continue;
202
+ let r = g.get(n);
203
+ if (r === void 0) continue;
204
+ let i = h.get(r);
205
+ i && i.parentCodecMessageId === void 0 && (i.parentCodecMessageId = t[p]);
206
+ }
207
+ let _ = [], v = 0;
208
+ if (u !== void 0) {
209
+ let e = K(h, u);
210
+ v = e.length;
211
+ for (let t of e) {
212
+ let e = h.get(t);
213
+ if (e?.runId === i) continue;
214
+ let n = e?.runId === void 0 ? ie(r, m, t) : J(r, m, e.runId).projection;
215
+ _.push(...r.getMessages(n).map((e) => e.message));
51
216
  }
52
- o = () => {
53
- e();
54
- }, n.addEventListener("abort", o, { once: !0 });
55
- }) : new Promise(() => {}), c = "complete";
217
+ }
218
+ let { projection: y, folded: b } = J(r, m, i);
219
+ return _.push(...r.getMessages(y).map((e) => e.message)), s?.debug("loadConversation(); built", {
220
+ runId: i,
221
+ chainLength: v,
222
+ totalMessages: _.length,
223
+ folded: b
224
+ }), {
225
+ messages: _,
226
+ projection: y
227
+ };
228
+ }, se = (e) => {
229
+ let t;
230
+ return {
231
+ promise: e === void 0 ? new Promise(() => {}) : e.aborted ? Promise.resolve() : new Promise((n) => {
232
+ t = () => {
233
+ n();
234
+ }, e.addEventListener("abort", t, { once: !0 });
235
+ }),
236
+ cleanup: () => {
237
+ t && e && e.removeEventListener("abort", t);
238
+ }
239
+ };
240
+ }, ce = async (e, t, n, r, i, a) => {
241
+ a?.trace("pipeStream();");
242
+ let o = e.getReader(), s = se(n), c = "complete", l;
56
243
  try {
57
244
  for (;;) {
58
- let e = await Promise.race([a.read(), s.then(() => "aborted")]);
59
- if (e === "aborted") {
60
- c = "cancelled", i?.debug("pipeStream(); stream cancelled by abort signal"), r && await r(async (e) => t.appendEvent(e)), await t.abort("cancelled");
245
+ let e = await Promise.race([o.read(), s.promise.then(() => "cancelled")]);
246
+ if (e === "cancelled") {
247
+ c = "cancelled", a?.debug("pipeStream(); stream cancelled by AbortSignal"), r && await r(async (e) => t.publishOutput(e)), await t.cancel("cancelled");
61
248
  break;
62
249
  }
63
- let { done: n, value: o } = e;
250
+ let { done: n, value: l } = e;
64
251
  if (n) {
65
- await t.close(), i?.debug("pipeStream(); stream completed");
252
+ await t.close(), a?.debug("pipeStream(); stream completed");
66
253
  break;
67
254
  }
68
- await t.appendEvent(o);
255
+ await t.publishOutput(l, i?.(l));
69
256
  }
70
257
  } catch (e) {
71
- c = "error";
72
- let n = e instanceof Error ? e.message : String(e);
73
- i?.error("pipeStream(); stream error", { error: n });
258
+ c = "error", l = e instanceof Error ? e : Error(String(e)), a?.error("pipeStream(); stream error", { error: l.message });
74
259
  try {
75
260
  await t.close();
76
261
  } catch {}
77
262
  } finally {
78
- o && n?.removeEventListener("abort", o), a.releaseLock();
263
+ s.cleanup(), o.releaseLock();
79
264
  }
80
- return { reason: c };
81
- }, N = class {
265
+ return {
266
+ reason: c,
267
+ error: l
268
+ };
269
+ }, le = class {
82
270
  constructor(e, t) {
83
- this._activeTurns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "TurnManager" });
271
+ this._activeRuns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "RunManager" });
84
272
  }
85
- async startTurn(e, t, n) {
86
- this._logger?.trace("DefaultTurnManager.startTurn();", {
87
- turnId: e,
273
+ async startRun(e, t, n, r) {
274
+ this._logger?.trace("DefaultRunManager.startRun();", {
275
+ runId: e,
88
276
  clientId: t
89
277
  });
90
- let r = n ?? new AbortController(), a = t ?? "";
91
- return this._activeTurns.set(e, {
92
- controller: r,
278
+ let i = n ?? new AbortController(), a = t ?? "";
279
+ this._activeRuns.set(e, {
280
+ controller: i,
93
281
  clientId: a
94
- }), await this._channel.publish({
95
- name: g,
96
- extras: { headers: {
97
- [i]: e,
98
- [o]: a
99
- } }
100
- }), this._logger?.debug("DefaultTurnManager.startTurn(); turn started", { turnId: e }), r.signal;
101
- }
102
- async endTurn(e, t) {
103
- this._logger?.trace("DefaultTurnManager.endTurn();", {
104
- turnId: e,
105
- reason: t
106
282
  });
107
- let n = this._activeTurns.get(e)?.clientId ?? "";
108
- await this._channel.publish({
109
- name: _,
110
- extras: { headers: {
111
- [i]: e,
112
- [o]: n,
113
- [m]: t
114
- } }
115
- }), this._activeTurns.delete(e), this._logger?.debug("DefaultTurnManager.endTurn(); turn ended", {
116
- turnId: e,
283
+ let o = r?.continuation === !0, s = H({
284
+ runId: e,
285
+ runClientId: a,
286
+ parent: o ? void 0 : r?.parent,
287
+ forkOf: o ? void 0 : r?.forkOf,
288
+ regenerates: o ? void 0 : r?.regenerates,
289
+ invocationId: r?.invocationId,
290
+ inputClientId: r?.inputClientId,
291
+ inputCodecMessageId: r?.inputCodecMessageId
292
+ });
293
+ return await this._channel.publish({
294
+ name: o ? C : x,
295
+ extras: { ai: { transport: s } }
296
+ }), this._logger?.debug("DefaultRunManager.startRun(); run started", { runId: e }), i.signal;
297
+ }
298
+ async suspendRun(e, t, n, r) {
299
+ this._logger?.trace("DefaultRunManager.suspendRun();", { runId: e }), await this._publishTerminal(S, e, {
300
+ invocationId: t,
301
+ inputClientId: n,
302
+ inputCodecMessageId: r
303
+ }), this._logger?.debug("DefaultRunManager.suspendRun(); run suspended", { runId: e });
304
+ }
305
+ async endRun(e, t, n, r, i) {
306
+ this._logger?.trace("DefaultRunManager.endRun();", {
307
+ runId: e,
308
+ reason: t
309
+ }), await this._publishTerminal(w, e, {
310
+ reason: t,
311
+ invocationId: n,
312
+ inputClientId: r,
313
+ inputCodecMessageId: i
314
+ }), this._logger?.debug("DefaultRunManager.endRun(); run ended", {
315
+ runId: e,
117
316
  reason: t
118
317
  });
119
318
  }
319
+ async _publishTerminal(e, t, n) {
320
+ let r = H({
321
+ runId: t,
322
+ runClientId: this._activeRuns.get(t)?.clientId ?? "",
323
+ ...n
324
+ });
325
+ await this._channel.publish({
326
+ name: e,
327
+ extras: { ai: { transport: r } }
328
+ }), this._activeRuns.delete(t);
329
+ }
120
330
  getSignal(e) {
121
- return this._activeTurns.get(e)?.controller.signal;
331
+ return this._activeRuns.get(e)?.controller.signal;
122
332
  }
123
333
  getClientId(e) {
124
- return this._activeTurns.get(e)?.clientId;
334
+ return this._activeRuns.get(e)?.clientId;
125
335
  }
126
- abort(e) {
127
- this._logger?.debug("DefaultTurnManager.abort();", { turnId: e }), this._activeTurns.get(e)?.controller.abort();
336
+ cancel(e) {
337
+ this._logger?.debug("DefaultRunManager.cancel();", { runId: e }), this._activeRuns.get(e)?.controller.abort();
128
338
  }
129
- getActiveTurnIds() {
130
- return [...this._activeTurns.keys()];
339
+ getActiveRunIds() {
340
+ return [...this._activeRuns.keys()];
131
341
  }
132
342
  close() {
133
- this._logger?.trace("DefaultTurnManager.close();", { activeTurns: this._activeTurns.size });
134
- for (let e of this._activeTurns.values()) e.controller.abort();
135
- this._activeTurns.clear();
136
- }
137
- }, P = (e, t) => new N(e, t), ee = class {
138
- constructor(t) {
139
- this._registeredTurns = /* @__PURE__ */ new Map(), this._channel = t.channel, this._codec = t.codec, this._logger = t.logger?.withContext({ component: "ServerTransport" }), this._onError = t.onError, this._turnManager = P(this._channel, this._logger), this._channelListener = (e) => {
343
+ this._logger?.trace("DefaultRunManager.close();", { activeRuns: this._activeRuns.size });
344
+ for (let e of this._activeRuns.values()) e.controller.abort();
345
+ this._activeRuns.clear();
346
+ }
347
+ }, ue = (e, t) => new le(e, t), de = async (t) => {
348
+ let { register: n, codec: r, invocationId: i, runId: a, expectedInputEventIds: o, timeoutMs: s, signal: l, logger: u } = t, d = new Set(o), f = d.size, h = [], g = [], _ = /* @__PURE__ */ new Set(), v, y, b = (e) => {
349
+ let t = r.createDecoder(), n = O(e), i = n["codec-message-id"] ?? "", { inputs: a, outputs: o } = t.decode(e), s = [...a, ...o], c = r.init();
350
+ for (let t of s) c = r.fold(c, t, {
351
+ serial: e.serial ?? "",
352
+ messageId: i
353
+ });
354
+ return r.getMessages(c).map(({ message: t }) => ({
355
+ kind: "message",
356
+ message: t,
357
+ codecMessageId: i,
358
+ parentId: n[p],
359
+ forkOf: n[m],
360
+ headers: n,
361
+ serial: e.serial
362
+ }));
363
+ };
364
+ return new Promise((t, r) => {
365
+ let o = !1, p = /* @__PURE__ */ new Set(), m = () => {}, x, S = () => {
366
+ m(), x !== void 0 && clearTimeout(x), l.removeEventListener("abort", C);
367
+ }, C = () => {
368
+ o || (o = !0, S(), r(new e.ErrorInfo(`unable to look up input event; run ${a} was cancelled`, T.InvalidArgument, 400)));
369
+ };
370
+ if (l.addEventListener("abort", C, { once: !0 }), !o) {
371
+ if (m = n((n) => {
372
+ if (o || n.serial !== void 0 && p.has(n.serial)) return;
373
+ n.serial !== void 0 && p.add(n.serial);
374
+ let s = O(n), l = s[c];
375
+ if (!l || !d.has(l) || _.has(l)) return;
376
+ _.add(l), v === void 0 && (v = s, y = n.clientId);
377
+ let m;
378
+ try {
379
+ m = b(n);
380
+ } catch (t) {
381
+ o = !0, S();
382
+ let n = t instanceof e.ErrorInfo ? t : void 0;
383
+ r(new e.ErrorInfo(`unable to look up input event; decode failed for invocation ${i}: ${t instanceof Error ? t.message : String(t)}`, T.InputEventNotFound, 504, n));
384
+ return;
385
+ }
386
+ for (let e of m) h.push(e);
387
+ g.push(n), !(_.size < f) && (o = !0, S(), h.sort(M), u?.debug("lookupInputEvents(); collected input events", {
388
+ runId: a,
389
+ invocationId: i,
390
+ count: h.length
391
+ }), t({
392
+ nodes: h,
393
+ firstHeaders: v,
394
+ firstClientId: y,
395
+ rawMessages: g
396
+ }));
397
+ }), o) {
398
+ m();
399
+ return;
400
+ }
401
+ x = setTimeout(() => {
402
+ o || (o = !0, S(), r(new e.ErrorInfo(`unable to look up input event; received ${String(h.length)} of ${String(f)} input events for invocation ${i} within ${String(s)}ms`, T.InputEventNotFound, 504)));
403
+ }, s);
404
+ }
405
+ });
406
+ }, fe = class {
407
+ constructor(e) {
408
+ this._registeredRuns = /* @__PURE__ */ new Map(), this._runIdByInputCodecMessageId = /* @__PURE__ */ new Map(), this._deferredCancels = /* @__PURE__ */ new Map(), this._pendingInputEventLookups = /* @__PURE__ */ new Map(), this._inputEventBuffer = /* @__PURE__ */ new Map(), this._state = "ready", this._codec = e.codec;
409
+ let t = { params: {
410
+ ...B(e.client, e.codec).params,
411
+ rewind: e.rewindWindow ?? "2m"
412
+ } };
413
+ this._channel = e.client.channels.get(e.channelName, t), this._logger = e.logger?.withContext({ component: "AgentSession" }), this._onError = e.onError, this._runManager = ue(this._channel, this._logger), this._inputEventLookupTimeoutMs = e.inputEventLookupTimeoutMs ?? 3e4, this._inputEventBufferLimit = e.inputEventBufferLimit ?? 200, this._channelListener = (e) => {
140
414
  this._handleChannelMessage(e);
141
- }, this._attachPromise = this._channel.subscribe(h, this._channelListener).then(() => {}, (t) => {
142
- let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`, x.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
143
- this._logger?.error("DefaultServerTransport(); subscribe failed"), this._onError?.(n);
144
- }), this._logger?.debug("DefaultServerTransport(); transport created");
415
+ }, this._hasAttachedOnce = this._channel.state === "attached", this._onChannelStateChange = (e) => {
416
+ this._handleChannelStateChange(e);
417
+ }, this._channel.on(this._onChannelStateChange), this._logger?.debug("DefaultAgentSession(); session created");
418
+ }
419
+ connect() {
420
+ return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", T.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger?.trace("DefaultAgentSession.connect();"), this._connectPromise = this._channel.subscribe(this._channelListener).then(() => {
421
+ this._logger?.debug("DefaultAgentSession.connect(); subscribed and attached");
422
+ }, (t) => {
423
+ let n = new e.ErrorInfo(`unable to subscribe to channel; ${t instanceof Error ? t.message : String(t)}`, T.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
424
+ throw this._logger?.error("DefaultAgentSession.connect(); subscribe failed"), this._onError?.(n), n;
425
+ }), this._connectPromise);
426
+ }
427
+ _registerInputEventListener(e, t) {
428
+ for (let n of e) this._pendingInputEventLookups.set(n, t);
429
+ for (let n of e) {
430
+ let e = this._inputEventBuffer.get(n);
431
+ if (e) {
432
+ this._inputEventBuffer.delete(n);
433
+ for (let n of e) t(n);
434
+ }
435
+ }
436
+ return () => {
437
+ for (let n of e) this._pendingInputEventLookups.get(n) === t && this._pendingInputEventLookups.delete(n);
438
+ };
145
439
  }
146
- newTurn(e) {
147
- return this._logger?.trace("DefaultServerTransport.newTurn();", { turnId: e.turnId }), this._createTurn(e);
440
+ createRun(e, t) {
441
+ return this._logger?.trace("DefaultAgentSession.createRun();", { inputEventId: e.inputEventId }), this._createRun(e, t ?? {});
148
442
  }
149
- close() {
150
- this._logger?.trace("DefaultServerTransport.close();"), this._channel.unsubscribe(h, this._channelListener);
151
- for (let e of this._registeredTurns.values()) e.controller.abort();
152
- this._registeredTurns.clear(), this._turnManager.close(), this._logger?.debug("DefaultServerTransport.close(); transport closed");
153
- }
154
- _resolveFilter(e, t) {
155
- let n = [...this._registeredTurns.keys()];
156
- 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] : [];
157
- }
158
- async _handleCancelMessage(t) {
159
- let n = C(t), r = {};
160
- n["x-ably-cancel-turn-id"] ? r.turnId = n[c] : n["x-ably-cancel-own"] === "true" ? r.own = !0 : n["x-ably-cancel-client-id"] ? r.clientId = n[d] : n["x-ably-cancel-all"] === "true" && (r.all = !0);
161
- let i = this._resolveFilter(r, t.clientId);
162
- if (i.length === 0) return;
163
- this._logger?.debug("DefaultServerTransport._handleCancelMessage(); matched turns", {
164
- matchedTurnIds: i,
165
- filter: r
166
- });
167
- let a = /* @__PURE__ */ new Map();
168
- for (let e of i) {
169
- let t = this._registeredTurns.get(e);
170
- a.set(e, t?.clientId ?? "");
443
+ async close() {
444
+ if (this._state !== "closed") {
445
+ this._state = "closed", this._logger?.trace("DefaultAgentSession.close();"), this._connectPromise && this._channel.unsubscribe(this._channelListener), this._channel.off(this._onChannelStateChange);
446
+ for (let e of this._registeredRuns.values()) e.controller.abort();
447
+ if (this._registeredRuns.clear(), this._runIdByInputCodecMessageId.clear(), this._deferredCancels.clear(), this._pendingInputEventLookups.clear(), this._inputEventBuffer.clear(), this._runManager.close(), this._connectPromise) try {
448
+ await this._channel.detach();
449
+ } catch (e) {
450
+ this._logger?.debug("DefaultAgentSession.close(); channel detach failed", { error: e });
451
+ }
452
+ this._logger?.debug("DefaultAgentSession.close(); session closed");
171
453
  }
172
- let o = {
173
- message: t,
174
- filter: r,
175
- matchedTurnIds: i,
176
- turnOwners: a
454
+ }
455
+ async _handleCancelMessage(e) {
456
+ let t = O(e), n = t[o], r = t[_];
457
+ if (!n && !r) {
458
+ this._logger?.warn("DefaultAgentSession._handleCancelMessage(); missing run-id and input-codec-message-id", { serial: e.serial });
459
+ return;
460
+ }
461
+ let i = n ?? (r ? this._runIdByInputCodecMessageId.get(r) : void 0), a = i ? this._registeredRuns.get(i) : void 0;
462
+ if (!a) {
463
+ r !== void 0 && this._bufferDeferredCancel(r, e);
464
+ return;
465
+ }
466
+ await this._cancelRegistration(a, e);
467
+ }
468
+ _bufferDeferredCancel(e, t) {
469
+ let n = G(this._deferredCancels, e, this._inputEventBufferLimit);
470
+ n !== void 0 && this._logger?.warn("DefaultAgentSession._bufferDeferredCancel(); deferred-cancel buffer full, dropping oldest", {
471
+ evictedInputCodecMessageId: n,
472
+ limit: this._inputEventBufferLimit
473
+ }), this._deferredCancels.set(e, t), this._logger?.debug("DefaultAgentSession._bufferDeferredCancel(); buffered early cancel", {
474
+ inputCodecMessageId: e,
475
+ serial: t.serial
476
+ });
477
+ }
478
+ async _pullDeferredCancel(e, t) {
479
+ let n = this._deferredCancels.get(t);
480
+ n !== void 0 && (this._deferredCancels.delete(t), this._logger?.debug("DefaultAgentSession._pullDeferredCancel(); honouring buffered cancel", {
481
+ runId: e.runId,
482
+ inputCodecMessageId: t
483
+ }), await this._cancelRegistration(e, n));
484
+ }
485
+ async _cancelRegistration(t, n) {
486
+ let { runId: r } = t;
487
+ this._logger?.debug("DefaultAgentSession._cancelRegistration(); matched run", { runId: r });
488
+ let i = {
489
+ message: n,
490
+ runId: r
177
491
  };
178
- for (let t of i) {
179
- let n = this._registeredTurns.get(t);
180
- if (n) try {
181
- if (n.onCancel && !await n.onCancel(o)) {
182
- this._logger?.debug("DefaultServerTransport._handleCancelMessage(); cancel rejected by onCancel", { turnId: t });
183
- continue;
184
- }
185
- n.controller.abort(), this._logger?.debug("DefaultServerTransport._handleCancelMessage(); turn aborted", { turnId: t });
186
- } catch (r) {
187
- let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`, x.CancelListenerError, 500, r instanceof e.ErrorInfo ? r : void 0);
188
- this._logger?.error("DefaultServerTransport._handleCancelMessage(); onCancel threw", { turnId: t }), (n.onError ?? this._onError)?.(i);
492
+ try {
493
+ if (t.onCancel && !await t.onCancel(i)) {
494
+ this._logger?.debug("DefaultAgentSession._cancelRegistration(); cancel rejected by onCancel", { runId: r });
495
+ return;
189
496
  }
497
+ t.controller.abort(), this._logger?.debug("DefaultAgentSession._cancelRegistration(); run cancelled", { runId: r });
498
+ } catch (n) {
499
+ let i = new e.ErrorInfo(`unable to process cancel for run ${r}; onCancel handler threw: ${n instanceof Error ? n.message : String(n)}`, T.CancelListenerError, 500, n instanceof e.ErrorInfo ? n : void 0);
500
+ this._logger?.error("DefaultAgentSession._cancelRegistration(); onCancel threw", { runId: r }), (t.onError ?? this._onError)?.(i);
501
+ }
502
+ }
503
+ _handleChannelStateChange(t) {
504
+ if (this._state === "closed") return;
505
+ let { current: n, resumed: r } = t;
506
+ if (n === "attached" && !this._hasAttachedOnce) {
507
+ this._hasAttachedOnce = !0;
508
+ return;
190
509
  }
510
+ if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
511
+ this._logger?.error("DefaultAgentSession._handleChannelStateChange(); channel continuity lost", {
512
+ current: n,
513
+ resumed: r,
514
+ previous: t.previous
515
+ });
516
+ let i = new e.ErrorInfo(`unable to deliver cancel messages; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, T.ChannelContinuityLost, 500, t.reason);
517
+ this._onError?.(i);
191
518
  }
192
519
  _handleChannelMessage(t) {
193
520
  try {
194
- t.name === "x-ably-cancel" && this._handleCancelMessage(t).catch((t) => {
195
- let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`, x.CancelListenerError, 500, t instanceof e.ErrorInfo ? t : void 0);
196
- this._logger?.error("DefaultServerTransport._handleChannelMessage(); cancel routing error"), this._onError?.(n);
197
- });
521
+ if (t.name === "ai-cancel") {
522
+ this._handleCancelMessage(t).catch((t) => {
523
+ let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`, T.CancelListenerError, 500, t instanceof e.ErrorInfo ? t : void 0);
524
+ this._logger?.error("DefaultAgentSession._handleChannelMessage(); cancel routing error"), this._onError?.(n);
525
+ });
526
+ return;
527
+ }
528
+ let n = O(t)[c];
529
+ if (n !== void 0) {
530
+ let e = this._pendingInputEventLookups.get(n);
531
+ if (e) e(t);
532
+ else {
533
+ let e = this._inputEventBuffer.get(n);
534
+ if (e) e.push(t);
535
+ else {
536
+ let e = G(this._inputEventBuffer, n, this._inputEventBufferLimit);
537
+ e !== void 0 && this._logger?.warn("DefaultAgentSession._handleChannelMessage(); input-event buffer full, dropping oldest entry", {
538
+ evictedEventId: e,
539
+ limit: this._inputEventBufferLimit
540
+ }), this._inputEventBuffer.set(n, [t]);
541
+ }
542
+ }
543
+ }
198
544
  } catch (t) {
199
- let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, x.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
200
- this._logger?.error("DefaultServerTransport._handleChannelMessage(); subscription error"), this._onError?.(n);
545
+ let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, T.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
546
+ this._logger?.error("DefaultAgentSession._handleChannelMessage(); subscription error"), this._onError?.(n);
201
547
  }
202
548
  }
203
- _createTurn(t) {
204
- let { turnId: n, clientId: r, onMessage: i, onAbort: a, onCancel: o, onError: s, parent: c, forkOf: l } = t, u = new AbortController(), d = !1, f = !1, p = {
205
- turnId: n,
206
- clientId: r ?? "",
207
- controller: u,
208
- onCancel: o,
209
- onError: s
549
+ async _requireConnected(t) {
550
+ if (!this._connectPromise) throw new e.ErrorInfo(`unable to ${t}; connect() must be called before ${t}()`, T.InvalidArgument, 400);
551
+ return this._connectPromise;
552
+ }
553
+ _createRun(t, n) {
554
+ let r = n.runId ?? crypto.randomUUID(), i = n.invocationId ?? crypto.randomUUID(), a = this._inputEventLookupTimeoutMs, { onMessage: s, onCancelled: c, onCancel: d, onError: f, signal: g } = n, _ = new AbortController(), v = "initialized", y = g ? AbortSignal.any([_.signal, g]) : _.signal, b = {
555
+ runId: r,
556
+ invocationId: i,
557
+ controller: _,
558
+ signal: y,
559
+ onCancel: d,
560
+ onError: f
210
561
  };
211
- this._registeredTurns.set(n, p);
212
- let m = this._logger, h = this._turnManager, g = this._attachPromise, _ = this._codec, v = this._channel, y = this._registeredTurns;
562
+ this._registeredRuns.set(r, b);
563
+ let x = this._logger, S = this._runManager, C = this._codec, w = this._channel, E = this._registeredRuns, D = this._runIdByInputCodecMessageId, O = this._deferredCancels, k = this._requireConnected.bind(this), ee = this._registerInputEventListener.bind(this), A = this._pullDeferredCancel.bind(this), j = t.inputEventId, M = [], N = { get messages() {
564
+ return M;
565
+ } }, P, F, I, L, R, z, B = !1, H, U, W, G = () => {
566
+ E.delete(r), z !== void 0 && (D.delete(z), O.delete(z));
567
+ }, K, q;
213
568
  return {
214
- get turnId() {
215
- return n;
569
+ get runId() {
570
+ return r;
571
+ },
572
+ get invocationId() {
573
+ return i;
216
574
  },
217
575
  get abortSignal() {
218
- return u.signal;
576
+ return y;
577
+ },
578
+ get view() {
579
+ return N;
580
+ },
581
+ get messages() {
582
+ return q === void 0 ? K === void 0 ? M.map((e) => e.message) : C.getMessages(K).map((e) => e.message) : [...q];
219
583
  },
220
584
  start: async () => {
221
- if (m?.trace("Turn.start();", { turnId: n }), u.signal.aborted) throw new e.ErrorInfo(`unable to start turn; turn ${n} was cancelled before start()`, x.InvalidArgument, 400);
222
- if (!d) {
223
- d = !0;
224
- try {
225
- await h.startTurn(n, r, u);
226
- } catch (t) {
227
- let r = new e.ErrorInfo(`unable to publish turn-start for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, x.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
228
- throw m?.error("Turn.start(); failed to publish turn-start", { turnId: n }), s?.(r), r;
229
- }
230
- m?.debug("Turn.start(); turn started", { turnId: n });
585
+ if (x?.trace("Run.start();", {
586
+ runId: r,
587
+ inputEventId: j
588
+ }), await k("start"), y.aborted) throw new e.ErrorInfo(`unable to start run; run ${r} was cancelled before start()`, T.InvalidArgument, 400);
589
+ if (v !== "initialized") return;
590
+ if (v = "started", j && a > 0) try {
591
+ let e = await de({
592
+ register: (e) => ee([j], e),
593
+ codec: C,
594
+ invocationId: i,
595
+ runId: r,
596
+ expectedInputEventIds: [j],
597
+ timeoutMs: a,
598
+ signal: y,
599
+ logger: x
600
+ });
601
+ for (let t of e.nodes) M.push(t);
602
+ e.firstHeaders !== void 0 && (H = e.firstHeaders), e.firstClientId !== void 0 && (F = e.firstClientId), W = e.rawMessages;
603
+ } catch (t) {
604
+ let n = t instanceof e.ErrorInfo ? t : new e.ErrorInfo(`unable to look up input event; ${t instanceof Error ? t.message : String(t)}`, T.InputEventNotFound, 504);
605
+ throw G(), x?.error("Run.start(); input-event lookup failed", {
606
+ runId: r,
607
+ invocationId: i
608
+ }), n;
609
+ }
610
+ let t = H ?? M[0]?.headers;
611
+ if (t) {
612
+ P = t[u], I = t[p], L = t[m], R = t[h], z = t[l];
613
+ let e = t[o];
614
+ B = e !== void 0, e !== void 0 && e !== r && (E.delete(r), r = e, b.runId = r, E.set(r, b));
231
615
  }
616
+ U = M.at(-1)?.codecMessageId ?? I, z !== void 0 && (D.set(z, r), await A(b, z));
617
+ try {
618
+ await S.startRun(r, P, _, {
619
+ parent: U,
620
+ forkOf: L,
621
+ regenerates: R,
622
+ invocationId: i,
623
+ inputClientId: F,
624
+ inputCodecMessageId: z,
625
+ continuation: B
626
+ });
627
+ } catch (t) {
628
+ let n = new e.ErrorInfo(`unable to publish run-start for run ${r}; ${t instanceof Error ? t.message : String(t)}`, T.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
629
+ throw x?.error("Run.start(); failed to publish run-start", { runId: r }), n;
630
+ }
631
+ x?.debug("Run.start(); run started", {
632
+ runId: r,
633
+ inputEventId: j
634
+ });
232
635
  },
233
- addMessages: async (t, r) => {
234
- if (m?.trace("Turn.addMessages();", {
235
- turnId: n,
636
+ addEvents: async (t) => {
637
+ if (x?.trace("Run.addEvents();", {
638
+ runId: r,
236
639
  count: t.length
237
- }), !d) throw new e.ErrorInfo(`unable to add messages; start() must be called before addMessages() (turn ${n})`, x.InvalidArgument, 400);
238
- await g;
239
- let a = [];
240
- for (let e of t) {
241
- let t = crypto.randomUUID(), o = T(j({
242
- role: "user",
243
- turnId: n,
244
- msgId: t,
245
- turnClientId: r?.clientId,
246
- parent: r?.parent === void 0 ? c ?? void 0 : r.parent ?? void 0,
247
- forkOf: r?.forkOf ?? l
248
- }), e.headers);
249
- await _.createEncoder(v, {
250
- extras: { headers: o },
251
- onMessage: i
252
- }).writeMessages([e.message], r?.clientId ? { clientId: r.clientId } : void 0), a.push(o["x-ably-msg-id"] ?? t);
640
+ }), await k("addEvents"), v === "initialized") throw new e.ErrorInfo(`unable to add events; start() must be called before addEvents() (run ${r})`, T.InvalidArgument, 400);
641
+ let n = S.getClientId(r);
642
+ try {
643
+ for (let e of t) {
644
+ let t = V({
645
+ role: "assistant",
646
+ runId: r,
647
+ codecMessageId: e.codecMessageId,
648
+ runClientId: n,
649
+ invocationId: i,
650
+ inputClientId: F,
651
+ inputCodecMessageId: z
652
+ }), a = C.createEncoder(w, {
653
+ extras: { headers: t },
654
+ onMessage: s
655
+ });
656
+ for (let t of e.events) await a.publishOutput(t);
657
+ await a.close();
658
+ }
659
+ } catch (t) {
660
+ let n = new e.ErrorInfo(`unable to publish events for run ${r}; ${t instanceof Error ? t.message : String(t)}`, T.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
661
+ throw x?.error("Run.addEvents(); publish failed", { runId: r }), n;
253
662
  }
254
- return m?.debug("Turn.addMessages(); messages published", {
255
- turnId: n,
663
+ x?.debug("Run.addEvents(); events published", {
664
+ runId: r,
256
665
  count: t.length
257
- }), { msgIds: a };
666
+ });
667
+ },
668
+ loadProjection: async () => {
669
+ x?.trace("Run.loadProjection();", { runId: r }), await k("loadProjection");
670
+ let e = await ae({
671
+ channel: w,
672
+ codec: C,
673
+ runId: r,
674
+ signal: y,
675
+ logger: x,
676
+ liveMessages: W
677
+ });
678
+ return K = e, e;
679
+ },
680
+ loadConversation: async (e) => {
681
+ x?.trace("Run.loadConversation();", { runId: r }), await k("loadConversation");
682
+ let { messages: t, projection: n } = await oe({
683
+ channel: w,
684
+ codec: C,
685
+ runId: r,
686
+ signal: y,
687
+ logger: x,
688
+ liveMessages: W,
689
+ assistantParentFallback: U,
690
+ pageLimit: e?.pageLimit ?? 200,
691
+ maxMessages: e?.maxMessages ?? 2e3
692
+ });
693
+ return K = n, q = t, t;
258
694
  },
259
- streamResponse: async (t, r) => {
260
- if (m?.trace("Turn.streamResponse();", { turnId: n }), !d) throw new e.ErrorInfo(`unable to stream response; start() must be called before streamResponse() (turn ${n})`, x.InvalidArgument, 400);
261
- await g;
262
- let o = h.getSignal(n), s = h.getClientId(n), u = r?.parent === void 0 ? c ?? void 0 : r.parent ?? void 0, f = j({
695
+ pipe: async (t, n) => {
696
+ if (x?.trace("Run.pipe();", { runId: r }), await k("pipe"), v === "initialized") throw new e.ErrorInfo(`unable to pipe stream; start() must be called before pipe() (run ${r})`, T.InvalidArgument, 400);
697
+ let a = S.getClientId(r), o = n?.parent ?? U, l = n?.forkOf ?? L, u = R, d = crypto.randomUUID(), p = V({
263
698
  role: "assistant",
264
- turnId: n,
265
- msgId: crypto.randomUUID(),
266
- turnClientId: s,
267
- parent: u,
268
- forkOf: r?.forkOf ?? l
269
- }), p = await M(t, _.createEncoder(v, {
270
- extras: { headers: f },
271
- onMessage: i
272
- }), o, a, m);
273
- return m?.debug("Turn.streamResponse(); stream finished", {
274
- turnId: n,
275
- reason: p.reason
276
- }), p;
699
+ runId: r,
700
+ codecMessageId: d,
701
+ runClientId: a,
702
+ parent: o,
703
+ forkOf: l,
704
+ invocationId: i,
705
+ inputClientId: F,
706
+ inputCodecMessageId: z,
707
+ regenerates: u
708
+ }), m = await ce(t, C.createEncoder(w, {
709
+ extras: { headers: p },
710
+ onMessage: s,
711
+ messageId: d
712
+ }), y, c, n?.resolveWriteOptions, x);
713
+ if (m.error) {
714
+ let t = new e.ErrorInfo(`unable to pipe response for run ${r}; ${m.error.message}`, T.StreamError, 500, m.error instanceof e.ErrorInfo ? m.error : void 0);
715
+ x?.error("Run.pipe(); stream error", { runId: r }), f?.(t);
716
+ }
717
+ return x?.debug("Run.pipe(); stream finished", {
718
+ runId: r,
719
+ reason: m.reason
720
+ }), m;
721
+ },
722
+ suspend: async () => {
723
+ if (x?.trace("Run.suspend();", { runId: r }), await k("suspend"), v === "initialized") throw new e.ErrorInfo(`unable to suspend run; start() must be called before suspend() (run ${r})`, T.InvalidArgument, 400);
724
+ if (v !== "ended") {
725
+ v = "ended";
726
+ try {
727
+ await S.suspendRun(r, i, F, z);
728
+ } catch (t) {
729
+ let n = new e.ErrorInfo(`unable to publish run-suspend for run ${r}; ${t instanceof Error ? t.message : String(t)}`, T.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
730
+ throw x?.error("Run.suspend(); failed to publish run-suspend", { runId: r }), n;
731
+ } finally {
732
+ G();
733
+ }
734
+ x?.debug("Run.suspend(); run suspended", { runId: r });
735
+ }
277
736
  },
278
737
  end: async (t) => {
279
- if (m?.trace("Turn.end();", {
280
- turnId: n,
738
+ if (x?.trace("Run.end();", {
739
+ runId: r,
281
740
  reason: t
282
- }), !d) throw new e.ErrorInfo(`unable to end turn; start() must be called before end() (turn ${n})`, x.InvalidArgument, 400);
283
- if (!f) {
284
- f = !0;
741
+ }), await k("end"), v === "initialized") throw new e.ErrorInfo(`unable to end run; start() must be called before end() (run ${r})`, T.InvalidArgument, 400);
742
+ if (v !== "ended") {
743
+ v = "ended";
285
744
  try {
286
- await h.endTurn(n, t);
745
+ await S.endRun(r, t, i, F, z);
287
746
  } catch (t) {
288
- let r = new e.ErrorInfo(`unable to publish turn-end for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, x.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
289
- throw m?.error("Turn.end(); failed to publish turn-end", { turnId: n }), s?.(r), r;
747
+ let n = new e.ErrorInfo(`unable to publish run-end for run ${r}; ${t instanceof Error ? t.message : String(t)}`, T.RunLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
748
+ throw x?.error("Run.end(); failed to publish run-end", { runId: r }), n;
290
749
  } finally {
291
- y.delete(n);
750
+ G();
292
751
  }
293
- m?.debug("Turn.end(); turn ended", {
294
- turnId: n,
752
+ x?.debug("Run.end(); run ended", {
753
+ runId: r,
295
754
  reason: t
296
755
  });
297
756
  }
298
757
  }
299
758
  };
300
759
  }
301
- }, F = (e) => new ee(e), I = (e) => ({
760
+ }, pe = (e) => new fe(e), me = (e) => ({
302
761
  logAction: (t, n, r) => {
303
762
  e.error(n, { detail: r });
304
763
  },
305
764
  shouldLog: () => !0
306
- }), L = e.Realtime.EventEmitter, R = class extends L {
765
+ }), he = e.Realtime.EventEmitter, Y = class extends he {
307
766
  constructor(e) {
308
- super(I(e));
767
+ super(me(e));
309
768
  }
310
- }, z = /* @__PURE__ */ function(e) {
769
+ }, ge = /* @__PURE__ */ function(e) {
311
770
  return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
312
- }({}), B = (e, t, n) => {
771
+ }({}), _e = (e, t, n) => {
313
772
  let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
314
773
  switch (t) {
315
- case z.Trace:
316
- case z.Debug:
774
+ case "trace":
775
+ case "debug":
317
776
  console.log(i);
318
777
  break;
319
- case z.Info:
778
+ case "info":
320
779
  console.info(i);
321
780
  break;
322
- case z.Warn:
781
+ case "warn":
323
782
  console.warn(i);
324
783
  break;
325
- case z.Error:
784
+ case "error":
326
785
  console.error(i);
327
786
  break;
328
- case z.Silent: break;
329
- }
330
- }, V = (e) => new W(e.logHandler ?? B, e.logLevel), H = /* @__PURE__ */ function(e) {
331
- 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;
332
- }(H || {}), U = new Map([
333
- [z.Trace, H.Trace],
334
- [z.Debug, H.Debug],
335
- [z.Info, H.Info],
336
- [z.Warn, H.Warn],
337
- [z.Error, H.Error],
338
- [z.Silent, H.Silent]
339
- ]), W = class t {
787
+ case "silent": break;
788
+ }
789
+ }, ve = (e) => new be(e.logHandler ?? _e, e.logLevel), ye = new Map([
790
+ ["trace", 0],
791
+ ["debug", 1],
792
+ ["info", 2],
793
+ ["warn", 3],
794
+ ["error", 4],
795
+ ["silent", 5]
796
+ ]), be = class t {
340
797
  constructor(t, n, r) {
341
798
  this._handler = t, this._context = r;
342
- let i = U.get(n);
343
- if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, x.InvalidArgument, 400);
799
+ let i = ye.get(n);
800
+ if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, T.InvalidArgument, 400);
344
801
  this._levelNumber = i;
345
802
  }
346
803
  trace(e, t) {
347
- this._write(e, z.Trace, H.Trace, t);
804
+ this._write(e, "trace", 0, t);
348
805
  }
349
806
  debug(e, t) {
350
- this._write(e, z.Debug, H.Debug, t);
807
+ this._write(e, "debug", 1, t);
351
808
  }
352
809
  info(e, t) {
353
- this._write(e, z.Info, H.Info, t);
810
+ this._write(e, "info", 2, t);
354
811
  }
355
812
  warn(e, t) {
356
- this._write(e, z.Warn, H.Warn, t);
813
+ this._write(e, "warn", 3, t);
357
814
  }
358
815
  error(e, t) {
359
- this._write(e, z.Error, H.Error, t);
816
+ this._write(e, "error", 4, t);
360
817
  }
361
818
  withContext(e) {
362
- let n = [...U.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? z.Error;
819
+ let n = [...ye.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? "error";
363
820
  return new t(this._handler, n, this._mergeContext(e));
364
821
  }
365
822
  _write(e, t, n, r) {
@@ -371,779 +828,979 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
371
828
  ...e
372
829
  } : this._context : e ?? void 0;
373
830
  }
374
- }, G = class {
831
+ }, X = (e) => e.kind === "run" ? e.runId : e.codecMessageId, Z = (e) => e.kind === "run" ? e.startSerial : e.serial, xe = (e, t, n) => {
832
+ let r = e.get(t);
833
+ r || (r = /* @__PURE__ */ new Set(), e.set(t, r)), r.add(n);
834
+ }, Se = (e, t, n) => {
835
+ let r = e.get(t);
836
+ r && (r.delete(n), r.size === 0 && e.delete(t));
837
+ }, Ce = class {
375
838
  constructor(e, t) {
376
- this._nodeIndex = /* @__PURE__ */ new Map(), this._codecKeyIndex = /* @__PURE__ */ new Map(), this._sortedList = [], this._parentIndex = /* @__PURE__ */ new Map(), this._selections = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._getKey = e, this._logger = t;
839
+ this._nodeIndex = /* @__PURE__ */ new Map(), this._codecMessageIdToNodeKey = /* @__PURE__ */ new Map(), this._sortedNodes = [], this._parentIndex = /* @__PURE__ */ new Map(), this._replyRunsByInput = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._structuralVersion = 0, this._siblingCache = /* @__PURE__ */ new Map(), this._siblingCacheVersion = -1, this._codec = e, this._logger = t, this._emitter = new Y(t);
377
840
  }
378
841
  _compareNodes(e, t) {
379
- let n = e.node.serial, r = t.node.serial;
842
+ let n = Z(e.node), r = Z(t.node);
380
843
  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;
381
844
  }
382
- _insertSorted(e) {
383
- if (e.node.serial === void 0) {
384
- this._sortedList.push(e);
845
+ _insertSortedNode(e) {
846
+ if (Z(e.node) === void 0) {
847
+ this._sortedNodes.push(e);
385
848
  return;
386
849
  }
387
- let t = 0, n = this._sortedList.length;
850
+ let t = 0, n = this._sortedNodes.length;
388
851
  for (; t < n;) {
389
- let r = t + n >>> 1, i = this._sortedList[r];
852
+ let r = t + n >>> 1, i = this._sortedNodes[r];
390
853
  if (!i) break;
391
854
  this._compareNodes(i, e) <= 0 ? t = r + 1 : n = r;
392
855
  }
393
- this._sortedList.splice(t, 0, e);
856
+ this._sortedNodes.splice(t, 0, e);
857
+ }
858
+ _removeSortedNode(e) {
859
+ let t = this._sortedNodes.indexOf(e);
860
+ t !== -1 && this._sortedNodes.splice(t, 1);
394
861
  }
395
- _removeSorted(e) {
396
- let t = this._sortedList.indexOf(e);
397
- t !== -1 && this._sortedList.splice(t, 1);
862
+ _insertNode(e, t, n) {
863
+ this._nodeIndex.set(e, t), this._addToParentIndex(n, e), this._insertSortedNode(t), this._structuralVersion++;
864
+ }
865
+ _promoteSerial(e) {
866
+ this._removeSortedNode(e), this._insertSortedNode(e), this._structuralVersion++;
867
+ }
868
+ _foldInto(e, t, n, r) {
869
+ for (let i of t) try {
870
+ e.node.projection = this._codec.fold(e.node.projection, i, {
871
+ serial: n ?? "",
872
+ messageId: r
873
+ });
874
+ } catch (t) {
875
+ this._logger.error("Tree._foldInto(); fold threw", {
876
+ key: X(e.node),
877
+ messageId: r,
878
+ err: t
879
+ });
880
+ }
398
881
  }
399
882
  _addToParentIndex(e, t) {
400
- let n = this._parentIndex.get(e);
401
- n || (n = /* @__PURE__ */ new Set(), this._parentIndex.set(e, n)), n.add(t);
883
+ xe(this._parentIndex, e, t);
402
884
  }
403
885
  _removeFromParentIndex(e, t) {
404
- let n = this._parentIndex.get(e);
405
- n && (n.delete(t), n.size === 0 && this._parentIndex.delete(e));
886
+ Se(this._parentIndex, e, t);
887
+ }
888
+ _parentKeyOf(e) {
889
+ let t = e.parentCodecMessageId;
890
+ return t === void 0 ? void 0 : this._codecMessageIdToNodeKey.get(t);
891
+ }
892
+ _inputGroupRoot(e) {
893
+ let t = e, n = new Set([X(t)]);
894
+ for (; t.forkOf !== void 0 && !n.has(t.forkOf);) {
895
+ let e = this._nodeIndex.get(t.forkOf);
896
+ if (e?.node.kind !== "input" || e.node.parentCodecMessageId !== t.parentCodecMessageId) break;
897
+ t = e.node, n.add(X(t));
898
+ }
899
+ return t;
406
900
  }
407
901
  _getSiblingGroup(e) {
408
- let t = this._nodeIndex.get(e);
409
- if (!t) return [];
410
- let n = t.node, r = new Set([n.msgId]);
411
- for (; n.forkOf && !r.has(n.forkOf);) {
412
- let e = this._nodeIndex.get(n.forkOf);
413
- if (!e || e.node.parentId !== n.parentId) break;
414
- n = e.node, r.add(n.msgId);
415
- }
416
- let i = n.parentId, a = n.msgId, o = [], s = this._parentIndex.get(i);
417
- if (s) for (let e of s) {
902
+ this._siblingCacheVersion !== this._structuralVersion && (this._siblingCache.clear(), this._siblingCacheVersion = this._structuralVersion);
903
+ let t = this._siblingCache.get(e);
904
+ if (t) return t;
905
+ let n = this._nodeIndex.get(e);
906
+ if (!n) return [];
907
+ let r = n.node;
908
+ r.kind === "input" && (r = this._inputGroupRoot(r));
909
+ let i = r.parentCodecMessageId, a = [], o = this._parentIndex.get(i);
910
+ if (o) for (let e of o) {
418
911
  let t = this._nodeIndex.get(e);
419
- t && this._isSiblingOf(t.node, a) && o.push(t);
912
+ t && this._isSiblingOf(t.node, r) && a.push(t);
420
913
  }
421
- return o.sort((e, t) => this._compareNodes(e, t)), o.map((e) => e.node);
914
+ a.sort((e, t) => this._compareNodes(e, t));
915
+ for (let e of a) this._siblingCache.set(X(e.node), a);
916
+ return this._siblingCache.set(e, a), a;
422
917
  }
423
918
  _isSiblingOf(e, t) {
424
- if (e.msgId === t) return !0;
425
- let n = e, r = new Set([n.msgId]);
426
- for (; n.forkOf;) {
427
- if (n.forkOf === t) return !0;
428
- if (r.has(n.forkOf)) break;
429
- let e = this._nodeIndex.get(n.forkOf);
919
+ if (e.kind !== t.kind || e.parentCodecMessageId !== t.parentCodecMessageId) return !1;
920
+ if (e.kind === "run") return !0;
921
+ let n = X(t);
922
+ if (X(e) === n) return !0;
923
+ let r = e, i = new Set([X(r)]);
924
+ for (; r.kind === "input" && r.forkOf !== void 0;) {
925
+ if (r.forkOf === n) return !0;
926
+ if (i.has(r.forkOf)) break;
927
+ let e = this._nodeIndex.get(r.forkOf);
430
928
  if (!e) break;
431
- n = e.node, r.add(n.msgId);
929
+ r = e.node, i.add(X(r));
432
930
  }
433
931
  return !1;
434
932
  }
435
- _getGroupRoot(e) {
933
+ getGroupRoot(e) {
436
934
  let t = this._nodeIndex.get(e);
437
935
  if (!t) return e;
438
- let n = t.node, r = new Set([n.msgId]);
439
- for (; n.forkOf && !r.has(n.forkOf);) {
440
- let e = this._nodeIndex.get(n.forkOf);
441
- if (!e || e.node.parentId !== n.parentId) break;
442
- n = e.node, r.add(n.msgId);
443
- }
444
- return n.msgId;
445
- }
446
- flatten() {
447
- let e = [], t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Map();
448
- for (let r of this._sortedList) {
449
- let i = r.node, { msgId: a, parentId: o } = i;
450
- if (o !== void 0 && !t.has(o)) continue;
451
- let s = this._getSiblingGroup(a);
452
- if (s.length > 1) {
453
- let e = this._getGroupRoot(a), t = n.get(e);
454
- if (t === void 0) {
455
- let r = this._selections.get(e) ?? s.length - 1, i = s[Math.max(0, Math.min(r, s.length - 1))];
456
- if (!i) break;
457
- t = i.msgId, n.set(e, t);
936
+ if (t.node.kind === "input") return X(this._inputGroupRoot(t.node));
937
+ let n = this._getSiblingGroup(e)[0]?.node;
938
+ return n ? X(n) : e;
939
+ }
940
+ visibleNodes(e = /* @__PURE__ */ new Map()) {
941
+ this._logger.trace("DefaultTree.visibleNodes();");
942
+ let t = [], n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map();
943
+ for (let i of this._sortedNodes) {
944
+ let a = i.node, o = X(a), s = this._parentKeyOf(a);
945
+ if (s !== void 0 && !n.has(s)) continue;
946
+ let c = this._getSiblingGroup(o);
947
+ if (c.length > 1) {
948
+ let t = this.getGroupRoot(o), n = r.get(t);
949
+ if (n === void 0) {
950
+ let i = e.get(t);
951
+ if (i !== void 0 && c.some((e) => X(e.node) === i)) n = i;
952
+ else {
953
+ let e = c.at(-1);
954
+ if (!e) break;
955
+ n = X(e.node);
956
+ }
957
+ r.set(t, n);
458
958
  }
459
- if (a !== t) continue;
959
+ if (o !== n) continue;
460
960
  }
461
- t.add(a), e.push(i.message);
961
+ n.add(o), t.push(a);
462
962
  }
463
- return e;
963
+ return t;
464
964
  }
465
- getSiblings(e) {
466
- return this._getSiblingGroup(e).map((e) => e.message);
965
+ getRunNode(e) {
966
+ this._logger.trace("DefaultTree.getRunNode();", { runId: e });
967
+ let t = this._nodeIndex.get(e)?.node;
968
+ return t?.kind === "run" ? t : void 0;
467
969
  }
468
- hasSiblings(e) {
469
- return this._getSiblingGroup(e).length > 1;
970
+ getNode(e) {
971
+ return this._logger.trace("DefaultTree.getNode();", { key: e }), this._nodeIndex.get(e)?.node;
470
972
  }
471
- getSelectedIndex(e) {
472
- let t = this._getSiblingGroup(e);
473
- if (t.length <= 1) return 0;
474
- let n = this._getGroupRoot(e), r = this._selections.get(n);
475
- return r === void 0 ? t.length - 1 : Math.max(0, Math.min(r, t.length - 1));
973
+ getNodeByCodecMessageId(e) {
974
+ this._logger.trace("DefaultTree.getNodeByCodecMessageId();", { codecMessageId: e });
975
+ let t = this._codecMessageIdToNodeKey.get(e);
976
+ return t === void 0 ? void 0 : this._nodeIndex.get(t)?.node;
476
977
  }
477
- select(e, t) {
478
- this._logger.debug("ConversationTree.select();", {
479
- msgId: e,
480
- index: t
481
- });
482
- let n = this._getSiblingGroup(e);
483
- if (n.length <= 1) return;
484
- let r = this._getGroupRoot(e);
485
- this._selections.set(r, Math.max(0, Math.min(t, n.length - 1)));
978
+ getReplyRuns(e) {
979
+ let t = this._replyRunsByInput.get(e);
980
+ if (!t) return [];
981
+ let n = [];
982
+ for (let e of t) {
983
+ let t = this._nodeIndex.get(e)?.node;
984
+ t?.kind === "run" && n.push(t);
985
+ }
986
+ return n;
486
987
  }
487
- getNode(e) {
488
- return this._nodeIndex.get(e)?.node;
489
- }
490
- getNodeByKey(e) {
491
- let t = this._codecKeyIndex.get(e);
492
- if (t) return this._nodeIndex.get(t)?.node;
493
- }
494
- getHeaders(e) {
495
- return this._nodeIndex.get(e)?.node.headers;
496
- }
497
- upsert(e, t, n, r) {
498
- let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0;
499
- this._codecKeyIndex.set(this._getKey(t), e);
500
- let o = this._nodeIndex.get(e);
501
- if (o) {
502
- o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("ConversationTree.upsert(); promoting serial", {
503
- msgId: e,
504
- serial: r
505
- }), o.node.serial = r, this._removeSorted(o), this._insertSorted(o));
988
+ getSiblingNodes(e) {
989
+ return this._logger.trace("DefaultTree.getSiblingNodes();", { key: e }), this._getSiblingGroup(e).map((e) => e.node);
990
+ }
991
+ applyMessage(e, t, n) {
992
+ let r = t[o], i = t[l], a = r === void 0 && i !== void 0 && t.role === "user" && e.inputs.length > 0 ? i : void 0;
993
+ if (r === void 0 && a === void 0) {
994
+ this._logger.warn("Tree.applyMessage(); message has no run-id and is not a user input; skipping");
506
995
  return;
507
996
  }
508
- this._logger.trace("ConversationTree.upsert(); inserting new node", {
509
- msgId: e,
510
- parentId: i,
511
- forkOf: a
997
+ let s = [...e.inputs, ...e.outputs], c = a ?? r;
998
+ if (s.length === 0 && c !== void 0 && !this._nodeIndex.has(c)) return;
999
+ let u = this._structuralVersion;
1000
+ a === void 0 ? r !== void 0 && this._applyRunMessage(r, e, t, n) : this._applyInputMessage(a, t, n, s), this._structuralVersion !== u && this._emitter.emit("update");
1001
+ }
1002
+ _applyInputMessage(e, t, n, r) {
1003
+ let i = this._nodeIndex.get(e);
1004
+ i ? i.node.kind === "input" && n && !i.node.serial && (this._logger.debug("Tree.applyMessage(); promoting input serial", {
1005
+ codecMessageId: e,
1006
+ serial: n
1007
+ }), i.node.serial = n, this._promoteSerial(i)) : (i = this._createInputNodeFromHeaders(e, t, n), this._insertNode(e, i, i.node.parentCodecMessageId), this._codecMessageIdToNodeKey.set(e, e), this._logger.debug("Tree.applyMessage(); created input node", { codecMessageId: e })), this._foldInto(i, r, n, e), this._emitter.emit("output", {
1008
+ runId: void 0,
1009
+ inputCodecMessageId: e,
1010
+ codecMessageId: e,
1011
+ serial: n,
1012
+ events: []
512
1013
  });
513
- let s = {
1014
+ }
1015
+ _applyRunMessage(e, t, n, r) {
1016
+ let i = n[l], a = n[_], o = [...t.inputs, ...t.outputs], s = t.outputs, c = this._nodeIndex.get(e);
1017
+ if (!c && i !== void 0) {
1018
+ let e = this._codecMessageIdToNodeKey.get(i), t = e === void 0 ? void 0 : this._nodeIndex.get(e);
1019
+ t?.node.kind === "run" && t.node.startSerial === void 0 && (c = t);
1020
+ }
1021
+ c ? r && c.node.kind === "run" && !c.node.startSerial && (this._logger.debug("Tree.applyMessage(); promoting startSerial", {
1022
+ runId: e,
1023
+ serial: r
1024
+ }), c.node.startSerial = r, this._promoteSerial(c)) : (c = this._createRunFromHeaders(e, n, r), this._insertNode(e, c, c.node.parentCodecMessageId), this._indexReplyRun(c.node, e), this._logger.debug("Tree.applyMessage(); created new Run", { runId: e }));
1025
+ let u = X(c.node);
1026
+ i && this._codecMessageIdToNodeKey.set(i, u), this._foldInto(c, o, r, i), this._emitter.emit("output", {
1027
+ runId: u,
1028
+ inputCodecMessageId: a,
1029
+ codecMessageId: i,
1030
+ serial: r,
1031
+ events: s
1032
+ });
1033
+ }
1034
+ _indexReplyRun(e, t) {
1035
+ e.parentCodecMessageId !== void 0 && xe(this._replyRunsByInput, e.parentCodecMessageId, t);
1036
+ }
1037
+ applyRunLifecycle(e) {
1038
+ this._logger.trace("DefaultTree.applyRunLifecycle();", {
1039
+ type: e.type,
1040
+ runId: e.runId
1041
+ });
1042
+ let t = this._structuralVersion;
1043
+ switch (e.type) {
1044
+ case "start":
1045
+ this._applyRunStart(e);
1046
+ break;
1047
+ case "suspend":
1048
+ this._applyRunSuspend(e);
1049
+ break;
1050
+ case "resume":
1051
+ this._applyRunResume(e);
1052
+ break;
1053
+ case "end":
1054
+ this._applyRunEnd(e);
1055
+ break;
1056
+ }
1057
+ this._emitter.emit("run", e), this._structuralVersion !== t && this._emitter.emit("update");
1058
+ }
1059
+ _applyRunStart(e) {
1060
+ let t = this._nodeIndex.get(e.runId);
1061
+ if (t?.node.kind === "run") {
1062
+ let n = t.node;
1063
+ if (n.status !== "active" && (n.status = "active"), e.serial && !n.startSerial && (n.startSerial = e.serial, this._promoteSerial(t)), n.parentCodecMessageId === void 0 && e.parent !== void 0 && (n.parentCodecMessageId = e.parent, this._removeFromParentIndex(void 0, e.runId), this._addToParentIndex(n.parentCodecMessageId, e.runId), this._indexReplyRun(n, e.runId), this._structuralVersion++), n.forkOf === void 0 && e.forkOf !== void 0) {
1064
+ let t = this._codecMessageIdToNodeKey.get(e.forkOf);
1065
+ t !== void 0 && t !== e.runId && (n.forkOf = t, this._structuralVersion++);
1066
+ }
1067
+ n.regeneratesCodecMessageId === void 0 && e.regenerates !== void 0 && (n.regeneratesCodecMessageId = e.regenerates, this._structuralVersion++), n.invocationId === "" && e.invocationId !== "" && (n.invocationId = e.invocationId);
1068
+ } else if (!t) {
1069
+ let t = this._createRunFromLifecycle(e);
1070
+ this._insertNode(e.runId, t, t.node.parentCodecMessageId), this._indexReplyRun(t.node, e.runId);
1071
+ }
1072
+ }
1073
+ _applyRunSuspend(e) {
1074
+ let t = this._nodeIndex.get(e.runId);
1075
+ t?.node.kind === "run" && (t.node.status = "suspended", t.node.endSerial = e.serial);
1076
+ }
1077
+ _applyRunResume(e) {
1078
+ let t = this._nodeIndex.get(e.runId);
1079
+ t?.node.kind === "run" && t.node.status === "suspended" && (t.node.status = "active");
1080
+ }
1081
+ _applyRunEnd(e) {
1082
+ let t = this._nodeIndex.get(e.runId);
1083
+ t?.node.kind === "run" && (t.node.status = e.reason, t.node.endSerial = e.serial);
1084
+ }
1085
+ delete(e) {
1086
+ let t = this._nodeIndex.get(e);
1087
+ 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 && Se(this._replyRunsByInput, t.node.parentCodecMessageId, e), this._structuralVersion++, this._emitter.emit("update"));
1088
+ }
1089
+ _createRunFromHeaders(e, t, n) {
1090
+ let r = t[m];
1091
+ return this._buildRunNode({
1092
+ runId: e,
1093
+ parentCodecMessageId: t[p],
1094
+ forkOf: r ? this._codecMessageIdToNodeKey.get(r) : void 0,
1095
+ regeneratesCodecMessageId: t[h],
1096
+ clientId: t["run-client-id"] ?? "",
1097
+ invocationId: t["invocation-id"] ?? "",
1098
+ startSerial: n
1099
+ });
1100
+ }
1101
+ _buildRunNode(e) {
1102
+ return {
514
1103
  node: {
515
- message: t,
516
- msgId: e,
517
- parentId: i,
518
- forkOf: a,
519
- headers: { ...n },
520
- serial: r
1104
+ kind: "run",
1105
+ runId: e.runId,
1106
+ parentCodecMessageId: e.parentCodecMessageId,
1107
+ forkOf: e.forkOf,
1108
+ regeneratesCodecMessageId: e.regeneratesCodecMessageId,
1109
+ clientId: e.clientId,
1110
+ invocationId: e.invocationId,
1111
+ status: "active",
1112
+ projection: this._codec.init(),
1113
+ startSerial: e.startSerial,
1114
+ endSerial: void 0
521
1115
  },
522
1116
  insertSeq: this._seqCounter++
523
1117
  };
524
- this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s);
525
1118
  }
526
- delete(e) {
527
- let t = this._nodeIndex.get(e);
528
- if (!t) return;
529
- this._logger.debug("ConversationTree.delete();", { msgId: e });
530
- let { node: n } = t, r = this._getKey(n.message);
531
- this._codecKeyIndex.get(r) === e && this._codecKeyIndex.delete(r), this._removeFromParentIndex(n.parentId, e), this._removeSorted(t), this._nodeIndex.delete(e), this._selections.delete(e);
532
- }
533
- }, K = (e, t) => new G(e, t), q = (e) => {
534
- let t = [...e.rawMessages].toReversed(), n = e.codec.createDecoder(), r = /* @__PURE__ */ new Map(), o = e.codec.createAccumulator(), s = 0, c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map();
535
- for (let u of t) {
536
- let t = n.decode(u), d = C(u), f = d[i], p = d[a], m = u.serial;
537
- if (f) {
538
- let n = r.get(f);
539
- if (n || (n = {
540
- accumulator: e.codec.createAccumulator(),
541
- firstSeen: s++,
542
- msgHeaders: /* @__PURE__ */ new Map(),
543
- msgSerials: /* @__PURE__ */ new Map()
544
- }, r.set(f, n)), p) {
545
- let e = n.msgHeaders.get(p);
546
- e ? Object.keys(d).length > 0 && Object.assign(e, d) : (n.msgHeaders.set(p, { ...d }), m && n.msgSerials.set(p, m));
547
- }
548
- n.accumulator.processOutputs(t);
549
- } else o.processOutputs(t);
550
- for (let n of t) if (n.kind === "message") {
551
- let t = e.getMessageKey(n.message), r = c.get(t);
552
- r ? Object.keys(d).length > 0 && Object.assign(r, d) : (c.set(t, { ...d }), m && l.set(t, m));
553
- }
1119
+ _createInputNodeFromHeaders(e, t, n) {
1120
+ let r = t[m];
1121
+ return {
1122
+ node: {
1123
+ kind: "input",
1124
+ codecMessageId: e,
1125
+ parentCodecMessageId: t[p],
1126
+ forkOf: r,
1127
+ projection: this._codec.init(),
1128
+ serial: n
1129
+ },
1130
+ insertSeq: this._seqCounter++
1131
+ };
554
1132
  }
555
- let u = [];
556
- for (let t of o.completedMessages) {
557
- let n = e.getMessageKey(t);
558
- u.push({
559
- message: t,
560
- headers: c.get(n) ?? {},
561
- serial: l.get(n) ?? ""
1133
+ _createRunFromLifecycle(e) {
1134
+ let t = e.forkOf;
1135
+ return this._buildRunNode({
1136
+ runId: e.runId,
1137
+ parentCodecMessageId: e.parent,
1138
+ forkOf: t ? this._codecMessageIdToNodeKey.get(t) : void 0,
1139
+ regeneratesCodecMessageId: e.regenerates,
1140
+ clientId: e.clientId,
1141
+ invocationId: e.invocationId,
1142
+ startSerial: e.serial
562
1143
  });
563
1144
  }
564
- let d = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
565
- for (let t of d) {
566
- let n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map();
567
- for (let o of t.accumulator.completedMessages) {
568
- let t = e.getMessageKey(o), s = c.get(t);
569
- if (s) {
570
- r.set(t, s);
571
- let e = l.get(t);
572
- e && i.set(t, e);
573
- let o = s[a];
574
- o && n.add(o);
575
- }
576
- }
577
- let o = [...t.msgHeaders.entries()].filter(([e]) => !n.has(e)), s = 0;
578
- for (let n of t.accumulator.completedMessages) {
579
- let a = e.getMessageKey(n), c = o[s];
580
- if (!r.has(a) && c) {
581
- let [e, n] = c;
582
- r.set(a, n);
583
- let o = t.msgSerials.get(e);
584
- o && i.set(a, o), s++;
585
- }
586
- }
587
- for (let n of t.accumulator.completedMessages) {
588
- let t = e.getMessageKey(n);
589
- u.push({
590
- message: n,
591
- headers: r.get(t) ?? {},
592
- serial: i.get(t) ?? ""
593
- });
594
- }
1145
+ on(e, t) {
1146
+ let n = t;
1147
+ return this._emitter.on(e, n), () => {
1148
+ this._emitter.off(e, n);
1149
+ };
595
1150
  }
596
- return u.toReversed();
597
- }, J = async (e, t, n) => {
598
- e.rawMessages.push(...t.items), e.lastAblyPage = t;
599
- let r = q(e).length;
600
- for (; r < e.returnedCount + n && t.hasNext();) {
601
- e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
1151
+ emitAblyMessage(e) {
1152
+ this._logger.trace("DefaultTree.emitAblyMessage();"), this._emitter.emit("ably-message", e);
1153
+ }
1154
+ }, we = (e, t) => new Ce(e, t), Te = (e, t) => {
1155
+ for (let n of t) {
1156
+ let t = O(n), i = t[l];
1157
+ if (!i) continue;
1158
+ 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";
1159
+ (o || s) && e.startedCodecMessageIds.add(i), (o || u) && e.terminatedCodecMessageIds.add(i), e.startedCodecMessageIds.has(i) && e.terminatedCodecMessageIds.has(i) && e.completedCodecMessageIds.add(i);
1160
+ }
1161
+ }, Ee = async (e, t, n) => {
1162
+ e.rawMessages.push(...t.items), e.lastAblyPage = t, Te(e, t.items);
1163
+ let r = e.returnedCount + n;
1164
+ for (; e.completedCodecMessageIds.size < r && t.hasNext();) {
1165
+ e.logger.debug("loadHistory.fetchUntilLimit(); fetching next page", {
602
1166
  collected: e.rawMessages.length,
603
- decoded: r
1167
+ completed: e.completedCodecMessageIds.size
604
1168
  });
605
1169
  let n = await t.next();
606
1170
  if (!n) break;
607
- t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, r = q(e).length;
1171
+ t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, Te(e, n.items);
608
1172
  }
609
- }, Y = (e, t) => {
610
- let n = q(e), r = n.slice(e.returnedCount, e.returnedCount + t), i = [...r].toReversed();
611
- e.returnedCount += r.length;
612
- let a = n.length > e.returnedCount, o = e.lastAblyPage?.hasNext() ?? !1, s = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
1173
+ }, Q = (e, t) => {
1174
+ let n = e.completedCodecMessageIds.size, r = Math.min(t, Math.max(0, n - e.returnedCount));
1175
+ e.returnedCount += r;
1176
+ let i = n > e.returnedCount, a = e.lastAblyPage?.hasNext() ?? !1, o = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
613
1177
  return e.returnedRawCount = e.rawMessages.length, {
614
- items: i.map((e) => e.message),
615
- itemHeaders: i.map((e) => e.headers),
616
- itemSerials: i.map((e) => e.serial),
617
- rawMessages: s,
618
- hasNext: () => a || o,
1178
+ rawMessages: o,
1179
+ hasNext: () => i || a,
619
1180
  next: async () => {
620
- if (a) return Y(e, t);
621
- if (!o || !e.lastAblyPage) return;
1181
+ if (i) return Q(e, t);
1182
+ if (!a || !e.lastAblyPage) return;
622
1183
  let n = await e.lastAblyPage.next();
623
- if (n) return await J(e, n, t), Y(e, t);
1184
+ if (n) return await Ee(e, n, t), Q(e, t);
624
1185
  }
625
1186
  };
626
- }, X = async (e, t, n, r) => {
627
- let i = n?.limit ?? 100, a = {
628
- codec: t,
1187
+ }, De = async (e, t, n) => {
1188
+ let r = t?.limit ?? 100, i = {
629
1189
  rawMessages: [],
630
1190
  returnedCount: 0,
631
1191
  returnedRawCount: 0,
632
1192
  lastAblyPage: void 0,
633
- getMessageKey: t.getMessageKey.bind(t),
634
- logger: r
1193
+ startedCodecMessageIds: /* @__PURE__ */ new Set(),
1194
+ terminatedCodecMessageIds: /* @__PURE__ */ new Set(),
1195
+ completedCodecMessageIds: /* @__PURE__ */ new Set(),
1196
+ logger: n
635
1197
  };
636
- r.trace("decodeHistory();", { limit: i });
637
- let o = i * 10;
638
- return await e.attach(), await J(a, await e.history({
1198
+ n.trace("loadHistory();", { limit: r });
1199
+ let a = r * 10;
1200
+ return await e.attach(), await Ee(i, await e.history({
639
1201
  untilAttach: !0,
640
- limit: o
641
- }), i), Y(a, i);
642
- }, Z = class {
643
- constructor(e, t) {
644
- this._turns = /* @__PURE__ */ new Map(), this._isTerminal = e, this._logger = t;
645
- }
646
- createStream(t) {
647
- this._logger.trace("StreamRouter.createStream();", { turnId: t });
648
- let n = {}, r = new ReadableStream({ start(e) {
649
- n.controller = e;
650
- } });
651
- if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", x.TransportSubscriptionError, 500);
652
- return this._turns.set(t, {
653
- controller: n.controller,
654
- turnId: t
655
- }), r;
656
- }
657
- closeStream(e) {
658
- let t = this._turns.get(e);
659
- if (!t) return !1;
660
- this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
661
- try {
662
- t.controller.close();
663
- } catch {}
664
- return this._turns.delete(e), !0;
1202
+ limit: a
1203
+ }), r), Q(i, r);
1204
+ }, Oe = (e) => Array.isArray(e) ? e : [e], ke = 3, $ = (e) => ({
1205
+ runId: e.runId,
1206
+ clientId: e.clientId,
1207
+ status: e.status,
1208
+ invocationId: e.invocationId
1209
+ }), Ae = class {
1210
+ constructor(e) {
1211
+ this._branchSelections = /* @__PURE__ */ new Map(), this._regenSelections = /* @__PURE__ */ new Map(), this._withheldRunIds = /* @__PURE__ */ new Set(), this._lastVisibleNodeKeys = [], this._lastVisibleProjections = [], this._lastVisibleMessagePairs = [], this._lastVisibleNodeKeySet = /* @__PURE__ */ new Set(), this._hasMoreHistory = !1, this._withheldBuffer = [], this._unsubs = [], this._cachedNodes = [], this._loadingOlder = !1, this._processingHistory = !1, this._closed = !1, this._tree = e.tree, this._channel = e.channel, this._codec = e.codec, this._sendDelegate = e.sendDelegate, this._onClose = e.onClose, this._logger = e.logger.withContext({ component: "View" }), this._logger.trace("DefaultView();"), this._emitter = new Y(this._logger), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
1212
+ this._onTreeUpdate();
1213
+ }), this._tree.on("ably-message", (e) => {
1214
+ this._onTreeAblyMessage(e);
1215
+ }), this._tree.on("run", (e) => {
1216
+ this._onTreeRun(e);
1217
+ }), this._tree.on("output", (e) => {
1218
+ this._onTreeOutput(e);
1219
+ }));
665
1220
  }
666
- route(e, t) {
667
- let n = this._turns.get(e);
668
- if (!n) return !1;
669
- try {
670
- n.controller.enqueue(t);
671
- } catch {
672
- return this._turns.delete(e), !1;
673
- }
674
- return this._isTerminal(t) && this.closeStream(e), !0;
1221
+ _onTreeOutput(e) {
1222
+ this._processingHistory || (e.runId !== void 0 && this._lastVisibleNodeKeySet.has(e.runId) || e.inputCodecMessageId !== void 0 && this._lastVisibleNodeKeySet.has(e.inputCodecMessageId)) && (this._lastVisibleProjections = this._cachedNodes.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(this._cachedNodes), this._emitter.emit("update"));
675
1223
  }
676
- has(e) {
677
- return this._turns.has(e);
1224
+ getMessages() {
1225
+ return this._lastVisibleMessagePairs;
678
1226
  }
679
- }, Q = (e, t) => new Z(e, t), te = () => {}, ne = class {
680
- constructor(e) {
681
- if (this._ownMsgIds = /* @__PURE__ */ new Set(), this._ownTurnIds = /* @__PURE__ */ new Set(), this._turnClientIds = /* @__PURE__ */ new Map(), this._turnMsgIds = /* @__PURE__ */ new Map(), this._turnObservers = /* @__PURE__ */ new Map(), this._ablyMessages = [], this._withheldKeys = /* @__PURE__ */ new Set(), this._closed = !1, this._channel = e.channel, this._codec = e.codec, this._clientId = e.clientId, this._api = e.api ?? "/api/chat", 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 ?? V({ logLevel: z.Silent })).withContext({ component: "ClientTransport" }), this._emitter = new R(this._logger), this._tree = K(this._codec.getMessageKey.bind(this._codec), this._logger), this._router = Q(this._codec.isTerminal.bind(this._codec), this._logger), this._decoder = this._codec.createDecoder(), e.messages) {
682
- let t;
683
- for (let n of e.messages) {
684
- let e = this._codec.getMessageKey(n), r = {};
685
- t && (r[f] = t), this._tree.upsert(e, n, r), t = e;
686
- }
687
- this._emitter.emit("message");
688
- }
689
- this._onMessage = (e) => {
690
- this._handleMessage(e);
691
- }, this._attachPromise = this._channel.subscribe(this._onMessage);
1227
+ runs() {
1228
+ return this._cachedNodes.filter((e) => e.kind === "run").map((e) => $(e));
692
1229
  }
693
- _handleMessage(t) {
694
- if (!this._closed) {
695
- this._ablyMessages.push(t), this._emitter.emit("ably-message");
1230
+ _computeFlatNodes() {
1231
+ let e = this._treeVisibleNodes();
1232
+ return this._withheldRunIds.size === 0 ? e : e.filter((e) => !this._withheldRunIds.has(X(e)));
1233
+ }
1234
+ _recomputeAndEmit() {
1235
+ this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update");
1236
+ }
1237
+ _recomputeAndEmitIfChanged() {
1238
+ let e = this._computeFlatNodes();
1239
+ this._visibleChanged(e) && (this._cachedNodes = e, this._updateVisibleSnapshot(e), this._emitter.emit("update"));
1240
+ }
1241
+ _runByCodecMessageId(e) {
1242
+ let t = this._tree.getNodeByCodecMessageId(e);
1243
+ return t?.kind === "run" ? t : void 0;
1244
+ }
1245
+ _extractMessages(e) {
1246
+ let t = [];
1247
+ for (let n of e) for (let e of this._codec.getMessages(n.projection)) t.push(e);
1248
+ return t;
1249
+ }
1250
+ hasOlder() {
1251
+ return this._withheldBuffer.length > 0 || this._hasMoreHistory;
1252
+ }
1253
+ async loadOlder(e = 100) {
1254
+ if (!(this._closed || this._loadingOlder)) {
1255
+ this._loadingOlder = !0, this._logger.trace("DefaultView.loadOlder();", { limit: e });
696
1256
  try {
697
- if (t.name === "x-ably-turn-start") {
698
- let e = C(t), n = e[i], r = e["x-ably-turn-client-id"] ?? "";
699
- n && (this._turnClientIds.set(n, r), this._emitter.emit("turn", {
700
- type: g,
701
- turnId: n,
702
- clientId: r
703
- }));
1257
+ if (this._withheldBuffer.length > 0) {
1258
+ let t = this._withheldBuffer.splice(-e, e);
1259
+ this._releaseWithheld(t);
704
1260
  return;
705
1261
  }
706
- if (t.name === "x-ably-turn-end") {
707
- let e = C(t), n = e[i], r = e["x-ably-turn-client-id"] ?? "", a = e["x-ably-turn-reason"] ?? "complete";
708
- if (n) {
709
- this._router.closeStream(n), this._turnObservers.delete(n), this._turnClientIds.delete(n);
710
- let e = this._turnMsgIds.get(n);
711
- if (e) {
712
- for (let t of e) this._ownMsgIds.delete(t);
713
- this._turnMsgIds.delete(n);
714
- }
715
- this._ownTurnIds.delete(n), this._emitter.emit("turn", {
716
- type: _,
717
- turnId: n,
718
- clientId: r,
719
- reason: a
720
- });
721
- }
1262
+ if (!this._hasMoreHistory && !this._lastHistoryPage) {
1263
+ await this._loadFirstPage(e);
722
1264
  return;
723
1265
  }
724
- let e = this._decoder.decode(t), n = C(t), r = t.serial, a = n[i];
725
- a && this._updateTurnObserverHeaders(a, n, r);
726
- for (let i of e) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, t.action) : this._handleEventOutput(i, n);
727
- } catch (t) {
728
- let n = t instanceof e.ErrorInfo ? t : void 0;
729
- this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, x.TransportSubscriptionError, 500, n));
1266
+ if (!this._hasMoreHistory) return;
1267
+ if (!this._lastHistoryPage?.hasNext()) {
1268
+ this._hasMoreHistory = !1;
1269
+ return;
1270
+ }
1271
+ let t = await this._lastHistoryPage.next();
1272
+ if (this._closed || !t) {
1273
+ t || (this._hasMoreHistory = !1);
1274
+ return;
1275
+ }
1276
+ await this._revealFromPage(t, e);
1277
+ } catch (e) {
1278
+ throw this._logger.error("DefaultView.loadOlder(); failed", { error: e }), e;
1279
+ } finally {
1280
+ this._loadingOlder = !1;
730
1281
  }
731
1282
  }
732
1283
  }
733
- _handleMessageOutput(e, t, n, r) {
734
- let i = t[a];
735
- if (i && this._ownMsgIds.has(i)) {
736
- this._upsertAndNotify(e, t, n);
737
- return;
1284
+ runOf(e) {
1285
+ this._logger.trace("DefaultView.runOf();", { codecMessageId: e });
1286
+ let t = this._tree.getNodeByCodecMessageId(e);
1287
+ if (!t) return;
1288
+ if (t.kind === "run") return $(t);
1289
+ let n = this._selectedReplyRun(t.codecMessageId);
1290
+ return n ? $(n) : void 0;
1291
+ }
1292
+ _selectedReplyRun(e) {
1293
+ let t = this._tree.getReplyRuns(e);
1294
+ if (t.length === 0) return;
1295
+ if (t.length === 1) return t[0];
1296
+ let n = this._tree.getGroupRoot(t[0]?.runId ?? ""), r = this._regenSelections.get(n), i = r && r.kind !== "pending" ? r.selectedRunId : void 0;
1297
+ if (i !== void 0) {
1298
+ let e = t.find((e) => e.runId === i);
1299
+ if (e) return e;
738
1300
  }
739
- r === "message.create" && this._upsertAndNotify(e, t, n);
740
- }
741
- _handleEventOutput(e, t) {
742
- if (e.kind !== "event") return;
743
- let n = e.event, r = t[i];
744
- if (r) {
745
- if (this._router.route(r, n)) {
746
- this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r);
747
- return;
1301
+ return t.toSorted((e, t) => (e.startSerial ?? "￿").localeCompare(t.startSerial ?? "￿")).at(-1);
1302
+ }
1303
+ run(e) {
1304
+ this._logger.trace("DefaultView.run();", { runId: e });
1305
+ let t = this._tree.getRunNode(e);
1306
+ return t ? $(t) : void 0;
1307
+ }
1308
+ branchSelection(e) {
1309
+ let t = this._resolveMessageBranchPoint(e);
1310
+ if (t) {
1311
+ let e = t.siblings.flatMap((e) => {
1312
+ let t = this._codec.getMessages(e.projection).at(0);
1313
+ return t ? [t.message] : [];
1314
+ });
1315
+ if (e.length > 0) {
1316
+ let n = this._resolveSelectedIndex(t), r = Math.max(0, Math.min(n, e.length - 1)), i = e[r];
1317
+ return {
1318
+ hasSiblings: e.length > 1,
1319
+ siblings: e,
1320
+ index: r,
1321
+ selected: i
1322
+ };
748
1323
  }
749
- this._ownTurnIds.has(r) && !this._turnObservers.has(r) || (this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r));
750
1324
  }
1325
+ let n = this._tree.getNodeByCodecMessageId(e);
1326
+ if (n) {
1327
+ let t = this._codec.getMessages(n.projection).find((t) => t.codecMessageId === e);
1328
+ if (t !== void 0) return {
1329
+ hasSiblings: !1,
1330
+ siblings: [t.message],
1331
+ index: 0,
1332
+ selected: t.message
1333
+ };
1334
+ }
1335
+ return {
1336
+ hasSiblings: !1,
1337
+ siblings: [],
1338
+ index: 0,
1339
+ selected: void 0
1340
+ };
751
1341
  }
752
- _upsertAndNotify(e, t, n) {
753
- let r = this._codec.getMessageKey(e), i = t["x-ably-msg-id"] ?? r;
754
- this._tree.upsert(i, e, t, n), this._emitter.emit("message");
755
- }
756
- _updateTurnObserverHeaders(e, t, n) {
757
- let r = this._turnObservers.get(e);
758
- r ? (Object.keys(t).length > 0 && Object.assign(r.headers, t), n !== void 0 && (r.serial = n)) : this._turnObservers.set(e, {
759
- headers: { ...t },
760
- serial: n,
761
- accumulator: this._codec.createAccumulator()
1342
+ selectSibling(e, t) {
1343
+ this._logger.trace("DefaultView.selectSibling();", {
1344
+ codecMessageId: e,
1345
+ index: t
762
1346
  });
763
- }
764
- _accumulateAndEmit(e, t) {
765
- let n = this._turnObservers.get(e);
1347
+ let n = this._resolveMessageBranchPoint(e);
766
1348
  if (!n) return;
767
- n.accumulator.processOutputs([t]);
768
- let r = n.accumulator.messages;
769
- if (r.length === 0) return;
770
- let i;
771
- try {
772
- i = structuredClone(r.at(-1));
773
- } catch {
774
- i = r.at(-1);
1349
+ let r = Math.max(0, Math.min(t, n.siblings.length - 1)), i = n.siblings[r];
1350
+ i && (n.kind === "fork-of" ? (this._branchSelections.set(n.groupRoot, {
1351
+ kind: "user",
1352
+ selectedKey: X(i)
1353
+ }), this._logger.debug("DefaultView.selectSibling(); fork-of", {
1354
+ codecMessageId: e,
1355
+ index: r,
1356
+ selectedKey: X(i)
1357
+ })) : (this._regenSelections.set(n.groupRoot, {
1358
+ kind: "user",
1359
+ selectedRunId: X(i)
1360
+ }), this._logger.debug("DefaultView.selectSibling(); regenerate", {
1361
+ codecMessageId: e,
1362
+ index: r,
1363
+ selectedRunId: X(i),
1364
+ groupRoot: n.groupRoot
1365
+ })), this._recomputeAndEmit());
1366
+ }
1367
+ _resolveSelectedIndex(e) {
1368
+ if (e.kind === "fork-of") {
1369
+ let t = this._branchSelections.get(e.groupRoot);
1370
+ if (!t) return e.siblings.length - 1;
1371
+ let n = e.siblings.findIndex((e) => X(e) === t.selectedKey);
1372
+ return n === -1 ? e.siblings.length - 1 : n;
775
1373
  }
776
- i && (this._tree.upsert(n.headers["x-ably-msg-id"] ?? this._codec.getMessageKey(i), i, { ...n.headers }, n.serial), this._emitter.emit("message"));
1374
+ let t = this._regenSelections.get(e.groupRoot);
1375
+ if (!t || t.kind === "pending") return e.siblings.length - 1;
1376
+ let n = e.siblings.findIndex((e) => X(e) === t.selectedRunId);
1377
+ return n === -1 ? e.siblings.length - 1 : n;
777
1378
  }
778
- async _publishCancel(e) {
779
- this._logger.trace("ClientTransport._publishCancel();", { filter: e });
780
- let t = {};
781
- e.turnId ? t[c] = e.turnId : e.own ? t[l] = "true" : e.clientId ? t[d] = e.clientId : e.all && (t[u] = "true"), await this._channel.publish({
782
- name: h,
783
- extras: { headers: t }
1379
+ _resolveMessageBranchPoint(e) {
1380
+ let t = this._tree.getNodeByCodecMessageId(e);
1381
+ if (!t) return;
1382
+ if (t.kind === "input") {
1383
+ let e = this._tree.getSiblingNodes(t.codecMessageId);
1384
+ return e.length > 1 ? {
1385
+ kind: "fork-of",
1386
+ groupRoot: this._tree.getGroupRoot(t.codecMessageId),
1387
+ siblings: e
1388
+ } : void 0;
1389
+ }
1390
+ let n = this._tree.getSiblingNodes(t.runId);
1391
+ if (n.length > 1 && this._codec.getMessages(t.projection).at(0)?.codecMessageId === e) return {
1392
+ kind: "regen",
1393
+ groupRoot: this._tree.getGroupRoot(t.runId),
1394
+ siblings: n
1395
+ };
1396
+ }
1397
+ async send(t, n) {
1398
+ if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", T.InvalidArgument, 400);
1399
+ let r = Oe(t), i = this._lastVisibleMessagePairs.at(-1)?.codecMessageId, a = await this._sendDelegate(r, n, i);
1400
+ return this._applyForkAutoSelect(a, n), a;
1401
+ }
1402
+ _applyForkAutoSelect(e, t) {
1403
+ if (!t?.forkOf) return;
1404
+ let n = e.optimisticCodecMessageIds.at(0);
1405
+ if (n === void 0) return;
1406
+ let r = this._tree.getGroupRoot(n);
1407
+ this._branchSelections.set(r, {
1408
+ kind: "auto",
1409
+ selectedKey: n
1410
+ }), this._recomputeAndEmit();
1411
+ }
1412
+ _applyRegenerateAutoSelect(e, t) {
1413
+ let n = this._runByCodecMessageId(t);
1414
+ if (!n) return;
1415
+ let r = this._tree.getGroupRoot(n.runId);
1416
+ this._regenSelections.set(r, {
1417
+ kind: "pending",
1418
+ carrierCodecMessageId: e.inputCodecMessageId
1419
+ }), this._logger.debug("DefaultView._applyRegenerateAutoSelect(); deferring regenerate selection", {
1420
+ anchorCodecMessageId: t,
1421
+ groupRoot: r,
1422
+ carrier: e.inputCodecMessageId
1423
+ }), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged();
1424
+ }
1425
+ async regenerate(t, n) {
1426
+ if (this._logger.trace("DefaultView.regenerate();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to regenerate; view is closed", T.InvalidArgument, 400);
1427
+ let r = this._runByCodecMessageId(t);
1428
+ if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, T.InvalidArgument, 400);
1429
+ let i = this._findParentMsgId(r, t);
1430
+ if (!i) throw new e.ErrorInfo(`unable to regenerate; parent user message not found for ${t}`, T.InvalidArgument, 400);
1431
+ let a = t;
1432
+ r.regeneratesCodecMessageId !== void 0 && this._codec.getMessages(r.projection).at(0)?.codecMessageId === t && (a = r.regeneratesCodecMessageId);
1433
+ let o = {
1434
+ ...n,
1435
+ parent: i
1436
+ }, s = this._codec.createRegenerate(a, i), c = await this._sendDelegate([s], o, i);
1437
+ return this._applyRegenerateAutoSelect(c, a), c;
1438
+ }
1439
+ async edit(t, n, r) {
1440
+ if (this._logger.trace("DefaultView.edit();", { messageId: t }), this._closed) throw new e.ErrorInfo("unable to edit; view is closed", T.InvalidArgument, 400);
1441
+ let i = this._tree.getNodeByCodecMessageId(t);
1442
+ if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, T.InvalidArgument, 400);
1443
+ let a = this._findParentMsgId(i, t);
1444
+ return this.send(n, {
1445
+ ...r,
1446
+ forkOf: t,
1447
+ parent: a
784
1448
  });
785
1449
  }
786
- _closeMatchingTurnStreams(e) {
787
- if (e.all) for (let e of this._ownTurnIds) this._router.closeStream(e);
788
- else if (e.own) for (let e of this._ownTurnIds) this._router.closeStream(e);
789
- else if (e.clientId) for (let [t, n] of this._turnClientIds) n === e.clientId && this._router.closeStream(t);
790
- else e.turnId && this._router.closeStream(e.turnId);
791
- }
792
- _getMatchingTurnIds(e) {
793
- let t = /* @__PURE__ */ new Set();
794
- if (e.all) for (let e of this._turnClientIds.keys()) t.add(e);
795
- else if (e.own) for (let [e, n] of this._turnClientIds) n === this._clientId && t.add(e);
796
- else if (e.clientId) for (let [n, r] of this._turnClientIds) r === e.clientId && t.add(n);
797
- else e.turnId && this._turnClientIds.has(e.turnId) && t.add(e.turnId);
798
- return t;
1450
+ _findParentMsgId(e, t) {
1451
+ let n = this._lastVisibleMessagePairs, r = n.findIndex((e) => e.codecMessageId === t);
1452
+ if (r > 0) return n[r - 1]?.codecMessageId;
1453
+ if (r === 0) return;
1454
+ let i = this._codec.getMessages(e.projection), a = i.findIndex((e) => e.codecMessageId === t);
1455
+ if (a > 0) return i[a - 1]?.codecMessageId;
1456
+ if (a === 0 && e.parentCodecMessageId !== void 0) {
1457
+ let t = this._tree.getNodeByCodecMessageId(e.parentCodecMessageId);
1458
+ if (t) return this._codec.getMessages(t.projection).at(-1)?.codecMessageId;
1459
+ }
799
1460
  }
800
- _getMessagesWithHeaders() {
801
- return this._tree.flatten().map((e) => ({
802
- message: e,
803
- headers: this.getMessageHeaders(e)
804
- }));
1461
+ on(e, t) {
1462
+ let n = t;
1463
+ return this._emitter.on(e, n), () => {
1464
+ this._emitter.off(e, n);
1465
+ };
805
1466
  }
806
- _getHistoryBefore(e) {
807
- let t = this._getMessagesWithHeaders(), n = t.findIndex((t) => t.headers?.[a] === e);
808
- return n === -1 ? t : t.slice(0, n);
1467
+ close() {
1468
+ if (!this._closed) {
1469
+ this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
1470
+ for (let e of this._unsubs) e();
1471
+ this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._regenSelections.clear(), this._withheldRunIds.clear(), this._withheldBuffer.length = 0, this._onClose?.();
1472
+ }
1473
+ }
1474
+ async _loadFirstPage(e) {
1475
+ let t = e * ke, n = await De(this._channel, { limit: t }, this._logger);
1476
+ this._closed || await this._revealFromPage(n, e);
1477
+ }
1478
+ async _revealFromPage(e, t) {
1479
+ let n = new Set(this._treeVisibleNodes().map((e) => X(e))), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
1480
+ this._closed || (this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext(), this._splitReveal(r, t));
1481
+ }
1482
+ _splitReveal(e, t) {
1483
+ let n = 0, r = e.length;
1484
+ for (let i = e.length - 1; i >= 0; i--) {
1485
+ if (e[i]?.kind === "run") {
1486
+ if (n === t) break;
1487
+ n++;
1488
+ }
1489
+ r = i;
1490
+ }
1491
+ let i = e.slice(r), a = e.slice(0, r);
1492
+ for (let e of a) this._withheldRunIds.add(X(e));
1493
+ this._withheldBuffer.push(...a), this._releaseWithheld(i);
809
1494
  }
810
1495
  _processHistoryPage(e) {
811
- for (let [t, n] of e.items.entries()) {
812
- let r = e.itemHeaders?.[t] ?? {}, i = e.itemSerials?.[t], a = this._codec.getMessageKey(n), o = r["x-ably-msg-id"] ?? a;
813
- this._tree.upsert(o, n, r, i);
1496
+ this._processingHistory = !0;
1497
+ try {
1498
+ let t = this._codec.createDecoder();
1499
+ for (let n of e.rawMessages) q(this._tree, t, n);
1500
+ for (let t of e.rawMessages) this._tree.emitAblyMessage(t);
1501
+ } finally {
1502
+ this._processingHistory = !1;
814
1503
  }
815
- this._emitter.emit("message"), e.rawMessages && e.rawMessages.length > 0 && (this._ablyMessages.unshift(...e.rawMessages), this._emitter.emit("ably-message"));
816
1504
  }
817
1505
  async _loadUntilVisible(e, t, n) {
818
1506
  this._processHistoryPage(e);
819
1507
  let r = e, i = () => {
820
1508
  let e = 0;
821
- for (let t of this._tree.flatten()) n.has(this._codec.getMessageKey(t)) || e++;
1509
+ for (let t of this._treeVisibleNodes()) t.kind === "run" && !n.has(X(t)) && e++;
822
1510
  return e;
823
1511
  };
824
1512
  for (; i() < t && r.hasNext();) {
825
1513
  let e = await r.next();
826
- if (!e) break;
1514
+ if (!e || this._closed) break;
827
1515
  this._processHistoryPage(e), r = e;
828
1516
  }
829
1517
  return {
830
- newVisible: this._tree.flatten().filter((e) => !n.has(this._codec.getMessageKey(e))),
1518
+ newVisible: this._treeVisibleNodes().filter((e) => !n.has(X(e))),
831
1519
  lastPage: r
832
1520
  };
833
1521
  }
834
1522
  _releaseWithheld(e) {
835
- for (let t of e) this._withheldKeys.delete(this._codec.getMessageKey(t));
836
- e.length > 0 && this._emitter.emit("message");
1523
+ for (let t of e) this._withheldRunIds.delete(X(t));
1524
+ e.length > 0 && this._recomputeAndEmit();
837
1525
  }
838
- async send(t, n) {
839
- if (this._closed || (await this._attachPromise, this._closed)) throw new e.ErrorInfo("unable to send; transport is closed", x.TransportClosed, 400);
840
- this._logger.trace("ClientTransport.send();");
841
- let r = Array.isArray(t) ? t : [t], i = crypto.randomUUID();
842
- this._ownTurnIds.add(i);
843
- let o = /* @__PURE__ */ new Set(), c = [], l = this._getMessagesWithHeaders(), u;
844
- if (n?.parent === void 0 && !n?.forkOf) {
845
- let e = this._tree.flatten();
846
- if (e.length > 0) {
847
- let t = e.at(-1);
848
- if (t) {
849
- let e = this._codec.getMessageKey(t);
850
- u = this._tree.getNodeByKey(e)?.msgId ?? e;
851
- }
852
- }
853
- }
854
- let d = n?.parent === void 0 ? u : n.parent;
855
- for (let e of r) {
856
- let t = crypto.randomUUID();
857
- this._ownMsgIds.add(t), o.add(t);
858
- let r = n?.parent === void 0 ? u : n.parent ?? void 0, l = j({
859
- role: "user",
860
- turnId: i,
861
- msgId: t,
862
- turnClientId: this._clientId,
863
- parent: r,
864
- forkOf: n?.forkOf
865
- });
866
- this._upsertAndNotify(e, l);
867
- let d = {
868
- [a]: t,
869
- [s]: "user"
870
- };
871
- r && (d[f] = r), c.push({
872
- message: e,
873
- headers: d
874
- }), n?.parent === void 0 && !n?.forkOf && (u = t);
875
- }
876
- this._turnMsgIds.set(i, o);
877
- let p = this._router.createStream(i), m = this._headersFn?.() ?? {}, h = {
878
- ...this._bodyFn?.() ?? {},
879
- history: l,
880
- ...n?.body,
881
- turnId: i,
882
- clientId: this._clientId,
883
- messages: c,
884
- ...n?.forkOf !== void 0 && { forkOf: n.forkOf },
885
- ...d !== void 0 && { parent: d }
886
- }, g = {
887
- ...m,
888
- ...n?.headers
889
- };
890
- return this._fetchFn(this._api, {
891
- method: "POST",
892
- headers: {
893
- "Content-Type": "application/json",
894
- ...g
895
- },
896
- body: JSON.stringify(h),
897
- ...this._credentials ? { credentials: this._credentials } : {}
898
- }).then((t) => {
899
- t.ok || (this._emitter.emit("error", new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(t.status)} ${t.statusText}`, x.TransportSendFailed, t.status)), this._router.closeStream(i));
900
- }).catch((t) => {
901
- let n = t instanceof e.ErrorInfo ? t : void 0;
902
- this._emitter.emit("error", new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} failed: ${t instanceof Error ? t.message : String(t)}`, x.TransportSendFailed, 500, n)), this._router.closeStream(i);
903
- }), {
904
- stream: p,
905
- turnId: i,
906
- cancel: async () => this.cancel({ turnId: i })
907
- };
1526
+ _updateVisibleSnapshot(e) {
1527
+ let t = e ?? this._cachedNodes;
1528
+ this._lastVisibleNodeKeys = t.map((e) => X(e)), this._lastVisibleNodeKeySet = new Set(this._lastVisibleNodeKeys), this._lastVisibleProjections = t.map((e) => e.projection), this._lastVisibleMessagePairs = this._extractMessages(t);
908
1529
  }
909
- async regenerate(e, t) {
910
- this._logger.trace("ClientTransport.regenerate();", { messageId: e });
911
- let n = this._tree.getNode(e)?.parentId;
912
- return this.send([], {
913
- ...t,
914
- body: {
915
- history: this._getHistoryBefore(e),
916
- ...t?.body
917
- },
918
- forkOf: e,
919
- parent: n
920
- });
1530
+ _onTreeUpdate() {
1531
+ this._processingHistory || (this._pinBranchSelections(), this._resolvePendingRegenSelections(), this._recomputeAndEmitIfChanged());
921
1532
  }
922
- async edit(e, t, n) {
923
- this._logger.trace("ClientTransport.edit();", { messageId: e });
924
- let r = this._tree.getNode(e)?.parentId;
925
- return this.send(t, {
926
- ...n,
927
- body: {
928
- history: this._getHistoryBefore(e),
929
- ...n?.body
930
- },
931
- forkOf: e,
932
- parent: r
933
- });
1533
+ _resolveSelections() {
1534
+ let e = /* @__PURE__ */ new Map();
1535
+ for (let [t, n] of this._branchSelections) e.set(t, n.selectedKey);
1536
+ for (let [t, n] of this._regenSelections) n.kind !== "pending" && e.set(t, n.selectedRunId);
1537
+ return e;
934
1538
  }
935
- async cancel(e) {
936
- if (this._closed) return;
937
- let t = e ?? { own: !0 };
938
- this._logger.debug("ClientTransport.cancel();", { filter: t }), await this._publishCancel(t), this._closeMatchingTurnStreams(t);
939
- }
940
- async waitForTurn(e) {
941
- if (this._closed) return;
942
- let t = e ?? { own: !0 }, n = this._getMatchingTurnIds(t);
943
- if (n.size !== 0) return this._logger.debug("ClientTransport.waitForTurn();", { turnIds: [...n] }), new Promise((e) => {
944
- let t = (r) => {
945
- r.type === "x-ably-turn-end" && (n.delete(r.turnId), n.size === 0 && (this._emitter.off("turn", t), e()));
946
- };
947
- this._emitter.on("turn", t);
948
- });
1539
+ _treeVisibleNodes() {
1540
+ return this._tree.visibleNodes(this._resolveSelections());
949
1541
  }
950
- on(e, t) {
951
- if (this._closed) return te;
952
- let n = t;
953
- return this._emitter.on(e, n), () => {
954
- this._emitter.off(e, n);
955
- };
1542
+ _pinBranchSelections() {
1543
+ for (let e of this._lastVisibleNodeKeys) {
1544
+ if (this._tree.getNode(e)?.kind !== "input" || this._tree.getSiblingNodes(e).length <= 1) continue;
1545
+ let t = this._tree.getGroupRoot(e);
1546
+ this._branchSelections.get(t) || this._branchSelections.set(t, {
1547
+ kind: "pinned",
1548
+ selectedKey: e
1549
+ });
1550
+ }
956
1551
  }
957
- getTree() {
958
- return this._tree;
1552
+ _resolvePendingRegenSelections() {
1553
+ for (let [e, t] of this._regenSelections) {
1554
+ if (t.kind === "user") continue;
1555
+ let n = this._tree.getSiblingNodes(e).filter((e) => e.kind === "run");
1556
+ if (n.length <= 1) continue;
1557
+ let r = n.at(-1);
1558
+ r && this._regenSelections.set(e, {
1559
+ kind: "auto",
1560
+ selectedRunId: r.runId
1561
+ });
1562
+ }
959
1563
  }
960
- getActiveTurnIds() {
961
- let e = /* @__PURE__ */ new Map();
962
- for (let [t, n] of this._turnClientIds) {
963
- let r = e.get(n);
964
- r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
1564
+ _onTreeAblyMessage(e) {
1565
+ let t = O(e), n = t[l], r = t[o];
1566
+ if (!n && !r) {
1567
+ this._emitter.emit("ably-message", e);
1568
+ return;
965
1569
  }
966
- return e;
1570
+ r && this._lastVisibleNodeKeySet.has(r) && this._emitter.emit("ably-message", e);
967
1571
  }
968
- getMessageHeaders(e) {
969
- let t = this._codec.getMessageKey(e);
970
- return this._tree.getNodeByKey(t)?.headers;
1572
+ _onTreeRun(e) {
1573
+ if (this._lastVisibleNodeKeySet.has(e.runId)) {
1574
+ this._emitter.emit("run", e);
1575
+ return;
1576
+ }
1577
+ e.type === "start" && this._isRunStartVisible(e) && (this._lastVisibleNodeKeySet.add(e.runId), this._emitter.emit("run", e));
971
1578
  }
972
- getMessages() {
973
- return this._withheldKeys.size === 0 ? this._tree.flatten() : this._tree.flatten().filter((e) => !this._withheldKeys.has(this._codec.getMessageKey(e)));
974
- }
975
- getMessagesWithHeaders() {
976
- return this._getMessagesWithHeaders();
977
- }
978
- getAblyMessages() {
979
- return [...this._ablyMessages];
980
- }
981
- async history(t) {
982
- if (this._closed) throw new e.ErrorInfo("unable to load history; transport is closed", x.TransportClosed, 400);
983
- this._logger.trace("ClientTransport.history();", { limit: t?.limit });
984
- let n = t?.limit ?? 100, r = new Set(this._tree.flatten().map((e) => this._codec.getMessageKey(e))), i = await X(this._channel, this._codec, t, this._logger), a = await this._loadUntilVisible(i, n, r);
985
- i = a.lastPage;
986
- let o = a.newVisible;
987
- for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
988
- let s = o.slice(-n), c = o.slice(0, -n);
989
- this._releaseWithheld(s);
990
- let l = (e) => ({
991
- items: e,
992
- hasNext: () => c.length > 0 || i.hasNext(),
993
- next: async () => {
994
- if (c.length > 0) {
995
- let e = c.splice(-n, n);
996
- return this._releaseWithheld(e), l(e);
997
- }
998
- if (!i.hasNext()) return;
999
- let e = await i.next();
1000
- if (!e) return;
1001
- let t = new Set(r);
1002
- for (let e of this._tree.flatten()) t.add(this._codec.getMessageKey(e));
1003
- let a = await this._loadUntilVisible(e, n, t);
1004
- i = a.lastPage;
1005
- let o = a.newVisible;
1006
- for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
1007
- let s = o.splice(-n, n);
1008
- if (c.push(...o), this._releaseWithheld(s), s.length !== 0) return l(s);
1009
- }
1010
- });
1011
- return l(s);
1579
+ _isRunStartVisible(e) {
1580
+ let { parent: t } = e;
1581
+ if (t === void 0) return !0;
1582
+ let n = this._tree.getNodeByCodecMessageId(t);
1583
+ return n ? this._lastVisibleNodeKeySet.has(X(n)) : !0;
1012
1584
  }
1013
- async close(e) {
1014
- if (!this._closed) {
1015
- if (this._closed = !0, this._logger.info("ClientTransport.close();"), e?.cancel) {
1016
- try {
1017
- await this._publishCancel(e.cancel);
1018
- } catch {}
1019
- this._closeMatchingTurnStreams(e.cancel);
1585
+ _visibleChanged(e) {
1586
+ if (e.length !== this._lastVisibleNodeKeys.length) return !0;
1587
+ for (let [t, n] of e.entries()) if (X(n) !== this._lastVisibleNodeKeys[t] || n.projection !== this._lastVisibleProjections[t]) return !0;
1588
+ return !1;
1589
+ }
1590
+ }, je = (e) => new Ae(e), Me = () => {}, Ne = class {
1591
+ constructor(e) {
1592
+ this._views = /* @__PURE__ */ new Set(), this._state = "ready", this._pendingRunStarts = /* @__PURE__ */ new Map();
1593
+ let t = B(e.client, e.codec);
1594
+ if (this._channel = e.client.channels.get(e.channelName, t), this._codec = e.codec, this._clientId = e.clientId, this._logger = (e.logger ?? ve({ logLevel: ge.Silent })).withContext({ component: "ClientSession" }), this._emitter = new Y(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = we(this._codec, this._logger), this._view = je({
1595
+ tree: this._tree,
1596
+ channel: this._channel,
1597
+ codec: this._codec,
1598
+ sendDelegate: this._internalSend.bind(this),
1599
+ logger: this._logger,
1600
+ onClose: () => this._views.delete(this._view)
1601
+ }), this._decoder = this._codec.createDecoder(), this._encoder = this._codec.createEncoder(this._channel, this._clientId === void 0 ? void 0 : { clientId: this._clientId }), this._views.add(this._view), this.tree = this._tree, this.view = this._view, e.messages) {
1602
+ let t;
1603
+ for (let n of e.messages) {
1604
+ let e = crypto.randomUUID(), r = {
1605
+ [l]: e,
1606
+ [f]: "user"
1607
+ };
1608
+ t && (r[p] = t), this._tree.applyMessage({
1609
+ inputs: [this._codec.createUserMessage(n)],
1610
+ outputs: []
1611
+ }, r), t = e;
1020
1612
  }
1021
- this._channel.unsubscribe(this._onMessage);
1022
- for (let e of this._ownTurnIds) this._router.closeStream(e);
1023
- this._turnObservers.clear(), this._emitter.off(), this._ownTurnIds.clear(), this._ownMsgIds.clear(), this._turnMsgIds.clear(), this._turnClientIds.clear(), this._withheldKeys.clear(), this._ablyMessages.length = 0;
1024
1613
  }
1614
+ this._onMessage = (e) => {
1615
+ this._handleMessage(e);
1616
+ }, this._onChannelStateChange = (e) => {
1617
+ this._handleChannelStateChange(e);
1618
+ }, this._channel.on(this._onChannelStateChange);
1619
+ }
1620
+ connect() {
1621
+ return this._state === "closed" ? Promise.reject(new e.ErrorInfo("unable to connect; session is closed", T.SessionClosed, 400)) : this._connectPromise ? this._connectPromise : (this._logger.trace("DefaultClientSession.connect();"), this._connectPromise = this._channel.subscribe(this._onMessage).then(() => {
1622
+ this._logger.debug("DefaultClientSession.connect(); subscribed and attached");
1623
+ }, (t) => {
1624
+ let n = new e.ErrorInfo(`unable to subscribe to channel; ${t instanceof Error ? t.message : String(t)}`, T.SessionSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
1625
+ throw this._logger.error("DefaultClientSession.connect(); subscribe failed"), this._emitter.emit("error", n), n;
1626
+ }), this._connectPromise);
1627
+ }
1628
+ async _requireConnected(t) {
1629
+ if (!this._connectPromise) throw new e.ErrorInfo(`unable to ${t}; connect() must be called before ${t}()`, T.InvalidArgument, 400);
1630
+ return this._connectPromise;
1025
1631
  }
1026
- }, re = (e) => new ne(e), ie = (e) => [{
1027
- kind: "event",
1028
- event: e
1029
- }], ae = class {
1030
- constructor(e, t = {}) {
1031
- this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
1032
- }
1033
- decode(e) {
1034
- let t = e.action;
1035
- this._logger?.trace("DefaultDecoderCore.decode();", {
1036
- action: t,
1037
- serial: e.serial,
1038
- name: e.name
1039
- });
1040
- let n;
1041
- switch (t) {
1042
- case "message.create": {
1043
- let t = this._toPayload(e);
1044
- n = t.headers?.["x-ably-stream"] === "true" ? this._decodeStreamedCreate(t, e.serial) : this._hooks.decodeDiscrete(t);
1045
- break;
1632
+ _handleMessage(t) {
1633
+ if (this._state !== "closed") try {
1634
+ if (t.name === "ai-run-end") {
1635
+ let n = O(t);
1636
+ if ((n["run-reason"] ?? "complete") === "error") {
1637
+ let t = n[v], r = t === void 0 ? NaN : Number(t), i = Number.isFinite(r) ? r : T.SessionSubscriptionError, a = n["error-message"] ?? "agent reported an error", c = i >= 1e4 && i < 6e4 ? Math.floor(i / 100) : 500, l = new e.ErrorInfo(a, i, c);
1638
+ this._logger.error("ClientSession._handleMessage(); agent error received", {
1639
+ runId: n[o],
1640
+ invocationId: n[s],
1641
+ code: i
1642
+ }), this._emitter.emit("error", l);
1643
+ }
1046
1644
  }
1047
- case "message.append":
1048
- n = this._decodeAppend(e);
1049
- break;
1050
- case "message.update":
1051
- n = this._decodeUpdate(e);
1052
- break;
1053
- case "message.delete":
1054
- n = this._decodeDelete(e);
1055
- break;
1056
- default: return [];
1645
+ let n = q(this._tree, this._decoder, t);
1646
+ if (n && (n.type === "start" || n.type === "resume")) {
1647
+ let e = O(t)[_];
1648
+ if (e !== void 0) {
1649
+ let t = this._pendingRunStarts.get(e);
1650
+ t && (this._pendingRunStarts.delete(e), t.resolve(n.runId));
1651
+ }
1652
+ }
1653
+ this._tree.emitAblyMessage(t);
1654
+ } catch (t) {
1655
+ let n = t instanceof e.ErrorInfo ? t : void 0;
1656
+ this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, T.SessionSubscriptionError, 500, n));
1057
1657
  }
1058
- let r = C(e)[a];
1059
- if (r) for (let e of n) e.kind === "event" && (e.messageId = r);
1060
- return n;
1061
1658
  }
1062
- _toPayload(e) {
1063
- return {
1064
- name: e.name ?? "",
1065
- data: e.data,
1066
- headers: C(e)
1067
- };
1068
- }
1069
- _stringData(e) {
1070
- return typeof e.data == "string" ? e.data : "";
1071
- }
1072
- _invokeOnStreamUpdate(e) {
1073
- if (this._onStreamUpdate) try {
1074
- this._onStreamUpdate(e);
1075
- } catch (e) {
1076
- this._logger?.error("DefaultDecoderCore._invokeOnStreamUpdate(); callback threw", { error: e });
1659
+ _handleChannelStateChange(t) {
1660
+ if (this._state === "closed") return;
1661
+ let { current: n, resumed: r } = t;
1662
+ if (n === "attached" && !this._hasAttachedOnce) {
1663
+ this._hasAttachedOnce = !0;
1664
+ return;
1077
1665
  }
1666
+ if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
1667
+ this._logger.error("ClientSession._handleChannelStateChange(); channel continuity lost", {
1668
+ current: n,
1669
+ resumed: r,
1670
+ previous: t.previous
1671
+ });
1672
+ let i = new e.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, T.ChannelContinuityLost, 500, t.reason);
1673
+ this._emitter.emit("error", i);
1078
1674
  }
1079
- _invokeOnStreamDelete(e, t) {
1080
- if (this._onStreamDelete) try {
1081
- this._onStreamDelete(e, t);
1082
- } catch (e) {
1083
- this._logger?.error("DefaultDecoderCore._invokeOnStreamDelete(); callback threw", { error: e });
1675
+ _cleanupFailedSend(e) {
1676
+ for (let t of e) {
1677
+ let e = this._tree.getNodeByCodecMessageId(t);
1678
+ e?.kind === "input" && e.serial === void 0 && this._tree.delete(e.codecMessageId);
1084
1679
  }
1085
1680
  }
1086
- _decodeStreamedCreate(e, t) {
1087
- if (!t) return [];
1088
- let n = e.headers?.["x-ably-stream-id"] ?? "", r = e.headers ?? {}, i = {
1089
- name: e.name,
1090
- streamId: n,
1091
- accumulated: "",
1092
- headers: { ...r },
1093
- closed: !1
1681
+ createView() {
1682
+ if (this._state === "closed") throw new e.ErrorInfo("unable to create view; session is closed", T.SessionClosed, 400);
1683
+ this._logger.trace("DefaultClientSession.createView();");
1684
+ let t = je({
1685
+ tree: this._tree,
1686
+ channel: this._channel,
1687
+ codec: this._codec,
1688
+ sendDelegate: this._internalSend.bind(this),
1689
+ logger: this._logger,
1690
+ onClose: () => this._views.delete(t)
1691
+ });
1692
+ return this._views.add(t), t;
1693
+ }
1694
+ async _internalSend(n, r, i) {
1695
+ if (this._state === "closed" || (await this._requireConnected("send"), this._state === "closed")) throw new e.ErrorInfo("unable to send; session is closed", T.SessionClosed, 400);
1696
+ let a = this._channel.state;
1697
+ if (a !== "attached" && a !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${a}`, T.ChannelNotReady, 400);
1698
+ this._logger.trace("ClientSession._internalSend();");
1699
+ let o = r?.runId !== void 0, s = r?.runId, c;
1700
+ r?.parent === void 0 && !r?.forkOf && (c = i);
1701
+ let l = /* @__PURE__ */ new Set(), u = [];
1702
+ for (let e of n) {
1703
+ let t = crypto.randomUUID(), n = e.codecMessageId ?? crypto.randomUUID();
1704
+ l.add(n);
1705
+ 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 = V({
1706
+ role: "user",
1707
+ runId: s,
1708
+ codecMessageId: n,
1709
+ runClientId: this._clientId,
1710
+ ...a !== void 0 && { parent: a },
1711
+ ...o !== void 0 && { forkOf: o },
1712
+ ...d !== void 0 && { regenerates: d },
1713
+ inputEventId: t
1714
+ });
1715
+ i || this._tree.applyMessage({
1716
+ inputs: [e],
1717
+ outputs: []
1718
+ }, f), u.push({
1719
+ input: e,
1720
+ codecMessageId: n,
1721
+ inputEventId: t,
1722
+ headers: f,
1723
+ isWireOnly: i
1724
+ }), !i && r?.parent === void 0 && !r?.forkOf && e.parent === void 0 && (c = n);
1725
+ }
1726
+ let d = u.at(-1);
1727
+ if (d === void 0) throw new e.ErrorInfo("unable to send; inputs array is empty (include at least one input)", T.InvalidArgument, 400);
1728
+ let f = d.inputEventId, p = d.codecMessageId, m = new Promise((e, t) => {
1729
+ this._pendingRunStarts.set(p, {
1730
+ resolve: e,
1731
+ reject: t
1732
+ });
1733
+ });
1734
+ return m.catch(() => {}), await (async () => {
1735
+ try {
1736
+ for (let e of u) await this._encoder.publishInput(e.input, {
1737
+ extras: { headers: e.headers },
1738
+ messageId: e.codecMessageId,
1739
+ ...this._clientId !== void 0 && { clientId: this._clientId }
1740
+ });
1741
+ } catch (t) {
1742
+ let n = t instanceof e.ErrorInfo ? t : void 0, r = n?.statusCode === 401 || n?.statusCode === 403, i = new e.ErrorInfo(r ? "unable to publish events; missing publish capability on the channel" : `unable to publish events; ${t instanceof Error ? t.message : String(t)}`, r ? T.InsufficientCapability : T.SessionSendFailed, r ? 401 : 500, n);
1743
+ throw this._emitter.emit("error", i), this._pendingRunStarts.delete(p), o || this._cleanupFailedSend([...l]), i;
1744
+ }
1745
+ })(), {
1746
+ inputCodecMessageId: p,
1747
+ runId: m,
1748
+ inputEventId: f,
1749
+ cancel: async () => {
1750
+ await this._publishCancel({
1751
+ inputCodecMessageId: p,
1752
+ ...s !== void 0 && { runId: s }
1753
+ });
1754
+ },
1755
+ optimisticCodecMessageIds: [...l],
1756
+ toInvocation: () => t.fromJSON({
1757
+ inputEventId: f,
1758
+ sessionName: this._channel.name
1759
+ })
1094
1760
  };
1095
- return this._serialState.set(t, i), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
1096
- name: e.name,
1097
- streamId: n,
1098
- serial: t
1099
- }), this._hooks.buildStartEvents(i);
1100
- }
1101
- _decodeAppend(e) {
1102
- let t = e.serial;
1103
- if (!t) return [];
1104
- let r = this._serialState.get(t);
1105
- if (!r) return this._decodeUpdate(e);
1106
- let i = C(e), a = typeof e.data == "string" ? e.data : "", o = i[n], s = [];
1107
- 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;
1108
1761
  }
1109
- _decodeUpdate(e) {
1110
- let r = e.serial;
1111
- if (!r) return [];
1112
- let i = this._toPayload(e), a = i.headers ?? {}, o = a[t] === "true", s = a[n], c = this._serialState.get(r);
1113
- if (!c) return this._decodeFirstContact(i, o, s, r);
1114
- let l = this._stringData(e);
1115
- if (l.startsWith(c.accumulated)) {
1116
- let e = l.slice(c.accumulated.length), t = [];
1117
- 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;
1118
- }
1119
- return c.accumulated = l, c.headers = { ...a }, this._invokeOnStreamUpdate(c), [];
1762
+ async cancel(e) {
1763
+ return this._publishCancel({ runId: e });
1120
1764
  }
1121
- _decodeFirstContact(e, t, n, r) {
1122
- if (!t) return this._hooks.decodeDiscrete(e);
1123
- let i = e.headers?.["x-ably-stream-id"] ?? "", a = e.headers ?? {}, o = typeof e.data == "string" ? e.data : "";
1124
- this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
1125
- name: e.name,
1126
- streamId: i,
1127
- serial: r
1765
+ async _publishCancel(e) {
1766
+ if (this._state === "closed" || (await this._requireConnected("cancel"), this._state === "closed")) return;
1767
+ this._logger.debug("ClientSession._publishCancel();", {
1768
+ runId: e.runId,
1769
+ inputCodecMessageId: e.inputCodecMessageId
1128
1770
  });
1129
- let s = {
1130
- name: e.name,
1131
- streamId: i,
1132
- accumulated: o,
1133
- headers: { ...a },
1134
- closed: n === "finished" || n === "aborted"
1771
+ let t = { [c]: crypto.randomUUID() };
1772
+ e.runId !== void 0 && (t[o] = e.runId), e.inputCodecMessageId !== void 0 && (t[_] = e.inputCodecMessageId), await this._channel.publish({
1773
+ name: b,
1774
+ extras: { ai: { transport: t } }
1775
+ });
1776
+ }
1777
+ on(e, t) {
1778
+ if (this._state === "closed") return Me;
1779
+ let n = t;
1780
+ return this._emitter.on(e, n), () => {
1781
+ this._emitter.off(e, n);
1135
1782
  };
1136
- this._serialState.set(r, s);
1137
- let c = this._hooks.buildStartEvents(s);
1138
- return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "finished" && c.push(...this._hooks.buildEndEvents(s, a)), c;
1139
1783
  }
1140
- _decodeDelete(e) {
1141
- let t = e.serial;
1142
- if (!t) return [];
1143
- let n = this._serialState.get(t);
1144
- return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
1784
+ async close() {
1785
+ if (this._state !== "closed") {
1786
+ this._state = "closed", this._logger.info("ClientSession.close();"), this._connectPromise && this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange), this._emitter.off();
1787
+ for (let e of this._views) e.close();
1788
+ if (this._views.clear(), this._pendingRunStarts.size > 0) {
1789
+ let t = new e.ErrorInfo("unable to await run-start; session closed", T.SessionClosed, 400);
1790
+ for (let e of this._pendingRunStarts.values()) e.reject(t);
1791
+ this._pendingRunStarts.clear();
1792
+ }
1793
+ try {
1794
+ await this._encoder.close();
1795
+ } catch {}
1796
+ if (this._connectPromise) try {
1797
+ await this._channel.detach();
1798
+ } catch (e) {
1799
+ this._logger.debug("ClientSession.close(); channel detach failed", { error: e });
1800
+ }
1801
+ }
1145
1802
  }
1146
- }, oe = (e, t = {}) => new ae(e, t), $ = class {
1803
+ }, Pe = (e) => new Ne(e), Fe = class {
1147
1804
  constructor(e, t = {}) {
1148
1805
  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" });
1149
1806
  }
@@ -1154,47 +1811,48 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1154
1811
  }
1155
1812
  async publishDiscreteBatch(e, t) {
1156
1813
  this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscreteBatch();", { count: e.length });
1157
- let n = e.map((e) => this._buildDiscreteMessage(e, t));
1814
+ let n = e.map((e) => this._buildDiscreteMessage(e, t, !0));
1158
1815
  return this._writer.publish(n);
1159
1816
  }
1160
- async startStream(i, a, o) {
1817
+ async startStream(t, a, o) {
1161
1818
  this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.startStream();", {
1162
1819
  name: a.name,
1163
- streamId: i
1820
+ streamId: t
1164
1821
  });
1165
- let s = this._buildHeaders(a.headers ?? {}, o);
1166
- s[t] = "true", s[n] = "streaming", s[r] = i;
1167
- let c = this._resolveClientId(o), l = {
1822
+ let s = this._buildTransport(a.transportHeaders, o);
1823
+ s[n] = "true", s[r] = "streaming", s[i] = t;
1824
+ let c = a.codecHeaders ?? {}, l = this._resolveClientId(o), u = {
1168
1825
  name: a.name,
1169
1826
  data: a.data,
1170
- extras: { headers: s },
1171
- ...c ? { clientId: c } : {}
1827
+ extras: { ai: this._aiExtras(s, c) },
1828
+ ...l ? { clientId: l } : {}
1172
1829
  };
1173
- this._invokeOnMessage(l);
1174
- let u = (await this._writer.publish(l)).serials[0];
1175
- if (!u) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${i})`, x.BadRequest, 400);
1176
- this._trackers.set(i, {
1177
- serial: u,
1830
+ this._invokeOnMessage(u);
1831
+ let d = (await this._writer.publish(u)).serials[0];
1832
+ if (!d) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${t})`, T.BadRequest, 400);
1833
+ this._trackers.set(t, {
1834
+ serial: d,
1178
1835
  name: a.name,
1179
- streamId: i,
1836
+ streamId: t,
1180
1837
  accumulated: a.data,
1181
- persistentHeaders: s,
1182
- aborted: !1
1838
+ persistentTransport: s,
1839
+ persistentCodec: c,
1840
+ cancelled: !1
1183
1841
  }), this._logger?.debug("DefaultEncoderCore.startStream(); stream started", {
1184
1842
  name: a.name,
1185
- streamId: i,
1186
- serial: u
1843
+ streamId: t,
1844
+ serial: d
1187
1845
  });
1188
1846
  }
1189
1847
  appendStream(t, n) {
1190
1848
  this._assertNotClosed();
1191
1849
  let r = this._trackers.get(t);
1192
- if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`, x.InvalidArgument, 400);
1850
+ if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`, T.InvalidArgument, 400);
1193
1851
  r.accumulated += n;
1194
1852
  let i = {
1195
1853
  serial: r.serial,
1196
1854
  data: n,
1197
- extras: { headers: { ...r.persistentHeaders } }
1855
+ extras: { ai: this._aiExtras({ ...r.persistentTransport }, { ...r.persistentCodec }) }
1198
1856
  };
1199
1857
  this._invokeOnMessage(i);
1200
1858
  let a = this._writer.appendMessage(i);
@@ -1203,59 +1861,59 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1203
1861
  streamId: t
1204
1862
  });
1205
1863
  }
1206
- async closeStream(t, r) {
1864
+ async closeStream(t, n) {
1207
1865
  this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.closeStream();", { streamId: t });
1208
1866
  let i = this._trackers.get(t);
1209
- if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, x.InvalidArgument, 400);
1210
- i.accumulated += r.data;
1211
- let a = this._buildClosingHeaders(i, r.headers ?? {});
1212
- a[n] = "finished";
1213
- let o = {
1867
+ if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, T.InvalidArgument, 400);
1868
+ i.accumulated += n.data;
1869
+ let { transport: a, codec: o } = this._buildClosing(i, n);
1870
+ a[r] = "complete";
1871
+ let s = {
1214
1872
  serial: i.serial,
1215
- data: r.data,
1216
- extras: { headers: a }
1873
+ data: n.data,
1874
+ extras: { ai: this._aiExtras(a, o) }
1217
1875
  };
1218
- this._invokeOnMessage(o);
1219
- let s = this._writer.appendMessage(o);
1876
+ this._invokeOnMessage(s);
1877
+ let c = this._writer.appendMessage(s);
1220
1878
  this._pending.push({
1221
- promise: s,
1879
+ promise: c,
1222
1880
  streamId: t
1223
1881
  }), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.closeStream(); stream closed", { streamId: t });
1224
1882
  }
1225
- async abortStream(t, r) {
1226
- this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortStream();", { streamId: t });
1883
+ async cancelStream(t, n) {
1884
+ this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.cancelStream();", { streamId: t });
1227
1885
  let i = this._trackers.get(t);
1228
- if (!i) throw new e.ErrorInfo(`unable to abort stream; no active stream for streamId '${t}'`, x.InvalidArgument, 400);
1229
- i.aborted = !0;
1230
- let a = this._buildClosingHeaders(i, {}, r);
1231
- a[n] = "aborted";
1232
- let o = {
1886
+ if (!i) throw new e.ErrorInfo(`unable to cancel stream; no active stream for streamId '${t}'`, T.InvalidArgument, 400);
1887
+ i.cancelled = !0;
1888
+ let { transport: a, codec: o } = this._buildClosing(i, void 0, n);
1889
+ a[r] = "cancelled";
1890
+ let s = {
1233
1891
  serial: i.serial,
1234
1892
  data: "",
1235
- extras: { headers: a }
1893
+ extras: { ai: this._aiExtras(a, o) }
1236
1894
  };
1237
- this._invokeOnMessage(o);
1238
- let s = this._writer.appendMessage(o);
1895
+ this._invokeOnMessage(s);
1896
+ let c = this._writer.appendMessage(s);
1239
1897
  this._pending.push({
1240
- promise: s,
1898
+ promise: c,
1241
1899
  streamId: t
1242
- }), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.abortStream(); stream aborted", { streamId: t });
1900
+ }), await this._flushPending(), this._logger?.debug("DefaultEncoderCore.cancelStream(); stream cancelled", { streamId: t });
1243
1901
  }
1244
- async abortAllStreams(e) {
1245
- this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortAllStreams();", { streamCount: this._trackers.size });
1902
+ async cancelAllStreams(e) {
1903
+ this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.cancelAllStreams();", { streamCount: this._trackers.size });
1246
1904
  for (let t of this._trackers.values()) {
1247
- t.aborted = !0;
1248
- let r = this._buildClosingHeaders(t, {}, e);
1249
- r[n] = "aborted";
1250
- let i = {
1905
+ t.cancelled = !0;
1906
+ let { transport: n, codec: i } = this._buildClosing(t, void 0, e);
1907
+ n[r] = "cancelled";
1908
+ let a = {
1251
1909
  serial: t.serial,
1252
1910
  data: "",
1253
- extras: { headers: r }
1911
+ extras: { ai: this._aiExtras(n, i) }
1254
1912
  };
1255
- this._invokeOnMessage(i);
1256
- let a = this._writer.appendMessage(i);
1913
+ this._invokeOnMessage(a);
1914
+ let o = this._writer.appendMessage(a);
1257
1915
  this._pending.push({
1258
- promise: a,
1916
+ promise: o,
1259
1917
  streamId: t.streamId
1260
1918
  });
1261
1919
  }
@@ -1274,10 +1932,10 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1274
1932
  }
1275
1933
  }
1276
1934
  async _doFlush(t) {
1277
- let r = await Promise.allSettled(t.map(async (e) => e.promise)), i = /* @__PURE__ */ new Set();
1278
- for (let [e, n] of r.entries()) {
1279
- let r = t[e];
1280
- r && n.status === "rejected" && i.add(r.streamId);
1935
+ let n = await Promise.allSettled(t.map(async (e) => e.promise)), i = /* @__PURE__ */ new Set();
1936
+ for (let [e, r] of n.entries()) {
1937
+ let n = t[e];
1938
+ n && r.status === "rejected" && i.add(n.streamId);
1281
1939
  }
1282
1940
  if (i.size === 0) {
1283
1941
  this._logger?.debug("DefaultEncoderCore._flushPending(); all appends succeeded");
@@ -1288,13 +1946,13 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1288
1946
  for (let e of i) {
1289
1947
  let t = this._trackers.get(e);
1290
1948
  if (!t) continue;
1291
- let r = t.aborted ? "aborted" : "finished", i = {
1949
+ let n = t.cancelled ? "cancelled" : "complete", i = {
1292
1950
  serial: t.serial,
1293
1951
  data: t.accumulated,
1294
- extras: { headers: {
1295
- ...t.persistentHeaders,
1296
- [n]: r
1297
- } }
1952
+ extras: { ai: this._aiExtras({
1953
+ ...t.persistentTransport,
1954
+ [r]: n
1955
+ }, { ...t.persistentCodec }) }
1298
1956
  };
1299
1957
  try {
1300
1958
  await this._writer.updateMessage(i);
@@ -1307,7 +1965,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1307
1965
  }
1308
1966
  if (a.length > 0) {
1309
1967
  let t = a.map((e) => e.streamId).join(", ");
1310
- throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`, x.EncoderRecoveryFailed, 500);
1968
+ throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`, T.EncoderRecoveryFailed, 500);
1311
1969
  }
1312
1970
  }
1313
1971
  async close() {
@@ -1329,37 +1987,161 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1329
1987
  }
1330
1988
  }
1331
1989
  _assertNotClosed() {
1332
- if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed", x.InvalidArgument, 400);
1990
+ if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed", T.InvalidArgument, 400);
1333
1991
  }
1334
1992
  _resolveClientId(e) {
1335
1993
  return e?.clientId ?? this._defaultClientId;
1336
1994
  }
1337
- _buildHeaders(e, t) {
1995
+ _buildTransport(e, t) {
1338
1996
  let n = {
1339
- ...T(this._defaultExtras?.headers, t?.extras?.headers),
1997
+ ...A(this._defaultExtras?.headers, t?.extras?.headers),
1340
1998
  ...e
1341
1999
  };
1342
- return t?.messageId !== void 0 && (n[a] = t.messageId), n;
1343
- }
1344
- _buildDiscreteMessage(e, n) {
1345
- let r = this._buildHeaders(e.headers ?? {}, n);
1346
- r[t] = "false";
1347
- let i = this._resolveClientId(n), a = {
2000
+ return t?.messageId !== void 0 && (n[l] = t.messageId), n;
2001
+ }
2002
+ _aiExtras(e, t) {
2003
+ return Object.keys(t).length > 0 ? {
2004
+ transport: e,
2005
+ codec: t
2006
+ } : { transport: e };
2007
+ }
2008
+ _buildDiscreteMessage(e, t, r = !1) {
2009
+ let i = this._buildTransport(e.transportHeaders, t);
2010
+ i[n] = "false", r && (i[a] = "true");
2011
+ let o = this._resolveClientId(t), s = {
1348
2012
  name: e.name,
1349
2013
  data: e.data,
1350
2014
  extras: {
1351
- headers: r,
2015
+ ai: this._aiExtras(i, e.codecHeaders ?? {}),
1352
2016
  ...e.ephemeral ? { ephemeral: !0 } : {}
1353
2017
  },
1354
- ...i ? { clientId: i } : {}
2018
+ ...o ? { clientId: o } : {}
2019
+ };
2020
+ return this._invokeOnMessage(s), s;
2021
+ }
2022
+ _buildClosing(e, t, n) {
2023
+ let r = A(this._defaultExtras?.headers, n?.extras?.headers);
2024
+ return {
2025
+ transport: {
2026
+ ...e.persistentTransport,
2027
+ ...r,
2028
+ ...t?.transportHeaders
2029
+ },
2030
+ codec: {
2031
+ ...e.persistentCodec,
2032
+ ...t?.codecHeaders
2033
+ }
1355
2034
  };
1356
- return this._invokeOnMessage(a), a;
1357
2035
  }
1358
- _buildClosingHeaders(e, t, n) {
1359
- let r = { ...e.persistentHeaders }, i = T(this._defaultExtras?.headers, n?.extras?.headers);
1360
- return Object.assign(r, i), Object.assign(r, t), r;
2036
+ }, Ie = (e, t = {}) => new Fe(e, t), Le = class {
2037
+ constructor(e, t = {}) {
2038
+ this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
2039
+ }
2040
+ decode(e) {
2041
+ let t = e.action;
2042
+ switch (this._logger?.trace("DefaultDecoderCore.decode();", {
2043
+ action: t,
2044
+ serial: e.serial,
2045
+ name: e.name
2046
+ }), t) {
2047
+ case "message.create": {
2048
+ let t = this._toPayload(e);
2049
+ return t.transportHeaders?.stream === "true" ? this._decodeStreamedCreate(t, e.serial) : this._hooks.decodeDiscrete(t);
2050
+ }
2051
+ case "message.append": return this._decodeAppend(e);
2052
+ case "message.update": return this._decodeUpdate(e);
2053
+ case "message.delete": return this._decodeDelete(e);
2054
+ default: return [];
2055
+ }
2056
+ }
2057
+ _toPayload(e) {
2058
+ return {
2059
+ name: e.name ?? "",
2060
+ data: e.data,
2061
+ transportHeaders: O(e),
2062
+ codecHeaders: k(e)
2063
+ };
2064
+ }
2065
+ _stringData(e) {
2066
+ return typeof e.data == "string" ? e.data : "";
2067
+ }
2068
+ _invokeOnStreamUpdate(e) {
2069
+ if (this._onStreamUpdate) try {
2070
+ this._onStreamUpdate(e);
2071
+ } catch (e) {
2072
+ this._logger?.error("DefaultDecoderCore._invokeOnStreamUpdate(); callback threw", { error: e });
2073
+ }
2074
+ }
2075
+ _invokeOnStreamDelete(e, t) {
2076
+ if (this._onStreamDelete) try {
2077
+ this._onStreamDelete(e, t);
2078
+ } catch (e) {
2079
+ this._logger?.error("DefaultDecoderCore._invokeOnStreamDelete(); callback threw", { error: e });
2080
+ }
2081
+ }
2082
+ _decodeStreamedCreate(e, t) {
2083
+ if (!t) return [];
2084
+ let n = e.transportHeaders?.["stream-id"] ?? "", r = {
2085
+ name: e.name,
2086
+ streamId: n,
2087
+ accumulated: "",
2088
+ codecHeaders: { ...e.codecHeaders },
2089
+ transportHeaders: { ...e.transportHeaders },
2090
+ closed: !1
2091
+ };
2092
+ return this._serialState.set(t, r), this._logger?.debug("DefaultDecoderCore._decodeStreamedCreate(); new stream", {
2093
+ name: e.name,
2094
+ streamId: n,
2095
+ serial: t
2096
+ }), this._hooks.buildStartEvents(r);
2097
+ }
2098
+ _decodeAppend(e) {
2099
+ let t = e.serial;
2100
+ if (!t) return [];
2101
+ let n = this._serialState.get(t);
2102
+ if (!n) return this._decodeUpdate(e);
2103
+ let i = O(e), a = k(e), o = typeof e.data == "string" ? e.data : "", s = i[r], c = [];
2104
+ return o.length > 0 && (n.accumulated += o, c.push(...this._hooks.buildDeltaEvents(n, o))), s === "complete" && !n.closed ? (n.closed = !0, c.push(...this._hooks.buildEndEvents(n, a)), this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream complete", { streamId: n.streamId })) : s === "cancelled" && !n.closed && (n.closed = !0, this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream cancelled", { streamId: n.streamId })), c;
2105
+ }
2106
+ _decodeUpdate(e) {
2107
+ let t = e.serial;
2108
+ if (!t) return [];
2109
+ let i = this._toPayload(e), a = i.transportHeaders ?? {}, o = i.codecHeaders ?? {}, s = a[n] === "true", c = a[r], l = this._serialState.get(t);
2110
+ if (!l) return this._decodeFirstContact(i, s, c, t);
2111
+ let u = this._stringData(e);
2112
+ if (u.startsWith(l.accumulated)) {
2113
+ let e = u.slice(l.accumulated.length), t = [];
2114
+ return e.length > 0 && (l.accumulated = u, t.push(...this._hooks.buildDeltaEvents(l, e))), c === "complete" && !l.closed ? (l.closed = !0, t.push(...this._hooks.buildEndEvents(l, o))) : c === "cancelled" && !l.closed && (l.closed = !0), t;
2115
+ }
2116
+ return l.accumulated = u, l.codecHeaders = { ...o }, l.transportHeaders = { ...a }, this._invokeOnStreamUpdate(l), [];
2117
+ }
2118
+ _decodeFirstContact(e, t, n, r) {
2119
+ if (!t) return this._hooks.decodeDiscrete(e);
2120
+ let i = e.transportHeaders?.["stream-id"] ?? "", a = e.codecHeaders ?? {}, o = typeof e.data == "string" ? e.data : "";
2121
+ this._logger?.debug("DefaultDecoderCore._decodeFirstContact(); first-contact stream", {
2122
+ name: e.name,
2123
+ streamId: i,
2124
+ serial: r
2125
+ });
2126
+ let s = {
2127
+ name: e.name,
2128
+ streamId: i,
2129
+ accumulated: o,
2130
+ codecHeaders: { ...a },
2131
+ transportHeaders: { ...e.transportHeaders },
2132
+ closed: n === "complete" || n === "cancelled"
2133
+ };
2134
+ this._serialState.set(r, s);
2135
+ let c = this._hooks.buildStartEvents(s);
2136
+ return o.length > 0 && c.push(...this._hooks.buildDeltaEvents(s, o)), n === "complete" && c.push(...this._hooks.buildEndEvents(s, a)), c;
2137
+ }
2138
+ _decodeDelete(e) {
2139
+ let t = e.serial;
2140
+ if (!t) return [];
2141
+ let n = this._serialState.get(t);
2142
+ return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
1361
2143
  }
1362
- }, se = (e, t = {}) => new $(e, t), ce = class {
2144
+ }, Re = (e, t = {}) => new Le(e, t), ze = class {
1363
2145
  constructor(e) {
1364
2146
  this._emitted = /* @__PURE__ */ new Map(), this._phases = e;
1365
2147
  }
@@ -1381,8 +2163,8 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
1381
2163
  let t = this._emitted.get(e);
1382
2164
  return t || (t = /* @__PURE__ */ new Set(), this._emitted.set(e, t)), t;
1383
2165
  }
1384
- }, le = (e) => new ce(e);
2166
+ }, Be = (e) => new ze(e);
1385
2167
  //#endregion
1386
- export { b as DOMAIN_HEADER_PREFIX, v as EVENT_ABORT, h as EVENT_CANCEL, y as EVENT_ERROR, _ as EVENT_TURN_END, g as EVENT_TURN_START, x as ErrorCode, R as EventEmitter, u as HEADER_CANCEL_ALL, d as HEADER_CANCEL_CLIENT_ID, l as HEADER_CANCEL_OWN, c as HEADER_CANCEL_TURN_ID, p as HEADER_FORK_OF, a as HEADER_MSG_ID, f as HEADER_PARENT, s as HEADER_ROLE, n as HEADER_STATUS, t as HEADER_STREAM, r as HEADER_STREAM_ID, o as HEADER_TURN_CLIENT_ID, i as HEADER_TURN_ID, m as HEADER_TURN_REASON, z as LogLevel, j as buildTransportHeaders, B as consoleLogger, re as createClientTransport, oe as createDecoderCore, se as createEncoderCore, le as createLifecycleTracker, F as createServerTransport, S as errorInfoIs, ie as eventOutput, C as getHeaders, k as headerReader, A as headerWriter, V as makeLogger, T as mergeHeaders, O as stripUndefined };
2168
+ export { b as EVENT_CANCEL, w as EVENT_RUN_END, x as EVENT_RUN_START, T as ErrorCode, Y 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, ge as LogLevel, V as buildTransportHeaders, _e as consoleLogger, pe as createAgentSession, Pe as createClientSession, Re as createDecoderCore, Ie as createEncoderCore, Be as createLifecycleTracker, E as errorInfoIs, k as getCodecHeaders, O as getTransportHeaders, F as headerReader, I as headerWriter, ve as makeLogger, A as mergeHeaders, P as stripUndefined };
1387
2169
 
1388
2170
  //# sourceMappingURL=ably-ai-transport.js.map