ccem 2.93.0 → 2.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +846 -261
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,8 +5,8 @@ import { spawn } from "child_process";
5
5
  import { TextDecoder } from "util";
6
6
 
7
7
  // src/desktopControl.ts
8
- import fs2 from "fs";
9
- import path2 from "path";
8
+ import fs4 from "fs";
9
+ import path4 from "path";
10
10
 
11
11
  // ../../packages/core/dist/chunk-4WH3CEOL.js
12
12
  var DEFAULT_ROUTER_PORT = 17820;
@@ -700,10 +700,595 @@ var getPermissionModeNames = () => {
700
700
 
701
701
  // ../../packages/core/dist/index.js
702
702
  import crypto2 from "crypto";
703
- import fs from "fs";
703
+ import fs3 from "fs";
704
+ import os2 from "os";
705
+ import path3 from "path";
706
+ import fs2 from "fs";
704
707
  import os from "os";
708
+ import path2 from "path";
709
+ import { randomUUID } from "crypto";
710
+ import fs from "fs";
705
711
  import path from "path";
712
+ import { execFileSync } from "child_process";
706
713
  import crypto from "crypto";
714
+ function processAlive(pid) {
715
+ try {
716
+ process.kill(pid, 0);
717
+ return true;
718
+ } catch (error) {
719
+ return error.code !== "ESRCH";
720
+ }
721
+ }
722
+ function samePath(left, right) {
723
+ const normalize = (value) => {
724
+ try {
725
+ value = fs.realpathSync(value);
726
+ } catch {
727
+ value = path.resolve(value);
728
+ }
729
+ return process.platform === "win32" ? value.toLowerCase() : value;
730
+ };
731
+ return normalize(left) === normalize(right);
732
+ }
733
+ function providerCommand(provider, executable, command) {
734
+ const name = path.basename(executable).toLowerCase().replace(/\.exe$/, "");
735
+ if (name === provider) return true;
736
+ if (!["node", "bun", "ccem-node"].includes(name) && !name.startsWith("ccem-node-")) return false;
737
+ if (/(?:^|[\\/\s])native-runtime-helper\.mjs(?:[\s"']|$)/.test(command)) return true;
738
+ return provider === "claude" ? /@anthropic-ai[\\/]claude-code[\\/]cli\.js(?:[\s"']|$)/.test(command) : /@openai[\\/]codex[\\/]bin[\\/]codex\.js(?:[\s"']|$)/.test(command);
739
+ }
740
+ function candidateExecutable(executable) {
741
+ const name = path.basename(executable).toLowerCase().replace(/\.exe$/, "");
742
+ return ["claude", "codex", "node", "bun", "ccem-node"].includes(name) || name.startsWith("ccem-node-");
743
+ }
744
+ function ps(args) {
745
+ return execFileSync("ps", args, {
746
+ encoding: "utf8",
747
+ stdio: ["ignore", "pipe", "ignore"],
748
+ timeout: 5e3,
749
+ maxBuffer: 16 * 1024 * 1024
750
+ }).trimEnd();
751
+ }
752
+ function parseEnvironment(value) {
753
+ const result = {};
754
+ const boundaries = [...value.matchAll(/(?:^|\s)([A-Za-z_][A-Za-z0-9_]*)=/g)];
755
+ for (let i = 0; i < boundaries.length; i += 1) {
756
+ const entry = boundaries[i];
757
+ if (!["HOME", "USERPROFILE", "CCEM_RUNTIME_ID", "CCEM_SESSION_ID", "CLAUDE_CONFIG_DIR", "CODEX_HOME"].includes(entry[1])) continue;
758
+ const start = entry.index + entry[0].length;
759
+ const end = i + 1 < boundaries.length ? boundaries[i + 1].index : value.length;
760
+ result[entry[1]] = value.slice(start, end).trim();
761
+ }
762
+ return result;
763
+ }
764
+ function migrationBlocked(provider, pid, unknownHome = false) {
765
+ const reason = unknownHome ? `Cannot verify the agent home of a live CCEM ${provider} session (PID ${pid}).` : `A live CCEM ${provider} session (PID ${pid}) is still writing legacy history.`;
766
+ throw new Error(`${reason} Finish that session and retry to preserve its latest messages before isolation.`);
767
+ }
768
+ function persistedProcesses(home) {
769
+ const result = [];
770
+ for (const name of ["sessions.json", "runtime-state.json"]) {
771
+ const file = path.join(home, ".ccem", name);
772
+ let value;
773
+ try {
774
+ const stat2 = fs.lstatSync(file);
775
+ if (!stat2.isFile() || stat2.isSymbolicLink()) continue;
776
+ value = JSON.parse(fs.readFileSync(file, "utf8"));
777
+ } catch (error) {
778
+ if (error.code === "ENOENT") continue;
779
+ throw new Error("Cannot inspect saved CCEM sessions before migration; retry when their state is available");
780
+ }
781
+ const rows = Array.isArray(value) ? value : value?.sessions;
782
+ for (const raw of Array.isArray(rows) ? rows : []) {
783
+ if (!raw || typeof raw !== "object") continue;
784
+ const row = raw;
785
+ if (!Number.isSafeInteger(row.pid) || row.pid <= 0 || row.pid === process.pid) continue;
786
+ if (typeof row.status === "string" && row.status !== "running") continue;
787
+ if (row.summary) continue;
788
+ result.push({
789
+ pid: row.pid,
790
+ client: typeof row.client === "string" ? row.client : void 0,
791
+ jsonlPath: typeof row.jsonl_path === "string" ? row.jsonl_path : void 0
792
+ });
793
+ }
794
+ }
795
+ return result;
796
+ }
797
+ function persistedPathIsLegacy(record, provider, source) {
798
+ if (record.client && record.client !== provider) return false;
799
+ if (!record.jsonlPath) return true;
800
+ const roots = provider === "claude" ? ["projects"] : ["sessions", "archived_sessions"];
801
+ const candidate = path.resolve(record.jsonlPath);
802
+ return roots.some((name) => {
803
+ const directory = path.resolve(source, name);
804
+ const relative2 = path.relative(directory, candidate);
805
+ return relative2 !== "" && relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2);
806
+ });
807
+ }
808
+ function assertWindowsProcesses(provider, home, source) {
809
+ for (const record of persistedProcesses(home)) {
810
+ if (!persistedPathIsLegacy(record, provider, source) || !processAlive(record.pid)) continue;
811
+ let command;
812
+ try {
813
+ const output = execFileSync(
814
+ "powershell.exe",
815
+ [
816
+ "-NoProfile",
817
+ "-NonInteractive",
818
+ "-Command",
819
+ `Get-CimInstance Win32_Process -Filter 'ProcessId = ${record.pid}' | Select-Object Name,CommandLine | ConvertTo-Json -Compress`
820
+ ],
821
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }
822
+ );
823
+ command = JSON.parse(output);
824
+ } catch {
825
+ if (processAlive(record.pid)) migrationBlocked(provider, record.pid, true);
826
+ continue;
827
+ }
828
+ if (!command || !providerCommand(provider, command.Name || "", command.CommandLine || "")) continue;
829
+ migrationBlocked(provider, record.pid, !record.jsonlPath);
830
+ }
831
+ }
832
+ function assertNoLegacyAgentWriters(provider, home, source, destination) {
833
+ if (process.platform === "win32") {
834
+ assertWindowsProcesses(provider, home, source);
835
+ return;
836
+ }
837
+ let listing;
838
+ try {
839
+ listing = ps(["-ax", "-o", "pid=,comm="]);
840
+ } catch {
841
+ throw new Error("Cannot inspect running CCEM sessions before migration; finish legacy sessions and retry");
842
+ }
843
+ const candidates = /* @__PURE__ */ new Map();
844
+ for (const row of listing.split("\n")) {
845
+ const match = row.match(/^\s*(\d+)\s+(.+)$/);
846
+ if (!match) continue;
847
+ const pid = Number(match[1]);
848
+ const executable = match[2];
849
+ if (pid === process.pid || !candidateExecutable(executable)) continue;
850
+ candidates.set(pid, executable);
851
+ }
852
+ if (candidates.size === 0) return;
853
+ const commands = /* @__PURE__ */ new Map();
854
+ try {
855
+ const rows = ps(["ww", "-p", [...candidates.keys()].join(","), "-o", "pid=,command="]);
856
+ for (const row of rows.split("\n")) {
857
+ const match = row.match(/^\s*(\d+)\s+(.+)$/);
858
+ if (match) commands.set(Number(match[1]), match[2]);
859
+ }
860
+ } catch {
861
+ }
862
+ for (const [pid, executable] of candidates) {
863
+ const command = commands.get(pid);
864
+ if (!command) {
865
+ if (processAlive(pid) && persistedProcesses(home).some((record) => record.pid === pid && persistedPathIsLegacy(record, provider, source))) {
866
+ migrationBlocked(provider, pid, true);
867
+ }
868
+ continue;
869
+ }
870
+ if (!providerCommand(provider, executable, command)) continue;
871
+ let withEnvironment;
872
+ try {
873
+ withEnvironment = ps(["eww", "-p", String(pid), "-o", "command="]);
874
+ } catch {
875
+ if (processAlive(pid) && persistedProcesses(home).some((record) => record.pid === pid && persistedPathIsLegacy(record, provider, source))) {
876
+ migrationBlocked(provider, pid, true);
877
+ }
878
+ continue;
879
+ }
880
+ const env = withEnvironment.startsWith(command) ? parseEnvironment(withEnvironment.slice(command.length).trimStart()) : {};
881
+ if (Object.keys(env).length === 0 && processAlive(pid) && persistedProcesses(home).some((record) => record.pid === pid && persistedPathIsLegacy(record, provider, source))) {
882
+ migrationBlocked(provider, pid, true);
883
+ }
884
+ if (!env.CCEM_RUNTIME_ID?.trim() && !env.CCEM_SESSION_ID?.trim()) continue;
885
+ const sourceHome = env.HOME || env.USERPROFILE || home;
886
+ let effectiveHome = provider === "claude" ? env.CLAUDE_CONFIG_DIR || path.join(sourceHome, ".claude") : env.CODEX_HOME || path.join(sourceHome, ".codex");
887
+ if (/^~[\\/]/.test(effectiveHome)) effectiveHome = path.join(sourceHome, effectiveHome.slice(2));
888
+ if (samePath(effectiveHome, source) && !samePath(effectiveHome, destination) && processAlive(pid)) {
889
+ migrationBlocked(provider, pid);
890
+ }
891
+ }
892
+ }
893
+ var AGENT_MIGRATION_MARKER = ".ccem-migration-v1.json";
894
+ var MIGRATION_LOCK = ".ccem-migration.lock";
895
+ var PROFILES_FILE = "profiles.json";
896
+ var LEGACY_ENTRIES = {
897
+ claude: ["projects", "history.jsonl", "plans", "file-history", "CLAUDE.md"],
898
+ codex: ["sessions", "archived_sessions", "history.jsonl", "session_index.jsonl", "memories", "memories_v2", "AGENTS.md", "AGENTS.override.md"]
899
+ };
900
+ var IDENTITY_ENV_KEYS = [
901
+ "ANTHROPIC_PROFILE",
902
+ "CLAUDE_CODE_SESSION_ACCESS_TOKEN",
903
+ "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",
904
+ "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
905
+ "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR",
906
+ "CLAUDE_CODE_ORGANIZATION_UUID",
907
+ "CLAUDE_CODE_USER_EMAIL",
908
+ "CLAUDE_CODE_HFI_BEARER_TOKEN",
909
+ "CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER",
910
+ "CLAUDE_CODE_CUSTOM_OAUTH_URL",
911
+ "CLAUDE_CODE_DESIGN_OAUTH_CLIENT_ID",
912
+ "CLAUDE_CODE_REMOTE_SETTINGS_PATH",
913
+ "CLAUDE_CODE_MOCK_REMOTE_SETTINGS",
914
+ "USE_LOCAL_OAUTH",
915
+ "USE_STAGING_OAUTH",
916
+ "CLAUDE_LOCAL_OAUTH_API_BASE",
917
+ "CODEX_ACCESS_TOKEN"
918
+ ];
919
+ function isAgentIdentityEnvKey(key) {
920
+ return IDENTITY_ENV_KEYS.includes(key) || ["CLAUDE_CODE_OAUTH_", "CLAUDE_CODE_HOST_", "CLAUDE_CODE_ACCOUNT_", "CLAUDE_COWORK_MEMORY_"].some((prefix) => key.startsWith(prefix));
921
+ }
922
+ var INHERITED_AGENT_ENV_KEYS = [
923
+ ...IDENTITY_ENV_KEYS,
924
+ "ANTHROPIC_BASE_URL",
925
+ "ANTHROPIC_AUTH_TOKEN",
926
+ "ANTHROPIC_API_KEY",
927
+ "ANTHROPIC_CUSTOM_HEADERS",
928
+ "ANTHROPIC_MODEL",
929
+ "ANTHROPIC_SMALL_FAST_MODEL",
930
+ "ANTHROPIC_PROFILE",
931
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
932
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
933
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
934
+ "CLAUDE_CODE_SUBAGENT_MODEL",
935
+ "CLAUDE_CODE_SESSION_ACCESS_TOKEN",
936
+ "CLAUDE_CODE_OAUTH_TOKEN",
937
+ "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
938
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
939
+ "CLAUDE_CODE_OAUTH_CLIENT_ID",
940
+ "CLAUDE_CODE_OAUTH_SCOPES",
941
+ "CLAUDE_CODE_HOST_CREDS_FILE",
942
+ "CLAUDE_CODE_HOST_AUTH_ENV_VAR",
943
+ "CLAUDE_CODE_ACCOUNT_UUID",
944
+ "CLAUDE_CODE_ACCOUNT_TAGGED_ID",
945
+ "CLAUDE_CODE_USE_BEDROCK",
946
+ "CLAUDE_CODE_USE_VERTEX",
947
+ "CLAUDE_CODE_USE_FOUNDRY",
948
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
949
+ "CLAUDE_CODE_USE_MANTLE",
950
+ "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
951
+ "CLAUDE_CODE_USE_GATEWAY",
952
+ "CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
953
+ "CLAUDE_CONFIG_DIR",
954
+ "CLAUDE_SECURESTORAGE_CONFIG_DIR",
955
+ "OPENAI_API_KEY",
956
+ "OPENAI_BASE_URL",
957
+ "CODEX_API_KEY",
958
+ "CODEX_HOME",
959
+ "CODEX_SQLITE_HOME",
960
+ "AWS_BEARER_TOKEN_BEDROCK",
961
+ "ANTHROPIC_AWS_API_KEY",
962
+ "ANTHROPIC_FOUNDRY_API_KEY",
963
+ "ANTHROPIC_FOUNDRY_AUTH_TOKEN",
964
+ "ANTHROPIC_FOUNDRY_RESOURCE",
965
+ "ANTHROPIC_VERTEX_PROJECT_ID",
966
+ "CLOUD_ML_REGION"
967
+ ];
968
+ var SHARED_CODEX_ENV_KEYS = [
969
+ "OPENAI_API_KEY",
970
+ "OPENAI_BASE_URL",
971
+ "CODEX_API_KEY",
972
+ "CODEX_ACCESS_TOKEN",
973
+ "CODEX_SQLITE_HOME"
974
+ ];
975
+ function userHome(env) {
976
+ return env.HOME || env.USERPROFILE || os.homedir();
977
+ }
978
+ function getCcemAgentBase(env = process.env) {
979
+ const override = env.CCEM_AGENT_HOME?.trim();
980
+ if (override && (!path2.isAbsolute(override) || override.split(/[\\/]/).includes(".."))) {
981
+ throw new Error("CCEM_AGENT_HOME must be an absolute path without '..'");
982
+ }
983
+ return path2.resolve(override || path2.join(userHome(env), ".ccem", "agents"));
984
+ }
985
+ function readCodexIsolation(env) {
986
+ if (env.CCEM_CODEX_ISOLATED === "1") return true;
987
+ if (env.CCEM_CODEX_ISOLATED === "0") return false;
988
+ const file = path2.join(getCcemAgentBase(env), PROFILES_FILE);
989
+ let raw;
990
+ try {
991
+ raw = fs2.readFileSync(file, "utf8");
992
+ } catch (error) {
993
+ if (error.code === "ENOENT") return false;
994
+ throw new Error("Cannot read CCEM agent profile preferences");
995
+ }
996
+ let profiles;
997
+ try {
998
+ profiles = JSON.parse(raw);
999
+ } catch {
1000
+ throw new Error("CCEM agent profile preferences are invalid");
1001
+ }
1002
+ if (!profiles || typeof profiles !== "object" || Array.isArray(profiles)) {
1003
+ throw new Error("CCEM agent profile preferences are invalid");
1004
+ }
1005
+ const value = profiles.codexIsolation;
1006
+ if (value === void 0) return false;
1007
+ if (typeof value !== "boolean") throw new Error("CCEM codexIsolation preference must be a boolean");
1008
+ return value;
1009
+ }
1010
+ function isCodexIsolated(env = process.env) {
1011
+ try {
1012
+ return readCodexIsolation(env);
1013
+ } catch {
1014
+ return true;
1015
+ }
1016
+ }
1017
+ function getCcemIsolatedAgentHome(provider, env = process.env) {
1018
+ return path2.join(getCcemAgentBase(env), provider);
1019
+ }
1020
+ function getOfficialCodexHome(env) {
1021
+ const override = env.CODEX_HOME?.trim();
1022
+ if (!override) return path2.resolve(userHome(env), ".codex");
1023
+ if (override === "~") return path2.resolve(userHome(env));
1024
+ if (/^~[\\/]/.test(override)) return path2.resolve(userHome(env), override.slice(2));
1025
+ return path2.resolve(override);
1026
+ }
1027
+ function getCcemAgentHome(provider, env = process.env) {
1028
+ return provider === "codex" && !isCodexIsolated(env) ? getOfficialCodexHome(env) : getCcemIsolatedAgentHome(provider, env);
1029
+ }
1030
+ function getCcemAgentEnv(env = process.env) {
1031
+ const isolated = readCodexIsolation(env);
1032
+ const claude = getCcemIsolatedAgentHome("claude", env);
1033
+ const codex = isolated ? getCcemIsolatedAgentHome("codex", env) : getOfficialCodexHome(env);
1034
+ return {
1035
+ CLAUDE_CONFIG_DIR: claude,
1036
+ CLAUDE_SECURESTORAGE_CONFIG_DIR: claude,
1037
+ CODEX_HOME: codex,
1038
+ CCEM_CODEX_ISOLATED: isolated ? "1" : "0",
1039
+ ...isolated ? { CODEX_SQLITE_HOME: codex } : {}
1040
+ };
1041
+ }
1042
+ function clearInheritedAgentEnv(env, codexIsolated = isCodexIsolated(env)) {
1043
+ for (const key of Object.keys(env)) {
1044
+ if (!codexIsolated && SHARED_CODEX_ENV_KEYS.includes(key)) continue;
1045
+ if (INHERITED_AGENT_ENV_KEYS.includes(key) || isAgentIdentityEnvKey(key)) {
1046
+ delete env[key];
1047
+ }
1048
+ }
1049
+ }
1050
+ function buildIsolatedAgentEnv(baseEnv = process.env, selectedEnv = {}) {
1051
+ const profile = getCcemAgentEnv(baseEnv);
1052
+ const codexIsolated = profile.CCEM_CODEX_ISOLATED === "1";
1053
+ const env = { ...baseEnv };
1054
+ clearInheritedAgentEnv(env, codexIsolated);
1055
+ Object.assign(env, selectedEnv);
1056
+ for (const key of Object.keys(env)) {
1057
+ if (isAgentIdentityEnvKey(key) && (codexIsolated || key !== "CODEX_ACCESS_TOKEN")) delete env[key];
1058
+ }
1059
+ delete env.CLAUDECODE;
1060
+ if (baseEnv.CCEM_AGENT_HOME === void 0) delete env.CCEM_AGENT_HOME;
1061
+ else env.CCEM_AGENT_HOME = baseEnv.CCEM_AGENT_HOME;
1062
+ if (!codexIsolated) {
1063
+ if (baseEnv.CODEX_SQLITE_HOME === void 0) delete env.CODEX_SQLITE_HOME;
1064
+ else env.CODEX_SQLITE_HOME = baseEnv.CODEX_SQLITE_HOME;
1065
+ }
1066
+ Object.assign(env, profile);
1067
+ return Object.fromEntries(Object.entries(env).filter((entry) => entry[1] !== void 0));
1068
+ }
1069
+ function statIfPresent(file) {
1070
+ try {
1071
+ return fs2.lstatSync(file);
1072
+ } catch (error) {
1073
+ if (error.code === "ENOENT") return void 0;
1074
+ throw error;
1075
+ }
1076
+ }
1077
+ function ensureRealDirectory(directory) {
1078
+ validateNoSymlinks(directory);
1079
+ fs2.mkdirSync(directory, { recursive: true, mode: 448 });
1080
+ const stat2 = fs2.lstatSync(directory);
1081
+ if (stat2.isSymbolicLink() || !stat2.isDirectory()) {
1082
+ throw new Error(`CCEM agent directory must be a real directory: ${directory}`);
1083
+ }
1084
+ fs2.chmodSync(directory, 448);
1085
+ }
1086
+ function validateNoSymlinks(file) {
1087
+ let current = path2.parse(file).root;
1088
+ for (const component of file.slice(current.length).split(path2.sep).filter(Boolean)) {
1089
+ current = path2.join(current, component);
1090
+ const stat2 = statIfPresent(current);
1091
+ if (!stat2) break;
1092
+ if (stat2.isSymbolicLink()) throw new Error(`CCEM agent state cannot use a symlink: ${current}`);
1093
+ }
1094
+ }
1095
+ function resolveExistingParent(file) {
1096
+ const suffix = [];
1097
+ let parent = file;
1098
+ while (!statIfPresent(parent)) {
1099
+ suffix.unshift(path2.basename(parent));
1100
+ parent = path2.dirname(parent);
1101
+ }
1102
+ return path2.join(fs2.realpathSync(parent), ...suffix);
1103
+ }
1104
+ function validateAgentBase(base, env) {
1105
+ validateNoSymlinks(base);
1106
+ const resolved = resolveExistingParent(base);
1107
+ for (const name of [".claude", ".codex"]) {
1108
+ const official = resolveExistingParent(path2.join(userHome(env), name));
1109
+ if (resolved === official || resolved.startsWith(`${official}${path2.sep}`) || official.startsWith(`${resolved}${path2.sep}`)) {
1110
+ throw new Error("CCEM agent state must not overlap an official Claude or Codex home");
1111
+ }
1112
+ }
1113
+ }
1114
+ function syncDirectory(directory) {
1115
+ if (process.platform === "win32") return;
1116
+ const fd = fs2.openSync(directory, "r");
1117
+ try {
1118
+ fs2.fsyncSync(fd);
1119
+ } finally {
1120
+ fs2.closeSync(fd);
1121
+ }
1122
+ }
1123
+ function migrationComplete(marker) {
1124
+ const stat2 = statIfPresent(marker);
1125
+ if (!stat2) return false;
1126
+ if (!stat2.isFile() || stat2.isSymbolicLink()) throw new Error("CCEM agent migration marker is invalid");
1127
+ let version;
1128
+ try {
1129
+ version = JSON.parse(fs2.readFileSync(marker, "utf8")).version;
1130
+ } catch {
1131
+ }
1132
+ if (version !== 1) throw new Error("CCEM agent migration marker is invalid or unsupported");
1133
+ return true;
1134
+ }
1135
+ function writeNewFile(file, contents) {
1136
+ validateNoSymlinks(file);
1137
+ const existing = statIfPresent(file);
1138
+ if (existing) {
1139
+ if (!existing.isFile()) throw new Error(`CCEM agent file conflicts with a directory: ${file}`);
1140
+ return;
1141
+ }
1142
+ const temporary = path2.join(path2.dirname(file), `.ccem-copy-${randomUUID()}.tmp`);
1143
+ try {
1144
+ const fd = fs2.openSync(temporary, "wx", 384);
1145
+ try {
1146
+ fs2.writeFileSync(fd, contents);
1147
+ fs2.fsyncSync(fd);
1148
+ } finally {
1149
+ fs2.closeSync(fd);
1150
+ }
1151
+ try {
1152
+ fs2.linkSync(temporary, file);
1153
+ } catch (error) {
1154
+ if (error.code !== "EEXIST") throw error;
1155
+ }
1156
+ } finally {
1157
+ fs2.rmSync(temporary, { force: true });
1158
+ }
1159
+ }
1160
+ function copyLegacyEntry(source, destination) {
1161
+ const sourceStat = statIfPresent(source);
1162
+ if (!sourceStat || sourceStat.isSymbolicLink()) return;
1163
+ if (sourceStat.isFile() && /\.(?:sqlite|sqlite3|db)(?:-(?:wal|shm))?$/i.test(path2.basename(source))) return;
1164
+ validateNoSymlinks(destination);
1165
+ const destinationStat = statIfPresent(destination);
1166
+ if (sourceStat.isDirectory()) {
1167
+ if (destinationStat && !destinationStat.isDirectory()) throw new Error(`CCEM agent directory conflicts with a file: ${destination}`);
1168
+ ensureRealDirectory(destination);
1169
+ for (const name of fs2.readdirSync(source)) {
1170
+ copyLegacyEntry(path2.join(source, name), path2.join(destination, name));
1171
+ }
1172
+ syncDirectory(destination);
1173
+ return;
1174
+ }
1175
+ if (!sourceStat.isFile()) return;
1176
+ if (destinationStat) {
1177
+ if (!destinationStat.isFile()) throw new Error(`CCEM agent file conflicts with a directory: ${destination}`);
1178
+ return;
1179
+ }
1180
+ const temporary = path2.join(path2.dirname(destination), `.ccem-copy-${randomUUID()}.tmp`);
1181
+ let sourceFd;
1182
+ let destinationFd;
1183
+ try {
1184
+ sourceFd = fs2.openSync(source, fs2.constants.O_RDONLY | (fs2.constants.O_NOFOLLOW ?? 0));
1185
+ const openedStat = fs2.fstatSync(sourceFd);
1186
+ if (!openedStat.isFile()) throw new Error("Legacy agent history changed during migration");
1187
+ destinationFd = fs2.openSync(temporary, "wx", 384);
1188
+ const buffer = Buffer.alloc(1024 * 1024);
1189
+ let remaining = openedStat.size;
1190
+ while (remaining > 0) {
1191
+ const bytesRead = fs2.readSync(sourceFd, buffer, 0, Math.min(remaining, buffer.length), null);
1192
+ if (!bytesRead) throw new Error("Legacy agent history changed during migration");
1193
+ let offset = 0;
1194
+ while (offset < bytesRead) offset += fs2.writeSync(destinationFd, buffer, offset, bytesRead - offset);
1195
+ remaining -= bytesRead;
1196
+ }
1197
+ fs2.futimesSync(destinationFd, openedStat.atime, openedStat.mtime);
1198
+ fs2.fsyncSync(destinationFd);
1199
+ fs2.closeSync(destinationFd);
1200
+ destinationFd = void 0;
1201
+ try {
1202
+ fs2.linkSync(temporary, destination);
1203
+ } catch (error) {
1204
+ if (error.code !== "EEXIST") throw error;
1205
+ }
1206
+ } finally {
1207
+ if (sourceFd !== void 0) fs2.closeSync(sourceFd);
1208
+ if (destinationFd !== void 0) fs2.closeSync(destinationFd);
1209
+ fs2.rmSync(temporary, { force: true });
1210
+ }
1211
+ }
1212
+ function acquireMigrationLock(base) {
1213
+ const lockPath = path2.join(base, MIGRATION_LOCK);
1214
+ const contents = JSON.stringify({ pid: process.pid });
1215
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1216
+ try {
1217
+ const fd = fs2.openSync(lockPath, "wx", 384);
1218
+ try {
1219
+ fs2.writeFileSync(fd, contents);
1220
+ fs2.fsyncSync(fd);
1221
+ } catch (error) {
1222
+ const owned = fs2.fstatSync(fd);
1223
+ const current = statIfPresent(lockPath);
1224
+ if (current?.ino === owned.ino && current.dev === owned.dev) fs2.unlinkSync(lockPath);
1225
+ throw error;
1226
+ } finally {
1227
+ fs2.closeSync(fd);
1228
+ }
1229
+ return () => {
1230
+ if (statIfPresent(lockPath)?.isFile() && fs2.readFileSync(lockPath, "utf8") === contents) fs2.unlinkSync(lockPath);
1231
+ };
1232
+ } catch (error) {
1233
+ if (error.code !== "EEXIST") throw error;
1234
+ const stat2 = fs2.lstatSync(lockPath);
1235
+ if (!stat2.isFile() || stat2.isSymbolicLink()) throw new Error("CCEM agent migration lock is invalid");
1236
+ const old = fs2.readFileSync(lockPath, "utf8");
1237
+ let pid;
1238
+ try {
1239
+ pid = JSON.parse(old).pid;
1240
+ } catch {
1241
+ }
1242
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("CCEM agent migration lock is invalid");
1243
+ try {
1244
+ process.kill(pid, 0);
1245
+ } catch (probeError) {
1246
+ if (probeError.code === "ESRCH" && attempt === 0) {
1247
+ if (fs2.readFileSync(lockPath, "utf8") !== old) throw new Error("CCEM agent migration lock changed; retry preparation");
1248
+ fs2.unlinkSync(lockPath);
1249
+ continue;
1250
+ }
1251
+ }
1252
+ throw new Error(`CCEM agent migration is in progress (PID ${pid}); retry when it finishes`);
1253
+ }
1254
+ }
1255
+ throw new Error("Could not acquire CCEM agent migration lock");
1256
+ }
1257
+ function ensureCcemAgentHome(provider, env = process.env) {
1258
+ if (provider === "codex" && !readCodexIsolation(env)) return getOfficialCodexHome(env);
1259
+ const base = getCcemAgentBase(env);
1260
+ const root = getCcemIsolatedAgentHome(provider, env);
1261
+ validateAgentBase(base, env);
1262
+ ensureRealDirectory(base);
1263
+ ensureRealDirectory(root);
1264
+ for (const entry of LEGACY_ENTRIES[provider]) validateNoSymlinks(path2.join(root, entry));
1265
+ validateNoSymlinks(path2.join(root, provider === "claude" ? ".claude.json" : "config.toml"));
1266
+ const marker = path2.join(root, AGENT_MIGRATION_MARKER);
1267
+ if (migrationComplete(marker)) return root;
1268
+ const unlock = acquireMigrationLock(base);
1269
+ try {
1270
+ if (migrationComplete(marker)) return root;
1271
+ const source = provider === "codex" ? getOfficialCodexHome(env) : path2.join(userHome(env), ".claude");
1272
+ if (provider === "codex") {
1273
+ const resolvedBase = resolveExistingParent(base);
1274
+ const resolvedSource = resolveExistingParent(source);
1275
+ if (resolvedBase === resolvedSource || resolvedBase.startsWith(`${resolvedSource}${path2.sep}`) || resolvedSource.startsWith(`${resolvedBase}${path2.sep}`)) {
1276
+ throw new Error("CCEM Codex migration source must not overlap its isolated agent directory");
1277
+ }
1278
+ }
1279
+ assertNoLegacyAgentWriters(provider, userHome(env), source, root);
1280
+ const sourceStat = statIfPresent(source);
1281
+ if (sourceStat?.isDirectory() && !sourceStat.isSymbolicLink()) {
1282
+ for (const entry of LEGACY_ENTRIES[provider]) copyLegacyEntry(path2.join(source, entry), path2.join(root, entry));
1283
+ }
1284
+ if (provider === "claude") writeNewFile(path2.join(root, ".claude.json"), JSON.stringify({ hasCompletedOnboarding: true }));
1285
+ writeNewFile(marker, JSON.stringify({ version: 1 }));
1286
+ syncDirectory(root);
1287
+ return root;
1288
+ } finally {
1289
+ unlock();
1290
+ }
1291
+ }
707
1292
  var V2_ALGORITHM = "aes-256-gcm";
708
1293
  function encryptV2WithKey(text, key, nonce) {
709
1294
  const cipher = crypto.createCipheriv(V2_ALGORITHM, key, nonce);
@@ -747,14 +1332,14 @@ var LEGACY_KEY = crypto2.scryptSync("claude-code-env-manager-secret", "salt", 32
747
1332
  var _installKey = null;
748
1333
  function getOrCreateInstallKey() {
749
1334
  if (_installKey) return _installKey;
750
- const keyPath = path.join(getCcemConfigDir(), ".install-key");
751
- if (fs.existsSync(keyPath)) {
752
- _installKey = Buffer.from(fs.readFileSync(keyPath, "utf-8").trim(), "hex");
1335
+ const keyPath = path3.join(getCcemConfigDir(), ".install-key");
1336
+ if (fs3.existsSync(keyPath)) {
1337
+ _installKey = Buffer.from(fs3.readFileSync(keyPath, "utf-8").trim(), "hex");
753
1338
  return _installKey;
754
1339
  }
755
1340
  ensureCcemDir();
756
1341
  _installKey = crypto2.randomBytes(32);
757
- fs.writeFileSync(keyPath, _installKey.toString("hex"), { mode: 384 });
1342
+ fs3.writeFileSync(keyPath, _installKey.toString("hex"), { mode: 384 });
758
1343
  return _installKey;
759
1344
  }
760
1345
  var encrypt = (text) => {
@@ -785,30 +1370,30 @@ var decrypt = (text) => {
785
1370
  }
786
1371
  };
787
1372
  var getHomeDir = () => {
788
- return process.env.HOME || process.env.USERPROFILE || os.homedir() || "";
1373
+ return process.env.HOME || process.env.USERPROFILE || os2.homedir() || "";
789
1374
  };
790
1375
  var getCcemConfigDir = () => {
791
- return path.join(getHomeDir(), ".ccem");
1376
+ return path3.join(getHomeDir(), ".ccem");
792
1377
  };
793
1378
  var getCcemConfigPath = () => {
794
- return path.join(getCcemConfigDir(), "config.json");
1379
+ return path3.join(getCcemConfigDir(), "config.json");
795
1380
  };
796
1381
  var ensureCcemDir = () => {
797
1382
  const ccemDir = getCcemConfigDir();
798
- if (!fs.existsSync(ccemDir)) {
799
- fs.mkdirSync(ccemDir, { recursive: true, mode: 448 });
1383
+ if (!fs3.existsSync(ccemDir)) {
1384
+ fs3.mkdirSync(ccemDir, { recursive: true, mode: 448 });
800
1385
  }
801
1386
  if (process.platform !== "win32") {
802
- fs.chmodSync(ccemDir, 448);
1387
+ fs3.chmodSync(ccemDir, 448);
803
1388
  }
804
1389
  return ccemDir;
805
1390
  };
806
1391
  var getLegacyConfigPath = () => {
807
1392
  const home = getHomeDir();
808
1393
  if (process.platform === "darwin") {
809
- return path.join(home, "Library", "Preferences", "claude-code-env-manager-nodejs", "config.json");
1394
+ return path3.join(home, "Library", "Preferences", "claude-code-env-manager-nodejs", "config.json");
810
1395
  }
811
- return path.join(home, ".config", "claude-code-env-manager-nodejs", "config.json");
1396
+ return path3.join(home, ".config", "claude-code-env-manager-nodejs", "config.json");
812
1397
  };
813
1398
 
814
1399
  // src/desktopControl.ts
@@ -875,11 +1460,11 @@ function getDesktopControlDescriptorPath() {
875
1460
  return process.env.CCEM_CONTROL_FILE?.trim() || getDefaultControlDescriptorPath();
876
1461
  }
877
1462
  function getDefaultControlDescriptorPath() {
878
- return path2.join(getCcemConfigDir(), "control.json");
1463
+ return path4.join(getCcemConfigDir(), "control.json");
879
1464
  }
880
1465
  function isDefaultDescriptorPath(descriptorPath) {
881
1466
  try {
882
- return path2.resolve(descriptorPath) === path2.resolve(getDefaultControlDescriptorPath());
1467
+ return path4.resolve(descriptorPath) === path4.resolve(getDefaultControlDescriptorPath());
883
1468
  } catch {
884
1469
  return false;
885
1470
  }
@@ -889,7 +1474,7 @@ function safeRemoveStaleDescriptor(descriptorPath) {
889
1474
  return false;
890
1475
  }
891
1476
  try {
892
- fs2.rmSync(descriptorPath);
1477
+ fs4.rmSync(descriptorPath);
893
1478
  return true;
894
1479
  } catch {
895
1480
  return false;
@@ -967,10 +1552,10 @@ function isDescriptor(value) {
967
1552
  );
968
1553
  }
969
1554
  function resolveDesktopControlDescriptor(descriptorPath = getDesktopControlDescriptorPath()) {
970
- if (!fs2.existsSync(descriptorPath)) {
1555
+ if (!fs4.existsSync(descriptorPath)) {
971
1556
  throw new Error(`CCEM Desktop control endpoint not found at ${descriptorPath}. Start CCEM Desktop first.`);
972
1557
  }
973
- const parsed = JSON.parse(fs2.readFileSync(descriptorPath, "utf-8"));
1558
+ const parsed = JSON.parse(fs4.readFileSync(descriptorPath, "utf-8"));
974
1559
  const endpoint = parsed.endpoint?.trim();
975
1560
  const token = parsed.token?.trim();
976
1561
  if (!endpoint || !token) {
@@ -1235,29 +1820,29 @@ import inquirer from "inquirer";
1235
1820
  import chalk9 from "chalk";
1236
1821
  import Table4 from "cli-table3";
1237
1822
  import { spawn as spawn4 } from "child_process";
1238
- import * as fs14 from "fs";
1239
- import * as path12 from "path";
1823
+ import * as fs16 from "fs";
1824
+ import * as path14 from "path";
1240
1825
  import { fileURLToPath as fileURLToPath2 } from "url";
1241
- import { randomUUID } from "crypto";
1826
+ import { randomUUID as randomUUID2 } from "crypto";
1242
1827
 
1243
1828
  // src/ui.ts
1244
1829
  import chalk from "chalk";
1245
1830
  import Table from "cli-table3";
1246
1831
 
1247
1832
  // src/usage.ts
1248
- import * as fs3 from "fs";
1833
+ import * as fs5 from "fs";
1249
1834
  import * as fsPromises from "fs/promises";
1250
- import * as path3 from "path";
1251
- import * as os2 from "os";
1835
+ import * as path5 from "path";
1836
+ import * as os3 from "os";
1252
1837
  import * as readline from "readline";
1253
1838
  import { fileURLToPath } from "url";
1254
1839
  var __filename = fileURLToPath(import.meta.url);
1255
- var __dirname = path3.dirname(__filename);
1256
- var CLAUDE_PROJECTS_DIR = path3.join(os2.homedir(), ".claude", "projects");
1257
- var CCEM_DIR = path3.join(os2.homedir(), ".ccem");
1258
- var CACHE_VERSION = 2;
1259
- var getCachePath = () => path3.join(CCEM_DIR, "usage-cache.json");
1260
- var getPricesPath = () => path3.join(CCEM_DIR, "model-prices.json");
1840
+ var __dirname = path5.dirname(__filename);
1841
+ var CLAUDE_PROJECTS_DIR = path5.join(getCcemAgentHome("claude"), "projects");
1842
+ var CCEM_DIR = path5.join(os3.homedir(), ".ccem");
1843
+ var CACHE_VERSION = 3;
1844
+ var getCachePath = () => path5.join(CCEM_DIR, "usage-cache.json");
1845
+ var getPricesPath = () => path5.join(CCEM_DIR, "model-prices.json");
1261
1846
  async function ensureCcemDir2() {
1262
1847
  try {
1263
1848
  await fsPromises.access(CCEM_DIR);
@@ -1267,7 +1852,7 @@ async function ensureCcemDir2() {
1267
1852
  }
1268
1853
  var LITELLM_PRICES_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
1269
1854
  var getBundledPricesPath = () => {
1270
- return path3.join(__dirname, "..", "model-prices.json");
1855
+ return path5.join(__dirname, "..", "model-prices.json");
1271
1856
  };
1272
1857
  var DEFAULT_PRICES = {
1273
1858
  "claude-opus-4-5": {
@@ -1386,8 +1971,8 @@ async function getFileMetaAsync(filePath) {
1386
1971
  function loadCacheSync() {
1387
1972
  try {
1388
1973
  const cachePath = getCachePath();
1389
- if (!fs3.existsSync(cachePath)) return null;
1390
- const data = JSON.parse(fs3.readFileSync(cachePath, "utf-8"));
1974
+ if (!fs5.existsSync(cachePath)) return null;
1975
+ const data = JSON.parse(fs5.readFileSync(cachePath, "utf-8"));
1391
1976
  if (data.version !== CACHE_VERSION) return null;
1392
1977
  return data;
1393
1978
  } catch {
@@ -1455,7 +2040,7 @@ async function parseJSONLFileAsync(filePath, prices, signal) {
1455
2040
  const entries = [];
1456
2041
  const messageEntryIndexes = /* @__PURE__ */ new Map();
1457
2042
  try {
1458
- const fileStream = fs3.createReadStream(filePath, { encoding: "utf-8" });
2043
+ const fileStream = fs5.createReadStream(filePath, { encoding: "utf-8" });
1459
2044
  const rl = readline.createInterface({
1460
2045
  input: fileStream,
1461
2046
  crlfDelay: Infinity
@@ -1521,14 +2106,15 @@ async function getAllJSONLFilesAsync() {
1521
2106
  if (!projectsDirExists) return files;
1522
2107
  const projects = await fsPromises.readdir(CLAUDE_PROJECTS_DIR);
1523
2108
  for (const project of projects) {
1524
- const projectPath = path3.join(CLAUDE_PROJECTS_DIR, project);
2109
+ const projectPath = path5.join(CLAUDE_PROJECTS_DIR, project);
1525
2110
  try {
1526
- const stat2 = await fsPromises.stat(projectPath);
2111
+ const stat2 = await fsPromises.lstat(projectPath);
1527
2112
  if (stat2.isDirectory()) {
1528
2113
  const projectFiles = await fsPromises.readdir(projectPath);
1529
2114
  for (const file of projectFiles) {
1530
- if (file.endsWith(".jsonl")) {
1531
- files.push(path3.join(projectPath, file));
2115
+ const filePath = path5.join(projectPath, file);
2116
+ if (file.endsWith(".jsonl") && (await fsPromises.lstat(filePath)).isFile()) {
2117
+ files.push(filePath);
1532
2118
  }
1533
2119
  }
1534
2120
  }
@@ -1541,6 +2127,7 @@ async function getAllJSONLFilesAsync() {
1541
2127
  }
1542
2128
  async function getUsageStats(signal) {
1543
2129
  if (signal?.aborted) throw new Error("Aborted");
2130
+ ensureCcemAgentHome("claude");
1544
2131
  const prices = await loadPrices();
1545
2132
  if (signal?.aborted) throw new Error("Aborted");
1546
2133
  const files = await getAllJSONLFilesAsync();
@@ -1751,10 +2338,10 @@ var renderLogoWithEnvPanel = (envName, env, defaultMode) => {
1751
2338
  const parsed = new URL(url);
1752
2339
  const protocol = parsed.protocol + "//";
1753
2340
  const host = parsed.host;
1754
- const path13 = parsed.pathname + parsed.search;
2341
+ const path15 = parsed.pathname + parsed.search;
1755
2342
  const hostStart = host.slice(0, 8);
1756
2343
  const hostEnd = host.slice(-4);
1757
- const pathPart = path13.length > 10 ? path13.slice(0, 7) + "..." : path13;
2344
+ const pathPart = path15.length > 10 ? path15.slice(0, 7) + "..." : path15;
1758
2345
  return `${protocol}${hostStart}...${hostEnd}${pathPart}`;
1759
2346
  } catch {
1760
2347
  return truncate(url, max);
@@ -2192,70 +2779,62 @@ var selectEnvWithKeys = (registries, current) => {
2192
2779
  };
2193
2780
 
2194
2781
  // src/permissions.ts
2195
- import fs7 from "fs";
2782
+ import fs9 from "fs";
2196
2783
  import chalk3 from "chalk";
2197
2784
  import Table2 from "cli-table3";
2198
2785
 
2199
2786
  // src/utils.ts
2200
2787
  import crypto3 from "crypto";
2201
- import fs4 from "fs";
2202
- import os3 from "os";
2203
- import path4 from "path";
2788
+ import fs6 from "fs";
2789
+ import path6 from "path";
2204
2790
  var SECRET_KEY = crypto3.scryptSync("claude-code-env-manager-secret", "salt", 32);
2205
2791
  var findProjectRoot = () => {
2206
2792
  let currentDir = process.cwd();
2207
- const root = path4.parse(currentDir).root;
2793
+ const root = path6.parse(currentDir).root;
2208
2794
  while (currentDir !== root) {
2209
- if (fs4.existsSync(path4.join(currentDir, ".git")) || fs4.existsSync(path4.join(currentDir, "package.json"))) {
2795
+ if (fs6.existsSync(path6.join(currentDir, ".git")) || fs6.existsSync(path6.join(currentDir, "package.json"))) {
2210
2796
  return currentDir;
2211
2797
  }
2212
- currentDir = path4.dirname(currentDir);
2798
+ currentDir = path6.dirname(currentDir);
2213
2799
  }
2214
2800
  return process.cwd();
2215
2801
  };
2216
2802
  var getSettingsPath = (useLocal = true) => {
2217
2803
  const projectRoot = findProjectRoot();
2218
- const claudeDir = path4.join(projectRoot, ".claude");
2804
+ const claudeDir = path6.join(projectRoot, ".claude");
2219
2805
  const filename = useLocal ? "settings.local.json" : "settings.json";
2220
- return path4.join(claudeDir, filename);
2806
+ return path6.join(claudeDir, filename);
2221
2807
  };
2222
2808
  var ensureClaudeDir = () => {
2223
2809
  const projectRoot = findProjectRoot();
2224
- const claudeDir = path4.join(projectRoot, ".claude");
2225
- if (!fs4.existsSync(claudeDir)) {
2226
- fs4.mkdirSync(claudeDir, { recursive: true });
2810
+ const claudeDir = path6.join(projectRoot, ".claude");
2811
+ if (!fs6.existsSync(claudeDir)) {
2812
+ fs6.mkdirSync(claudeDir, { recursive: true });
2227
2813
  }
2228
2814
  return claudeDir;
2229
2815
  };
2230
- var getHomeDir2 = () => {
2231
- return process.env.HOME || process.env.USERPROFILE || os3.homedir() || "";
2232
- };
2233
2816
  var getGlobalClaudeConfigPath = () => {
2234
- return path4.join(getHomeDir2(), ".claude.json");
2817
+ return path6.join(getCcemAgentHome("claude"), ".claude.json");
2235
2818
  };
2236
2819
  var getGlobalClaudeSettingsPath = () => {
2237
- return path4.join(getHomeDir2(), ".claude", "settings.json");
2820
+ return path6.join(getCcemAgentHome("claude"), "settings.json");
2238
2821
  };
2239
2822
  var ensureGlobalClaudeDir = () => {
2240
- const claudeDir = path4.join(getHomeDir2(), ".claude");
2241
- if (!fs4.existsSync(claudeDir)) {
2242
- fs4.mkdirSync(claudeDir, { recursive: true });
2243
- }
2244
- return claudeDir;
2823
+ return ensureCcemAgentHome("claude");
2245
2824
  };
2246
2825
 
2247
2826
  // src/launcher.ts
2248
2827
  import { spawn as spawn2 } from "child_process";
2249
- import * as fs6 from "fs";
2250
- import * as path6 from "path";
2828
+ import * as fs8 from "fs";
2829
+ import * as path8 from "path";
2251
2830
  import chalk2 from "chalk";
2252
2831
 
2253
2832
  // src/sessionProvenance.ts
2254
- import { execFileSync } from "child_process";
2255
- import fs5 from "fs";
2833
+ import { execFileSync as execFileSync2 } from "child_process";
2834
+ import fs7 from "fs";
2256
2835
  import { createRequire } from "module";
2257
2836
  import os4 from "os";
2258
- import path5 from "path";
2837
+ import path7 from "path";
2259
2838
  var DEFAULT_CONFIG_SOURCE = "ccem";
2260
2839
  var STATE_DB_FILE_NAME = "state.sqlite";
2261
2840
  var BIND_POLL_INTERVAL_MS = 500;
@@ -2310,7 +2889,7 @@ function startCliClaudeProvenanceTracking(options) {
2310
2889
  if (!jsonlPath) {
2311
2890
  return;
2312
2891
  }
2313
- const sourceSessionId = readClaudeSessionId(jsonlPath) ?? normalizeText(path5.parse(jsonlPath).name);
2892
+ const sourceSessionId = readClaudeSessionId(jsonlPath) ?? normalizeText(path7.parse(jsonlPath).name);
2314
2893
  if (!sourceSessionId) {
2315
2894
  return;
2316
2895
  }
@@ -2437,7 +3016,7 @@ function bindSourceSessionId(client, ccemSessionId, sourceSessionId) {
2437
3016
  }
2438
3017
  function openNodeSqliteDb(DatabaseSync) {
2439
3018
  const dbPath = getStateDbPath();
2440
- fs5.mkdirSync(path5.dirname(dbPath), { recursive: true });
3019
+ fs7.mkdirSync(path7.dirname(dbPath), { recursive: true });
2441
3020
  const db = new DatabaseSync(dbPath);
2442
3021
  db.exec(schemaSql());
2443
3022
  return db;
@@ -2468,7 +3047,7 @@ function getDatabaseSyncCtor() {
2468
3047
  function execSqlite3Cli(statementSql) {
2469
3048
  if (sqlite3CliAvailable == null) {
2470
3049
  try {
2471
- execFileSync("sqlite3", ["-version"], { stdio: "ignore" });
3050
+ execFileSync2("sqlite3", ["-version"], { stdio: "ignore" });
2472
3051
  sqlite3CliAvailable = true;
2473
3052
  } catch {
2474
3053
  sqlite3CliAvailable = false;
@@ -2478,8 +3057,8 @@ function execSqlite3Cli(statementSql) {
2478
3057
  throw new Error("sqlite3 CLI is unavailable and node:sqlite is not supported by this Node runtime");
2479
3058
  }
2480
3059
  const dbPath = getStateDbPath();
2481
- fs5.mkdirSync(path5.dirname(dbPath), { recursive: true });
2482
- execFileSync("sqlite3", [dbPath], {
3060
+ fs7.mkdirSync(path7.dirname(dbPath), { recursive: true });
3061
+ execFileSync2("sqlite3", [dbPath], {
2483
3062
  input: `${schemaSql()}
2484
3063
  ${statementSql}
2485
3064
  `,
@@ -2491,7 +3070,7 @@ function getStateDbPath() {
2491
3070
  if (override) {
2492
3071
  return override;
2493
3072
  }
2494
- return path5.join(os4.homedir(), ".ccem", STATE_DB_FILE_NAME);
3073
+ return path7.join(os4.homedir(), ".ccem", STATE_DB_FILE_NAME);
2495
3074
  }
2496
3075
  function schemaSql() {
2497
3076
  return `
@@ -2517,16 +3096,16 @@ function schemaSql() {
2517
3096
  `;
2518
3097
  }
2519
3098
  function discoverClaudeJsonlPath(projectDir, startedAtMs) {
2520
- const projectsDir = path5.join(os4.homedir(), ".claude", "projects");
3099
+ const projectsDir = path7.join(getCcemAgentHome("claude"), "projects");
2521
3100
  const earliestModifiedAt = startedAtMs - 15e3;
2522
3101
  for (const key of projectDirKeys(projectDir)) {
2523
- const baseDir = path5.join(projectsDir, key);
2524
- if (!fs5.existsSync(baseDir)) {
3102
+ const baseDir = path7.join(projectsDir, key);
3103
+ if (!fs7.existsSync(baseDir)) {
2525
3104
  continue;
2526
3105
  }
2527
- const candidates = fs5.readdirSync(baseDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => {
2528
- const fullPath = path5.join(baseDir, entry.name);
2529
- return { path: fullPath, modifiedAt: fs5.statSync(fullPath).mtimeMs };
3106
+ const candidates = fs7.readdirSync(baseDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => {
3107
+ const fullPath = path7.join(baseDir, entry.name);
3108
+ return { path: fullPath, modifiedAt: fs7.statSync(fullPath).mtimeMs };
2530
3109
  }).filter((candidate) => candidate.modifiedAt >= earliestModifiedAt).sort((left, right) => right.modifiedAt - left.modifiedAt);
2531
3110
  if (candidates.length > 0) {
2532
3111
  return candidates[0].path;
@@ -2537,16 +3116,16 @@ function discoverClaudeJsonlPath(projectDir, startedAtMs) {
2537
3116
  function projectDirKeys(projectDir) {
2538
3117
  const candidates = [projectDir];
2539
3118
  try {
2540
- candidates.push(fs5.realpathSync(projectDir));
3119
+ candidates.push(fs7.realpathSync(projectDir));
2541
3120
  } catch {
2542
3121
  }
2543
3122
  if (process.platform === "darwin") {
2544
3123
  if (projectDir.startsWith("/private/")) {
2545
3124
  candidates.push(projectDir.slice("/private".length));
2546
3125
  } else if (projectDir.startsWith("/tmp")) {
2547
- candidates.push(path5.posix.join("/private", projectDir));
3126
+ candidates.push(path7.posix.join("/private", projectDir));
2548
3127
  } else if (projectDir.startsWith("/var/")) {
2549
- candidates.push(path5.posix.join("/private", projectDir));
3128
+ candidates.push(path7.posix.join("/private", projectDir));
2550
3129
  }
2551
3130
  }
2552
3131
  return [...new Set(candidates.map(projectDirKey))];
@@ -2555,7 +3134,7 @@ function projectDirKey(projectDir) {
2555
3134
  return projectDir.replace(/[\/\\: ]/g, "-");
2556
3135
  }
2557
3136
  function readClaudeSessionId(jsonlPath) {
2558
- const lines = fs5.readFileSync(jsonlPath, "utf8").split("\n");
3137
+ const lines = fs7.readFileSync(jsonlPath, "utf8").split("\n");
2559
3138
  for (const line of lines) {
2560
3139
  if (!line.trim()) {
2561
3140
  continue;
@@ -2587,17 +3166,6 @@ function reportTrackingError(stage, error) {
2587
3166
  }
2588
3167
 
2589
3168
  // src/launcher.ts
2590
- var MANAGED_CLAUDE_ENV_KEYS = [
2591
- "ANTHROPIC_BASE_URL",
2592
- "ANTHROPIC_AUTH_TOKEN",
2593
- "ANTHROPIC_DEFAULT_OPUS_MODEL",
2594
- "ANTHROPIC_DEFAULT_SONNET_MODEL",
2595
- "ANTHROPIC_DEFAULT_HAIKU_MODEL",
2596
- "ANTHROPIC_MODEL",
2597
- "CLAUDE_CODE_SUBAGENT_MODEL",
2598
- "ANTHROPIC_API_KEY",
2599
- "ANTHROPIC_SMALL_FAST_MODEL"
2600
- ];
2601
3169
  function buildEnvVars(envName, envConfig, options = {}) {
2602
3170
  const runtimeEnv = resolveEnvConfigForRuntime(envName, envConfig);
2603
3171
  const authToken = runtimeEnv.ANTHROPIC_AUTH_TOKEN ? decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN) : void 0;
@@ -2641,9 +3209,9 @@ function buildPermArgs(modeName) {
2641
3209
  return args;
2642
3210
  }
2643
3211
  function ensureSessionsDir() {
2644
- const dir = path6.join(ensureCcemDir(), "sessions");
2645
- if (!fs6.existsSync(dir)) {
2646
- fs6.mkdirSync(dir, { recursive: true });
3212
+ const dir = path8.join(ensureCcemDir(), "sessions");
3213
+ if (!fs8.existsSync(dir)) {
3214
+ fs8.mkdirSync(dir, { recursive: true });
2647
3215
  }
2648
3216
  return dir;
2649
3217
  }
@@ -2659,13 +3227,11 @@ async function launchClaude(options) {
2659
3227
  allowDesktopProxyOverride
2660
3228
  } = options;
2661
3229
  const ccemRuntimeId = sessionId ?? `cli-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
2662
- const env = { ...process.env };
2663
- for (const key of MANAGED_CLAUDE_ENV_KEYS) {
2664
- delete env[key];
2665
- }
2666
- if (envConfig) {
2667
- Object.assign(env, buildEnvVars(envName, envConfig, { allowDesktopProxyOverride }));
2668
- }
3230
+ ensureCcemAgentHome("claude");
3231
+ const env = buildIsolatedAgentEnv(
3232
+ process.env,
3233
+ envConfig ? buildEnvVars(envName, envConfig, { allowDesktopProxyOverride }) : {}
3234
+ );
2669
3235
  delete env.CLAUDECODE;
2670
3236
  env.CCEM_RUNTIME_ID = ccemRuntimeId;
2671
3237
  env.CCEM_SESSION_ID = ccemRuntimeId;
@@ -2716,8 +3282,8 @@ async function launchClaude(options) {
2716
3282
  provenanceTracking?.stop();
2717
3283
  if (sessionId) {
2718
3284
  try {
2719
- fs6.writeFileSync(
2720
- path6.join(sessionsDir, `${sessionId}.exit`),
3285
+ fs8.writeFileSync(
3286
+ path8.join(sessionsDir, `${sessionId}.exit`),
2721
3287
  String(code ?? 0)
2722
3288
  );
2723
3289
  } catch {
@@ -2748,6 +3314,19 @@ async function launchClaude(options) {
2748
3314
  });
2749
3315
  });
2750
3316
  }
3317
+ async function launchAgentAuth(provider) {
3318
+ const env = buildIsolatedAgentEnv();
3319
+ ensureCcemAgentHome(provider, { ...process.env, CCEM_CODEX_ISOLATED: env.CCEM_CODEX_ISOLATED });
3320
+ const args = provider === "claude" ? ["auth", "login"] : env.CCEM_CODEX_ISOLATED === "1" ? ["--config", `sqlite_home=${JSON.stringify(env.CODEX_HOME)}`, "login"] : ["login"];
3321
+ await new Promise((resolve5, reject) => {
3322
+ const child = spawn2(provider, args, { env, stdio: "inherit", shell: false });
3323
+ child.once("error", reject);
3324
+ child.once("exit", (code, signal) => {
3325
+ if (code === 0) resolve5();
3326
+ else reject(new Error(`${provider} login ${signal ? `was interrupted (${signal})` : `failed (exit ${code ?? 1})`}`));
3327
+ });
3328
+ });
3329
+ }
2751
3330
 
2752
3331
  // src/permissions.ts
2753
3332
  var PERMISSION_RULE_LINE_WIDTH = 100;
@@ -2774,14 +3353,14 @@ var formatPermissionRulesForDisplay = (rules) => {
2774
3353
  }).join("\n");
2775
3354
  };
2776
3355
  var readSettings = (settingsPath) => {
2777
- if (fs7.existsSync(settingsPath)) {
3356
+ if (fs9.existsSync(settingsPath)) {
2778
3357
  try {
2779
- const content = fs7.readFileSync(settingsPath, "utf-8");
3358
+ const content = fs9.readFileSync(settingsPath, "utf-8");
2780
3359
  return JSON.parse(content);
2781
3360
  } catch {
2782
3361
  console.warn(chalk3.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${settingsPath}\uFF0C\u5C06\u521B\u5EFA\u5907\u4EFD`));
2783
3362
  const backupPath = settingsPath + ".error." + Date.now();
2784
- fs7.copyFileSync(settingsPath, backupPath);
3363
+ fs9.copyFileSync(settingsPath, backupPath);
2785
3364
  console.log(chalk3.gray(`\u5907\u4EFD\u5DF2\u4FDD\u5B58\u5230: ${backupPath}`));
2786
3365
  return {};
2787
3366
  }
@@ -2790,7 +3369,7 @@ var readSettings = (settingsPath) => {
2790
3369
  };
2791
3370
  var writeSettings = (settingsPath, config3) => {
2792
3371
  ensureClaudeDir();
2793
- fs7.writeFileSync(settingsPath, JSON.stringify(config3, null, 2) + "\n");
3372
+ fs9.writeFileSync(settingsPath, JSON.stringify(config3, null, 2) + "\n");
2794
3373
  };
2795
3374
  var mergePermissions = (existing, preset) => {
2796
3375
  const existingAllow = normalizePermissionAllowRules(existing.permissions?.allow || []);
@@ -2823,14 +3402,14 @@ var applyPermissionMode = (modeName) => {
2823
3402
  };
2824
3403
  var resetPermissions = () => {
2825
3404
  const settingsPath = getSettingsPath(true);
2826
- if (!fs7.existsSync(settingsPath)) {
3405
+ if (!fs9.existsSync(settingsPath)) {
2827
3406
  console.log(chalk3.yellow("\u6CA1\u6709\u81EA\u5B9A\u4E49\u6743\u9650\u914D\u7F6E\u9700\u8981\u91CD\u7F6E"));
2828
3407
  return;
2829
3408
  }
2830
3409
  const config3 = readSettings(settingsPath);
2831
3410
  delete config3.permissions;
2832
3411
  if (Object.keys(config3).length === 0) {
2833
- fs7.unlinkSync(settingsPath);
3412
+ fs9.unlinkSync(settingsPath);
2834
3413
  console.log(chalk3.green("\u5DF2\u5220\u9664\u914D\u7F6E\u6587\u4EF6\uFF08\u6587\u4EF6\u4E3A\u7A7A\uFF09"));
2835
3414
  } else {
2836
3415
  writeSettings(settingsPath, config3);
@@ -2840,7 +3419,7 @@ var resetPermissions = () => {
2840
3419
  };
2841
3420
  var showCurrentMode = () => {
2842
3421
  const settingsPath = getSettingsPath(true);
2843
- if (!fs7.existsSync(settingsPath)) {
3422
+ if (!fs9.existsSync(settingsPath)) {
2844
3423
  console.log(chalk3.yellow("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49\u6743\u9650"));
2845
3424
  console.log(chalk3.gray(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${settingsPath}`));
2846
3425
  return;
@@ -2899,14 +3478,14 @@ var runWithTempPermissions = async (modeName, envConfig, envName) => {
2899
3478
  };
2900
3479
 
2901
3480
  // src/environmentMutations.ts
2902
- import fs8 from "fs";
2903
- import path7 from "path";
3481
+ import fs10 from "fs";
3482
+ import path9 from "path";
2904
3483
  function nativeRuntimeStatePath() {
2905
- return path7.join(getCcemConfigDir(), "native-runtime-state.json");
3484
+ return path9.join(getCcemConfigDir(), "native-runtime-state.json");
2906
3485
  }
2907
3486
  function resolveMutationAuthority(options) {
2908
- const descriptorExists = options.descriptorExists ?? (() => fs8.existsSync(getDesktopControlDescriptorPath()));
2909
- const stateExists = options.stateExists ?? (() => fs8.existsSync(nativeRuntimeStatePath()));
3487
+ const descriptorExists = options.descriptorExists ?? (() => fs10.existsSync(getDesktopControlDescriptorPath()));
3488
+ const stateExists = options.stateExists ?? (() => fs10.existsSync(nativeRuntimeStatePath()));
2910
3489
  return { descriptorExists, stateExists };
2911
3490
  }
2912
3491
  function assertOfflineMutationIsSafe(name, stateExists) {
@@ -3006,13 +3585,13 @@ function deleteEnvironmentFromConfig(config3, name) {
3006
3585
  }
3007
3586
 
3008
3587
  // src/setup.ts
3009
- import fs9 from "fs";
3588
+ import fs11 from "fs";
3010
3589
  import chalk4 from "chalk";
3011
3590
  import { spawn as spawn3 } from "child_process";
3012
3591
  var readJsonFile = (filePath) => {
3013
- if (fs9.existsSync(filePath)) {
3592
+ if (fs11.existsSync(filePath)) {
3014
3593
  try {
3015
- const content = fs9.readFileSync(filePath, "utf-8");
3594
+ const content = fs11.readFileSync(filePath, "utf-8");
3016
3595
  return JSON.parse(content);
3017
3596
  } catch {
3018
3597
  console.warn(chalk4.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${filePath}`));
@@ -3022,11 +3601,12 @@ var readJsonFile = (filePath) => {
3022
3601
  return {};
3023
3602
  };
3024
3603
  var writeJsonFile = (filePath, data) => {
3025
- fs9.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
3604
+ fs11.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
3026
3605
  };
3027
3606
  var setupOnboarding = () => {
3028
3607
  const configPath = getGlobalClaudeConfigPath();
3029
3608
  try {
3609
+ ensureGlobalClaudeDir();
3030
3610
  const config3 = readJsonFile(configPath);
3031
3611
  if (config3.hasCompletedOnboarding === true) {
3032
3612
  console.log(chalk4.gray(" \u2713 hasCompletedOnboarding \u5DF2\u8BBE\u7F6E"));
@@ -3090,6 +3670,7 @@ var setupMcpTool = () => {
3090
3670
  "user"
3091
3671
  ], {
3092
3672
  stdio: "pipe",
3673
+ env: buildIsolatedAgentEnv(),
3093
3674
  shell: true
3094
3675
  });
3095
3676
  let stdout = "";
@@ -3123,7 +3704,7 @@ var setupMcpTool = () => {
3123
3704
  });
3124
3705
  };
3125
3706
  var runSetupInit = async (options = {}) => {
3126
- console.log(chalk4.bold("\n\u{1F527} Claude Code \u521D\u59CB\u5316\u8BBE\u7F6E\n"));
3707
+ console.log(chalk4.bold("\n\u{1F527} CCEM Claude Code \u521D\u59CB\u5316\u8BBE\u7F6E\n"));
3127
3708
  console.log(chalk4.cyan("1. \u8BBE\u7F6E onboarding \u72B6\u6001"));
3128
3709
  const step1 = setupOnboarding();
3129
3710
  console.log(chalk4.cyan("\n2. \u914D\u7F6E\u9690\u79C1\u8BBE\u7F6E"));
@@ -3148,9 +3729,9 @@ var runSetupInit = async (options = {}) => {
3148
3729
  };
3149
3730
 
3150
3731
  // src/skills.ts
3151
- import { execFileSync as execFileSync2 } from "child_process";
3152
- import * as fs10 from "fs";
3153
- import * as path8 from "path";
3732
+ import { execFileSync as execFileSync3 } from "child_process";
3733
+ import * as fs12 from "fs";
3734
+ import * as path10 from "path";
3154
3735
  import chalk5 from "chalk";
3155
3736
  var SKILL_GROUPS = {
3156
3737
  official: { label: "\u5B98\u65B9", icon: "\u{1F3E2}" },
@@ -3386,7 +3967,7 @@ function parseGitHubUrl(url) {
3386
3967
  repo,
3387
3968
  branch,
3388
3969
  repoPath,
3389
- repoPath ? path8.basename(repoPath) : repo
3970
+ repoPath ? path10.basename(repoPath) : repo
3390
3971
  );
3391
3972
  return { owner, repo, branch, path: repoPath };
3392
3973
  } catch {
@@ -3394,12 +3975,12 @@ function parseGitHubUrl(url) {
3394
3975
  }
3395
3976
  }
3396
3977
  function getSkillsDir() {
3397
- return path8.join(process.cwd(), ".claude", "skills");
3978
+ return path10.join(process.cwd(), ".claude", "skills");
3398
3979
  }
3399
3980
  function ensureSkillsDir() {
3400
3981
  const skillsDir = getSkillsDir();
3401
- if (!fs10.existsSync(skillsDir)) {
3402
- fs10.mkdirSync(skillsDir, { recursive: true });
3982
+ if (!fs12.existsSync(skillsDir)) {
3983
+ fs12.mkdirSync(skillsDir, { recursive: true });
3403
3984
  } else {
3404
3985
  cleanupTempDirs(skillsDir);
3405
3986
  }
@@ -3407,11 +3988,11 @@ function ensureSkillsDir() {
3407
3988
  }
3408
3989
  function cleanupTempDirs(skillsDir) {
3409
3990
  try {
3410
- const entries = fs10.readdirSync(skillsDir, { withFileTypes: true });
3991
+ const entries = fs12.readdirSync(skillsDir, { withFileTypes: true });
3411
3992
  for (const entry of entries) {
3412
3993
  if (entry.isDirectory() && entry.name.startsWith(".tmp-")) {
3413
- const tmpPath = path8.join(skillsDir, entry.name);
3414
- fs10.rmSync(tmpPath, { recursive: true });
3994
+ const tmpPath = path10.join(skillsDir, entry.name);
3995
+ fs12.rmSync(tmpPath, { recursive: true });
3415
3996
  }
3416
3997
  }
3417
3998
  } catch {
@@ -3422,27 +4003,27 @@ function downloadSkillWithGit(owner, repo, branch, repoPath, targetName) {
3422
4003
  try {
3423
4004
  validateGitHubInstallParts(owner, repo, branch, repoPath, targetName);
3424
4005
  const skillsDir = ensureSkillsDir();
3425
- const targetDir = path8.join(skillsDir, targetName);
3426
- if (fs10.existsSync(targetDir)) {
4006
+ const targetDir = path10.join(skillsDir, targetName);
4007
+ if (fs12.existsSync(targetDir)) {
3427
4008
  console.log(chalk5.yellow(`Skill "${targetName}" already exists. Updating...`));
3428
- fs10.rmSync(targetDir, { recursive: true });
4009
+ fs12.rmSync(targetDir, { recursive: true });
3429
4010
  }
3430
4011
  const repoUrl = `https://github.com/${owner}/${repo}.git`;
3431
- tempDir = path8.join(skillsDir, `.tmp-${Date.now()}`);
3432
- fs10.mkdirSync(tempDir, { recursive: true });
3433
- execFileSync2("git", ["init"], { cwd: tempDir, stdio: "pipe" });
3434
- execFileSync2("git", ["remote", "add", "origin", repoUrl], { cwd: tempDir, stdio: "pipe" });
3435
- execFileSync2("git", ["config", "core.sparseCheckout", "true"], { cwd: tempDir, stdio: "pipe" });
3436
- const sparseFile = path8.join(tempDir, ".git", "info", "sparse-checkout");
3437
- fs10.mkdirSync(path8.dirname(sparseFile), { recursive: true });
3438
- fs10.writeFileSync(sparseFile, repoPath ? `${repoPath}/
4012
+ tempDir = path10.join(skillsDir, `.tmp-${Date.now()}`);
4013
+ fs12.mkdirSync(tempDir, { recursive: true });
4014
+ execFileSync3("git", ["init"], { cwd: tempDir, stdio: "pipe" });
4015
+ execFileSync3("git", ["remote", "add", "origin", repoUrl], { cwd: tempDir, stdio: "pipe" });
4016
+ execFileSync3("git", ["config", "core.sparseCheckout", "true"], { cwd: tempDir, stdio: "pipe" });
4017
+ const sparseFile = path10.join(tempDir, ".git", "info", "sparse-checkout");
4018
+ fs12.mkdirSync(path10.dirname(sparseFile), { recursive: true });
4019
+ fs12.writeFileSync(sparseFile, repoPath ? `${repoPath}/
3439
4020
  ` : "*\n");
3440
- execFileSync2("git", ["pull", "--depth=1", "origin", branch], {
4021
+ execFileSync3("git", ["pull", "--depth=1", "origin", branch], {
3441
4022
  cwd: tempDir,
3442
4023
  stdio: "pipe"
3443
4024
  });
3444
- const sourceDir = repoPath ? path8.join(tempDir, repoPath) : tempDir;
3445
- if (!fs10.existsSync(sourceDir)) {
4025
+ const sourceDir = repoPath ? path10.join(tempDir, repoPath) : tempDir;
4026
+ if (!fs12.existsSync(sourceDir)) {
3446
4027
  throw new Error(`Path "${repoPath}" not found in repository`);
3447
4028
  }
3448
4029
  copyDir(sourceDir, targetDir);
@@ -3453,31 +4034,31 @@ function downloadSkillWithGit(owner, repo, branch, repoPath, targetName) {
3453
4034
  console.error(chalk5.red(`Failed to download skill: ${errMsg}`));
3454
4035
  return false;
3455
4036
  } finally {
3456
- if (tempDir && fs10.existsSync(tempDir)) {
3457
- fs10.rmSync(tempDir, { recursive: true });
4037
+ if (tempDir && fs12.existsSync(tempDir)) {
4038
+ fs12.rmSync(tempDir, { recursive: true });
3458
4039
  }
3459
4040
  }
3460
4041
  }
3461
4042
  function copyDir(src, dest) {
3462
- fs10.mkdirSync(dest, { recursive: true });
3463
- const entries = fs10.readdirSync(src, { withFileTypes: true });
4043
+ fs12.mkdirSync(dest, { recursive: true });
4044
+ const entries = fs12.readdirSync(src, { withFileTypes: true });
3464
4045
  for (const entry of entries) {
3465
4046
  if (entry.name === ".git") continue;
3466
- const srcPath = path8.join(src, entry.name);
3467
- const destPath = path8.join(dest, entry.name);
4047
+ const srcPath = path10.join(src, entry.name);
4048
+ const destPath = path10.join(dest, entry.name);
3468
4049
  if (entry.isDirectory()) {
3469
4050
  copyDir(srcPath, destPath);
3470
4051
  } else {
3471
- fs10.copyFileSync(srcPath, destPath);
4052
+ fs12.copyFileSync(srcPath, destPath);
3472
4053
  }
3473
4054
  }
3474
4055
  }
3475
4056
  function isSafeSkillName(name) {
3476
- return name.trim().length > 0 && name !== "." && name !== ".." && !name.startsWith(".") && !path8.isAbsolute(name) && !name.includes("/") && !name.includes("\\") && !name.includes("\0");
4057
+ return name.trim().length > 0 && name !== "." && name !== ".." && !name.startsWith(".") && !path10.isAbsolute(name) && !name.includes("/") && !name.includes("\\") && !name.includes("\0");
3477
4058
  }
3478
4059
  function isPathInside(childPath, parentPath) {
3479
- const relativePath = path8.relative(parentPath, childPath);
3480
- return relativePath === "" || relativePath.length > 0 && !relativePath.startsWith("..") && !path8.isAbsolute(relativePath);
4060
+ const relativePath = path10.relative(parentPath, childPath);
4061
+ return relativePath === "" || relativePath.length > 0 && !relativePath.startsWith("..") && !path10.isAbsolute(relativePath);
3481
4062
  }
3482
4063
  function addSkillFromGitHub(urlOrPreset) {
3483
4064
  const preset = SKILL_PRESETS.find((p) => p.name === urlOrPreset);
@@ -3521,7 +4102,7 @@ function addSkillFromGitHub(urlOrPreset) {
3521
4102
  }
3522
4103
  let skillName;
3523
4104
  if (parsed.path) {
3524
- skillName = path8.basename(parsed.path);
4105
+ skillName = path10.basename(parsed.path);
3525
4106
  } else {
3526
4107
  skillName = parsed.repo;
3527
4108
  }
@@ -3535,13 +4116,13 @@ function addSkillFromGitHub(urlOrPreset) {
3535
4116
  }
3536
4117
  function listInstalledSkills() {
3537
4118
  const skillsDir = getSkillsDir();
3538
- if (!fs10.existsSync(skillsDir)) {
4119
+ if (!fs12.existsSync(skillsDir)) {
3539
4120
  return [];
3540
4121
  }
3541
- const entries = fs10.readdirSync(skillsDir, { withFileTypes: true });
4122
+ const entries = fs12.readdirSync(skillsDir, { withFileTypes: true });
3542
4123
  return entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => ({
3543
4124
  name: entry.name,
3544
- path: path8.join(skillsDir, entry.name)
4125
+ path: path10.join(skillsDir, entry.name)
3545
4126
  }));
3546
4127
  }
3547
4128
  function removeSkill(name) {
@@ -3550,18 +4131,18 @@ function removeSkill(name) {
3550
4131
  return false;
3551
4132
  }
3552
4133
  const skillsDir = getSkillsDir();
3553
- const targetDir = path8.resolve(skillsDir, name);
3554
- if (!fs10.existsSync(targetDir)) {
4134
+ const targetDir = path10.resolve(skillsDir, name);
4135
+ if (!fs12.existsSync(targetDir)) {
3555
4136
  console.error(chalk5.red(`Skill "${name}" not found`));
3556
4137
  return false;
3557
4138
  }
3558
- const canonicalSkillsDir = fs10.realpathSync(skillsDir);
3559
- const canonicalTargetDir = fs10.realpathSync(targetDir);
4139
+ const canonicalSkillsDir = fs12.realpathSync(skillsDir);
4140
+ const canonicalTargetDir = fs12.realpathSync(targetDir);
3560
4141
  if (!isPathInside(canonicalTargetDir, canonicalSkillsDir)) {
3561
4142
  console.error(chalk5.red(`Refusing to remove skill outside skills directory: "${name}"`));
3562
4143
  return false;
3563
4144
  }
3564
- fs10.rmSync(targetDir, { recursive: true });
4145
+ fs12.rmSync(targetDir, { recursive: true });
3565
4146
  console.log(chalk5.green(`Removed skill "${name}"`));
3566
4147
  return true;
3567
4148
  }
@@ -3573,13 +4154,17 @@ function installFromPluginMarketplace(marketplace, packageName) {
3573
4154
  if (!isSafePluginPackage(packageName)) {
3574
4155
  throw new Error(`Invalid package name: ${packageName}`);
3575
4156
  }
4157
+ ensureCcemAgentHome("claude");
4158
+ const env = buildIsolatedAgentEnv();
3576
4159
  console.log(chalk5.cyan(`Adding marketplace: ${marketplace}...`));
3577
- execFileSync2("claude", ["plugin", "marketplace", "add", marketplace], {
3578
- stdio: "inherit"
4160
+ execFileSync3("claude", ["plugin", "marketplace", "add", marketplace], {
4161
+ stdio: "inherit",
4162
+ env
3579
4163
  });
3580
4164
  console.log(chalk5.cyan(`Installing package: ${packageName}...`));
3581
- execFileSync2("claude", ["plugin", "install", packageName], {
3582
- stdio: "inherit"
4165
+ execFileSync3("claude", ["plugin", "install", packageName], {
4166
+ stdio: "inherit",
4167
+ env
3583
4168
  });
3584
4169
  console.log(chalk5.green(`Successfully installed ${packageName}`));
3585
4170
  return true;
@@ -4112,9 +4697,9 @@ import Table3 from "cli-table3";
4112
4697
 
4113
4698
  // src/cron.ts
4114
4699
  import crypto5 from "crypto";
4115
- import * as fs11 from "fs";
4700
+ import * as fs13 from "fs";
4116
4701
  import * as os5 from "os";
4117
- import * as path9 from "path";
4702
+ import * as path11 from "path";
4118
4703
  function parseHermesNotification(value) {
4119
4704
  if (value == null) return null;
4120
4705
  const target = value;
@@ -4178,13 +4763,13 @@ var EXECUTION_PROFILES = /* @__PURE__ */ new Set([
4178
4763
  "autonomous"
4179
4764
  ]);
4180
4765
  function getCronTasksPath(baseDir = getCcemConfigDir()) {
4181
- return path9.join(baseDir, CRON_TASKS_FILE_NAME);
4766
+ return path11.join(baseDir, CRON_TASKS_FILE_NAME);
4182
4767
  }
4183
4768
  function readCronTasks(tasksPath = getCronTasksPath()) {
4184
- if (!fs11.existsSync(tasksPath)) {
4769
+ if (!fs13.existsSync(tasksPath)) {
4185
4770
  return [];
4186
4771
  }
4187
- const content = fs11.readFileSync(tasksPath, "utf-8").trim();
4772
+ const content = fs13.readFileSync(tasksPath, "utf-8").trim();
4188
4773
  if (!content) {
4189
4774
  return [];
4190
4775
  }
@@ -4199,14 +4784,14 @@ function writeCronTasks(tasks, tasksPath = getCronTasksPath()) {
4199
4784
  if (tasksPath === getCronTasksPath()) {
4200
4785
  ensureCcemDir();
4201
4786
  } else {
4202
- fs11.mkdirSync(path9.dirname(tasksPath), { recursive: true });
4787
+ fs13.mkdirSync(path11.dirname(tasksPath), { recursive: true });
4203
4788
  }
4204
4789
  const payload = { tasks };
4205
4790
  const content = `${JSON.stringify(payload, null, 2)}
4206
4791
  `;
4207
4792
  const tempPath = `${tasksPath}.${process.pid}.${Date.now()}.tmp`;
4208
- fs11.writeFileSync(tempPath, content, { encoding: "utf-8", mode: 384 });
4209
- fs11.renameSync(tempPath, tasksPath);
4793
+ fs13.writeFileSync(tempPath, content, { encoding: "utf-8", mode: 384 });
4794
+ fs13.renameSync(tempPath, tasksPath);
4210
4795
  }
4211
4796
  function validateCronExpression(cronExpression) {
4212
4797
  const fields = cronExpression.trim().split(/\s+/);
@@ -4333,10 +4918,10 @@ function deleteCronTask(selector, tasksPath = getCronTasksPath()) {
4333
4918
  }
4334
4919
  function resolveJsonInput(raw) {
4335
4920
  if (raw === "-") {
4336
- return fs11.readFileSync(0, "utf-8");
4921
+ return fs13.readFileSync(0, "utf-8");
4337
4922
  }
4338
4923
  if (raw.startsWith("@")) {
4339
- return fs11.readFileSync(path9.resolve(raw.slice(1)), "utf-8");
4924
+ return fs13.readFileSync(path11.resolve(raw.slice(1)), "utf-8");
4340
4925
  }
4341
4926
  return raw;
4342
4927
  }
@@ -4613,9 +5198,9 @@ function deriveDshProvider(envName, envConfig, options = {}) {
4613
5198
 
4614
5199
  // src/dsh/launcher.ts
4615
5200
  import { spawn as defaultSpawn } from "child_process";
4616
- import * as fs13 from "fs";
5201
+ import * as fs15 from "fs";
4617
5202
  import * as os7 from "os";
4618
- import * as path11 from "path";
5203
+ import * as path13 from "path";
4619
5204
 
4620
5205
  // src/dsh/patch.ts
4621
5206
  var IDENTIFIER_PATTERN = /^[A-Za-z0-9][\w./-]*$/;
@@ -4653,9 +5238,9 @@ function renderCordisPatch(spec) {
4653
5238
 
4654
5239
  // src/dsh/environment.ts
4655
5240
  import { execFile } from "child_process";
4656
- import * as fs12 from "fs";
5241
+ import * as fs14 from "fs";
4657
5242
  import * as os6 from "os";
4658
- import * as path10 from "path";
5243
+ import * as path12 from "path";
4659
5244
  import { promisify } from "util";
4660
5245
 
4661
5246
  // src/dsh/version.ts
@@ -4726,17 +5311,17 @@ function resolveDshRoot(env = process.env) {
4726
5311
  const inherited = env.DSH_HOME?.trim();
4727
5312
  if (inherited) return inherited;
4728
5313
  const home = env.HOME?.trim() || os6.homedir();
4729
- return path10.join(home, ".dsh");
5314
+ return path12.join(home, ".dsh");
4730
5315
  }
4731
5316
  function resolveBinOnPath(name, env = process.env, platform = process.platform) {
4732
5317
  if (name.includes("/") || platform === "win32" && name.includes("\\")) {
4733
5318
  return fileIsExecutable(name, platform) ? name : null;
4734
5319
  }
4735
- const searchDirs = (env.PATH ?? "").split(path10.delimiter).filter(Boolean);
5320
+ const searchDirs = (env.PATH ?? "").split(path12.delimiter).filter(Boolean);
4736
5321
  const extensions = platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").toLowerCase().split(";").filter(Boolean) : [""];
4737
5322
  for (const dir of searchDirs) {
4738
5323
  for (const ext of extensions) {
4739
- const candidate = path10.join(dir, name + ext);
5324
+ const candidate = path12.join(dir, name + ext);
4740
5325
  if (fileIsExecutable(candidate, platform)) return candidate;
4741
5326
  }
4742
5327
  }
@@ -4745,10 +5330,10 @@ function resolveBinOnPath(name, env = process.env, platform = process.platform)
4745
5330
  function fileIsExecutable(file, platform = process.platform) {
4746
5331
  try {
4747
5332
  if (platform === "win32") {
4748
- return fs12.statSync(file).isFile();
5333
+ return fs14.statSync(file).isFile();
4749
5334
  }
4750
- fs12.accessSync(file, fs12.constants.X_OK);
4751
- return fs12.statSync(file).isFile();
5335
+ fs14.accessSync(file, fs14.constants.X_OK);
5336
+ return fs14.statSync(file).isFile();
4752
5337
  } catch {
4753
5338
  return false;
4754
5339
  }
@@ -4766,15 +5351,15 @@ function resolveDshInvocation(deps = {}) {
4766
5351
  function resolveWindowsDshInvocation(env) {
4767
5352
  const dshFile = resolveBinOnPath("dsh", env, "win32");
4768
5353
  if (!dshFile) return null;
4769
- const ext = path10.extname(dshFile).toLowerCase();
5354
+ const ext = path12.extname(dshFile).toLowerCase();
4770
5355
  if (ext === ".exe" || ext === ".com") {
4771
5356
  return { bin: dshFile, prefix: [] };
4772
5357
  }
4773
5358
  if (ext !== ".cmd") return null;
4774
- const shimDir = path10.dirname(dshFile);
5359
+ const shimDir = path12.dirname(dshFile);
4775
5360
  const candidates = [
4776
- path10.join(shimDir, "node_modules", "@deepseek-ai", "dsh"),
4777
- path10.join(shimDir, "..", "node_modules", "@deepseek-ai", "dsh")
5361
+ path12.join(shimDir, "node_modules", "@deepseek-ai", "dsh"),
5362
+ path12.join(shimDir, "..", "node_modules", "@deepseek-ai", "dsh")
4778
5363
  ];
4779
5364
  for (const pkgDir of candidates) {
4780
5365
  const entryScript = verifyDshPackage(pkgDir);
@@ -4787,18 +5372,18 @@ function resolveWindowsDshInvocation(env) {
4787
5372
  return null;
4788
5373
  }
4789
5374
  function verifyDshPackage(pkgDir) {
4790
- const pkgJsonPath = path10.join(pkgDir, "package.json");
5375
+ const pkgJsonPath = path12.join(pkgDir, "package.json");
4791
5376
  try {
4792
- const raw = fs12.readFileSync(pkgJsonPath, "utf-8");
5377
+ const raw = fs14.readFileSync(pkgJsonPath, "utf-8");
4793
5378
  const pkg2 = JSON.parse(raw);
4794
5379
  if (pkg2.name !== "@deepseek-ai/dsh") return null;
4795
5380
  const binEntry = typeof pkg2.bin === "string" ? pkg2.bin : pkg2.bin?.dsh ?? null;
4796
5381
  if (!binEntry || typeof binEntry !== "string") return null;
4797
- const entryPath = path10.resolve(pkgDir, binEntry);
4798
- const realEntry = fs12.realpathSync(entryPath);
4799
- const realPkgDir = fs12.realpathSync(pkgDir);
4800
- if (!realEntry.startsWith(realPkgDir + path10.sep) && realEntry !== realPkgDir) return null;
4801
- if (!fs12.statSync(realEntry).isFile()) return null;
5382
+ const entryPath = path12.resolve(pkgDir, binEntry);
5383
+ const realEntry = fs14.realpathSync(entryPath);
5384
+ const realPkgDir = fs14.realpathSync(pkgDir);
5385
+ if (!realEntry.startsWith(realPkgDir + path12.sep) && realEntry !== realPkgDir) return null;
5386
+ if (!fs14.statSync(realEntry).isFile()) return null;
4802
5387
  return realEntry;
4803
5388
  } catch {
4804
5389
  return null;
@@ -4936,7 +5521,7 @@ var DSH_PERMISSION_MODES = [
4936
5521
  ];
4937
5522
  var DSH_PERMISSION_ENV = "DSH_PERMISSION_MODE";
4938
5523
  function cleanupTempDir(dir) {
4939
- fs13.rmSync(dir, { recursive: true, force: true });
5524
+ fs15.rmSync(dir, { recursive: true, force: true });
4940
5525
  }
4941
5526
  function signalExitCode(signal) {
4942
5527
  if (!signal) return 1;
@@ -5041,10 +5626,10 @@ async function runDshTask(options) {
5041
5626
  };
5042
5627
  }
5043
5628
  const inheritedDshHome = env.DSH_HOME?.trim() || void 0;
5044
- const tempDir = fs13.mkdtempSync(path11.join(os7.tmpdir(), "ccem-dsh-"));
5045
- const patchPath = path11.join(tempDir, "cordis.ccem.patch.yml");
5629
+ const tempDir = fs15.mkdtempSync(path13.join(os7.tmpdir(), "ccem-dsh-"));
5630
+ const patchPath = path13.join(tempDir, "cordis.ccem.patch.yml");
5046
5631
  const patchContent = renderCordisPatch(options.spec);
5047
- fs13.writeFileSync(patchPath, patchContent, { mode: 384 });
5632
+ fs15.writeFileSync(patchPath, patchContent, { mode: 384 });
5048
5633
  let exitCode = null;
5049
5634
  let signal = null;
5050
5635
  let spawnError = null;
@@ -5413,32 +5998,17 @@ Note: Use -- to separate task text from options if the task could be
5413
5998
 
5414
5999
  // src/index.ts
5415
6000
  var __filename2 = fileURLToPath2(import.meta.url);
5416
- var __dirname2 = path12.dirname(__filename2);
5417
- var pkgPath = path12.resolve(__dirname2, "..", "package.json");
5418
- var pkg = JSON.parse(fs14.readFileSync(pkgPath, "utf-8"));
6001
+ var __dirname2 = path14.dirname(__filename2);
6002
+ var pkgPath = path14.resolve(__dirname2, "..", "package.json");
6003
+ var pkg = JSON.parse(fs16.readFileSync(pkgPath, "utf-8"));
5419
6004
  var program = new Command();
5420
6005
  var DEFAULT_OFFICIAL_ENV = {
5421
6006
  ANTHROPIC_BASE_URL: "https://api.anthropic.com",
5422
6007
  ANTHROPIC_DEFAULT_HAIKU_MODEL: "claude-3-5-haiku-20241022",
5423
6008
  ANTHROPIC_MODEL: "opus"
5424
6009
  };
5425
- var MANAGED_CLAUDE_ENV_KEYS2 = [
5426
- "ANTHROPIC_BASE_URL",
5427
- "ANTHROPIC_AUTH_TOKEN",
5428
- "ANTHROPIC_DEFAULT_OPUS_MODEL",
5429
- "ANTHROPIC_DEFAULT_SONNET_MODEL",
5430
- "ANTHROPIC_DEFAULT_HAIKU_MODEL",
5431
- "ANTHROPIC_MODEL",
5432
- "CLAUDE_CODE_SUBAGENT_MODEL",
5433
- "ANTHROPIC_API_KEY",
5434
- "ANTHROPIC_SMALL_FAST_MODEL"
5435
- ];
6010
+ var MANAGED_CLAUDE_ENV_KEYS = INHERITED_AGENT_ENV_KEYS;
5436
6011
  var shellQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
5437
- var clearManagedClaudeEnv = (env) => {
5438
- for (const key of MANAGED_CLAUDE_ENV_KEYS2) {
5439
- delete env[key];
5440
- }
5441
- };
5442
6012
  var buildResolvedEnvVars = (envName, env) => {
5443
6013
  const runtimeEnv = resolveEnvConfigForRuntime(envName, env);
5444
6014
  const authToken = runtimeEnv.ANTHROPIC_AUTH_TOKEN ? decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN) : void 0;
@@ -5447,7 +6017,7 @@ var buildResolvedEnvVars = (envName, env) => {
5447
6017
  runtimeEnv.ANTHROPIC_BASE_URL,
5448
6018
  authToken
5449
6019
  );
5450
- const resolved = {};
6020
+ const resolved = getCcemAgentEnv();
5451
6021
  if (runtimeEnv.ANTHROPIC_BASE_URL) resolved.ANTHROPIC_BASE_URL = runtimeEnv.ANTHROPIC_BASE_URL;
5452
6022
  if (authToken) resolved.ANTHROPIC_AUTH_TOKEN = authToken;
5453
6023
  if (runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL) resolved.ANTHROPIC_DEFAULT_OPUS_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL;
@@ -5458,8 +6028,15 @@ var buildResolvedEnvVars = (envName, env) => {
5458
6028
  return resolved;
5459
6029
  };
5460
6030
  var buildShellEnvCommands = (envName, env) => {
6031
+ ensureCcemAgentHome("claude");
6032
+ ensureCcemAgentHome("codex");
5461
6033
  const resolved = buildResolvedEnvVars(envName, env);
5462
- return MANAGED_CLAUDE_ENV_KEYS2.map(
6034
+ const keys = [.../* @__PURE__ */ new Set([
6035
+ ...MANAGED_CLAUDE_ENV_KEYS,
6036
+ ...Object.keys(process.env).filter(isAgentIdentityEnvKey),
6037
+ ...Object.keys(resolved)
6038
+ ])];
6039
+ return keys.filter((key) => resolved.CCEM_CODEX_ISOLATED === "1" || !SHARED_CODEX_ENV_KEYS.includes(key)).map(
5463
6040
  (key) => resolved[key] ? `export ${key}=${shellQuote(resolved[key])}` : `unset ${key}`
5464
6041
  );
5465
6042
  };
@@ -5510,11 +6087,11 @@ var recoverRegistriesFromLegacy = (registries) => {
5510
6087
  return registries;
5511
6088
  }
5512
6089
  const legacyConfigPath = getLegacyConfigPath();
5513
- if (!fs14.existsSync(legacyConfigPath)) {
6090
+ if (!fs16.existsSync(legacyConfigPath)) {
5514
6091
  return registries;
5515
6092
  }
5516
6093
  try {
5517
- const legacyRaw = JSON.parse(fs14.readFileSync(legacyConfigPath, "utf-8"));
6094
+ const legacyRaw = JSON.parse(fs16.readFileSync(legacyConfigPath, "utf-8"));
5518
6095
  const legacyRegistries = legacyRaw.registries ?? {};
5519
6096
  let changed = false;
5520
6097
  const recovered = { ...registries };
@@ -5717,15 +6294,15 @@ var switchEnvironment = async (name) => {
5717
6294
  exportCmds.forEach((cmd) => console.log(cmd));
5718
6295
  }
5719
6296
  };
5720
- var getSessionsFilePath = () => path12.join(getCcemConfigDir(), "sessions.json");
5721
- var getRuntimeStateFilePath = () => path12.join(getCcemConfigDir(), "runtime-state.json");
5722
- var getBotBindRequestFilePath = () => path12.join(getCcemConfigDir(), "bot-bind-requests.jsonl");
6297
+ var getSessionsFilePath = () => path14.join(getCcemConfigDir(), "sessions.json");
6298
+ var getRuntimeStateFilePath = () => path14.join(getCcemConfigDir(), "runtime-state.json");
6299
+ var getBotBindRequestFilePath = () => path14.join(getCcemConfigDir(), "bot-bind-requests.jsonl");
5723
6300
  var parseJsonFile = (filePath) => {
5724
- if (!fs14.existsSync(filePath)) {
6301
+ if (!fs16.existsSync(filePath)) {
5725
6302
  return null;
5726
6303
  }
5727
6304
  try {
5728
- return JSON.parse(fs14.readFileSync(filePath, "utf-8"));
6305
+ return JSON.parse(fs16.readFileSync(filePath, "utf-8"));
5729
6306
  } catch {
5730
6307
  return null;
5731
6308
  }
@@ -5817,8 +6394,8 @@ var resolveBotBindRuntimeId = (explicitRuntimeId) => {
5817
6394
  };
5818
6395
  var appendBotBindRequest = (payload) => {
5819
6396
  const requestPath = getBotBindRequestFilePath();
5820
- fs14.mkdirSync(path12.dirname(requestPath), { recursive: true });
5821
- fs14.appendFileSync(requestPath, `${JSON.stringify(payload)}
6397
+ fs16.mkdirSync(path14.dirname(requestPath), { recursive: true });
6398
+ fs16.appendFileSync(requestPath, `${JSON.stringify(payload)}
5822
6399
  `, "utf-8");
5823
6400
  return requestPath;
5824
6401
  };
@@ -6033,6 +6610,8 @@ program.command("env").description("Output environment variables for shell eval"
6033
6610
  const current = config2.get("current");
6034
6611
  const env = registries[current];
6035
6612
  if (!env) return;
6613
+ ensureCcemAgentHome("claude");
6614
+ ensureCcemAgentHome("codex");
6036
6615
  const outputEnv = buildResolvedEnvVars(current, env);
6037
6616
  if (options.json) {
6038
6617
  console.log(JSON.stringify(outputEnv, null, 2));
@@ -6048,9 +6627,9 @@ program.command("run <command...>").description("Run a command with the current
6048
6627
  console.error(chalk9.red("No environment configuration found."));
6049
6628
  process.exit(1);
6050
6629
  }
6051
- const env = { ...process.env };
6052
- clearManagedClaudeEnv(env);
6053
- Object.assign(env, buildResolvedEnvVars(current, envConfig));
6630
+ ensureCcemAgentHome("claude");
6631
+ ensureCcemAgentHome("codex");
6632
+ const env = buildIsolatedAgentEnv(process.env, buildResolvedEnvVars(current, envConfig));
6054
6633
  const [cmd, ...args] = command;
6055
6634
  const child = spawn4(cmd, args, {
6056
6635
  env,
@@ -6061,6 +6640,12 @@ program.command("run <command...>").description("Run a command with the current
6061
6640
  process.exit(code ?? 0);
6062
6641
  });
6063
6642
  });
6643
+ program.command("auth <provider>").description("Sign in using the selected Claude Code or Codex profile").action(async (provider) => {
6644
+ if (provider !== "claude" && provider !== "codex") {
6645
+ program.error("Provider must be claude or codex");
6646
+ }
6647
+ await launchAgentAuth(provider);
6648
+ });
6064
6649
  registerCronCommands(program);
6065
6650
  var setupCmd = program.command("setup").description("Setup commands for permanent configurations");
6066
6651
  setupCmd.command("perms").description("\u6C38\u4E45\u914D\u7F6E\u6743\u9650\u6A21\u5F0F").option("--yolo", "\u5E94\u7528 YOLO \u6A21\u5F0F\uFF08\u5168\u90E8\u653E\u5F00\uFF09").option("--dev", "\u5E94\u7528\u5F00\u53D1\u6A21\u5F0F").option("--readonly", "\u5E94\u7528\u53EA\u8BFB\u6A21\u5F0F").option("--safe", "\u5E94\u7528\u5B89\u5168\u6A21\u5F0F").option("--ci", "\u5E94\u7528 CI/CD \u6A21\u5F0F").option("--audit", "\u5E94\u7528\u5BA1\u8BA1\u6A21\u5F0F").option("--reset", "\u91CD\u7F6E\u6743\u9650\u914D\u7F6E").action(function() {
@@ -6113,12 +6698,12 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
6113
6698
  const newConfigPath = getCcemConfigPath();
6114
6699
  const legacyConfigPath = getLegacyConfigPath();
6115
6700
  console.log(chalk9.cyan("\n\u{1F504} \u914D\u7F6E\u8FC1\u79FB\n"));
6116
- if (!fs14.existsSync(legacyConfigPath)) {
6701
+ if (!fs16.existsSync(legacyConfigPath)) {
6117
6702
  console.log(chalk9.yellow("\u672A\u627E\u5230\u65E7\u7248\u914D\u7F6E\u6587\u4EF6"));
6118
6703
  console.log(chalk9.gray(` \u65E7\u8DEF\u5F84: ${legacyConfigPath}`));
6119
6704
  return;
6120
6705
  }
6121
- if (fs14.existsSync(newConfigPath) && !options.force) {
6706
+ if (fs16.existsSync(newConfigPath) && !options.force) {
6122
6707
  console.log(chalk9.green("\u2713 \u914D\u7F6E\u5DF2\u5728\u65B0\u8DEF\u5F84"));
6123
6708
  console.log(chalk9.gray(` \u8DEF\u5F84: ${newConfigPath}`));
6124
6709
  console.log(chalk9.gray("\n\u4F7F\u7528 --force \u5F3A\u5236\u91CD\u65B0\u8FC1\u79FB"));
@@ -6126,7 +6711,7 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
6126
6711
  }
6127
6712
  try {
6128
6713
  ensureCcemDir();
6129
- const legacyRaw = JSON.parse(fs14.readFileSync(legacyConfigPath, "utf-8"));
6714
+ const legacyRaw = JSON.parse(fs16.readFileSync(legacyConfigPath, "utf-8"));
6130
6715
  const migrated = normalizeCcemConfig(legacyRaw);
6131
6716
  if (!migrated.registries[OFFICIAL_ENV_NAME]) {
6132
6717
  migrated.registries[OFFICIAL_ENV_NAME] = { ...DEFAULT_OFFICIAL_ENV };
@@ -6137,10 +6722,10 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
6137
6722
  console.log(chalk9.gray(` \u4ECE: ${legacyConfigPath}`));
6138
6723
  console.log(chalk9.gray(` \u5230: ${newConfigPath}`));
6139
6724
  if (options.clean) {
6140
- fs14.unlinkSync(legacyConfigPath);
6141
- const legacyDir = path12.dirname(legacyConfigPath);
6725
+ fs16.unlinkSync(legacyConfigPath);
6726
+ const legacyDir = path14.dirname(legacyConfigPath);
6142
6727
  try {
6143
- fs14.rmdirSync(legacyDir);
6728
+ fs16.rmdirSync(legacyDir);
6144
6729
  } catch {
6145
6730
  }
6146
6731
  console.log(chalk9.green("\u2713 \u5DF2\u5220\u9664\u65E7\u914D\u7F6E\u6587\u4EF6"));
@@ -6149,15 +6734,15 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
6149
6734
  console.error(chalk9.red(`\u2717 \u8FC1\u79FB\u5931\u8D25: ${err}`));
6150
6735
  }
6151
6736
  });
6152
- setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 Claude Code\uFF08~/.claude/skills/\uFF09").option("--force", "\u5F3A\u5236\u8986\u76D6\u5DF2\u6709\u6587\u4EF6").action(async function() {
6737
+ setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 CCEM \u7684 Claude Code").option("--force", "\u5F3A\u5236\u8986\u76D6\u5DF2\u6709\u6587\u4EF6").action(async function() {
6153
6738
  const options = this.opts();
6154
- const skillDir = path12.join(getHomeDir(), ".claude", "skills");
6155
- const targetPath = path12.join(skillDir, "ccem-cron.md");
6156
- if (!fs14.existsSync(skillDir)) {
6157
- fs14.mkdirSync(skillDir, { recursive: true });
6739
+ const skillDir = path14.join(ensureCcemAgentHome("claude"), "skills");
6740
+ const targetPath = path14.join(skillDir, "ccem-cron.md");
6741
+ if (!fs16.existsSync(skillDir)) {
6742
+ fs16.mkdirSync(skillDir, { recursive: true });
6158
6743
  console.log(chalk9.gray(`\u521B\u5EFA\u76EE\u5F55: ${skillDir}`));
6159
6744
  }
6160
- if (fs14.existsSync(targetPath) && !options.force) {
6745
+ if (fs16.existsSync(targetPath) && !options.force) {
6161
6746
  const { overwrite } = await inquirer.prompt([
6162
6747
  {
6163
6748
  type: "confirm",
@@ -6171,21 +6756,21 @@ setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 Claude
6171
6756
  return;
6172
6757
  }
6173
6758
  }
6174
- fs14.writeFileSync(targetPath, CCEM_CRON_SKILL_CONTENT, "utf-8");
6759
+ fs16.writeFileSync(targetPath, CCEM_CRON_SKILL_CONTENT, "utf-8");
6175
6760
  console.log(chalk9.green(`\u2713 \u5DF2\u5B89\u88C5 ccem-cron skill`));
6176
6761
  console.log(chalk9.gray(` \u8DEF\u5F84: ${targetPath}`));
6177
6762
  console.log(chalk9.cyan(`
6178
6763
  \u5728 Claude Code \u4E2D\u4F7F\u7528 /ccem-cron \u5373\u53EF\u8C03\u7528\u6B64 skill`));
6179
6764
  });
6180
- setupCmd.command("bot-bind").description("\u5B89\u88C5 ccem-bot-bind skill \u5230 Claude Code\uFF08~/.claude/skills/\uFF09").option("--force", "\u5F3A\u5236\u8986\u76D6\u5DF2\u6709\u6587\u4EF6").action(async function() {
6765
+ setupCmd.command("bot-bind").description("\u5B89\u88C5 ccem-bot-bind skill \u5230 CCEM \u7684 Claude Code").option("--force", "\u5F3A\u5236\u8986\u76D6\u5DF2\u6709\u6587\u4EF6").action(async function() {
6181
6766
  const options = this.opts();
6182
- const skillDir = path12.join(getHomeDir(), ".claude", "skills");
6183
- const targetPath = path12.join(skillDir, "ccem-bot-bind.md");
6184
- if (!fs14.existsSync(skillDir)) {
6185
- fs14.mkdirSync(skillDir, { recursive: true });
6767
+ const skillDir = path14.join(ensureCcemAgentHome("claude"), "skills");
6768
+ const targetPath = path14.join(skillDir, "ccem-bot-bind.md");
6769
+ if (!fs16.existsSync(skillDir)) {
6770
+ fs16.mkdirSync(skillDir, { recursive: true });
6186
6771
  console.log(chalk9.gray(`\u521B\u5EFA\u76EE\u5F55: ${skillDir}`));
6187
6772
  }
6188
- if (fs14.existsSync(targetPath) && !options.force) {
6773
+ if (fs16.existsSync(targetPath) && !options.force) {
6189
6774
  const { overwrite } = await inquirer.prompt([
6190
6775
  {
6191
6776
  type: "confirm",
@@ -6199,7 +6784,7 @@ setupCmd.command("bot-bind").description("\u5B89\u88C5 ccem-bot-bind skill \u523
6199
6784
  return;
6200
6785
  }
6201
6786
  }
6202
- fs14.writeFileSync(targetPath, CCEM_BOT_BIND_SKILL_CONTENT, "utf-8");
6787
+ fs16.writeFileSync(targetPath, CCEM_BOT_BIND_SKILL_CONTENT, "utf-8");
6203
6788
  console.log(chalk9.green(`\u2713 \u5DF2\u5B89\u88C5 ccem-bot-bind skill`));
6204
6789
  console.log(chalk9.gray(` \u8DEF\u5F84: ${targetPath}`));
6205
6790
  console.log(chalk9.cyan(`
@@ -6376,7 +6961,7 @@ desktopCmd.command("send <runtimeId>").description("Send input to a CCEM Desktop
6376
6961
  const opts = this.opts();
6377
6962
  const result = await requestDesktopControl("ccem.workspace.sendInput", {
6378
6963
  runtimeId,
6379
- clientMessageId: opts.messageId?.trim() || `ccem-cli-${randomUUID()}`,
6964
+ clientMessageId: opts.messageId?.trim() || `ccem-cli-${randomUUID2()}`,
6380
6965
  text: opts.text,
6381
6966
  displayText: opts.displayText ?? null
6382
6967
  });