@love-moon/conductor-cli 0.2.15 → 0.2.17

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.
@@ -1,716 +0,0 @@
1
- import fs from "node:fs";
2
- import { promises as fsp } from "node:fs";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import readline from "node:readline";
6
- import enquirer from "enquirer";
7
-
8
- const { Select } = enquirer;
9
-
10
- const SUPPORTED_FROM_PROVIDERS = ["codex", "claude"];
11
- const DEFAULT_HISTORY_LIMIT = 50;
12
- const DEFAULT_SESSION_LIMIT = 20;
13
-
14
- export function parseFromSpec(rawFrom, rawProvider, defaultProvider) {
15
- if (!rawFrom) {
16
- return null;
17
- }
18
-
19
- const providerOverride = rawProvider ? String(rawProvider).trim().toLowerCase() : "";
20
- if (providerOverride && !SUPPORTED_FROM_PROVIDERS.includes(providerOverride)) {
21
- throw new Error(`Unsupported --from-provider: ${rawProvider}`);
22
- }
23
-
24
- if (rawFrom === true) {
25
- const provider = providerOverride || defaultProvider;
26
- if (!provider) {
27
- throw new Error(
28
- "Missing provider for --from. Use --from <provider>:<sessionId> or --from-provider <provider>."
29
- );
30
- }
31
- return { provider, sessionId: "" };
32
- }
33
-
34
- const text = typeof rawFrom === "string" ? rawFrom.trim() : "";
35
- if (!text) {
36
- const provider = providerOverride || defaultProvider;
37
- if (!provider) {
38
- return null;
39
- }
40
- return { provider, sessionId: "" };
41
- }
42
-
43
- let provider = providerOverride || "";
44
- let sessionId = text;
45
-
46
- const colonIndex = text.indexOf(":");
47
- if (colonIndex > 0) {
48
- const maybeProvider = text.slice(0, colonIndex).trim().toLowerCase();
49
- const maybeSession = text.slice(colonIndex + 1).trim();
50
- if (SUPPORTED_FROM_PROVIDERS.includes(maybeProvider)) {
51
- provider = maybeProvider;
52
- sessionId = maybeSession;
53
- }
54
- }
55
-
56
- if (!provider) {
57
- provider = defaultProvider || "";
58
- }
59
-
60
- if (!provider) {
61
- throw new Error(
62
- "Missing provider for --from. Use --from <provider>:<sessionId> or --from-provider <provider>."
63
- );
64
- }
65
-
66
- if (!sessionId) {
67
- return { provider, sessionId: "" };
68
- }
69
-
70
- return { provider, sessionId };
71
- }
72
-
73
- export async function loadHistoryFromSpec(spec, options = {}) {
74
- if (!spec) {
75
- return { history: [], source: null, provider: null, sessionId: null };
76
- }
77
- const provider = spec.provider;
78
- if (!SUPPORTED_FROM_PROVIDERS.includes(provider)) {
79
- throw new Error(`Unsupported --from provider: ${provider}`);
80
- }
81
- if (provider === "codex") {
82
- return loadCodexHistory(spec.sessionId, options);
83
- }
84
- return loadClaudeHistory(spec.sessionId, options);
85
- }
86
-
87
- export async function listHistorySessions(provider, options = {}) {
88
- if (!SUPPORTED_FROM_PROVIDERS.includes(provider)) {
89
- throw new Error(`Unsupported --from provider: ${provider}`);
90
- }
91
- if (provider === "codex") {
92
- return listCodexSessions(options);
93
- }
94
- return listClaudeSessions(options);
95
- }
96
-
97
- export async function selectHistorySession(provider, options = {}) {
98
- const sessions = await listHistorySessions(provider, options);
99
- if (!sessions.length) {
100
- return null;
101
- }
102
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
103
- throw new Error("Interactive --from requires a TTY.");
104
- }
105
-
106
- const choices = sessions.map((session) => ({
107
- name: session.sessionId,
108
- message: formatSessionLine(session),
109
- value: session
110
- }));
111
- choices.push({
112
- name: "__cancel__",
113
- message: "Cancel",
114
- value: null
115
- });
116
-
117
- const prompt = new Select({
118
- name: "session",
119
- message: `Select a ${provider} session to resume`,
120
- choices,
121
- initial: 0
122
- });
123
-
124
- const selected = await prompt.run();
125
- return selected || null;
126
- }
127
-
128
- export async function findSessionPath(provider, sessionId, options = {}) {
129
- const normalizedProvider = String(provider || "").trim().toLowerCase();
130
- if (normalizedProvider === "codex") {
131
- return findCodexSessionPath(sessionId, options);
132
- }
133
- if (normalizedProvider === "claude") {
134
- return findClaudeSessionPath(sessionId, options);
135
- }
136
- if (normalizedProvider === "copilot") {
137
- return findCopilotSessionPath(sessionId, options);
138
- }
139
- throw new Error(`Unsupported provider: ${provider}`);
140
- }
141
-
142
- export async function findCodexSessionPath(sessionId, options = {}) {
143
- const normalizedSessionId = normalizeSessionId(sessionId);
144
- if (!normalizedSessionId) {
145
- return null;
146
- }
147
- const homeDir = resolveHomeDir(options);
148
- const sessionsDir = options.codexSessionsDir || path.join(homeDir, ".codex", "sessions");
149
- return findCodexSessionFile(sessionsDir, normalizedSessionId);
150
- }
151
-
152
- export async function findClaudeSessionPath(sessionId, options = {}) {
153
- const normalizedSessionId = normalizeSessionId(sessionId);
154
- if (!normalizedSessionId) {
155
- return null;
156
- }
157
-
158
- const homeDir = resolveHomeDir(options);
159
- const projectsDir = options.claudeProjectsDir || path.join(homeDir, ".claude", "projects");
160
- const sessionEntries = await findClaudeSessionEntries(projectsDir, normalizedSessionId);
161
- if (sessionEntries.length > 0) {
162
- return sessionEntries[0]?.source || null;
163
- }
164
-
165
- const tasksDir = options.claudeTasksDir || path.join(homeDir, ".claude", "tasks");
166
- const directTaskDir = path.join(tasksDir, normalizedSessionId);
167
- if (await pathExists(directTaskDir, "directory")) {
168
- return directTaskDir;
169
- }
170
-
171
- return null;
172
- }
173
-
174
- export async function findCopilotSessionPath(sessionId, options = {}) {
175
- const normalizedSessionId = normalizeSessionId(sessionId);
176
- if (!normalizedSessionId) {
177
- return null;
178
- }
179
-
180
- const homeDir = resolveHomeDir(options);
181
- const sessionStateDir = options.copilotSessionStateDir || path.join(homeDir, ".copilot", "session-state");
182
- const directJsonlPath = path.join(sessionStateDir, `${normalizedSessionId}.jsonl`);
183
- if (await pathExists(directJsonlPath, "file")) {
184
- return directJsonlPath;
185
- }
186
-
187
- const directSessionDir = path.join(sessionStateDir, normalizedSessionId);
188
- if (await pathExists(directSessionDir, "directory")) {
189
- return directSessionDir;
190
- }
191
-
192
- return findPathByName(sessionStateDir, normalizedSessionId);
193
- }
194
-
195
- function resolveHomeDir(options) {
196
- if (options?.homeDir) {
197
- return options.homeDir;
198
- }
199
- return os.homedir();
200
- }
201
-
202
- function normalizeSessionId(sessionId) {
203
- return typeof sessionId === "string" ? sessionId.trim() : "";
204
- }
205
-
206
- function trimHistory(history, limit) {
207
- const max = Number.isFinite(limit) ? Math.max(1, limit) : DEFAULT_HISTORY_LIMIT;
208
- if (history.length <= max) {
209
- return history;
210
- }
211
- return history.slice(history.length - max);
212
- }
213
-
214
- async function loadCodexHistory(sessionId, options = {}) {
215
- const homeDir = resolveHomeDir(options);
216
- const sessionsDir = options.codexSessionsDir || path.join(homeDir, ".codex", "sessions");
217
- const sessionFile = await findCodexSessionFile(sessionsDir, sessionId);
218
-
219
- if (!sessionFile) {
220
- return {
221
- provider: "codex",
222
- sessionId,
223
- history: [],
224
- source: null,
225
- warning: `Codex session file not found for ${sessionId}`
226
- };
227
- }
228
-
229
- const messages = [];
230
- const rl = readline.createInterface({
231
- input: fs.createReadStream(sessionFile),
232
- crlfDelay: Infinity
233
- });
234
-
235
- for await (const line of rl) {
236
- const trimmed = line.trim();
237
- if (!trimmed) {
238
- continue;
239
- }
240
- let entry;
241
- try {
242
- entry = JSON.parse(trimmed);
243
- } catch {
244
- continue;
245
- }
246
-
247
- if (entry.type === "event_msg" && entry.payload?.type === "user_message") {
248
- const content = String(entry.payload.message || "").trim();
249
- if (content) {
250
- messages.push({
251
- role: "user",
252
- content,
253
- timestamp: entry.timestamp || Date.now()
254
- });
255
- }
256
- continue;
257
- }
258
-
259
- if (entry.type === "response_item" && entry.payload?.type === "message") {
260
- const role = entry.payload.role || "assistant";
261
- const textContent = extractCodexText(entry.payload.content);
262
- if (!textContent || textContent.includes("<environment_context>")) {
263
- continue;
264
- }
265
- if (textContent.trim()) {
266
- messages.push({
267
- role: role === "user" ? "user" : "assistant",
268
- content: textContent.trim(),
269
- timestamp: entry.timestamp || Date.now()
270
- });
271
- }
272
- }
273
- }
274
-
275
- const history = trimHistory(
276
- messages
277
- .sort((a, b) => new Date(a.timestamp || 0) - new Date(b.timestamp || 0))
278
- .map(({ role, content }) => ({ role, content })),
279
- options.maxMessages
280
- );
281
-
282
- return {
283
- provider: "codex",
284
- sessionId,
285
- history,
286
- source: sessionFile
287
- };
288
- }
289
-
290
- async function listCodexSessions(options = {}) {
291
- const homeDir = resolveHomeDir(options);
292
- const sessionsDir = options.codexSessionsDir || path.join(homeDir, ".codex", "sessions");
293
- const jsonlFiles = await findJsonlFiles(sessionsDir);
294
- const sessions = [];
295
-
296
- for (const filePath of jsonlFiles) {
297
- const session = await parseCodexSessionFile(filePath);
298
- if (session) {
299
- sessions.push(session);
300
- }
301
- }
302
-
303
- sessions.sort((a, b) => new Date(b.lastActivity || 0) - new Date(a.lastActivity || 0));
304
- return sessions.slice(0, options.sessionLimit ?? DEFAULT_SESSION_LIMIT);
305
- }
306
-
307
- async function loadClaudeHistory(sessionId, options = {}) {
308
- const homeDir = resolveHomeDir(options);
309
- const projectsDir = options.claudeProjectsDir || path.join(homeDir, ".claude", "projects");
310
- const sessionEntries = await findClaudeSessionEntries(projectsDir, sessionId);
311
-
312
- if (!sessionEntries.length) {
313
- return {
314
- provider: "claude",
315
- sessionId,
316
- history: [],
317
- source: null,
318
- warning: `Claude session not found for ${sessionId}`
319
- };
320
- }
321
-
322
- const history = [];
323
- const sorted = sessionEntries.sort(
324
- (a, b) => new Date(a.timestamp || 0) - new Date(b.timestamp || 0)
325
- );
326
-
327
- for (const entry of sorted) {
328
- const message = entry.message;
329
- if (!message || !message.role || !message.content) {
330
- continue;
331
- }
332
- const role = String(message.role).toLowerCase();
333
- if (role !== "user" && role !== "assistant") {
334
- continue;
335
- }
336
- const content = extractClaudeText(message.content);
337
- if (!content) {
338
- continue;
339
- }
340
- if (shouldSkipClaudeMessage(content)) {
341
- continue;
342
- }
343
- history.push({ role, content });
344
- }
345
-
346
- return {
347
- provider: "claude",
348
- sessionId,
349
- history: trimHistory(history, options.maxMessages),
350
- source: sessionEntries[0]?.source || null
351
- };
352
- }
353
-
354
- async function listClaudeSessions(options = {}) {
355
- const homeDir = resolveHomeDir(options);
356
- const projectsDir = options.claudeProjectsDir || path.join(homeDir, ".claude", "projects");
357
- const sessions = new Map();
358
-
359
- let projectDirs = [];
360
- try {
361
- projectDirs = await fsp.readdir(projectsDir, { withFileTypes: true });
362
- } catch {
363
- return [];
364
- }
365
-
366
- for (const projectDir of projectDirs) {
367
- if (!projectDir.isDirectory()) {
368
- continue;
369
- }
370
- const projectPath = path.join(projectsDir, projectDir.name);
371
- let files = [];
372
- try {
373
- files = await fsp.readdir(projectPath, { withFileTypes: true });
374
- } catch {
375
- continue;
376
- }
377
-
378
- for (const file of files) {
379
- if (!file.isFile()) {
380
- continue;
381
- }
382
- if (!file.name.endsWith(".jsonl") || file.name.startsWith("agent-")) {
383
- continue;
384
- }
385
- const filePath = path.join(projectPath, file.name);
386
- const rl = readline.createInterface({
387
- input: fs.createReadStream(filePath),
388
- crlfDelay: Infinity
389
- });
390
-
391
- for await (const line of rl) {
392
- const trimmed = line.trim();
393
- if (!trimmed) {
394
- continue;
395
- }
396
- let entry;
397
- try {
398
- entry = JSON.parse(trimmed);
399
- } catch {
400
- continue;
401
- }
402
- if (!entry.sessionId) {
403
- continue;
404
- }
405
- const sessionId = entry.sessionId;
406
- const record = sessions.get(sessionId) || {
407
- provider: "claude",
408
- sessionId,
409
- projectName: projectDir.name,
410
- summary: "Claude Session",
411
- lastActivity: null,
412
- messageCount: 0,
413
- source: filePath
414
- };
415
-
416
- if (entry.timestamp) {
417
- record.lastActivity = entry.timestamp;
418
- }
419
-
420
- if (entry.message?.role && entry.message?.content) {
421
- const content = extractClaudeText(entry.message.content);
422
- if (content && !shouldSkipClaudeMessage(content)) {
423
- record.messageCount += 1;
424
- if (entry.message.role === "user") {
425
- record.summary = truncateSummary(content);
426
- } else if (record.summary === "Claude Session") {
427
- record.summary = truncateSummary(content);
428
- }
429
- }
430
- }
431
-
432
- sessions.set(sessionId, record);
433
- }
434
- }
435
- }
436
-
437
- const list = Array.from(sessions.values());
438
- list.sort((a, b) => new Date(b.lastActivity || 0) - new Date(a.lastActivity || 0));
439
- return list.slice(0, options.sessionLimit ?? DEFAULT_SESSION_LIMIT);
440
- }
441
-
442
- async function findCodexSessionFile(rootDir, sessionId) {
443
- const queue = [rootDir];
444
- while (queue.length) {
445
- const current = queue.pop();
446
- let entries = [];
447
- try {
448
- entries = await fsp.readdir(current, { withFileTypes: true });
449
- } catch {
450
- continue;
451
- }
452
- for (const entry of entries) {
453
- const fullPath = path.join(current, entry.name);
454
- if (entry.isDirectory()) {
455
- queue.push(fullPath);
456
- } else if (
457
- entry.isFile() &&
458
- entry.name.includes(sessionId) &&
459
- entry.name.endsWith(".jsonl")
460
- ) {
461
- return fullPath;
462
- }
463
- }
464
- }
465
- return null;
466
- }
467
-
468
- async function findClaudeSessionEntries(projectsDir, sessionId) {
469
- const entries = [];
470
- let projectDirs = [];
471
- try {
472
- projectDirs = await fsp.readdir(projectsDir, { withFileTypes: true });
473
- } catch {
474
- return entries;
475
- }
476
-
477
- for (const projectDir of projectDirs) {
478
- if (!projectDir.isDirectory()) {
479
- continue;
480
- }
481
- const projectPath = path.join(projectsDir, projectDir.name);
482
- let files = [];
483
- try {
484
- files = await fsp.readdir(projectPath, { withFileTypes: true });
485
- } catch {
486
- continue;
487
- }
488
-
489
- for (const file of files) {
490
- if (!file.isFile()) {
491
- continue;
492
- }
493
- if (!file.name.endsWith(".jsonl") || file.name.startsWith("agent-")) {
494
- continue;
495
- }
496
-
497
- const filePath = path.join(projectPath, file.name);
498
- const rl = readline.createInterface({
499
- input: fs.createReadStream(filePath),
500
- crlfDelay: Infinity
501
- });
502
-
503
- for await (const line of rl) {
504
- const trimmed = line.trim();
505
- if (!trimmed) {
506
- continue;
507
- }
508
- let entry;
509
- try {
510
- entry = JSON.parse(trimmed);
511
- } catch {
512
- continue;
513
- }
514
- if (entry.sessionId === sessionId) {
515
- entries.push({ ...entry, source: filePath });
516
- }
517
- }
518
- }
519
- }
520
-
521
- return entries;
522
- }
523
-
524
- async function findJsonlFiles(rootDir) {
525
- const files = [];
526
- const queue = [rootDir];
527
- while (queue.length) {
528
- const current = queue.pop();
529
- let entries = [];
530
- try {
531
- entries = await fsp.readdir(current, { withFileTypes: true });
532
- } catch {
533
- continue;
534
- }
535
- for (const entry of entries) {
536
- const fullPath = path.join(current, entry.name);
537
- if (entry.isDirectory()) {
538
- queue.push(fullPath);
539
- } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
540
- files.push(fullPath);
541
- }
542
- }
543
- }
544
- return files;
545
- }
546
-
547
- async function findPathByName(rootDir, sessionId) {
548
- const queue = [rootDir];
549
- while (queue.length) {
550
- const current = queue.pop();
551
- let entries = [];
552
- try {
553
- entries = await fsp.readdir(current, { withFileTypes: true });
554
- } catch {
555
- continue;
556
- }
557
- for (const entry of entries) {
558
- const fullPath = path.join(current, entry.name);
559
- if (entry.name.includes(sessionId)) {
560
- return fullPath;
561
- }
562
- if (entry.isDirectory()) {
563
- queue.push(fullPath);
564
- }
565
- }
566
- }
567
- return null;
568
- }
569
-
570
- async function pathExists(targetPath, expectedType) {
571
- try {
572
- const stats = await fsp.stat(targetPath);
573
- if (expectedType === "file") {
574
- return stats.isFile();
575
- }
576
- if (expectedType === "directory") {
577
- return stats.isDirectory();
578
- }
579
- return true;
580
- } catch {
581
- return false;
582
- }
583
- }
584
-
585
- async function parseCodexSessionFile(filePath) {
586
- const fileStream = fs.createReadStream(filePath);
587
- const rl = readline.createInterface({
588
- input: fileStream,
589
- crlfDelay: Infinity
590
- });
591
-
592
- let sessionMeta = null;
593
- let lastTimestamp = null;
594
- let lastUserMessage = null;
595
- let messageCount = 0;
596
-
597
- for await (const line of rl) {
598
- if (!line.trim()) {
599
- continue;
600
- }
601
- let entry;
602
- try {
603
- entry = JSON.parse(line);
604
- } catch {
605
- continue;
606
- }
607
-
608
- if (entry.timestamp) {
609
- lastTimestamp = entry.timestamp;
610
- }
611
-
612
- if (entry.type === "session_meta" && entry.payload) {
613
- sessionMeta = {
614
- id: entry.payload.id,
615
- cwd: entry.payload.cwd,
616
- model: entry.payload.model || entry.payload.model_provider,
617
- timestamp: entry.timestamp
618
- };
619
- }
620
-
621
- if (entry.type === "event_msg" && entry.payload?.type === "user_message") {
622
- messageCount += 1;
623
- if (entry.payload.message) {
624
- lastUserMessage = entry.payload.message;
625
- }
626
- }
627
-
628
- if (entry.type === "response_item" && entry.payload?.type === "message") {
629
- messageCount += 1;
630
- }
631
- }
632
-
633
- if (!sessionMeta?.id) {
634
- return null;
635
- }
636
-
637
- return {
638
- provider: "codex",
639
- sessionId: sessionMeta.id,
640
- summary: lastUserMessage ? truncateSummary(lastUserMessage) : "Codex Session",
641
- lastActivity: lastTimestamp || sessionMeta.timestamp,
642
- messageCount,
643
- cwd: sessionMeta.cwd,
644
- model: sessionMeta.model,
645
- source: filePath
646
- };
647
- }
648
-
649
- function extractCodexText(content) {
650
- if (!Array.isArray(content)) {
651
- return typeof content === "string" ? content : "";
652
- }
653
- return content
654
- .map((item) => {
655
- if (item?.type === "input_text" || item?.type === "output_text" || item?.type === "text") {
656
- return item.text;
657
- }
658
- return "";
659
- })
660
- .filter(Boolean)
661
- .join("\n");
662
- }
663
-
664
- function extractClaudeText(content) {
665
- if (Array.isArray(content)) {
666
- const parts = content
667
- .map((part) => {
668
- if (part?.type === "text") {
669
- return part.text;
670
- }
671
- return "";
672
- })
673
- .filter(Boolean);
674
- return parts.join("\n").trim();
675
- }
676
- if (typeof content === "string") {
677
- return content.trim();
678
- }
679
- return String(content || "").trim();
680
- }
681
-
682
- function shouldSkipClaudeMessage(content) {
683
- if (!content) {
684
- return true;
685
- }
686
- const trimmed = content.trim();
687
- return (
688
- trimmed.startsWith("<command-name>") ||
689
- trimmed.startsWith("<command-message>") ||
690
- trimmed.startsWith("<command-args>") ||
691
- trimmed.startsWith("<local-command-stdout>") ||
692
- trimmed.startsWith("<system-reminder>") ||
693
- trimmed.startsWith("Caveat:") ||
694
- trimmed.startsWith("This session is being continued from a previous") ||
695
- trimmed.startsWith("[Request interrupted")
696
- );
697
- }
698
-
699
- function truncateSummary(value) {
700
- const text = String(value || "").trim();
701
- if (!text) {
702
- return "";
703
- }
704
- return text.length > 60 ? `${text.slice(0, 60)}...` : text;
705
- }
706
-
707
- function formatSessionLine(session) {
708
- const summary = session.summary || "Untitled session";
709
- const when = session.lastActivity
710
- ? new Date(session.lastActivity).toLocaleString("sv-SE", { timeZone: "Asia/Shanghai" })
711
- : "unknown time";
712
- const project = session.projectName ? ` · ${session.projectName}` : "";
713
- return `${summary} (${session.sessionId}) · ${when}${project}`;
714
- }
715
-
716
- export { SUPPORTED_FROM_PROVIDERS };