ccem 2.94.0 → 2.96.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 +1553 -277
  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 fs6 from "fs";
9
+ import path6 from "path";
10
10
 
11
11
  // ../../packages/core/dist/chunk-4WH3CEOL.js
12
12
  var DEFAULT_ROUTER_PORT = 17820;
@@ -234,10 +234,10 @@ function renameRouterEnvironmentReferences(router, oldName, newName) {
234
234
  profiles: normalized.profiles.map((profile) => {
235
235
  const bindings = renameBindings(profile.bindings);
236
236
  const allowedEnvs = replaceEnvironmentNames(profile.allowedEnvs, oldName, newName);
237
- const changed = Object.entries(profile.bindings).some(([, target]) => target === oldName && target !== newName) || profile.allowedEnvs.some((target) => target === oldName && target !== newName);
237
+ const changed2 = Object.entries(profile.bindings).some(([, target]) => target === oldName && target !== newName) || profile.allowedEnvs.some((target) => target === oldName && target !== newName);
238
238
  return {
239
239
  ...profile,
240
- revision: changed ? bumpProfileRevision(profile.revision) : profile.revision,
240
+ revision: changed2 ? bumpProfileRevision(profile.revision) : profile.revision,
241
241
  bindings,
242
242
  allowedEnvs
243
243
  };
@@ -700,10 +700,1286 @@ var getPermissionModeNames = () => {
700
700
 
701
701
  // ../../packages/core/dist/index.js
702
702
  import crypto2 from "crypto";
703
- import fs from "fs";
703
+ import fs5 from "fs";
704
+ import os2 from "os";
705
+ import path5 from "path";
706
+ import fs4 from "fs";
704
707
  import os from "os";
708
+ import path4 from "path";
709
+ import { randomUUID as randomUUID3 } from "crypto";
710
+ import fs from "fs";
705
711
  import path from "path";
712
+ import { execFileSync } from "child_process";
713
+ import fs2 from "fs";
714
+ import path2 from "path";
715
+ import { randomUUID } from "crypto";
716
+ import fs3 from "fs";
717
+ import path3 from "path";
718
+ import { createHash, randomUUID as randomUUID2 } from "crypto";
706
719
  import crypto from "crypto";
720
+ function processAlive(pid) {
721
+ try {
722
+ process.kill(pid, 0);
723
+ return true;
724
+ } catch (error) {
725
+ return error.code !== "ESRCH";
726
+ }
727
+ }
728
+ function samePath(left, right) {
729
+ const normalize = (value) => {
730
+ try {
731
+ value = fs.realpathSync(value);
732
+ } catch {
733
+ value = path.resolve(value);
734
+ }
735
+ return process.platform === "win32" ? value.toLowerCase() : value;
736
+ };
737
+ return normalize(left) === normalize(right);
738
+ }
739
+ function providerCommand(provider, executable, command) {
740
+ const name = path.basename(executable).toLowerCase().replace(/\.exe$/, "");
741
+ if (name === provider) return true;
742
+ if (!["node", "bun", "ccem-node"].includes(name) && !name.startsWith("ccem-node-")) return false;
743
+ if (/(?:^|[\\/\s])native-runtime-helper\.mjs(?:[\s"']|$)/.test(command)) return true;
744
+ return provider === "claude" ? /@anthropic-ai[\\/]claude-code[\\/]cli\.js(?:[\s"']|$)/.test(command) : /@openai[\\/]codex[\\/]bin[\\/]codex\.js(?:[\s"']|$)/.test(command);
745
+ }
746
+ function candidateExecutable(executable) {
747
+ const name = path.basename(executable).toLowerCase().replace(/\.exe$/, "");
748
+ return ["claude", "codex", "node", "bun", "ccem-node"].includes(name) || name.startsWith("ccem-node-");
749
+ }
750
+ function ps(args) {
751
+ return execFileSync("ps", args, {
752
+ encoding: "utf8",
753
+ stdio: ["ignore", "pipe", "ignore"],
754
+ timeout: 5e3,
755
+ maxBuffer: 16 * 1024 * 1024
756
+ }).trimEnd();
757
+ }
758
+ function parseEnvironment(value) {
759
+ const result = {};
760
+ const boundaries = [...value.matchAll(/(?:^|\s)([A-Za-z_][A-Za-z0-9_]*)=/g)];
761
+ for (let i = 0; i < boundaries.length; i += 1) {
762
+ const entry = boundaries[i];
763
+ if (!["HOME", "USERPROFILE", "CCEM_RUNTIME_ID", "CCEM_SESSION_ID", "CLAUDE_CONFIG_DIR", "CODEX_HOME"].includes(entry[1])) continue;
764
+ const start = entry.index + entry[0].length;
765
+ const end = i + 1 < boundaries.length ? boundaries[i + 1].index : value.length;
766
+ result[entry[1]] = value.slice(start, end).trim();
767
+ }
768
+ return result;
769
+ }
770
+ function migrationBlocked(provider, pid, unknownHome = false) {
771
+ 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.`;
772
+ throw new Error(`${reason} Finish that session and retry to preserve its latest messages before isolation.`);
773
+ }
774
+ function persistedProcesses(home) {
775
+ const result = [];
776
+ for (const name of ["sessions.json", "runtime-state.json"]) {
777
+ const file = path.join(home, ".ccem", name);
778
+ let value;
779
+ try {
780
+ const stat22 = fs.lstatSync(file);
781
+ if (!stat22.isFile() || stat22.isSymbolicLink()) continue;
782
+ value = JSON.parse(fs.readFileSync(file, "utf8"));
783
+ } catch (error) {
784
+ if (error.code === "ENOENT") continue;
785
+ throw new Error("Cannot inspect saved CCEM sessions before migration; retry when their state is available");
786
+ }
787
+ const rows = Array.isArray(value) ? value : value?.sessions;
788
+ for (const raw of Array.isArray(rows) ? rows : []) {
789
+ if (!raw || typeof raw !== "object") continue;
790
+ const row = raw;
791
+ if (!Number.isSafeInteger(row.pid) || row.pid <= 0 || row.pid === process.pid) continue;
792
+ if (typeof row.status === "string" && row.status !== "running") continue;
793
+ if (row.summary) continue;
794
+ result.push({
795
+ pid: row.pid,
796
+ client: typeof row.client === "string" ? row.client : void 0,
797
+ jsonlPath: typeof row.jsonl_path === "string" ? row.jsonl_path : void 0
798
+ });
799
+ }
800
+ }
801
+ return result;
802
+ }
803
+ function persistedPathIsLegacy(record, provider, source) {
804
+ if (record.client && record.client !== provider) return false;
805
+ if (!record.jsonlPath) return true;
806
+ const roots = provider === "claude" ? ["projects"] : ["sessions", "archived_sessions"];
807
+ const candidate = path.resolve(record.jsonlPath);
808
+ return roots.some((name) => {
809
+ const directory = path.resolve(source, name);
810
+ const relative2 = path.relative(directory, candidate);
811
+ return relative2 !== "" && relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2);
812
+ });
813
+ }
814
+ function assertWindowsProcesses(provider, home, source) {
815
+ for (const record of persistedProcesses(home)) {
816
+ if (!persistedPathIsLegacy(record, provider, source) || !processAlive(record.pid)) continue;
817
+ let command;
818
+ try {
819
+ const output = execFileSync(
820
+ "powershell.exe",
821
+ [
822
+ "-NoProfile",
823
+ "-NonInteractive",
824
+ "-Command",
825
+ `Get-CimInstance Win32_Process -Filter 'ProcessId = ${record.pid}' | Select-Object Name,CommandLine | ConvertTo-Json -Compress`
826
+ ],
827
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }
828
+ );
829
+ command = JSON.parse(output);
830
+ } catch {
831
+ if (processAlive(record.pid)) migrationBlocked(provider, record.pid, true);
832
+ continue;
833
+ }
834
+ if (!command || !providerCommand(provider, command.Name || "", command.CommandLine || "")) continue;
835
+ migrationBlocked(provider, record.pid, !record.jsonlPath);
836
+ }
837
+ }
838
+ function assertNoLegacyAgentWriters(provider, home, source, destination) {
839
+ if (process.platform === "win32") {
840
+ assertWindowsProcesses(provider, home, source);
841
+ return;
842
+ }
843
+ let listing;
844
+ try {
845
+ listing = ps(["-ax", "-o", "pid=,comm="]);
846
+ } catch {
847
+ throw new Error("Cannot inspect running CCEM sessions before migration; finish legacy sessions and retry");
848
+ }
849
+ const candidates = /* @__PURE__ */ new Map();
850
+ for (const row of listing.split("\n")) {
851
+ const match = row.match(/^\s*(\d+)\s+(.+)$/);
852
+ if (!match) continue;
853
+ const pid = Number(match[1]);
854
+ const executable = match[2];
855
+ if (pid === process.pid || !candidateExecutable(executable)) continue;
856
+ candidates.set(pid, executable);
857
+ }
858
+ if (candidates.size === 0) return;
859
+ const commands = /* @__PURE__ */ new Map();
860
+ try {
861
+ const rows = ps(["ww", "-p", [...candidates.keys()].join(","), "-o", "pid=,command="]);
862
+ for (const row of rows.split("\n")) {
863
+ const match = row.match(/^\s*(\d+)\s+(.+)$/);
864
+ if (match) commands.set(Number(match[1]), match[2]);
865
+ }
866
+ } catch {
867
+ }
868
+ for (const [pid, executable] of candidates) {
869
+ const command = commands.get(pid);
870
+ if (!command) {
871
+ if (processAlive(pid) && persistedProcesses(home).some((record) => record.pid === pid && persistedPathIsLegacy(record, provider, source))) {
872
+ migrationBlocked(provider, pid, true);
873
+ }
874
+ continue;
875
+ }
876
+ if (!providerCommand(provider, executable, command)) continue;
877
+ let withEnvironment;
878
+ try {
879
+ withEnvironment = ps(["eww", "-p", String(pid), "-o", "command="]);
880
+ } catch {
881
+ if (processAlive(pid) && persistedProcesses(home).some((record) => record.pid === pid && persistedPathIsLegacy(record, provider, source))) {
882
+ migrationBlocked(provider, pid, true);
883
+ }
884
+ continue;
885
+ }
886
+ const env = withEnvironment.startsWith(command) ? parseEnvironment(withEnvironment.slice(command.length).trimStart()) : {};
887
+ if (Object.keys(env).length === 0 && processAlive(pid) && persistedProcesses(home).some((record) => record.pid === pid && persistedPathIsLegacy(record, provider, source))) {
888
+ migrationBlocked(provider, pid, true);
889
+ }
890
+ if (!env.CCEM_RUNTIME_ID?.trim() && !env.CCEM_SESSION_ID?.trim()) continue;
891
+ const sourceHome = env.HOME || env.USERPROFILE || home;
892
+ let effectiveHome = provider === "claude" ? env.CLAUDE_CONFIG_DIR || path.join(sourceHome, ".claude") : env.CODEX_HOME || path.join(sourceHome, ".codex");
893
+ if (/^~[\\/]/.test(effectiveHome)) effectiveHome = path.join(sourceHome, effectiveHome.slice(2));
894
+ if (samePath(effectiveHome, source) && !samePath(effectiveHome, destination) && processAlive(pid)) {
895
+ migrationBlocked(provider, pid);
896
+ }
897
+ }
898
+ }
899
+ var CLAUDE_PLUGIN_IMPORT_LEDGER = ".ccem-plugins-import-v1.json";
900
+ function object(value, label) {
901
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid ${label}`);
902
+ return value;
903
+ }
904
+ function stat(file) {
905
+ try {
906
+ return fs2.lstatSync(file);
907
+ } catch (error) {
908
+ if (error.code === "ENOENT") return void 0;
909
+ throw error;
910
+ }
911
+ }
912
+ function noLinks(file) {
913
+ let current = path2.parse(file).root;
914
+ for (const part of file.slice(current.length).split(path2.sep).filter(Boolean)) {
915
+ current = path2.join(current, part);
916
+ if (stat(current)?.isSymbolicLink()) throw new Error(`Plugin import cannot use a destination symlink: ${current}`);
917
+ }
918
+ }
919
+ function readDocument(file, fallback = {}) {
920
+ noLinks(file);
921
+ const info = stat(file);
922
+ if (!info) return { file, value: structuredClone(fallback) };
923
+ if (!info.isFile()) throw new Error(`Plugin metadata is not a file: ${file}`);
924
+ const before = fs2.readFileSync(file, "utf8");
925
+ return { file, before, value: object(JSON.parse(before), `plugin metadata: ${file}`) };
926
+ }
927
+ function pluginId(id) {
928
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*@[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(id)) {
929
+ throw new Error("Invalid plugin identity");
930
+ }
931
+ }
932
+ function identity(value) {
933
+ const row = object(value, "plugin install");
934
+ if (typeof row.scope !== "string" || !["user", "project", "local"].includes(row.scope)) throw new Error("Invalid plugin scope");
935
+ const projectPath = row.projectPath ?? null;
936
+ if (row.scope === "user" ? projectPath !== null : typeof projectPath !== "string" || !path2.isAbsolute(projectPath) || projectPath.split(/[\\/]/).includes("..")) {
937
+ throw new Error("Invalid plugin project scope");
938
+ }
939
+ return { scope: row.scope, projectPath };
940
+ }
941
+ function same(a, b) {
942
+ return a.scope === b.scope && a.projectPath === b.projectPath;
943
+ }
944
+ function registry(document) {
945
+ if (document.value.version !== 2) throw new Error("Unsupported Claude plugin registry version");
946
+ const plugins = object(document.value.plugins, "Claude plugin registry");
947
+ for (const [id, rows] of Object.entries(plugins)) {
948
+ pluginId(id);
949
+ if (!Array.isArray(rows)) throw new Error("Invalid plugin installations");
950
+ const seen = [];
951
+ for (const row of rows) {
952
+ const key = identity(row);
953
+ if (seen.some((old) => same(old, key))) throw new Error("Duplicate plugin installation identity");
954
+ seen.push(key);
955
+ }
956
+ }
957
+ return plugins;
958
+ }
959
+ function readLedger(target) {
960
+ const document = readDocument(path2.join(target, CLAUDE_PLUGIN_IMPORT_LEDGER), { version: 1, seen: {} });
961
+ if (document.value.version !== 1 || Object.keys(document.value).some((key) => !["version", "seen"].includes(key))) {
962
+ throw new Error("Unsupported Claude plugin import ledger");
963
+ }
964
+ for (const [id, rows] of Object.entries(object(document.value.seen, "plugin import ledger"))) {
965
+ pluginId(id);
966
+ if (!Array.isArray(rows) || rows.length === 0) throw new Error("Invalid plugin import ledger");
967
+ const parsed = [];
968
+ for (const row of rows) {
969
+ if (!Object.hasOwn(object(row, "plugin import identity"), "projectPath") || Object.keys(row).some((key) => !["scope", "projectPath"].includes(key))) {
970
+ throw new Error("Invalid plugin import identity");
971
+ }
972
+ const item = identity(row);
973
+ if (parsed.some((old) => same(old, item))) throw new Error("Duplicate plugin import identity");
974
+ parsed.push(item);
975
+ }
976
+ }
977
+ return document;
978
+ }
979
+ function readSource(source) {
980
+ return readDocument(path2.join(source, "plugins", "installed_plugins.json"), { version: 2, plugins: {} });
981
+ }
982
+ function claudePluginImportPending(source, target) {
983
+ const installed = registry(readSource(source));
984
+ const ledger = readLedger(target).value;
985
+ return Object.entries(installed).some(([id, rows]) => rows.length > 0 && !Object.hasOwn(ledger.seen, id));
986
+ }
987
+ function contained(root, file) {
988
+ const relative2 = path2.relative(root, file);
989
+ return relative2 !== "" && !relative2.startsWith(`..${path2.sep}`) && relative2 !== ".." && !path2.isAbsolute(relative2);
990
+ }
991
+ function rejectPrivateData(root, file) {
992
+ if (path2.relative(root, file).split(path2.sep)[0] === "data") {
993
+ throw new Error("Plugin import cannot copy private plugin data");
994
+ }
995
+ }
996
+ function relocated(value, source, target) {
997
+ if (typeof value !== "string" || !path2.isAbsolute(value)) throw new Error("Plugin installation path must be absolute");
998
+ const resolved = path2.resolve(value);
999
+ if (!contained(source, resolved)) throw new Error("Plugin path escapes the official plugin store");
1000
+ rejectPrivateData(source, resolved);
1001
+ return { source: resolved, target: path2.join(target, path2.relative(source, resolved)) };
1002
+ }
1003
+ function planCopy(source, target, sourceRoot, copies, excluded = /* @__PURE__ */ new Set(), ancestors = /* @__PURE__ */ new Set()) {
1004
+ if (excluded.has(target)) return;
1005
+ const resolved = fs2.realpathSync(source);
1006
+ if (resolved !== sourceRoot && !contained(sourceRoot, resolved)) throw new Error("Plugin symlink escapes the official plugin store");
1007
+ rejectPrivateData(sourceRoot, resolved);
1008
+ if (ancestors.has(resolved)) throw new Error("Plugin symlink cycle");
1009
+ noLinks(target);
1010
+ const info = fs2.statSync(resolved);
1011
+ const existing = stat(target);
1012
+ if (info.isDirectory()) {
1013
+ if (existing && !existing.isDirectory()) throw new Error("Plugin destination directory conflicts with a file");
1014
+ copies.push({ source: resolved, target, directory: true, mode: 448 });
1015
+ const next = new Set(ancestors).add(resolved);
1016
+ for (const name of fs2.readdirSync(resolved).sort()) planCopy(path2.join(resolved, name), path2.join(target, name), sourceRoot, copies, excluded, next);
1017
+ } else if (info.isFile()) {
1018
+ if (existing) {
1019
+ if (!existing.isFile() || !fs2.readFileSync(target).equals(fs2.readFileSync(resolved))) {
1020
+ throw new Error("Existing CCEM plugin files differ; keeping the CCEM copy");
1021
+ }
1022
+ return;
1023
+ }
1024
+ copies.push({ source: resolved, target, directory: false, mode: 384 | info.mode & 73 });
1025
+ } else {
1026
+ throw new Error("Plugin asset is not a regular file or directory");
1027
+ }
1028
+ }
1029
+ function privateDirectory(directory) {
1030
+ noLinks(directory);
1031
+ fs2.mkdirSync(directory, { recursive: true, mode: 448 });
1032
+ }
1033
+ function publishCopy(copy) {
1034
+ noLinks(copy.target);
1035
+ if (copy.directory) {
1036
+ privateDirectory(copy.target);
1037
+ return;
1038
+ }
1039
+ privateDirectory(path2.dirname(copy.target));
1040
+ const temporary = `${copy.target}.ccem-${randomUUID()}.tmp`;
1041
+ let input;
1042
+ let output;
1043
+ try {
1044
+ input = fs2.openSync(copy.source, fs2.constants.O_RDONLY | (fs2.constants.O_NOFOLLOW ?? 0));
1045
+ const before = fs2.fstatSync(input);
1046
+ if (!before.isFile()) throw new Error("Plugin source changed during import");
1047
+ output = fs2.openSync(temporary, "wx", copy.mode);
1048
+ const buffer = Buffer.alloc(1024 * 1024);
1049
+ let remaining = before.size;
1050
+ while (remaining > 0) {
1051
+ const count = fs2.readSync(input, buffer, 0, Math.min(buffer.length, remaining), null);
1052
+ if (!count) throw new Error("Plugin source changed during import");
1053
+ let offset = 0;
1054
+ while (offset < count) offset += fs2.writeSync(output, buffer, offset, count - offset);
1055
+ remaining -= count;
1056
+ }
1057
+ const after = fs2.fstatSync(input);
1058
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) throw new Error("Plugin source changed during import");
1059
+ fs2.fsyncSync(output);
1060
+ fs2.closeSync(output);
1061
+ output = void 0;
1062
+ noLinks(copy.target);
1063
+ try {
1064
+ fs2.linkSync(temporary, copy.target);
1065
+ } catch (error) {
1066
+ if (error.code !== "EEXIST" || !stat(copy.target)?.isFile() || !fs2.readFileSync(copy.target).equals(fs2.readFileSync(temporary))) throw error;
1067
+ }
1068
+ } finally {
1069
+ if (input !== void 0) fs2.closeSync(input);
1070
+ if (output !== void 0) fs2.closeSync(output);
1071
+ fs2.rmSync(temporary, { force: true });
1072
+ }
1073
+ }
1074
+ function unchanged(document) {
1075
+ noLinks(document.file);
1076
+ const current = stat(document.file) ? fs2.readFileSync(document.file, "utf8") : void 0;
1077
+ if (current !== document.before) throw new Error("Plugin metadata changed during import; retry later");
1078
+ }
1079
+ function publishDocument(document, target, backupDirectory = ".ccem-plugins-backup-v1") {
1080
+ const contents = `${JSON.stringify(document.value, null, 2)}
1081
+ `;
1082
+ if (document.before !== void 0 && JSON.stringify(JSON.parse(document.before)) === JSON.stringify(document.value)) return;
1083
+ unchanged(document);
1084
+ privateDirectory(path2.dirname(document.file));
1085
+ if (document.before !== void 0) {
1086
+ const backup = path2.join(target, backupDirectory, path2.relative(target, document.file));
1087
+ privateDirectory(path2.dirname(backup));
1088
+ noLinks(backup);
1089
+ const existing = stat(backup);
1090
+ if (existing && !existing.isFile()) throw new Error("Plugin metadata backup is not a file");
1091
+ if (!existing) fs2.writeFileSync(backup, document.before, { flag: "wx", mode: 384 });
1092
+ }
1093
+ const temporary = `${document.file}.ccem-${randomUUID()}.tmp`;
1094
+ try {
1095
+ const fd = fs2.openSync(temporary, "wx", 384);
1096
+ try {
1097
+ fs2.writeFileSync(fd, contents);
1098
+ fs2.fsyncSync(fd);
1099
+ } finally {
1100
+ fs2.closeSync(fd);
1101
+ }
1102
+ unchanged(document);
1103
+ fs2.renameSync(temporary, document.file);
1104
+ document.before = contents;
1105
+ } finally {
1106
+ fs2.rmSync(temporary, { force: true });
1107
+ }
1108
+ }
1109
+ function importClaudePlugins(sourceHome, targetHome) {
1110
+ const sourceRegistry = readSource(sourceHome);
1111
+ const sourcePlugins = registry(sourceRegistry);
1112
+ const ledger = readLedger(targetHome);
1113
+ const pending = Object.entries(sourcePlugins).flatMap(([id, installs]) => installs.filter(() => !Object.hasOwn(ledger.value.seen, id)).map((install) => ({ id, install, identity: identity(install) })));
1114
+ if (!pending.length) return { imported: 0, observed: 0 };
1115
+ noLinks(path2.join(sourceHome, "plugins"));
1116
+ const sourceRoot = fs2.realpathSync(path2.join(sourceHome, "plugins"));
1117
+ const targetRoot = path2.join(targetHome, "plugins");
1118
+ if (sourceRoot === path2.resolve(targetRoot) || contained(sourceRoot, path2.resolve(targetRoot)) || contained(path2.resolve(targetRoot), sourceRoot)) throw new Error("Plugin stores must not overlap");
1119
+ noLinks(targetRoot);
1120
+ const sourceSettings = readDocument(path2.join(sourceHome, "settings.json"));
1121
+ const sourceMarkets = readDocument(path2.join(sourceRoot, "known_marketplaces.json"));
1122
+ const targetRegistry = readDocument(path2.join(targetRoot, "installed_plugins.json"), { version: 2, plugins: {} });
1123
+ const targetPlugins = registry(targetRegistry);
1124
+ const targetSettings = readDocument(path2.join(targetHome, "settings.json"));
1125
+ const targetMarkets = readDocument(path2.join(targetRoot, "known_marketplaces.json"));
1126
+ const existingMarketplaces = new Set(Object.keys(targetMarkets.value));
1127
+ const sourceCatalogues = /* @__PURE__ */ new Map();
1128
+ const targetCatalogues = /* @__PURE__ */ new Map();
1129
+ const catalogueFiles = /* @__PURE__ */ new Set();
1130
+ const copies = [];
1131
+ function sourceCatalogue(location) {
1132
+ const file = fs2.realpathSync(path2.join(location, ".claude-plugin/marketplace.json"));
1133
+ if (!contained(sourceRoot, file)) throw new Error("Marketplace manifest escapes the official plugin store");
1134
+ rejectPrivateData(sourceRoot, file);
1135
+ const document = sourceCatalogues.get(file) ?? readDocument(file);
1136
+ if (!Array.isArray(document.value.plugins)) throw new Error("Invalid plugin marketplace catalogue");
1137
+ sourceCatalogues.set(file, document);
1138
+ return document;
1139
+ }
1140
+ function localCatalogueEntry(entry, from, to) {
1141
+ const local = typeof entry.source === "string" ? entry.source : entry.source && typeof entry.source === "object" && ["directory", "file"].includes(String(entry.source.source)) ? entry.source.path : void 0;
1142
+ if (local === void 0) return;
1143
+ if (typeof local !== "string") throw new Error("Invalid local marketplace plugin source");
1144
+ const original = path2.resolve(from, local);
1145
+ const destination = path2.isAbsolute(local) ? relocated(local, sourceRoot, targetRoot).target : path2.resolve(to, local);
1146
+ if (!contained(sourceRoot, original) || !contained(targetRoot, destination)) throw new Error("Local marketplace source escapes its plugin store");
1147
+ rejectPrivateData(targetRoot, destination);
1148
+ planCopy(original, destination, sourceRoot, copies, catalogueFiles);
1149
+ if (path2.isAbsolute(local)) {
1150
+ if (typeof entry.source === "string") entry.source = destination;
1151
+ else entry.source.path = destination;
1152
+ }
1153
+ }
1154
+ let imported = 0;
1155
+ const visitedIds = /* @__PURE__ */ new Set();
1156
+ for (const { id, install, identity: key } of pending) {
1157
+ if (!targetPlugins[id]?.some((existing) => same(identity(existing), key))) {
1158
+ const location = relocated(install.installPath, sourceRoot, targetRoot);
1159
+ planCopy(location.source, location.target, sourceRoot, copies);
1160
+ (targetPlugins[id] ??= []).push({ ...install, installPath: location.target });
1161
+ imported += 1;
1162
+ }
1163
+ if (!visitedIds.has(id)) {
1164
+ visitedIds.add(id);
1165
+ const marketplace = id.split("@")[1];
1166
+ if (!Object.hasOwn(sourceMarkets.value, marketplace) && !Object.hasOwn(targetMarkets.value, marketplace)) {
1167
+ throw new Error(`Plugin is missing its marketplace registration: ${id}`);
1168
+ }
1169
+ if (Object.hasOwn(sourceMarkets.value, marketplace) && !Object.hasOwn(targetMarkets.value, marketplace)) {
1170
+ const entry = structuredClone(object(sourceMarkets.value[marketplace], "marketplace"));
1171
+ const location = relocated(entry.installLocation, sourceRoot, targetRoot);
1172
+ const catalogue = sourceCatalogue(location.source);
1173
+ const file = path2.join(location.target, ".claude-plugin/marketplace.json");
1174
+ const destination = readDocument(file);
1175
+ const existingCatalogue = destination.value;
1176
+ destination.value = structuredClone(catalogue.value);
1177
+ targetCatalogues.set(file, destination);
1178
+ catalogueFiles.add(file);
1179
+ for (const item of destination.value.plugins) {
1180
+ const plugin = object(item, "catalogue plugin");
1181
+ localCatalogueEntry(plugin, location.source, location.target);
1182
+ }
1183
+ if (destination.before !== void 0 && JSON.stringify(existingCatalogue) !== JSON.stringify(destination.value)) {
1184
+ throw new Error("Existing CCEM marketplace catalogue differs; keeping the CCEM copy");
1185
+ }
1186
+ for (const newId of pending.filter((item) => item.id.split("@")[1] === marketplace).map((item) => item.id)) {
1187
+ if (!destination.value.plugins.some((item) => item.name === newId.split("@")[0])) {
1188
+ throw new Error(`Plugin is missing from its marketplace catalogue: ${newId}`);
1189
+ }
1190
+ }
1191
+ planCopy(location.source, location.target, sourceRoot, copies, catalogueFiles);
1192
+ entry.installLocation = location.target;
1193
+ if (entry.source && typeof entry.source === "object" && ["directory", "file"].includes(String(entry.source.source)) && "path" in entry.source) {
1194
+ const local = relocated(entry.source.path, sourceRoot, targetRoot);
1195
+ planCopy(local.source, local.target, sourceRoot, copies, catalogueFiles);
1196
+ entry.source.path = local.target;
1197
+ }
1198
+ targetMarkets.value[marketplace] = entry;
1199
+ }
1200
+ if (existingMarketplaces.has(marketplace) && Object.hasOwn(sourceMarkets.value, marketplace)) {
1201
+ const from = relocated(object(sourceMarkets.value[marketplace], "marketplace").installLocation, sourceRoot, targetRoot);
1202
+ const to = relocated(object(targetMarkets.value[marketplace], "marketplace").installLocation, targetRoot, targetRoot);
1203
+ const targetFile = path2.join(to.target, ".claude-plugin/marketplace.json");
1204
+ const officialCatalogue = sourceCatalogue(from.source);
1205
+ const targetCatalogue = targetCatalogues.get(targetFile) ?? readDocument(targetFile);
1206
+ targetCatalogues.set(targetFile, targetCatalogue);
1207
+ catalogueFiles.add(targetFile);
1208
+ if (!Array.isArray(officialCatalogue.value.plugins) || !Array.isArray(targetCatalogue.value.plugins)) {
1209
+ throw new Error("Invalid plugin marketplace catalogue");
1210
+ }
1211
+ const name = id.split("@")[0];
1212
+ if (!targetCatalogue.value.plugins.some((entry) => object(entry, "catalogue plugin").name === name)) {
1213
+ const entry = officialCatalogue.value.plugins.find((entry2) => object(entry2, "catalogue plugin").name === name);
1214
+ if (!entry) throw new Error(`Plugin is missing from its marketplace catalogue: ${id}`);
1215
+ const importedEntry = structuredClone(object(entry, "catalogue plugin"));
1216
+ localCatalogueEntry(importedEntry, from.source, to.target);
1217
+ targetCatalogue.value.plugins.push(importedEntry);
1218
+ }
1219
+ }
1220
+ for (const [field, entryKey] of [["enabledPlugins", id], ["extraKnownMarketplaces", marketplace]]) {
1221
+ if (field === "enabledPlugins" && !pending.some((item) => item.id === id && item.identity.scope === "user")) continue;
1222
+ const from = sourceSettings.value[field] === void 0 ? {} : object(sourceSettings.value[field], field);
1223
+ const to = targetSettings.value[field] === void 0 ? {} : object(targetSettings.value[field], field);
1224
+ if (Object.hasOwn(from, entryKey) && !Object.hasOwn(to, entryKey)) {
1225
+ const value = structuredClone(from[entryKey]);
1226
+ if (field === "enabledPlugins" && typeof value !== "boolean") throw new Error("Invalid plugin enablement");
1227
+ if (field === "extraKnownMarketplaces") {
1228
+ const extra = object(value, field);
1229
+ if (extra.source && typeof extra.source === "object" && ["directory", "file"].includes(String(extra.source.source)) && "path" in extra.source) {
1230
+ const local = relocated(extra.source.path, sourceRoot, targetRoot);
1231
+ planCopy(local.source, local.target, sourceRoot, copies, catalogueFiles);
1232
+ extra.source.path = local.target;
1233
+ }
1234
+ }
1235
+ to[entryKey] = value;
1236
+ targetSettings.value[field] = to;
1237
+ }
1238
+ }
1239
+ }
1240
+ (ledger.value.seen[id] ??= []).push(key);
1241
+ }
1242
+ const sources = [sourceRegistry, sourceSettings, sourceMarkets, ...sourceCatalogues.values()];
1243
+ const targets = [...targetCatalogues.values(), targetMarkets, targetRegistry, targetSettings, ledger];
1244
+ for (const document of [...sources, ...targets]) unchanged(document);
1245
+ for (const copy of copies) if (!catalogueFiles.has(copy.target)) publishCopy(copy);
1246
+ for (const document of [...sources, ...targets]) unchanged(document);
1247
+ for (const document of targets) {
1248
+ for (const observed of [...sources, ...targets]) unchanged(observed);
1249
+ if (document.before === void 0 && Object.keys(document.value).length === 0) continue;
1250
+ publishDocument(document, targetHome);
1251
+ }
1252
+ return { imported, observed: pending.length };
1253
+ }
1254
+ var CLAUDE_PLUGIN_LINK_LEDGER = ".ccem-plugin-links-v1.json";
1255
+ var MARKER = ".ccem-plugin-link-v1.json";
1256
+ var BACKUP = ".ccem-plugin-links-backup-v1";
1257
+ var IGNORED = /* @__PURE__ */ new Set([".git", ".in_use", ".orphaned_at", MARKER]);
1258
+ function absolute(value) {
1259
+ return typeof value === "string" && path3.isAbsolute(value) && !value.split(/[\\/]/).includes("..");
1260
+ }
1261
+ function readLinks(target) {
1262
+ const document = readDocument(path3.join(target, CLAUDE_PLUGIN_LINK_LEDGER), { version: 1, plugins: {} });
1263
+ if (document.value.version !== 1 || Object.keys(document.value).some((key) => !["version", "plugins"].includes(key))) {
1264
+ throw new Error("Unsupported plugin links ledger");
1265
+ }
1266
+ for (const [id, rows] of Object.entries(object(document.value.plugins, "plugin links ledger"))) {
1267
+ pluginId(id);
1268
+ if (!Array.isArray(rows) || !rows.length) throw new Error("Invalid plugin link identities");
1269
+ const seen = [];
1270
+ for (const entry of rows) {
1271
+ const row = object(entry, "plugin link identity");
1272
+ const key = identity(row);
1273
+ const fields = row.local === true ? ["scope", "projectPath", "local"] : ["scope", "projectPath", "sourcePath", "installPath", "version"];
1274
+ if (!Object.hasOwn(row, "projectPath") || Object.keys(row).some((field) => !fields.includes(field)) || seen.some((old) => same(old, key))) throw new Error("Invalid plugin link identity");
1275
+ if (row.local !== true && (!absolute(row.sourcePath) || !absolute(row.installPath) || typeof row.version !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._+-]*$/.test(row.version))) {
1276
+ throw new Error("Invalid managed plugin link");
1277
+ }
1278
+ if (row.local !== true) {
1279
+ const [name, market] = id.split("@");
1280
+ const suffix = `.ccem-linked-${createHash("sha256").update(row.sourcePath).digest("hex").slice(0, 8)}`;
1281
+ if (!row.version.endsWith(suffix) || row.installPath !== path3.resolve(target, "plugins/cache", market, name, row.version)) {
1282
+ throw new Error("Managed plugin link escapes its CCEM cache");
1283
+ }
1284
+ }
1285
+ seen.push(key);
1286
+ }
1287
+ }
1288
+ return document;
1289
+ }
1290
+ function children(root) {
1291
+ return fs3.readdirSync(root).filter((name) => !IGNORED.has(name)).sort();
1292
+ }
1293
+ function validateCode(file, store, protectedCatalogues, ancestors = /* @__PURE__ */ new Set()) {
1294
+ const resolved = fs3.realpathSync(file);
1295
+ if (!contained(store, resolved)) throw new Error("Linked plugin code escapes the official plugin store");
1296
+ rejectPrivateData(store, resolved);
1297
+ const parts = path3.relative(store, resolved).split(path3.sep);
1298
+ if (parts.length < 2 || protectedCatalogues.has(resolved) || parts.some((part) => [".in_use", ".orphaned_at", MARKER].includes(part))) {
1299
+ throw new Error("Linked plugin code cannot expose official plugin metadata or runtime markers");
1300
+ }
1301
+ if (ancestors.has(resolved)) throw new Error("Linked plugin code has a symlink cycle");
1302
+ const info = fs3.statSync(resolved);
1303
+ if (info.isDirectory()) {
1304
+ const next = new Set(ancestors).add(resolved);
1305
+ const names = ancestors.size === 0 ? children(resolved) : fs3.readdirSync(resolved).sort();
1306
+ for (const name of names) validateCode(path3.join(resolved, name), store, protectedCatalogues, next);
1307
+ } else if (!info.isFile()) throw new Error("Linked plugin code is not a regular file or directory");
1308
+ }
1309
+ function equalCopy(source, target) {
1310
+ noLinks(target);
1311
+ const from = fs3.statSync(source);
1312
+ const to = stat(target);
1313
+ if (!to || from.isDirectory() !== to.isDirectory() || from.isFile() !== to.isFile()) return false;
1314
+ if (from.isFile()) return fs3.readFileSync(source).equals(fs3.readFileSync(target)) && (from.mode & 73) === (to.mode & 73);
1315
+ const names = children(source);
1316
+ const local = children(target);
1317
+ return JSON.stringify(names) === JSON.stringify(local) && names.every((name) => equalCopy(path3.join(source, name), path3.join(target, name)));
1318
+ }
1319
+ function rootMarker(target, source) {
1320
+ noLinks(target);
1321
+ const marker = readDocument(path3.join(target, MARKER));
1322
+ if (stat(target) && (!stat(target)?.isDirectory() || marker.value.version !== 1 || marker.value.source !== source || Object.keys(marker.value).some((key) => !["version", "source"].includes(key)))) {
1323
+ throw new Error("Existing plugin link root is not managed by CCEM");
1324
+ }
1325
+ return marker;
1326
+ }
1327
+ function recoverPublished(row, key, id, sourceRoot, targetRoot) {
1328
+ const [name, market] = id.split("@");
1329
+ if (typeof row.version !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._+-]*$/.test(row.version) || row.installPath !== path3.join(targetRoot, "cache", market, name, row.version) || !stat(row.installPath)) return;
1330
+ const marker = readDocument(path3.join(row.installPath, MARKER));
1331
+ if (marker.value.version !== 1 || !absolute(marker.value.source) || !contained(sourceRoot, marker.value.source)) return;
1332
+ rejectPrivateData(sourceRoot, marker.value.source);
1333
+ const suffix = `.ccem-linked-${createHash("sha256").update(marker.value.source).digest("hex").slice(0, 8)}`;
1334
+ if (!row.version.endsWith(suffix) || row.version.length === suffix.length) return;
1335
+ rootMarker(row.installPath, marker.value.source);
1336
+ return { ...key, sourcePath: marker.value.source, installPath: row.installPath, version: row.version };
1337
+ }
1338
+ function planRoot(source, target) {
1339
+ const marker = rootMarker(target, source);
1340
+ let changed2 = marker.before === void 0;
1341
+ const wanted = new Set(children(source));
1342
+ if (stat(target)) for (const name of children(target)) {
1343
+ const child = path3.join(target, name);
1344
+ if (!stat(child)?.isSymbolicLink() || fs3.readlinkSync(child) !== path3.join(source, name)) {
1345
+ throw new Error("CCEM plugin code was changed locally; keeping it");
1346
+ }
1347
+ if (!wanted.has(name)) changed2 = true;
1348
+ }
1349
+ for (const name of wanted) if (!stat(path3.join(target, name))) changed2 = true;
1350
+ return { source, target, changed: changed2 };
1351
+ }
1352
+ function publishRoot(root) {
1353
+ if (!root.changed) return;
1354
+ planRoot(root.source, root.target);
1355
+ const fresh = !stat(root.target);
1356
+ const directory = fresh ? `${root.target}.ccem-${randomUUID2()}.tmp` : root.target;
1357
+ privateDirectory(directory);
1358
+ try {
1359
+ if (fresh) fs3.writeFileSync(path3.join(directory, MARKER), `${JSON.stringify({ version: 1, source: root.source })}
1360
+ `, { flag: "wx", mode: 384 });
1361
+ const wanted = new Set(children(root.source));
1362
+ for (const name of children(directory)) if (!wanted.has(name)) {
1363
+ const child = path3.join(directory, name);
1364
+ if (!stat(child)?.isSymbolicLink() || fs3.readlinkSync(child) !== path3.join(root.source, name)) throw new Error("Plugin link changed during preparation");
1365
+ fs3.unlinkSync(child);
1366
+ }
1367
+ for (const name of wanted) {
1368
+ const child = path3.join(directory, name);
1369
+ if (stat(child)) continue;
1370
+ const original = path3.join(root.source, name);
1371
+ fs3.symlinkSync(original, child, fs3.statSync(original).isDirectory() ? "dir" : "file");
1372
+ }
1373
+ if (fresh) {
1374
+ noLinks(root.target);
1375
+ if (stat(root.target)) throw new Error("Plugin link root changed during preparation");
1376
+ fs3.renameSync(directory, root.target);
1377
+ }
1378
+ } finally {
1379
+ if (fresh) fs3.rmSync(directory, { recursive: true, force: true });
1380
+ }
1381
+ }
1382
+ function changed(document) {
1383
+ return document.before === void 0 ? Object.keys(document.value).length > 0 : JSON.stringify(JSON.parse(document.before)) !== JSON.stringify(document.value);
1384
+ }
1385
+ function planLinks(sourceHome, targetHome) {
1386
+ const imports = readLedger(targetHome);
1387
+ if (!Object.keys(imports.value.seen).length) return { documents: [], targets: [], roots: [], changed: false };
1388
+ const sourceRegistry = readSource(sourceHome);
1389
+ const sourcePlugins = registry(sourceRegistry);
1390
+ const targetRegistry = readSource(targetHome);
1391
+ const targetPlugins = registry(targetRegistry);
1392
+ const ledger = readLinks(targetHome);
1393
+ const sourceRoot = fs3.realpathSync(path3.join(sourceHome, "plugins"));
1394
+ noLinks(path3.join(sourceHome, "plugins"));
1395
+ const targetRoot = path3.resolve(targetHome, "plugins");
1396
+ noLinks(targetRoot);
1397
+ if (sourceRoot === targetRoot || contained(sourceRoot, targetRoot) || contained(targetRoot, sourceRoot)) throw new Error("Plugin stores must not overlap");
1398
+ for (const choices of Object.values(ledger.value.plugins)) for (const choice of choices) if (!("local" in choice)) {
1399
+ if (!contained(sourceRoot, choice.sourcePath)) throw new Error("Managed plugin source escapes the official store");
1400
+ rejectPrivateData(sourceRoot, choice.sourcePath);
1401
+ }
1402
+ const sourceMarkets = readDocument(path3.join(sourceRoot, "known_marketplaces.json"));
1403
+ const targetMarkets = readDocument(path3.join(targetRoot, "known_marketplaces.json"));
1404
+ const protectedCatalogues = /* @__PURE__ */ new Set();
1405
+ for (const market of Object.values(sourceMarkets.value)) {
1406
+ const location = market && typeof market === "object" ? market.installLocation : void 0;
1407
+ if (absolute(location) && contained(sourceRoot, location)) {
1408
+ const file = path3.join(location, ".claude-plugin/marketplace.json");
1409
+ if (fs3.existsSync(file)) protectedCatalogues.add(fs3.realpathSync(file));
1410
+ }
1411
+ }
1412
+ const documents = [imports, sourceRegistry, targetRegistry, ledger, sourceMarkets, targetMarkets];
1413
+ const catalogues = /* @__PURE__ */ new Map();
1414
+ const roots = /* @__PURE__ */ new Map();
1415
+ function catalogue(markets, market, store, mutable) {
1416
+ if (!Object.hasOwn(markets.value, market)) return void 0;
1417
+ const location = relocated(object(markets.value[market], "marketplace").installLocation, store, store).source;
1418
+ const file = path3.join(location, ".claude-plugin/marketplace.json");
1419
+ const document = catalogues.get(file) ?? readDocument(file);
1420
+ if (!Array.isArray(document.value.plugins)) throw new Error("Invalid marketplace catalogue");
1421
+ if (!catalogues.has(file)) {
1422
+ documents.push(document);
1423
+ if (mutable) catalogues.set(file, document);
1424
+ }
1425
+ return { document, location };
1426
+ }
1427
+ for (const [id, identities] of Object.entries(imports.value.seen)) {
1428
+ const choices = ledger.value.plugins[id] ??= [];
1429
+ for (const key of identities) {
1430
+ let index = choices.findIndex((choice) => same(choice, key));
1431
+ let old = index < 0 ? void 0 : choices[index];
1432
+ if (old && "local" in old) continue;
1433
+ const local = targetPlugins[id]?.find((row) => same(identity(row), key));
1434
+ const detach = () => {
1435
+ if (index < 0) {
1436
+ index = choices.length;
1437
+ choices.push({ ...key, local: true });
1438
+ } else choices[index] = { ...key, local: true };
1439
+ };
1440
+ if (!local) {
1441
+ detach();
1442
+ continue;
1443
+ }
1444
+ if (!old || local.installPath !== old.installPath || local.version !== old.version) {
1445
+ const recovered = recoverPublished(local, key, id, sourceRoot, targetRoot);
1446
+ if (recovered) {
1447
+ old = recovered;
1448
+ if (index < 0) {
1449
+ index = choices.length;
1450
+ choices.push(recovered);
1451
+ } else choices[index] = recovered;
1452
+ }
1453
+ }
1454
+ const registryMoved = old && (local.installPath !== old.installPath || local.version !== old.version);
1455
+ const official = sourcePlugins[id]?.find((row) => same(identity(row), key));
1456
+ if (!official) {
1457
+ if (registryMoved) detach();
1458
+ continue;
1459
+ }
1460
+ const original = relocated(official.installPath, sourceRoot, targetRoot);
1461
+ const [name, market] = id.split("@");
1462
+ const fromCatalogue = catalogue(sourceMarkets, market, sourceRoot, false);
1463
+ const toCatalogue = catalogue(targetMarkets, market, targetRoot, true);
1464
+ const fromEntry = fromCatalogue?.document.value.plugins?.find((entry) => entry.name === name);
1465
+ const toEntry = toCatalogue?.document.value.plugins?.find((entry) => entry.name === name);
1466
+ const entrySource = fromEntry?.source;
1467
+ const localSource = typeof entrySource === "string" ? entrySource : entrySource && typeof entrySource === "object" && ["directory", "file"].includes(String(entrySource.source)) ? entrySource.path : void 0;
1468
+ let code = original.source;
1469
+ let legacyCode = original.target;
1470
+ let expectedCatalogueSource;
1471
+ let actualCatalogueSource;
1472
+ if (localSource !== void 0) {
1473
+ if (typeof localSource !== "string" || !fromCatalogue || !toCatalogue || !toEntry) throw new Error("Invalid local plugin catalogue source");
1474
+ code = path3.resolve(fromCatalogue.location, localSource);
1475
+ if (!contained(sourceRoot, code)) throw new Error("Local plugin source escapes the official store");
1476
+ legacyCode = path3.isAbsolute(localSource) ? relocated(localSource, sourceRoot, targetRoot).target : path3.resolve(toCatalogue.location, localSource);
1477
+ if (!contained(targetRoot, legacyCode)) throw new Error("Local plugin destination escapes its store");
1478
+ expectedCatalogueSource = old ? old.installPath : path3.isAbsolute(localSource) ? legacyCode : localSource;
1479
+ actualCatalogueSource = typeof toEntry.source === "string" ? toEntry.source : object(toEntry.source, "local catalogue source").path;
1480
+ }
1481
+ if (!fs3.existsSync(code)) {
1482
+ if (registryMoved) detach();
1483
+ continue;
1484
+ }
1485
+ code = fs3.realpathSync(code);
1486
+ validateCode(code, sourceRoot, protectedCatalogues);
1487
+ const sourceVersion = typeof official.version === "string" ? official.version : path3.basename(original.source);
1488
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._+-]*$/.test(sourceVersion)) throw new Error("Invalid plugin version");
1489
+ const version = `${sourceVersion}.ccem-linked-${createHash("sha256").update(code).digest("hex").slice(0, 8)}`;
1490
+ const destination = path3.join(targetRoot, "cache", market, name, version);
1491
+ if (registryMoved) {
1492
+ if (local.installPath === destination && local.version === version && stat(destination)) rootMarker(destination, code);
1493
+ else {
1494
+ detach();
1495
+ continue;
1496
+ }
1497
+ }
1498
+ if (old && !registryMoved) {
1499
+ rootMarker(old.installPath, old.sourcePath);
1500
+ if (!stat(old.installPath) || children(old.installPath).some((name2) => {
1501
+ const child = path3.join(old.installPath, name2);
1502
+ return !stat(child)?.isSymbolicLink() || fs3.readlinkSync(child) !== path3.join(old.sourcePath, name2);
1503
+ })) {
1504
+ detach();
1505
+ continue;
1506
+ }
1507
+ }
1508
+ if (localSource !== void 0 && actualCatalogueSource !== expectedCatalogueSource) {
1509
+ const recovered = typeof actualCatalogueSource === "string" ? recoverPublished({
1510
+ installPath: actualCatalogueSource,
1511
+ version: path3.basename(actualCatalogueSource)
1512
+ }, key, id, sourceRoot, targetRoot) : void 0;
1513
+ if (!recovered) {
1514
+ detach();
1515
+ continue;
1516
+ }
1517
+ }
1518
+ if (!old) {
1519
+ const recovering = local.installPath === destination && local.version === version && stat(destination);
1520
+ if (recovering) rootMarker(destination, code);
1521
+ else {
1522
+ validateCode(original.source, sourceRoot, protectedCatalogues);
1523
+ if (local.installPath !== original.target || local.version !== official.version || !equalCopy(original.source, original.target) || !equalCopy(code, legacyCode)) {
1524
+ detach();
1525
+ continue;
1526
+ }
1527
+ }
1528
+ }
1529
+ roots.set(destination, planRoot(code, destination));
1530
+ if (localSource !== void 0 && toEntry) toEntry.source = destination;
1531
+ local.installPath = destination;
1532
+ local.version = version;
1533
+ const next = { ...key, sourcePath: code, installPath: destination, version };
1534
+ if (index < 0) choices.push(next);
1535
+ else choices[index] = next;
1536
+ }
1537
+ if (!choices.length) delete ledger.value.plugins[id];
1538
+ }
1539
+ const targets = [...catalogues.values(), targetRegistry, ledger];
1540
+ return { documents, targets, roots: [...roots.values()], changed: targets.some(changed) || [...roots.values()].some((root) => root.changed) };
1541
+ }
1542
+ function claudePluginLinksPending(sourceHome, targetHome) {
1543
+ return planLinks(sourceHome, targetHome).changed;
1544
+ }
1545
+ function linkClaudePlugins(sourceHome, targetHome) {
1546
+ const plan = planLinks(sourceHome, targetHome);
1547
+ if (!plan.changed) return;
1548
+ for (const document of plan.documents) unchanged(document);
1549
+ for (const root of plan.roots) publishRoot(root);
1550
+ for (const document of plan.targets) {
1551
+ for (const observed of plan.documents) unchanged(observed);
1552
+ publishDocument(document, targetHome, BACKUP);
1553
+ }
1554
+ }
1555
+ var AGENT_MIGRATION_MARKER = ".ccem-migration-v1.json";
1556
+ var MIGRATION_LOCK = ".ccem-migration.lock";
1557
+ var PROFILES_FILE = "profiles.json";
1558
+ var LEGACY_ENTRIES = {
1559
+ claude: ["projects", "history.jsonl", "plans", "file-history", "CLAUDE.md"],
1560
+ codex: ["sessions", "archived_sessions", "history.jsonl", "session_index.jsonl", "memories", "memories_v2", "AGENTS.md", "AGENTS.override.md"]
1561
+ };
1562
+ var IDENTITY_ENV_KEYS = [
1563
+ "ANTHROPIC_PROFILE",
1564
+ "CLAUDE_CODE_SESSION_ACCESS_TOKEN",
1565
+ "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",
1566
+ "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
1567
+ "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR",
1568
+ "CLAUDE_CODE_ORGANIZATION_UUID",
1569
+ "CLAUDE_CODE_USER_EMAIL",
1570
+ "CLAUDE_CODE_HFI_BEARER_TOKEN",
1571
+ "CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER",
1572
+ "CLAUDE_CODE_CUSTOM_OAUTH_URL",
1573
+ "CLAUDE_CODE_DESIGN_OAUTH_CLIENT_ID",
1574
+ "CLAUDE_CODE_REMOTE_SETTINGS_PATH",
1575
+ "CLAUDE_CODE_MOCK_REMOTE_SETTINGS",
1576
+ "CLAUDE_CODE_PLUGIN_SEED_DIR",
1577
+ "CLAUDE_CODE_PLUGIN_USE_ZIP_CACHE",
1578
+ "USE_LOCAL_OAUTH",
1579
+ "USE_STAGING_OAUTH",
1580
+ "CLAUDE_LOCAL_OAUTH_API_BASE",
1581
+ "CODEX_ACCESS_TOKEN"
1582
+ ];
1583
+ function isAgentIdentityEnvKey(key) {
1584
+ return IDENTITY_ENV_KEYS.includes(key) || ["CLAUDE_CODE_OAUTH_", "CLAUDE_CODE_HOST_", "CLAUDE_CODE_ACCOUNT_", "CLAUDE_COWORK_MEMORY_"].some((prefix) => key.startsWith(prefix));
1585
+ }
1586
+ var INHERITED_AGENT_ENV_KEYS = [
1587
+ ...IDENTITY_ENV_KEYS,
1588
+ "ANTHROPIC_BASE_URL",
1589
+ "ANTHROPIC_AUTH_TOKEN",
1590
+ "ANTHROPIC_API_KEY",
1591
+ "ANTHROPIC_CUSTOM_HEADERS",
1592
+ "ANTHROPIC_MODEL",
1593
+ "ANTHROPIC_SMALL_FAST_MODEL",
1594
+ "ANTHROPIC_PROFILE",
1595
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
1596
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
1597
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
1598
+ "CLAUDE_CODE_SUBAGENT_MODEL",
1599
+ "CLAUDE_CODE_SESSION_ACCESS_TOKEN",
1600
+ "CLAUDE_CODE_OAUTH_TOKEN",
1601
+ "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
1602
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
1603
+ "CLAUDE_CODE_OAUTH_CLIENT_ID",
1604
+ "CLAUDE_CODE_OAUTH_SCOPES",
1605
+ "CLAUDE_CODE_HOST_CREDS_FILE",
1606
+ "CLAUDE_CODE_HOST_AUTH_ENV_VAR",
1607
+ "CLAUDE_CODE_ACCOUNT_UUID",
1608
+ "CLAUDE_CODE_ACCOUNT_TAGGED_ID",
1609
+ "CLAUDE_CODE_USE_BEDROCK",
1610
+ "CLAUDE_CODE_USE_VERTEX",
1611
+ "CLAUDE_CODE_USE_FOUNDRY",
1612
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
1613
+ "CLAUDE_CODE_USE_MANTLE",
1614
+ "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
1615
+ "CLAUDE_CODE_USE_GATEWAY",
1616
+ "CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
1617
+ "CLAUDE_CONFIG_DIR",
1618
+ "CLAUDE_SECURESTORAGE_CONFIG_DIR",
1619
+ "CLAUDE_CODE_PLUGIN_CACHE_DIR",
1620
+ "OPENAI_API_KEY",
1621
+ "OPENAI_BASE_URL",
1622
+ "CODEX_API_KEY",
1623
+ "CODEX_HOME",
1624
+ "CODEX_SQLITE_HOME",
1625
+ "AWS_BEARER_TOKEN_BEDROCK",
1626
+ "ANTHROPIC_AWS_API_KEY",
1627
+ "ANTHROPIC_FOUNDRY_API_KEY",
1628
+ "ANTHROPIC_FOUNDRY_AUTH_TOKEN",
1629
+ "ANTHROPIC_FOUNDRY_RESOURCE",
1630
+ "ANTHROPIC_VERTEX_PROJECT_ID",
1631
+ "CLOUD_ML_REGION"
1632
+ ];
1633
+ var SHARED_CODEX_ENV_KEYS = [
1634
+ "OPENAI_API_KEY",
1635
+ "OPENAI_BASE_URL",
1636
+ "CODEX_API_KEY",
1637
+ "CODEX_ACCESS_TOKEN",
1638
+ "CODEX_SQLITE_HOME"
1639
+ ];
1640
+ function userHome(env) {
1641
+ return env.HOME || env.USERPROFILE || os.homedir();
1642
+ }
1643
+ function getCcemAgentBase(env = process.env) {
1644
+ const override = env.CCEM_AGENT_HOME?.trim();
1645
+ if (override && (!path4.isAbsolute(override) || override.split(/[\\/]/).includes(".."))) {
1646
+ throw new Error("CCEM_AGENT_HOME must be an absolute path without '..'");
1647
+ }
1648
+ return path4.resolve(override || path4.join(userHome(env), ".ccem", "agents"));
1649
+ }
1650
+ function readCodexIsolation(env) {
1651
+ if (env.CCEM_CODEX_ISOLATED === "1") return true;
1652
+ if (env.CCEM_CODEX_ISOLATED === "0") return false;
1653
+ const file = path4.join(getCcemAgentBase(env), PROFILES_FILE);
1654
+ let raw;
1655
+ try {
1656
+ raw = fs4.readFileSync(file, "utf8");
1657
+ } catch (error) {
1658
+ if (error.code === "ENOENT") return false;
1659
+ throw new Error("Cannot read CCEM agent profile preferences");
1660
+ }
1661
+ let profiles;
1662
+ try {
1663
+ profiles = JSON.parse(raw);
1664
+ } catch {
1665
+ throw new Error("CCEM agent profile preferences are invalid");
1666
+ }
1667
+ if (!profiles || typeof profiles !== "object" || Array.isArray(profiles)) {
1668
+ throw new Error("CCEM agent profile preferences are invalid");
1669
+ }
1670
+ const value = profiles.codexIsolation;
1671
+ if (value === void 0) return false;
1672
+ if (typeof value !== "boolean") throw new Error("CCEM codexIsolation preference must be a boolean");
1673
+ return value;
1674
+ }
1675
+ function isCodexIsolated(env = process.env) {
1676
+ try {
1677
+ return readCodexIsolation(env);
1678
+ } catch {
1679
+ return true;
1680
+ }
1681
+ }
1682
+ function getCcemIsolatedAgentHome(provider, env = process.env) {
1683
+ return path4.join(getCcemAgentBase(env), provider);
1684
+ }
1685
+ function getOfficialCodexHome(env) {
1686
+ const override = env.CODEX_HOME?.trim();
1687
+ if (!override) return path4.resolve(userHome(env), ".codex");
1688
+ if (override === "~") return path4.resolve(userHome(env));
1689
+ if (/^~[\\/]/.test(override)) return path4.resolve(userHome(env), override.slice(2));
1690
+ return path4.resolve(override);
1691
+ }
1692
+ function getCcemAgentHome(provider, env = process.env) {
1693
+ return provider === "codex" && !isCodexIsolated(env) ? getOfficialCodexHome(env) : getCcemIsolatedAgentHome(provider, env);
1694
+ }
1695
+ function getCcemAgentEnv(env = process.env) {
1696
+ const isolated = readCodexIsolation(env);
1697
+ const claude = getCcemIsolatedAgentHome("claude", env);
1698
+ const codex = isolated ? getCcemIsolatedAgentHome("codex", env) : getOfficialCodexHome(env);
1699
+ return {
1700
+ CLAUDE_CONFIG_DIR: claude,
1701
+ CLAUDE_SECURESTORAGE_CONFIG_DIR: claude,
1702
+ CLAUDE_CODE_PLUGIN_CACHE_DIR: path4.join(claude, "plugins"),
1703
+ CODEX_HOME: codex,
1704
+ CCEM_CODEX_ISOLATED: isolated ? "1" : "0",
1705
+ ...isolated ? { CODEX_SQLITE_HOME: codex } : {}
1706
+ };
1707
+ }
1708
+ function clearInheritedAgentEnv(env, codexIsolated = isCodexIsolated(env)) {
1709
+ for (const key of Object.keys(env)) {
1710
+ if (!codexIsolated && SHARED_CODEX_ENV_KEYS.includes(key)) continue;
1711
+ if (INHERITED_AGENT_ENV_KEYS.includes(key) || isAgentIdentityEnvKey(key)) {
1712
+ delete env[key];
1713
+ }
1714
+ }
1715
+ }
1716
+ function buildIsolatedAgentEnv(baseEnv = process.env, selectedEnv = {}) {
1717
+ const profile = getCcemAgentEnv(baseEnv);
1718
+ const codexIsolated = profile.CCEM_CODEX_ISOLATED === "1";
1719
+ const env = { ...baseEnv };
1720
+ clearInheritedAgentEnv(env, codexIsolated);
1721
+ Object.assign(env, selectedEnv);
1722
+ for (const key of Object.keys(env)) {
1723
+ if (isAgentIdentityEnvKey(key) && (codexIsolated || key !== "CODEX_ACCESS_TOKEN")) delete env[key];
1724
+ }
1725
+ delete env.CLAUDECODE;
1726
+ if (baseEnv.CCEM_AGENT_HOME === void 0) delete env.CCEM_AGENT_HOME;
1727
+ else env.CCEM_AGENT_HOME = baseEnv.CCEM_AGENT_HOME;
1728
+ if (!codexIsolated) {
1729
+ if (baseEnv.CODEX_SQLITE_HOME === void 0) delete env.CODEX_SQLITE_HOME;
1730
+ else env.CODEX_SQLITE_HOME = baseEnv.CODEX_SQLITE_HOME;
1731
+ }
1732
+ Object.assign(env, profile);
1733
+ return Object.fromEntries(Object.entries(env).filter((entry) => entry[1] !== void 0));
1734
+ }
1735
+ function statIfPresent(file) {
1736
+ try {
1737
+ return fs4.lstatSync(file);
1738
+ } catch (error) {
1739
+ if (error.code === "ENOENT") return void 0;
1740
+ throw error;
1741
+ }
1742
+ }
1743
+ function ensureRealDirectory(directory) {
1744
+ validateNoSymlinks(directory);
1745
+ fs4.mkdirSync(directory, { recursive: true, mode: 448 });
1746
+ const stat22 = fs4.lstatSync(directory);
1747
+ if (stat22.isSymbolicLink() || !stat22.isDirectory()) {
1748
+ throw new Error(`CCEM agent directory must be a real directory: ${directory}`);
1749
+ }
1750
+ fs4.chmodSync(directory, 448);
1751
+ }
1752
+ function validateNoSymlinks(file) {
1753
+ let current = path4.parse(file).root;
1754
+ for (const component of file.slice(current.length).split(path4.sep).filter(Boolean)) {
1755
+ current = path4.join(current, component);
1756
+ const stat22 = statIfPresent(current);
1757
+ if (!stat22) break;
1758
+ if (stat22.isSymbolicLink()) throw new Error(`CCEM agent state cannot use a symlink: ${current}`);
1759
+ }
1760
+ }
1761
+ function resolveExistingParent(file) {
1762
+ const suffix = [];
1763
+ let parent = file;
1764
+ while (!statIfPresent(parent)) {
1765
+ suffix.unshift(path4.basename(parent));
1766
+ parent = path4.dirname(parent);
1767
+ }
1768
+ return path4.join(fs4.realpathSync(parent), ...suffix);
1769
+ }
1770
+ function validateAgentBase(base, env) {
1771
+ validateNoSymlinks(base);
1772
+ const resolved = resolveExistingParent(base);
1773
+ for (const name of [".claude", ".codex"]) {
1774
+ const official = resolveExistingParent(path4.join(userHome(env), name));
1775
+ if (resolved === official || resolved.startsWith(`${official}${path4.sep}`) || official.startsWith(`${resolved}${path4.sep}`)) {
1776
+ throw new Error("CCEM agent state must not overlap an official Claude or Codex home");
1777
+ }
1778
+ }
1779
+ }
1780
+ function syncDirectory(directory) {
1781
+ if (process.platform === "win32") return;
1782
+ const fd = fs4.openSync(directory, "r");
1783
+ try {
1784
+ fs4.fsyncSync(fd);
1785
+ } finally {
1786
+ fs4.closeSync(fd);
1787
+ }
1788
+ }
1789
+ function migrationComplete(marker) {
1790
+ const stat22 = statIfPresent(marker);
1791
+ if (!stat22) return false;
1792
+ if (!stat22.isFile() || stat22.isSymbolicLink()) throw new Error("CCEM agent migration marker is invalid");
1793
+ let version;
1794
+ try {
1795
+ version = JSON.parse(fs4.readFileSync(marker, "utf8")).version;
1796
+ } catch {
1797
+ }
1798
+ if (version !== 1) throw new Error("CCEM agent migration marker is invalid or unsupported");
1799
+ return true;
1800
+ }
1801
+ function writeNewFile(file, contents) {
1802
+ validateNoSymlinks(file);
1803
+ const existing = statIfPresent(file);
1804
+ if (existing) {
1805
+ if (!existing.isFile()) throw new Error(`CCEM agent file conflicts with a directory: ${file}`);
1806
+ return;
1807
+ }
1808
+ const temporary = path4.join(path4.dirname(file), `.ccem-copy-${randomUUID3()}.tmp`);
1809
+ try {
1810
+ const fd = fs4.openSync(temporary, "wx", 384);
1811
+ try {
1812
+ fs4.writeFileSync(fd, contents);
1813
+ fs4.fsyncSync(fd);
1814
+ } finally {
1815
+ fs4.closeSync(fd);
1816
+ }
1817
+ try {
1818
+ fs4.linkSync(temporary, file);
1819
+ } catch (error) {
1820
+ if (error.code !== "EEXIST") throw error;
1821
+ }
1822
+ } finally {
1823
+ fs4.rmSync(temporary, { force: true });
1824
+ }
1825
+ }
1826
+ function copyLegacyEntry(source, destination) {
1827
+ const sourceStat = statIfPresent(source);
1828
+ if (!sourceStat || sourceStat.isSymbolicLink()) return;
1829
+ if (sourceStat.isFile() && /\.(?:sqlite|sqlite3|db)(?:-(?:wal|shm))?$/i.test(path4.basename(source))) return;
1830
+ validateNoSymlinks(destination);
1831
+ const destinationStat = statIfPresent(destination);
1832
+ if (sourceStat.isDirectory()) {
1833
+ if (destinationStat && !destinationStat.isDirectory()) throw new Error(`CCEM agent directory conflicts with a file: ${destination}`);
1834
+ ensureRealDirectory(destination);
1835
+ for (const name of fs4.readdirSync(source)) {
1836
+ copyLegacyEntry(path4.join(source, name), path4.join(destination, name));
1837
+ }
1838
+ syncDirectory(destination);
1839
+ return;
1840
+ }
1841
+ if (!sourceStat.isFile()) return;
1842
+ if (destinationStat) {
1843
+ if (!destinationStat.isFile()) throw new Error(`CCEM agent file conflicts with a directory: ${destination}`);
1844
+ return;
1845
+ }
1846
+ const temporary = path4.join(path4.dirname(destination), `.ccem-copy-${randomUUID3()}.tmp`);
1847
+ let sourceFd;
1848
+ let destinationFd;
1849
+ try {
1850
+ sourceFd = fs4.openSync(source, fs4.constants.O_RDONLY | (fs4.constants.O_NOFOLLOW ?? 0));
1851
+ const openedStat = fs4.fstatSync(sourceFd);
1852
+ if (!openedStat.isFile()) throw new Error("Legacy agent history changed during migration");
1853
+ destinationFd = fs4.openSync(temporary, "wx", 384);
1854
+ const buffer = Buffer.alloc(1024 * 1024);
1855
+ let remaining = openedStat.size;
1856
+ while (remaining > 0) {
1857
+ const bytesRead = fs4.readSync(sourceFd, buffer, 0, Math.min(remaining, buffer.length), null);
1858
+ if (!bytesRead) throw new Error("Legacy agent history changed during migration");
1859
+ let offset = 0;
1860
+ while (offset < bytesRead) offset += fs4.writeSync(destinationFd, buffer, offset, bytesRead - offset);
1861
+ remaining -= bytesRead;
1862
+ }
1863
+ fs4.futimesSync(destinationFd, openedStat.atime, openedStat.mtime);
1864
+ fs4.fsyncSync(destinationFd);
1865
+ fs4.closeSync(destinationFd);
1866
+ destinationFd = void 0;
1867
+ try {
1868
+ fs4.linkSync(temporary, destination);
1869
+ } catch (error) {
1870
+ if (error.code !== "EEXIST") throw error;
1871
+ }
1872
+ } finally {
1873
+ if (sourceFd !== void 0) fs4.closeSync(sourceFd);
1874
+ if (destinationFd !== void 0) fs4.closeSync(destinationFd);
1875
+ fs4.rmSync(temporary, { force: true });
1876
+ }
1877
+ }
1878
+ function acquireMigrationLock(base) {
1879
+ const lockPath = path4.join(base, MIGRATION_LOCK);
1880
+ const contents = JSON.stringify({ pid: process.pid });
1881
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1882
+ try {
1883
+ const fd = fs4.openSync(lockPath, "wx", 384);
1884
+ try {
1885
+ fs4.writeFileSync(fd, contents);
1886
+ fs4.fsyncSync(fd);
1887
+ } catch (error) {
1888
+ const owned = fs4.fstatSync(fd);
1889
+ const current = statIfPresent(lockPath);
1890
+ if (current?.ino === owned.ino && current.dev === owned.dev) fs4.unlinkSync(lockPath);
1891
+ throw error;
1892
+ } finally {
1893
+ fs4.closeSync(fd);
1894
+ }
1895
+ return () => {
1896
+ if (statIfPresent(lockPath)?.isFile() && fs4.readFileSync(lockPath, "utf8") === contents) fs4.unlinkSync(lockPath);
1897
+ };
1898
+ } catch (error) {
1899
+ if (error.code !== "EEXIST") throw error;
1900
+ const stat22 = fs4.lstatSync(lockPath);
1901
+ if (!stat22.isFile() || stat22.isSymbolicLink()) throw new Error("CCEM agent migration lock is invalid");
1902
+ const old = fs4.readFileSync(lockPath, "utf8");
1903
+ let pid;
1904
+ try {
1905
+ pid = JSON.parse(old).pid;
1906
+ } catch {
1907
+ }
1908
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("CCEM agent migration lock is invalid");
1909
+ try {
1910
+ process.kill(pid, 0);
1911
+ } catch (probeError) {
1912
+ if (probeError.code === "ESRCH" && attempt === 0) {
1913
+ if (fs4.readFileSync(lockPath, "utf8") !== old) throw new Error("CCEM agent migration lock changed; retry preparation");
1914
+ fs4.unlinkSync(lockPath);
1915
+ continue;
1916
+ }
1917
+ }
1918
+ throw new Error(`CCEM agent migration is in progress (PID ${pid}); retry when it finishes`);
1919
+ }
1920
+ }
1921
+ throw new Error("Could not acquire CCEM agent migration lock");
1922
+ }
1923
+ function ensureCcemAgentHome(provider, env = process.env) {
1924
+ if (provider === "codex" && !readCodexIsolation(env)) return getOfficialCodexHome(env);
1925
+ const base = getCcemAgentBase(env);
1926
+ const root = getCcemIsolatedAgentHome(provider, env);
1927
+ validateAgentBase(base, env);
1928
+ for (const entry of LEGACY_ENTRIES[provider]) validateNoSymlinks(path4.join(root, entry));
1929
+ validateNoSymlinks(path4.join(root, provider === "claude" ? ".claude.json" : "config.toml"));
1930
+ const marker = path4.join(root, AGENT_MIGRATION_MARKER);
1931
+ const source = provider === "codex" ? getOfficialCodexHome(env) : path4.join(userHome(env), ".claude");
1932
+ const historyReady = migrationComplete(marker);
1933
+ if (historyReady) {
1934
+ if (provider !== "claude") return root;
1935
+ try {
1936
+ if (!claudePluginImportPending(source, root) && !claudePluginLinksPending(source, root)) return root;
1937
+ } catch (error) {
1938
+ console.warn(`CCEM plugin import deferred: ${error.message}`);
1939
+ return root;
1940
+ }
1941
+ }
1942
+ ensureRealDirectory(base);
1943
+ ensureRealDirectory(root);
1944
+ let unlock;
1945
+ try {
1946
+ unlock = acquireMigrationLock(base);
1947
+ } catch (error) {
1948
+ if (!historyReady) throw error;
1949
+ console.warn(`CCEM plugin import deferred: ${error.message}`);
1950
+ return root;
1951
+ }
1952
+ try {
1953
+ if (!migrationComplete(marker)) {
1954
+ if (provider === "codex") {
1955
+ const resolvedBase = resolveExistingParent(base);
1956
+ const resolvedSource = resolveExistingParent(source);
1957
+ if (resolvedBase === resolvedSource || resolvedBase.startsWith(`${resolvedSource}${path4.sep}`) || resolvedSource.startsWith(`${resolvedBase}${path4.sep}`)) {
1958
+ throw new Error("CCEM Codex migration source must not overlap its isolated agent directory");
1959
+ }
1960
+ }
1961
+ assertNoLegacyAgentWriters(provider, userHome(env), source, root);
1962
+ const sourceStat = statIfPresent(source);
1963
+ if (sourceStat?.isDirectory() && !sourceStat.isSymbolicLink()) {
1964
+ for (const entry of LEGACY_ENTRIES[provider]) copyLegacyEntry(path4.join(source, entry), path4.join(root, entry));
1965
+ }
1966
+ if (provider === "claude") writeNewFile(path4.join(root, ".claude.json"), JSON.stringify({ hasCompletedOnboarding: true }));
1967
+ writeNewFile(marker, JSON.stringify({ version: 1 }));
1968
+ syncDirectory(root);
1969
+ }
1970
+ if (provider === "claude") {
1971
+ try {
1972
+ importClaudePlugins(source, root);
1973
+ linkClaudePlugins(source, root);
1974
+ } catch (error) {
1975
+ console.warn(`CCEM plugin import deferred: ${error.message}`);
1976
+ }
1977
+ }
1978
+ return root;
1979
+ } finally {
1980
+ unlock();
1981
+ }
1982
+ }
707
1983
  var V2_ALGORITHM = "aes-256-gcm";
708
1984
  function encryptV2WithKey(text, key, nonce) {
709
1985
  const cipher = crypto.createCipheriv(V2_ALGORITHM, key, nonce);
@@ -747,14 +2023,14 @@ var LEGACY_KEY = crypto2.scryptSync("claude-code-env-manager-secret", "salt", 32
747
2023
  var _installKey = null;
748
2024
  function getOrCreateInstallKey() {
749
2025
  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");
2026
+ const keyPath = path5.join(getCcemConfigDir(), ".install-key");
2027
+ if (fs5.existsSync(keyPath)) {
2028
+ _installKey = Buffer.from(fs5.readFileSync(keyPath, "utf-8").trim(), "hex");
753
2029
  return _installKey;
754
2030
  }
755
2031
  ensureCcemDir();
756
2032
  _installKey = crypto2.randomBytes(32);
757
- fs.writeFileSync(keyPath, _installKey.toString("hex"), { mode: 384 });
2033
+ fs5.writeFileSync(keyPath, _installKey.toString("hex"), { mode: 384 });
758
2034
  return _installKey;
759
2035
  }
760
2036
  var encrypt = (text) => {
@@ -785,30 +2061,30 @@ var decrypt = (text) => {
785
2061
  }
786
2062
  };
787
2063
  var getHomeDir = () => {
788
- return process.env.HOME || process.env.USERPROFILE || os.homedir() || "";
2064
+ return process.env.HOME || process.env.USERPROFILE || os2.homedir() || "";
789
2065
  };
790
2066
  var getCcemConfigDir = () => {
791
- return path.join(getHomeDir(), ".ccem");
2067
+ return path5.join(getHomeDir(), ".ccem");
792
2068
  };
793
2069
  var getCcemConfigPath = () => {
794
- return path.join(getCcemConfigDir(), "config.json");
2070
+ return path5.join(getCcemConfigDir(), "config.json");
795
2071
  };
796
2072
  var ensureCcemDir = () => {
797
2073
  const ccemDir = getCcemConfigDir();
798
- if (!fs.existsSync(ccemDir)) {
799
- fs.mkdirSync(ccemDir, { recursive: true, mode: 448 });
2074
+ if (!fs5.existsSync(ccemDir)) {
2075
+ fs5.mkdirSync(ccemDir, { recursive: true, mode: 448 });
800
2076
  }
801
2077
  if (process.platform !== "win32") {
802
- fs.chmodSync(ccemDir, 448);
2078
+ fs5.chmodSync(ccemDir, 448);
803
2079
  }
804
2080
  return ccemDir;
805
2081
  };
806
2082
  var getLegacyConfigPath = () => {
807
2083
  const home = getHomeDir();
808
2084
  if (process.platform === "darwin") {
809
- return path.join(home, "Library", "Preferences", "claude-code-env-manager-nodejs", "config.json");
2085
+ return path5.join(home, "Library", "Preferences", "claude-code-env-manager-nodejs", "config.json");
810
2086
  }
811
- return path.join(home, ".config", "claude-code-env-manager-nodejs", "config.json");
2087
+ return path5.join(home, ".config", "claude-code-env-manager-nodejs", "config.json");
812
2088
  };
813
2089
 
814
2090
  // src/desktopControl.ts
@@ -875,11 +2151,11 @@ function getDesktopControlDescriptorPath() {
875
2151
  return process.env.CCEM_CONTROL_FILE?.trim() || getDefaultControlDescriptorPath();
876
2152
  }
877
2153
  function getDefaultControlDescriptorPath() {
878
- return path2.join(getCcemConfigDir(), "control.json");
2154
+ return path6.join(getCcemConfigDir(), "control.json");
879
2155
  }
880
2156
  function isDefaultDescriptorPath(descriptorPath) {
881
2157
  try {
882
- return path2.resolve(descriptorPath) === path2.resolve(getDefaultControlDescriptorPath());
2158
+ return path6.resolve(descriptorPath) === path6.resolve(getDefaultControlDescriptorPath());
883
2159
  } catch {
884
2160
  return false;
885
2161
  }
@@ -889,7 +2165,7 @@ function safeRemoveStaleDescriptor(descriptorPath) {
889
2165
  return false;
890
2166
  }
891
2167
  try {
892
- fs2.rmSync(descriptorPath);
2168
+ fs6.rmSync(descriptorPath);
893
2169
  return true;
894
2170
  } catch {
895
2171
  return false;
@@ -967,10 +2243,10 @@ function isDescriptor(value) {
967
2243
  );
968
2244
  }
969
2245
  function resolveDesktopControlDescriptor(descriptorPath = getDesktopControlDescriptorPath()) {
970
- if (!fs2.existsSync(descriptorPath)) {
2246
+ if (!fs6.existsSync(descriptorPath)) {
971
2247
  throw new Error(`CCEM Desktop control endpoint not found at ${descriptorPath}. Start CCEM Desktop first.`);
972
2248
  }
973
- const parsed = JSON.parse(fs2.readFileSync(descriptorPath, "utf-8"));
2249
+ const parsed = JSON.parse(fs6.readFileSync(descriptorPath, "utf-8"));
974
2250
  const endpoint = parsed.endpoint?.trim();
975
2251
  const token = parsed.token?.trim();
976
2252
  if (!endpoint || !token) {
@@ -1235,29 +2511,29 @@ import inquirer from "inquirer";
1235
2511
  import chalk9 from "chalk";
1236
2512
  import Table4 from "cli-table3";
1237
2513
  import { spawn as spawn4 } from "child_process";
1238
- import * as fs14 from "fs";
1239
- import * as path12 from "path";
2514
+ import * as fs18 from "fs";
2515
+ import * as path16 from "path";
1240
2516
  import { fileURLToPath as fileURLToPath2 } from "url";
1241
- import { randomUUID } from "crypto";
2517
+ import { randomUUID as randomUUID4 } from "crypto";
1242
2518
 
1243
2519
  // src/ui.ts
1244
2520
  import chalk from "chalk";
1245
2521
  import Table from "cli-table3";
1246
2522
 
1247
2523
  // src/usage.ts
1248
- import * as fs3 from "fs";
2524
+ import * as fs7 from "fs";
1249
2525
  import * as fsPromises from "fs/promises";
1250
- import * as path3 from "path";
1251
- import * as os2 from "os";
2526
+ import * as path7 from "path";
2527
+ import * as os3 from "os";
1252
2528
  import * as readline from "readline";
1253
2529
  import { fileURLToPath } from "url";
1254
2530
  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");
2531
+ var __dirname = path7.dirname(__filename);
2532
+ var CLAUDE_PROJECTS_DIR = path7.join(getCcemAgentHome("claude"), "projects");
2533
+ var CCEM_DIR = path7.join(os3.homedir(), ".ccem");
2534
+ var CACHE_VERSION = 3;
2535
+ var getCachePath = () => path7.join(CCEM_DIR, "usage-cache.json");
2536
+ var getPricesPath = () => path7.join(CCEM_DIR, "model-prices.json");
1261
2537
  async function ensureCcemDir2() {
1262
2538
  try {
1263
2539
  await fsPromises.access(CCEM_DIR);
@@ -1267,7 +2543,7 @@ async function ensureCcemDir2() {
1267
2543
  }
1268
2544
  var LITELLM_PRICES_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
1269
2545
  var getBundledPricesPath = () => {
1270
- return path3.join(__dirname, "..", "model-prices.json");
2546
+ return path7.join(__dirname, "..", "model-prices.json");
1271
2547
  };
1272
2548
  var DEFAULT_PRICES = {
1273
2549
  "claude-opus-4-5": {
@@ -1374,10 +2650,10 @@ function mergeUsage(a, b) {
1374
2650
  }
1375
2651
  async function getFileMetaAsync(filePath) {
1376
2652
  try {
1377
- const stat2 = await fsPromises.stat(filePath);
2653
+ const stat3 = await fsPromises.stat(filePath);
1378
2654
  return {
1379
- mtime: stat2.mtimeMs,
1380
- size: stat2.size
2655
+ mtime: stat3.mtimeMs,
2656
+ size: stat3.size
1381
2657
  };
1382
2658
  } catch {
1383
2659
  return null;
@@ -1386,8 +2662,8 @@ async function getFileMetaAsync(filePath) {
1386
2662
  function loadCacheSync() {
1387
2663
  try {
1388
2664
  const cachePath = getCachePath();
1389
- if (!fs3.existsSync(cachePath)) return null;
1390
- const data = JSON.parse(fs3.readFileSync(cachePath, "utf-8"));
2665
+ if (!fs7.existsSync(cachePath)) return null;
2666
+ const data = JSON.parse(fs7.readFileSync(cachePath, "utf-8"));
1391
2667
  if (data.version !== CACHE_VERSION) return null;
1392
2668
  return data;
1393
2669
  } catch {
@@ -1455,7 +2731,7 @@ async function parseJSONLFileAsync(filePath, prices, signal) {
1455
2731
  const entries = [];
1456
2732
  const messageEntryIndexes = /* @__PURE__ */ new Map();
1457
2733
  try {
1458
- const fileStream = fs3.createReadStream(filePath, { encoding: "utf-8" });
2734
+ const fileStream = fs7.createReadStream(filePath, { encoding: "utf-8" });
1459
2735
  const rl = readline.createInterface({
1460
2736
  input: fileStream,
1461
2737
  crlfDelay: Infinity
@@ -1521,14 +2797,15 @@ async function getAllJSONLFilesAsync() {
1521
2797
  if (!projectsDirExists) return files;
1522
2798
  const projects = await fsPromises.readdir(CLAUDE_PROJECTS_DIR);
1523
2799
  for (const project of projects) {
1524
- const projectPath = path3.join(CLAUDE_PROJECTS_DIR, project);
2800
+ const projectPath = path7.join(CLAUDE_PROJECTS_DIR, project);
1525
2801
  try {
1526
- const stat2 = await fsPromises.stat(projectPath);
1527
- if (stat2.isDirectory()) {
2802
+ const stat3 = await fsPromises.lstat(projectPath);
2803
+ if (stat3.isDirectory()) {
1528
2804
  const projectFiles = await fsPromises.readdir(projectPath);
1529
2805
  for (const file of projectFiles) {
1530
- if (file.endsWith(".jsonl")) {
1531
- files.push(path3.join(projectPath, file));
2806
+ const filePath = path7.join(projectPath, file);
2807
+ if (file.endsWith(".jsonl") && (await fsPromises.lstat(filePath)).isFile()) {
2808
+ files.push(filePath);
1532
2809
  }
1533
2810
  }
1534
2811
  }
@@ -1541,6 +2818,7 @@ async function getAllJSONLFilesAsync() {
1541
2818
  }
1542
2819
  async function getUsageStats(signal) {
1543
2820
  if (signal?.aborted) throw new Error("Aborted");
2821
+ ensureCcemAgentHome("claude");
1544
2822
  const prices = await loadPrices();
1545
2823
  if (signal?.aborted) throw new Error("Aborted");
1546
2824
  const files = await getAllJSONLFilesAsync();
@@ -1751,10 +3029,10 @@ var renderLogoWithEnvPanel = (envName, env, defaultMode) => {
1751
3029
  const parsed = new URL(url);
1752
3030
  const protocol = parsed.protocol + "//";
1753
3031
  const host = parsed.host;
1754
- const path13 = parsed.pathname + parsed.search;
3032
+ const path17 = parsed.pathname + parsed.search;
1755
3033
  const hostStart = host.slice(0, 8);
1756
3034
  const hostEnd = host.slice(-4);
1757
- const pathPart = path13.length > 10 ? path13.slice(0, 7) + "..." : path13;
3035
+ const pathPart = path17.length > 10 ? path17.slice(0, 7) + "..." : path17;
1758
3036
  return `${protocol}${hostStart}...${hostEnd}${pathPart}`;
1759
3037
  } catch {
1760
3038
  return truncate(url, max);
@@ -2192,70 +3470,62 @@ var selectEnvWithKeys = (registries, current) => {
2192
3470
  };
2193
3471
 
2194
3472
  // src/permissions.ts
2195
- import fs7 from "fs";
3473
+ import fs11 from "fs";
2196
3474
  import chalk3 from "chalk";
2197
3475
  import Table2 from "cli-table3";
2198
3476
 
2199
3477
  // src/utils.ts
2200
3478
  import crypto3 from "crypto";
2201
- import fs4 from "fs";
2202
- import os3 from "os";
2203
- import path4 from "path";
3479
+ import fs8 from "fs";
3480
+ import path8 from "path";
2204
3481
  var SECRET_KEY = crypto3.scryptSync("claude-code-env-manager-secret", "salt", 32);
2205
3482
  var findProjectRoot = () => {
2206
3483
  let currentDir = process.cwd();
2207
- const root = path4.parse(currentDir).root;
3484
+ const root = path8.parse(currentDir).root;
2208
3485
  while (currentDir !== root) {
2209
- if (fs4.existsSync(path4.join(currentDir, ".git")) || fs4.existsSync(path4.join(currentDir, "package.json"))) {
3486
+ if (fs8.existsSync(path8.join(currentDir, ".git")) || fs8.existsSync(path8.join(currentDir, "package.json"))) {
2210
3487
  return currentDir;
2211
3488
  }
2212
- currentDir = path4.dirname(currentDir);
3489
+ currentDir = path8.dirname(currentDir);
2213
3490
  }
2214
3491
  return process.cwd();
2215
3492
  };
2216
3493
  var getSettingsPath = (useLocal = true) => {
2217
3494
  const projectRoot = findProjectRoot();
2218
- const claudeDir = path4.join(projectRoot, ".claude");
3495
+ const claudeDir = path8.join(projectRoot, ".claude");
2219
3496
  const filename = useLocal ? "settings.local.json" : "settings.json";
2220
- return path4.join(claudeDir, filename);
3497
+ return path8.join(claudeDir, filename);
2221
3498
  };
2222
3499
  var ensureClaudeDir = () => {
2223
3500
  const projectRoot = findProjectRoot();
2224
- const claudeDir = path4.join(projectRoot, ".claude");
2225
- if (!fs4.existsSync(claudeDir)) {
2226
- fs4.mkdirSync(claudeDir, { recursive: true });
3501
+ const claudeDir = path8.join(projectRoot, ".claude");
3502
+ if (!fs8.existsSync(claudeDir)) {
3503
+ fs8.mkdirSync(claudeDir, { recursive: true });
2227
3504
  }
2228
3505
  return claudeDir;
2229
3506
  };
2230
- var getHomeDir2 = () => {
2231
- return process.env.HOME || process.env.USERPROFILE || os3.homedir() || "";
2232
- };
2233
3507
  var getGlobalClaudeConfigPath = () => {
2234
- return path4.join(getHomeDir2(), ".claude.json");
3508
+ return path8.join(getCcemAgentHome("claude"), ".claude.json");
2235
3509
  };
2236
3510
  var getGlobalClaudeSettingsPath = () => {
2237
- return path4.join(getHomeDir2(), ".claude", "settings.json");
3511
+ return path8.join(getCcemAgentHome("claude"), "settings.json");
2238
3512
  };
2239
3513
  var ensureGlobalClaudeDir = () => {
2240
- const claudeDir = path4.join(getHomeDir2(), ".claude");
2241
- if (!fs4.existsSync(claudeDir)) {
2242
- fs4.mkdirSync(claudeDir, { recursive: true });
2243
- }
2244
- return claudeDir;
3514
+ return ensureCcemAgentHome("claude");
2245
3515
  };
2246
3516
 
2247
3517
  // src/launcher.ts
2248
3518
  import { spawn as spawn2 } from "child_process";
2249
- import * as fs6 from "fs";
2250
- import * as path6 from "path";
3519
+ import * as fs10 from "fs";
3520
+ import * as path10 from "path";
2251
3521
  import chalk2 from "chalk";
2252
3522
 
2253
3523
  // src/sessionProvenance.ts
2254
- import { execFileSync } from "child_process";
2255
- import fs5 from "fs";
3524
+ import { execFileSync as execFileSync2 } from "child_process";
3525
+ import fs9 from "fs";
2256
3526
  import { createRequire } from "module";
2257
3527
  import os4 from "os";
2258
- import path5 from "path";
3528
+ import path9 from "path";
2259
3529
  var DEFAULT_CONFIG_SOURCE = "ccem";
2260
3530
  var STATE_DB_FILE_NAME = "state.sqlite";
2261
3531
  var BIND_POLL_INTERVAL_MS = 500;
@@ -2310,7 +3580,7 @@ function startCliClaudeProvenanceTracking(options) {
2310
3580
  if (!jsonlPath) {
2311
3581
  return;
2312
3582
  }
2313
- const sourceSessionId = readClaudeSessionId(jsonlPath) ?? normalizeText(path5.parse(jsonlPath).name);
3583
+ const sourceSessionId = readClaudeSessionId(jsonlPath) ?? normalizeText(path9.parse(jsonlPath).name);
2314
3584
  if (!sourceSessionId) {
2315
3585
  return;
2316
3586
  }
@@ -2437,7 +3707,7 @@ function bindSourceSessionId(client, ccemSessionId, sourceSessionId) {
2437
3707
  }
2438
3708
  function openNodeSqliteDb(DatabaseSync) {
2439
3709
  const dbPath = getStateDbPath();
2440
- fs5.mkdirSync(path5.dirname(dbPath), { recursive: true });
3710
+ fs9.mkdirSync(path9.dirname(dbPath), { recursive: true });
2441
3711
  const db = new DatabaseSync(dbPath);
2442
3712
  db.exec(schemaSql());
2443
3713
  return db;
@@ -2468,7 +3738,7 @@ function getDatabaseSyncCtor() {
2468
3738
  function execSqlite3Cli(statementSql) {
2469
3739
  if (sqlite3CliAvailable == null) {
2470
3740
  try {
2471
- execFileSync("sqlite3", ["-version"], { stdio: "ignore" });
3741
+ execFileSync2("sqlite3", ["-version"], { stdio: "ignore" });
2472
3742
  sqlite3CliAvailable = true;
2473
3743
  } catch {
2474
3744
  sqlite3CliAvailable = false;
@@ -2478,8 +3748,8 @@ function execSqlite3Cli(statementSql) {
2478
3748
  throw new Error("sqlite3 CLI is unavailable and node:sqlite is not supported by this Node runtime");
2479
3749
  }
2480
3750
  const dbPath = getStateDbPath();
2481
- fs5.mkdirSync(path5.dirname(dbPath), { recursive: true });
2482
- execFileSync("sqlite3", [dbPath], {
3751
+ fs9.mkdirSync(path9.dirname(dbPath), { recursive: true });
3752
+ execFileSync2("sqlite3", [dbPath], {
2483
3753
  input: `${schemaSql()}
2484
3754
  ${statementSql}
2485
3755
  `,
@@ -2491,7 +3761,7 @@ function getStateDbPath() {
2491
3761
  if (override) {
2492
3762
  return override;
2493
3763
  }
2494
- return path5.join(os4.homedir(), ".ccem", STATE_DB_FILE_NAME);
3764
+ return path9.join(os4.homedir(), ".ccem", STATE_DB_FILE_NAME);
2495
3765
  }
2496
3766
  function schemaSql() {
2497
3767
  return `
@@ -2517,16 +3787,16 @@ function schemaSql() {
2517
3787
  `;
2518
3788
  }
2519
3789
  function discoverClaudeJsonlPath(projectDir, startedAtMs) {
2520
- const projectsDir = path5.join(os4.homedir(), ".claude", "projects");
3790
+ const projectsDir = path9.join(getCcemAgentHome("claude"), "projects");
2521
3791
  const earliestModifiedAt = startedAtMs - 15e3;
2522
3792
  for (const key of projectDirKeys(projectDir)) {
2523
- const baseDir = path5.join(projectsDir, key);
2524
- if (!fs5.existsSync(baseDir)) {
3793
+ const baseDir = path9.join(projectsDir, key);
3794
+ if (!fs9.existsSync(baseDir)) {
2525
3795
  continue;
2526
3796
  }
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 };
3797
+ const candidates = fs9.readdirSync(baseDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => {
3798
+ const fullPath = path9.join(baseDir, entry.name);
3799
+ return { path: fullPath, modifiedAt: fs9.statSync(fullPath).mtimeMs };
2530
3800
  }).filter((candidate) => candidate.modifiedAt >= earliestModifiedAt).sort((left, right) => right.modifiedAt - left.modifiedAt);
2531
3801
  if (candidates.length > 0) {
2532
3802
  return candidates[0].path;
@@ -2537,16 +3807,16 @@ function discoverClaudeJsonlPath(projectDir, startedAtMs) {
2537
3807
  function projectDirKeys(projectDir) {
2538
3808
  const candidates = [projectDir];
2539
3809
  try {
2540
- candidates.push(fs5.realpathSync(projectDir));
3810
+ candidates.push(fs9.realpathSync(projectDir));
2541
3811
  } catch {
2542
3812
  }
2543
3813
  if (process.platform === "darwin") {
2544
3814
  if (projectDir.startsWith("/private/")) {
2545
3815
  candidates.push(projectDir.slice("/private".length));
2546
3816
  } else if (projectDir.startsWith("/tmp")) {
2547
- candidates.push(path5.posix.join("/private", projectDir));
3817
+ candidates.push(path9.posix.join("/private", projectDir));
2548
3818
  } else if (projectDir.startsWith("/var/")) {
2549
- candidates.push(path5.posix.join("/private", projectDir));
3819
+ candidates.push(path9.posix.join("/private", projectDir));
2550
3820
  }
2551
3821
  }
2552
3822
  return [...new Set(candidates.map(projectDirKey))];
@@ -2555,7 +3825,7 @@ function projectDirKey(projectDir) {
2555
3825
  return projectDir.replace(/[\/\\: ]/g, "-");
2556
3826
  }
2557
3827
  function readClaudeSessionId(jsonlPath) {
2558
- const lines = fs5.readFileSync(jsonlPath, "utf8").split("\n");
3828
+ const lines = fs9.readFileSync(jsonlPath, "utf8").split("\n");
2559
3829
  for (const line of lines) {
2560
3830
  if (!line.trim()) {
2561
3831
  continue;
@@ -2587,17 +3857,6 @@ function reportTrackingError(stage, error) {
2587
3857
  }
2588
3858
 
2589
3859
  // 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
3860
  function buildEnvVars(envName, envConfig, options = {}) {
2602
3861
  const runtimeEnv = resolveEnvConfigForRuntime(envName, envConfig);
2603
3862
  const authToken = runtimeEnv.ANTHROPIC_AUTH_TOKEN ? decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN) : void 0;
@@ -2641,9 +3900,9 @@ function buildPermArgs(modeName) {
2641
3900
  return args;
2642
3901
  }
2643
3902
  function ensureSessionsDir() {
2644
- const dir = path6.join(ensureCcemDir(), "sessions");
2645
- if (!fs6.existsSync(dir)) {
2646
- fs6.mkdirSync(dir, { recursive: true });
3903
+ const dir = path10.join(ensureCcemDir(), "sessions");
3904
+ if (!fs10.existsSync(dir)) {
3905
+ fs10.mkdirSync(dir, { recursive: true });
2647
3906
  }
2648
3907
  return dir;
2649
3908
  }
@@ -2659,13 +3918,11 @@ async function launchClaude(options) {
2659
3918
  allowDesktopProxyOverride
2660
3919
  } = options;
2661
3920
  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
- }
3921
+ ensureCcemAgentHome("claude");
3922
+ const env = buildIsolatedAgentEnv(
3923
+ process.env,
3924
+ envConfig ? buildEnvVars(envName, envConfig, { allowDesktopProxyOverride }) : {}
3925
+ );
2669
3926
  delete env.CLAUDECODE;
2670
3927
  env.CCEM_RUNTIME_ID = ccemRuntimeId;
2671
3928
  env.CCEM_SESSION_ID = ccemRuntimeId;
@@ -2716,8 +3973,8 @@ async function launchClaude(options) {
2716
3973
  provenanceTracking?.stop();
2717
3974
  if (sessionId) {
2718
3975
  try {
2719
- fs6.writeFileSync(
2720
- path6.join(sessionsDir, `${sessionId}.exit`),
3976
+ fs10.writeFileSync(
3977
+ path10.join(sessionsDir, `${sessionId}.exit`),
2721
3978
  String(code ?? 0)
2722
3979
  );
2723
3980
  } catch {
@@ -2748,6 +4005,19 @@ async function launchClaude(options) {
2748
4005
  });
2749
4006
  });
2750
4007
  }
4008
+ async function launchAgentAuth(provider) {
4009
+ const env = buildIsolatedAgentEnv();
4010
+ ensureCcemAgentHome(provider, { ...process.env, CCEM_CODEX_ISOLATED: env.CCEM_CODEX_ISOLATED });
4011
+ const args = provider === "claude" ? ["auth", "login"] : env.CCEM_CODEX_ISOLATED === "1" ? ["--config", `sqlite_home=${JSON.stringify(env.CODEX_HOME)}`, "login"] : ["login"];
4012
+ await new Promise((resolve5, reject) => {
4013
+ const child = spawn2(provider, args, { env, stdio: "inherit", shell: false });
4014
+ child.once("error", reject);
4015
+ child.once("exit", (code, signal) => {
4016
+ if (code === 0) resolve5();
4017
+ else reject(new Error(`${provider} login ${signal ? `was interrupted (${signal})` : `failed (exit ${code ?? 1})`}`));
4018
+ });
4019
+ });
4020
+ }
2751
4021
 
2752
4022
  // src/permissions.ts
2753
4023
  var PERMISSION_RULE_LINE_WIDTH = 100;
@@ -2774,14 +4044,14 @@ var formatPermissionRulesForDisplay = (rules) => {
2774
4044
  }).join("\n");
2775
4045
  };
2776
4046
  var readSettings = (settingsPath) => {
2777
- if (fs7.existsSync(settingsPath)) {
4047
+ if (fs11.existsSync(settingsPath)) {
2778
4048
  try {
2779
- const content = fs7.readFileSync(settingsPath, "utf-8");
4049
+ const content = fs11.readFileSync(settingsPath, "utf-8");
2780
4050
  return JSON.parse(content);
2781
4051
  } catch {
2782
4052
  console.warn(chalk3.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${settingsPath}\uFF0C\u5C06\u521B\u5EFA\u5907\u4EFD`));
2783
4053
  const backupPath = settingsPath + ".error." + Date.now();
2784
- fs7.copyFileSync(settingsPath, backupPath);
4054
+ fs11.copyFileSync(settingsPath, backupPath);
2785
4055
  console.log(chalk3.gray(`\u5907\u4EFD\u5DF2\u4FDD\u5B58\u5230: ${backupPath}`));
2786
4056
  return {};
2787
4057
  }
@@ -2790,7 +4060,7 @@ var readSettings = (settingsPath) => {
2790
4060
  };
2791
4061
  var writeSettings = (settingsPath, config3) => {
2792
4062
  ensureClaudeDir();
2793
- fs7.writeFileSync(settingsPath, JSON.stringify(config3, null, 2) + "\n");
4063
+ fs11.writeFileSync(settingsPath, JSON.stringify(config3, null, 2) + "\n");
2794
4064
  };
2795
4065
  var mergePermissions = (existing, preset) => {
2796
4066
  const existingAllow = normalizePermissionAllowRules(existing.permissions?.allow || []);
@@ -2823,14 +4093,14 @@ var applyPermissionMode = (modeName) => {
2823
4093
  };
2824
4094
  var resetPermissions = () => {
2825
4095
  const settingsPath = getSettingsPath(true);
2826
- if (!fs7.existsSync(settingsPath)) {
4096
+ if (!fs11.existsSync(settingsPath)) {
2827
4097
  console.log(chalk3.yellow("\u6CA1\u6709\u81EA\u5B9A\u4E49\u6743\u9650\u914D\u7F6E\u9700\u8981\u91CD\u7F6E"));
2828
4098
  return;
2829
4099
  }
2830
4100
  const config3 = readSettings(settingsPath);
2831
4101
  delete config3.permissions;
2832
4102
  if (Object.keys(config3).length === 0) {
2833
- fs7.unlinkSync(settingsPath);
4103
+ fs11.unlinkSync(settingsPath);
2834
4104
  console.log(chalk3.green("\u5DF2\u5220\u9664\u914D\u7F6E\u6587\u4EF6\uFF08\u6587\u4EF6\u4E3A\u7A7A\uFF09"));
2835
4105
  } else {
2836
4106
  writeSettings(settingsPath, config3);
@@ -2840,7 +4110,7 @@ var resetPermissions = () => {
2840
4110
  };
2841
4111
  var showCurrentMode = () => {
2842
4112
  const settingsPath = getSettingsPath(true);
2843
- if (!fs7.existsSync(settingsPath)) {
4113
+ if (!fs11.existsSync(settingsPath)) {
2844
4114
  console.log(chalk3.yellow("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49\u6743\u9650"));
2845
4115
  console.log(chalk3.gray(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${settingsPath}`));
2846
4116
  return;
@@ -2899,14 +4169,14 @@ var runWithTempPermissions = async (modeName, envConfig, envName) => {
2899
4169
  };
2900
4170
 
2901
4171
  // src/environmentMutations.ts
2902
- import fs8 from "fs";
2903
- import path7 from "path";
4172
+ import fs12 from "fs";
4173
+ import path11 from "path";
2904
4174
  function nativeRuntimeStatePath() {
2905
- return path7.join(getCcemConfigDir(), "native-runtime-state.json");
4175
+ return path11.join(getCcemConfigDir(), "native-runtime-state.json");
2906
4176
  }
2907
4177
  function resolveMutationAuthority(options) {
2908
- const descriptorExists = options.descriptorExists ?? (() => fs8.existsSync(getDesktopControlDescriptorPath()));
2909
- const stateExists = options.stateExists ?? (() => fs8.existsSync(nativeRuntimeStatePath()));
4178
+ const descriptorExists = options.descriptorExists ?? (() => fs12.existsSync(getDesktopControlDescriptorPath()));
4179
+ const stateExists = options.stateExists ?? (() => fs12.existsSync(nativeRuntimeStatePath()));
2910
4180
  return { descriptorExists, stateExists };
2911
4181
  }
2912
4182
  function assertOfflineMutationIsSafe(name, stateExists) {
@@ -3006,13 +4276,13 @@ function deleteEnvironmentFromConfig(config3, name) {
3006
4276
  }
3007
4277
 
3008
4278
  // src/setup.ts
3009
- import fs9 from "fs";
4279
+ import fs13 from "fs";
3010
4280
  import chalk4 from "chalk";
3011
4281
  import { spawn as spawn3 } from "child_process";
3012
4282
  var readJsonFile = (filePath) => {
3013
- if (fs9.existsSync(filePath)) {
4283
+ if (fs13.existsSync(filePath)) {
3014
4284
  try {
3015
- const content = fs9.readFileSync(filePath, "utf-8");
4285
+ const content = fs13.readFileSync(filePath, "utf-8");
3016
4286
  return JSON.parse(content);
3017
4287
  } catch {
3018
4288
  console.warn(chalk4.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${filePath}`));
@@ -3022,11 +4292,12 @@ var readJsonFile = (filePath) => {
3022
4292
  return {};
3023
4293
  };
3024
4294
  var writeJsonFile = (filePath, data) => {
3025
- fs9.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
4295
+ fs13.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
3026
4296
  };
3027
4297
  var setupOnboarding = () => {
3028
4298
  const configPath = getGlobalClaudeConfigPath();
3029
4299
  try {
4300
+ ensureGlobalClaudeDir();
3030
4301
  const config3 = readJsonFile(configPath);
3031
4302
  if (config3.hasCompletedOnboarding === true) {
3032
4303
  console.log(chalk4.gray(" \u2713 hasCompletedOnboarding \u5DF2\u8BBE\u7F6E"));
@@ -3055,14 +4326,14 @@ var setupEnvSettings = () => {
3055
4326
  "DISABLE_ERROR_REPORTING": "1",
3056
4327
  "DISABLE_TELEMETRY": "1"
3057
4328
  };
3058
- let changed = false;
4329
+ let changed2 = false;
3059
4330
  for (const [key, value] of Object.entries(envVars)) {
3060
4331
  if (env[key] !== value) {
3061
4332
  env[key] = value;
3062
- changed = true;
4333
+ changed2 = true;
3063
4334
  }
3064
4335
  }
3065
- if (!changed) {
4336
+ if (!changed2) {
3066
4337
  console.log(chalk4.gray(" \u2713 \u73AF\u5883\u53D8\u91CF\u5DF2\u914D\u7F6E"));
3067
4338
  return true;
3068
4339
  }
@@ -3090,6 +4361,7 @@ var setupMcpTool = () => {
3090
4361
  "user"
3091
4362
  ], {
3092
4363
  stdio: "pipe",
4364
+ env: buildIsolatedAgentEnv(),
3093
4365
  shell: true
3094
4366
  });
3095
4367
  let stdout = "";
@@ -3123,7 +4395,7 @@ var setupMcpTool = () => {
3123
4395
  });
3124
4396
  };
3125
4397
  var runSetupInit = async (options = {}) => {
3126
- console.log(chalk4.bold("\n\u{1F527} Claude Code \u521D\u59CB\u5316\u8BBE\u7F6E\n"));
4398
+ console.log(chalk4.bold("\n\u{1F527} CCEM Claude Code \u521D\u59CB\u5316\u8BBE\u7F6E\n"));
3127
4399
  console.log(chalk4.cyan("1. \u8BBE\u7F6E onboarding \u72B6\u6001"));
3128
4400
  const step1 = setupOnboarding();
3129
4401
  console.log(chalk4.cyan("\n2. \u914D\u7F6E\u9690\u79C1\u8BBE\u7F6E"));
@@ -3148,9 +4420,9 @@ var runSetupInit = async (options = {}) => {
3148
4420
  };
3149
4421
 
3150
4422
  // src/skills.ts
3151
- import { execFileSync as execFileSync2 } from "child_process";
3152
- import * as fs10 from "fs";
3153
- import * as path8 from "path";
4423
+ import { execFileSync as execFileSync3 } from "child_process";
4424
+ import * as fs14 from "fs";
4425
+ import * as path12 from "path";
3154
4426
  import chalk5 from "chalk";
3155
4427
  var SKILL_GROUPS = {
3156
4428
  official: { label: "\u5B98\u65B9", icon: "\u{1F3E2}" },
@@ -3386,7 +4658,7 @@ function parseGitHubUrl(url) {
3386
4658
  repo,
3387
4659
  branch,
3388
4660
  repoPath,
3389
- repoPath ? path8.basename(repoPath) : repo
4661
+ repoPath ? path12.basename(repoPath) : repo
3390
4662
  );
3391
4663
  return { owner, repo, branch, path: repoPath };
3392
4664
  } catch {
@@ -3394,12 +4666,12 @@ function parseGitHubUrl(url) {
3394
4666
  }
3395
4667
  }
3396
4668
  function getSkillsDir() {
3397
- return path8.join(process.cwd(), ".claude", "skills");
4669
+ return path12.join(process.cwd(), ".claude", "skills");
3398
4670
  }
3399
4671
  function ensureSkillsDir() {
3400
4672
  const skillsDir = getSkillsDir();
3401
- if (!fs10.existsSync(skillsDir)) {
3402
- fs10.mkdirSync(skillsDir, { recursive: true });
4673
+ if (!fs14.existsSync(skillsDir)) {
4674
+ fs14.mkdirSync(skillsDir, { recursive: true });
3403
4675
  } else {
3404
4676
  cleanupTempDirs(skillsDir);
3405
4677
  }
@@ -3407,11 +4679,11 @@ function ensureSkillsDir() {
3407
4679
  }
3408
4680
  function cleanupTempDirs(skillsDir) {
3409
4681
  try {
3410
- const entries = fs10.readdirSync(skillsDir, { withFileTypes: true });
4682
+ const entries = fs14.readdirSync(skillsDir, { withFileTypes: true });
3411
4683
  for (const entry of entries) {
3412
4684
  if (entry.isDirectory() && entry.name.startsWith(".tmp-")) {
3413
- const tmpPath = path8.join(skillsDir, entry.name);
3414
- fs10.rmSync(tmpPath, { recursive: true });
4685
+ const tmpPath = path12.join(skillsDir, entry.name);
4686
+ fs14.rmSync(tmpPath, { recursive: true });
3415
4687
  }
3416
4688
  }
3417
4689
  } catch {
@@ -3422,27 +4694,27 @@ function downloadSkillWithGit(owner, repo, branch, repoPath, targetName) {
3422
4694
  try {
3423
4695
  validateGitHubInstallParts(owner, repo, branch, repoPath, targetName);
3424
4696
  const skillsDir = ensureSkillsDir();
3425
- const targetDir = path8.join(skillsDir, targetName);
3426
- if (fs10.existsSync(targetDir)) {
4697
+ const targetDir = path12.join(skillsDir, targetName);
4698
+ if (fs14.existsSync(targetDir)) {
3427
4699
  console.log(chalk5.yellow(`Skill "${targetName}" already exists. Updating...`));
3428
- fs10.rmSync(targetDir, { recursive: true });
4700
+ fs14.rmSync(targetDir, { recursive: true });
3429
4701
  }
3430
4702
  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}/
4703
+ tempDir = path12.join(skillsDir, `.tmp-${Date.now()}`);
4704
+ fs14.mkdirSync(tempDir, { recursive: true });
4705
+ execFileSync3("git", ["init"], { cwd: tempDir, stdio: "pipe" });
4706
+ execFileSync3("git", ["remote", "add", "origin", repoUrl], { cwd: tempDir, stdio: "pipe" });
4707
+ execFileSync3("git", ["config", "core.sparseCheckout", "true"], { cwd: tempDir, stdio: "pipe" });
4708
+ const sparseFile = path12.join(tempDir, ".git", "info", "sparse-checkout");
4709
+ fs14.mkdirSync(path12.dirname(sparseFile), { recursive: true });
4710
+ fs14.writeFileSync(sparseFile, repoPath ? `${repoPath}/
3439
4711
  ` : "*\n");
3440
- execFileSync2("git", ["pull", "--depth=1", "origin", branch], {
4712
+ execFileSync3("git", ["pull", "--depth=1", "origin", branch], {
3441
4713
  cwd: tempDir,
3442
4714
  stdio: "pipe"
3443
4715
  });
3444
- const sourceDir = repoPath ? path8.join(tempDir, repoPath) : tempDir;
3445
- if (!fs10.existsSync(sourceDir)) {
4716
+ const sourceDir = repoPath ? path12.join(tempDir, repoPath) : tempDir;
4717
+ if (!fs14.existsSync(sourceDir)) {
3446
4718
  throw new Error(`Path "${repoPath}" not found in repository`);
3447
4719
  }
3448
4720
  copyDir(sourceDir, targetDir);
@@ -3453,31 +4725,31 @@ function downloadSkillWithGit(owner, repo, branch, repoPath, targetName) {
3453
4725
  console.error(chalk5.red(`Failed to download skill: ${errMsg}`));
3454
4726
  return false;
3455
4727
  } finally {
3456
- if (tempDir && fs10.existsSync(tempDir)) {
3457
- fs10.rmSync(tempDir, { recursive: true });
4728
+ if (tempDir && fs14.existsSync(tempDir)) {
4729
+ fs14.rmSync(tempDir, { recursive: true });
3458
4730
  }
3459
4731
  }
3460
4732
  }
3461
4733
  function copyDir(src, dest) {
3462
- fs10.mkdirSync(dest, { recursive: true });
3463
- const entries = fs10.readdirSync(src, { withFileTypes: true });
4734
+ fs14.mkdirSync(dest, { recursive: true });
4735
+ const entries = fs14.readdirSync(src, { withFileTypes: true });
3464
4736
  for (const entry of entries) {
3465
4737
  if (entry.name === ".git") continue;
3466
- const srcPath = path8.join(src, entry.name);
3467
- const destPath = path8.join(dest, entry.name);
4738
+ const srcPath = path12.join(src, entry.name);
4739
+ const destPath = path12.join(dest, entry.name);
3468
4740
  if (entry.isDirectory()) {
3469
4741
  copyDir(srcPath, destPath);
3470
4742
  } else {
3471
- fs10.copyFileSync(srcPath, destPath);
4743
+ fs14.copyFileSync(srcPath, destPath);
3472
4744
  }
3473
4745
  }
3474
4746
  }
3475
4747
  function isSafeSkillName(name) {
3476
- return name.trim().length > 0 && name !== "." && name !== ".." && !name.startsWith(".") && !path8.isAbsolute(name) && !name.includes("/") && !name.includes("\\") && !name.includes("\0");
4748
+ return name.trim().length > 0 && name !== "." && name !== ".." && !name.startsWith(".") && !path12.isAbsolute(name) && !name.includes("/") && !name.includes("\\") && !name.includes("\0");
3477
4749
  }
3478
4750
  function isPathInside(childPath, parentPath) {
3479
- const relativePath = path8.relative(parentPath, childPath);
3480
- return relativePath === "" || relativePath.length > 0 && !relativePath.startsWith("..") && !path8.isAbsolute(relativePath);
4751
+ const relativePath = path12.relative(parentPath, childPath);
4752
+ return relativePath === "" || relativePath.length > 0 && !relativePath.startsWith("..") && !path12.isAbsolute(relativePath);
3481
4753
  }
3482
4754
  function addSkillFromGitHub(urlOrPreset) {
3483
4755
  const preset = SKILL_PRESETS.find((p) => p.name === urlOrPreset);
@@ -3521,7 +4793,7 @@ function addSkillFromGitHub(urlOrPreset) {
3521
4793
  }
3522
4794
  let skillName;
3523
4795
  if (parsed.path) {
3524
- skillName = path8.basename(parsed.path);
4796
+ skillName = path12.basename(parsed.path);
3525
4797
  } else {
3526
4798
  skillName = parsed.repo;
3527
4799
  }
@@ -3535,13 +4807,13 @@ function addSkillFromGitHub(urlOrPreset) {
3535
4807
  }
3536
4808
  function listInstalledSkills() {
3537
4809
  const skillsDir = getSkillsDir();
3538
- if (!fs10.existsSync(skillsDir)) {
4810
+ if (!fs14.existsSync(skillsDir)) {
3539
4811
  return [];
3540
4812
  }
3541
- const entries = fs10.readdirSync(skillsDir, { withFileTypes: true });
4813
+ const entries = fs14.readdirSync(skillsDir, { withFileTypes: true });
3542
4814
  return entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => ({
3543
4815
  name: entry.name,
3544
- path: path8.join(skillsDir, entry.name)
4816
+ path: path12.join(skillsDir, entry.name)
3545
4817
  }));
3546
4818
  }
3547
4819
  function removeSkill(name) {
@@ -3550,18 +4822,18 @@ function removeSkill(name) {
3550
4822
  return false;
3551
4823
  }
3552
4824
  const skillsDir = getSkillsDir();
3553
- const targetDir = path8.resolve(skillsDir, name);
3554
- if (!fs10.existsSync(targetDir)) {
4825
+ const targetDir = path12.resolve(skillsDir, name);
4826
+ if (!fs14.existsSync(targetDir)) {
3555
4827
  console.error(chalk5.red(`Skill "${name}" not found`));
3556
4828
  return false;
3557
4829
  }
3558
- const canonicalSkillsDir = fs10.realpathSync(skillsDir);
3559
- const canonicalTargetDir = fs10.realpathSync(targetDir);
4830
+ const canonicalSkillsDir = fs14.realpathSync(skillsDir);
4831
+ const canonicalTargetDir = fs14.realpathSync(targetDir);
3560
4832
  if (!isPathInside(canonicalTargetDir, canonicalSkillsDir)) {
3561
4833
  console.error(chalk5.red(`Refusing to remove skill outside skills directory: "${name}"`));
3562
4834
  return false;
3563
4835
  }
3564
- fs10.rmSync(targetDir, { recursive: true });
4836
+ fs14.rmSync(targetDir, { recursive: true });
3565
4837
  console.log(chalk5.green(`Removed skill "${name}"`));
3566
4838
  return true;
3567
4839
  }
@@ -3573,13 +4845,17 @@ function installFromPluginMarketplace(marketplace, packageName) {
3573
4845
  if (!isSafePluginPackage(packageName)) {
3574
4846
  throw new Error(`Invalid package name: ${packageName}`);
3575
4847
  }
4848
+ ensureCcemAgentHome("claude");
4849
+ const env = buildIsolatedAgentEnv();
3576
4850
  console.log(chalk5.cyan(`Adding marketplace: ${marketplace}...`));
3577
- execFileSync2("claude", ["plugin", "marketplace", "add", marketplace], {
3578
- stdio: "inherit"
4851
+ execFileSync3("claude", ["plugin", "marketplace", "add", marketplace], {
4852
+ stdio: "inherit",
4853
+ env
3579
4854
  });
3580
4855
  console.log(chalk5.cyan(`Installing package: ${packageName}...`));
3581
- execFileSync2("claude", ["plugin", "install", packageName], {
3582
- stdio: "inherit"
4856
+ execFileSync3("claude", ["plugin", "install", packageName], {
4857
+ stdio: "inherit",
4858
+ env
3583
4859
  });
3584
4860
  console.log(chalk5.green(`Successfully installed ${packageName}`));
3585
4861
  return true;
@@ -4112,9 +5388,9 @@ import Table3 from "cli-table3";
4112
5388
 
4113
5389
  // src/cron.ts
4114
5390
  import crypto5 from "crypto";
4115
- import * as fs11 from "fs";
5391
+ import * as fs15 from "fs";
4116
5392
  import * as os5 from "os";
4117
- import * as path9 from "path";
5393
+ import * as path13 from "path";
4118
5394
  function parseHermesNotification(value) {
4119
5395
  if (value == null) return null;
4120
5396
  const target = value;
@@ -4178,13 +5454,13 @@ var EXECUTION_PROFILES = /* @__PURE__ */ new Set([
4178
5454
  "autonomous"
4179
5455
  ]);
4180
5456
  function getCronTasksPath(baseDir = getCcemConfigDir()) {
4181
- return path9.join(baseDir, CRON_TASKS_FILE_NAME);
5457
+ return path13.join(baseDir, CRON_TASKS_FILE_NAME);
4182
5458
  }
4183
5459
  function readCronTasks(tasksPath = getCronTasksPath()) {
4184
- if (!fs11.existsSync(tasksPath)) {
5460
+ if (!fs15.existsSync(tasksPath)) {
4185
5461
  return [];
4186
5462
  }
4187
- const content = fs11.readFileSync(tasksPath, "utf-8").trim();
5463
+ const content = fs15.readFileSync(tasksPath, "utf-8").trim();
4188
5464
  if (!content) {
4189
5465
  return [];
4190
5466
  }
@@ -4199,14 +5475,14 @@ function writeCronTasks(tasks, tasksPath = getCronTasksPath()) {
4199
5475
  if (tasksPath === getCronTasksPath()) {
4200
5476
  ensureCcemDir();
4201
5477
  } else {
4202
- fs11.mkdirSync(path9.dirname(tasksPath), { recursive: true });
5478
+ fs15.mkdirSync(path13.dirname(tasksPath), { recursive: true });
4203
5479
  }
4204
5480
  const payload = { tasks };
4205
5481
  const content = `${JSON.stringify(payload, null, 2)}
4206
5482
  `;
4207
5483
  const tempPath = `${tasksPath}.${process.pid}.${Date.now()}.tmp`;
4208
- fs11.writeFileSync(tempPath, content, { encoding: "utf-8", mode: 384 });
4209
- fs11.renameSync(tempPath, tasksPath);
5484
+ fs15.writeFileSync(tempPath, content, { encoding: "utf-8", mode: 384 });
5485
+ fs15.renameSync(tempPath, tasksPath);
4210
5486
  }
4211
5487
  function validateCronExpression(cronExpression) {
4212
5488
  const fields = cronExpression.trim().split(/\s+/);
@@ -4333,10 +5609,10 @@ function deleteCronTask(selector, tasksPath = getCronTasksPath()) {
4333
5609
  }
4334
5610
  function resolveJsonInput(raw) {
4335
5611
  if (raw === "-") {
4336
- return fs11.readFileSync(0, "utf-8");
5612
+ return fs15.readFileSync(0, "utf-8");
4337
5613
  }
4338
5614
  if (raw.startsWith("@")) {
4339
- return fs11.readFileSync(path9.resolve(raw.slice(1)), "utf-8");
5615
+ return fs15.readFileSync(path13.resolve(raw.slice(1)), "utf-8");
4340
5616
  }
4341
5617
  return raw;
4342
5618
  }
@@ -4481,7 +5757,7 @@ function registerCronCommands(program2) {
4481
5757
  import chalk8 from "chalk";
4482
5758
 
4483
5759
  // src/dsh/provider.ts
4484
- import { createHash } from "crypto";
5760
+ import { createHash as createHash2 } from "crypto";
4485
5761
  var DSH_API_KEY_ENV = "CCEM_DSH_API_KEY";
4486
5762
  var DSH_PROTOCOL = "anthropic-messages";
4487
5763
  var DSH_TIERS = ["opus", "sonnet", "haiku"];
@@ -4524,7 +5800,7 @@ function collectDshModels(envName, envConfig) {
4524
5800
  }
4525
5801
  function generateProviderId(envName) {
4526
5802
  const slug = envName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24) || "env";
4527
- const hash = createHash("sha256").update(envName).digest("hex").slice(0, 12);
5803
+ const hash = createHash2("sha256").update(envName).digest("hex").slice(0, 12);
4528
5804
  return `ccem-${slug}-${hash}`;
4529
5805
  }
4530
5806
  function verifyTokenPresence(envConfig) {
@@ -4613,9 +5889,9 @@ function deriveDshProvider(envName, envConfig, options = {}) {
4613
5889
 
4614
5890
  // src/dsh/launcher.ts
4615
5891
  import { spawn as defaultSpawn } from "child_process";
4616
- import * as fs13 from "fs";
5892
+ import * as fs17 from "fs";
4617
5893
  import * as os7 from "os";
4618
- import * as path11 from "path";
5894
+ import * as path15 from "path";
4619
5895
 
4620
5896
  // src/dsh/patch.ts
4621
5897
  var IDENTIFIER_PATTERN = /^[A-Za-z0-9][\w./-]*$/;
@@ -4653,9 +5929,9 @@ function renderCordisPatch(spec) {
4653
5929
 
4654
5930
  // src/dsh/environment.ts
4655
5931
  import { execFile } from "child_process";
4656
- import * as fs12 from "fs";
5932
+ import * as fs16 from "fs";
4657
5933
  import * as os6 from "os";
4658
- import * as path10 from "path";
5934
+ import * as path14 from "path";
4659
5935
  import { promisify } from "util";
4660
5936
 
4661
5937
  // src/dsh/version.ts
@@ -4726,17 +6002,17 @@ function resolveDshRoot(env = process.env) {
4726
6002
  const inherited = env.DSH_HOME?.trim();
4727
6003
  if (inherited) return inherited;
4728
6004
  const home = env.HOME?.trim() || os6.homedir();
4729
- return path10.join(home, ".dsh");
6005
+ return path14.join(home, ".dsh");
4730
6006
  }
4731
6007
  function resolveBinOnPath(name, env = process.env, platform = process.platform) {
4732
6008
  if (name.includes("/") || platform === "win32" && name.includes("\\")) {
4733
6009
  return fileIsExecutable(name, platform) ? name : null;
4734
6010
  }
4735
- const searchDirs = (env.PATH ?? "").split(path10.delimiter).filter(Boolean);
6011
+ const searchDirs = (env.PATH ?? "").split(path14.delimiter).filter(Boolean);
4736
6012
  const extensions = platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").toLowerCase().split(";").filter(Boolean) : [""];
4737
6013
  for (const dir of searchDirs) {
4738
6014
  for (const ext of extensions) {
4739
- const candidate = path10.join(dir, name + ext);
6015
+ const candidate = path14.join(dir, name + ext);
4740
6016
  if (fileIsExecutable(candidate, platform)) return candidate;
4741
6017
  }
4742
6018
  }
@@ -4745,10 +6021,10 @@ function resolveBinOnPath(name, env = process.env, platform = process.platform)
4745
6021
  function fileIsExecutable(file, platform = process.platform) {
4746
6022
  try {
4747
6023
  if (platform === "win32") {
4748
- return fs12.statSync(file).isFile();
6024
+ return fs16.statSync(file).isFile();
4749
6025
  }
4750
- fs12.accessSync(file, fs12.constants.X_OK);
4751
- return fs12.statSync(file).isFile();
6026
+ fs16.accessSync(file, fs16.constants.X_OK);
6027
+ return fs16.statSync(file).isFile();
4752
6028
  } catch {
4753
6029
  return false;
4754
6030
  }
@@ -4766,15 +6042,15 @@ function resolveDshInvocation(deps = {}) {
4766
6042
  function resolveWindowsDshInvocation(env) {
4767
6043
  const dshFile = resolveBinOnPath("dsh", env, "win32");
4768
6044
  if (!dshFile) return null;
4769
- const ext = path10.extname(dshFile).toLowerCase();
6045
+ const ext = path14.extname(dshFile).toLowerCase();
4770
6046
  if (ext === ".exe" || ext === ".com") {
4771
6047
  return { bin: dshFile, prefix: [] };
4772
6048
  }
4773
6049
  if (ext !== ".cmd") return null;
4774
- const shimDir = path10.dirname(dshFile);
6050
+ const shimDir = path14.dirname(dshFile);
4775
6051
  const candidates = [
4776
- path10.join(shimDir, "node_modules", "@deepseek-ai", "dsh"),
4777
- path10.join(shimDir, "..", "node_modules", "@deepseek-ai", "dsh")
6052
+ path14.join(shimDir, "node_modules", "@deepseek-ai", "dsh"),
6053
+ path14.join(shimDir, "..", "node_modules", "@deepseek-ai", "dsh")
4778
6054
  ];
4779
6055
  for (const pkgDir of candidates) {
4780
6056
  const entryScript = verifyDshPackage(pkgDir);
@@ -4787,18 +6063,18 @@ function resolveWindowsDshInvocation(env) {
4787
6063
  return null;
4788
6064
  }
4789
6065
  function verifyDshPackage(pkgDir) {
4790
- const pkgJsonPath = path10.join(pkgDir, "package.json");
6066
+ const pkgJsonPath = path14.join(pkgDir, "package.json");
4791
6067
  try {
4792
- const raw = fs12.readFileSync(pkgJsonPath, "utf-8");
6068
+ const raw = fs16.readFileSync(pkgJsonPath, "utf-8");
4793
6069
  const pkg2 = JSON.parse(raw);
4794
6070
  if (pkg2.name !== "@deepseek-ai/dsh") return null;
4795
6071
  const binEntry = typeof pkg2.bin === "string" ? pkg2.bin : pkg2.bin?.dsh ?? null;
4796
6072
  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;
6073
+ const entryPath = path14.resolve(pkgDir, binEntry);
6074
+ const realEntry = fs16.realpathSync(entryPath);
6075
+ const realPkgDir = fs16.realpathSync(pkgDir);
6076
+ if (!realEntry.startsWith(realPkgDir + path14.sep) && realEntry !== realPkgDir) return null;
6077
+ if (!fs16.statSync(realEntry).isFile()) return null;
4802
6078
  return realEntry;
4803
6079
  } catch {
4804
6080
  return null;
@@ -4936,7 +6212,7 @@ var DSH_PERMISSION_MODES = [
4936
6212
  ];
4937
6213
  var DSH_PERMISSION_ENV = "DSH_PERMISSION_MODE";
4938
6214
  function cleanupTempDir(dir) {
4939
- fs13.rmSync(dir, { recursive: true, force: true });
6215
+ fs17.rmSync(dir, { recursive: true, force: true });
4940
6216
  }
4941
6217
  function signalExitCode(signal) {
4942
6218
  if (!signal) return 1;
@@ -5041,10 +6317,10 @@ async function runDshTask(options) {
5041
6317
  };
5042
6318
  }
5043
6319
  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");
6320
+ const tempDir = fs17.mkdtempSync(path15.join(os7.tmpdir(), "ccem-dsh-"));
6321
+ const patchPath = path15.join(tempDir, "cordis.ccem.patch.yml");
5046
6322
  const patchContent = renderCordisPatch(options.spec);
5047
- fs13.writeFileSync(patchPath, patchContent, { mode: 384 });
6323
+ fs17.writeFileSync(patchPath, patchContent, { mode: 384 });
5048
6324
  let exitCode = null;
5049
6325
  let signal = null;
5050
6326
  let spawnError = null;
@@ -5413,32 +6689,17 @@ Note: Use -- to separate task text from options if the task could be
5413
6689
 
5414
6690
  // src/index.ts
5415
6691
  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"));
6692
+ var __dirname2 = path16.dirname(__filename2);
6693
+ var pkgPath = path16.resolve(__dirname2, "..", "package.json");
6694
+ var pkg = JSON.parse(fs18.readFileSync(pkgPath, "utf-8"));
5419
6695
  var program = new Command();
5420
6696
  var DEFAULT_OFFICIAL_ENV = {
5421
6697
  ANTHROPIC_BASE_URL: "https://api.anthropic.com",
5422
6698
  ANTHROPIC_DEFAULT_HAIKU_MODEL: "claude-3-5-haiku-20241022",
5423
6699
  ANTHROPIC_MODEL: "opus"
5424
6700
  };
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
- ];
6701
+ var MANAGED_CLAUDE_ENV_KEYS = INHERITED_AGENT_ENV_KEYS;
5436
6702
  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
6703
  var buildResolvedEnvVars = (envName, env) => {
5443
6704
  const runtimeEnv = resolveEnvConfigForRuntime(envName, env);
5444
6705
  const authToken = runtimeEnv.ANTHROPIC_AUTH_TOKEN ? decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN) : void 0;
@@ -5447,7 +6708,7 @@ var buildResolvedEnvVars = (envName, env) => {
5447
6708
  runtimeEnv.ANTHROPIC_BASE_URL,
5448
6709
  authToken
5449
6710
  );
5450
- const resolved = {};
6711
+ const resolved = getCcemAgentEnv();
5451
6712
  if (runtimeEnv.ANTHROPIC_BASE_URL) resolved.ANTHROPIC_BASE_URL = runtimeEnv.ANTHROPIC_BASE_URL;
5452
6713
  if (authToken) resolved.ANTHROPIC_AUTH_TOKEN = authToken;
5453
6714
  if (runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL) resolved.ANTHROPIC_DEFAULT_OPUS_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL;
@@ -5458,8 +6719,15 @@ var buildResolvedEnvVars = (envName, env) => {
5458
6719
  return resolved;
5459
6720
  };
5460
6721
  var buildShellEnvCommands = (envName, env) => {
6722
+ ensureCcemAgentHome("claude");
6723
+ ensureCcemAgentHome("codex");
5461
6724
  const resolved = buildResolvedEnvVars(envName, env);
5462
- return MANAGED_CLAUDE_ENV_KEYS2.map(
6725
+ const keys = [.../* @__PURE__ */ new Set([
6726
+ ...MANAGED_CLAUDE_ENV_KEYS,
6727
+ ...Object.keys(process.env).filter(isAgentIdentityEnvKey),
6728
+ ...Object.keys(resolved)
6729
+ ])];
6730
+ return keys.filter((key) => resolved.CCEM_CODEX_ISOLATED === "1" || !SHARED_CODEX_ENV_KEYS.includes(key)).map(
5463
6731
  (key) => resolved[key] ? `export ${key}=${shellQuote(resolved[key])}` : `unset ${key}`
5464
6732
  );
5465
6733
  };
@@ -5510,13 +6778,13 @@ var recoverRegistriesFromLegacy = (registries) => {
5510
6778
  return registries;
5511
6779
  }
5512
6780
  const legacyConfigPath = getLegacyConfigPath();
5513
- if (!fs14.existsSync(legacyConfigPath)) {
6781
+ if (!fs18.existsSync(legacyConfigPath)) {
5514
6782
  return registries;
5515
6783
  }
5516
6784
  try {
5517
- const legacyRaw = JSON.parse(fs14.readFileSync(legacyConfigPath, "utf-8"));
6785
+ const legacyRaw = JSON.parse(fs18.readFileSync(legacyConfigPath, "utf-8"));
5518
6786
  const legacyRegistries = legacyRaw.registries ?? {};
5519
- let changed = false;
6787
+ let changed2 = false;
5520
6788
  const recovered = { ...registries };
5521
6789
  for (const [name, envConfig] of Object.entries(registries)) {
5522
6790
  const legacyEnvConfig = legacyRegistries[name];
@@ -5526,10 +6794,10 @@ var recoverRegistriesFromLegacy = (registries) => {
5526
6794
  const recoveredEnv = recoverEnvConfigFromLegacy(envConfig, legacyEnvConfig);
5527
6795
  if (JSON.stringify(recoveredEnv) !== JSON.stringify(envConfig)) {
5528
6796
  recovered[name] = recoveredEnv;
5529
- changed = true;
6797
+ changed2 = true;
5530
6798
  }
5531
6799
  }
5532
- return changed ? recovered : registries;
6800
+ return changed2 ? recovered : registries;
5533
6801
  } catch {
5534
6802
  return registries;
5535
6803
  }
@@ -5546,8 +6814,8 @@ var getRegistries = () => {
5546
6814
  repairedRegistries[OFFICIAL_ENV_NAME] = { ...DEFAULT_OFFICIAL_ENV };
5547
6815
  }
5548
6816
  assertOfficialEnvironmentInvariant(repairedRegistries);
5549
- const changed = Object.keys(rawRegistries).length !== Object.keys(repairedRegistries).length || JSON.stringify(rawRegistries) !== JSON.stringify(repairedRegistries);
5550
- if (changed) {
6817
+ const changed2 = Object.keys(rawRegistries).length !== Object.keys(repairedRegistries).length || JSON.stringify(rawRegistries) !== JSON.stringify(repairedRegistries);
6818
+ if (changed2) {
5551
6819
  config2.set("registries", repairedRegistries);
5552
6820
  }
5553
6821
  return repairedRegistries;
@@ -5717,15 +6985,15 @@ var switchEnvironment = async (name) => {
5717
6985
  exportCmds.forEach((cmd) => console.log(cmd));
5718
6986
  }
5719
6987
  };
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");
6988
+ var getSessionsFilePath = () => path16.join(getCcemConfigDir(), "sessions.json");
6989
+ var getRuntimeStateFilePath = () => path16.join(getCcemConfigDir(), "runtime-state.json");
6990
+ var getBotBindRequestFilePath = () => path16.join(getCcemConfigDir(), "bot-bind-requests.jsonl");
5723
6991
  var parseJsonFile = (filePath) => {
5724
- if (!fs14.existsSync(filePath)) {
6992
+ if (!fs18.existsSync(filePath)) {
5725
6993
  return null;
5726
6994
  }
5727
6995
  try {
5728
- return JSON.parse(fs14.readFileSync(filePath, "utf-8"));
6996
+ return JSON.parse(fs18.readFileSync(filePath, "utf-8"));
5729
6997
  } catch {
5730
6998
  return null;
5731
6999
  }
@@ -5817,8 +7085,8 @@ var resolveBotBindRuntimeId = (explicitRuntimeId) => {
5817
7085
  };
5818
7086
  var appendBotBindRequest = (payload) => {
5819
7087
  const requestPath = getBotBindRequestFilePath();
5820
- fs14.mkdirSync(path12.dirname(requestPath), { recursive: true });
5821
- fs14.appendFileSync(requestPath, `${JSON.stringify(payload)}
7088
+ fs18.mkdirSync(path16.dirname(requestPath), { recursive: true });
7089
+ fs18.appendFileSync(requestPath, `${JSON.stringify(payload)}
5822
7090
  `, "utf-8");
5823
7091
  return requestPath;
5824
7092
  };
@@ -6033,6 +7301,8 @@ program.command("env").description("Output environment variables for shell eval"
6033
7301
  const current = config2.get("current");
6034
7302
  const env = registries[current];
6035
7303
  if (!env) return;
7304
+ ensureCcemAgentHome("claude");
7305
+ ensureCcemAgentHome("codex");
6036
7306
  const outputEnv = buildResolvedEnvVars(current, env);
6037
7307
  if (options.json) {
6038
7308
  console.log(JSON.stringify(outputEnv, null, 2));
@@ -6048,9 +7318,9 @@ program.command("run <command...>").description("Run a command with the current
6048
7318
  console.error(chalk9.red("No environment configuration found."));
6049
7319
  process.exit(1);
6050
7320
  }
6051
- const env = { ...process.env };
6052
- clearManagedClaudeEnv(env);
6053
- Object.assign(env, buildResolvedEnvVars(current, envConfig));
7321
+ ensureCcemAgentHome("claude");
7322
+ ensureCcemAgentHome("codex");
7323
+ const env = buildIsolatedAgentEnv(process.env, buildResolvedEnvVars(current, envConfig));
6054
7324
  const [cmd, ...args] = command;
6055
7325
  const child = spawn4(cmd, args, {
6056
7326
  env,
@@ -6061,6 +7331,12 @@ program.command("run <command...>").description("Run a command with the current
6061
7331
  process.exit(code ?? 0);
6062
7332
  });
6063
7333
  });
7334
+ program.command("auth <provider>").description("Sign in using the selected Claude Code or Codex profile").action(async (provider) => {
7335
+ if (provider !== "claude" && provider !== "codex") {
7336
+ program.error("Provider must be claude or codex");
7337
+ }
7338
+ await launchAgentAuth(provider);
7339
+ });
6064
7340
  registerCronCommands(program);
6065
7341
  var setupCmd = program.command("setup").description("Setup commands for permanent configurations");
6066
7342
  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 +7389,12 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
6113
7389
  const newConfigPath = getCcemConfigPath();
6114
7390
  const legacyConfigPath = getLegacyConfigPath();
6115
7391
  console.log(chalk9.cyan("\n\u{1F504} \u914D\u7F6E\u8FC1\u79FB\n"));
6116
- if (!fs14.existsSync(legacyConfigPath)) {
7392
+ if (!fs18.existsSync(legacyConfigPath)) {
6117
7393
  console.log(chalk9.yellow("\u672A\u627E\u5230\u65E7\u7248\u914D\u7F6E\u6587\u4EF6"));
6118
7394
  console.log(chalk9.gray(` \u65E7\u8DEF\u5F84: ${legacyConfigPath}`));
6119
7395
  return;
6120
7396
  }
6121
- if (fs14.existsSync(newConfigPath) && !options.force) {
7397
+ if (fs18.existsSync(newConfigPath) && !options.force) {
6122
7398
  console.log(chalk9.green("\u2713 \u914D\u7F6E\u5DF2\u5728\u65B0\u8DEF\u5F84"));
6123
7399
  console.log(chalk9.gray(` \u8DEF\u5F84: ${newConfigPath}`));
6124
7400
  console.log(chalk9.gray("\n\u4F7F\u7528 --force \u5F3A\u5236\u91CD\u65B0\u8FC1\u79FB"));
@@ -6126,7 +7402,7 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
6126
7402
  }
6127
7403
  try {
6128
7404
  ensureCcemDir();
6129
- const legacyRaw = JSON.parse(fs14.readFileSync(legacyConfigPath, "utf-8"));
7405
+ const legacyRaw = JSON.parse(fs18.readFileSync(legacyConfigPath, "utf-8"));
6130
7406
  const migrated = normalizeCcemConfig(legacyRaw);
6131
7407
  if (!migrated.registries[OFFICIAL_ENV_NAME]) {
6132
7408
  migrated.registries[OFFICIAL_ENV_NAME] = { ...DEFAULT_OFFICIAL_ENV };
@@ -6137,10 +7413,10 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
6137
7413
  console.log(chalk9.gray(` \u4ECE: ${legacyConfigPath}`));
6138
7414
  console.log(chalk9.gray(` \u5230: ${newConfigPath}`));
6139
7415
  if (options.clean) {
6140
- fs14.unlinkSync(legacyConfigPath);
6141
- const legacyDir = path12.dirname(legacyConfigPath);
7416
+ fs18.unlinkSync(legacyConfigPath);
7417
+ const legacyDir = path16.dirname(legacyConfigPath);
6142
7418
  try {
6143
- fs14.rmdirSync(legacyDir);
7419
+ fs18.rmdirSync(legacyDir);
6144
7420
  } catch {
6145
7421
  }
6146
7422
  console.log(chalk9.green("\u2713 \u5DF2\u5220\u9664\u65E7\u914D\u7F6E\u6587\u4EF6"));
@@ -6149,15 +7425,15 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
6149
7425
  console.error(chalk9.red(`\u2717 \u8FC1\u79FB\u5931\u8D25: ${err}`));
6150
7426
  }
6151
7427
  });
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() {
7428
+ 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
7429
  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 });
7430
+ const skillDir = path16.join(ensureCcemAgentHome("claude"), "skills");
7431
+ const targetPath = path16.join(skillDir, "ccem-cron.md");
7432
+ if (!fs18.existsSync(skillDir)) {
7433
+ fs18.mkdirSync(skillDir, { recursive: true });
6158
7434
  console.log(chalk9.gray(`\u521B\u5EFA\u76EE\u5F55: ${skillDir}`));
6159
7435
  }
6160
- if (fs14.existsSync(targetPath) && !options.force) {
7436
+ if (fs18.existsSync(targetPath) && !options.force) {
6161
7437
  const { overwrite } = await inquirer.prompt([
6162
7438
  {
6163
7439
  type: "confirm",
@@ -6171,21 +7447,21 @@ setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 Claude
6171
7447
  return;
6172
7448
  }
6173
7449
  }
6174
- fs14.writeFileSync(targetPath, CCEM_CRON_SKILL_CONTENT, "utf-8");
7450
+ fs18.writeFileSync(targetPath, CCEM_CRON_SKILL_CONTENT, "utf-8");
6175
7451
  console.log(chalk9.green(`\u2713 \u5DF2\u5B89\u88C5 ccem-cron skill`));
6176
7452
  console.log(chalk9.gray(` \u8DEF\u5F84: ${targetPath}`));
6177
7453
  console.log(chalk9.cyan(`
6178
7454
  \u5728 Claude Code \u4E2D\u4F7F\u7528 /ccem-cron \u5373\u53EF\u8C03\u7528\u6B64 skill`));
6179
7455
  });
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() {
7456
+ 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
7457
  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 });
7458
+ const skillDir = path16.join(ensureCcemAgentHome("claude"), "skills");
7459
+ const targetPath = path16.join(skillDir, "ccem-bot-bind.md");
7460
+ if (!fs18.existsSync(skillDir)) {
7461
+ fs18.mkdirSync(skillDir, { recursive: true });
6186
7462
  console.log(chalk9.gray(`\u521B\u5EFA\u76EE\u5F55: ${skillDir}`));
6187
7463
  }
6188
- if (fs14.existsSync(targetPath) && !options.force) {
7464
+ if (fs18.existsSync(targetPath) && !options.force) {
6189
7465
  const { overwrite } = await inquirer.prompt([
6190
7466
  {
6191
7467
  type: "confirm",
@@ -6199,7 +7475,7 @@ setupCmd.command("bot-bind").description("\u5B89\u88C5 ccem-bot-bind skill \u523
6199
7475
  return;
6200
7476
  }
6201
7477
  }
6202
- fs14.writeFileSync(targetPath, CCEM_BOT_BIND_SKILL_CONTENT, "utf-8");
7478
+ fs18.writeFileSync(targetPath, CCEM_BOT_BIND_SKILL_CONTENT, "utf-8");
6203
7479
  console.log(chalk9.green(`\u2713 \u5DF2\u5B89\u88C5 ccem-bot-bind skill`));
6204
7480
  console.log(chalk9.gray(` \u8DEF\u5F84: ${targetPath}`));
6205
7481
  console.log(chalk9.cyan(`
@@ -6376,7 +7652,7 @@ desktopCmd.command("send <runtimeId>").description("Send input to a CCEM Desktop
6376
7652
  const opts = this.opts();
6377
7653
  const result = await requestDesktopControl("ccem.workspace.sendInput", {
6378
7654
  runtimeId,
6379
- clientMessageId: opts.messageId?.trim() || `ccem-cli-${randomUUID()}`,
7655
+ clientMessageId: opts.messageId?.trim() || `ccem-cli-${randomUUID4()}`,
6380
7656
  text: opts.text,
6381
7657
  displayText: opts.displayText ?? null
6382
7658
  });