@ably/ai-transport 0.2.0 → 0.3.0

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