@wherever-dev/client 0.2.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.
package/dist/client.js ADDED
@@ -0,0 +1,782 @@
1
+ import { writable, get } from "sveltore";
2
+ const defaultState = {
3
+ connected: false,
4
+ connecting: false,
5
+ creatingSession: false,
6
+ error: null,
7
+ session: null,
8
+ sessionId: null,
9
+ isStreaming: false,
10
+ messages: [],
11
+ clientId: null,
12
+ conflict: null,
13
+ isInterrupted: false,
14
+ sessionError: null,
15
+ readOnly: false,
16
+ activeSessionFile: null,
17
+ activeCwd: null,
18
+ activeModel: null,
19
+ hideThinking: false,
20
+ hideTools: false,
21
+ historyTotalCount: 0,
22
+ historyOffset: 0,
23
+ loadingMoreHistory: false,
24
+ };
25
+ export class WhereverClient {
26
+ ws = null;
27
+ config;
28
+ stateStore;
29
+ reconnectTimer = null;
30
+ agentEndTimeout = null;
31
+ reconnectAttempts = 0;
32
+ reconnectDelay = 2000;
33
+ maxReconnectDelay = 15000;
34
+ isInitialConnect = true;
35
+ listeners = new Set();
36
+ pendingUploads = new Map();
37
+ constructor(config) {
38
+ this.config = {
39
+ secure: true,
40
+ ...config
41
+ };
42
+ this.stateStore = writable({
43
+ ...defaultState,
44
+ hideThinking: !!this.config.hideThinking,
45
+ hideTools: !!this.config.hideTools,
46
+ });
47
+ }
48
+ connect(newConfig) {
49
+ if (newConfig) {
50
+ this.config = {
51
+ ...this.config,
52
+ ...newConfig
53
+ };
54
+ }
55
+ this.disconnect(false);
56
+ this.stateStore.update(s => ({
57
+ ...defaultState,
58
+ connecting: true,
59
+ hideThinking: !!this.config.hideThinking,
60
+ hideTools: !!this.config.hideTools,
61
+ }));
62
+ const protocol = this.config.secure ? "wss" : "ws";
63
+ const host = this.config.host.startsWith('http')
64
+ ? this.config.host.replace(/^https?:\/\//, '')
65
+ : this.config.host;
66
+ const tokenQuery = this.config.token ? `?token=${encodeURIComponent(this.config.token)}` : "";
67
+ const wsUrl = `${protocol}://${host}:${this.config.port}/ws${tokenQuery}`;
68
+ const WebSocketImpl = this.config.WebSocketCtor || (typeof globalThis !== 'undefined' ? globalThis.WebSocket : null);
69
+ if (!WebSocketImpl) {
70
+ this.stateStore.update(s => ({
71
+ ...s,
72
+ connecting: false,
73
+ error: "No WebSocket implementation found. Please pass custom WebSocketCtor."
74
+ }));
75
+ return;
76
+ }
77
+ try {
78
+ const wsOptions = this.config.secure && this.config.WebSocketCtor ? { rejectUnauthorized: false } : undefined;
79
+ this.ws = wsOptions ? new WebSocketImpl(wsUrl, wsOptions) : new WebSocketImpl(wsUrl);
80
+ }
81
+ catch (err) {
82
+ this.stateStore.update(s => ({
83
+ ...s,
84
+ connecting: false,
85
+ error: `Failed to connect: ${err}`
86
+ }));
87
+ this.scheduleReconnect();
88
+ return;
89
+ }
90
+ const currentWs = this.ws;
91
+ const onOpen = () => {
92
+ if (this.ws !== currentWs)
93
+ return;
94
+ this.reconnectAttempts = 0;
95
+ this.reconnectDelay = 2000;
96
+ this.isInitialConnect = false;
97
+ this.stateStore.update(s => ({
98
+ ...s,
99
+ connected: true,
100
+ connecting: false,
101
+ error: null
102
+ }));
103
+ };
104
+ const onMessage = (event) => {
105
+ if (this.ws !== currentWs)
106
+ return;
107
+ try {
108
+ const rawData = typeof event.data === 'string' ? event.data : event.data.toString();
109
+ const msg = JSON.parse(rawData);
110
+ this.handleMessage(msg);
111
+ }
112
+ catch (err) {
113
+ console.error("Failed to parse WebSocket message:", err);
114
+ }
115
+ };
116
+ const onClose = () => {
117
+ if (this.ws !== currentWs)
118
+ return;
119
+ this.ws = null;
120
+ this.stateStore.update(s => ({
121
+ ...s,
122
+ connected: false,
123
+ connecting: false,
124
+ }));
125
+ this.scheduleReconnect();
126
+ };
127
+ const onError = (err) => {
128
+ if (this.ws !== currentWs)
129
+ return;
130
+ this.stateStore.update(s => ({
131
+ ...s,
132
+ error: s.error || 'Connection error occurred'
133
+ }));
134
+ };
135
+ if (typeof currentWs.addEventListener === 'function') {
136
+ currentWs.addEventListener('open', onOpen);
137
+ currentWs.addEventListener('message', onMessage);
138
+ currentWs.addEventListener('close', onClose);
139
+ currentWs.addEventListener('error', onError);
140
+ }
141
+ else if (typeof currentWs.on === 'function') {
142
+ currentWs.on('open', onOpen);
143
+ currentWs.on('message', (data) => onMessage({ data }));
144
+ currentWs.on('close', onClose);
145
+ currentWs.on('error', onError);
146
+ }
147
+ }
148
+ disconnect(resetState = true) {
149
+ if (this.reconnectTimer) {
150
+ clearTimeout(this.reconnectTimer);
151
+ this.reconnectTimer = null;
152
+ }
153
+ if (this.ws) {
154
+ try {
155
+ if (typeof this.ws.removeAllListeners === 'function') {
156
+ this.ws.removeAllListeners();
157
+ }
158
+ this.ws.close();
159
+ }
160
+ catch (err) { }
161
+ this.ws = null;
162
+ }
163
+ if (resetState) {
164
+ this.stateStore.set({
165
+ ...defaultState,
166
+ hideThinking: !!this.config.hideThinking,
167
+ hideTools: !!this.config.hideTools,
168
+ });
169
+ }
170
+ }
171
+ scheduleReconnect() {
172
+ if (this.reconnectTimer)
173
+ return;
174
+ this.reconnectTimer = setTimeout(() => {
175
+ this.reconnectTimer = null;
176
+ this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
177
+ this.stateStore.update(s => ({
178
+ ...s,
179
+ connecting: true,
180
+ error: 'Reconnecting...',
181
+ }));
182
+ this.connect();
183
+ }, this.reconnectDelay);
184
+ }
185
+ handleMessage(msg) {
186
+ for (const listener of this.listeners) {
187
+ try {
188
+ listener(msg);
189
+ }
190
+ catch (err) {
191
+ console.error("Error in message listener:", err);
192
+ }
193
+ }
194
+ switch (msg.type) {
195
+ case 'connected':
196
+ this.stateStore.update((s) => ({
197
+ ...s,
198
+ connected: true,
199
+ connecting: false,
200
+ clientId: msg.clientId,
201
+ error: null,
202
+ }));
203
+ break;
204
+ case 'file_uploaded': {
205
+ const pending = this.pendingUploads.get(msg.uploadId);
206
+ if (pending) {
207
+ pending.resolve({ savedPath: msg.savedPath, filename: msg.filename });
208
+ this.pendingUploads.delete(msg.uploadId);
209
+ }
210
+ break;
211
+ }
212
+ case 'file_upload_error': {
213
+ const pending = this.pendingUploads.get(msg.uploadId);
214
+ if (pending) {
215
+ pending.reject(new Error(msg.error));
216
+ this.pendingUploads.delete(msg.uploadId);
217
+ }
218
+ break;
219
+ }
220
+ case 'agent_start':
221
+ if (this.agentEndTimeout) {
222
+ clearTimeout(this.agentEndTimeout);
223
+ this.agentEndTimeout = null;
224
+ }
225
+ this.stateStore.update((s) => ({ ...s, isStreaming: true }));
226
+ break;
227
+ case 'thinking_update':
228
+ this.stateStore.update((s) => {
229
+ let lastThinking = [...s.messages]
230
+ .reverse()
231
+ .find((m) => m.role === 'thinking' && m.isStreaming);
232
+ if (!lastThinking) {
233
+ const newMsg = {
234
+ id: this.generateId(),
235
+ role: 'thinking',
236
+ content: msg.delta,
237
+ timestamp: Date.now(),
238
+ isStreaming: true,
239
+ };
240
+ return { ...s, messages: [...s.messages, newMsg] };
241
+ }
242
+ return {
243
+ ...s,
244
+ messages: s.messages.map((m) => m.id === lastThinking.id
245
+ ? { ...m, content: m.content + msg.delta, isStreaming: true }
246
+ : m),
247
+ };
248
+ });
249
+ break;
250
+ case 'message_update':
251
+ this.stateStore.update((s) => {
252
+ let lastAssistant = [...s.messages]
253
+ .reverse()
254
+ .find((m) => m.role === 'assistant' && m.isStreaming);
255
+ if (!lastAssistant) {
256
+ const newMsg = {
257
+ id: this.generateId(),
258
+ role: 'assistant',
259
+ content: msg.delta,
260
+ timestamp: Date.now(),
261
+ isStreaming: true,
262
+ };
263
+ return { ...s, messages: [...s.messages, newMsg] };
264
+ }
265
+ return {
266
+ ...s,
267
+ messages: s.messages.map((m) => m.id === lastAssistant.id
268
+ ? { ...m, content: m.content + msg.delta, isStreaming: true }
269
+ : m),
270
+ };
271
+ });
272
+ break;
273
+ case 'message_end':
274
+ this.stateStore.update((s) => {
275
+ let newMessages = s.messages;
276
+ const lastThinking = [...newMessages]
277
+ .reverse()
278
+ .find((m) => m.role === 'thinking' && m.isStreaming);
279
+ if (lastThinking) {
280
+ newMessages = newMessages.map((m) => m.id === lastThinking.id ? { ...m, isStreaming: false } : m);
281
+ }
282
+ const lastAssistant = [...newMessages]
283
+ .reverse()
284
+ .find((m) => m.role === 'assistant' && m.isStreaming);
285
+ if (lastAssistant) {
286
+ newMessages = newMessages.map((m) => m.id === lastAssistant.id
287
+ ? {
288
+ ...m,
289
+ content: msg.content || m.content,
290
+ isStreaming: false,
291
+ }
292
+ : m);
293
+ }
294
+ else if (msg.content) {
295
+ const lastUserMessage = [...newMessages]
296
+ .reverse()
297
+ .find((m) => m.role === 'user');
298
+ const isDuplicateUserMsg = msg.role === 'user' &&
299
+ lastUserMessage &&
300
+ lastUserMessage.content === msg.content;
301
+ if (!isDuplicateUserMsg) {
302
+ newMessages = [
303
+ ...newMessages,
304
+ {
305
+ id: this.generateId(),
306
+ role: msg.role || 'assistant',
307
+ content: msg.content,
308
+ timestamp: Date.now(),
309
+ isStreaming: false,
310
+ },
311
+ ];
312
+ }
313
+ }
314
+ return { ...s, messages: newMessages };
315
+ });
316
+ break;
317
+ case 'agent_end':
318
+ if (this.agentEndTimeout) {
319
+ clearTimeout(this.agentEndTimeout);
320
+ this.agentEndTimeout = null;
321
+ }
322
+ this.agentEndTimeout = setTimeout(() => {
323
+ this.stateStore.update((s) => ({
324
+ ...s,
325
+ isStreaming: false,
326
+ messages: s.messages.map((m) => m.isStreaming ? { ...m, isStreaming: false } : m),
327
+ }));
328
+ this.agentEndTimeout = null;
329
+ }, 300);
330
+ break;
331
+ case 'tool_start':
332
+ if (this.agentEndTimeout) {
333
+ clearTimeout(this.agentEndTimeout);
334
+ this.agentEndTimeout = null;
335
+ }
336
+ const toolArgs = msg.args
337
+ ? Object.entries(msg.args)
338
+ .filter(([k, v]) => v !== undefined && v !== '')
339
+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
340
+ .join(' ')
341
+ : '';
342
+ this.stateStore.update((s) => {
343
+ const finalizedMessages = s.messages.map((m) => m.isStreaming && (m.role === 'assistant' || m.role === 'thinking')
344
+ ? { ...m, isStreaming: false }
345
+ : m);
346
+ const newMsg = {
347
+ id: this.generateId(),
348
+ role: 'tool',
349
+ content: toolArgs
350
+ ? `$ ${msg.toolName} ${toolArgs}`
351
+ : `$ ${msg.toolName}`,
352
+ timestamp: Date.now(),
353
+ isStreaming: true,
354
+ toolName: msg.toolName,
355
+ toolArgs: toolArgs,
356
+ toolOutput: '',
357
+ };
358
+ return {
359
+ ...s,
360
+ messages: [...finalizedMessages, newMsg],
361
+ };
362
+ });
363
+ break;
364
+ case 'tool_update': {
365
+ this.stateStore.update((s) => {
366
+ const toolMsg = [...s.messages]
367
+ .reverse()
368
+ .find((m) => m.role === 'tool' &&
369
+ m.toolName === msg.toolName &&
370
+ m.isStreaming);
371
+ if (toolMsg) {
372
+ return {
373
+ ...s,
374
+ messages: s.messages.map((m) => m.id === toolMsg.id
375
+ ? {
376
+ ...m,
377
+ content: m.content.includes('\n')
378
+ ? m.content + msg.delta
379
+ : `${m.content}\n${msg.delta}`,
380
+ toolOutput: `${m.toolOutput}${msg.delta}`,
381
+ }
382
+ : m),
383
+ };
384
+ }
385
+ return s;
386
+ });
387
+ break;
388
+ }
389
+ case 'tool_end': {
390
+ const result = msg.result ? `${msg.result}` : '';
391
+ this.stateStore.update((s) => {
392
+ const toolMsg = [...s.messages]
393
+ .reverse()
394
+ .find((m) => m.role === 'tool' &&
395
+ m.toolName === msg.toolName &&
396
+ !m.content.startsWith('Tool error:'));
397
+ if (toolMsg) {
398
+ const errorPrefix = msg.isError ? 'Error: ' : '';
399
+ return {
400
+ ...s,
401
+ messages: s.messages.map((m) => m.id === toolMsg.id
402
+ ? {
403
+ ...m,
404
+ content: `${errorPrefix}${m.content}\n${result}`,
405
+ isStreaming: false,
406
+ isError: msg.isError,
407
+ toolOutput: result,
408
+ }
409
+ : m),
410
+ };
411
+ }
412
+ else {
413
+ const content = msg.isError
414
+ ? `Tool error: ${msg.toolName}\n${result}`
415
+ : `${msg.toolName}\n${result}`;
416
+ const message = {
417
+ id: this.generateId(),
418
+ role: 'tool',
419
+ content,
420
+ timestamp: Date.now(),
421
+ isStreaming: false,
422
+ toolName: msg.toolName,
423
+ toolArgs: '',
424
+ toolOutput: result,
425
+ isError: msg.isError,
426
+ };
427
+ return {
428
+ ...s,
429
+ messages: [...s.messages, message],
430
+ };
431
+ }
432
+ });
433
+ break;
434
+ }
435
+ case 'aborted':
436
+ this.stateStore.update((s) => ({
437
+ ...s,
438
+ isStreaming: false,
439
+ messages: s.messages.map((m) => m.isStreaming ? { ...m, isStreaming: false } : m),
440
+ }));
441
+ break;
442
+ case 'session_created':
443
+ this.stateStore.update((s) => ({
444
+ ...s,
445
+ session: msg.sessionFile,
446
+ sessionId: msg.sessionId,
447
+ activeSessionFile: msg.sessionFile,
448
+ activeCwd: msg.cwd,
449
+ activeModel: msg.model,
450
+ isStreaming: msg.isStreaming ?? false,
451
+ creatingSession: false,
452
+ }));
453
+ break;
454
+ case 'session_destroyed':
455
+ this.stateStore.update((s) => {
456
+ if (s.sessionId === msg.sessionId) {
457
+ return {
458
+ ...s,
459
+ messages: [],
460
+ session: null,
461
+ sessionId: null,
462
+ activeSessionFile: null,
463
+ activeCwd: null,
464
+ activeModel: null,
465
+ };
466
+ }
467
+ return s;
468
+ });
469
+ break;
470
+ case 'session_error':
471
+ this.stateStore.update((s) => ({
472
+ ...s,
473
+ sessionError: msg.error,
474
+ isStreaming: false,
475
+ creatingSession: false,
476
+ }));
477
+ break;
478
+ case 'session_conflict':
479
+ this.stateStore.update((s) => ({
480
+ ...s,
481
+ conflict: {
482
+ targetSessionId: msg.sessionId,
483
+ conflictingSessionId: msg.conflictingSession,
484
+ conflictingCwd: msg.conflictingCwd,
485
+ },
486
+ creatingSession: false,
487
+ }));
488
+ break;
489
+ case 'session_interrupted':
490
+ this.stateStore.update((s) => ({
491
+ ...s,
492
+ isInterrupted: true,
493
+ readOnly: true,
494
+ messages: [],
495
+ session: null,
496
+ sessionId: null,
497
+ activeSessionFile: null,
498
+ activeCwd: null,
499
+ activeModel: null,
500
+ creatingSession: false,
501
+ }));
502
+ break;
503
+ case 'message_history':
504
+ this.stateStore.update((s) => {
505
+ const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);
506
+ const totalCount = typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;
507
+ const offset = typeof msg.offset === 'number' ? msg.offset : 0;
508
+ return {
509
+ ...s,
510
+ messages: mapped,
511
+ historyTotalCount: totalCount,
512
+ historyOffset: offset,
513
+ loadingMoreHistory: false,
514
+ };
515
+ });
516
+ break;
517
+ case 'message_history_prepend':
518
+ this.stateStore.update((s) => {
519
+ // Older window prepended ahead of currently-loaded messages. No
520
+ // streaming-tail handling here (those messages are historical).
521
+ const older = this.mapHistory(msg.messages, msg.sessionId, false);
522
+ const offset = typeof msg.offset === 'number' ? msg.offset : 0;
523
+ if (older.length === 0) {
524
+ return { ...s, loadingMoreHistory: false, historyOffset: offset };
525
+ }
526
+ return {
527
+ ...s,
528
+ messages: [...older, ...s.messages],
529
+ historyOffset: offset,
530
+ loadingMoreHistory: false,
531
+ };
532
+ });
533
+ break;
534
+ case 'model_changed':
535
+ this.stateStore.update((s) => ({
536
+ ...s,
537
+ activeModel: msg.model,
538
+ }));
539
+ break;
540
+ }
541
+ }
542
+ /**
543
+ * Map a server `HistoryMessage[]` window into UI `ChatMessage[]`. When
544
+ * `applyStreamingTail` is true, the last assistant/thinking message and any
545
+ * unmatched tool-call placeholders are marked streaming (used only for the
546
+ * live tail window, not for prepended older history).
547
+ */
548
+ mapHistory(rawMessages, sessionId, applyStreamingTail) {
549
+ const mapped = [];
550
+ const pendingCalls = {};
551
+ for (const m of rawMessages) {
552
+ if (m.role === 'tool_call') {
553
+ const tName = m.toolName || 'unknown';
554
+ if (!pendingCalls[tName]) {
555
+ pendingCalls[tName] = [];
556
+ }
557
+ pendingCalls[tName].push(m.content || '');
558
+ }
559
+ else if (m.role === 'tool_result') {
560
+ const tName = m.toolName || 'unknown';
561
+ const tArgs = pendingCalls[tName] && pendingCalls[tName].length > 0
562
+ ? pendingCalls[tName].shift()
563
+ : '';
564
+ mapped.push({
565
+ id: this.generateId(),
566
+ role: 'tool',
567
+ content: tArgs
568
+ ? `$ ${tName} ${tArgs}\n${m.content}`
569
+ : `$ ${tName}\n${m.content}`,
570
+ timestamp: m.timestamp,
571
+ isStreaming: false,
572
+ toolName: tName,
573
+ toolArgs: tArgs,
574
+ toolOutput: m.content,
575
+ isError: m.isError,
576
+ sessionId,
577
+ });
578
+ }
579
+ else {
580
+ mapped.push({
581
+ id: this.generateId(),
582
+ role: m.role,
583
+ content: m.content,
584
+ timestamp: m.timestamp,
585
+ isStreaming: false,
586
+ toolName: m.toolName,
587
+ sessionId,
588
+ });
589
+ }
590
+ }
591
+ for (const [tName, argsList] of Object.entries(pendingCalls)) {
592
+ for (const args of argsList) {
593
+ mapped.push({
594
+ id: this.generateId(),
595
+ role: 'tool',
596
+ content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
597
+ timestamp: mapped.length > 0
598
+ ? mapped[mapped.length - 1].timestamp + 1
599
+ : Date.now(),
600
+ isStreaming: applyStreamingTail,
601
+ toolName: tName,
602
+ toolArgs: args,
603
+ toolOutput: '',
604
+ sessionId,
605
+ });
606
+ }
607
+ }
608
+ if (applyStreamingTail && mapped.length > 0) {
609
+ const lastIndex = mapped.length - 1;
610
+ const lastMsg = mapped[lastIndex];
611
+ if (lastMsg.role === 'assistant' || lastMsg.role === 'thinking') {
612
+ mapped[lastIndex] = {
613
+ ...lastMsg,
614
+ isStreaming: true,
615
+ };
616
+ }
617
+ }
618
+ return mapped;
619
+ }
620
+ /**
621
+ * Request the previous window of older history for the active session.
622
+ * No-op when there is nothing older to load or a request is already in
623
+ * flight.
624
+ */
625
+ loadMoreHistory() {
626
+ const s = get(this.stateStore);
627
+ if (!s.sessionId)
628
+ return;
629
+ if (s.loadingMoreHistory)
630
+ return;
631
+ if (s.historyOffset <= 0)
632
+ return;
633
+ this.stateStore.update((st) => ({
634
+ ...st,
635
+ loadingMoreHistory: true,
636
+ }));
637
+ this.send({
638
+ type: 'history_load_more',
639
+ sessionId: s.sessionId,
640
+ beforeOffset: s.historyOffset,
641
+ });
642
+ }
643
+ send(msg) {
644
+ if (this.ws && this.ws.readyState === 1 /* OPEN */) {
645
+ this.ws.send(JSON.stringify(msg));
646
+ }
647
+ }
648
+ sendMessage(text) {
649
+ const s = get(this.stateStore);
650
+ if (!s.sessionId)
651
+ return;
652
+ this.stateStore.update((s) => ({ ...s, sessionError: null }));
653
+ const message = {
654
+ id: this.generateId(),
655
+ role: 'user',
656
+ content: text,
657
+ timestamp: Date.now(),
658
+ isStreaming: false,
659
+ sessionId: s.sessionId,
660
+ };
661
+ this.stateStore.update((s) => ({
662
+ ...s,
663
+ messages: [...s.messages, message],
664
+ }));
665
+ this.send({ type: 'message', message: text, sessionId: s.sessionId });
666
+ }
667
+ abort() {
668
+ const s = get(this.stateStore);
669
+ if (!s.sessionId)
670
+ return;
671
+ this.send({ type: 'abort', sessionId: s.sessionId });
672
+ }
673
+ joinSession(sessionFile, cwd, model) {
674
+ this.stateStore.update((s) => ({
675
+ ...s,
676
+ conflict: null,
677
+ sessionError: null,
678
+ }));
679
+ this.send({ type: 'session_load', sessionFile, cwd, model });
680
+ }
681
+ createSession(cwd, model, gitInit, createRemote, repoVisibility) {
682
+ this.stateStore.update((s) => ({
683
+ ...s,
684
+ conflict: null,
685
+ sessionError: null,
686
+ creatingSession: true,
687
+ }));
688
+ this.send({
689
+ type: 'session_new',
690
+ cwd,
691
+ model,
692
+ gitInit,
693
+ createRemote,
694
+ repoVisibility,
695
+ });
696
+ }
697
+ leaveSession() {
698
+ const s = get(this.stateStore);
699
+ if (!s.sessionId)
700
+ return;
701
+ this.send({ type: 'session_leave', sessionId: s.sessionId });
702
+ this.stateStore.update((s) => ({
703
+ ...s,
704
+ messages: [],
705
+ session: null,
706
+ sessionId: null,
707
+ activeSessionFile: null,
708
+ activeCwd: null,
709
+ activeModel: null,
710
+ readOnly: false,
711
+ creatingSession: false,
712
+ }));
713
+ }
714
+ resolveConflict(action, cwd) {
715
+ const s = get(this.stateStore);
716
+ if (!s.conflict)
717
+ return;
718
+ this.send({
719
+ type: 'session_resolve_conflict',
720
+ action,
721
+ sessionId: s.conflict.targetSessionId,
722
+ cwd: cwd || s.conflict.conflictingCwd,
723
+ });
724
+ this.stateStore.update((s) => ({
725
+ ...s,
726
+ conflict: null,
727
+ readOnly: action === 'read_only',
728
+ }));
729
+ }
730
+ ping() {
731
+ this.send({ type: 'ping' });
732
+ }
733
+ clearMessages() {
734
+ this.stateStore.update((s) => ({ ...s, messages: [] }));
735
+ }
736
+ dismissSessionError() {
737
+ this.stateStore.update((s) => ({ ...s, sessionError: null }));
738
+ }
739
+ changeModel(model) {
740
+ this.send({ type: 'model_change', model });
741
+ }
742
+ setConfig(updates) {
743
+ this.config = {
744
+ ...this.config,
745
+ ...updates,
746
+ };
747
+ this.stateStore.update((s) => {
748
+ const next = { ...s };
749
+ if (updates.hideThinking !== undefined)
750
+ next.hideThinking = !!updates.hideThinking;
751
+ if (updates.hideTools !== undefined)
752
+ next.hideTools = !!updates.hideTools;
753
+ return next;
754
+ });
755
+ }
756
+ onMessage(cb) {
757
+ this.listeners.add(cb);
758
+ return () => {
759
+ this.listeners.delete(cb);
760
+ };
761
+ }
762
+ uploadFileViaWebSocket(sessionId, filename, base64Data) {
763
+ return new Promise((resolve, reject) => {
764
+ const uploadId = this.generateId();
765
+ this.pendingUploads.set(uploadId, { resolve, reject });
766
+ this.send({
767
+ type: 'file_upload',
768
+ uploadId,
769
+ sessionId,
770
+ filename,
771
+ data: base64Data
772
+ });
773
+ });
774
+ }
775
+ generateId() {
776
+ return Math.random().toString(36).substring(2) + Date.now().toString(36);
777
+ }
778
+ getIsConnected() {
779
+ return this.ws && this.ws.readyState === 1;
780
+ }
781
+ }
782
+ //# sourceMappingURL=client.js.map