-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathccm.js
More file actions
5820 lines (5343 loc) · 166 KB
/
Copy pathccm.js
File metadata and controls
5820 lines (5343 loc) · 166 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
#!/usr/bin/env node
const fs = require("fs");
const http = require("http");
const os = require("os");
const path = require("path");
const readline = require("readline");
const crypto = require("crypto");
const { execFileSync, spawnSync } = require("child_process");
const { createWindowsRuntime } = require("./lib/windows-runtime");
const { syncWindowsCodexBaseUrl, syncWindowsCodexApiKey } = require("./lib/wsl-runtime");
const { importWslRegistries, withOfficialChannel } = require("./lib/wsl-import");
const {
buildOfficialEnv,
ensureCodexOfficialLogin,
ensureOfficialHome,
} = require("./lib/codex-official");
const {
buildOfficialEnv: buildOfficialClaudeEnv,
clearApiChannel: clearClaudeApiChannel,
ensureClaudeOfficialLogin,
readSettings: readClaudeSettings,
updateApiChannel: updateClaudeApiChannel,
} = require("./lib/claude-settings");
const {
PI_API_TYPES,
applyPiChannel,
capturePiDefaults,
clearPiManagedSelection,
normalizePiApi,
parseJsonObject: parsePiJsonObject,
readPiSnapshot,
} = require("./lib/pi-settings");
const {
GROK_API_BACKENDS,
activateGrokOfficial,
applyGrokChannel,
normalizeGrokApiBackend,
readGrokSnapshot,
} = require("./lib/grok-settings");
const WINDOWS_RUNTIME = process.platform === "win32" ? createWindowsRuntime() : null;
const HOME = WINDOWS_RUNTIME ? WINDOWS_RUNTIME.home : os.homedir();
const STATE_HOME =
process.env.CCM_STATE_HOME ||
(WINDOWS_RUNTIME ? WINDOWS_RUNTIME.stateHome : path.join(HOME, ".local", "state", "ccm"));
const ACTIVATION_PATH = path.join(STATE_HOME, "activate.sh");
const SESSION_META_PATH = path.join(STATE_HOME, "session-metadata.json");
const SESSION_ARCHIVE_DIR = path.join(STATE_HOME, "session-archives");
const SESSION_TRASH_DIR = path.join(STATE_HOME, "trash", "sessions");
const SKILL_BACKUP_DIR = path.join(STATE_HOME, "skill-backups");
const SKILL_DISABLED_DIR = path.join(STATE_HOME, "disabled-skills");
const SKILL_TRASH_DIR = path.join(STATE_HOME, "trash", "skills");
const TUI_PAGES = ["channels", "skills", "sessions"];
const CCM_BUILD_ID = "2026-09-05-codex-empty-model-v0.4.8";
let claudePluginCache = { expiresAt: 0, installed: [] };
const CODEX_HOME =
process.env.CCM_CODEX_HOME ||
process.env.CODEX_HOME ||
(WINDOWS_RUNTIME ? WINDOWS_RUNTIME.codexHome : path.join(HOME, ".codex"));
const OFFICIAL_CODEX_HOME = CODEX_HOME;
const CODEX_SHELL_INIT =
process.env.CCM_CODEX_SHELL_INIT ||
(WINDOWS_RUNTIME ? "" : resolveUnixShellInitPath(HOME, process.env));
const CLAUDE_BASHRC =
process.env.CCM_CLAUDE_BASHRC ||
(WINDOWS_RUNTIME
? WINDOWS_RUNTIME.claudeSettingsPath
: resolveUnixShellInitPath(HOME, process.env));
const CLAUDE_HOME =
process.env.CCM_CLAUDE_HOME ||
(WINDOWS_RUNTIME ? WINDOWS_RUNTIME.claudeHome : path.join(HOME, ".claude"));
const PI_HOME =
process.env.CCM_PI_HOME ||
path.join(HOME, ".pi", "agent");
const GROK_HOME =
process.env.CCM_GROK_HOME ||
process.env.GROK_HOME ||
path.join(HOME, ".grok");
const TOOLS = {
codex: {
id: "codex",
label: "Codex",
command: process.env.CCM_CODEX_BIN || "codex",
home: CODEX_HOME,
registryPath: path.join(STATE_HOME, "channels.json"),
statePath: path.join(STATE_HOME, "state.json"),
backupDir: path.join(STATE_HOME, "backups"),
lockPath: path.join(STATE_HOME, "switch.lock"),
},
claude: {
id: "claude",
label: "Claude",
command: process.env.CCM_CLAUDE_BIN || "claude",
home: CLAUDE_HOME,
bashrcPath: CLAUDE_BASHRC,
registryPath: path.join(STATE_HOME, "claude-channels.json"),
statePath: path.join(STATE_HOME, "claude-state.json"),
backupDir: path.join(STATE_HOME, "claude-backups"),
lockPath: path.join(STATE_HOME, "claude-switch.lock"),
},
pi: {
id: "pi",
label: "Pi",
command: process.env.CCM_PI_BIN || "pi",
home: PI_HOME,
modelsPath: path.join(PI_HOME, "models.json"),
settingsPath: path.join(PI_HOME, "settings.json"),
registryPath: path.join(STATE_HOME, "pi-channels.json"),
statePath: path.join(STATE_HOME, "pi-state.json"),
backupDir: path.join(STATE_HOME, "pi-backups"),
lockPath: path.join(STATE_HOME, "pi-switch.lock"),
},
grok: {
id: "grok",
label: "Grok Build",
command: process.env.CCM_GROK_BIN || "grok",
home: GROK_HOME,
configPath: path.join(GROK_HOME, "config.toml"),
registryPath: path.join(STATE_HOME, "grok-channels.json"),
statePath: path.join(STATE_HOME, "grok-state.json"),
backupDir: path.join(STATE_HOME, "grok-backups"),
lockPath: path.join(STATE_HOME, "grok-switch.lock"),
},
};
if (require.main === module) {
main();
}
function main() {
try {
const args = parseArgs(process.argv.slice(2));
if (args.help) {
printHelp();
return;
}
if (args.importWsl) {
runWslImport(args);
return;
}
for (const tool of Object.values(TOOLS)) {
ensureToolStateDirs(tool);
bootstrapRegistryIfNeeded(tool);
}
if (args.doctor) {
printDoctor();
return;
}
if (args.loginOfficial) {
switchToOfficialAndLogin(args.tool || "codex");
return;
}
if (args.ui) {
runWebUi(args);
return;
}
if (args.tui) {
runTerminalUi(args.tool || "codex").catch(fail);
return;
}
if (!args.hasExplicitCommand) {
runTerminalUi("codex").catch(fail);
return;
}
const tool = getTool(args.tool || "codex");
if (args.list) {
listChannelsCli(tool);
return;
}
if (args.current) {
printCurrentChannelCli(tool);
return;
}
if (args.use) {
useChannelCli(tool, args.use);
return;
}
runInteractive(tool).catch(fail);
} catch (error) {
fail(error);
}
}
function parseArgs(argv) {
const args = {
_: [],
tool: "",
list: false,
current: false,
use: "",
ui: false,
tui: false,
host: "127.0.0.1",
port: 17883,
help: false,
doctor: false,
importWsl: false,
dryRun: false,
loginOfficial: false,
hasExplicitCommand: argv.length > 0,
};
for (let index = 0; index < argv.length; index += 1) {
const item = argv[index];
if (item === "--help" || item === "-h") {
args.help = true;
} else if (item === "--doctor" || item === "doctor") {
args.doctor = true;
} else if (item === "--import-wsl") {
args.importWsl = true;
} else if (item === "--dry-run") {
args.dryRun = true;
} else if (item === "--login-official") {
args.loginOfficial = true;
} else if (item === "--tool") {
args.tool = requireValue(argv, index, "--tool");
index += 1;
} else if (item === "--codex") {
args.tool = "codex";
} else if (item === "--claude") {
args.tool = "claude";
} else if (item === "--pi") {
args.tool = "pi";
} else if (item === "--grok") {
args.tool = "grok";
} else if (item === "--list") {
args.list = true;
} else if (item === "--current") {
args.current = true;
} else if (item === "--use") {
args.use = requireValue(argv, index, "--use");
index += 1;
} else if (item === "--ui" || item === "ui") {
args.ui = true;
} else if (item === "--tui" || item === "--terminal-ui" || item === "tui") {
args.tui = true;
} else if (item === "--host") {
args.host = requireValue(argv, index, "--host");
index += 1;
} else if (item === "--port") {
args.port = Number(requireValue(argv, index, "--port"));
index += 1;
} else if (["codex", "claude", "pi", "grok"].includes(item)) {
args.tool = item;
} else {
args._.push(item);
}
}
if (!Number.isInteger(args.port) || args.port <= 0 || args.port > 65535) {
throw new Error("--port 必须是 1-65535 之间的数字");
}
return args;
}
function requireValue(argv, index, option) {
const value = argv[index + 1];
if (!value || value.startsWith("--")) {
throw new Error(`${option} 需要提供值`);
}
return value;
}
function printHelp() {
console.log(`CCM Agent Channel Manager
用法:
ccm
ccm --tui
ccm codex
ccm claude
ccm pi
ccm grok
ccm --ui [--host 127.0.0.1] [--port 17883]
ccm --tool codex --list
ccm --tool claude --list
ccm --tool pi --list
ccm --tool grok --list
ccm --tool codex --current
ccm --tool claude --current
ccm --tool pi --current
ccm --tool grok --current
ccm --tool codex --use <channel-name-or-id>
ccm --tool claude --use <channel-name-or-id>
ccm --tool pi --use <channel-name-or-id>
ccm --tool grok --use <channel-name-or-id>
ccm --doctor
ccm --import-wsl [--dry-run]
ccm --tool codex --login-official
ccm --tool claude --login-official
ccm --tool pi --login-official
ccm --tool grok --login-official
说明:
Codex 渠道写入 ${CODEX_HOME}/config.toml 和 auth.json
Claude 渠道写入 ${CLAUDE_BASHRC} 中的 ANTHROPIC_BASE_URL 与密钥变量
Pi 第三方渠道写入 ${PI_HOME}/models.json 和 settings.json;官方登录在 Pi 内执行 /login
Grok 第三方渠道写入 ${GROK_HOME}/config.toml;官方登录执行 grok login
环境变量覆盖:
CCM_CODEX_HOME 覆盖 Codex home(默认 CODEX_HOME 或 ~/.codex)
CCM_CLAUDE_BASHRC 覆盖 Claude shell 初始化文件(macOS zsh 默认 ~/.zshrc,其他 Unix 默认 ~/.bashrc)
CCM_PI_HOME 覆盖 Pi agent 配置目录(默认 ~/.pi/agent)
CCM_GROK_HOME 覆盖 Grok Build 配置目录(默认 ~/.grok)
CCM_STATE_HOME 覆盖渠道注册表和备份目录
CCM_CODEX_BIN 覆盖 codex 命令
CCM_CLAUDE_BIN 覆盖 claude 命令
CCM_PI_BIN 覆盖 pi 命令
CCM_GROK_BIN 覆盖 grok 命令
`);
}
function runWslImport(args) {
const sourceRoot =
process.env.CCM_WSL_ROOT ||
"\\\\wsl.localhost\\Ubuntu-24.04\\home\\fleix";
const result = importWslRegistries({
sourceRoot,
stateHome: STATE_HOME,
dryRun: args.dryRun,
});
console.log(args.dryRun ? "WSL import preview" : "WSL import complete");
console.log(`Codex channels: ${result.codexCount}`);
console.log(`Claude channels: ${result.claudeCount}`);
if (result.backupDir) {
console.log(`Previous Windows registries backed up: ${result.backupDir}`);
}
}
function loginOfficialCli(toolId) {
if (toolId === "claude") {
ensureClaudeOfficialLogin({
settingsPath: TOOLS.claude.bashrcPath,
command: TOOLS.claude.command,
env: process.env,
spawnSyncImpl: spawnToolCommand,
});
console.log("Claude 官方登录已完成");
return;
}
if (toolId === "pi") {
console.log("Pi 已启动。请在 Pi 中输入 /login,然后选择要使用的官方订阅提供商。");
const result = spawnToolCommand(TOOLS.pi.command, [], {
stdio: "inherit",
env: { ...process.env },
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
throw new Error("pi login exited with code " + result.status);
}
return;
}
if (toolId === "grok") {
const args = isWslRuntime() ? ["login", "--device-auth"] : ["login"];
const result = spawnToolCommand(TOOLS.grok.command, args, {
stdio: "inherit",
env: { ...process.env },
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
throw new Error("grok login exited with code " + result.status);
}
console.log("Grok Build 官方登录已完成。");
return;
}
if (toolId !== "codex") {
throw new Error(`不支持的官方登录工具: ${toolId}`);
}
const result = ensureCodexOfficialLogin({
officialHome: OFFICIAL_CODEX_HOME,
command: TOOLS.codex.command,
env: process.env,
spawnSyncImpl: spawnToolCommand,
});
console.log(result.loginStarted ? "Codex 官方登录已完成" : "Codex 官方登录已存在");
}
function switchToOfficialAndLogin(toolId) {
const tool = getTool(toolId);
const official = loadRegistry(tool).find((channel) => channel.kind === "official");
if (!official) {
throw new Error(`${tool.label} 官方渠道不存在`);
}
switchToChannelSync(tool, official);
loginOfficialCli(tool.id);
return official;
}
function printDoctor() {
const scriptPath = safeRealpath(__filename);
const homeBinPath = path.join(HOME, "bin", "ccm");
const mainScript = path.join(HOME, ".nvm", "versions", "node", "v24.15.0", "bin", "ccm");
const frameProbe = stripAnsi(
buildTerminalUiFrame({
activeToolId: "codex",
activePage: "channels",
selectedIndex: 0,
message: "doctor",
help: false,
busy: false,
}),
);
const interactiveType = WINDOWS_RUNTIME
? spawnSync("where.exe", ["ccm"], { encoding: "utf8" })
: spawnSync("bash", ["-ic", "type -a ccm"], { encoding: "utf8" });
console.log("ccm doctor");
console.log(`build_id : ${CCM_BUILD_ID}`);
console.log(`node : ${process.version} ${process.execPath}`);
console.log(`script : ${__filename}`);
console.log(`script_real : ${scriptPath}`);
console.log(`script_sha256 : ${sha256File(__filename) || "-"}`);
console.log(`main_sha256 : ${sha256File(mainScript) || "-"}`);
console.log(`home_bin : ${homeBinPath}`);
console.log(`home_bin_real : ${safeRealpath(homeBinPath) || "-"}`);
console.log(`home_bin_sha : ${sha256File(homeBinPath) || "-"}`);
console.log(`cwd : ${process.cwd()}`);
console.log(`home : ${HOME}`);
console.log(`shell : ${process.env.SHELL || "-"}`);
console.log(`term : ${process.env.TERM || "-"}`);
console.log(`path : ${process.env.PATH || "-"}`);
console.log(`frame_header : ${frameProbe.includes("ccm Channel Manager") ? "yes" : "no"}`);
console.log(WINDOWS_RUNTIME ? "where ccm:" : "type -a ccm:");
process.stdout.write((interactiveType.stdout || "").trimEnd() || "-");
if (interactiveType.stderr) {
process.stdout.write(`\n${interactiveType.stderr.trimEnd()}`);
}
process.stdout.write("\n");
}
async function runToolChooser() {
while (true) {
clearScreen();
console.log("Channel Manager");
console.log("");
const tools = Object.values(TOOLS);
tools.forEach(printToolSummary);
console.log("");
tools.forEach((tool, index) => console.log(`${index + 1}. 管理 ${tool.label} 渠道`));
console.log(`${tools.length + 1}. 启动 Web UI`);
console.log("q. 退出");
console.log("");
const answer = (await prompt("请选择: ")).trim().toLowerCase();
if (answer === "q") {
return;
}
const selectedTool =
tools.find((tool, index) => answer === String(index + 1) || answer === tool.id) || null;
if (selectedTool) {
await runInteractive(selectedTool);
continue;
}
if (answer === String(tools.length + 1) || answer === "ui") {
console.log("");
console.log("请在终端运行: ccm --ui");
await pause();
continue;
}
console.log("选择无效。");
await pause();
}
}
async function runTerminalUi(initialToolId) {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("终端 TUI 需要在交互式终端中运行");
}
writeRuntimeProbe();
const stdin = process.stdin;
const stdout = process.stdout;
const state = {
activeToolId: getTool(initialToolId).id,
activePage: "channels",
selectedIndex: 0,
message: "Enter 切换渠道,Tab 切换 Agent。",
help: false,
busy: false,
modal: null,
};
const wasRaw = stdin.isRaw;
const wasPaused =
typeof stdin.isPaused === "function" ? stdin.isPaused() : false;
readline.emitKeypressEvents(stdin);
if (wasPaused) {
stdin.resume();
}
stdin.setRawMode(true);
stdout.write("\x1b[?1049h\x1b[?25l");
return new Promise((resolve) => {
let cleanedUp = false;
function cleanup() {
if (cleanedUp) {
return;
}
cleanedUp = true;
stdin.removeListener("keypress", onKeypress);
try {
stdin.setRawMode(Boolean(wasRaw));
} catch {}
if (typeof stdin.pause === "function") {
stdin.pause();
}
stdout.write("\x1b[0m\x1b[?25h\x1b[?1049l");
}
function render() {
const frame = buildTerminalUiFrame(state);
stdout.write(`\x1b[2J\x1b[H${frame}`);
}
function clampSelection() {
const items = getTuiItems(state);
if (!items.length) {
state.selectedIndex = 0;
return;
}
state.selectedIndex = Math.max(
0,
Math.min(state.selectedIndex, items.length - 1),
);
}
function selectCurrentChannel() {
const tool = getTool(state.activeToolId);
const channels = loadRegistry(tool);
const current = resolveCurrentChannel(tool, channels);
const index = current
? channels.findIndex((channel) => channel.id === current.id)
: -1;
if (index >= 0) {
state.selectedIndex = index;
return;
}
clampSelection();
}
function selectDefaultForPage() {
if (state.activePage === "channels") {
selectCurrentChannel();
return;
}
state.selectedIndex = 0;
clampSelection();
}
function setActiveTool(toolId) {
state.activeToolId = getTool(toolId).id;
selectDefaultForPage();
state.message = `${pageLabel(state.activePage)} / ${getTool(state.activeToolId).label}`;
}
function setActivePage(pageId) {
state.activePage = pageId;
selectDefaultForPage();
state.message = `${pageLabel(pageId)} / ${getTool(state.activeToolId).label}`;
}
function rotatePage(delta) {
const current = TUI_PAGES.indexOf(state.activePage);
const next = (current + delta + TUI_PAGES.length) % TUI_PAGES.length;
setActivePage(TUI_PAGES[next]);
}
async function suspendForPrompt(fn) {
state.busy = true;
stdin.removeListener("keypress", onKeypress);
try {
stdin.setRawMode(false);
} catch {}
stdout.write("\x1b[?25h\x1b[?1049l");
try {
await fn();
} catch (error) {
state.message = `操作失败: ${error.message}`;
} finally {
readline.emitKeypressEvents(stdin);
stdin.on("keypress", onKeypress);
stdin.setRawMode(true);
stdout.write("\x1b[?1049h\x1b[?25l");
state.busy = false;
clampSelection();
render();
}
}
function selectedChannel() {
const channels = loadRegistry(getTool(state.activeToolId));
return channels[state.selectedIndex] || null;
}
function selectedSession() {
const sessions = listSessions(state.activeToolId);
return sessions[state.selectedIndex] || null;
}
function selectedSkill() {
const skills = listSkills(state.activeToolId);
return skills[state.selectedIndex] || null;
}
async function switchSelected(mode) {
const tool = getTool(state.activeToolId);
const channel = selectedChannel();
if (!channel) {
state.message = "当前没有可切换的渠道。";
render();
return;
}
const running = detectRunningToolPids(tool);
try {
switchToChannelSync(tool, channel);
if (shouldStartOfficialLogin(channel, mode)) {
await suspendForPrompt(async () => {
loginOfficialCli(tool.id);
state.message = `${channel.name} official login completed.`;
});
return;
}
state.message =
tool.id === "claude"
? `已切换到 ${channel.name}。本次 ccm 内已生效,退出后 shell wrapper 会自动加载。`
: `已切换到 ${channel.name}。${running.length ? "已运行的 Codex 进程不会自动继承新配置。" : ""}`;
if (mode === "start" || mode === "resume") {
cleanup();
launchTool(tool, channel, mode);
return;
}
render();
} catch (error) {
state.message = `切换失败: ${error.message}`;
render();
}
}
async function loginSelectedOfficialChannel() {
const channel = selectedChannel();
if (!channel || channel.kind !== "official") {
state.message = "Select an Official channel first.";
render();
return;
}
await suspendForPrompt(async () => {
switchToChannelSync(getTool(state.activeToolId), channel);
loginOfficialCli(state.activeToolId);
state.message = `${channel.name} official login completed.`;
});
}
function editSelected() {
const tool = getTool(state.activeToolId);
const channel = selectedChannel();
if (!channel) {
state.message = "请选择一个渠道后再编辑。";
render();
return;
}
state.modal = createChannelFormModal(tool, "edit", channel);
state.help = false;
render();
}
async function deleteSelected() {
const tool = getTool(state.activeToolId);
const channel = selectedChannel();
if (!channel) {
state.message = "请选择一个渠道后再删除。";
render();
return;
}
await suspendForPrompt(async () => {
await deleteChannel(tool, channel.id);
state.message = "删除操作已完成。";
});
}
function addForActiveTool() {
const tool = getTool(state.activeToolId);
state.modal = createChannelFormModal(tool, "add");
state.help = false;
render();
}
function closeModal() {
state.modal = null;
state.message = "已取消渠道表单。";
render();
}
function submitChannelModal() {
const modal = state.modal;
if (!modal || modal.type !== "channel-form") {
return;
}
try {
const tool = getTool(modal.toolId);
const values = channelModalValues(modal);
const saved = saveChannelForm(tool, modal.mode, modal.channelId, values);
const channels = loadRegistry(tool);
const index = channels.findIndex((item) => item.id === saved.id);
state.modal = null;
state.selectedIndex = Math.max(0, index);
state.message = modal.mode === "add" ? "渠道已新增。" : "渠道已更新。";
} catch (error) {
modal.error = error.message;
}
render();
}
function handleModalKeypress(str, key = {}) {
const modal = state.modal;
if (!modal || modal.type !== "channel-form") {
return;
}
const name = key.name || "";
const fields = modal.fields;
const field = fields[modal.activeField];
if (name === "escape") {
closeModal();
return;
}
if (name === "return" || name === "enter") {
submitChannelModal();
return;
}
if (name === "tab" || name === "up" || name === "down") {
const backwards = name === "up" || (name === "tab" && key.shift);
modal.activeField =
(modal.activeField + (backwards ? -1 : 1) + fields.length) %
fields.length;
modal.error = "";
render();
return;
}
if (!field) {
return;
}
if (field.type === "select") {
if (
name === "left" ||
name === "right" ||
str === " " ||
name === "space"
) {
const delta = name === "left" ? -1 : 1;
const current = Math.max(0, field.options.indexOf(field.value));
field.value =
field.options[
(current + delta + field.options.length) % field.options.length
];
modal.error = "";
render();
}
return;
}
const chars = Array.from(field.value);
field.cursor = Math.max(0, Math.min(field.cursor, chars.length));
if (name === "left") {
field.cursor = Math.max(0, field.cursor - 1);
} else if (name === "right") {
field.cursor = Math.min(chars.length, field.cursor + 1);
} else if (name === "home") {
field.cursor = 0;
} else if (name === "end") {
field.cursor = chars.length;
} else if (name === "backspace") {
if (field.cursor > 0) {
chars.splice(field.cursor - 1, 1);
field.cursor -= 1;
field.value = chars.join("");
}
} else if (name === "delete") {
if (field.cursor < chars.length) {
chars.splice(field.cursor, 1);
field.value = chars.join("");
}
} else if (key.ctrl && name === "u") {
field.value = "";
field.cursor = 0;
} else if (str && !key.ctrl && !key.meta) {
const inserted = Array.from(str).filter(
(char) => char >= " " && char !== "\x7f",
);
if (inserted.length) {
chars.splice(field.cursor, 0, ...inserted);
field.cursor += inserted.length;
field.value = chars.join("");
}
} else {
return;
}
modal.error = "";
render();
}
async function rollbackActiveTool() {
const tool = getTool(state.activeToolId);
await suspendForPrompt(async () => {
await rollbackLastBackup(tool);
state.message = "回滚操作已完成。";
});
}
function resumeSelectedSession() {
const tool = getTool(state.activeToolId);
const session = selectedSession();
if (!session) {
state.message = "请选择一个会话后再恢复。";
render();
return;
}
try {
if (session.channel_id) {
const channel = loadRegistry(tool).find(
(item) => item.id === session.channel_id,
);
if (channel) {
switchToChannelSync(tool, channel);
}
}
cleanup();
launchSession(tool, session);
} catch (error) {
state.message = `恢复失败: ${error.message}`;
render();
}
}
function describeSelectedSkill() {
const skill = selectedSkill();
if (!skill) {
state.message = "当前没有可查看的 skill/plugin。";
render();
return;
}
state.message = `${skill.name}: ${skill.description || skill.path}`;
render();
}
async function toggleFavoriteSelectedSession() {
const session = selectedSession();
if (!session) {
state.message = "请选择一个会话。";
render();
return;
}
const next = toggleSessionFavorite(session);
const nextSessions = listSessions(state.activeToolId);
const nextIndex = nextSessions.findIndex((item) => item.key === session.key);
if (nextIndex >= 0) {
state.selectedIndex = nextIndex;
}
state.message = next.favorite ? "会话已收藏。" : "已取消收藏。";
render();
}
async function tagSelectedSession() {
const session = selectedSession();
if (!session) {
state.message = "请选择一个会话。";
render();
return;
}
await suspendForPrompt(async () => {
const answer = await promptWithDefault(
"标签(逗号分隔)",
session.tags.join(", "),
);
const next = setSessionTags(session, answer);
state.message = next.tags?.length
? `标签已更新: ${next.tags.join(", ")}`
: "标签已清空。";
});
}
async function bindSelectedSessionChannel() {
const tool = getTool(state.activeToolId);
const session = selectedSession();
if (!session) {
state.message = "请选择一个会话。";
render();
return;
}
await suspendForPrompt(async () => {
const channels = loadRegistry(tool);
console.log("");
console.log("0. 解除渠道绑定");
channels.forEach((channel, index) => {
console.log(`${index + 1}. ${channel.name}`);
});
const answer = (await prompt("选择渠道: ")).trim();
const index = Number(answer) - 1;
if (answer === "0" || !answer) {
bindSessionChannel(session, "");
state.message = "已解除会话渠道绑定。";
return;
}
if (!Number.isInteger(index) || !channels[index]) {
state.message = "无效的渠道选择。";
return;
}
bindSessionChannel(session, channels[index].id);
state.message = `会话已绑定渠道: ${channels[index].name}`;
});
}
async function archiveSelectedSession() {
const session = selectedSession();
if (!session) {
state.message = "请选择一个会话。";
render();
return;
}
await suspendForPrompt(async () => {
const archivePath = archiveSession(session);
state.message = `会话已归档: ${archivePath}`;
});
}
async function deleteSelectedSession() {
const session = selectedSession();
if (!session) {
state.message = "请选择一个会话。";
render();
return;
}
await suspendForPrompt(async () => {
const answer = (
await prompt(`将会话“${session.title}”移入 CCM 回收站? [y/N]: `)
)
.trim()
.toLowerCase();
if (answer !== "y") {
state.message = "已取消删除。";
return;
}
const target = trashSession(session);
state.message = `会话已移入回收站: ${target}`;
});
}
async function cleanupSessions() {
const tool = getTool(state.activeToolId);
await suspendForPrompt(async () => {
const daysText = await promptWithDefault("清理多少天前的会话", "90");
const days = Number(daysText);
if (!Number.isFinite(days) || days < 1) {
state.message = "天数必须大于 0。";
return;
}
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
const candidates = listSessions(tool.id, 100000).filter(
(session) =>
!session.favorite &&
session.path &&
fs.existsSync(session.path) &&
new Date(session.updated_at || 0).getTime() < cutoff,
);
if (!candidates.length) {
state.message = `没有 ${days} 天前的未收藏会话。`;
return;