-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathqwenAgentManager.ts
More file actions
1515 lines (1399 loc) · 47.6 KB
/
qwenAgentManager.ts
File metadata and controls
1515 lines (1399 loc) · 47.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { AcpConnection } from './acpConnection.js';
import type {
ModelInfo,
AvailableCommand,
ContentBlock,
RequestPermissionRequest,
SessionNotification,
} from '@agentclientprotocol/sdk';
import type {
AuthenticateUpdateNotification,
AskUserQuestionRequest,
} from '../types/acpTypes.js';
import type { ApprovalModeValue } from '../types/approvalModeValueTypes.js';
import { QwenSessionReader, type QwenSession } from './qwenSessionReader.js';
import { QwenSessionManager } from './qwenSessionManager.js';
import type {
ChatMessage,
PlanEntry,
ToolCallUpdateData,
QwenAgentCallbacks,
UsageStatsPayload,
} from '../types/chatTypes.js';
import {
QwenConnectionHandler,
type QwenConnectionResult,
} from '../services/qwenConnectionHandler.js';
import { QwenSessionUpdateHandler } from './qwenSessionUpdateHandler.js';
import { authMethod } from '../types/acpTypes.js';
import {
extractModelInfoFromNewSessionResult,
extractSessionModeState,
extractSessionModelState,
} from '../utils/acpModelInfo.js';
import { isAuthenticationRequiredError } from '../utils/authErrors.js';
import { getErrorMessage } from '../utils/errorMessage.js';
import { handleAuthenticateUpdate } from '../utils/authNotificationHandler.js';
export type { ChatMessage, PlanEntry, ToolCallUpdateData };
/**
* Extract session list items from ACP response.
* Handles both 'sessions' (new) and 'items' (legacy) response shapes.
* @param response - The ACP session/list response
* @returns Array of session items, or empty array if invalid
*/
export function extractSessionListItems(
response: unknown,
): Array<Record<string, unknown>> {
if (!response || typeof response !== 'object') {
return [];
}
const payload = response as {
sessions?: unknown;
items?: unknown;
};
// Prefer 'sessions' field, fall back to 'items' for backwards compatibility
if (Array.isArray(payload.sessions)) {
return payload.sessions as Array<Record<string, unknown>>;
}
if (Array.isArray(payload.items)) {
return payload.items as Array<Record<string, unknown>>;
}
return [];
}
/**
* Qwen Agent Manager
*
* Coordinates various modules and provides unified interface
*/
interface AgentConnectOptions {
autoAuthenticate?: boolean;
}
interface AgentSessionOptions {
autoAuthenticate?: boolean;
}
export class QwenAgentManager {
private connection: AcpConnection;
private sessionReader: QwenSessionReader;
private sessionManager: QwenSessionManager;
private connectionHandler: QwenConnectionHandler;
private sessionUpdateHandler: QwenSessionUpdateHandler;
private currentWorkingDir: string = process.cwd();
// When loading a past session via ACP, the CLI replays history through
// session/update notifications. We set this flag to route message chunks
// (user/assistant) as discrete chat messages instead of live streaming.
private rehydratingSessionId: string | null = null;
// CLI is now the single source of truth for authentication state
// Deduplicate concurrent session/new attempts
private sessionCreateInFlight: Promise<string | null> | null = null;
// Callback storage
private callbacks: QwenAgentCallbacks = {};
// Baseline state from session/new (default/settings-backed), used to clear stale
// UI mode/model when session/load response omits optional fields.
private baselineModeId: ApprovalModeValue = 'default';
private baselineAvailableModes:
| Array<{
id: ApprovalModeValue;
name: string;
description: string;
}>
| undefined;
private baselineModelInfo: ModelInfo | null = null;
private baselineAvailableModels: ModelInfo[] = [];
constructor() {
this.connection = new AcpConnection();
this.sessionReader = new QwenSessionReader();
this.sessionManager = new QwenSessionManager();
this.connectionHandler = new QwenConnectionHandler();
this.sessionUpdateHandler = new QwenSessionUpdateHandler({});
// Set ACP connection callbacks
this.connection.onSessionUpdate = (data: SessionNotification) => {
// If we are rehydrating a loaded session, map message chunks into
// discrete messages for the UI instead of streaming behavior.
// During rehydration the webview is NOT in streaming mode, so
// streaming-only callbacks (onStreamChunk, onThoughtChunk) would be
// silently dropped by the UI. Route all text-bearing updates through
// onMessage which calls addMessage() regardless of streaming state.
try {
const targetId = this.rehydratingSessionId;
if (
targetId &&
typeof data === 'object' &&
data &&
'update' in data &&
(data as { sessionId?: string }).sessionId === targetId
) {
const update = (
data as unknown as {
update: {
sessionUpdate: string;
content?: { text?: string };
_meta?: Record<string, unknown>;
};
}
).update;
const text = update?.content?.text || '';
const metaObj = update?._meta ?? {};
const timestamp =
typeof metaObj['timestamp'] === 'number'
? (metaObj['timestamp'] as number)
: Date.now();
if (update?.sessionUpdate === 'user_message_chunk' && text) {
this.callbacks.onMessage?.({
role: 'user',
content: text,
timestamp,
});
return;
}
if (update?.sessionUpdate === 'agent_message_chunk' && text) {
this.callbacks.onMessage?.({
role: 'assistant',
content: text,
timestamp,
});
return;
}
if (update?.sessionUpdate === 'agent_thought_chunk' && text) {
this.callbacks.onMessage?.({
role: 'thinking',
content: text,
timestamp,
});
return;
}
// Usage-only agent_message_chunk (empty text): forward usage but
// skip the empty stream chunk that would be discarded anyway.
if (
update?.sessionUpdate === 'agent_message_chunk' &&
!text &&
metaObj['usage']
) {
if (this.callbacks.onUsageUpdate) {
const raw = metaObj['usage'] as Record<string, unknown>;
this.callbacks.onUsageUpdate({
usage: {
inputTokens: raw['inputTokens'] as number | undefined,
outputTokens: raw['outputTokens'] as number | undefined,
totalTokens: raw['totalTokens'] as number | undefined,
thoughtTokens: raw['thoughtTokens'] as number | undefined,
cachedReadTokens: raw['cachedReadTokens'] as
| number
| undefined,
},
durationMs: metaObj['durationMs'] as number | undefined,
});
}
return;
}
// Tool calls, plans, mode/model updates: fall through to the
// normal handler which emits them via dedicated callbacks that
// the webview can process independently of streaming state.
}
} catch (err) {
console.warn('[QwenAgentManager] Rehydration routing failed:', err);
}
// Default handling path
this.sessionUpdateHandler.handleSessionUpdate(data);
};
this.connection.onPermissionRequest = async (
data: RequestPermissionRequest,
) => {
if (this.callbacks.onPermissionRequest) {
const optionId = await this.callbacks.onPermissionRequest(data);
return {
optionId:
this.resolvePermissionOptionId(data, optionId) ||
this.resolvePermissionOptionId(data) ||
'',
};
}
return { optionId: this.resolvePermissionOptionId(data) || '' };
};
this.connection.onAskUserQuestion = async (
data: AskUserQuestionRequest,
) => {
if (this.callbacks.onAskUserQuestion) {
const result = await this.callbacks.onAskUserQuestion(data);
return result;
}
return { optionId: 'cancel' };
};
this.connection.onEndTurn = (reason?: string) => {
try {
if (this.callbacks.onEndTurn) {
this.callbacks.onEndTurn(reason);
} else if (this.callbacks.onStreamChunk) {
// Fallback: send a zero-length chunk then rely on streamEnd elsewhere
this.callbacks.onStreamChunk('');
}
} catch (err) {
console.warn('[QwenAgentManager] onEndTurn callback error:', err);
}
};
this.connection.onAuthenticateUpdate = (
data: AuthenticateUpdateNotification,
) => {
try {
// Handle authentication update notifications by showing VS Code notification
handleAuthenticateUpdate(data);
} catch (err) {
console.warn(
'[QwenAgentManager] onAuthenticateUpdate callback error:',
err,
);
}
};
// Initialize callback to surface available modes and current mode to UI
this.connection.onInitialized = (init: unknown) => {
try {
const obj = (init || {}) as Record<string, unknown>;
const modes = obj['modes'] as
| {
currentModeId?: 'plan' | 'default' | 'auto-edit' | 'yolo';
availableModes?: Array<{
id: 'plan' | 'default' | 'auto-edit' | 'yolo';
name: string;
description: string;
}>;
}
| undefined;
if (modes && this.callbacks.onModeInfo) {
this.callbacks.onModeInfo({
currentModeId: modes.currentModeId,
availableModes: modes.availableModes,
});
}
} catch (err) {
console.warn('[QwenAgentManager] onInitialized parse error:', err);
}
};
}
/**
* Connect to Qwen service
*
* @param workingDir - Working directory
* @param cliEntryPath - Path to bundled CLI entrypoint (cli.js)
*/
async connect(
workingDir: string,
cliEntryPath: string,
options?: AgentConnectOptions,
): Promise<QwenConnectionResult> {
this.currentWorkingDir = workingDir;
const res = await this.connectionHandler.connect(
this.connection,
workingDir,
cliEntryPath,
options,
);
if (res.modelInfo && this.callbacks.onModelInfo) {
this.baselineModelInfo = res.modelInfo;
this.callbacks.onModelInfo(res.modelInfo);
}
// Emit available models from connect result
if (res.availableModels && res.availableModels.length > 0) {
this.baselineAvailableModels = res.availableModels;
console.log(
'[QwenAgentManager] Emitting availableModels from connect():',
res.availableModels.map((m) => m.modelId),
);
if (this.callbacks.onAvailableModels) {
this.callbacks.onAvailableModels(res.availableModels);
}
}
if (res.currentModeId) {
this.baselineModeId = res.currentModeId;
this.callbacks.onModeChanged?.(res.currentModeId);
}
if (res.availableModes) {
this.baselineAvailableModes = res.availableModes;
this.callbacks.onModeInfo?.({
currentModeId: res.currentModeId ?? this.baselineModeId,
availableModes: res.availableModes,
});
} else if (res.currentModeId) {
this.callbacks.onModeInfo?.({
currentModeId: res.currentModeId,
});
}
return res;
}
/**
* Send message
*
* @param message - Message content
*/
async sendMessage(message: string | ContentBlock[]): Promise<void> {
await this.connection.sendPrompt(message);
}
/**
* Set approval mode from UI
*/
async setApprovalModeFromUi(
mode: ApprovalModeValue,
): Promise<ApprovalModeValue> {
const modeId = mode;
try {
await this.connection.setMode(modeId);
// set_mode response has no mode payload; use requested value.
const confirmed = modeId;
this.callbacks.onModeChanged?.(confirmed);
return confirmed;
} catch (err) {
console.error('[QwenAgentManager] Failed to set mode:', err);
throw err;
}
}
/**
* Set model from UI
*/
async setModelFromUi(modelId: string): Promise<ModelInfo | null> {
try {
await this.connection.setModel(modelId);
const confirmedModelId = modelId;
const modelInfo = this.baselineAvailableModels.find(
(model) => model.modelId === confirmedModelId,
) ?? {
modelId: confirmedModelId,
name: confirmedModelId,
};
this.baselineModelInfo = modelInfo;
this.callbacks.onModelChanged?.(modelInfo);
return modelInfo;
} catch (err) {
console.error('[QwenAgentManager] Failed to set model:', err);
throw err;
}
}
/**
* Validate if current session is still active
* This is a lightweight check to verify session validity
*
* @returns True if session is valid, false otherwise
*/
async validateCurrentSession(): Promise<boolean> {
try {
// If we don't have a current session, it's definitely not valid
if (!this.connection.currentSessionId) {
return false;
}
// Try to get session list to verify our session still exists
const sessions = await this.getSessionList();
const currentSessionId = this.connection.currentSessionId;
// Check if our current session exists in the session list
const sessionExists = sessions.some(
(session: Record<string, unknown>) =>
session.id === currentSessionId ||
session.sessionId === currentSessionId,
);
return sessionExists;
} catch (error) {
console.warn('[QwenAgentManager] Session validation failed:', error);
// If we can't validate, assume session is invalid
return false;
}
}
/**
* Get session list with version-aware strategy
* First tries ACP method if CLI version supports it, falls back to file system method
*
* @returns Session list
*/
async getSessionList(): Promise<Array<Record<string, unknown>>> {
console.log(
'[QwenAgentManager] Getting session list with version-aware strategy',
);
try {
console.log(
'[QwenAgentManager] Attempting to get session list via ACP method',
);
const response = await this.connection.listSessions();
console.log('[QwenAgentManager] ACP session list response:', response);
const res: unknown = response;
const items = extractSessionListItems(res);
console.log(
'[QwenAgentManager] Sessions retrieved via ACP:',
res,
items.length,
);
if (items.length > 0) {
const sessions = items.map((item) => ({
id: item.sessionId || item.id,
sessionId: item.sessionId || item.id,
title: item.title || item.name || item.prompt || 'Untitled Session',
name: item.title || item.name || item.prompt || 'Untitled Session',
startTime: item.startTime,
lastUpdated: item.updatedAt || item.mtime || item.lastUpdated,
messageCount: item.messageCount || 0,
projectHash: item.projectHash,
filePath: item.filePath,
cwd: item.cwd,
}));
console.log(
'[QwenAgentManager] Sessions retrieved via ACP:',
sessions.length,
);
return sessions;
}
} catch (error) {
console.warn(
'[QwenAgentManager] ACP session list failed, falling back to file system method:',
error,
);
}
// Always fall back to file system method
try {
console.log('[QwenAgentManager] Getting session list from file system');
const sessions = await this.sessionReader.getAllSessions(undefined, true);
console.log(
'[QwenAgentManager] Session list from file system (all projects):',
sessions.length,
);
const result = sessions.map(
(session: QwenSession): Record<string, unknown> => ({
id: session.sessionId,
sessionId: session.sessionId,
title: this.sessionReader.getSessionTitle(session),
name: this.sessionReader.getSessionTitle(session),
startTime: session.startTime,
lastUpdated: session.lastUpdated,
messageCount: session.messageCount ?? session.messages.length,
projectHash: session.projectHash,
filePath: session.filePath,
cwd: session.cwd,
}),
);
console.log(
'[QwenAgentManager] Sessions retrieved from file system:',
result.length,
);
return result;
} catch (error) {
console.error(
'[QwenAgentManager] Failed to get session list from file system:',
error,
);
return [];
}
}
/**
* Get session list (paged)
* Uses ACP session/list with cursor-based pagination when available.
* Falls back to file system scan with equivalent pagination semantics.
*/
async getSessionListPaged(params?: {
cursor?: number;
size?: number;
}): Promise<{
sessions: Array<Record<string, unknown>>;
nextCursor?: number;
hasMore: boolean;
}> {
const size = params?.size ?? 20;
const cursor = params?.cursor;
try {
const response = await this.connection.listSessions({
size,
...(cursor !== undefined ? { cursor } : {}),
});
const res: unknown = response;
const items = extractSessionListItems(res);
const mapped = items.map((item) => ({
id: item.sessionId || item.id,
sessionId: item.sessionId || item.id,
title: item.title || item.name || item.prompt || 'Untitled Session',
name: item.title || item.name || item.prompt || 'Untitled Session',
startTime: item.startTime,
lastUpdated: item.updatedAt || item.mtime || item.lastUpdated,
messageCount: item.messageCount || 0,
projectHash: item.projectHash,
filePath: item.filePath,
cwd: item.cwd,
}));
// SDK returns nextCursor as string; convert to numeric cursor for paging
let nextCursorNum: number | undefined;
if (typeof res === 'object' && res !== null && 'nextCursor' in res) {
const raw = (res as { nextCursor?: unknown }).nextCursor;
if (typeof raw === 'number') {
nextCursorNum = raw;
} else if (typeof raw === 'string') {
const parsed = Number(raw);
if (!Number.isNaN(parsed)) {
nextCursorNum = parsed;
}
}
}
const hasMore = nextCursorNum !== undefined;
return { sessions: mapped, nextCursor: nextCursorNum, hasMore };
} catch (error) {
console.warn('[QwenAgentManager] Paged ACP session list failed:', error);
// fall through to file system
}
// Fallback: file system for current project only (to match ACP semantics)
try {
const all = await this.sessionReader.getAllSessions(
this.currentWorkingDir,
false,
);
// Sorted by lastUpdated desc already per reader
const allWithMtime = all.map((s) => ({
raw: s,
mtime: new Date(s.lastUpdated).getTime(),
}));
const filtered =
cursor !== undefined
? allWithMtime.filter((x) => x.mtime < cursor)
: allWithMtime;
const page = filtered.slice(0, size);
const sessions = page.map((x) => ({
id: x.raw.sessionId,
sessionId: x.raw.sessionId,
title: this.sessionReader.getSessionTitle(x.raw),
name: this.sessionReader.getSessionTitle(x.raw),
startTime: x.raw.startTime,
lastUpdated: x.raw.lastUpdated,
messageCount: x.raw.messageCount ?? x.raw.messages.length,
projectHash: x.raw.projectHash,
filePath: x.raw.filePath,
cwd: x.raw.cwd,
}));
const nextCursorVal =
page.length > 0 ? page[page.length - 1].mtime : undefined;
const hasMore = filtered.length > size;
return { sessions, nextCursor: nextCursorVal, hasMore };
} catch (error) {
console.error('[QwenAgentManager] File system paged list failed:', error);
return { sessions: [], hasMore: false };
}
}
/**
* Get session messages (read from disk)
*
* @param sessionId - Session ID
* @returns Message list
*/
async getSessionMessages(sessionId: string): Promise<ChatMessage[]> {
try {
try {
const list = await this.getSessionList();
const item = list.find(
(s) => s.sessionId === sessionId || s.id === sessionId,
);
console.log(
'[QwenAgentManager] Session list item for filePath lookup:',
item,
);
if (
typeof item === 'object' &&
item !== null &&
'filePath' in item &&
typeof item.filePath === 'string'
) {
const messages = await this.readJsonlMessages(item.filePath);
// Even if messages array is empty, we should return it rather than falling back
// This ensures we don't accidentally show messages from a different session format
return messages;
}
} catch (e) {
console.warn('[QwenAgentManager] JSONL read path lookup failed:', e);
}
// Fallback: legacy JSON session files
const session = await this.sessionReader.getSession(
sessionId,
this.currentWorkingDir,
);
if (!session) {
return [];
}
return session.messages.map(
(msg: { type: string; content: string; timestamp: string }) => ({
role: msg.type === 'user' ? 'user' : 'assistant',
content: msg.content,
timestamp: new Date(msg.timestamp).getTime(),
}),
);
} catch (error) {
console.error(
'[QwenAgentManager] Failed to get session messages:',
error,
);
return [];
}
}
// Read CLI JSONL session file and convert to ChatMessage[] for UI
private async readJsonlMessages(filePath: string): Promise<ChatMessage[]> {
const fs = await import('fs');
const readline = await import('readline');
try {
if (!fs.existsSync(filePath)) {
return [];
}
const fileStream = fs.createReadStream(filePath, { encoding: 'utf-8' });
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
const records: unknown[] = [];
for await (const line of rl) {
const trimmed = line.trim();
if (!trimmed) {
continue;
}
try {
const obj = JSON.parse(trimmed);
records.push(obj);
} catch {
/* ignore */
}
}
// Simple linear reconstruction: filter user/assistant and sort by timestamp
console.log(
'[QwenAgentManager] JSONL records read:',
records.length,
filePath,
);
// Include all types of records, not just user/assistant
// Narrow unknown JSONL rows into a minimal shape we can work with.
type JsonlRecord = {
type: string;
timestamp: string;
message?: unknown;
toolCallResult?: { callId?: string; status?: string } | unknown;
subtype?: string;
systemPayload?: { uiEvent?: Record<string, unknown> } | unknown;
plan?: { entries?: Array<Record<string, unknown>> } | unknown;
};
const isJsonlRecord = (x: unknown): x is JsonlRecord =>
typeof x === 'object' &&
x !== null &&
typeof (x as Record<string, unknown>).type === 'string' &&
typeof (x as Record<string, unknown>).timestamp === 'string';
const allRecords = records
.filter(isJsonlRecord)
.sort(
(a, b) =>
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
);
const msgs: ChatMessage[] = [];
for (const r of allRecords) {
// Handle user and assistant messages
if ((r.type === 'user' || r.type === 'assistant') && r.message) {
msgs.push({
role:
r.type === 'user' ? ('user' as const) : ('assistant' as const),
content: this.contentToText(r.message),
timestamp: new Date(r.timestamp).getTime(),
});
}
// Handle tool call records that might have content we want to show
else if (r.type === 'tool_call' || r.type === 'tool_call_update') {
// Convert tool calls to messages if they have relevant content
const toolContent = this.extractToolCallContent(r as unknown);
if (toolContent) {
msgs.push({
role: 'assistant',
content: toolContent,
timestamp: new Date(r.timestamp).getTime(),
});
}
}
// Handle tool result records
else if (
r.type === 'tool_result' &&
r.toolCallResult &&
typeof r.toolCallResult === 'object'
) {
const toolResult = r.toolCallResult as {
callId?: string;
status?: string;
};
const callId = toolResult.callId ?? 'unknown';
const status = toolResult.status ?? 'unknown';
const resultText = `Tool Result (${callId}): ${status}`;
msgs.push({
role: 'assistant',
content: resultText,
timestamp: new Date(r.timestamp).getTime(),
});
}
// Handle system telemetry records
else if (
r.type === 'system' &&
r.subtype === 'ui_telemetry' &&
r.systemPayload &&
typeof r.systemPayload === 'object' &&
'uiEvent' in r.systemPayload &&
(r.systemPayload as { uiEvent?: Record<string, unknown> }).uiEvent
) {
const uiEvent = (
r.systemPayload as {
uiEvent?: Record<string, unknown>;
}
).uiEvent as Record<string, unknown>;
let telemetryText = '';
if (
typeof uiEvent['event.name'] === 'string' &&
(uiEvent['event.name'] as string).includes('tool_call')
) {
const functionName =
(uiEvent['function_name'] as string | undefined) ||
'Unknown tool';
const status =
(uiEvent['status'] as string | undefined) || 'unknown';
const duration =
typeof uiEvent['duration_ms'] === 'number'
? ` (${uiEvent['duration_ms']}ms)`
: '';
telemetryText = `Tool Call: ${functionName} - ${status}${duration}`;
} else if (
typeof uiEvent['event.name'] === 'string' &&
(uiEvent['event.name'] as string).includes('api_response')
) {
const statusCode =
(uiEvent['status_code'] as string | number | undefined) ||
'unknown';
const duration =
typeof uiEvent['duration_ms'] === 'number'
? ` (${uiEvent['duration_ms']}ms)`
: '';
telemetryText = `API Response: Status ${statusCode}${duration}`;
} else {
// Generic system telemetry
const eventName =
(uiEvent['event.name'] as string | undefined) || 'Unknown event';
telemetryText = `System Event: ${eventName}`;
}
if (telemetryText) {
msgs.push({
role: 'assistant',
content: telemetryText,
timestamp: new Date(r.timestamp).getTime(),
});
}
}
// Handle plan entries
else if (
r.type === 'plan' &&
r.plan &&
typeof r.plan === 'object' &&
'entries' in r.plan
) {
const planEntries =
((r.plan as { entries?: Array<Record<string, unknown>> })
.entries as Array<Record<string, unknown>> | undefined) || [];
if (planEntries.length > 0) {
const planText = planEntries
.map(
(entry: Record<string, unknown>, index: number) =>
`${index + 1}. ${
entry.description || entry.title || 'Unnamed step'
}`,
)
.join('\n');
msgs.push({
role: 'assistant',
content: `Plan:\n${planText}`,
timestamp: new Date(r.timestamp).getTime(),
});
}
}
// Handle other types if needed
}
console.log(
'[QwenAgentManager] JSONL messages reconstructed:',
msgs.length,
);
return msgs;
} catch (err) {
console.warn('[QwenAgentManager] Failed to read JSONL messages:', err);
return [];
}
}
// Extract meaningful content from tool call records
private extractToolCallContent(record: unknown): string | null {
try {
// Type guard for record
if (typeof record !== 'object' || record === null) {
return null;
}
// Cast to a more specific type for easier handling
const typedRecord = record as Record<string, unknown>;
// If the tool call has a result or output, include it
if ('toolCallResult' in typedRecord && typedRecord.toolCallResult) {
return `Tool result: ${this.formatValue(typedRecord.toolCallResult)}`;
}
// If the tool call has content, include it
if ('content' in typedRecord && typedRecord.content) {
return this.formatValue(typedRecord.content);
}
// If the tool call has a title or name, include it
if (
('title' in typedRecord && typedRecord.title) ||
('name' in typedRecord && typedRecord.name)
) {
return `Tool: ${typedRecord.title || typedRecord.name}`;
}
// Handle tool_call records with more details
if (
typedRecord.type === 'tool_call' &&
'toolCall' in typedRecord &&
typedRecord.toolCall
) {
const toolCall = typedRecord.toolCall as Record<string, unknown>;
if (
('title' in toolCall && toolCall.title) ||
('name' in toolCall && toolCall.name)
) {
return `Tool call: ${toolCall.title || toolCall.name}`;
}
if ('rawInput' in toolCall && toolCall.rawInput) {
return `Tool input: ${this.formatValue(toolCall.rawInput)}`;
}
}
// Handle tool_call_update records with status
if (typedRecord.type === 'tool_call_update') {
const status =
('status' in typedRecord && typedRecord.status) || 'unknown';
const title =
('title' in typedRecord && typedRecord.title) ||
('name' in typedRecord && typedRecord.name) ||
'Unknown tool';
return `Tool ${status}: ${title}`;
}
return null;
} catch {
return null;
}
}
// Format any value to a string for display
private formatValue(value: unknown): string {
if (value === null || value === undefined) {
return '';
}
if (typeof value === 'string') {
return value;
}
if (typeof value === 'object') {
try {
return JSON.stringify(value, null, 2);
} catch (_e) {
return String(value);
}
}
return String(value);
}
// Extract plain text from Content (genai Content)
private contentToText(message: unknown): string {
try {
// Type guard for message
if (typeof message !== 'object' || message === null) {
return '';
}
// Cast to a more specific type for easier handling
const typedMessage = message as Record<string, unknown>;
const parts = Array.isArray(typedMessage.parts) ? typedMessage.parts : [];
const texts: string[] = [];
for (const p of parts) {
// Type guard for part
if (typeof p !== 'object' || p === null) {
continue;
}
const typedPart = p as Record<string, unknown>;
if (typeof typedPart.text === 'string') {
texts.push(typedPart.text);
} else if (typeof typedPart.data === 'string') {
texts.push(typedPart.data);
}
}
return texts.join('\n');
} catch {
return '';
}
}
/**
* Try to load session via ACP session/load method
* This method will only be used if CLI version supports it
*
* @param sessionId - Session ID
* @returns Load response or error
*/
async loadSessionViaAcp(
sessionId: string,
cwdOverride?: string,
): Promise<unknown> {
try {
// Route upcoming session/update messages as discrete messages for replay
this.rehydratingSessionId = sessionId;
console.log(