@sveda-ai/chat 0.3.1

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 (108) hide show
  1. package/LICENSE +557 -0
  2. package/README.md +18 -0
  3. package/dist/appearance.d.ts +54 -0
  4. package/dist/appearance.d.ts.map +1 -0
  5. package/dist/appearance.js +516 -0
  6. package/dist/appearance.js.map +1 -0
  7. package/dist/chatStore.d.ts +60 -0
  8. package/dist/chatStore.d.ts.map +1 -0
  9. package/dist/chatStore.js +518 -0
  10. package/dist/chatStore.js.map +1 -0
  11. package/dist/i18n/catalogs.d.ts +4 -0
  12. package/dist/i18n/catalogs.d.ts.map +1 -0
  13. package/dist/i18n/catalogs.js +3 -0
  14. package/dist/i18n/catalogs.js.map +1 -0
  15. package/dist/i18n/locales/en.d.ts +4 -0
  16. package/dist/i18n/locales/en.d.ts.map +1 -0
  17. package/dist/i18n/locales/en.js +59 -0
  18. package/dist/i18n/locales/en.js.map +1 -0
  19. package/dist/i18n/locales/ru.d.ts +4 -0
  20. package/dist/i18n/locales/ru.d.ts.map +1 -0
  21. package/dist/i18n/locales/ru.js +59 -0
  22. package/dist/i18n/locales/ru.js.map +1 -0
  23. package/dist/i18n/types.d.ts +2 -0
  24. package/dist/i18n/types.d.ts.map +1 -0
  25. package/dist/i18n/types.js +2 -0
  26. package/dist/i18n/types.js.map +1 -0
  27. package/dist/index.d.ts +27 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +19 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/lib/assistantMessage.d.ts +90 -0
  32. package/dist/lib/assistantMessage.d.ts.map +1 -0
  33. package/dist/lib/assistantMessage.js +311 -0
  34. package/dist/lib/assistantMessage.js.map +1 -0
  35. package/dist/lib/chatHistoryMerge.d.ts +20 -0
  36. package/dist/lib/chatHistoryMerge.d.ts.map +1 -0
  37. package/dist/lib/chatHistoryMerge.js +61 -0
  38. package/dist/lib/chatHistoryMerge.js.map +1 -0
  39. package/dist/lib/chatI18nKeys.d.ts +2 -0
  40. package/dist/lib/chatI18nKeys.d.ts.map +1 -0
  41. package/dist/lib/chatI18nKeys.js +63 -0
  42. package/dist/lib/chatI18nKeys.js.map +1 -0
  43. package/dist/lib/chatMessageVisibility.d.ts +6 -0
  44. package/dist/lib/chatMessageVisibility.d.ts.map +1 -0
  45. package/dist/lib/chatMessageVisibility.js +68 -0
  46. package/dist/lib/chatMessageVisibility.js.map +1 -0
  47. package/dist/lib/chatResize.d.ts +42 -0
  48. package/dist/lib/chatResize.d.ts.map +1 -0
  49. package/dist/lib/chatResize.js +71 -0
  50. package/dist/lib/chatResize.js.map +1 -0
  51. package/dist/lib/chatTabs.d.ts +9 -0
  52. package/dist/lib/chatTabs.d.ts.map +1 -0
  53. package/dist/lib/chatTabs.js +34 -0
  54. package/dist/lib/chatTabs.js.map +1 -0
  55. package/dist/lib/chatTitle.d.ts +3 -0
  56. package/dist/lib/chatTitle.d.ts.map +1 -0
  57. package/dist/lib/chatTitle.js +25 -0
  58. package/dist/lib/chatTitle.js.map +1 -0
  59. package/dist/lib/chatUiStorage.d.ts +6 -0
  60. package/dist/lib/chatUiStorage.d.ts.map +1 -0
  61. package/dist/lib/chatUiStorage.js +61 -0
  62. package/dist/lib/chatUiStorage.js.map +1 -0
  63. package/dist/lib/finalizeMessages.d.ts +21 -0
  64. package/dist/lib/finalizeMessages.d.ts.map +1 -0
  65. package/dist/lib/finalizeMessages.js +54 -0
  66. package/dist/lib/finalizeMessages.js.map +1 -0
  67. package/dist/lib/markdown.d.ts +8 -0
  68. package/dist/lib/markdown.d.ts.map +1 -0
  69. package/dist/lib/markdown.js +69 -0
  70. package/dist/lib/markdown.js.map +1 -0
  71. package/dist/lib/modelLabels.d.ts +3 -0
  72. package/dist/lib/modelLabels.d.ts.map +1 -0
  73. package/dist/lib/modelLabels.js +23 -0
  74. package/dist/lib/modelLabels.js.map +1 -0
  75. package/dist/lib/toolConfirmation.d.ts +11 -0
  76. package/dist/lib/toolConfirmation.d.ts.map +1 -0
  77. package/dist/lib/toolConfirmation.js +16 -0
  78. package/dist/lib/toolConfirmation.js.map +1 -0
  79. package/dist/lib/userMessage.d.ts +17 -0
  80. package/dist/lib/userMessage.d.ts.map +1 -0
  81. package/dist/lib/userMessage.js +33 -0
  82. package/dist/lib/userMessage.js.map +1 -0
  83. package/dist/streaming.d.ts +59 -0
  84. package/dist/streaming.d.ts.map +1 -0
  85. package/dist/streaming.js +375 -0
  86. package/dist/streaming.js.map +1 -0
  87. package/package.json +53 -0
  88. package/src/appearance.ts +654 -0
  89. package/src/chatStore.ts +696 -0
  90. package/src/i18n/catalogs.ts +3 -0
  91. package/src/i18n/locales/en.ts +64 -0
  92. package/src/i18n/locales/ru.ts +65 -0
  93. package/src/i18n/types.ts +1 -0
  94. package/src/index.ts +84 -0
  95. package/src/lib/assistantMessage.ts +439 -0
  96. package/src/lib/chatHistoryMerge.ts +93 -0
  97. package/src/lib/chatI18nKeys.ts +64 -0
  98. package/src/lib/chatMessageVisibility.ts +92 -0
  99. package/src/lib/chatResize.ts +123 -0
  100. package/src/lib/chatTabs.ts +54 -0
  101. package/src/lib/chatTitle.ts +30 -0
  102. package/src/lib/chatUiStorage.ts +69 -0
  103. package/src/lib/finalizeMessages.ts +81 -0
  104. package/src/lib/markdown.ts +90 -0
  105. package/src/lib/modelLabels.ts +24 -0
  106. package/src/lib/toolConfirmation.ts +31 -0
  107. package/src/lib/userMessage.ts +55 -0
  108. package/src/streaming.ts +514 -0
@@ -0,0 +1,24 @@
1
+ export function humanizeModelId(raw: string): string {
2
+ const part = raw.includes('/') ? (raw.split('/').pop() as string) : raw;
3
+ const cleaned = part.replace(/-preview$/i, '').replace(/_/g, '-');
4
+ return cleaned
5
+ .split('-')
6
+ .map(seg => {
7
+ if (/^\d+(\.\d+)?$/.test(seg)) {
8
+ return seg;
9
+ }
10
+ if (seg.length === 0) {
11
+ return '';
12
+ }
13
+ return seg[0].toUpperCase() + seg.slice(1).toLowerCase();
14
+ })
15
+ .join(' ');
16
+ }
17
+
18
+ export function getSvedaModelDisplayName(model: string | null | undefined): string {
19
+ if (!model) {
20
+ return '—';
21
+ }
22
+
23
+ return humanizeModelId(model);
24
+ }
@@ -0,0 +1,31 @@
1
+ type ToolPart = {
2
+ type?: string;
3
+ toolCallId?: string;
4
+ confirmation?: string;
5
+ };
6
+
7
+ type ToolMessage = {
8
+ parts?: ToolPart[];
9
+ };
10
+
11
+ export function hasPendingToolConfirmation(messages: ToolMessage[] | null | undefined): boolean {
12
+ const resolved = new Set<string>();
13
+ for (const message of messages ?? []) {
14
+ for (const part of message.parts ?? []) {
15
+ if (part.type === 'tool-result' && part.toolCallId) {
16
+ resolved.add(part.toolCallId);
17
+ }
18
+ }
19
+ }
20
+
21
+ return (messages ?? []).some(message =>
22
+ (message.parts ?? []).some(
23
+ part =>
24
+ part.type === 'tool-call' &&
25
+ part.confirmation === 'required' &&
26
+ typeof part.toolCallId === 'string' &&
27
+ part.toolCallId !== '' &&
28
+ !resolved.has(part.toolCallId)
29
+ )
30
+ );
31
+ }
@@ -0,0 +1,55 @@
1
+ export type SvedaUserMessageLike = {
2
+ role?: string;
3
+ content?: string;
4
+ attachmentNames?: string[];
5
+ metadata?: {
6
+ attachmentNames?: string[];
7
+ };
8
+ parts?: Array<{
9
+ type?: string;
10
+ text?: string;
11
+ name?: string;
12
+ }>;
13
+ };
14
+
15
+ export const getUserMessageText = (message: SvedaUserMessageLike): string => {
16
+ if (typeof message.content === 'string' && message.content.trim()) {
17
+ return message.content.trim();
18
+ }
19
+
20
+ if (!Array.isArray(message.parts)) {
21
+ return '';
22
+ }
23
+
24
+ return message.parts
25
+ .filter(part => part?.type === 'text')
26
+ .map(part => String(part.text || '').trim())
27
+ .filter(Boolean)
28
+ .join(' ');
29
+ };
30
+
31
+ export const getUserMessageAttachmentNames = (message: SvedaUserMessageLike): string[] => {
32
+ const raw = message.attachmentNames ?? message.metadata?.attachmentNames;
33
+ if (Array.isArray(raw)) {
34
+ return raw.map(name => String(name).trim()).filter(Boolean);
35
+ }
36
+
37
+ if (!Array.isArray(message.parts)) {
38
+ return [];
39
+ }
40
+
41
+ return message.parts
42
+ .filter(part => part?.type === 'file')
43
+ .map(part => String(part.name || '').trim())
44
+ .filter(Boolean);
45
+ };
46
+
47
+ export const userMessageHasVisibleContent = (message: SvedaUserMessageLike): boolean => {
48
+ if (message.role !== 'user') {
49
+ return false;
50
+ }
51
+
52
+ return (
53
+ getUserMessageText(message).length > 0 || getUserMessageAttachmentNames(message).length > 0
54
+ );
55
+ };
@@ -0,0 +1,514 @@
1
+ import type {
2
+ SvedaChatSession,
3
+ SvedaClient,
4
+ SvedaDisplayMessage,
5
+ SvedaMessagePart,
6
+ SvedaSendOptions,
7
+ SvedaSessionStatus,
8
+ } from '@sveda-ai/core';
9
+ import type { SvedaContextUsageEvent, SvedaMaxStepsEvent, SvedaToolProgressEvent } from '@sveda-ai/protocol';
10
+ import { deriveProvisionalChatTitle, isChatTitlePlaceholder } from './lib/chatTitle.js';
11
+
12
+ export interface SvedaStreamingChatRef {
13
+ id: string;
14
+ title?: string;
15
+ messages?: SvedaDisplayMessage[];
16
+ }
17
+
18
+ export interface SvedaStreamingStore {
19
+ getCurrentChat(): SvedaStreamingChatRef | null;
20
+ setChatMessages(chatId: string, messages: SvedaDisplayMessage[]): void;
21
+ setChatTitle(chatId: string, title: string): void;
22
+ refreshChatTitleFromServer(chatId: string): Promise<string | null>;
23
+ incrementChatTokens(chatId: string, tokens: number): void;
24
+ setChatContextWindowTokens(chatId: string, tokens: number): void;
25
+ }
26
+
27
+ export interface SvedaStreamingOptions {
28
+ newChatLabel?: () => string;
29
+ resolveSendOptions?: () => Pick<SvedaSendOptions, 'model' | 'provider' | 'options'>;
30
+ onMaxStepsReached?: (chatId: string, data: { maxSteps: number }) => void;
31
+ onToolProgress?: (chatId: string, event: SvedaToolProgressEvent) => void;
32
+ onContextUsage?: (chatId: string, event: SvedaContextUsageEvent) => void;
33
+ onError?: (chatId: string, error: unknown) => void;
34
+ onDone?: (chatId: string) => void;
35
+ translate?: (key: string) => string;
36
+ beforeSend?: (() => void | Promise<void>) | null;
37
+ onAfterFinish?: (chatId: string) => void;
38
+ onCurrentChatIdChange?: (newId: string | null | undefined, oldId: string | null | undefined) => void;
39
+ }
40
+
41
+ export type SvedaSendPayload =
42
+ | string
43
+ | {
44
+ displayText: string;
45
+ promptText: string;
46
+ attachmentNames?: string[];
47
+ };
48
+
49
+ export interface SvedaStreamingState {
50
+ isThinking: boolean;
51
+ thinkingMessage: string;
52
+ streamingChatIds: Set<string>;
53
+ unreadChatIds: Set<string>;
54
+ statusByChatId: Record<string, SvedaSessionStatus>;
55
+ }
56
+
57
+ export interface SvedaStreamingController {
58
+ getState(): SvedaStreamingState;
59
+ subscribe(listener: () => void): () => void;
60
+ sendMessage(userPayload: SvedaSendPayload, pageContext?: Record<string, unknown>): Promise<void>;
61
+ continueAfterMaxSteps(pageContext?: Record<string, unknown>): Promise<void>;
62
+ resolveToolConfirmation(
63
+ toolCallId: string,
64
+ decision: 'approve' | 'deny',
65
+ pageContext?: Record<string, unknown>
66
+ ): Promise<void>;
67
+ stopStreaming(chatId?: string | null): void;
68
+ clearChatUnread(chatId?: string | null): void;
69
+ isStreamingFor(chatId: string | null | undefined): boolean;
70
+ dispose(): void;
71
+ watchCurrentChatId(getId: () => string | null | undefined): () => void;
72
+ }
73
+
74
+ export function createSvedaStreaming(
75
+ client: SvedaClient,
76
+ store: SvedaStreamingStore,
77
+ scrollToBottom: (options?: { behavior?: string; onlyIfNearBottom?: boolean }) => void,
78
+ options: SvedaStreamingOptions = {}
79
+ ): SvedaStreamingController {
80
+ const listeners = new Set<() => void>();
81
+ const translate = options.translate ?? ((key: string) => key);
82
+ const beforeSend = options.beforeSend ?? null;
83
+
84
+ let isThinking = false;
85
+ let thinkingMessage = '';
86
+ let streamingChatIds = new Set<string>();
87
+ let unreadChatIds = new Set<string>();
88
+ let statusByChatId: Record<string, SvedaSessionStatus> = {};
89
+
90
+ const subscriptions = new Map<string, Array<() => void>>();
91
+ const displayTextOverrides = new Map<string, Map<string, string>>();
92
+ let lastWatchedChatId: string | null | undefined = undefined;
93
+
94
+ const notify = () => {
95
+ for (const listener of listeners) {
96
+ listener();
97
+ }
98
+ };
99
+
100
+ const getState = (): SvedaStreamingState => ({
101
+ isThinking,
102
+ thinkingMessage,
103
+ streamingChatIds: new Set(streamingChatIds),
104
+ unreadChatIds: new Set(unreadChatIds),
105
+ statusByChatId: { ...statusByChatId },
106
+ });
107
+
108
+ const subscribe = (listener: () => void): (() => void) => {
109
+ listeners.add(listener);
110
+ return () => {
111
+ listeners.delete(listener);
112
+ };
113
+ };
114
+
115
+ const setChatStreaming = (chatId: string, streaming: boolean) => {
116
+ const next = new Set(streamingChatIds);
117
+ if (streaming) {
118
+ next.add(chatId);
119
+ } else {
120
+ next.delete(chatId);
121
+ }
122
+ streamingChatIds = next;
123
+ notify();
124
+ };
125
+
126
+ const clearChatUnread = (chatId?: string | null) => {
127
+ if (!chatId) {
128
+ return;
129
+ }
130
+ const next = new Set(unreadChatIds);
131
+ next.delete(chatId);
132
+ unreadChatIds = next;
133
+ notify();
134
+ };
135
+
136
+ const resolveNewChatLabel = () => {
137
+ if (typeof options.newChatLabel === 'function') {
138
+ return options.newChatLabel();
139
+ }
140
+ return translate('newChat');
141
+ };
142
+
143
+ const applyProvisionalChatTitle = (chatId: string, userRequest: string) => {
144
+ const current = store.getCurrentChat();
145
+ if (!current || current.id !== chatId) {
146
+ return;
147
+ }
148
+
149
+ const newChatLabel = resolveNewChatLabel();
150
+ if (!isChatTitlePlaceholder((current.title || '').trim(), newChatLabel)) {
151
+ return;
152
+ }
153
+
154
+ const provisionalTitle = deriveProvisionalChatTitle(userRequest);
155
+ if (provisionalTitle) {
156
+ store.setChatTitle(chatId, provisionalTitle);
157
+ }
158
+ };
159
+
160
+ const scheduleChatTitleRefresh = (chatId: string) => {
161
+ const newChatLabel = resolveNewChatLabel();
162
+ const delays = [800, 2500, 6000];
163
+
164
+ delays.forEach(delay => {
165
+ setTimeout(async () => {
166
+ const title = await store.refreshChatTitleFromServer(chatId);
167
+ if (!title || isChatTitlePlaceholder(title, newChatLabel)) {
168
+ return;
169
+ }
170
+ store.setChatTitle(chatId, title);
171
+ }, delay);
172
+ });
173
+ };
174
+
175
+ const setChatStatus = (chatId: string, status: SvedaSessionStatus) => {
176
+ const previous = statusByChatId[chatId];
177
+ statusByChatId = {
178
+ ...statusByChatId,
179
+ [chatId]: status,
180
+ };
181
+
182
+ const wasStreaming = previous === 'streaming' || previous === 'submitted';
183
+ const isStreamingNow = status === 'streaming' || status === 'submitted';
184
+ setChatStreaming(chatId, isStreamingNow);
185
+
186
+ if (wasStreaming && !isStreamingNow && store.getCurrentChat()?.id !== chatId) {
187
+ const next = new Set(unreadChatIds);
188
+ next.add(chatId);
189
+ unreadChatIds = next;
190
+ }
191
+
192
+ if (isStreamingNow) {
193
+ clearChatUnread(chatId);
194
+ }
195
+
196
+ const currentId = store.getCurrentChat()?.id;
197
+ if (chatId === currentId) {
198
+ if (status === 'streaming' || status === 'submitted') {
199
+ isThinking = true;
200
+ thinkingMessage = translate('analyzingRequest');
201
+ } else {
202
+ isThinking = false;
203
+ thinkingMessage = '';
204
+ }
205
+ }
206
+ notify();
207
+ };
208
+
209
+ const applyDisplayOverrides = (
210
+ chatId: string,
211
+ messages: SvedaDisplayMessage[]
212
+ ): SvedaDisplayMessage[] => {
213
+ const overrides = displayTextOverrides.get(chatId);
214
+ if (!overrides || overrides.size === 0) {
215
+ return messages;
216
+ }
217
+
218
+ return messages.map(message => {
219
+ const override = overrides.get(message.id);
220
+ if (override === undefined || message.role !== 'user') {
221
+ return message;
222
+ }
223
+
224
+ const fileParts = message.parts.filter(part => part.type === 'file');
225
+ const parts: SvedaMessagePart[] = [
226
+ ...(override ? [{ type: 'text', text: override } as SvedaMessagePart] : []),
227
+ ...fileParts,
228
+ ];
229
+
230
+ return { ...message, parts };
231
+ });
232
+ };
233
+
234
+ const ensureSession = (chatId: string): SvedaChatSession => {
235
+ const session = client.session(chatId);
236
+ if (subscriptions.has(chatId)) {
237
+ return session;
238
+ }
239
+
240
+ const offMessages = session.on('messages', () => {
241
+ store.setChatMessages(chatId, applyDisplayOverrides(chatId, session.messages));
242
+ });
243
+
244
+ const offStatus = session.on('status', payload => {
245
+ setChatStatus(chatId, payload as SvedaSessionStatus);
246
+ });
247
+
248
+ const offTitle = session.on('title', payload => {
249
+ if (typeof payload === 'string' && payload.trim()) {
250
+ store.setChatTitle(chatId, payload);
251
+ }
252
+ });
253
+
254
+ const offMaxSteps = session.on('maxSteps', payload => {
255
+ const event = payload as SvedaMaxStepsEvent | undefined;
256
+ options.onMaxStepsReached?.(chatId, {
257
+ maxSteps: typeof event?.maxSteps === 'number' ? event.maxSteps : 0,
258
+ });
259
+ });
260
+
261
+ const offContextUsage = session.on('contextUsage', payload => {
262
+ const event = payload as SvedaContextUsageEvent | undefined;
263
+ if (event && typeof event.usedTokens === 'number') {
264
+ store.setChatContextWindowTokens(chatId, event.usedTokens);
265
+ }
266
+ if (event) {
267
+ options.onContextUsage?.(chatId, event);
268
+ }
269
+ });
270
+
271
+ const offToolProgress = session.on('toolProgress', payload => {
272
+ options.onToolProgress?.(chatId, payload as SvedaToolProgressEvent);
273
+ });
274
+
275
+ const offFinish = session.on('finish', payload => {
276
+ const event = payload as
277
+ | { usage?: { totalTokens?: number; promptTokens?: number } }
278
+ | undefined;
279
+ if (event?.usage) {
280
+ if (typeof event.usage.totalTokens === 'number') {
281
+ store.incrementChatTokens(chatId, event.usage.totalTokens);
282
+ }
283
+ if (typeof event.usage.promptTokens === 'number') {
284
+ store.setChatContextWindowTokens(chatId, event.usage.promptTokens);
285
+ }
286
+ }
287
+ queueMicrotask(() => {
288
+ options.onDone?.(chatId);
289
+ options.onAfterFinish?.(chatId);
290
+ scheduleChatTitleRefresh(chatId);
291
+ if (store.getCurrentChat()?.id === chatId) {
292
+ scrollToBottom();
293
+ }
294
+ });
295
+ });
296
+
297
+ const offError = session.on('error', payload => {
298
+ options.onError?.(chatId, payload);
299
+ queueMicrotask(() => {
300
+ options.onDone?.(chatId);
301
+ if (store.getCurrentChat()?.id === chatId) {
302
+ scrollToBottom();
303
+ }
304
+ });
305
+ });
306
+
307
+ subscriptions.set(chatId, [
308
+ offMessages,
309
+ offStatus,
310
+ offTitle,
311
+ offMaxSteps,
312
+ offContextUsage,
313
+ offToolProgress,
314
+ offFinish,
315
+ offError,
316
+ ]);
317
+ setChatStatus(chatId, session.status);
318
+
319
+ return session;
320
+ };
321
+
322
+ const syncCurrentChatMessages = (chatId: string | null | undefined) => {
323
+ if (!chatId || !subscriptions.has(chatId)) {
324
+ return;
325
+ }
326
+
327
+ const session = client.session(chatId);
328
+ if (session.isStreaming) {
329
+ return;
330
+ }
331
+
332
+ session.setMessages(store.getCurrentChat()?.messages ?? []);
333
+ };
334
+
335
+ const watchCurrentChatId = (getId: () => string | null | undefined): (() => void) => {
336
+ lastWatchedChatId = getId();
337
+ const poll = () => {
338
+ const newId = getId();
339
+ if (newId !== lastWatchedChatId) {
340
+ const oldId = lastWatchedChatId;
341
+ lastWatchedChatId = newId;
342
+ options.onCurrentChatIdChange?.(newId, oldId);
343
+ syncCurrentChatMessages(newId);
344
+
345
+ const status = newId ? statusByChatId[newId] : undefined;
346
+ if (status === 'streaming' || status === 'submitted') {
347
+ isThinking = true;
348
+ thinkingMessage = translate('analyzingRequest');
349
+ } else {
350
+ isThinking = false;
351
+ thinkingMessage = '';
352
+ }
353
+ notify();
354
+ }
355
+ };
356
+
357
+ // Store subscribers can call poll via returned handle; Vue adapter will drive via watch.
358
+ return poll;
359
+ };
360
+
361
+ const isStreamingFor = (chatId: string | null | undefined): boolean =>
362
+ streamingChatIds.has(chatId ?? '');
363
+
364
+ const stopStreaming = (chatId: string | null | undefined = store.getCurrentChat()?.id) => {
365
+ if (!chatId || !subscriptions.has(chatId)) {
366
+ return;
367
+ }
368
+ client.session(chatId).stop();
369
+ setChatStreaming(chatId, false);
370
+ isThinking = false;
371
+ thinkingMessage = '';
372
+ notify();
373
+ };
374
+
375
+ const resolveSendOptions = (): SvedaSendOptions => ({
376
+ ...(options.resolveSendOptions?.() ?? {}),
377
+ });
378
+
379
+ const sendMessage = async (
380
+ userPayload: SvedaSendPayload,
381
+ pageContext: Record<string, unknown> = {}
382
+ ) => {
383
+ let displayText = '';
384
+ let promptText = '';
385
+ let attachmentNames: string[] = [];
386
+
387
+ if (typeof userPayload === 'string') {
388
+ displayText = userPayload.trim();
389
+ promptText = displayText;
390
+ } else if (userPayload && typeof userPayload === 'object') {
391
+ displayText = String(userPayload.displayText ?? '').trim();
392
+ promptText = String(userPayload.promptText ?? '').trim();
393
+ attachmentNames = Array.isArray(userPayload.attachmentNames)
394
+ ? userPayload.attachmentNames.map(name => String(name).trim()).filter(Boolean)
395
+ : [];
396
+ } else {
397
+ return;
398
+ }
399
+
400
+ const current = store.getCurrentChat();
401
+ if (!promptText || !current) {
402
+ return;
403
+ }
404
+
405
+ try {
406
+ await beforeSend?.();
407
+ } catch (error) {
408
+ options.onError?.(current.id, error);
409
+ return;
410
+ }
411
+
412
+ const chatId = current.id;
413
+ applyProvisionalChatTitle(chatId, promptText || displayText);
414
+ const session = ensureSession(chatId);
415
+ session.setMessages(store.getCurrentChat()?.messages ?? []);
416
+
417
+ const sendOptions: SvedaSendOptions = {
418
+ ...resolveSendOptions(),
419
+ context: { ...pageContext },
420
+ ...(attachmentNames.length > 0
421
+ ? { files: attachmentNames.map(name => ({ name })) }
422
+ : {}),
423
+ };
424
+
425
+ const sendPromise = session.send(promptText, sendOptions);
426
+
427
+ if (displayText !== promptText) {
428
+ const userMessage = [...session.messages].reverse().find(message => message.role === 'user');
429
+ if (userMessage) {
430
+ if (!displayTextOverrides.has(chatId)) {
431
+ displayTextOverrides.set(chatId, new Map());
432
+ }
433
+ displayTextOverrides.get(chatId)!.set(userMessage.id, displayText);
434
+ store.setChatMessages(chatId, applyDisplayOverrides(chatId, session.messages));
435
+ }
436
+ }
437
+
438
+ try {
439
+ await sendPromise;
440
+ } catch {
441
+ return;
442
+ }
443
+
444
+ scrollToBottom();
445
+ };
446
+
447
+ const continueAfterMaxSteps = async (pageContext: Record<string, unknown> = {}) => {
448
+ const chatId = store.getCurrentChat()?.id;
449
+ if (!chatId) {
450
+ return;
451
+ }
452
+
453
+ const session = ensureSession(chatId);
454
+ if (session.messages.length === 0) {
455
+ session.setMessages(store.getCurrentChat()?.messages ?? []);
456
+ }
457
+
458
+ try {
459
+ await session.continueAfterMaxSteps({
460
+ ...resolveSendOptions(),
461
+ context: { ...pageContext },
462
+ });
463
+ } catch {
464
+ return;
465
+ }
466
+
467
+ scrollToBottom();
468
+ };
469
+
470
+ const resolveToolConfirmation = async (
471
+ toolCallId: string,
472
+ decision: 'approve' | 'deny',
473
+ pageContext: Record<string, unknown> = {}
474
+ ) => {
475
+ const chatId = store.getCurrentChat()?.id;
476
+ if (!chatId || !toolCallId) {
477
+ return;
478
+ }
479
+ const session = ensureSession(chatId);
480
+ session.setMessages(store.getCurrentChat()?.messages ?? []);
481
+ try {
482
+ await session.resolveToolConfirmation(toolCallId, decision, {
483
+ ...resolveSendOptions(),
484
+ context: { ...pageContext },
485
+ });
486
+ } catch {
487
+ return;
488
+ }
489
+ scrollToBottom();
490
+ };
491
+
492
+ const dispose = () => {
493
+ for (const [chatId, unsubscribes] of subscriptions.entries()) {
494
+ client.session(chatId).stop();
495
+ unsubscribes.forEach(off => off());
496
+ }
497
+ subscriptions.clear();
498
+ displayTextOverrides.clear();
499
+ listeners.clear();
500
+ };
501
+
502
+ return {
503
+ getState,
504
+ subscribe,
505
+ sendMessage,
506
+ continueAfterMaxSteps,
507
+ resolveToolConfirmation,
508
+ stopStreaming,
509
+ clearChatUnread,
510
+ isStreamingFor,
511
+ dispose,
512
+ watchCurrentChatId,
513
+ };
514
+ }