omnix-chat 0.1.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 (176) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +21 -0
  3. package/README.md +360 -0
  4. package/dist/es-BoccmK_s.js +457 -0
  5. package/dist/es-BoccmK_s.js.map +1 -0
  6. package/dist/favicon.svg +1 -0
  7. package/dist/logo.svg +1 -0
  8. package/dist/omnix-chat.es.js +3197 -0
  9. package/dist/omnix-chat.es.js.map +1 -0
  10. package/dist/omnix-chat.umd.js +4 -0
  11. package/dist/omnix-chat.umd.js.map +1 -0
  12. package/dist/react.es.js +26062 -0
  13. package/dist/react.es.js.map +1 -0
  14. package/dist/react.umd.js +593 -0
  15. package/dist/react.umd.js.map +1 -0
  16. package/dist/src/chat/ChatRoot.d.ts +9 -0
  17. package/dist/src/chat/ChatRoot.d.ts.map +1 -0
  18. package/dist/src/chat/bridge/index.d.ts +2 -0
  19. package/dist/src/chat/bridge/index.d.ts.map +1 -0
  20. package/dist/src/chat/bridge/messageBridge.d.ts +8 -0
  21. package/dist/src/chat/bridge/messageBridge.d.ts.map +1 -0
  22. package/dist/src/chat/components/AIAssistantBubble.d.ts +13 -0
  23. package/dist/src/chat/components/AIAssistantBubble.d.ts.map +1 -0
  24. package/dist/src/chat/components/ErrorBoundary.d.ts +25 -0
  25. package/dist/src/chat/components/ErrorBoundary.d.ts.map +1 -0
  26. package/dist/src/chat/components/LauncherSlot.d.ts +8 -0
  27. package/dist/src/chat/components/LauncherSlot.d.ts.map +1 -0
  28. package/dist/src/chat/components/LoginForm.d.ts +7 -0
  29. package/dist/src/chat/components/LoginForm.d.ts.map +1 -0
  30. package/dist/src/chat/components/PanelHeaderTitle.d.ts +7 -0
  31. package/dist/src/chat/components/PanelHeaderTitle.d.ts.map +1 -0
  32. package/dist/src/chat/components/message/BlockExportActions.d.ts +7 -0
  33. package/dist/src/chat/components/message/BlockExportActions.d.ts.map +1 -0
  34. package/dist/src/chat/components/message/MessageBlockRenderer.d.ts +6 -0
  35. package/dist/src/chat/components/message/MessageBlockRenderer.d.ts.map +1 -0
  36. package/dist/src/chat/components/message/SafeMarkdownHtml.d.ts +11 -0
  37. package/dist/src/chat/components/message/SafeMarkdownHtml.d.ts.map +1 -0
  38. package/dist/src/chat/components/message/blockExport.d.ts +5 -0
  39. package/dist/src/chat/components/message/blockExport.d.ts.map +1 -0
  40. package/dist/src/chat/components/message/chartBlockUtils.d.ts +10 -0
  41. package/dist/src/chat/components/message/chartBlockUtils.d.ts.map +1 -0
  42. package/dist/src/chat/components/message/index.d.ts +4 -0
  43. package/dist/src/chat/components/message/index.d.ts.map +1 -0
  44. package/dist/src/chat/components/message/parseMessageBlocks.d.ts +15 -0
  45. package/dist/src/chat/components/message/parseMessageBlocks.d.ts.map +1 -0
  46. package/dist/src/chat/components/message/types.d.ts +89 -0
  47. package/dist/src/chat/components/message/types.d.ts.map +1 -0
  48. package/dist/src/chat/components/panel/AIAssistantPanel.d.ts +4 -0
  49. package/dist/src/chat/components/panel/AIAssistantPanel.d.ts.map +1 -0
  50. package/dist/src/chat/components/panel/AgentSkillBar.d.ts +17 -0
  51. package/dist/src/chat/components/panel/AgentSkillBar.d.ts.map +1 -0
  52. package/dist/src/chat/components/panel/BubbleAvatars.d.ts +7 -0
  53. package/dist/src/chat/components/panel/BubbleAvatars.d.ts.map +1 -0
  54. package/dist/src/chat/components/panel/ConversationSidebar.d.ts +23 -0
  55. package/dist/src/chat/components/panel/ConversationSidebar.d.ts.map +1 -0
  56. package/dist/src/chat/components/panel/DownFeedbackModal.d.ts +18 -0
  57. package/dist/src/chat/components/panel/DownFeedbackModal.d.ts.map +1 -0
  58. package/dist/src/chat/components/panel/MessageBody.d.ts +16 -0
  59. package/dist/src/chat/components/panel/MessageBody.d.ts.map +1 -0
  60. package/dist/src/chat/components/panel/MessageFeedbackFooter.d.ts +10 -0
  61. package/dist/src/chat/components/panel/MessageFeedbackFooter.d.ts.map +1 -0
  62. package/dist/src/chat/components/panel/MessageList.d.ts +13 -0
  63. package/dist/src/chat/components/panel/MessageList.d.ts.map +1 -0
  64. package/dist/src/chat/components/panel/PanelModals.d.ts +13 -0
  65. package/dist/src/chat/components/panel/PanelModals.d.ts.map +1 -0
  66. package/dist/src/chat/components/panel/PromptsSection.d.ts +11 -0
  67. package/dist/src/chat/components/panel/PromptsSection.d.ts.map +1 -0
  68. package/dist/src/chat/components/panel/constants.d.ts +83 -0
  69. package/dist/src/chat/components/panel/constants.d.ts.map +1 -0
  70. package/dist/src/chat/components/panel/index.d.ts +3 -0
  71. package/dist/src/chat/components/panel/index.d.ts.map +1 -0
  72. package/dist/src/chat/components/panel/types.d.ts +60 -0
  73. package/dist/src/chat/components/panel/types.d.ts.map +1 -0
  74. package/dist/src/chat/components/panel/useBubbleItems.d.ts +15 -0
  75. package/dist/src/chat/components/panel/useBubbleItems.d.ts.map +1 -0
  76. package/dist/src/chat/components/panel/useBubbleScroll.d.ts +21 -0
  77. package/dist/src/chat/components/panel/useBubbleScroll.d.ts.map +1 -0
  78. package/dist/src/chat/components/panel/useConversationSidebarScroll.d.ts +10 -0
  79. package/dist/src/chat/components/panel/useConversationSidebarScroll.d.ts.map +1 -0
  80. package/dist/src/chat/components/panel/utils.d.ts +25 -0
  81. package/dist/src/chat/components/panel/utils.d.ts.map +1 -0
  82. package/dist/src/chat/config/assistantPrompts.d.ts +9 -0
  83. package/dist/src/chat/config/assistantPrompts.d.ts.map +1 -0
  84. package/dist/src/chat/config/globalInteractionCopy.d.ts +19 -0
  85. package/dist/src/chat/config/globalInteractionCopy.d.ts.map +1 -0
  86. package/dist/src/chat/config/index.d.ts +2 -0
  87. package/dist/src/chat/config/index.d.ts.map +1 -0
  88. package/dist/src/chat/hooks/index.d.ts +4 -0
  89. package/dist/src/chat/hooks/index.d.ts.map +1 -0
  90. package/dist/src/chat/hooks/useClientState.d.ts +15 -0
  91. package/dist/src/chat/hooks/useClientState.d.ts.map +1 -0
  92. package/dist/src/chat/hooks/useDebouncedSessionPrepare.d.ts +9 -0
  93. package/dist/src/chat/hooks/useDebouncedSessionPrepare.d.ts.map +1 -0
  94. package/dist/src/chat/hooks/useLauncherPosition.d.ts +11 -0
  95. package/dist/src/chat/hooks/useLauncherPosition.d.ts.map +1 -0
  96. package/dist/src/chat/i18n.d.ts +11 -0
  97. package/dist/src/chat/i18n.d.ts.map +1 -0
  98. package/dist/src/chat/styles/host-styles.d.ts +10 -0
  99. package/dist/src/chat/styles/host-styles.d.ts.map +1 -0
  100. package/dist/src/chat/styles/inject.d.ts +4 -0
  101. package/dist/src/chat/styles/inject.d.ts.map +1 -0
  102. package/dist/src/chat/types.d.ts +56 -0
  103. package/dist/src/chat/types.d.ts.map +1 -0
  104. package/dist/src/chat/utils.d.ts +3 -0
  105. package/dist/src/chat/utils.d.ts.map +1 -0
  106. package/dist/src/core/api-envelope.d.ts +6 -0
  107. package/dist/src/core/api-envelope.d.ts.map +1 -0
  108. package/dist/src/core/auth-headers.d.ts +19 -0
  109. package/dist/src/core/auth-headers.d.ts.map +1 -0
  110. package/dist/src/core/auth-response.d.ts +9 -0
  111. package/dist/src/core/auth-response.d.ts.map +1 -0
  112. package/dist/src/core/auth-store.d.ts +23 -0
  113. package/dist/src/core/auth-store.d.ts.map +1 -0
  114. package/dist/src/core/auth-types.d.ts +26 -0
  115. package/dist/src/core/auth-types.d.ts.map +1 -0
  116. package/dist/src/core/auth.d.ts +25 -0
  117. package/dist/src/core/auth.d.ts.map +1 -0
  118. package/dist/src/core/chat-response.d.ts +66 -0
  119. package/dist/src/core/chat-response.d.ts.map +1 -0
  120. package/dist/src/core/chat-sse.d.ts +66 -0
  121. package/dist/src/core/chat-sse.d.ts.map +1 -0
  122. package/dist/src/core/errors.d.ts +16 -0
  123. package/dist/src/core/errors.d.ts.map +1 -0
  124. package/dist/src/core/events.d.ts +19 -0
  125. package/dist/src/core/events.d.ts.map +1 -0
  126. package/dist/src/core/feedback-utils.d.ts +9 -0
  127. package/dist/src/core/feedback-utils.d.ts.map +1 -0
  128. package/dist/src/core/http/client.d.ts +3 -0
  129. package/dist/src/core/http/client.d.ts.map +1 -0
  130. package/dist/src/core/http/errors.d.ts +6 -0
  131. package/dist/src/core/http/errors.d.ts.map +1 -0
  132. package/dist/src/core/http/index.d.ts +3 -0
  133. package/dist/src/core/http/index.d.ts.map +1 -0
  134. package/dist/src/core/http/sse.d.ts +5 -0
  135. package/dist/src/core/http/sse.d.ts.map +1 -0
  136. package/dist/src/core/http/types.d.ts +30 -0
  137. package/dist/src/core/http/types.d.ts.map +1 -0
  138. package/dist/src/core/instance.d.ts +135 -0
  139. package/dist/src/core/instance.d.ts.map +1 -0
  140. package/dist/src/core/message-blocks.d.ts +25 -0
  141. package/dist/src/core/message-blocks.d.ts.map +1 -0
  142. package/dist/src/core/resolve.d.ts +5 -0
  143. package/dist/src/core/resolve.d.ts.map +1 -0
  144. package/dist/src/core/services/agent.service.d.ts +18 -0
  145. package/dist/src/core/services/agent.service.d.ts.map +1 -0
  146. package/dist/src/core/services/auth.service.d.ts +14 -0
  147. package/dist/src/core/services/auth.service.d.ts.map +1 -0
  148. package/dist/src/core/services/chat.service.d.ts +28 -0
  149. package/dist/src/core/services/chat.service.d.ts.map +1 -0
  150. package/dist/src/core/services/feedback.service.d.ts +15 -0
  151. package/dist/src/core/services/feedback.service.d.ts.map +1 -0
  152. package/dist/src/core/services/index.d.ts +5 -0
  153. package/dist/src/core/services/index.d.ts.map +1 -0
  154. package/dist/src/index.d.ts +15 -0
  155. package/dist/src/index.d.ts.map +1 -0
  156. package/dist/src/react/AgentChat.d.ts +25 -0
  157. package/dist/src/react/AgentChat.d.ts.map +1 -0
  158. package/dist/src/react/AgentChatEmbedded.d.ts +12 -0
  159. package/dist/src/react/AgentChatEmbedded.d.ts.map +1 -0
  160. package/dist/src/react/AgentChatProvider.d.ts +15 -0
  161. package/dist/src/react/AgentChatProvider.d.ts.map +1 -0
  162. package/dist/src/react/context.d.ts +4 -0
  163. package/dist/src/react/context.d.ts.map +1 -0
  164. package/dist/src/react/index.d.ts +11 -0
  165. package/dist/src/react/index.d.ts.map +1 -0
  166. package/dist/src/react/useAgentChat.d.ts +36 -0
  167. package/dist/src/react/useAgentChat.d.ts.map +1 -0
  168. package/dist/src/types.d.ts +337 -0
  169. package/dist/src/types.d.ts.map +1 -0
  170. package/dist/src/utils/id.d.ts +7 -0
  171. package/dist/src/utils/id.d.ts.map +1 -0
  172. package/dist/src/utils/sdk-version.d.ts +9 -0
  173. package/dist/src/utils/sdk-version.d.ts.map +1 -0
  174. package/dist/xlsx-CXTDRHcz.js +12389 -0
  175. package/dist/xlsx-CXTDRHcz.js.map +1 -0
  176. package/package.json +115 -0
@@ -0,0 +1,3197 @@
1
+ import e from "react";
2
+ import { createParser as t } from "eventsource-parser";
3
+ //#region \0@oxc-project+runtime@0.127.0/helpers/typeof.js
4
+ function n(e) {
5
+ "@babel/helpers - typeof";
6
+ return n = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
7
+ return typeof e;
8
+ } : function(e) {
9
+ return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
10
+ }, n(e);
11
+ }
12
+ //#endregion
13
+ //#region \0@oxc-project+runtime@0.127.0/helpers/toPrimitive.js
14
+ function r(e, t) {
15
+ if (n(e) != "object" || !e) return e;
16
+ var r = e[Symbol.toPrimitive];
17
+ if (r !== void 0) {
18
+ var i = r.call(e, t || "default");
19
+ if (n(i) != "object") return i;
20
+ throw TypeError("@@toPrimitive must return a primitive value.");
21
+ }
22
+ return (t === "string" ? String : Number)(e);
23
+ }
24
+ //#endregion
25
+ //#region \0@oxc-project+runtime@0.127.0/helpers/toPropertyKey.js
26
+ function i(e) {
27
+ var t = r(e, "string");
28
+ return n(t) == "symbol" ? t : t + "";
29
+ }
30
+ //#endregion
31
+ //#region \0@oxc-project+runtime@0.127.0/helpers/defineProperty.js
32
+ function a(e, t, n) {
33
+ return (t = i(t)) in e ? Object.defineProperty(e, t, {
34
+ value: n,
35
+ enumerable: !0,
36
+ configurable: !0,
37
+ writable: !0
38
+ }) : e[t] = n, e;
39
+ }
40
+ //#endregion
41
+ //#region src/core/errors.ts
42
+ var o = class e extends Error {
43
+ constructor(t, n, r = {}) {
44
+ super(n), a(this, "code", void 0), a(this, "details", void 0), this.name = "AgentChatError", this.code = t, r.cause !== void 0 && (this.cause = r.cause), r.details !== void 0 && (this.details = r.details), typeof Object.setPrototypeOf == "function" && Object.setPrototypeOf(this, e.prototype);
45
+ }
46
+ }, s = "http://localhost:3030", c = "x-app-dsn";
47
+ function l(e) {
48
+ if (typeof e != "string" || e.trim() === "") throw new o("INVALID_DSN", "DSN must be a non-empty string", { details: { received: typeof e } });
49
+ return e.trim();
50
+ }
51
+ //#endregion
52
+ //#region src/core/auth-headers.ts
53
+ var u = "x-account-token", d = "Authorization", f = "X-App-Dsn";
54
+ function p(e, t) {
55
+ let n = { [c]: e.trim() };
56
+ return t?.trim() && (n[u] = m(t)), n;
57
+ }
58
+ function m(e) {
59
+ return e.trim().replace(/^Bearer\s+/i, "");
60
+ }
61
+ function ee(e) {
62
+ return `Bearer ${m(e)}`;
63
+ }
64
+ function te(e, t) {
65
+ e.setDefaultHeader(d, ee(t));
66
+ }
67
+ function ne(e) {
68
+ e.setDefaultHeader(d, void 0);
69
+ }
70
+ function re(e) {
71
+ return { [f]: e.trim() };
72
+ }
73
+ //#endregion
74
+ //#region src/core/auth-response.ts
75
+ function ie(e) {
76
+ return typeof e == "object" && !!e;
77
+ }
78
+ function h(e) {
79
+ return ie(e) ? ie(e.data) ? e.data : e : null;
80
+ }
81
+ function g(e) {
82
+ return typeof e == "string" && e.trim().length > 0 ? e.trim() : void 0;
83
+ }
84
+ function ae(e) {
85
+ if (!ie(e)) return;
86
+ let t = e.id, n = g(e.dsn), r = g(e.name);
87
+ if (!(typeof t != "number" || !n || !r)) return {
88
+ id: t,
89
+ dsn: n,
90
+ name: r
91
+ };
92
+ }
93
+ function oe(e) {
94
+ if (!ie(e)) return;
95
+ let t = e.id, n = g(e.email), r = g(e.username), i = g(e.userType), a = g(e.userRole);
96
+ if (!(typeof t != "number" || !n || !r || !i || !a)) return {
97
+ id: t,
98
+ employeeId: g(e.employeeId),
99
+ email: n,
100
+ username: r,
101
+ userType: i,
102
+ userRole: a,
103
+ mustChangePassword: typeof e.mustChangePassword == "boolean" ? e.mustChangePassword : void 0,
104
+ createdAt: g(e.createdAt)
105
+ };
106
+ }
107
+ function se(e) {
108
+ let t = h(e);
109
+ if (!t) return null;
110
+ let n = g(t.accessToken);
111
+ return {
112
+ ok: t.ok === !0 || t.ok !== !1 && n !== void 0,
113
+ accessToken: n,
114
+ appClient: ae(t.appClient),
115
+ user: oe(t.user),
116
+ accountTokenBound: typeof t.accountTokenBound == "boolean" ? t.accountTokenBound : void 0
117
+ };
118
+ }
119
+ //#endregion
120
+ //#region src/core/chat-response.ts
121
+ function _(e) {
122
+ return typeof e == "object" && !!e;
123
+ }
124
+ function v(e) {
125
+ return typeof e == "string" && e.trim().length > 0 ? e.trim() : void 0;
126
+ }
127
+ function ce(e) {
128
+ if (!_(e)) return null;
129
+ let t = v(e.sessionId) ?? v(e.id) ?? (typeof e.sessionId == "number" ? String(e.sessionId) : void 0) ?? (typeof e.id == "number" ? String(e.id) : void 0);
130
+ if (!t) return null;
131
+ let n = e.updatedAt ?? e.updated_at ?? e.lastMessageAt, r;
132
+ if (typeof n == "number") r = n;
133
+ else if (n !== void 0) {
134
+ let e = new Date(n).getTime();
135
+ r = Number.isFinite(e) ? e : void 0;
136
+ }
137
+ return {
138
+ sessionId: t,
139
+ title: v(e.title) ?? v(e.name),
140
+ preview: v(e.preview) ?? v(e.lastMessage) ?? v(e.summary),
141
+ updatedAt: r
142
+ };
143
+ }
144
+ function le(e) {
145
+ if (Array.isArray(e)) return e;
146
+ if (!_(e)) return [];
147
+ if (Array.isArray(e.data)) return e.data;
148
+ if (_(e.data)) for (let t of [
149
+ "sessions",
150
+ "agents",
151
+ "skills",
152
+ "list",
153
+ "items",
154
+ "records"
155
+ ]) {
156
+ let n = e.data[t];
157
+ if (Array.isArray(n)) return n;
158
+ }
159
+ for (let t of [
160
+ "sessions",
161
+ "agents",
162
+ "skills",
163
+ "list",
164
+ "items",
165
+ "records"
166
+ ]) {
167
+ let n = e[t];
168
+ if (Array.isArray(n)) return n;
169
+ }
170
+ return [];
171
+ }
172
+ function ue(e) {
173
+ return le(e).map((e) => ce(e)).filter((e) => e !== null);
174
+ }
175
+ function y(e) {
176
+ if (typeof e == "number" && Number.isFinite(e)) return e;
177
+ if (typeof e == "string" && e.trim().length > 0) {
178
+ let t = Number(e);
179
+ return Number.isFinite(t) ? t : void 0;
180
+ }
181
+ }
182
+ function b(e) {
183
+ if (typeof e == "boolean") return e;
184
+ }
185
+ function de(e) {
186
+ return _(e) ? _(e.data) ? e.data : e : null;
187
+ }
188
+ function fe(e, t, n) {
189
+ let r = ue(e), i = de(e), a = y(i?.page) ?? y(i?.current) ?? t, o = y(i?.size) ?? y(i?.pageSize) ?? n, s = y(i?.total) ?? y(i?.totalCount), c = b(i?.hasMore) ?? b(i?.hasNext) ?? (s === void 0 ? r.length >= n : a * o < s);
190
+ return r.length < n && (c = !1), {
191
+ sessions: r,
192
+ page: a,
193
+ size: o,
194
+ total: s,
195
+ hasMore: c
196
+ };
197
+ }
198
+ function pe(e) {
199
+ let t = e.messages;
200
+ if (Array.isArray(t)) return { messages: t };
201
+ if (_(t)) {
202
+ let e = Array.isArray(t.items) ? t.items : Array.isArray(t.list) ? t.list : Array.isArray(t.records) ? t.records : [], n = y(t.page) ?? y(t.current), r = y(t.pageSize) ?? y(t.size), i = y(t.total) ?? y(t.totalCount), a = y(t.totalPages), o = b(t.hasMore) ?? b(t.hasNext);
203
+ return o === void 0 && n !== void 0 && a !== void 0 && (o = n < a), o === void 0 && n !== void 0 && r !== void 0 && i !== void 0 && (o = n * r < i), {
204
+ messages: e,
205
+ page: n,
206
+ size: r,
207
+ total: i,
208
+ totalPages: a,
209
+ hasMore: o
210
+ };
211
+ }
212
+ for (let t of [
213
+ "list",
214
+ "items",
215
+ "records"
216
+ ]) {
217
+ let n = e[t];
218
+ if (Array.isArray(n)) return { messages: n };
219
+ }
220
+ return { messages: [] };
221
+ }
222
+ function me(e) {
223
+ return v(e.sessionId) ?? v(e.id) ?? (typeof e.sessionId == "number" ? String(e.sessionId) : void 0);
224
+ }
225
+ function he(e, t, n, r) {
226
+ let i = h(e) ?? (_(e) ? e : null);
227
+ if (!i) return null;
228
+ let a = me(i) ?? t.trim();
229
+ if (!a) return null;
230
+ let o = pe(i), s = o.messages, c = de(e), l = o.page ?? y(c?.page) ?? y(c?.current) ?? n, u = o.size ?? y(c?.size) ?? y(c?.pageSize) ?? r, d = o.total ?? y(c?.total) ?? y(c?.totalCount), f = o.hasMore ?? b(c?.hasMore) ?? b(c?.hasNext);
231
+ return f === void 0 && o.totalPages !== void 0 && (f = l < o.totalPages), f === void 0 && d !== void 0 && (f = l * u < d), f === void 0 && (f = s.length >= r), s.length < r && (f = !1), {
232
+ sessionId: a,
233
+ messages: s,
234
+ page: l,
235
+ size: u,
236
+ total: d,
237
+ hasMore: f
238
+ };
239
+ }
240
+ function ge(e) {
241
+ let t = h(e) ?? (_(e) ? e : null);
242
+ if (!t) return null;
243
+ let n = v(t.sessionId) ?? v(t.id) ?? (typeof t.sessionId == "number" ? String(t.sessionId) : void 0);
244
+ return n ? { sessionId: n } : null;
245
+ }
246
+ function _e(e) {
247
+ let t = h(e) ?? (_(e) ? e : null);
248
+ if (!t) return null;
249
+ let n = t.id;
250
+ return n == null || typeof n != "string" && typeof n != "number" ? null : {
251
+ id: n,
252
+ role: v(t.role) ?? "user",
253
+ content: typeof t.content == "string" ? t.content : t.content == null ? null : String(t.content),
254
+ createdAt: t.createdAt ?? t.created_at ?? Date.now()
255
+ };
256
+ }
257
+ function ve(e, ...t) {
258
+ for (let n of t) {
259
+ let t = e[n];
260
+ if (typeof t == "number" && Number.isFinite(t)) return String(t);
261
+ let r = v(t);
262
+ if (r) return r;
263
+ }
264
+ }
265
+ function ye(e) {
266
+ if (!_(e)) return null;
267
+ let t = ve(e, "id", "agentId"), n = v(e.name) ?? v(e.title) ?? v(e.label);
268
+ return !t || !n ? null : {
269
+ id: t,
270
+ name: n,
271
+ description: v(e.description) ?? v(e.desc) ?? null
272
+ };
273
+ }
274
+ function be(e) {
275
+ if (!_(e)) return null;
276
+ let t = ve(e, "id", "skillId"), n = v(e.name) ?? v(e.title) ?? v(e.label);
277
+ if (!t || !n) return null;
278
+ let r = ve(e, "agentId", "agent_id"), i = v(e.riskLevel), a = i === "L1" || i === "L2" || i === "L3" ? i : void 0, o = Array.isArray(e.toolIds) ? e.toolIds.filter((e) => typeof e == "number") : void 0;
279
+ return {
280
+ id: t,
281
+ name: n,
282
+ description: v(e.description) ?? v(e.desc) ?? null,
283
+ agentId: r,
284
+ capabilityKey: v(e.capabilityKey) ?? null,
285
+ riskLevel: a,
286
+ requiresWriteConfirmation: typeof e.requiresWriteConfirmation == "boolean" ? e.requiresWriteConfirmation : void 0,
287
+ toolIds: o
288
+ };
289
+ }
290
+ function xe(e) {
291
+ return le(e).map((e) => ye(e)).filter((e) => e !== null);
292
+ }
293
+ function Se(e) {
294
+ return Array.isArray(e) ? e.filter((e) => typeof e == "string" && e.trim().length > 0) : [];
295
+ }
296
+ function Ce(e) {
297
+ if (!_(e)) return null;
298
+ let t = v(e.key), n = v(e.label);
299
+ return !t || !n ? null : {
300
+ key: t,
301
+ label: n
302
+ };
303
+ }
304
+ function we(e) {
305
+ return _(e) ? { items: (Array.isArray(e.items) ? e.items : []).map((e) => Ce(e)).filter((e) => e !== null) } : { items: [] };
306
+ }
307
+ function Te(e) {
308
+ if (!_(e)) throw Error("Invalid message feedback payload");
309
+ let t = y(e.messageId), n = e.rating === "up" || e.rating === "down" ? e.rating : null, r = v(e.createdAt), i = v(e.updatedAt);
310
+ if (t === void 0 || !n || !r || !i) throw Error("Invalid message feedback payload");
311
+ return {
312
+ messageId: t,
313
+ rating: n,
314
+ reasonTags: Se(e.reasonTags),
315
+ comment: typeof e.comment == "string" ? e.comment : e.comment == null ? null : String(e.comment),
316
+ createdAt: r,
317
+ updatedAt: i
318
+ };
319
+ }
320
+ function Ee(e) {
321
+ if (!_(e)) return { items: [] };
322
+ let t = Array.isArray(e.items) ? e.items : [], n = [];
323
+ for (let e of t) try {
324
+ n.push(Te(e));
325
+ } catch {}
326
+ return { items: n };
327
+ }
328
+ function De(e, t) {
329
+ let n = t?.trim().toLowerCase();
330
+ return le(e).map((e) => be(e)).filter((e) => e !== null).filter((e) => !n || !e.agentId ? !0 : e.agentId.trim().toLowerCase() === n);
331
+ }
332
+ //#endregion
333
+ //#region node_modules/.pnpm/zustand@5.0.5_@types+react@19.2.14_react@19.2.5/node_modules/zustand/esm/vanilla.mjs
334
+ var Oe = (e) => {
335
+ let t, n = /* @__PURE__ */ new Set(), r = (e, r) => {
336
+ let i = typeof e == "function" ? e(t) : e;
337
+ if (!Object.is(i, t)) {
338
+ let e = t;
339
+ t = r ?? (typeof i != "object" || !i) ? i : Object.assign({}, t, i), n.forEach((n) => n(t, e));
340
+ }
341
+ }, i = () => t, a = {
342
+ setState: r,
343
+ getState: i,
344
+ getInitialState: () => o,
345
+ subscribe: (e) => (n.add(e), () => n.delete(e))
346
+ }, o = t = e(r, i, a);
347
+ return a;
348
+ }, ke = (e) => e ? Oe(e) : Oe, Ae = (e) => e;
349
+ function je(t, n = Ae) {
350
+ let r = e.useSyncExternalStore(t.subscribe, () => n(t.getState()), () => n(t.getInitialState()));
351
+ return e.useDebugValue(r), r;
352
+ }
353
+ var Me = (e) => {
354
+ let t = ke(e), n = (e) => je(t, e);
355
+ return Object.assign(n, t), n;
356
+ }, Ne = (e) => e ? Me(e) : Me;
357
+ //#endregion
358
+ //#region node_modules/.pnpm/zustand@5.0.5_@types+react@19.2.14_react@19.2.5/node_modules/zustand/esm/middleware.mjs
359
+ function Pe(e, t) {
360
+ let n;
361
+ try {
362
+ n = e();
363
+ } catch {
364
+ return;
365
+ }
366
+ return {
367
+ getItem: (e) => {
368
+ let r = (e) => e === null ? null : JSON.parse(e, t?.reviver), i = n.getItem(e) ?? null;
369
+ return i instanceof Promise ? i.then(r) : r(i);
370
+ },
371
+ setItem: (e, r) => n.setItem(e, JSON.stringify(r, t?.replacer)),
372
+ removeItem: (e) => n.removeItem(e)
373
+ };
374
+ }
375
+ var Fe = (e) => (t) => {
376
+ try {
377
+ let n = e(t);
378
+ return n instanceof Promise ? n : {
379
+ then(e) {
380
+ return Fe(e)(n);
381
+ },
382
+ catch(e) {
383
+ return this;
384
+ }
385
+ };
386
+ } catch (e) {
387
+ return {
388
+ then(e) {
389
+ return this;
390
+ },
391
+ catch(t) {
392
+ return Fe(t)(e);
393
+ }
394
+ };
395
+ }
396
+ }, Ie = (e, t) => (n, r, i) => {
397
+ let a = {
398
+ storage: Pe(() => localStorage),
399
+ partialize: (e) => e,
400
+ version: 0,
401
+ merge: (e, t) => ({
402
+ ...t,
403
+ ...e
404
+ }),
405
+ ...t
406
+ }, o = !1, s = /* @__PURE__ */ new Set(), c = /* @__PURE__ */ new Set(), l = a.storage;
407
+ if (!l) return e((...e) => {
408
+ console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`), n(...e);
409
+ }, r, i);
410
+ let u = () => {
411
+ let e = a.partialize({ ...r() });
412
+ return l.setItem(a.name, {
413
+ state: e,
414
+ version: a.version
415
+ });
416
+ }, d = i.setState;
417
+ i.setState = (e, t) => {
418
+ d(e, t), u();
419
+ };
420
+ let f = e((...e) => {
421
+ n(...e), u();
422
+ }, r, i);
423
+ i.getInitialState = () => f;
424
+ let p, m = () => {
425
+ if (!l) return;
426
+ o = !1, s.forEach((e) => e(r() ?? f));
427
+ let e = a.onRehydrateStorage?.call(a, r() ?? f) || void 0;
428
+ return Fe(l.getItem.bind(l))(a.name).then((e) => {
429
+ if (e) if (typeof e.version == "number" && e.version !== a.version) {
430
+ if (a.migrate) {
431
+ let t = a.migrate(e.state, e.version);
432
+ return t instanceof Promise ? t.then((e) => [!0, e]) : [!0, t];
433
+ }
434
+ console.error("State loaded from storage couldn't be migrated since no migrate function was provided");
435
+ } else return [!1, e.state];
436
+ return [!1, void 0];
437
+ }).then((e) => {
438
+ let [t, i] = e;
439
+ if (p = a.merge(i, r() ?? f), n(p, !0), t) return u();
440
+ }).then(() => {
441
+ e?.(p, void 0), p = r(), o = !0, c.forEach((e) => e(p));
442
+ }).catch((t) => {
443
+ e?.(void 0, t);
444
+ });
445
+ };
446
+ return i.persist = {
447
+ setOptions: (e) => {
448
+ a = {
449
+ ...a,
450
+ ...e
451
+ }, e.storage && (l = e.storage);
452
+ },
453
+ clearStorage: () => {
454
+ l?.removeItem(a.name);
455
+ },
456
+ getOptions: () => a,
457
+ rehydrate: () => m(),
458
+ hasHydrated: () => o,
459
+ onHydrate: (e) => (s.add(e), () => {
460
+ s.delete(e);
461
+ }),
462
+ onFinishHydration: (e) => (c.add(e), () => {
463
+ c.delete(e);
464
+ })
465
+ }, a.skipHydration || m(), p || f;
466
+ }, Le = {
467
+ dsn: null,
468
+ accessToken: null,
469
+ user: null,
470
+ appClient: null,
471
+ accountTokenBound: null
472
+ }, x = Ne()(Ie((e, t) => ({
473
+ ...Le,
474
+ setAuth(t, n) {
475
+ e({
476
+ dsn: t,
477
+ accessToken: n.accessToken ?? null,
478
+ user: n.user ?? null,
479
+ appClient: n.appClient ?? null,
480
+ accountTokenBound: n.accountTokenBound ?? null
481
+ });
482
+ },
483
+ clearAuth() {
484
+ e({ ...Le });
485
+ },
486
+ getAccessTokenForDsn(e) {
487
+ let n = t();
488
+ return n.dsn === e && n.accessToken ? n.accessToken : null;
489
+ }
490
+ }), { name: "agent-chat-auth" })), Re = class {
491
+ constructor() {
492
+ a(this, "handlers", /* @__PURE__ */ new Map());
493
+ }
494
+ on(e, t) {
495
+ let n = this.handlers.get(e);
496
+ return n || (n = /* @__PURE__ */ new Set(), this.handlers.set(e, n)), n.add(t), () => this.off(e, t);
497
+ }
498
+ off(e, t) {
499
+ let n = this.handlers.get(e);
500
+ n && (n.delete(t), n.size === 0 && this.handlers.delete(e));
501
+ }
502
+ emit(e, t) {
503
+ let n = this.handlers.get(e);
504
+ if (!n || n.size === 0) return;
505
+ let r = Array.from(n);
506
+ for (let e of r) try {
507
+ e(t);
508
+ } catch (e) {
509
+ typeof console < "u" && typeof console.error == "function" && console.error("[agent-chat] event handler threw:", e);
510
+ }
511
+ }
512
+ listenerCount(e) {
513
+ return this.handlers.get(e)?.size ?? 0;
514
+ }
515
+ clear() {
516
+ this.handlers.clear();
517
+ }
518
+ };
519
+ //#endregion
520
+ //#region src/core/chat-sse.ts
521
+ function S(e) {
522
+ try {
523
+ return JSON.parse(e);
524
+ } catch {
525
+ return null;
526
+ }
527
+ }
528
+ function ze(e) {
529
+ let t = S(e);
530
+ if (!t) return;
531
+ let n = t.messageId ?? t.message_id ?? t.outputMessageId ?? t.output_message_id ?? t.id;
532
+ if (n != null) return String(n);
533
+ }
534
+ function Be(e) {
535
+ let t = S(e);
536
+ return t?.content == null ? e.trim() : String(t.content);
537
+ }
538
+ function Ve(e) {
539
+ let t = S(e);
540
+ return {
541
+ message: t?.message?.trim() || e.trim() || "Stream failed",
542
+ code: typeof t?.code == "string" ? t.code : void 0
543
+ };
544
+ }
545
+ var He = new Set([
546
+ "delta",
547
+ "stream",
548
+ "chunk",
549
+ "token",
550
+ "append",
551
+ "message.delta"
552
+ ]);
553
+ function Ue(e) {
554
+ return e ? e === "full" || e === "replace" ? "replace" : (He.has(e), "append") : "append";
555
+ }
556
+ function We(e) {
557
+ let t = ze(e), n = S(e);
558
+ if (n && typeof n == "object") {
559
+ let e = typeof n.content == "string" ? n.content : typeof n.text == "string" ? n.text : "";
560
+ return e ? {
561
+ type: "think",
562
+ text: e,
563
+ mode: Ue(typeof n.mode == "string" ? n.mode : void 0),
564
+ messageId: t
565
+ } : { type: "noop" };
566
+ }
567
+ let r = Be(e);
568
+ return r ? {
569
+ type: "think",
570
+ text: r,
571
+ mode: "append",
572
+ messageId: t
573
+ } : { type: "noop" };
574
+ }
575
+ function Ge(e) {
576
+ let t = e.blocks;
577
+ if (Array.isArray(t) && t.length > 0) {
578
+ let e = t.map((e) => {
579
+ if (!e || typeof e != "object") return "";
580
+ let t = e.content;
581
+ return typeof t == "string" ? t : "";
582
+ }).join("");
583
+ if (e) return e;
584
+ }
585
+ for (let t of [
586
+ "output",
587
+ "content",
588
+ "text",
589
+ "delta",
590
+ "token"
591
+ ]) {
592
+ let n = e[t];
593
+ if (typeof n == "string" && n.length > 0) return n;
594
+ }
595
+ return "";
596
+ }
597
+ function Ke(e) {
598
+ let t = ze(e), n = S(e)?.content ?? e, r = typeof n == "string" ? S(n) : n;
599
+ if (r && typeof r == "object") {
600
+ let e = r, n = typeof e.source == "string" ? e.source : void 0, i = typeof e.action == "string" ? e.action : void 0, a = typeof e.stream?.mode == "string" ? String(e.stream.mode) : void 0, o = Ge(e), s = (i ? He.has(i) : !1) || (a ? He.has(a) : !1);
601
+ if (n === "agent-run") {
602
+ if (i === "final") return o.trim() ? {
603
+ type: "result",
604
+ text: o,
605
+ mode: "replace",
606
+ messageId: t
607
+ } : { type: "noop" };
608
+ if (s) return o ? {
609
+ type: "result",
610
+ text: o,
611
+ mode: "append",
612
+ messageId: t
613
+ } : { type: "noop" };
614
+ if (o) return {
615
+ type: "result",
616
+ text: o,
617
+ mode: "append",
618
+ messageId: t
619
+ };
620
+ }
621
+ if ((n === "message" || Ye(e)) && o || o) return {
622
+ type: "result",
623
+ text: o,
624
+ mode: "append",
625
+ messageId: t
626
+ };
627
+ }
628
+ let i = Be(e);
629
+ return i ? {
630
+ type: "result",
631
+ text: i,
632
+ mode: "append",
633
+ messageId: t
634
+ } : { type: "noop" };
635
+ }
636
+ function qe(e) {
637
+ let t = typeof e.action == "string" ? e.action : void 0, n = typeof e.message == "string" ? e.message.trim() : "", r = typeof e.code == "string" ? e.code : void 0, i = typeof e.runId == "number" ? e.runId : void 0, a = typeof e.turnId == "number" ? e.turnId : void 0;
638
+ return t === "confirmation_required" && i != null && n ? {
639
+ type: "write-confirmation-required",
640
+ runId: i,
641
+ turnId: a,
642
+ message: n,
643
+ code: r
644
+ } : t === "write_confirmation_cancelled" && n ? {
645
+ type: "write-confirmation-cancelled",
646
+ runId: i,
647
+ turnId: a,
648
+ message: n,
649
+ code: r
650
+ } : null;
651
+ }
652
+ function Je(e) {
653
+ let t = ze(e), n = S(e);
654
+ if (!n) return Ke(e);
655
+ if (n.source === "message") return { type: "noop" };
656
+ let r = qe(n);
657
+ if (r) return r;
658
+ let i = n.action, a = i === "patch" ? "patch" : i === "stream" ? "stream" : void 0;
659
+ if (!a) return Ke(e);
660
+ let o = typeof n.runId == "number" ? n.runId : void 0, s = typeof n.turnId == "number" ? n.turnId : void 0, c = n.stream ?? void 0, l = c?.mode;
661
+ return {
662
+ type: "message-blocks",
663
+ action: a,
664
+ runId: o,
665
+ turnId: s,
666
+ streamMode: l === "delta" || l === "full" || l === "patch" ? l : void 0,
667
+ seq: typeof c?.seq == "number" ? c.seq : void 0,
668
+ blocks: Array.isArray(n.blocks) ? n.blocks.filter((e) => !!e && typeof e == "object" && typeof e.type == "string") : void 0,
669
+ patches: Array.isArray(n.patches) ? n.patches.map((e) => {
670
+ if (!e || typeof e != "object") return null;
671
+ let t = e;
672
+ return typeof t.replaceId != "string" || !t.block || typeof t.block != "object" || typeof t.block.type != "string" ? null : {
673
+ replaceId: t.replaceId,
674
+ block: t.block
675
+ };
676
+ }).filter((e) => e != null) : void 0,
677
+ messageId: t
678
+ };
679
+ }
680
+ function Ye(e) {
681
+ let t = e.type;
682
+ return typeof t == "string" ? t === "message" || t === "result" : !1;
683
+ }
684
+ function Xe(e, t) {
685
+ let n = e.trim() || "message", r = ze(t);
686
+ switch (n) {
687
+ case "think": return We(t);
688
+ case "message":
689
+ case "result": {
690
+ let e = n === "message" ? Je(t) : Ke(t);
691
+ return e.type === "result" && !e.messageId && r ? {
692
+ ...e,
693
+ messageId: r
694
+ } : e;
695
+ }
696
+ case "message.delta": {
697
+ let e = Be(t);
698
+ return e ? {
699
+ type: "result",
700
+ text: e,
701
+ mode: "append",
702
+ messageId: r
703
+ } : { type: "noop" };
704
+ }
705
+ case "complete": {
706
+ let e = S(t);
707
+ return e && (e.content != null || e.id != null || e.role != null) ? {
708
+ type: "complete",
709
+ serverMessage: e,
710
+ messageId: e.id == null ? r : String(e.id)
711
+ } : {
712
+ type: "complete",
713
+ messageId: r
714
+ };
715
+ }
716
+ case "error": {
717
+ let e = Ve(t);
718
+ return {
719
+ type: "error",
720
+ message: e.message,
721
+ code: e.code
722
+ };
723
+ }
724
+ case "message.done": {
725
+ let e = S(t);
726
+ return {
727
+ type: "complete",
728
+ serverMessage: e ?? void 0,
729
+ messageId: e?.id == null ? r : String(e.id)
730
+ };
731
+ }
732
+ default: return { type: "noop" };
733
+ }
734
+ }
735
+ //#endregion
736
+ //#region node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/KyError.js
737
+ var Ze = class extends Error {
738
+ constructor(...e) {
739
+ super(...e), a(this, "name", "KyError");
740
+ }
741
+ get isKyError() {
742
+ return !0;
743
+ }
744
+ }, Qe = class extends Ze {
745
+ constructor(e, t, n) {
746
+ let r = `${e.status || e.status === 0 ? e.status : ""} ${e.statusText ?? ""}`.trim(), i = r ? `status code ${r}` : "an unknown error";
747
+ super(`Request failed with ${i}: ${t.method} ${t.url}`), a(this, "name", "HTTPError"), a(this, "response", void 0), a(this, "request", void 0), a(this, "options", void 0), a(this, "data", void 0), this.response = e, this.request = t, this.options = n;
748
+ }
749
+ }, $e = class extends Ze {
750
+ constructor(e, t) {
751
+ super(`Request failed due to a network error: ${e.method} ${e.url}`, t), a(this, "name", "NetworkError"), a(this, "request", void 0), this.request = e;
752
+ }
753
+ }, et = class extends Error {
754
+ constructor(e) {
755
+ let t = "Non-error value was thrown";
756
+ try {
757
+ typeof e == "string" ? t = e : e && typeof e == "object" && "message" in e && typeof e.message == "string" && (t = e.message);
758
+ } catch {}
759
+ super(t), a(this, "name", "NonError"), a(this, "value", void 0), this.value = e;
760
+ }
761
+ }, C = class extends Ze {
762
+ constructor(e) {
763
+ let t = e?.cause ? e.cause instanceof Error ? e.cause : new et(e.cause) : void 0;
764
+ super(e?.code ? `Forced retry: ${e.code}` : "Forced retry", t ? { cause: t } : void 0), a(this, "name", "ForceRetryError"), a(this, "customDelay", void 0), a(this, "code", void 0), a(this, "customRequest", void 0), this.customDelay = e?.delay, this.code = e?.code, this.customRequest = e?.request;
765
+ }
766
+ }, tt = class extends Error {
767
+ constructor(e) {
768
+ super("Response schema validation failed"), a(this, "name", "SchemaValidationError"), a(this, "issues", void 0), this.issues = e;
769
+ }
770
+ }, w = class extends Ze {
771
+ constructor(e) {
772
+ super(`Request timed out: ${e.method} ${e.url}`), a(this, "name", "TimeoutError"), a(this, "request", void 0), this.request = e;
773
+ }
774
+ }, nt = (() => {
775
+ let e = !1, t = !1, n = typeof globalThis.ReadableStream == "function", r = typeof globalThis.Request == "function";
776
+ if (n && r) try {
777
+ t = new globalThis.Request("https://empty.invalid", {
778
+ body: new globalThis.ReadableStream(),
779
+ method: "POST",
780
+ get duplex() {
781
+ return e = !0, "half";
782
+ }
783
+ }).headers.has("Content-Type");
784
+ } catch (e) {
785
+ if (e instanceof Error && e.message === "unsupported BodyInit type") return !1;
786
+ throw e;
787
+ }
788
+ return e && !t;
789
+ })(), rt = typeof globalThis.AbortController == "function", it = typeof globalThis.AbortSignal == "function" && typeof globalThis.AbortSignal.any == "function", at = typeof globalThis.ReadableStream == "function", ot = typeof globalThis.FormData == "function", st = [
790
+ "get",
791
+ "post",
792
+ "put",
793
+ "patch",
794
+ "head",
795
+ "delete"
796
+ ], ct = {
797
+ json: "application/json",
798
+ text: "text/*",
799
+ formData: "multipart/form-data",
800
+ arrayBuffer: "*/*",
801
+ blob: "*/*",
802
+ bytes: "*/*"
803
+ }, lt = 2147483647, ut = Symbol("stop"), dt = class {
804
+ constructor(e) {
805
+ a(this, "options", void 0), this.options = e;
806
+ }
807
+ }, ft = (e) => new dt(e), pt = {
808
+ json: !0,
809
+ parseJson: !0,
810
+ stringifyJson: !0,
811
+ searchParams: !0,
812
+ baseUrl: !0,
813
+ prefix: !0,
814
+ retry: !0,
815
+ timeout: !0,
816
+ totalTimeout: !0,
817
+ hooks: !0,
818
+ throwHttpErrors: !0,
819
+ onDownloadProgress: !0,
820
+ onUploadProgress: !0,
821
+ fetch: !0,
822
+ context: !0
823
+ }, mt = {
824
+ method: !0,
825
+ headers: !0,
826
+ body: !0,
827
+ mode: !0,
828
+ credentials: !0,
829
+ cache: !0,
830
+ redirect: !0,
831
+ referrer: !0,
832
+ referrerPolicy: !0,
833
+ integrity: !0,
834
+ keepalive: !0,
835
+ signal: !0,
836
+ window: !0,
837
+ duplex: !0
838
+ }, T = new TextEncoder(), ht = (e) => {
839
+ if (!e) return 0;
840
+ if (e instanceof FormData) {
841
+ let t = 0;
842
+ for (let [n, r] of e) t += 40, t += T.encode(`Content-Disposition: form-data; name="${n}"`).byteLength, t += typeof r == "string" ? T.encode(r).byteLength : r.size;
843
+ return t;
844
+ }
845
+ return e instanceof Blob ? e.size : e instanceof ArrayBuffer || ArrayBuffer.isView(e) ? e.byteLength : typeof e == "string" ? T.encode(e).byteLength : e instanceof URLSearchParams ? T.encode(e.toString()).byteLength : 0;
846
+ }, gt = (e, t, n) => {
847
+ let r, i = 0;
848
+ return e.pipeThrough(new TransformStream({
849
+ transform(e, a) {
850
+ if (a.enqueue(e), r) {
851
+ i += r.byteLength;
852
+ let e = t === 0 ? 0 : i / t;
853
+ e >= 1 && (e = 1 - 2 ** -52), n?.({
854
+ percent: e,
855
+ totalBytes: Math.max(t, i),
856
+ transferredBytes: i
857
+ }, r);
858
+ }
859
+ r = e;
860
+ },
861
+ flush() {
862
+ r && (i += r.byteLength, n?.({
863
+ percent: 1,
864
+ totalBytes: Math.max(t, i),
865
+ transferredBytes: i
866
+ }, r));
867
+ }
868
+ }));
869
+ }, _t = (e, t) => {
870
+ if (!e.body) return e;
871
+ let n = {
872
+ status: e.status,
873
+ statusText: e.statusText,
874
+ headers: e.headers
875
+ };
876
+ if (e.status === 204) return new Response(null, n);
877
+ let r = Math.max(0, Number(e.headers.get("content-length")) || 0);
878
+ return new Response(gt(e.body, r, t), n);
879
+ }, vt = (e, t, n) => {
880
+ if (!e.body) return e;
881
+ let r = ht(n ?? e.body);
882
+ return new Request(e, {
883
+ duplex: "half",
884
+ body: gt(e.body, r, t)
885
+ });
886
+ }, E = (e) => typeof e == "object" && !!e, yt = Symbol("replaceOption"), bt = (e) => E(e) && e[yt] === !0 ? {
887
+ isReplace: !0,
888
+ value: e.value
889
+ } : {
890
+ isReplace: !1,
891
+ value: e
892
+ }, xt = (...e) => {
893
+ for (let t of e) if ((!E(t) || Array.isArray(t)) && t !== void 0) throw TypeError("The `options` argument must be an object");
894
+ return Ot({}, ...e);
895
+ }, St = (e = {}, t = {}) => {
896
+ let n = new globalThis.Headers(e), r = t instanceof globalThis.Headers, i = new globalThis.Headers(t);
897
+ for (let [e, t] of i.entries()) r && t === "undefined" || t === void 0 ? n.delete(e) : n.set(e, t);
898
+ return n;
899
+ }, Ct = (e) => {
900
+ if (!E(e) || Array.isArray(e)) return !1;
901
+ let t = Object.getPrototypeOf(e);
902
+ return t === Object.prototype || t === null;
903
+ }, D = (e) => {
904
+ if (e instanceof URLSearchParams) {
905
+ let t = new URLSearchParams(e), n = e[k];
906
+ return n && (t[k] = new Set(n)), t;
907
+ }
908
+ return e instanceof globalThis.Headers ? new globalThis.Headers(e) : Array.isArray(e) ? [...e] : Ct(e) ? { ...e } : e;
909
+ }, wt = (e) => Object.fromEntries(Object.entries(e).filter((e) => e[1] !== void 0)), Tt = (e, t) => Ct(e) && Ct(t) ? wt({
910
+ ...e,
911
+ ...t
912
+ }) : St(e, t);
913
+ function O(e, t, n) {
914
+ return Object.hasOwn(t, n) && t[n] === void 0 ? [] : Ot(e[n] ?? [], t[n] ?? []);
915
+ }
916
+ var Et = (e = {}, t = {}) => ({
917
+ init: O(e, t, "init"),
918
+ beforeRequest: O(e, t, "beforeRequest"),
919
+ beforeRetry: O(e, t, "beforeRetry"),
920
+ beforeError: O(e, t, "beforeError"),
921
+ afterResponse: O(e, t, "afterResponse")
922
+ }), k = Symbol("deletedParameters"), Dt = (e, t) => {
923
+ let n = new URLSearchParams(), r = /* @__PURE__ */ new Set();
924
+ for (let i of [e, t]) if (i !== void 0) if (i instanceof URLSearchParams) {
925
+ for (let [e, t] of i.entries()) n.append(e, t), r.delete(e);
926
+ let e = i[k];
927
+ if (e) for (let t of e) n.delete(t), r.add(t);
928
+ } else if (Array.isArray(i)) for (let e of i) {
929
+ if (!Array.isArray(e) || e.length !== 2) throw TypeError("Array search parameters must be provided in [[key, value], ...] format");
930
+ n.append(String(e[0]), String(e[1])), r.delete(String(e[0]));
931
+ }
932
+ else if (E(i)) for (let [e, t] of Object.entries(i)) t === void 0 ? (n.delete(e), r.add(e)) : (n.append(e, String(t)), r.delete(e));
933
+ else {
934
+ let e = new URLSearchParams(i);
935
+ for (let [t, i] of e.entries()) n.append(t, i), r.delete(t);
936
+ }
937
+ return r.size > 0 && (n[k] = r), n;
938
+ }, Ot = (...e) => {
939
+ let t = {}, n = {}, r = {}, i, a = [];
940
+ for (let o of e) if (Array.isArray(o)) Array.isArray(t) || (t = []), t = [...t, ...o];
941
+ else if (E(o)) {
942
+ for (let [e, n] of Object.entries(o)) {
943
+ if (e === "signal" && n instanceof globalThis.AbortSignal) {
944
+ a.push(n);
945
+ continue;
946
+ }
947
+ let r = bt(n), { isReplace: o } = r;
948
+ if (n = r.value, e === "context") {
949
+ if (n != null && (!E(n) || Array.isArray(n))) throw TypeError("The `context` option must be an object");
950
+ t = {
951
+ ...t,
952
+ context: n == null ? {} : o ? { ...n } : {
953
+ ...t.context,
954
+ ...n
955
+ }
956
+ };
957
+ continue;
958
+ }
959
+ if (e === "searchParams") {
960
+ i = n == null ? void 0 : o || i === void 0 ? n : Dt(i, n);
961
+ continue;
962
+ }
963
+ E(n) && !o && e in t && (n = Ot(t[e], n)), t = {
964
+ ...t,
965
+ [e]: n
966
+ };
967
+ }
968
+ if (E(o.hooks)) {
969
+ let { value: e, isReplace: n } = bt(o.hooks);
970
+ r = Et(n ? {} : r, e), t.hooks = r;
971
+ }
972
+ if (E(o.headers)) {
973
+ let { value: e, isReplace: r } = bt(o.headers);
974
+ n = r ? D(e) : Tt(n, e), t.headers = n;
975
+ }
976
+ }
977
+ return i !== void 0 && (t.searchParams = i), a.length > 0 && (a.length === 1 ? t.signal = a[0] : it ? t.signal = AbortSignal.any(a) : t.signal = a.at(-1)), t;
978
+ }, kt = (e) => st.includes(e) ? e.toUpperCase() : e, At = {
979
+ limit: 2,
980
+ methods: [
981
+ "get",
982
+ "put",
983
+ "head",
984
+ "delete",
985
+ "options",
986
+ "trace"
987
+ ],
988
+ statusCodes: [
989
+ 408,
990
+ 413,
991
+ 429,
992
+ 500,
993
+ 502,
994
+ 503,
995
+ 504
996
+ ],
997
+ afterStatusCodes: [
998
+ 413,
999
+ 429,
1000
+ 503
1001
+ ],
1002
+ maxRetryAfter: Infinity,
1003
+ backoffLimit: Infinity,
1004
+ delay: (e) => .3 * 2 ** (e - 1) * 1e3,
1005
+ jitter: void 0,
1006
+ retryOnTimeout: !1
1007
+ }, jt = (e = {}) => {
1008
+ if (typeof e == "number") return {
1009
+ ...At,
1010
+ limit: e
1011
+ };
1012
+ if (e.methods && !Array.isArray(e.methods)) throw Error("retry.methods must be an array");
1013
+ if (e.statusCodes && !Array.isArray(e.statusCodes)) throw Error("retry.statusCodes must be an array");
1014
+ let t = Object.fromEntries(Object.entries({
1015
+ ...e,
1016
+ methods: e.methods?.map((e) => e.toLowerCase())
1017
+ }).filter(([, e]) => e !== void 0));
1018
+ return {
1019
+ ...At,
1020
+ ...t
1021
+ };
1022
+ };
1023
+ //#endregion
1024
+ //#region node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/timeout.js
1025
+ async function Mt(e, t, n, r) {
1026
+ return new Promise((i, a) => {
1027
+ let o = setTimeout(() => {
1028
+ n && n.abort(), a(new w(e));
1029
+ }, r.timeout);
1030
+ r.fetch(e, t).then(i).catch(a).then(() => {
1031
+ clearTimeout(o);
1032
+ });
1033
+ });
1034
+ }
1035
+ //#endregion
1036
+ //#region node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/delay.js
1037
+ async function Nt(e, { signal: t }) {
1038
+ return new Promise((n, r) => {
1039
+ t && (t.throwIfAborted(), t.addEventListener("abort", i, { once: !0 }));
1040
+ function i() {
1041
+ clearTimeout(a), r(t.reason);
1042
+ }
1043
+ let a = setTimeout(() => {
1044
+ t?.removeEventListener("abort", i), n();
1045
+ }, e);
1046
+ });
1047
+ }
1048
+ //#endregion
1049
+ //#region node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/options.js
1050
+ var Pt = (e) => {
1051
+ let t = {};
1052
+ for (let n in e) Object.hasOwn(e, n) && !(n in mt) && !(n in pt) && (t[n] = e[n]);
1053
+ return t;
1054
+ }, Ft = (e) => e === void 0 ? !1 : Array.isArray(e) ? e.length > 0 : e instanceof URLSearchParams ? e.size > 0 || !!e[k]?.size : typeof e == "object" ? Object.keys(e).length > 0 : typeof e == "string" ? e.trim().length > 0 : !!e, It = Object.prototype.toString, Lt = (e) => It.call(e) === "[object Error]", Rt = new Set([
1055
+ "network error",
1056
+ "NetworkError when attempting to fetch resource.",
1057
+ "The Internet connection appears to be offline.",
1058
+ "Network request failed",
1059
+ "fetch failed",
1060
+ "terminated",
1061
+ " A network error occurred.",
1062
+ "Network connection lost"
1063
+ ]);
1064
+ function zt(e) {
1065
+ if (!(e && Lt(e) && e.name === "TypeError" && typeof e.message == "string")) return !1;
1066
+ let { message: t, stack: n } = e;
1067
+ return t === "Load failed" ? n === void 0 || "__sentry_captured__" in e : t.startsWith("error sending request for url") || t === "Failed to fetch" || t.startsWith("Failed to fetch (") && t.endsWith(")") ? !0 : Rt.has(t);
1068
+ }
1069
+ //#endregion
1070
+ //#region node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/type-guards.js
1071
+ var Bt = (e, t) => e instanceof t || e?.name === t.name;
1072
+ function Vt(e) {
1073
+ return Bt(e, Qe);
1074
+ }
1075
+ function Ht(e) {
1076
+ return Bt(e, $e);
1077
+ }
1078
+ function Ut(e) {
1079
+ return Bt(e, w);
1080
+ }
1081
+ //#endregion
1082
+ //#region \0@oxc-project+runtime@0.127.0/helpers/checkPrivateRedeclaration.js
1083
+ function Wt(e, t) {
1084
+ if (t.has(e)) throw TypeError("Cannot initialize the same private elements twice on an object");
1085
+ }
1086
+ //#endregion
1087
+ //#region \0@oxc-project+runtime@0.127.0/helpers/classPrivateMethodInitSpec.js
1088
+ function Gt(e, t) {
1089
+ Wt(e, t), t.add(e);
1090
+ }
1091
+ //#endregion
1092
+ //#region \0@oxc-project+runtime@0.127.0/helpers/classPrivateFieldInitSpec.js
1093
+ function A(e, t, n) {
1094
+ Wt(e, t), t.set(e, n);
1095
+ }
1096
+ //#endregion
1097
+ //#region \0@oxc-project+runtime@0.127.0/helpers/assertClassBrand.js
1098
+ function j(e, t, n) {
1099
+ if (typeof e == "function" ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
1100
+ throw TypeError("Private element is not present on this object");
1101
+ }
1102
+ //#endregion
1103
+ //#region \0@oxc-project+runtime@0.127.0/helpers/classPrivateFieldGet2.js
1104
+ function M(e, t) {
1105
+ return e.get(j(e, t));
1106
+ }
1107
+ //#endregion
1108
+ //#region \0@oxc-project+runtime@0.127.0/helpers/classPrivateFieldSet2.js
1109
+ function N(e, t, n) {
1110
+ return e.set(j(e, t), n), n;
1111
+ }
1112
+ //#endregion
1113
+ //#region node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/core/Ky.js
1114
+ var Kt = 10 * 1024 * 1024, qt = "The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl", P = Symbol("timedOutResponseData"), Jt = (e) => {
1115
+ let t = /;\s*charset\s*=\s*(?:"([^"]+)"|([^;,\s]+))/i.exec(e), n = t?.[1] ?? t?.[2];
1116
+ if (n) try {
1117
+ return new TextDecoder(n);
1118
+ } catch {}
1119
+ return new TextDecoder();
1120
+ }, Yt = "The `schema` argument must follow the Standard Schema specification", Xt = (e) => typeof e == "object" ? {
1121
+ ...e,
1122
+ ...e.methods && { methods: [...e.methods] },
1123
+ ...e.statusCodes && { statusCodes: [...e.statusCodes] },
1124
+ ...e.afterStatusCodes && { afterStatusCodes: [...e.afterStatusCodes] }
1125
+ } : e, Zt = Object.prototype.toString, Qt = (e) => e instanceof globalThis.Request || Zt.call(e) === "[object Request]", F = (e) => e instanceof globalThis.Response || Zt.call(e) === "[object Response]", $t = (e) => Array.isArray(e) ? e.map((e) => [...e]) : D(e);
1126
+ function en(e) {
1127
+ let t = {
1128
+ ...e,
1129
+ json: D(e.json),
1130
+ context: D(e.context),
1131
+ headers: D(e.headers),
1132
+ searchParams: $t(e.searchParams)
1133
+ };
1134
+ return e.retry !== void 0 && (t.retry = Xt(e.retry)), t;
1135
+ }
1136
+ var tn = async (e, t) => {
1137
+ if (typeof t != "object" && typeof t != "function" || t === null) throw TypeError(Yt);
1138
+ let n = t["~standard"];
1139
+ if (typeof n != "object" || !n || typeof n.validate != "function") throw TypeError(Yt);
1140
+ let r = await n.validate(e);
1141
+ if (r.issues) throw new tt(r.issues);
1142
+ return r.value;
1143
+ }, I = /* @__PURE__ */ new WeakMap(), L = /* @__PURE__ */ new WeakMap(), R = /* @__PURE__ */ new WeakMap(), z = /* @__PURE__ */ new WeakMap(), nn = /* @__PURE__ */ new WeakMap(), B = /* @__PURE__ */ new WeakMap(), rn = /* @__PURE__ */ new WeakMap(), V = /* @__PURE__ */ new WeakMap(), an = /* @__PURE__ */ new WeakMap(), H = /* @__PURE__ */ new WeakMap(), on = /* @__PURE__ */ new WeakMap(), U = /* @__PURE__ */ new WeakSet(), sn = class e {
1144
+ static create(t, n) {
1145
+ let r = n.hooks?.init ?? [], i = r.length > 0 ? en(n) : n;
1146
+ for (let e of r) e(i);
1147
+ let a = new e(t, i), o = async () => {
1148
+ if (typeof M(z, a).timeout == "number" && M(z, a).timeout > 2147483647) throw RangeError(`The \`timeout\` option cannot be greater than ${lt}`);
1149
+ if (typeof M(z, a).totalTimeout == "number" && M(z, a).totalTimeout > 2147483647) throw RangeError(`The \`totalTimeout\` option cannot be greater than ${lt}`);
1150
+ await Promise.resolve();
1151
+ let e = await j(U, a, yn).call(a), t = e ?? await j(U, a, xn).call(a, async () => j(U, a, wn).call(a)), n = e !== void 0 || j(U, a, Cn).call(a);
1152
+ for (;;) {
1153
+ if (t === void 0) return t;
1154
+ if (F(t)) try {
1155
+ t = await j(U, a, bn).call(a, t);
1156
+ } catch (e) {
1157
+ if (!(e instanceof C)) throw e;
1158
+ let r = await j(U, a, Sn).call(a, e, async () => j(U, a, wn).call(a));
1159
+ if (r === void 0) return r;
1160
+ t = r, n = j(U, a, Cn).call(a);
1161
+ continue;
1162
+ }
1163
+ let e = t;
1164
+ if (!e.ok && e.type !== "opaque" && (typeof M(z, a).throwHttpErrors == "function" ? M(z, a).throwHttpErrors(e.status) : M(z, a).throwHttpErrors)) {
1165
+ let r = new Qe(e, j(U, a, q).call(a, e), j(U, a, K).call(a)), i = r;
1166
+ if (r.data = await j(U, a, dn).call(a, e), n) throw i;
1167
+ let o = await j(U, a, Sn).call(a, r, async () => j(U, a, wn).call(a));
1168
+ if (o === void 0) return o;
1169
+ t = o, n = j(U, a, Cn).call(a);
1170
+ continue;
1171
+ }
1172
+ break;
1173
+ }
1174
+ if (!F(t)) return t;
1175
+ if (j(U, a, un).call(a, t), M(z, a).onDownloadProgress) {
1176
+ if (typeof M(z, a).onDownloadProgress != "function") throw TypeError("The `onDownloadProgress` option must be a function");
1177
+ if (!at) throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");
1178
+ let e = t.clone();
1179
+ return j(U, a, G).call(a, t), _t(e, M(z, a).onDownloadProgress);
1180
+ }
1181
+ return t;
1182
+ }, s = (async () => {
1183
+ try {
1184
+ return await o();
1185
+ } catch (e) {
1186
+ if (!(e instanceof Error) || M(rn, a).has(e)) throw e;
1187
+ let t = e;
1188
+ for (let e of M(z, a).hooks.beforeError) {
1189
+ let n = await e({
1190
+ request: a.request,
1191
+ options: j(U, a, K).call(a),
1192
+ error: t,
1193
+ retryCount: M(L, a)
1194
+ });
1195
+ n instanceof Error && (t = n);
1196
+ }
1197
+ throw t;
1198
+ } finally {
1199
+ let e = M(nn, a);
1200
+ j(U, a, gn).call(a, e?.body ?? void 0), a.request !== e && j(U, a, gn).call(a, a.request.body ?? void 0);
1201
+ }
1202
+ })();
1203
+ for (let [e, t] of Object.entries(ct)) e === "bytes" && typeof globalThis.Response?.prototype?.bytes != "function" || (s[e] = async (n) => {
1204
+ a.request.headers.set("accept", a.request.headers.get("accept") || t);
1205
+ let r = await s;
1206
+ if (e !== "json") return r[e]();
1207
+ let o = await r.text();
1208
+ if (o === "") return n === void 0 ? JSON.parse(o) : tn(void 0, n);
1209
+ let c = i.parseJson ? await i.parseJson(o, {
1210
+ request: j(U, a, q).call(a, r),
1211
+ response: r
1212
+ }) : JSON.parse(o);
1213
+ return n === void 0 ? c : tn(c, n);
1214
+ });
1215
+ return s;
1216
+ }
1217
+ constructor(t, n = {}) {
1218
+ if (Gt(this, U), a(this, "request", void 0), A(this, I, void 0), A(this, L, 0), A(this, R, void 0), A(this, z, void 0), A(this, nn, void 0), A(this, B, void 0), A(this, rn, /* @__PURE__ */ new WeakSet()), A(this, V, void 0), A(this, an, void 0), A(this, H, !1), A(this, on, /* @__PURE__ */ new WeakMap()), N(R, this, t), Object.hasOwn(n, "prefixUrl")) throw Error(qt);
1219
+ if (N(z, this, {
1220
+ ...n,
1221
+ headers: St(M(R, this).headers, n.headers),
1222
+ hooks: Et({}, n.hooks),
1223
+ method: kt(n.method ?? M(R, this).method ?? "GET"),
1224
+ prefix: String(n.prefix || ""),
1225
+ retry: jt(n.retry),
1226
+ throwHttpErrors: n.throwHttpErrors ?? !0,
1227
+ timeout: n.timeout ?? 1e4,
1228
+ totalTimeout: n.totalTimeout ?? !1,
1229
+ fetch: n.fetch ?? globalThis.fetch.bind(globalThis),
1230
+ context: n.context ?? {}
1231
+ }), typeof M(R, this) != "string" && !(M(R, this) instanceof URL || M(R, this) instanceof globalThis.Request)) throw TypeError("`input` must be a string, URL, or Request");
1232
+ if (typeof M(R, this) == "string") {
1233
+ if (M(z, this).prefix) {
1234
+ let e = M(z, this).prefix.replace(/\/+$/, ""), t = M(R, this).replace(/^\/+/, "");
1235
+ N(R, this, `${e}/${t}`);
1236
+ }
1237
+ if (M(z, this).baseUrl) {
1238
+ let e;
1239
+ try {
1240
+ e = new URL(M(R, this));
1241
+ } catch {}
1242
+ e || N(R, this, new URL(M(R, this), new Request(M(z, this).baseUrl).url));
1243
+ }
1244
+ }
1245
+ rt && it && (N(B, this, M(z, this).signal ?? M(R, this).signal), N(I, this, new globalThis.AbortController()), M(z, this).signal = j(U, this, _n).call(this)), nt && (M(z, this).duplex = "half"), M(z, this).json !== void 0 && (M(z, this).body = M(z, this).stringifyJson?.(M(z, this).json) ?? JSON.stringify(M(z, this).json), M(z, this).headers.set("content-type", M(z, this).headers.get("content-type") ?? "application/json"));
1246
+ let r = n.headers && new globalThis.Headers(n.headers).has("content-type");
1247
+ if (M(R, this) instanceof globalThis.Request && (ot && M(z, this).body instanceof globalThis.FormData || M(z, this).body instanceof URLSearchParams) && !r && M(z, this).headers.delete("content-type"), this.request = new globalThis.Request(M(R, this), M(z, this)), Ft(M(z, this).searchParams)) {
1248
+ let t = new URL(this.request.url), n = M(z, this).searchParams?.[k];
1249
+ if (n) for (let e of n) t.searchParams.delete(e);
1250
+ if (typeof M(z, this).searchParams == "string") {
1251
+ let e = M(z, this).searchParams.replace(/^\?/, "");
1252
+ e !== "" && (t.search = t.search ? `${t.search}&${e}` : `?${e}`);
1253
+ } else {
1254
+ let n = new URLSearchParams(cn.call(e, M(z, this).searchParams));
1255
+ for (let [e, r] of n.entries()) t.searchParams.append(e, r);
1256
+ }
1257
+ if (M(z, this).searchParams && typeof M(z, this).searchParams == "object" && !Array.isArray(M(z, this).searchParams) && !(M(z, this).searchParams instanceof URLSearchParams)) for (let [e, n] of Object.entries(M(z, this).searchParams)) n === void 0 && t.searchParams.delete(e);
1258
+ this.request = new globalThis.Request(t, M(z, this));
1259
+ }
1260
+ if (M(z, this).onUploadProgress && typeof M(z, this).onUploadProgress != "function") throw TypeError("The `onUploadProgress` option must be a function");
1261
+ N(an, this, typeof M(z, this).totalTimeout == "number" ? j(U, this, En).call(this) : void 0);
1262
+ }
1263
+ };
1264
+ function cn(e) {
1265
+ return e && typeof e == "object" && !Array.isArray(e) && !(e instanceof URLSearchParams) ? Object.fromEntries(Object.entries(e).filter(([, e]) => e !== void 0)) : e;
1266
+ }
1267
+ function W() {
1268
+ let e = M(z, this).retry.delay(M(L, this) + 1), t = e;
1269
+ return M(z, this).retry.jitter === !0 ? t = Math.random() * e : typeof M(z, this).retry.jitter == "function" && (t = M(z, this).retry.jitter(e), (!Number.isFinite(t) || t < 0) && (t = e)), Math.min(M(z, this).retry.backoffLimit, t);
1270
+ }
1271
+ async function ln(e) {
1272
+ if (M(L, this) >= M(z, this).retry.limit) throw e;
1273
+ let t = e instanceof Error ? e : new et(e);
1274
+ if (t instanceof C) return t.customDelay ?? j(U, this, W).call(this);
1275
+ if (!M(z, this).retry.methods.includes(this.request.method.toLowerCase())) throw e;
1276
+ if (M(z, this).retry.shouldRetry !== void 0) {
1277
+ let n = await M(z, this).retry.shouldRetry({
1278
+ error: t,
1279
+ retryCount: M(L, this) + 1
1280
+ });
1281
+ if (n === !1) throw e;
1282
+ if (n === !0) return j(U, this, W).call(this);
1283
+ }
1284
+ if (Ut(e)) {
1285
+ if (!M(z, this).retry.retryOnTimeout) throw e;
1286
+ return j(U, this, W).call(this);
1287
+ }
1288
+ if (Vt(e)) {
1289
+ if (!M(z, this).retry.statusCodes.includes(e.response.status)) throw e;
1290
+ let t = e.response.headers.get("Retry-After") ?? e.response.headers.get("RateLimit-Reset") ?? e.response.headers.get("X-RateLimit-Retry-After") ?? e.response.headers.get("X-RateLimit-Reset") ?? e.response.headers.get("X-Rate-Limit-Reset");
1291
+ if (t && M(z, this).retry.afterStatusCodes.includes(e.response.status)) {
1292
+ let e = Number(t) * 1e3;
1293
+ return Number.isNaN(e) ? e = Date.parse(t) - Date.now() : e >= Date.parse("2024-01-01") && (e -= Date.now()), Number.isFinite(e) ? (e = Math.max(0, e), Math.min(M(z, this).retry.maxRetryAfter, e)) : Math.min(M(z, this).retry.maxRetryAfter, j(U, this, W).call(this));
1294
+ }
1295
+ if (e.response.status === 413) throw e;
1296
+ return j(U, this, W).call(this);
1297
+ }
1298
+ if (!Ht(e)) throw e;
1299
+ return j(U, this, W).call(this);
1300
+ }
1301
+ function un(e) {
1302
+ let t = j(U, this, q).call(this, e);
1303
+ return M(z, this).parseJson && (e.json = async () => {
1304
+ let n = await e.text();
1305
+ return n === "" ? JSON.parse(n) : M(z, this).parseJson(n, {
1306
+ request: t,
1307
+ response: e
1308
+ });
1309
+ }), e;
1310
+ }
1311
+ async function dn(e) {
1312
+ let t = await j(U, this, mn).call(this, e, j(U, this, fn).call(this));
1313
+ if (t === P) {
1314
+ j(U, this, vn).call(this);
1315
+ return;
1316
+ }
1317
+ if (!t) return;
1318
+ if (!j(U, this, pn).call(this, e.headers.get("content-type") ?? "")) return t;
1319
+ let n = await j(U, this, hn).call(this, t, e, j(U, this, fn).call(this), j(U, this, q).call(this, e));
1320
+ if (n === P) {
1321
+ j(U, this, vn).call(this);
1322
+ return;
1323
+ }
1324
+ return n;
1325
+ }
1326
+ function fn() {
1327
+ let e = M(z, this).timeout === !1 ? 1e4 : M(z, this).timeout, t = j(U, this, Tn).call(this);
1328
+ if (t === void 0) return e;
1329
+ if (t <= 0) throw new w(this.request);
1330
+ return Math.min(e, t);
1331
+ }
1332
+ function pn(e) {
1333
+ let t = (e.split(";", 1)[0] ?? "").trim().toLowerCase();
1334
+ return /\/(?:.*[.+-])?json$/.test(t);
1335
+ }
1336
+ async function mn(e, t) {
1337
+ let { body: n } = e;
1338
+ if (!n) try {
1339
+ return await e.text();
1340
+ } catch {
1341
+ return;
1342
+ }
1343
+ let r;
1344
+ try {
1345
+ r = n.getReader();
1346
+ } catch {
1347
+ return;
1348
+ }
1349
+ let i = Jt(e.headers.get("content-type") ?? ""), a = [], o = 0, s = (async () => {
1350
+ try {
1351
+ for (;;) {
1352
+ let { done: e, value: t } = await r.read();
1353
+ if (e) break;
1354
+ if (o += t.byteLength, o > Kt) {
1355
+ r.cancel().catch(() => void 0);
1356
+ return;
1357
+ }
1358
+ a.push(i.decode(t, { stream: !0 }));
1359
+ }
1360
+ } catch {
1361
+ return;
1362
+ }
1363
+ return a.push(i.decode()), a.join("");
1364
+ })(), c = new Promise((e) => {
1365
+ let n = setTimeout(() => {
1366
+ e(P);
1367
+ }, t);
1368
+ s.finally(() => {
1369
+ clearTimeout(n);
1370
+ });
1371
+ }), l = await Promise.race([s, c]);
1372
+ return l === P && r.cancel().catch(() => void 0), l;
1373
+ }
1374
+ async function hn(e, t, n, r) {
1375
+ let i;
1376
+ try {
1377
+ return await Promise.race([Promise.resolve().then(() => M(z, this).parseJson ? M(z, this).parseJson(e, {
1378
+ request: r,
1379
+ response: t
1380
+ }) : JSON.parse(e)), new Promise((e) => {
1381
+ i = setTimeout(() => {
1382
+ e(P);
1383
+ }, n);
1384
+ })]);
1385
+ } catch {
1386
+ return;
1387
+ } finally {
1388
+ clearTimeout(i);
1389
+ }
1390
+ }
1391
+ function gn(e) {
1392
+ e && e.cancel().catch(() => void 0);
1393
+ }
1394
+ function G(e) {
1395
+ j(U, this, gn).call(this, e.body ?? void 0);
1396
+ }
1397
+ function _n() {
1398
+ return M(B, this) ? AbortSignal.any([M(B, this), M(I, this).signal]) : M(I, this).signal;
1399
+ }
1400
+ function vn() {
1401
+ let e = j(U, this, Tn).call(this);
1402
+ if (e !== void 0 && e <= 0) throw new w(this.request);
1403
+ }
1404
+ async function yn() {
1405
+ for (let e of M(z, this).hooks.beforeRequest) {
1406
+ let t = await e({
1407
+ request: this.request,
1408
+ options: j(U, this, K).call(this),
1409
+ retryCount: 0
1410
+ });
1411
+ if (Qt(t)) j(U, this, Dn).call(this, t);
1412
+ else if (F(t)) return t;
1413
+ }
1414
+ }
1415
+ async function bn(e) {
1416
+ let t = j(U, this, q).call(this, e);
1417
+ for (let n of M(z, this).hooks.afterResponse) {
1418
+ let r = j(U, this, On).call(this, e.clone(), t);
1419
+ j(U, this, un).call(this, r);
1420
+ let i;
1421
+ try {
1422
+ i = await n({
1423
+ request: this.request,
1424
+ options: j(U, this, K).call(this),
1425
+ response: r,
1426
+ retryCount: M(L, this)
1427
+ });
1428
+ } catch (t) {
1429
+ throw r !== e && j(U, this, G).call(this, r), j(U, this, G).call(this, e), t;
1430
+ }
1431
+ if (i instanceof dt) throw r !== e && j(U, this, G).call(this, r), j(U, this, G).call(this, e), new C(i.options);
1432
+ let a = F(i) ? j(U, this, On).call(this, i, t) : e;
1433
+ r !== e && r !== a && r.body !== a.body && j(U, this, G).call(this, r), e !== a && e.body !== a.body && j(U, this, G).call(this, e), e = a;
1434
+ }
1435
+ return e;
1436
+ }
1437
+ async function xn(e) {
1438
+ try {
1439
+ return await e();
1440
+ } catch (t) {
1441
+ return j(U, this, Sn).call(this, t, e);
1442
+ }
1443
+ }
1444
+ async function Sn(e, t) {
1445
+ var n;
1446
+ N(H, this, !1);
1447
+ let r = Math.min(await j(U, this, ln).call(this, e), lt), i = { signal: M(B, this) }, a = j(U, this, Tn).call(this);
1448
+ if (a !== void 0) {
1449
+ if (a <= 0) throw new w(this.request);
1450
+ if (r >= a) throw await Nt(a, i), new w(this.request);
1451
+ }
1452
+ if (await Nt(r, i), j(U, this, vn).call(this), e instanceof C && e.customRequest) {
1453
+ let t = new globalThis.Request(e.customRequest, M(z, this).signal ? { signal: M(z, this).signal } : void 0);
1454
+ j(U, this, Dn).call(this, t);
1455
+ }
1456
+ for (let t of M(z, this).hooks.beforeRetry) {
1457
+ let n;
1458
+ try {
1459
+ n = await t({
1460
+ request: this.request,
1461
+ options: j(U, this, K).call(this),
1462
+ error: e,
1463
+ retryCount: M(L, this) + 1
1464
+ });
1465
+ } catch (t) {
1466
+ throw t instanceof Error && t !== e && M(rn, this).add(t), t;
1467
+ }
1468
+ if (Qt(n)) {
1469
+ j(U, this, Dn).call(this, n);
1470
+ break;
1471
+ }
1472
+ if (F(n)) {
1473
+ var o;
1474
+ return N(H, this, !0), N(L, this, (o = M(L, this), o++, o)), n;
1475
+ }
1476
+ if (n === ut) return;
1477
+ }
1478
+ return j(U, this, vn).call(this), N(L, this, (n = M(L, this), n++, n)), j(U, this, xn).call(this, t);
1479
+ }
1480
+ function Cn() {
1481
+ let e = M(H, this);
1482
+ return N(H, this, !1), e;
1483
+ }
1484
+ async function wn() {
1485
+ M(I, this)?.signal.aborted && (N(I, this, new globalThis.AbortController()), M(z, this).signal = j(U, this, _n).call(this), this.request = new globalThis.Request(this.request, { signal: M(z, this).signal }));
1486
+ let e = Pt(M(z, this)), t = M(z, this).retry.limit > 0 ? this.request.clone() : void 0, n = j(U, this, kn).call(this, this.request, M(z, this).body ?? void 0);
1487
+ N(nn, this, n), t && (this.request = t);
1488
+ try {
1489
+ let t = j(U, this, Tn).call(this);
1490
+ if (t !== void 0 && t <= 0) throw new w(this.request);
1491
+ let r = M(z, this).timeout === !1 ? t : t === void 0 ? M(z, this).timeout : Math.min(M(z, this).timeout, t), i = r === void 0 ? await M(z, this).fetch(n, e) : await Mt(n, e, M(I, this), {
1492
+ timeout: r,
1493
+ fetch: M(z, this).fetch
1494
+ });
1495
+ return j(U, this, On).call(this, i, n);
1496
+ } catch (e) {
1497
+ throw zt(e) ? new $e(this.request, { cause: e }) : e;
1498
+ }
1499
+ }
1500
+ function Tn() {
1501
+ if (M(an, this) === void 0) return;
1502
+ let e = j(U, this, En).call(this) - M(an, this);
1503
+ return Math.max(0, M(z, this).totalTimeout - e);
1504
+ }
1505
+ function En() {
1506
+ return globalThis.performance?.now() ?? Date.now();
1507
+ }
1508
+ function K() {
1509
+ if (!M(V, this)) {
1510
+ let { hooks: e, json: t, parseJson: n, stringifyJson: r, searchParams: i, timeout: a, totalTimeout: o, throwHttpErrors: s, fetch: c, ...l } = M(z, this);
1511
+ N(V, this, Object.freeze(l));
1512
+ }
1513
+ return M(V, this);
1514
+ }
1515
+ function Dn(e) {
1516
+ N(V, this, void 0), this.request = e;
1517
+ }
1518
+ function q(e) {
1519
+ return M(on, this).get(e) ?? this.request;
1520
+ }
1521
+ function On(e, t) {
1522
+ return M(on, this).set(e, t), e;
1523
+ }
1524
+ function kn(e, t) {
1525
+ return !M(z, this).onUploadProgress || !e.body || !nt ? e : vt(e, M(z, this).onUploadProgress, t ?? M(z, this).body ?? void 0);
1526
+ }
1527
+ //#endregion
1528
+ //#region node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/index.js
1529
+ var An = (e) => {
1530
+ let t = (t, n) => sn.create(t, xt(e, n));
1531
+ for (let n of st) t[n] = (t, r) => sn.create(t, xt(e, r, { method: n }));
1532
+ return t.create = (e) => An(xt(e)), t.extend = (t) => (typeof t == "function" && (t = t(e ?? {})), An(xt(e, t))), t.stop = ut, t.retry = ft, t;
1533
+ }, jn = An();
1534
+ //#endregion
1535
+ //#region src/core/http/errors.ts
1536
+ function Mn(e) {
1537
+ if (typeof e == "string") return e;
1538
+ if (Array.isArray(e)) return e.filter((e) => typeof e == "string").join("; ") || void 0;
1539
+ }
1540
+ function Nn(e) {
1541
+ return (e.get("content-type") ?? "").includes("application/json");
1542
+ }
1543
+ async function Pn(e) {
1544
+ let t, n;
1545
+ try {
1546
+ if (Nn(e.headers)) {
1547
+ let r = await e.json();
1548
+ t = r.error?.code ?? r.code, n = Mn(r.error?.message) ?? Mn(r.message) ?? Mn(r.data?.message);
1549
+ } else n = (await e.text()).slice(0, 500);
1550
+ } catch {}
1551
+ return new o("TRANSPORT_FAILED", n ? `HTTP ${e.status}: ${n}` : `HTTP ${e.status}: ${e.statusText || "request failed"}`, { details: {
1552
+ status: e.status,
1553
+ serverCode: t,
1554
+ url: e.url
1555
+ } });
1556
+ }
1557
+ function Fn(e, t = "Request aborted") {
1558
+ return new o("TRANSPORT_ABORTED", t, { cause: e });
1559
+ }
1560
+ function In(e, t = "Network error") {
1561
+ return new o("TRANSPORT_FAILED", t, { cause: e });
1562
+ }
1563
+ function Ln(e) {
1564
+ return e instanceof o && e.code === "TRANSPORT_ABORTED" ? !0 : e?.name === "AbortError";
1565
+ }
1566
+ //#endregion
1567
+ //#region src/core/http/sse.ts
1568
+ function Rn(e, t) {
1569
+ return `${e.replace(/\/+$/, "")}${t.startsWith("/") ? t : `/${t}`}`;
1570
+ }
1571
+ async function* zn(e, n, r, i = {}) {
1572
+ let a = i.method ?? (i.body === void 0 ? "GET" : "POST"), s = new Headers(r);
1573
+ for (let [e, t] of Object.entries(i.headers ?? {})) s.set(e, t);
1574
+ s.set("accept", "text/event-stream");
1575
+ let c;
1576
+ i.body !== void 0 && a !== "GET" && a !== "HEAD" && (c = typeof i.body == "string" ? i.body : JSON.stringify(i.body), !s.has("content-type") && typeof i.body != "string" && s.set("content-type", "application/json"));
1577
+ let l;
1578
+ try {
1579
+ l = await e(n, {
1580
+ method: a,
1581
+ headers: s,
1582
+ body: c,
1583
+ signal: i.signal
1584
+ });
1585
+ } catch (e) {
1586
+ throw In(e);
1587
+ }
1588
+ if (!l.ok) throw await Pn(l);
1589
+ if (!l.body) throw new o("TRANSPORT_FAILED", "SSE response has no body");
1590
+ i.onConnected?.();
1591
+ let u = l.body.getReader(), d = new TextDecoder("utf-8"), f = [], p = t({ onEvent(e) {
1592
+ let t = e.event?.trim() ? e.event.trim() : "message";
1593
+ f.push({
1594
+ event: t,
1595
+ data: e.data,
1596
+ id: e.id
1597
+ });
1598
+ } }), m = () => f.splice(0, f.length);
1599
+ try {
1600
+ for (;;) {
1601
+ let { value: e, done: t } = await u.read();
1602
+ if (t) {
1603
+ let e = d.decode();
1604
+ e && p.feed(e);
1605
+ for (let e of m()) yield e;
1606
+ break;
1607
+ }
1608
+ p.feed(d.decode(e, { stream: !0 }));
1609
+ for (let e of m()) yield e;
1610
+ }
1611
+ } finally {
1612
+ u.releaseLock();
1613
+ }
1614
+ }
1615
+ //#endregion
1616
+ //#region src/core/http/client.ts
1617
+ function Bn(e) {
1618
+ return e.replace(/^\//, "");
1619
+ }
1620
+ function Vn(e, t) {
1621
+ let n = new Set((t.omitDefaultHeaders ?? []).map((e) => e.toLowerCase())), r = {};
1622
+ for (let [t, i] of Object.entries(e)) n.has(t.toLowerCase()) || (r[t] = i);
1623
+ return {
1624
+ ...r,
1625
+ ...t.headers ?? {}
1626
+ };
1627
+ }
1628
+ function Hn(e) {
1629
+ let t = e.apiBase.replace(/\/+$/, ""), n = { ...e.defaultHeaders ?? {} }, r = e.fetch ?? (typeof fetch < "u" ? fetch.bind(globalThis) : void 0);
1630
+ if (!r) throw new o("TRANSPORT_FAILED", "No fetch implementation available. Provide one via HttpClientOptions.fetch.");
1631
+ let i = jn.create({
1632
+ baseUrl: `${t}/`,
1633
+ retry: { limit: 0 },
1634
+ timeout: !1,
1635
+ fetch: r,
1636
+ hooks: { beforeError: [async (e) => {
1637
+ throw e instanceof Qe ? await Pn(e.response) : Ln(e) ? Fn(e) : In(e);
1638
+ }] }
1639
+ });
1640
+ return {
1641
+ setDefaultHeader(e, t) {
1642
+ t === void 0 ? delete n[e] : n[e] = t;
1643
+ },
1644
+ async request(e, t = {}) {
1645
+ let r = t.method ?? (t.body === void 0 ? "GET" : "POST"), a = {
1646
+ accept: "application/json",
1647
+ ...Vn(n, t)
1648
+ }, s = t.searchParams ? Object.fromEntries(Object.entries(t.searchParams).filter(([, e]) => e !== void 0).map(([e, t]) => [e, String(t)])) : void 0;
1649
+ try {
1650
+ let n = await i(Bn(e), {
1651
+ method: r,
1652
+ headers: a,
1653
+ searchParams: s,
1654
+ json: r === "GET" || r === "HEAD" ? void 0 : t.body,
1655
+ signal: t.signal
1656
+ });
1657
+ return n.status === 204 ? void 0 : (n.headers.get("content-type") ?? "").includes("application/json") ? await n.json() : await n.text();
1658
+ } catch (e) {
1659
+ throw e instanceof o ? e : Ln(e) ? Fn(e) : In(e);
1660
+ }
1661
+ },
1662
+ stream(e, i = {}) {
1663
+ return zn(r, Rn(t, e), n, i);
1664
+ }
1665
+ };
1666
+ }
1667
+ //#endregion
1668
+ //#region src/core/services/auth.service.ts
1669
+ var Un = class {
1670
+ constructor(e) {
1671
+ a(this, "http", void 0), this.http = e;
1672
+ }
1673
+ async authenticate(e, t) {
1674
+ let n = se(await this.http.request("/app-client/auth", {
1675
+ method: "POST",
1676
+ headers: p(e, t)
1677
+ }));
1678
+ if (!n?.ok) throw new o("AUTH_REQUIRED", "App client authentication failed");
1679
+ return n;
1680
+ }
1681
+ async login(e, t) {
1682
+ let n = se(await this.http.request("/user/login", {
1683
+ method: "POST",
1684
+ body: {
1685
+ email: e,
1686
+ password: t
1687
+ }
1688
+ }));
1689
+ if (!n?.accessToken) throw new o("LOGIN_FAILED", "Login succeeded but accessToken is missing");
1690
+ return n;
1691
+ }
1692
+ };
1693
+ //#endregion
1694
+ //#region src/core/services/agent.service.ts
1695
+ function Wn(e) {
1696
+ if (!e) return;
1697
+ let t = Object.entries(e).filter(([, e]) => e !== void 0 && e !== "");
1698
+ return t.length > 0 ? Object.fromEntries(t) : void 0;
1699
+ }
1700
+ var Gn = class {
1701
+ constructor(e, t) {
1702
+ a(this, "http", void 0), a(this, "resolveAuth", void 0), this.http = e, this.resolveAuth = t;
1703
+ }
1704
+ agentRequestInit(e, t) {
1705
+ return {
1706
+ method: "GET",
1707
+ signal: t.signal,
1708
+ searchParams: t.searchParams,
1709
+ omitDefaultHeaders: [c],
1710
+ headers: re(e)
1711
+ };
1712
+ }
1713
+ listAvailableAgents(e, t) {
1714
+ let { dsn: n } = this.resolveAuth();
1715
+ return this.http.request("/agent/client/available", this.agentRequestInit(n, {
1716
+ signal: t,
1717
+ searchParams: Wn(e)
1718
+ }));
1719
+ }
1720
+ listAllClientAgents(e) {
1721
+ let { dsn: t } = this.resolveAuth();
1722
+ return this.http.request("/agent/client/list", this.agentRequestInit(t, { signal: e }));
1723
+ }
1724
+ listClientSkills(e, t, n) {
1725
+ let { dsn: r } = this.resolveAuth(), i = e.trim();
1726
+ return this.http.request(`/agent/${i}/skills/client`, this.agentRequestInit(r, {
1727
+ signal: n,
1728
+ searchParams: Wn(t)
1729
+ }));
1730
+ }
1731
+ };
1732
+ //#endregion
1733
+ //#region src/core/services/chat.service.ts
1734
+ function Kn(e) {
1735
+ return !(e instanceof o) || e.code !== "TRANSPORT_FAILED" ? !1 : e.message.toLowerCase().includes("property content should not exist");
1736
+ }
1737
+ function J(e) {
1738
+ return e.trim().toLowerCase();
1739
+ }
1740
+ var qn = class {
1741
+ constructor(e) {
1742
+ a(this, "http", void 0), this.http = e;
1743
+ }
1744
+ listSessions(e, t, n) {
1745
+ return this.http.request("/chat", {
1746
+ method: "GET",
1747
+ signal: n,
1748
+ searchParams: {
1749
+ page: e,
1750
+ size: t
1751
+ }
1752
+ });
1753
+ }
1754
+ getSession(e, t, n, r) {
1755
+ return this.http.request(`/chat/${J(e)}`, {
1756
+ method: "GET",
1757
+ signal: r,
1758
+ searchParams: {
1759
+ page: t,
1760
+ size: n
1761
+ }
1762
+ });
1763
+ }
1764
+ prepareSession(e, t) {
1765
+ return this.http.request(`/chat/${J(e)}/prepare`, {
1766
+ method: "POST",
1767
+ signal: t
1768
+ });
1769
+ }
1770
+ deleteSession(e) {
1771
+ return this.http.request(`/chat/${J(e)}`, { method: "DELETE" });
1772
+ }
1773
+ streamSession(e, t) {
1774
+ return this.http.stream(`/chat/${J(e)}/stream`, t);
1775
+ }
1776
+ createSession(e, t, n) {
1777
+ return this.postUserPayload("/chat", e, t, n);
1778
+ }
1779
+ postMessage(e, t, n, r) {
1780
+ return this.postUserPayload(`/chat/${e}/messages`, t, n, r);
1781
+ }
1782
+ postWriteConfirmation(e, t, n) {
1783
+ let r = `/chat/${J(e)}/messages`, i = {
1784
+ role: "user",
1785
+ content: "",
1786
+ ...t
1787
+ };
1788
+ return this.postUserPayloadVoid(r, i, n);
1789
+ }
1790
+ async postUserPayload(e, t, n, r) {
1791
+ let i = this.buildUserMessageBody(t, r);
1792
+ try {
1793
+ return await this.http.request(e, {
1794
+ method: "POST",
1795
+ body: i,
1796
+ signal: n
1797
+ });
1798
+ } catch (t) {
1799
+ if (!Kn(t)) throw t;
1800
+ let { content: r, ...a } = i;
1801
+ return this.http.request(e, {
1802
+ method: "POST",
1803
+ body: {
1804
+ ...a,
1805
+ message: r
1806
+ },
1807
+ signal: n
1808
+ });
1809
+ }
1810
+ }
1811
+ buildUserMessageBody(e, t) {
1812
+ let n = {
1813
+ role: "user",
1814
+ content: e
1815
+ }, r = t?.agentId?.trim(), i = t?.skillId?.trim();
1816
+ return r && (n.agentId = /^\d+$/.test(r) ? Number(r) : r), i && (n.skillId = /^\d+$/.test(i) ? Number(i) : i), n;
1817
+ }
1818
+ async postUserPayloadVoid(e, t, n) {
1819
+ try {
1820
+ await this.http.request(e, {
1821
+ method: "POST",
1822
+ body: t,
1823
+ signal: n
1824
+ });
1825
+ } catch (r) {
1826
+ if (!Kn(r)) throw r;
1827
+ let { content: i, ...a } = t;
1828
+ await this.http.request(e, {
1829
+ method: "POST",
1830
+ body: {
1831
+ ...a,
1832
+ message: i
1833
+ },
1834
+ signal: n
1835
+ });
1836
+ }
1837
+ }
1838
+ };
1839
+ //#endregion
1840
+ //#region src/core/api-envelope.ts
1841
+ function Jn(e) {
1842
+ return typeof e == "object" && !!e;
1843
+ }
1844
+ function Yn(e) {
1845
+ return typeof e == "string" && e.trim().length > 0 ? e.trim() : void 0;
1846
+ }
1847
+ function Xn(e) {
1848
+ if (typeof e == "number" && Number.isFinite(e)) return e;
1849
+ if (typeof e == "string" && e.trim().length > 0) {
1850
+ let t = Number(e);
1851
+ return Number.isFinite(t) ? t : void 0;
1852
+ }
1853
+ }
1854
+ function Zn(e) {
1855
+ if (!Jn(e)) throw new o("TRANSPORT_FAILED", "Invalid API response");
1856
+ let t = Xn(e.status);
1857
+ if (t !== void 0 && t !== 200) throw new o("TRANSPORT_FAILED", Yn(e.message) ?? "request failed", { details: {
1858
+ status: t,
1859
+ data: e.data
1860
+ } });
1861
+ if ("data" in e && e.data === null) return null;
1862
+ let n = h(e);
1863
+ return n === null ? e : n;
1864
+ }
1865
+ //#endregion
1866
+ //#region src/core/services/feedback.service.ts
1867
+ function Qn(e) {
1868
+ return e.trim().toLowerCase();
1869
+ }
1870
+ var $n = class {
1871
+ constructor(e) {
1872
+ a(this, "http", void 0), this.http = e;
1873
+ }
1874
+ async getDownReasonTags(e) {
1875
+ return we(Zn(await this.http.request("/chat/feedback/down-reason-tags", {
1876
+ method: "GET",
1877
+ signal: e
1878
+ }))).items;
1879
+ }
1880
+ async batchFeedbacks(e, t, n) {
1881
+ return t.length === 0 ? { items: [] } : Ee(Zn(await this.http.request(`/chat/${Qn(e)}/messages/feedbacks`, {
1882
+ method: "GET",
1883
+ signal: n,
1884
+ searchParams: { messageIds: t.join(",") }
1885
+ })));
1886
+ }
1887
+ async upsert(e, t, n, r) {
1888
+ return Te(Zn(await this.http.request(`/chat/${Qn(e)}/messages/${t}/feedback`, {
1889
+ method: "PUT",
1890
+ body: n,
1891
+ signal: r
1892
+ })));
1893
+ }
1894
+ async remove(e, t, n) {
1895
+ Zn(await this.http.request(`/chat/${Qn(e)}/messages/${t}/feedback`, {
1896
+ method: "DELETE",
1897
+ signal: n
1898
+ }));
1899
+ }
1900
+ }, er = class {
1901
+ constructor(e) {
1902
+ a(this, "context", void 0), a(this, "sessionId", null), a(this, "initialMessages", []), this.context = e.context;
1903
+ }
1904
+ updateContext(e) {
1905
+ this.context = {
1906
+ ...this.context,
1907
+ ...e
1908
+ };
1909
+ }
1910
+ getSession() {
1911
+ return this.sessionId ? {
1912
+ sessionId: this.sessionId,
1913
+ conversationId: this.sessionId
1914
+ } : null;
1915
+ }
1916
+ getInitialMessages() {
1917
+ return this.initialMessages;
1918
+ }
1919
+ setSession(e, t = []) {
1920
+ this.sessionId = e.trim().toLowerCase(), this.initialMessages = t;
1921
+ }
1922
+ reset() {
1923
+ this.sessionId = null, this.initialMessages = [];
1924
+ }
1925
+ };
1926
+ //#endregion
1927
+ //#region src/core/feedback-utils.ts
1928
+ function Y(e) {
1929
+ return /^\d+$/.test(e);
1930
+ }
1931
+ function tr(e) {
1932
+ if (!Y(e)) return null;
1933
+ let t = Number(e);
1934
+ return Number.isFinite(t) ? t : null;
1935
+ }
1936
+ //#endregion
1937
+ //#region src/core/message-blocks.ts
1938
+ function nr(e) {
1939
+ return typeof e == "object" && !!e && !Array.isArray(e);
1940
+ }
1941
+ function X(e) {
1942
+ if (!e) return;
1943
+ let t = e.trim();
1944
+ if (!(!t || t[0] !== "{")) try {
1945
+ let e = JSON.parse(t);
1946
+ return Array.isArray(e.blocks) ? e.blocks.filter((e) => nr(e) && typeof e.type == "string") : void 0;
1947
+ } catch {
1948
+ return;
1949
+ }
1950
+ }
1951
+ function rr(e) {
1952
+ return e?.length ? e.map((e) => e.type === "text" && typeof e.content == "string" ? e.content : "").join("") : "";
1953
+ }
1954
+ function ir(e, t) {
1955
+ let n = "";
1956
+ for (let e of t) e.type === "text" && typeof e.content == "string" && (n += e.content);
1957
+ if (!n) return e;
1958
+ let r = [...e], i = r[r.length - 1];
1959
+ return i?.type === "text" && typeof i.content == "string" ? (r[r.length - 1] = {
1960
+ ...i,
1961
+ content: `${i.content}${n}`
1962
+ }, r) : (r.push({
1963
+ type: "text",
1964
+ format: "markdown",
1965
+ content: n
1966
+ }), r);
1967
+ }
1968
+ var ar = new Set([
1969
+ "table",
1970
+ "chart",
1971
+ "metric",
1972
+ "list",
1973
+ "image",
1974
+ "alert"
1975
+ ]);
1976
+ function or(e) {
1977
+ return e.filter((e) => e.type !== "text" || typeof e.content != "string" || !e.content.trimStart().startsWith("{") ? !0 : !X(e.content));
1978
+ }
1979
+ function sr(e) {
1980
+ let t = e.trim().split("\n").filter((e) => e.trim().length > 0);
1981
+ return t.length < 2 ? !1 : t.slice(0, 3).some((e) => e.includes("|"));
1982
+ }
1983
+ function cr(e, t) {
1984
+ let n = typeof t.id == "string" ? t.id.trim() : "";
1985
+ if (n) {
1986
+ let r = e.findIndex((e) => e.id === n);
1987
+ if (r >= 0) {
1988
+ let i = [...e];
1989
+ return i[r] = {
1990
+ ...t,
1991
+ id: n
1992
+ }, i;
1993
+ }
1994
+ return [...e, {
1995
+ ...t,
1996
+ id: n
1997
+ }];
1998
+ }
1999
+ if (ar.has(t.type)) {
2000
+ let n = e.findIndex((e) => e.type === t.type);
2001
+ if (n >= 0) {
2002
+ let r = [...e];
2003
+ return r[n] = t, r;
2004
+ }
2005
+ }
2006
+ return [...e, t];
2007
+ }
2008
+ function lr(e, t) {
2009
+ let n = [...e];
2010
+ t.some((e) => e.type !== "text" && e.type !== "loading") && (n = or(n));
2011
+ let r = n.some((e) => ar.has(e.type)), i = !1;
2012
+ for (let e of t) {
2013
+ if (e.type === "text") {
2014
+ i = !0;
2015
+ let t = typeof e.content == "string" ? e.content : "";
2016
+ if (!t || n.some((e) => e.type === "text" && typeof e.content == "string") || r && sr(t)) continue;
2017
+ n.push({
2018
+ ...e,
2019
+ content: t
2020
+ });
2021
+ continue;
2022
+ }
2023
+ n = cr(n, e);
2024
+ }
2025
+ return !i && t.length === 0 ? e : n;
2026
+ }
2027
+ function ur(e, t) {
2028
+ return ir(e, t);
2029
+ }
2030
+ function dr(e) {
2031
+ let t = "";
2032
+ for (let n = 0; n < e.length; n += 1) {
2033
+ let r = e[n];
2034
+ if (r !== "\\") {
2035
+ t += r;
2036
+ continue;
2037
+ }
2038
+ let i = e[n + 1];
2039
+ if (i === void 0) {
2040
+ t += r;
2041
+ break;
2042
+ }
2043
+ switch (i) {
2044
+ case "n":
2045
+ t += "\n";
2046
+ break;
2047
+ case "t":
2048
+ t += " ";
2049
+ break;
2050
+ case "r":
2051
+ t += "\r";
2052
+ break;
2053
+ case "\"":
2054
+ t += "\"";
2055
+ break;
2056
+ case "\\":
2057
+ t += "\\";
2058
+ break;
2059
+ default:
2060
+ t += i;
2061
+ break;
2062
+ }
2063
+ n += 1;
2064
+ }
2065
+ return t;
2066
+ }
2067
+ function fr(e) {
2068
+ let t = e.trimStart();
2069
+ return t.startsWith("{") ? /"blocks"/.test(t) : !1;
2070
+ }
2071
+ var pr = /"type"\s*:\s*"text"\s*,\s*"content"\s*:\s*"/;
2072
+ function mr(e) {
2073
+ if (!fr(e)) return;
2074
+ let t = X(e);
2075
+ if (t) return rr(t);
2076
+ let n = pr.exec(e);
2077
+ if (!n) return null;
2078
+ let r = n.index + n[0].length, i = "";
2079
+ for (; r < e.length;) {
2080
+ let t = e[r];
2081
+ if (t === "\\") {
2082
+ if (r + 1 >= e.length) {
2083
+ i += t;
2084
+ break;
2085
+ }
2086
+ i += e.slice(r, r + 2), r += 2;
2087
+ continue;
2088
+ }
2089
+ if (t === "\"") break;
2090
+ i += t, r += 1;
2091
+ }
2092
+ return dr(i);
2093
+ }
2094
+ function hr(e) {
2095
+ if (e.length !== 1) return e;
2096
+ let t = e[0];
2097
+ if (t?.type !== "text" || typeof t.content != "string") return e;
2098
+ let n = X(t.content);
2099
+ if (n && n.length > 0) return n;
2100
+ let r = mr(t.content);
2101
+ return r === void 0 ? e : [{
2102
+ type: "text",
2103
+ format: typeof t.format == "string" ? t.format : "markdown",
2104
+ content: r ?? ""
2105
+ }];
2106
+ }
2107
+ function gr(e, t) {
2108
+ if (!t.length) return e;
2109
+ let n = [...e];
2110
+ for (let e of t) {
2111
+ let t = e.replaceId.trim();
2112
+ if (!t) continue;
2113
+ let r = n.findIndex((e) => e.id === t);
2114
+ r >= 0 ? n[r] = {
2115
+ ...e.block,
2116
+ id: t
2117
+ } : n.push({
2118
+ ...e.block,
2119
+ id: t
2120
+ });
2121
+ }
2122
+ return n;
2123
+ }
2124
+ //#endregion
2125
+ //#region src/utils/sdk-version.ts
2126
+ var _r = "0.1.0";
2127
+ //#endregion
2128
+ //#region src/utils/id.ts
2129
+ function vr(e = "id") {
2130
+ let t = globalThis.crypto;
2131
+ return t?.randomUUID ? `${e}_${t.randomUUID().replace(/-/g, "").slice(0, 12)}` : `${e}_${Math.random().toString(36).slice(2, 14)}`;
2132
+ }
2133
+ //#endregion
2134
+ //#region src/core/instance.ts
2135
+ function yr(e) {
2136
+ return e.replace(/\/+$/, "");
2137
+ }
2138
+ function Z(e) {
2139
+ return e.trim().toLowerCase();
2140
+ }
2141
+ function br(e, t) {
2142
+ let n = new Set(e.map((e) => Z(e.sessionId))), r = [...e];
2143
+ for (let e of t) {
2144
+ let t = Z(e.sessionId);
2145
+ n.has(t) || (n.add(t), r.push(e));
2146
+ }
2147
+ return r;
2148
+ }
2149
+ function xr(e, t) {
2150
+ let n = new Set(e.map((e) => String(e.id))), r = [];
2151
+ for (let e of t) {
2152
+ let t = String(e.id);
2153
+ n.has(t) || (n.add(t), r.push(e));
2154
+ }
2155
+ return [...r, ...e];
2156
+ }
2157
+ function Q() {
2158
+ return {
2159
+ phase: "thinking",
2160
+ thinkText: "",
2161
+ resultText: ""
2162
+ };
2163
+ }
2164
+ function $(e, t, n = {}) {
2165
+ let r = (n.content?.type === "text" ? n.content.text : void 0) ?? (t.resultText || e.content.text), i = n.blocks ?? t.resultBlocks ?? e.blocks, a = X(r), o = a ?? hr(i ?? []), s = a ? rr(o) : r;
2166
+ return {
2167
+ ...e,
2168
+ ...n,
2169
+ status: n.status ?? "sent",
2170
+ content: {
2171
+ type: "text",
2172
+ text: s
2173
+ },
2174
+ blocks: o,
2175
+ thinkText: void 0,
2176
+ stream: void 0
2177
+ };
2178
+ }
2179
+ function Sr() {
2180
+ return typeof navigator < "u" && navigator.language ? navigator.language : "en";
2181
+ }
2182
+ function Cr() {
2183
+ return typeof window < "u" && window.location?.origin ? window.location.origin : "unknown://sdk";
2184
+ }
2185
+ var wr = class {
2186
+ constructor(e = vr("inst")) {
2187
+ a(this, "id", void 0), a(this, "bus", new Re()), a(this, "lifecycle", "uninitialized"), a(this, "state", null), a(this, "stateChangeListeners", /* @__PURE__ */ new Set()), a(this, "sessionEpoch", 0), a(this, "stateSnapshot", null), this.id = e;
2188
+ }
2189
+ async init(e) {
2190
+ if (this.state) {
2191
+ if (this.state.options.dsn === e.dsn) return typeof console < "u" && typeof console.warn == "function" && console.warn("[agent-chat] init() called twice with the same DSN — keeping existing instance state."), this;
2192
+ throw new o("ALREADY_INITIALIZED", "AgentChat is already initialized with a different DSN. Call destroy() first.");
2193
+ }
2194
+ if (!e || typeof e != "object") throw new o("INVALID_OPTIONS", "init(options): options object is required");
2195
+ let t = yr((e.baseUrl?.trim() || "http://localhost:3030").replace(/\s+/g, "")), n = l(e.dsn), r = x.getState().getAccessTokenForDsn(n), i = typeof e.accountToken == "string" && e.accountToken.trim() || typeof e.userAccessToken == "string" && e.userAccessToken.trim() || r || null, a = Hn({
2196
+ apiBase: t,
2197
+ defaultHeaders: {
2198
+ [c]: n,
2199
+ "X-Agent-Sdk-Version": _r,
2200
+ ...e.headers ?? {}
2201
+ }
2202
+ }), s = new Un(a), u = new qn(a), d = new $n(a), f = await s.authenticate(n, i), p = f.accessToken?.trim() ?? null;
2203
+ x.getState().setAuth(n, f), p && te(a, p);
2204
+ let m = new Gn(a, () => ({ dsn: this.state?.dsn ?? n })), ee = new er({ context: {
2205
+ sdkVersion: _r,
2206
+ origin: Cr(),
2207
+ locale: e.locale ?? Sr(),
2208
+ user: e.user ?? Tr(f.user)
2209
+ } });
2210
+ return this.state = {
2211
+ options: e,
2212
+ dsn: n,
2213
+ apiBaseUrl: t,
2214
+ http: a,
2215
+ auth: s,
2216
+ chat: u,
2217
+ agent: m,
2218
+ feedback: d,
2219
+ session: ee,
2220
+ abortControllers: /* @__PURE__ */ new Set(),
2221
+ isOpen: !1,
2222
+ isClientAuthenticated: !0,
2223
+ isLoggedIn: !!p,
2224
+ sessions: [],
2225
+ sessionsPage: 0,
2226
+ sessionsPageSize: 20,
2227
+ sessionsHasMore: !1,
2228
+ sessionsLoadingMore: !1,
2229
+ activeSessionId: null,
2230
+ activeSessionMessagesPage: 0,
2231
+ activeSessionMessagesHasMore: !1,
2232
+ sessionMessagesLoadingMore: !1,
2233
+ sessionMessagesPageSize: 20,
2234
+ sessionMessagesCache: /* @__PURE__ */ new Map(),
2235
+ agents: e.agents ? [...e.agents] : [],
2236
+ skills: [],
2237
+ selectedAgentId: e.defaultAgentId?.trim() ?? null,
2238
+ selectedSkillId: e.defaultSkillId?.trim() ?? null,
2239
+ agentsLoading: !1,
2240
+ skillsLoading: !1,
2241
+ agentsEmptyReason: null,
2242
+ userJwt: p,
2243
+ activeStreamAbort: null,
2244
+ activeStreamSessionId: null,
2245
+ activeStreamTargetMessageId: null,
2246
+ messages: [],
2247
+ lastError: null,
2248
+ writeConfirmation: null,
2249
+ downReasonTagsCache: null
2250
+ }, this.lifecycle = "initialized", this.stateSnapshot = null, this.applyStaticSkills(this.state), this.syncDefaultAgentSelection(this.state), e.onReady && this.bus.on("ready", e.onReady), queueMicrotask(() => this.bus.emit("ready", void 0)), e.autoOpen && this.open(), this;
2251
+ }
2252
+ async login(e) {
2253
+ let t = this.requireState("login"), n = e?.email?.trim(), r = e?.password?.trim();
2254
+ if (!n || !r) throw new o("INVALID_OPTIONS", "login requires email and password");
2255
+ let i;
2256
+ try {
2257
+ i = await t.auth.login(n, r);
2258
+ } catch (e) {
2259
+ throw e instanceof o && e.code === "TRANSPORT_FAILED" ? new o("LOGIN_FAILED", e.message, {
2260
+ cause: e,
2261
+ details: e.details
2262
+ }) : e;
2263
+ }
2264
+ x.getState().setAuth(t.dsn, i);
2265
+ let a = i.accessToken?.trim();
2266
+ if (!a) throw new o("LOGIN_FAILED", "Login succeeded but no access token was returned.");
2267
+ ne(t.http);
2268
+ let s = await t.auth.authenticate(t.dsn, a), c = s.accessToken?.trim();
2269
+ if (!c) throw new o("LOGIN_FAILED", "App client auth succeeded but accessToken is missing");
2270
+ x.getState().setAuth(t.dsn, s), te(t.http, c), t.userJwt = c, t.isLoggedIn = !0, this.notifyStateChange(), t.isOpen && this.refreshAgentCatalog().catch(() => {});
2271
+ }
2272
+ logout() {
2273
+ let e = this.state;
2274
+ e && (this.abortActiveStream(), e.isLoggedIn = !1, ne(e.http), x.getState().clearAuth(), e.session.reset(), e.sessions = [], e.sessionsPage = 0, e.sessionsHasMore = !1, e.sessionsLoadingMore = !1, e.activeSessionId = null, e.activeSessionMessagesPage = 0, e.activeSessionMessagesHasMore = !1, e.sessionMessagesLoadingMore = !1, e.sessionMessagesCache.clear(), e.agents = [], e.skills = [], e.selectedAgentId = null, e.selectedSkillId = null, e.agentsLoading = !1, e.skillsLoading = !1, e.agentsEmptyReason = null, e.userJwt = null, e.messages = [], this.notifyStateChange());
2275
+ }
2276
+ isLoggedIn() {
2277
+ return this.state?.isLoggedIn ?? !1;
2278
+ }
2279
+ destroy() {
2280
+ if (this.state) {
2281
+ this.abortActiveStream();
2282
+ for (let e of this.state.abortControllers) try {
2283
+ e.abort();
2284
+ } catch {}
2285
+ this.state.abortControllers.clear(), this.state.session.reset(), this.state.isOpen = !1, this.state = null, this.lifecycle = "destroyed", this.stateSnapshot = null, this.bus.emit("destroyed", void 0), this.bus.clear(), this.stateChangeListeners.clear();
2286
+ }
2287
+ }
2288
+ open() {
2289
+ let e = this.state;
2290
+ if (!e) {
2291
+ typeof console < "u" && console.warn("[agent-chat] open() called before init() (or after destroy()) — ignoring.");
2292
+ return;
2293
+ }
2294
+ e.isOpen || (e.isOpen = !0, this.notifyStateChange(), this.bus.emit("open", void 0), e.isLoggedIn && queueMicrotask(() => {
2295
+ this.state?.isOpen && this.prefetch().catch(() => {});
2296
+ }));
2297
+ }
2298
+ close() {
2299
+ let e = this.state;
2300
+ !e || !e.isOpen || (e.isOpen = !1, this.notifyStateChange(), this.bus.emit("close", void 0));
2301
+ }
2302
+ toggle() {
2303
+ this.isOpen() ? this.close() : this.open();
2304
+ }
2305
+ isOpen() {
2306
+ return this.state?.isOpen ?? !1;
2307
+ }
2308
+ identify(e) {
2309
+ let t = this.requireState("identify"), n = t.session.getSession();
2310
+ t.session.updateContext({ user: e });
2311
+ let r = t.options.user?.id;
2312
+ t.options = {
2313
+ ...t.options,
2314
+ user: e
2315
+ }, n && r && r !== e.id && (t.session.reset(), t.messages = [], this.notifyStateChange());
2316
+ }
2317
+ async prefetch() {
2318
+ let e = this.requireState("prefetch");
2319
+ this.requireLoggedIn("prefetch");
2320
+ let t = this.makeAbortController();
2321
+ try {
2322
+ if (await Promise.all([this.refreshSessions(t.signal), this.refreshAgentCatalog(t.signal)]), !e.sessions.length) return;
2323
+ let n = e.activeSessionId && e.sessions.some((t) => t.sessionId === e.activeSessionId) ? e.activeSessionId : e.sessions[0].sessionId;
2324
+ await this.selectSession(n, {
2325
+ signal: t.signal,
2326
+ skipAbortStream: !0
2327
+ });
2328
+ } finally {
2329
+ e.abortControllers.delete(t);
2330
+ }
2331
+ }
2332
+ async selectSession(e, t = {}) {
2333
+ let n = this.requireState("selectSession");
2334
+ this.requireLoggedIn("selectSession");
2335
+ let r = e.trim();
2336
+ if (!r) throw new o("INVALID_OPTIONS", "selectSession: sessionId is required");
2337
+ let i = this.sessionEpoch;
2338
+ t.skipAbortStream || this.abortActiveStream(), n.activeSessionId && n.activeSessionId !== r && this.writeSessionMessagesCache(n, n.activeSessionId), n.writeConfirmation = null;
2339
+ let a = n.sessionMessagesCache.get(r);
2340
+ if (a) {
2341
+ i === this.sessionEpoch && (n.activeSessionId = r, n.messages = a.messages, n.activeSessionMessagesPage = a.page, n.activeSessionMessagesHasMore = a.hasMore, n.session.setSession(r, a.messages), this.notifyStateChange(), this.bus.emit("session", n.session.getSession()), t.signal?.aborted || (this.ensureSessionStream(r).catch(() => {}), this.syncMessageFeedbacks(n, r).catch(() => {})));
2342
+ return;
2343
+ }
2344
+ let s = this.makeAbortController(), c = t.signal;
2345
+ c && c.addEventListener("abort", () => s.abort(), { once: !0 });
2346
+ try {
2347
+ let e = await this.fetchSessionMessagesPage(n, r, 1, s.signal), a = e.messages.map((e) => this.toAgentMessage(e)), o = {
2348
+ messages: a,
2349
+ page: e.page,
2350
+ hasMore: e.hasMore
2351
+ };
2352
+ if (n.sessionMessagesCache.set(r, o), i !== this.sessionEpoch) return;
2353
+ n.activeSessionId = r, n.activeSessionMessagesPage = e.page, n.activeSessionMessagesHasMore = e.hasMore, n.session.setSession(e.sessionId, a), n.messages = a, this.notifyStateChange(), this.bus.emit("session", n.session.getSession()), t.signal?.aborted || (this.ensureSessionStream(r).catch(() => {}), this.syncMessageFeedbacks(n, r).catch(() => {}));
2354
+ } finally {
2355
+ n.abortControllers.delete(s);
2356
+ }
2357
+ }
2358
+ async sendMessage(e, t = {}) {
2359
+ let n = this.requireState("sendMessage");
2360
+ this.requireLoggedIn("sendMessage");
2361
+ let r = e.trim();
2362
+ if (r.length === 0) throw new o("INVALID_OPTIONS", "sendMessage: text must not be empty");
2363
+ this.sessionEpoch += 1, this.settlePendingAgentReplies(n), n.writeConfirmation = null;
2364
+ let i = this.appendOptimisticUserMessage(n, r, t.id);
2365
+ n.activeStreamTargetMessageId = this.appendAgentPlaceholder(n).id;
2366
+ let a = this.makeAbortController();
2367
+ try {
2368
+ let e = n.activeSessionId ?? n.session.getSession()?.sessionId ?? null;
2369
+ if (!e) return e = await this.createChatSession(n, r, a.signal), this.refreshSessions(a.signal).catch(() => {}), await this.ensureSessionStream(e), this.applyUserMessageSent(n, i);
2370
+ let t = await this.postUserMessageAndApply(n, e, r, a.signal, i);
2371
+ return await this.ensureSessionStream(e), t;
2372
+ } catch (e) {
2373
+ let t = {
2374
+ ...i,
2375
+ status: "failed"
2376
+ };
2377
+ n.messages = n.messages.map((e) => e.id === i.id ? t : e), this.cacheActiveSessionMessages(n), this.notifyStateChange();
2378
+ let r = e instanceof o ? new o("MESSAGE_FAILED", e.message, {
2379
+ cause: e,
2380
+ details: {
2381
+ ...e.details ?? {},
2382
+ messageId: i.id
2383
+ }
2384
+ }) : new o("MESSAGE_FAILED", "Failed to send message", {
2385
+ cause: e,
2386
+ details: { messageId: i.id }
2387
+ });
2388
+ throw this.reportError(r), r;
2389
+ } finally {
2390
+ n.abortControllers.delete(a);
2391
+ }
2392
+ }
2393
+ async confirmWrite() {
2394
+ let e = this.requireState("confirmWrite");
2395
+ this.requireLoggedIn("confirmWrite");
2396
+ let t = e.writeConfirmation;
2397
+ if (!t?.awaiting) throw new o("INVALID_OPTIONS", "No pending write confirmation");
2398
+ let n = e.activeSessionId ?? e.session.getSession()?.sessionId ?? null;
2399
+ if (!n) throw new o("INVALID_OPTIONS", "confirmWrite: no active session");
2400
+ e.writeConfirmation = {
2401
+ ...t,
2402
+ awaiting: !1,
2403
+ submitting: !0
2404
+ }, this.notifyStateChange(), e.activeStreamTargetMessageId = this.appendAgentPlaceholder(e).id;
2405
+ let r = this.makeAbortController();
2406
+ try {
2407
+ await this.postWriteConfirmationAction(e, n, { confirmWrite: !0 }, r.signal);
2408
+ } catch (n) {
2409
+ e.writeConfirmation = {
2410
+ ...t,
2411
+ awaiting: !0,
2412
+ submitting: !1
2413
+ }, this.notifyStateChange();
2414
+ let r = n instanceof o ? n : new o("MESSAGE_FAILED", "Failed to confirm write operation", { cause: n });
2415
+ throw this.reportError(r), r;
2416
+ } finally {
2417
+ e.abortControllers.delete(r);
2418
+ }
2419
+ }
2420
+ async cancelWrite() {
2421
+ let e = this.requireState("cancelWrite");
2422
+ this.requireLoggedIn("cancelWrite");
2423
+ let t = e.writeConfirmation;
2424
+ if (!t?.awaiting) throw new o("INVALID_OPTIONS", "No pending write confirmation");
2425
+ let n = e.activeSessionId ?? e.session.getSession()?.sessionId ?? null;
2426
+ if (!n) throw new o("INVALID_OPTIONS", "cancelWrite: no active session");
2427
+ e.writeConfirmation = {
2428
+ ...t,
2429
+ awaiting: !1,
2430
+ submitting: !0
2431
+ }, this.notifyStateChange();
2432
+ let r = this.makeAbortController();
2433
+ try {
2434
+ await this.postWriteConfirmationAction(e, n, { cancelWrite: !0 }, r.signal);
2435
+ } catch (n) {
2436
+ e.writeConfirmation = {
2437
+ ...t,
2438
+ awaiting: !0,
2439
+ submitting: !1
2440
+ }, this.notifyStateChange();
2441
+ let r = n instanceof o ? n : new o("MESSAGE_FAILED", "Failed to cancel write operation", { cause: n });
2442
+ throw this.reportError(r), r;
2443
+ } finally {
2444
+ e.abortControllers.delete(r);
2445
+ }
2446
+ }
2447
+ async getDownReasonTags() {
2448
+ let e = this.requireState("getDownReasonTags");
2449
+ if (this.requireLoggedIn("getDownReasonTags"), e.downReasonTagsCache) return e.downReasonTagsCache;
2450
+ let t = await e.feedback.getDownReasonTags();
2451
+ return e.downReasonTagsCache = t, t;
2452
+ }
2453
+ async submitMessageFeedback(e, t) {
2454
+ let n = this.requireState("submitMessageFeedback");
2455
+ this.requireLoggedIn("submitMessageFeedback");
2456
+ let r = n.activeSessionId ?? n.session.getSession()?.sessionId ?? null;
2457
+ if (!r) throw new o("INVALID_OPTIONS", "submitMessageFeedback: no active session");
2458
+ let i = tr(e);
2459
+ if (i === null) throw new o("INVALID_OPTIONS", "submitMessageFeedback: invalid messageId");
2460
+ let a = n.messages.find((t) => t.id === e);
2461
+ if (!a || a.role !== "agent") throw new o("INVALID_OPTIONS", "submitMessageFeedback: not an assistant message");
2462
+ let s = a.feedback ?? null, c = this.buildOptimisticFeedback(i, t);
2463
+ this.patchMessageFeedback(n, e, c);
2464
+ try {
2465
+ let a = await n.feedback.upsert(r, i, t);
2466
+ this.patchMessageFeedback(n, e, a);
2467
+ } catch (t) {
2468
+ this.patchMessageFeedback(n, e, s);
2469
+ let r = t instanceof o ? t : new o("MESSAGE_FAILED", "Failed to submit feedback", { cause: t });
2470
+ throw this.reportError(r), r;
2471
+ }
2472
+ }
2473
+ async removeMessageFeedback(e) {
2474
+ let t = this.requireState("removeMessageFeedback");
2475
+ this.requireLoggedIn("removeMessageFeedback");
2476
+ let n = t.activeSessionId ?? t.session.getSession()?.sessionId ?? null;
2477
+ if (!n) throw new o("INVALID_OPTIONS", "removeMessageFeedback: no active session");
2478
+ let r = tr(e);
2479
+ if (r === null) throw new o("INVALID_OPTIONS", "removeMessageFeedback: invalid messageId");
2480
+ let i = t.messages.find((t) => t.id === e);
2481
+ if (!i || i.role !== "agent") throw new o("INVALID_OPTIONS", "removeMessageFeedback: not an assistant message");
2482
+ let a = i.feedback ?? null;
2483
+ this.patchMessageFeedback(t, e, null);
2484
+ try {
2485
+ await t.feedback.remove(n, r);
2486
+ } catch (n) {
2487
+ this.patchMessageFeedback(t, e, a);
2488
+ let r = n instanceof o ? n : new o("MESSAGE_FAILED", "Failed to remove feedback", { cause: n });
2489
+ throw this.reportError(r), r;
2490
+ }
2491
+ }
2492
+ getOptions() {
2493
+ return this.state?.options ?? null;
2494
+ }
2495
+ getState() {
2496
+ return this.stateSnapshot || (this.state ? this.stateSnapshot = {
2497
+ lifecycle: this.lifecycle,
2498
+ isOpen: this.state.isOpen,
2499
+ isClientAuthenticated: this.state.isClientAuthenticated,
2500
+ isLoggedIn: this.state.isLoggedIn,
2501
+ session: this.state.session.getSession(),
2502
+ sessions: this.state.sessions,
2503
+ sessionsHasMore: this.state.sessionsHasMore,
2504
+ sessionsLoadingMore: this.state.sessionsLoadingMore,
2505
+ activeSessionId: this.state.activeSessionId,
2506
+ messages: [...this.state.messages],
2507
+ sessionMessagesHasMore: this.state.activeSessionMessagesHasMore,
2508
+ sessionMessagesLoadingMore: this.state.sessionMessagesLoadingMore,
2509
+ agents: [...this.state.agents],
2510
+ skills: [...this.state.skills],
2511
+ selectedAgentId: this.state.selectedAgentId,
2512
+ selectedSkillId: this.state.selectedSkillId,
2513
+ agentsLoading: this.state.agentsLoading,
2514
+ skillsLoading: this.state.skillsLoading,
2515
+ agentsEmptyReason: this.state.agentsEmptyReason,
2516
+ lastError: this.state.lastError,
2517
+ writeConfirmation: this.state.writeConfirmation
2518
+ } : this.stateSnapshot = {
2519
+ lifecycle: this.lifecycle,
2520
+ isOpen: !1,
2521
+ isClientAuthenticated: !1,
2522
+ isLoggedIn: !1,
2523
+ session: null,
2524
+ sessions: [],
2525
+ sessionsHasMore: !1,
2526
+ sessionsLoadingMore: !1,
2527
+ activeSessionId: null,
2528
+ messages: [],
2529
+ sessionMessagesHasMore: !1,
2530
+ sessionMessagesLoadingMore: !1,
2531
+ agents: [],
2532
+ skills: [],
2533
+ selectedAgentId: null,
2534
+ selectedSkillId: null,
2535
+ agentsLoading: !1,
2536
+ skillsLoading: !1,
2537
+ agentsEmptyReason: null,
2538
+ lastError: null,
2539
+ writeConfirmation: null
2540
+ }), this.stateSnapshot;
2541
+ }
2542
+ on(e, t) {
2543
+ return this.bus.on(e, t);
2544
+ }
2545
+ off(e, t) {
2546
+ this.bus.off(e, t);
2547
+ }
2548
+ subscribeStateChange(e) {
2549
+ return this.stateChangeListeners.add(e), () => this.stateChangeListeners.delete(e);
2550
+ }
2551
+ appendMessage(e) {
2552
+ let t = this.state;
2553
+ t && (t.messages = [...t.messages, e], this.notifyStateChange(), this.bus.emit("message", {
2554
+ message: e,
2555
+ source: e.role
2556
+ }));
2557
+ }
2558
+ notifyStateChange() {
2559
+ this.stateSnapshot = null;
2560
+ for (let e of Array.from(this.stateChangeListeners)) try {
2561
+ e();
2562
+ } catch (e) {
2563
+ this.state?.options.debug && console.error("[agent-chat] state listener threw:", e);
2564
+ }
2565
+ }
2566
+ reportError(e) {
2567
+ let t = {
2568
+ code: e.code,
2569
+ message: e.message,
2570
+ cause: e.cause
2571
+ };
2572
+ this.state && (this.state.lastError = t, this.notifyStateChange()), this.state?.options.debug && typeof console < "u" && (console.error("[agent-chat]", e), this.bus.listenerCount("error") === 0 && console.warn("[agent-chat] Unhandled AgentChat error (no `error` listeners attached)")), this.bus.emit("error", t);
2573
+ }
2574
+ requireState(e) {
2575
+ if (!this.state) throw new o("NOT_INITIALIZED", `AgentChat.${e}() called before init(). Call AgentChat.init({ dsn }) first.`);
2576
+ return this.state;
2577
+ }
2578
+ requireLoggedIn(e) {
2579
+ let t = this.state;
2580
+ if (!(!t || t.isLoggedIn)) throw new o("AUTH_REQUIRED", `AgentChat.${e}() requires authentication. Call init() and ensure /app-client/auth succeeds.`);
2581
+ }
2582
+ makeAbortController() {
2583
+ let e = new AbortController();
2584
+ return this.state?.abortControllers.add(e), e;
2585
+ }
2586
+ async prepareSession(e, t) {
2587
+ let n = this.requireState("prepareSession");
2588
+ this.requireLoggedIn("prepareSession");
2589
+ let r = e.trim();
2590
+ if (r) try {
2591
+ await n.chat.prepareSession(r, t);
2592
+ } catch (e) {
2593
+ if (t?.aborted) return;
2594
+ n.options.debug && console.warn("[agent-chat] prepareSession failed:", e);
2595
+ }
2596
+ }
2597
+ async deleteSession(e) {
2598
+ let t = this.requireState("deleteSession");
2599
+ this.requireLoggedIn("deleteSession");
2600
+ let n = e.trim();
2601
+ if (!n) throw new o("INVALID_OPTIONS", "deleteSession: sessionId is required");
2602
+ let r = Z(n), i = t.activeSessionId != null && Z(t.activeSessionId) === r;
2603
+ i && (this.sessionEpoch += 1, this.abortActiveStream(), this.settlePendingAgentReplies(t), t.activeSessionId = null, t.activeSessionMessagesPage = 0, t.activeSessionMessagesHasMore = !1, t.session.reset(), t.messages = [], t.writeConfirmation = null);
2604
+ for (let e of [...t.sessionMessagesCache.keys()]) Z(e) === r && t.sessionMessagesCache.delete(e);
2605
+ try {
2606
+ await t.chat.deleteSession(n), await this.refreshSessions();
2607
+ } catch (e) {
2608
+ let t = e instanceof o ? e : new o("TRANSPORT_FAILED", "Failed to delete session", { cause: e });
2609
+ throw this.reportError(t), t;
2610
+ }
2611
+ if (i) {
2612
+ let e = t.sessions[0];
2613
+ e && await this.selectSession(e.sessionId);
2614
+ }
2615
+ }
2616
+ async refreshSessions(e) {
2617
+ let t = this.requireState("refreshSessions");
2618
+ this.requireLoggedIn("refreshSessions");
2619
+ let n = await this.fetchSessionsPage(t, 1, e);
2620
+ t.sessions = n.sessions, t.sessionsPage = n.page, t.sessionsHasMore = n.hasMore, t.sessionsLoadingMore = !1, this.notifyStateChange(), this.bus.emit("sessions", { sessions: t.sessions });
2621
+ }
2622
+ async loadMoreSessions(e) {
2623
+ let t = this.requireState("loadMoreSessions");
2624
+ if (this.requireLoggedIn("loadMoreSessions"), !(!t.sessionsHasMore || t.sessionsLoadingMore)) {
2625
+ t.sessionsLoadingMore = !0, this.notifyStateChange();
2626
+ try {
2627
+ let n = await this.fetchSessionsPage(t, t.sessionsPage + 1, e);
2628
+ t.sessions = br(t.sessions, n.sessions), t.sessionsPage = n.page, t.sessionsHasMore = n.hasMore, this.bus.emit("sessions", { sessions: t.sessions });
2629
+ } finally {
2630
+ t.sessionsLoadingMore = !1, this.notifyStateChange();
2631
+ }
2632
+ }
2633
+ }
2634
+ async fetchSessionsPage(e, t, n) {
2635
+ return fe(await e.chat.listSessions(t, e.sessionsPageSize, n), t, e.sessionsPageSize);
2636
+ }
2637
+ async loadMoreSessionMessages(e) {
2638
+ let t = this.requireState("loadMoreSessionMessages");
2639
+ this.requireLoggedIn("loadMoreSessionMessages");
2640
+ let n = t.activeSessionId;
2641
+ if (!(!n || !t.activeSessionMessagesHasMore || t.sessionMessagesLoadingMore)) {
2642
+ t.sessionMessagesLoadingMore = !0, this.notifyStateChange();
2643
+ try {
2644
+ let r = await this.fetchSessionMessagesPage(t, n, t.activeSessionMessagesPage + 1, e), i = r.messages.map((e) => this.toAgentMessage(e)), a = xr(t.messages, i);
2645
+ t.messages = a, t.activeSessionMessagesPage = r.page, t.activeSessionMessagesHasMore = r.hasMore, t.session.setSession(n, a), this.writeSessionMessagesCache(t, n, a, r.page, r.hasMore), this.notifyStateChange(), this.syncMessageFeedbacks(t, n).catch(() => {});
2646
+ } finally {
2647
+ t.sessionMessagesLoadingMore = !1, this.notifyStateChange();
2648
+ }
2649
+ }
2650
+ }
2651
+ async selectAgent(e) {
2652
+ let t = this.requireState("selectAgent");
2653
+ this.requireLoggedIn("selectAgent");
2654
+ let n = e.trim();
2655
+ !n || t.selectedAgentId === n || (t.selectedAgentId = n, t.selectedSkillId = null, this.notifyStateChange(), await this.refreshSkills(n));
2656
+ }
2657
+ selectSkill(e) {
2658
+ let t = this.requireState("selectSkill"), n = e.trim();
2659
+ if (!n) {
2660
+ if (t.selectedSkillId == null) return;
2661
+ t.selectedSkillId = null, this.notifyStateChange();
2662
+ return;
2663
+ }
2664
+ t.selectedSkillId !== n && (t.selectedSkillId = n, this.notifyStateChange());
2665
+ }
2666
+ async refreshAgentCatalog(e) {
2667
+ let t = this.requireState("refreshAgentCatalog");
2668
+ if (t.options.agents?.length) {
2669
+ t.agents = [...t.options.agents], t.agentsEmptyReason = null, this.syncDefaultAgentSelection(t), t.options.skills?.length || await this.refreshSkills(t.selectedAgentId ?? void 0, e);
2670
+ return;
2671
+ }
2672
+ if (t.userJwt) {
2673
+ t.agentsLoading = !0, t.agentsEmptyReason = null, this.notifyStateChange();
2674
+ try {
2675
+ let n = xe(await t.agent.listAvailableAgents(t.options.agentListQuery, e));
2676
+ t.agents = n, n.length === 0 && (t.agentsEmptyReason = await this.resolveAgentsEmptyReason(t, e)), this.syncDefaultAgentSelection(t), await this.refreshSkills(t.selectedAgentId ?? void 0, e);
2677
+ } catch {
2678
+ t.agents = [], t.agentsEmptyReason = null, this.applyStaticSkills(t);
2679
+ } finally {
2680
+ t.agentsLoading = !1, this.notifyStateChange();
2681
+ }
2682
+ }
2683
+ }
2684
+ async resolveAgentsEmptyReason(e, t) {
2685
+ try {
2686
+ return xe(await e.agent.listAllClientAgents(t)).length > 0 ? "permission" : "not_configured";
2687
+ } catch {
2688
+ return null;
2689
+ }
2690
+ }
2691
+ async refreshSkills(e, t) {
2692
+ let n = this.requireState("refreshSkills"), r = e?.trim() || n.selectedAgentId || void 0;
2693
+ if (n.options.skills?.length) {
2694
+ n.skills = r ? n.options.skills.filter((e) => !e.agentId || e.agentId === r) : [...n.options.skills], this.syncDefaultSkillSelection(n), this.notifyStateChange();
2695
+ return;
2696
+ }
2697
+ if (!r) {
2698
+ n.skills = [], n.selectedSkillId = null, this.notifyStateChange();
2699
+ return;
2700
+ }
2701
+ n.skillsLoading = !0, this.notifyStateChange();
2702
+ try {
2703
+ n.skills = De(await n.agent.listClientSkills(r, n.options.skillListQuery, t)), this.syncDefaultSkillSelection(n);
2704
+ } catch {
2705
+ n.skills = [], n.selectedSkillId = null;
2706
+ } finally {
2707
+ n.skillsLoading = !1, this.notifyStateChange();
2708
+ }
2709
+ }
2710
+ applyStaticSkills(e) {
2711
+ let t = e.options.skills;
2712
+ if (!t?.length) return;
2713
+ let n = e.selectedAgentId;
2714
+ e.skills = n ? t.filter((e) => !e.agentId || e.agentId === n) : [...t], this.syncDefaultSkillSelection(e);
2715
+ }
2716
+ syncDefaultAgentSelection(e) {
2717
+ e.selectedAgentId ? e.agents.some((t) => t.id === e.selectedAgentId) || (e.selectedAgentId = e.agents[0]?.id ?? e.selectedAgentId) : e.agents.length && (e.selectedAgentId = e.agents[0].id), this.applyStaticSkills(e);
2718
+ }
2719
+ syncDefaultSkillSelection(e) {
2720
+ let t = e.options.defaultSkillId?.trim();
2721
+ if (!(e.selectedSkillId && e.skills.some((t) => t.id === e.selectedSkillId))) {
2722
+ if (t && e.skills.some((e) => e.id === t)) {
2723
+ e.selectedSkillId = t;
2724
+ return;
2725
+ }
2726
+ e.selectedSkillId = e.skills[0]?.id ?? null;
2727
+ }
2728
+ }
2729
+ getMessageSendContext(e) {
2730
+ let t = e.selectedAgentId?.trim(), n = e.selectedSkillId?.trim();
2731
+ if (!(!t && !n)) return {
2732
+ agentId: t || void 0,
2733
+ skillId: n || void 0
2734
+ };
2735
+ }
2736
+ async fetchSessionMessagesPage(e, t, n, r) {
2737
+ let i = he(await e.chat.getSession(t, n, e.sessionMessagesPageSize, r), t, n, e.sessionMessagesPageSize);
2738
+ if (!i) throw new o("TRANSPORT_FAILED", "Invalid session detail response", { details: {
2739
+ sessionId: t,
2740
+ page: n
2741
+ } });
2742
+ return i;
2743
+ }
2744
+ startNewChat() {
2745
+ let e = this.requireState("startNewChat");
2746
+ this.requireLoggedIn("startNewChat"), this.sessionEpoch += 1, this.abortActiveStream(), e.activeSessionId && this.writeSessionMessagesCache(e, e.activeSessionId), e.activeSessionId = null, e.activeSessionMessagesPage = 0, e.activeSessionMessagesHasMore = !1, e.session.reset(), e.messages = [], e.writeConfirmation = null, this.notifyStateChange();
2747
+ }
2748
+ cancelGeneration() {
2749
+ this.abortActiveStream();
2750
+ }
2751
+ abortActiveStream() {
2752
+ let e = this.state;
2753
+ if (e?.activeStreamAbort) {
2754
+ try {
2755
+ e.activeStreamAbort.abort();
2756
+ } catch {}
2757
+ e.activeStreamAbort = null, e.activeStreamSessionId = null, e.activeStreamTargetMessageId = null;
2758
+ }
2759
+ }
2760
+ async ensureSessionStream(e) {
2761
+ let t = this.requireState("ensureSessionStream"), n = Z(e);
2762
+ if (t.activeStreamAbort && t.activeStreamSessionId === n) return;
2763
+ this.abortActiveStream();
2764
+ let r = new AbortController();
2765
+ await this.connectSessionStream(n, r);
2766
+ }
2767
+ writeSessionMessagesCache(e, t, n = e.messages, r = e.activeSessionMessagesPage, i = e.activeSessionMessagesHasMore) {
2768
+ e.sessionMessagesCache.set(t, {
2769
+ messages: n,
2770
+ page: r,
2771
+ hasMore: i
2772
+ });
2773
+ }
2774
+ cacheActiveSessionMessages(e) {
2775
+ e.activeSessionId && this.writeSessionMessagesCache(e, e.activeSessionId);
2776
+ }
2777
+ settlePendingAgentReplies(e) {
2778
+ let t = [], n = !1;
2779
+ for (let r of e.messages) {
2780
+ if (r.role !== "agent" || r.status !== "pending") {
2781
+ t.push(r);
2782
+ continue;
2783
+ }
2784
+ n = !0;
2785
+ let e = r.stream ?? Q();
2786
+ (e.resultText || r.content.text).trim() && t.push($(r, e, { status: "sent" }));
2787
+ }
2788
+ n && (e.messages = t, this.cacheActiveSessionMessages(e), this.notifyStateChange());
2789
+ }
2790
+ removeAgentMessage(e, t) {
2791
+ let n = e.messages.filter((e) => e.id !== t);
2792
+ n.length !== e.messages.length && (e.messages = n, this.cacheActiveSessionMessages(e), this.notifyStateChange());
2793
+ }
2794
+ patchMessageById(e, t, n) {
2795
+ let r = e.messages.find((e) => e.id === t);
2796
+ if (!r) return null;
2797
+ let i = n(r);
2798
+ return e.messages = e.messages.map((e) => e.id === t ? i : e), this.cacheActiveSessionMessages(e), this.notifyStateChange(), this.bus.emit("message", {
2799
+ message: i,
2800
+ source: i.role === "user" ? "user" : "agent"
2801
+ }), i;
2802
+ }
2803
+ isExistingSentAssistantText(e, t, n) {
2804
+ let r = t.trim();
2805
+ return r ? e.messages.some((e) => e.role === "agent" && e.id !== n && e.status === "sent" && e.content.text.trim() === r) : !1;
2806
+ }
2807
+ resolveStreamTargetMessageId(e, t) {
2808
+ if (t) return t;
2809
+ let n = e.activeStreamTargetMessageId;
2810
+ if (n && e.messages.some((e) => e.id === n)) return n;
2811
+ for (let t = e.messages.length - 1; t >= 0; --t) {
2812
+ let n = e.messages[t];
2813
+ if (n?.role === "agent" && (n.status ?? "pending") === "pending") return e.activeStreamTargetMessageId = n.id, n.id;
2814
+ }
2815
+ return null;
2816
+ }
2817
+ appendAgentPlaceholder(e) {
2818
+ let t = {
2819
+ id: vr("msg"),
2820
+ role: "agent",
2821
+ content: {
2822
+ type: "text",
2823
+ text: ""
2824
+ },
2825
+ createdAt: Date.now(),
2826
+ status: "pending",
2827
+ stream: Q()
2828
+ };
2829
+ return e.messages = [...e.messages, t], this.cacheActiveSessionMessages(e), this.notifyStateChange(), this.bus.emit("message", {
2830
+ message: t,
2831
+ source: "agent"
2832
+ }), t;
2833
+ }
2834
+ appendOptimisticUserMessage(e, t, n) {
2835
+ let r = {
2836
+ id: n ?? vr("msg"),
2837
+ role: "user",
2838
+ content: {
2839
+ type: "text",
2840
+ text: t
2841
+ },
2842
+ createdAt: Date.now(),
2843
+ status: "pending"
2844
+ };
2845
+ return e.messages = [...e.messages, r], this.cacheActiveSessionMessages(e), this.notifyStateChange(), this.bus.emit("message", {
2846
+ message: r,
2847
+ source: "user"
2848
+ }), r;
2849
+ }
2850
+ async createChatSession(e, t, n) {
2851
+ let r = await e.chat.createSession(t, n, this.getMessageSendContext(e)), i = ge(r);
2852
+ if (!i?.sessionId) throw new o("TRANSPORT_FAILED", "POST /chat did not return sessionId", { details: { body: r } });
2853
+ return e.activeSessionId = i.sessionId, e.activeSessionMessagesPage = 1, e.activeSessionMessagesHasMore = !1, e.session.setSession(i.sessionId, e.messages), this.writeSessionMessagesCache(e, i.sessionId), this.bus.emit("session", e.session.getSession()), i.sessionId;
2854
+ }
2855
+ applyUserMessageSent(e, t) {
2856
+ let n = {
2857
+ ...t,
2858
+ status: "sent"
2859
+ };
2860
+ return e.messages = e.messages.map((e) => e.id === t.id ? n : e), this.cacheActiveSessionMessages(e), this.notifyStateChange(), this.bus.emit("message", {
2861
+ message: n,
2862
+ source: "user"
2863
+ }), n;
2864
+ }
2865
+ async postUserMessageAndApply(e, t, n, r, i) {
2866
+ let a = _e(await e.chat.postMessage(t, n, r, this.getMessageSendContext(e))), o = a ? {
2867
+ ...this.toAgentMessage(a),
2868
+ status: "sent"
2869
+ } : {
2870
+ ...i,
2871
+ status: "sent"
2872
+ };
2873
+ return e.messages = e.messages.map((e) => e.id === i.id ? o : e), this.cacheActiveSessionMessages(e), this.notifyStateChange(), this.bus.emit("message", {
2874
+ message: o,
2875
+ source: o.role
2876
+ }), o;
2877
+ }
2878
+ async postWriteConfirmationAction(e, t, n, r) {
2879
+ await e.chat.postWriteConfirmation(t, n, r);
2880
+ }
2881
+ connectSessionStream(e, t) {
2882
+ let n = this.requireState("connectSessionStream");
2883
+ return n.activeStreamAbort = t, n.activeStreamSessionId = Z(e), n.abortControllers.add(t), new Promise((r, i) => {
2884
+ let a = !1, o = () => {
2885
+ a || (a = !0, r());
2886
+ }, s = (e) => {
2887
+ a || (a = !0, i(e));
2888
+ };
2889
+ this.consumeSessionStream(e, t, o).catch((e) => {
2890
+ a || s(e);
2891
+ }).finally(() => {
2892
+ n.abortControllers.delete(t), n.activeStreamAbort === t && (n.activeStreamAbort = null, n.activeStreamSessionId = null);
2893
+ });
2894
+ });
2895
+ }
2896
+ async consumeSessionStream(e, t, n) {
2897
+ let r = this.requireState("consumeSessionStream"), i = (e) => e ? r.messages.find((t) => t.id === e) : void 0, a = (e, t) => {
2898
+ r.messages = r.messages.map((n) => n.id === t ? e : n), this.cacheActiveSessionMessages(r), this.notifyStateChange(), this.bus.emit("message", {
2899
+ message: e,
2900
+ source: "agent"
2901
+ });
2902
+ };
2903
+ try {
2904
+ for await (let s of r.chat.streamSession(e, {
2905
+ signal: t.signal,
2906
+ onConnected: n
2907
+ })) {
2908
+ r.options.debug && console.debug("[agent-chat] SSE", s.event, s.data.slice(0, 120));
2909
+ let t = Xe(s.event, s.data), n = t.type === "think" || t.type === "result" || t.type === "message-blocks" || t.type === "complete" ? this.resolveStreamTargetMessageId(r, t.messageId) : null;
2910
+ switch (n = this.maybeRebindStreamMessageId(r, n, t.type === "think" || t.type === "result" || t.type === "message-blocks" || t.type === "complete" ? t.messageId : void 0), t.type) {
2911
+ case "think":
2912
+ if (!n) break;
2913
+ this.patchMessageById(r, n, (e) => {
2914
+ let n = { ...e.stream ?? Q() }, r = t.mode === "append" ? `${n.thinkText}${t.text}` : t.text, i = !!n.resultText?.trim() || !!(n.resultBlocks ?? e.blocks ?? []).length;
2915
+ return {
2916
+ ...e,
2917
+ status: "pending",
2918
+ content: i ? e.content : {
2919
+ type: "text",
2920
+ text: ""
2921
+ },
2922
+ stream: {
2923
+ ...n,
2924
+ thinkText: r,
2925
+ phase: i ? "result" : "thinking"
2926
+ }
2927
+ };
2928
+ });
2929
+ break;
2930
+ case "result":
2931
+ if (!n || t.mode === "replace" && this.isExistingSentAssistantText(r, t.text, n)) break;
2932
+ this.patchMessageById(r, n, (e) => {
2933
+ let n = { ...e.stream ?? Q() }, r = t.mode === "append" ? `${n.resultText}${t.text}` : t.text;
2934
+ return {
2935
+ ...e,
2936
+ status: "pending",
2937
+ content: {
2938
+ type: "text",
2939
+ text: r
2940
+ },
2941
+ stream: {
2942
+ ...n,
2943
+ resultText: r,
2944
+ phase: "result"
2945
+ }
2946
+ };
2947
+ });
2948
+ break;
2949
+ case "message-blocks": {
2950
+ if (!n && t.runId != null && r.writeConfirmation?.submitting) {
2951
+ let e = this.appendAgentPlaceholder(r);
2952
+ r.activeStreamTargetMessageId = e.id, n = e.id;
2953
+ }
2954
+ if (!n) break;
2955
+ let e = t.seq;
2956
+ this.patchMessageById(r, n, (n) => {
2957
+ let r = { ...n.stream ?? Q() }, i = new Set(r.seenSeq ?? []);
2958
+ if (e != null && i.has(e)) return n;
2959
+ e != null && i.add(e);
2960
+ let a = r.resultBlocks ?? n.blocks ?? [], o = a;
2961
+ t.action === "stream" ? o = t.streamMode === "full" ? lr(a, t.blocks ?? []) : ur(a, t.blocks ?? []) : t.action === "patch" && (o = gr(a, (t.patches ?? []).map((e) => ({
2962
+ replaceId: e.replaceId,
2963
+ block: e.block
2964
+ })))), o = hr(o);
2965
+ let s = rr(o);
2966
+ return {
2967
+ ...n,
2968
+ status: "pending",
2969
+ content: {
2970
+ type: "text",
2971
+ text: s
2972
+ },
2973
+ blocks: o,
2974
+ stream: {
2975
+ ...r,
2976
+ runId: t.runId ?? r.runId,
2977
+ resultBlocks: o,
2978
+ resultText: s,
2979
+ phase: "result",
2980
+ seenSeq: [...i]
2981
+ }
2982
+ };
2983
+ });
2984
+ break;
2985
+ }
2986
+ case "write-confirmation-required":
2987
+ r.writeConfirmation = {
2988
+ awaiting: !0,
2989
+ submitting: !1,
2990
+ runId: t.runId,
2991
+ turnId: t.turnId,
2992
+ message: t.message
2993
+ }, this.notifyStateChange();
2994
+ break;
2995
+ case "write-confirmation-cancelled": {
2996
+ r.writeConfirmation = null, this.notifyStateChange();
2997
+ let e = {
2998
+ id: vr("msg"),
2999
+ role: "system",
3000
+ content: {
3001
+ type: "text",
3002
+ text: t.message
3003
+ },
3004
+ createdAt: Date.now(),
3005
+ status: "sent"
3006
+ };
3007
+ r.messages = [...r.messages, e], this.cacheActiveSessionMessages(r), this.notifyStateChange(), this.bus.emit("message", {
3008
+ message: e,
3009
+ source: "agent"
3010
+ });
3011
+ break;
3012
+ }
3013
+ case "complete": {
3014
+ if (!n) break;
3015
+ let o = i(n);
3016
+ if (!o) break;
3017
+ let s = r.writeConfirmation?.awaiting, c = {
3018
+ ...o.stream ?? Q(),
3019
+ phase: "complete"
3020
+ }, l;
3021
+ if (t.serverMessage) {
3022
+ let e = this.toAgentMessage(t.serverMessage);
3023
+ l = $({
3024
+ ...o,
3025
+ content: e.content,
3026
+ blocks: e.blocks ?? o.blocks
3027
+ }, {
3028
+ ...c,
3029
+ resultText: e.content.text,
3030
+ resultBlocks: e.blocks ?? c.resultBlocks
3031
+ }, { status: "sent" });
3032
+ } else l = $(o, c, { status: "sent" });
3033
+ let u = this.resolveCompleteServerMessageId(t);
3034
+ u && u !== n && !r.messages.some((e) => e.id === u) ? a({
3035
+ ...l,
3036
+ id: u
3037
+ }, n) : a(l, n), r.activeStreamTargetMessageId = null, s || (r.writeConfirmation = null, this.notifyStateChange()), this.alignPersistedMessageIds(r, e, {
3038
+ preferLocalId: n,
3039
+ preferServerId: u
3040
+ }).catch(() => {});
3041
+ break;
3042
+ }
3043
+ case "error": throw t.code === "WRITE_CONFIRMATION_EXPIRED" && (r.writeConfirmation = null, this.notifyStateChange()), new o("MESSAGE_FAILED", t.message, { details: t.code ? { code: t.code } : void 0 });
3044
+ case "noop": break;
3045
+ default: break;
3046
+ }
3047
+ }
3048
+ let s = i(this.resolveStreamTargetMessageId(r));
3049
+ s && (s.status ?? "pending") === "pending" && a($(s, {
3050
+ ...s.stream ?? Q(),
3051
+ phase: "complete"
3052
+ }, { status: "sent" }), s.id), this.alignPersistedMessageIds(r, e).catch(() => {});
3053
+ } catch (e) {
3054
+ if (e?.name === "AbortError") {
3055
+ let e = i(this.resolveStreamTargetMessageId(r));
3056
+ if (!e) return;
3057
+ let t = e.stream ?? Q();
3058
+ (t.resultText || e.content.text).trim() ? a($(e, {
3059
+ ...t,
3060
+ phase: "complete"
3061
+ }, { status: "sent" }), e.id) : this.removeAgentMessage(r, e.id);
3062
+ return;
3063
+ }
3064
+ let t = i(this.resolveStreamTargetMessageId(r));
3065
+ if (t) {
3066
+ let n = t.stream ?? Q();
3067
+ a({
3068
+ ...t,
3069
+ status: "failed",
3070
+ stream: {
3071
+ ...n,
3072
+ phase: "error",
3073
+ errorMessage: e instanceof Error ? e.message : "Stream failed"
3074
+ }
3075
+ }, t.id);
3076
+ }
3077
+ let n = e instanceof o ? e : new o("MESSAGE_FAILED", "Failed to receive assistant reply", { cause: e });
3078
+ this.reportError(n);
3079
+ }
3080
+ }
3081
+ toAgentMessage(e) {
3082
+ let t = e.role === "assistant" ? "agent" : e.role === "user" ? "user" : "system", n = e.createdAt, r = typeof n == "number" ? n : new Date(n).getTime(), i = X(e.content), a = i ? rr(i) : e.content ?? "";
3083
+ return {
3084
+ id: String(e.id),
3085
+ role: t,
3086
+ content: {
3087
+ type: "text",
3088
+ text: a
3089
+ },
3090
+ blocks: i,
3091
+ createdAt: Number.isFinite(r) ? r : Date.now(),
3092
+ status: "sent"
3093
+ };
3094
+ }
3095
+ resolveCompleteServerMessageId(e) {
3096
+ if (e.serverMessage?.id != null) return String(e.serverMessage.id);
3097
+ if (e.messageId && Y(e.messageId)) return e.messageId;
3098
+ }
3099
+ async alignPersistedMessageIds(e, t, n = {}) {
3100
+ let r = n.preferLocalId?.trim(), i = n.preferServerId && Y(n.preferServerId) ? n.preferServerId : void 0;
3101
+ if (r && i) {
3102
+ let n = e.messages.find((e) => e.id === r);
3103
+ if (n && !Y(n.id) && !e.messages.some((e) => e.id === i)) {
3104
+ e.messages = e.messages.map((e) => e.id === r ? {
3105
+ ...e,
3106
+ id: i
3107
+ } : e), e.activeStreamTargetMessageId === r && (e.activeStreamTargetMessageId = i), this.cacheActiveSessionMessages(e), this.notifyStateChange(), this.syncMessageFeedbacks(e, t).catch(() => {});
3108
+ return;
3109
+ }
3110
+ }
3111
+ let a = e.messages.filter((e) => e.role === "agent" && e.status === "sent" && !e.stream && !Y(e.id));
3112
+ if (a.length === 0) return;
3113
+ let o = (await this.fetchSessionMessagesPage(e, t, 1)).messages.map((e) => this.toAgentMessage(e)).filter((e) => e.role === "agent"), s = new Set(e.messages.filter((e) => e.role === "agent" && Y(e.id)).map((e) => e.id)), c = o.filter((e) => !s.has(e.id));
3114
+ if (c.length === 0) return;
3115
+ let l = Math.max(0, c.length - a.length), u = !1;
3116
+ e.messages = e.messages.map((e) => {
3117
+ let t = a.findIndex((t) => t.id === e.id);
3118
+ if (t < 0) return e;
3119
+ let n = c[l + t];
3120
+ return !n || !Y(n.id) ? e : (u = !0, {
3121
+ ...e,
3122
+ id: n.id,
3123
+ createdAt: n.createdAt
3124
+ });
3125
+ }), u && (this.cacheActiveSessionMessages(e), this.notifyStateChange(), this.syncMessageFeedbacks(e, t).catch(() => {}));
3126
+ }
3127
+ maybeRebindStreamMessageId(e, t, n) {
3128
+ return !t || !n || !Y(n) || t === n || Y(t) || e.messages.some((e) => e.id === n) ? t : e.messages.find((e) => e.id === t) ? (e.messages = e.messages.map((e) => e.id === t ? {
3129
+ ...e,
3130
+ id: n
3131
+ } : e), e.activeStreamTargetMessageId === t && (e.activeStreamTargetMessageId = n), this.cacheActiveSessionMessages(e), this.notifyStateChange(), n) : n;
3132
+ }
3133
+ buildOptimisticFeedback(e, t) {
3134
+ let n = (/* @__PURE__ */ new Date()).toISOString();
3135
+ return t.rating === "up" ? {
3136
+ messageId: e,
3137
+ rating: "up",
3138
+ reasonTags: [],
3139
+ comment: null,
3140
+ createdAt: n,
3141
+ updatedAt: n
3142
+ } : {
3143
+ messageId: e,
3144
+ rating: "down",
3145
+ reasonTags: t.reasonTags ?? [],
3146
+ comment: t.comment?.trim() || null,
3147
+ createdAt: n,
3148
+ updatedAt: n
3149
+ };
3150
+ }
3151
+ patchMessageFeedback(e, t, n) {
3152
+ let r = e.messages.map((e) => e.id === t ? {
3153
+ ...e,
3154
+ feedback: n
3155
+ } : e);
3156
+ r.every((t, n) => t === e.messages[n]) || (e.messages = r, this.cacheActiveSessionMessages(e), this.notifyStateChange());
3157
+ }
3158
+ collectFeedbackMessageIds(e) {
3159
+ let t = [];
3160
+ for (let n of e) {
3161
+ if (n.role !== "agent" || n.status !== "sent" || n.stream) continue;
3162
+ let e = tr(n.id);
3163
+ e !== null && t.push(e);
3164
+ }
3165
+ return t;
3166
+ }
3167
+ async syncMessageFeedbacks(e, t) {
3168
+ let n = this.collectFeedbackMessageIds(e.messages);
3169
+ if (n.length === 0) return;
3170
+ let r = await e.feedback.batchFeedbacks(t, n), i = new Map(r.items.map((e) => [String(e.messageId), e])), a = !1;
3171
+ e.messages = e.messages.map((e) => {
3172
+ if (e.role !== "agent" || !Y(e.id)) return e;
3173
+ let t = i.get(e.id) ?? null, n = e.feedback ?? null;
3174
+ return n === null && t === null || n && t && n.rating === t.rating && n.updatedAt === t.updatedAt ? e : (a = !0, {
3175
+ ...e,
3176
+ feedback: t
3177
+ });
3178
+ }), a && (this.cacheActiveSessionMessages(e), this.notifyStateChange());
3179
+ }
3180
+ };
3181
+ function Tr(e) {
3182
+ if (e) return {
3183
+ id: String(e.id),
3184
+ email: e.email,
3185
+ name: e.username
3186
+ };
3187
+ }
3188
+ function Er() {
3189
+ return new wr();
3190
+ }
3191
+ //#endregion
3192
+ //#region src/index.ts
3193
+ var Dr = Er();
3194
+ //#endregion
3195
+ export { Dr as AgentChat, Dr as default, wr as AgentChatClient, o as AgentChatError, s as DEFAULT_BASE_URL, c as DSN_AUTH_HEADER, _r as SDK_VERSION, Er as createAgentChat, l as normalizeDsn, x as useAuthStore };
3196
+
3197
+ //# sourceMappingURL=omnix-chat.es.js.map