ccem 2.95.0 → 2.97.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.
- package/dist/index.js +1128 -362
- 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
|
|
9
|
-
import
|
|
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
|
|
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:
|
|
240
|
+
revision: changed2 ? bumpProfileRevision(profile.revision) : profile.revision,
|
|
241
241
|
bindings,
|
|
242
242
|
allowedEnvs
|
|
243
243
|
};
|
|
@@ -700,16 +700,22 @@ var getPermissionModeNames = () => {
|
|
|
700
700
|
|
|
701
701
|
// ../../packages/core/dist/index.js
|
|
702
702
|
import crypto2 from "crypto";
|
|
703
|
-
import
|
|
703
|
+
import fs5 from "fs";
|
|
704
704
|
import os2 from "os";
|
|
705
|
-
import
|
|
706
|
-
import
|
|
705
|
+
import path5 from "path";
|
|
706
|
+
import fs4 from "fs";
|
|
707
707
|
import os from "os";
|
|
708
|
-
import
|
|
709
|
-
import { randomUUID } from "crypto";
|
|
708
|
+
import path4 from "path";
|
|
709
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
710
710
|
import fs from "fs";
|
|
711
711
|
import path from "path";
|
|
712
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";
|
|
713
719
|
import crypto from "crypto";
|
|
714
720
|
function processAlive(pid) {
|
|
715
721
|
try {
|
|
@@ -771,8 +777,8 @@ function persistedProcesses(home) {
|
|
|
771
777
|
const file = path.join(home, ".ccem", name);
|
|
772
778
|
let value;
|
|
773
779
|
try {
|
|
774
|
-
const
|
|
775
|
-
if (!
|
|
780
|
+
const stat22 = fs.lstatSync(file);
|
|
781
|
+
if (!stat22.isFile() || stat22.isSymbolicLink()) continue;
|
|
776
782
|
value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
777
783
|
} catch (error) {
|
|
778
784
|
if (error.code === "ENOENT") continue;
|
|
@@ -890,6 +896,690 @@ function assertNoLegacyAgentWriters(provider, home, source, destination) {
|
|
|
890
896
|
}
|
|
891
897
|
}
|
|
892
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 METADATA = ".claude-plugin";
|
|
1258
|
+
var LAYOUT = ".ccem-layout-v2";
|
|
1259
|
+
var IGNORED = /* @__PURE__ */ new Set([".git", ".in_use", ".orphaned_at", MARKER]);
|
|
1260
|
+
function absolute(value) {
|
|
1261
|
+
return typeof value === "string" && path3.isAbsolute(value) && !value.split(/[\\/]/).includes("..");
|
|
1262
|
+
}
|
|
1263
|
+
function readLinks(target) {
|
|
1264
|
+
const document = readDocument(path3.join(target, CLAUDE_PLUGIN_LINK_LEDGER), { version: 1, plugins: {} });
|
|
1265
|
+
if (document.value.version !== 1 || Object.keys(document.value).some((key) => !["version", "plugins"].includes(key))) {
|
|
1266
|
+
throw new Error("Unsupported plugin links ledger");
|
|
1267
|
+
}
|
|
1268
|
+
for (const [id, rows] of Object.entries(object(document.value.plugins, "plugin links ledger"))) {
|
|
1269
|
+
pluginId(id);
|
|
1270
|
+
if (!Array.isArray(rows) || !rows.length) throw new Error("Invalid plugin link identities");
|
|
1271
|
+
const seen = [];
|
|
1272
|
+
for (const entry of rows) {
|
|
1273
|
+
const row = object(entry, "plugin link identity");
|
|
1274
|
+
const key = identity(row);
|
|
1275
|
+
const fields = row.local === true ? ["scope", "projectPath", "local"] : ["scope", "projectPath", "sourcePath", "installPath", "version"];
|
|
1276
|
+
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");
|
|
1277
|
+
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))) {
|
|
1278
|
+
throw new Error("Invalid managed plugin link");
|
|
1279
|
+
}
|
|
1280
|
+
if (row.local !== true) {
|
|
1281
|
+
const [name, market] = id.split("@");
|
|
1282
|
+
const suffix = `.ccem-linked-${createHash("sha256").update(row.sourcePath).digest("hex").slice(0, 8)}`;
|
|
1283
|
+
if (!row.version.endsWith(suffix) || row.installPath !== path3.resolve(target, "plugins/cache", market, name, row.version)) {
|
|
1284
|
+
throw new Error("Managed plugin link escapes its CCEM cache");
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
seen.push(key);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
return document;
|
|
1291
|
+
}
|
|
1292
|
+
function children(root) {
|
|
1293
|
+
return fs3.readdirSync(root).filter((name) => !IGNORED.has(name)).sort();
|
|
1294
|
+
}
|
|
1295
|
+
function metadataChildren(root) {
|
|
1296
|
+
return fs3.readdirSync(root).filter((name) => name !== "marketplace.json").sort();
|
|
1297
|
+
}
|
|
1298
|
+
function linkChildren(root, legacy = false) {
|
|
1299
|
+
return children(root).flatMap((name) => {
|
|
1300
|
+
if (name !== METADATA || legacy && stat(path3.join(root, name))?.isSymbolicLink()) return [name];
|
|
1301
|
+
return metadataChildren(path3.join(root, name)).map((child) => path3.join(name, child));
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
function validateCode(file, store, protectedCatalogues, ancestors = /* @__PURE__ */ new Set(), metadata = false) {
|
|
1305
|
+
const resolved = fs3.realpathSync(file);
|
|
1306
|
+
for (const candidate of [path3.resolve(file), resolved]) {
|
|
1307
|
+
if (!contained(store, candidate)) throw new Error("Linked plugin code escapes the official plugin store");
|
|
1308
|
+
rejectPrivateData(store, candidate);
|
|
1309
|
+
const parts = path3.relative(store, candidate).split(path3.sep);
|
|
1310
|
+
if (parts.length < 2 || protectedCatalogues.has(candidate) || parts.some((part) => [".in_use", ".orphaned_at", MARKER].includes(part))) {
|
|
1311
|
+
throw new Error("Linked plugin code cannot expose official plugin metadata or runtime markers");
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
if (ancestors.has(resolved)) throw new Error("Linked plugin code has a symlink cycle");
|
|
1315
|
+
const info = fs3.statSync(resolved);
|
|
1316
|
+
if (info.isDirectory()) {
|
|
1317
|
+
const next = new Set(ancestors).add(resolved);
|
|
1318
|
+
const names = metadata ? metadataChildren(resolved) : ancestors.size === 0 ? children(resolved) : fs3.readdirSync(resolved).sort();
|
|
1319
|
+
for (const name of names) validateCode(path3.join(resolved, name), store, protectedCatalogues, next, ancestors.size === 0 && name === METADATA);
|
|
1320
|
+
} else if (!info.isFile()) throw new Error("Linked plugin code is not a regular file or directory");
|
|
1321
|
+
}
|
|
1322
|
+
function equalCopy(source, target, top = true, metadata = false) {
|
|
1323
|
+
noLinks(target);
|
|
1324
|
+
const from = fs3.statSync(source);
|
|
1325
|
+
const to = stat(target);
|
|
1326
|
+
if (!to || from.isDirectory() !== to.isDirectory() || from.isFile() !== to.isFile()) return false;
|
|
1327
|
+
if (from.isFile()) return fs3.readFileSync(source).equals(fs3.readFileSync(target)) && (from.mode & 73) === (to.mode & 73);
|
|
1328
|
+
const names = metadata ? metadataChildren(source) : children(source);
|
|
1329
|
+
const local = metadata ? metadataChildren(target) : children(target);
|
|
1330
|
+
return JSON.stringify(names) === JSON.stringify(local) && names.every((name) => equalCopy(path3.join(source, name), path3.join(target, name), false, top && name === METADATA));
|
|
1331
|
+
}
|
|
1332
|
+
function rootMarker(target, source) {
|
|
1333
|
+
noLinks(target);
|
|
1334
|
+
const marker = readDocument(path3.join(target, MARKER));
|
|
1335
|
+
if (stat(target) && (!stat(target)?.isDirectory() || marker.value.version !== 1 || marker.value.source !== source || Object.keys(marker.value).some((key) => !["version", "source"].includes(key)))) {
|
|
1336
|
+
throw new Error("Existing plugin link root is not managed by CCEM");
|
|
1337
|
+
}
|
|
1338
|
+
return marker;
|
|
1339
|
+
}
|
|
1340
|
+
function recoverPublished(row, key, id, sourceRoot, targetRoot) {
|
|
1341
|
+
const [name, market] = id.split("@");
|
|
1342
|
+
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;
|
|
1343
|
+
const marker = readDocument(path3.join(row.installPath, MARKER));
|
|
1344
|
+
if (marker.value.version !== 1 || !absolute(marker.value.source) || !contained(sourceRoot, marker.value.source)) return;
|
|
1345
|
+
rejectPrivateData(sourceRoot, marker.value.source);
|
|
1346
|
+
const suffix = `.ccem-linked-${createHash("sha256").update(marker.value.source).digest("hex").slice(0, 8)}`;
|
|
1347
|
+
if (!row.version.endsWith(suffix) || row.version.length === suffix.length) return;
|
|
1348
|
+
rootMarker(row.installPath, marker.value.source);
|
|
1349
|
+
if (!ownedChildren(row.installPath, marker.value.source)) return;
|
|
1350
|
+
return { ...key, sourcePath: marker.value.source, installPath: row.installPath, version: row.version };
|
|
1351
|
+
}
|
|
1352
|
+
function planRoot(source, target) {
|
|
1353
|
+
const marker = rootMarker(target, source);
|
|
1354
|
+
let changed2 = marker.before === void 0;
|
|
1355
|
+
noLinks(path3.join(target, METADATA));
|
|
1356
|
+
const wanted = new Set(linkChildren(source));
|
|
1357
|
+
if (stat(target)) for (const name of linkChildren(target)) {
|
|
1358
|
+
const child = path3.join(target, name);
|
|
1359
|
+
if (!stat(child)?.isSymbolicLink() || fs3.readlinkSync(child) !== path3.join(source, name)) {
|
|
1360
|
+
throw new Error("CCEM plugin code was changed locally; keeping it");
|
|
1361
|
+
}
|
|
1362
|
+
if (!wanted.has(name)) changed2 = true;
|
|
1363
|
+
}
|
|
1364
|
+
if (!stat(path3.join(target, METADATA))) changed2 = true;
|
|
1365
|
+
for (const name of wanted) if (!stat(path3.join(target, name))) changed2 = true;
|
|
1366
|
+
return { source, target, changed: changed2 };
|
|
1367
|
+
}
|
|
1368
|
+
function ownedChildren(target, source) {
|
|
1369
|
+
if (!stat(target)) return false;
|
|
1370
|
+
const legacy = !path3.basename(target).includes(`${LAYOUT}.ccem-linked-`);
|
|
1371
|
+
const metadata = stat(path3.join(target, METADATA));
|
|
1372
|
+
if (metadata && !(legacy ? metadata.isSymbolicLink() : metadata.isDirectory())) return false;
|
|
1373
|
+
if (!legacy && stat(path3.join(target, METADATA, "marketplace.json"))) return false;
|
|
1374
|
+
return linkChildren(target, legacy).every((name) => {
|
|
1375
|
+
const child = path3.join(target, name);
|
|
1376
|
+
return stat(child)?.isSymbolicLink() && fs3.readlinkSync(child) === path3.join(source, name);
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
function publishRoot(root) {
|
|
1380
|
+
if (!root.changed) return;
|
|
1381
|
+
planRoot(root.source, root.target);
|
|
1382
|
+
const fresh = !stat(root.target);
|
|
1383
|
+
const directory = fresh ? `${root.target}.ccem-${randomUUID2()}.tmp` : root.target;
|
|
1384
|
+
privateDirectory(directory);
|
|
1385
|
+
try {
|
|
1386
|
+
if (fresh) fs3.writeFileSync(path3.join(directory, MARKER), `${JSON.stringify({ version: 1, source: root.source })}
|
|
1387
|
+
`, { flag: "wx", mode: 384 });
|
|
1388
|
+
const wanted = new Set(linkChildren(root.source));
|
|
1389
|
+
privateDirectory(path3.join(directory, METADATA));
|
|
1390
|
+
for (const name of linkChildren(directory)) if (!wanted.has(name)) {
|
|
1391
|
+
const child = path3.join(directory, name);
|
|
1392
|
+
if (!stat(child)?.isSymbolicLink() || fs3.readlinkSync(child) !== path3.join(root.source, name)) throw new Error("Plugin link changed during preparation");
|
|
1393
|
+
fs3.unlinkSync(child);
|
|
1394
|
+
}
|
|
1395
|
+
for (const name of wanted) {
|
|
1396
|
+
const child = path3.join(directory, name);
|
|
1397
|
+
if (stat(child)) continue;
|
|
1398
|
+
const original = path3.join(root.source, name);
|
|
1399
|
+
fs3.symlinkSync(original, child, fs3.statSync(original).isDirectory() ? "dir" : "file");
|
|
1400
|
+
}
|
|
1401
|
+
if (fresh) {
|
|
1402
|
+
noLinks(root.target);
|
|
1403
|
+
if (stat(root.target)) throw new Error("Plugin link root changed during preparation");
|
|
1404
|
+
fs3.renameSync(directory, root.target);
|
|
1405
|
+
}
|
|
1406
|
+
} finally {
|
|
1407
|
+
if (fresh) fs3.rmSync(directory, { recursive: true, force: true });
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
function changed(document) {
|
|
1411
|
+
return document.before === void 0 ? Object.keys(document.value).length > 0 : JSON.stringify(JSON.parse(document.before)) !== JSON.stringify(document.value);
|
|
1412
|
+
}
|
|
1413
|
+
function planLinks(sourceHome, targetHome) {
|
|
1414
|
+
const imports = readLedger(targetHome);
|
|
1415
|
+
if (!Object.keys(imports.value.seen).length) return { documents: [], targets: [], roots: [], changed: false };
|
|
1416
|
+
const sourceRegistry = readSource(sourceHome);
|
|
1417
|
+
const sourcePlugins = registry(sourceRegistry);
|
|
1418
|
+
const targetRegistry = readSource(targetHome);
|
|
1419
|
+
const targetPlugins = registry(targetRegistry);
|
|
1420
|
+
const ledger = readLinks(targetHome);
|
|
1421
|
+
const sourceRoot = fs3.realpathSync(path3.join(sourceHome, "plugins"));
|
|
1422
|
+
noLinks(path3.join(sourceHome, "plugins"));
|
|
1423
|
+
const targetRoot = path3.resolve(targetHome, "plugins");
|
|
1424
|
+
noLinks(targetRoot);
|
|
1425
|
+
if (sourceRoot === targetRoot || contained(sourceRoot, targetRoot) || contained(targetRoot, sourceRoot)) throw new Error("Plugin stores must not overlap");
|
|
1426
|
+
for (const choices of Object.values(ledger.value.plugins)) for (const choice of choices) if (!("local" in choice)) {
|
|
1427
|
+
if (!contained(sourceRoot, choice.sourcePath)) throw new Error("Managed plugin source escapes the official store");
|
|
1428
|
+
rejectPrivateData(sourceRoot, choice.sourcePath);
|
|
1429
|
+
}
|
|
1430
|
+
const sourceMarkets = readDocument(path3.join(sourceRoot, "known_marketplaces.json"));
|
|
1431
|
+
const targetMarkets = readDocument(path3.join(targetRoot, "known_marketplaces.json"));
|
|
1432
|
+
const protectedCatalogues = /* @__PURE__ */ new Set();
|
|
1433
|
+
for (const market of Object.values(sourceMarkets.value)) {
|
|
1434
|
+
const location = market && typeof market === "object" ? market.installLocation : void 0;
|
|
1435
|
+
if (absolute(location) && contained(sourceRoot, location)) {
|
|
1436
|
+
const file = path3.join(location, ".claude-plugin/marketplace.json");
|
|
1437
|
+
if (fs3.existsSync(file)) protectedCatalogues.add(fs3.realpathSync(file));
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
const documents = [imports, sourceRegistry, targetRegistry, ledger, sourceMarkets, targetMarkets];
|
|
1441
|
+
const catalogues = /* @__PURE__ */ new Map();
|
|
1442
|
+
const roots = /* @__PURE__ */ new Map();
|
|
1443
|
+
function catalogue(markets, market, store, mutable) {
|
|
1444
|
+
if (!Object.hasOwn(markets.value, market)) return void 0;
|
|
1445
|
+
const location = relocated(object(markets.value[market], "marketplace").installLocation, store, store).source;
|
|
1446
|
+
const file = path3.join(location, ".claude-plugin/marketplace.json");
|
|
1447
|
+
const document = catalogues.get(file) ?? readDocument(file);
|
|
1448
|
+
if (!Array.isArray(document.value.plugins)) throw new Error("Invalid marketplace catalogue");
|
|
1449
|
+
if (!catalogues.has(file)) {
|
|
1450
|
+
documents.push(document);
|
|
1451
|
+
if (mutable) catalogues.set(file, document);
|
|
1452
|
+
}
|
|
1453
|
+
return { document, location };
|
|
1454
|
+
}
|
|
1455
|
+
for (const [id, identities] of Object.entries(imports.value.seen)) {
|
|
1456
|
+
const choices = ledger.value.plugins[id] ??= [];
|
|
1457
|
+
for (const key of identities) {
|
|
1458
|
+
let index = choices.findIndex((choice) => same(choice, key));
|
|
1459
|
+
let old = index < 0 ? void 0 : choices[index];
|
|
1460
|
+
if (old && "local" in old) continue;
|
|
1461
|
+
const local = targetPlugins[id]?.find((row) => same(identity(row), key));
|
|
1462
|
+
const detach = () => {
|
|
1463
|
+
if (index < 0) {
|
|
1464
|
+
index = choices.length;
|
|
1465
|
+
choices.push({ ...key, local: true });
|
|
1466
|
+
} else choices[index] = { ...key, local: true };
|
|
1467
|
+
};
|
|
1468
|
+
if (!local) {
|
|
1469
|
+
detach();
|
|
1470
|
+
continue;
|
|
1471
|
+
}
|
|
1472
|
+
if (!old || local.installPath !== old.installPath || local.version !== old.version) {
|
|
1473
|
+
const recovered = recoverPublished(local, key, id, sourceRoot, targetRoot);
|
|
1474
|
+
if (recovered) {
|
|
1475
|
+
old = recovered;
|
|
1476
|
+
if (index < 0) {
|
|
1477
|
+
index = choices.length;
|
|
1478
|
+
choices.push(recovered);
|
|
1479
|
+
} else choices[index] = recovered;
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
const registryMoved = old && (local.installPath !== old.installPath || local.version !== old.version);
|
|
1483
|
+
const official = sourcePlugins[id]?.find((row) => same(identity(row), key));
|
|
1484
|
+
if (!official) {
|
|
1485
|
+
if (registryMoved) detach();
|
|
1486
|
+
continue;
|
|
1487
|
+
}
|
|
1488
|
+
const original = relocated(official.installPath, sourceRoot, targetRoot);
|
|
1489
|
+
const [name, market] = id.split("@");
|
|
1490
|
+
const fromCatalogue = catalogue(sourceMarkets, market, sourceRoot, false);
|
|
1491
|
+
const toCatalogue = catalogue(targetMarkets, market, targetRoot, true);
|
|
1492
|
+
const fromEntry = fromCatalogue?.document.value.plugins?.find((entry) => entry.name === name);
|
|
1493
|
+
const toEntry = toCatalogue?.document.value.plugins?.find((entry) => entry.name === name);
|
|
1494
|
+
const entrySource = fromEntry?.source;
|
|
1495
|
+
const localSource = typeof entrySource === "string" ? entrySource : entrySource && typeof entrySource === "object" && ["directory", "file"].includes(String(entrySource.source)) ? entrySource.path : void 0;
|
|
1496
|
+
let code = original.source;
|
|
1497
|
+
let legacyCode = original.target;
|
|
1498
|
+
let expectedCatalogueSource;
|
|
1499
|
+
let actualCatalogueSource;
|
|
1500
|
+
if (localSource !== void 0) {
|
|
1501
|
+
if (typeof localSource !== "string" || !fromCatalogue || !toCatalogue || !toEntry) throw new Error("Invalid local plugin catalogue source");
|
|
1502
|
+
code = path3.resolve(fromCatalogue.location, localSource);
|
|
1503
|
+
if (!contained(sourceRoot, code)) throw new Error("Local plugin source escapes the official store");
|
|
1504
|
+
legacyCode = path3.isAbsolute(localSource) ? relocated(localSource, sourceRoot, targetRoot).target : path3.resolve(toCatalogue.location, localSource);
|
|
1505
|
+
if (!contained(targetRoot, legacyCode)) throw new Error("Local plugin destination escapes its store");
|
|
1506
|
+
expectedCatalogueSource = old ? old.installPath : path3.isAbsolute(localSource) ? legacyCode : localSource;
|
|
1507
|
+
actualCatalogueSource = typeof toEntry.source === "string" ? toEntry.source : object(toEntry.source, "local catalogue source").path;
|
|
1508
|
+
}
|
|
1509
|
+
if (!fs3.existsSync(code)) {
|
|
1510
|
+
if (registryMoved) detach();
|
|
1511
|
+
continue;
|
|
1512
|
+
}
|
|
1513
|
+
code = fs3.realpathSync(code);
|
|
1514
|
+
validateCode(code, sourceRoot, protectedCatalogues);
|
|
1515
|
+
const sourceVersion = typeof official.version === "string" ? official.version : path3.basename(original.source);
|
|
1516
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._+-]*$/.test(sourceVersion)) throw new Error("Invalid plugin version");
|
|
1517
|
+
const version = `${sourceVersion}${LAYOUT}.ccem-linked-${createHash("sha256").update(code).digest("hex").slice(0, 8)}`;
|
|
1518
|
+
const destination = path3.join(targetRoot, "cache", market, name, version);
|
|
1519
|
+
if (registryMoved) {
|
|
1520
|
+
if (local.installPath === destination && local.version === version && stat(destination)) rootMarker(destination, code);
|
|
1521
|
+
else {
|
|
1522
|
+
detach();
|
|
1523
|
+
continue;
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
if (old && !registryMoved) {
|
|
1527
|
+
rootMarker(old.installPath, old.sourcePath);
|
|
1528
|
+
if (!ownedChildren(old.installPath, old.sourcePath)) {
|
|
1529
|
+
detach();
|
|
1530
|
+
continue;
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
if (localSource !== void 0 && actualCatalogueSource !== expectedCatalogueSource) {
|
|
1534
|
+
const recovered = typeof actualCatalogueSource === "string" ? recoverPublished({
|
|
1535
|
+
installPath: actualCatalogueSource,
|
|
1536
|
+
version: path3.basename(actualCatalogueSource)
|
|
1537
|
+
}, key, id, sourceRoot, targetRoot) : void 0;
|
|
1538
|
+
if (!recovered) {
|
|
1539
|
+
detach();
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
if (!old) {
|
|
1544
|
+
const recovering = local.installPath === destination && local.version === version && stat(destination);
|
|
1545
|
+
if (recovering) rootMarker(destination, code);
|
|
1546
|
+
else {
|
|
1547
|
+
validateCode(original.source, sourceRoot, protectedCatalogues);
|
|
1548
|
+
if (local.installPath !== original.target || local.version !== official.version || !equalCopy(original.source, original.target) || !equalCopy(code, legacyCode)) {
|
|
1549
|
+
detach();
|
|
1550
|
+
continue;
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
roots.set(destination, planRoot(code, destination));
|
|
1555
|
+
if (localSource !== void 0 && toEntry) toEntry.source = destination;
|
|
1556
|
+
local.installPath = destination;
|
|
1557
|
+
local.version = version;
|
|
1558
|
+
const next = { ...key, sourcePath: code, installPath: destination, version };
|
|
1559
|
+
if (index < 0) choices.push(next);
|
|
1560
|
+
else choices[index] = next;
|
|
1561
|
+
}
|
|
1562
|
+
if (!choices.length) delete ledger.value.plugins[id];
|
|
1563
|
+
}
|
|
1564
|
+
const targets = [...catalogues.values(), targetRegistry, ledger];
|
|
1565
|
+
return { documents, targets, roots: [...roots.values()], changed: targets.some(changed) || [...roots.values()].some((root) => root.changed), store: sourceRoot, protectedCatalogues };
|
|
1566
|
+
}
|
|
1567
|
+
function claudePluginLinksPending(sourceHome, targetHome) {
|
|
1568
|
+
return planLinks(sourceHome, targetHome).changed;
|
|
1569
|
+
}
|
|
1570
|
+
function linkClaudePlugins(sourceHome, targetHome) {
|
|
1571
|
+
const plan = planLinks(sourceHome, targetHome);
|
|
1572
|
+
if (!plan.changed) return;
|
|
1573
|
+
for (const document of plan.documents) unchanged(document);
|
|
1574
|
+
for (const root of plan.roots) {
|
|
1575
|
+
validateCode(root.source, plan.store, plan.protectedCatalogues);
|
|
1576
|
+
publishRoot(root);
|
|
1577
|
+
}
|
|
1578
|
+
for (const document of plan.targets) {
|
|
1579
|
+
for (const observed of plan.documents) unchanged(observed);
|
|
1580
|
+
publishDocument(document, targetHome, BACKUP);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
893
1583
|
var AGENT_MIGRATION_MARKER = ".ccem-migration-v1.json";
|
|
894
1584
|
var MIGRATION_LOCK = ".ccem-migration.lock";
|
|
895
1585
|
var PROFILES_FILE = "profiles.json";
|
|
@@ -911,6 +1601,8 @@ var IDENTITY_ENV_KEYS = [
|
|
|
911
1601
|
"CLAUDE_CODE_DESIGN_OAUTH_CLIENT_ID",
|
|
912
1602
|
"CLAUDE_CODE_REMOTE_SETTINGS_PATH",
|
|
913
1603
|
"CLAUDE_CODE_MOCK_REMOTE_SETTINGS",
|
|
1604
|
+
"CLAUDE_CODE_PLUGIN_SEED_DIR",
|
|
1605
|
+
"CLAUDE_CODE_PLUGIN_USE_ZIP_CACHE",
|
|
914
1606
|
"USE_LOCAL_OAUTH",
|
|
915
1607
|
"USE_STAGING_OAUTH",
|
|
916
1608
|
"CLAUDE_LOCAL_OAUTH_API_BASE",
|
|
@@ -952,6 +1644,7 @@ var INHERITED_AGENT_ENV_KEYS = [
|
|
|
952
1644
|
"CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
|
|
953
1645
|
"CLAUDE_CONFIG_DIR",
|
|
954
1646
|
"CLAUDE_SECURESTORAGE_CONFIG_DIR",
|
|
1647
|
+
"CLAUDE_CODE_PLUGIN_CACHE_DIR",
|
|
955
1648
|
"OPENAI_API_KEY",
|
|
956
1649
|
"OPENAI_BASE_URL",
|
|
957
1650
|
"CODEX_API_KEY",
|
|
@@ -977,18 +1670,18 @@ function userHome(env) {
|
|
|
977
1670
|
}
|
|
978
1671
|
function getCcemAgentBase(env = process.env) {
|
|
979
1672
|
const override = env.CCEM_AGENT_HOME?.trim();
|
|
980
|
-
if (override && (!
|
|
1673
|
+
if (override && (!path4.isAbsolute(override) || override.split(/[\\/]/).includes(".."))) {
|
|
981
1674
|
throw new Error("CCEM_AGENT_HOME must be an absolute path without '..'");
|
|
982
1675
|
}
|
|
983
|
-
return
|
|
1676
|
+
return path4.resolve(override || path4.join(userHome(env), ".ccem", "agents"));
|
|
984
1677
|
}
|
|
985
1678
|
function readCodexIsolation(env) {
|
|
986
1679
|
if (env.CCEM_CODEX_ISOLATED === "1") return true;
|
|
987
1680
|
if (env.CCEM_CODEX_ISOLATED === "0") return false;
|
|
988
|
-
const file =
|
|
1681
|
+
const file = path4.join(getCcemAgentBase(env), PROFILES_FILE);
|
|
989
1682
|
let raw;
|
|
990
1683
|
try {
|
|
991
|
-
raw =
|
|
1684
|
+
raw = fs4.readFileSync(file, "utf8");
|
|
992
1685
|
} catch (error) {
|
|
993
1686
|
if (error.code === "ENOENT") return false;
|
|
994
1687
|
throw new Error("Cannot read CCEM agent profile preferences");
|
|
@@ -1015,14 +1708,14 @@ function isCodexIsolated(env = process.env) {
|
|
|
1015
1708
|
}
|
|
1016
1709
|
}
|
|
1017
1710
|
function getCcemIsolatedAgentHome(provider, env = process.env) {
|
|
1018
|
-
return
|
|
1711
|
+
return path4.join(getCcemAgentBase(env), provider);
|
|
1019
1712
|
}
|
|
1020
1713
|
function getOfficialCodexHome(env) {
|
|
1021
1714
|
const override = env.CODEX_HOME?.trim();
|
|
1022
|
-
if (!override) return
|
|
1023
|
-
if (override === "~") return
|
|
1024
|
-
if (/^~[\\/]/.test(override)) return
|
|
1025
|
-
return
|
|
1715
|
+
if (!override) return path4.resolve(userHome(env), ".codex");
|
|
1716
|
+
if (override === "~") return path4.resolve(userHome(env));
|
|
1717
|
+
if (/^~[\\/]/.test(override)) return path4.resolve(userHome(env), override.slice(2));
|
|
1718
|
+
return path4.resolve(override);
|
|
1026
1719
|
}
|
|
1027
1720
|
function getCcemAgentHome(provider, env = process.env) {
|
|
1028
1721
|
return provider === "codex" && !isCodexIsolated(env) ? getOfficialCodexHome(env) : getCcemIsolatedAgentHome(provider, env);
|
|
@@ -1034,6 +1727,7 @@ function getCcemAgentEnv(env = process.env) {
|
|
|
1034
1727
|
return {
|
|
1035
1728
|
CLAUDE_CONFIG_DIR: claude,
|
|
1036
1729
|
CLAUDE_SECURESTORAGE_CONFIG_DIR: claude,
|
|
1730
|
+
CLAUDE_CODE_PLUGIN_CACHE_DIR: path4.join(claude, "plugins"),
|
|
1037
1731
|
CODEX_HOME: codex,
|
|
1038
1732
|
CCEM_CODEX_ISOLATED: isolated ? "1" : "0",
|
|
1039
1733
|
...isolated ? { CODEX_SQLITE_HOME: codex } : {}
|
|
@@ -1068,7 +1762,7 @@ function buildIsolatedAgentEnv(baseEnv = process.env, selectedEnv = {}) {
|
|
|
1068
1762
|
}
|
|
1069
1763
|
function statIfPresent(file) {
|
|
1070
1764
|
try {
|
|
1071
|
-
return
|
|
1765
|
+
return fs4.lstatSync(file);
|
|
1072
1766
|
} catch (error) {
|
|
1073
1767
|
if (error.code === "ENOENT") return void 0;
|
|
1074
1768
|
throw error;
|
|
@@ -1076,57 +1770,57 @@ function statIfPresent(file) {
|
|
|
1076
1770
|
}
|
|
1077
1771
|
function ensureRealDirectory(directory) {
|
|
1078
1772
|
validateNoSymlinks(directory);
|
|
1079
|
-
|
|
1080
|
-
const
|
|
1081
|
-
if (
|
|
1773
|
+
fs4.mkdirSync(directory, { recursive: true, mode: 448 });
|
|
1774
|
+
const stat22 = fs4.lstatSync(directory);
|
|
1775
|
+
if (stat22.isSymbolicLink() || !stat22.isDirectory()) {
|
|
1082
1776
|
throw new Error(`CCEM agent directory must be a real directory: ${directory}`);
|
|
1083
1777
|
}
|
|
1084
|
-
|
|
1778
|
+
fs4.chmodSync(directory, 448);
|
|
1085
1779
|
}
|
|
1086
1780
|
function validateNoSymlinks(file) {
|
|
1087
|
-
let current =
|
|
1088
|
-
for (const component of file.slice(current.length).split(
|
|
1089
|
-
current =
|
|
1090
|
-
const
|
|
1091
|
-
if (!
|
|
1092
|
-
if (
|
|
1781
|
+
let current = path4.parse(file).root;
|
|
1782
|
+
for (const component of file.slice(current.length).split(path4.sep).filter(Boolean)) {
|
|
1783
|
+
current = path4.join(current, component);
|
|
1784
|
+
const stat22 = statIfPresent(current);
|
|
1785
|
+
if (!stat22) break;
|
|
1786
|
+
if (stat22.isSymbolicLink()) throw new Error(`CCEM agent state cannot use a symlink: ${current}`);
|
|
1093
1787
|
}
|
|
1094
1788
|
}
|
|
1095
1789
|
function resolveExistingParent(file) {
|
|
1096
1790
|
const suffix = [];
|
|
1097
1791
|
let parent = file;
|
|
1098
1792
|
while (!statIfPresent(parent)) {
|
|
1099
|
-
suffix.unshift(
|
|
1100
|
-
parent =
|
|
1793
|
+
suffix.unshift(path4.basename(parent));
|
|
1794
|
+
parent = path4.dirname(parent);
|
|
1101
1795
|
}
|
|
1102
|
-
return
|
|
1796
|
+
return path4.join(fs4.realpathSync(parent), ...suffix);
|
|
1103
1797
|
}
|
|
1104
1798
|
function validateAgentBase(base, env) {
|
|
1105
1799
|
validateNoSymlinks(base);
|
|
1106
1800
|
const resolved = resolveExistingParent(base);
|
|
1107
1801
|
for (const name of [".claude", ".codex"]) {
|
|
1108
|
-
const official = resolveExistingParent(
|
|
1109
|
-
if (resolved === official || resolved.startsWith(`${official}${
|
|
1802
|
+
const official = resolveExistingParent(path4.join(userHome(env), name));
|
|
1803
|
+
if (resolved === official || resolved.startsWith(`${official}${path4.sep}`) || official.startsWith(`${resolved}${path4.sep}`)) {
|
|
1110
1804
|
throw new Error("CCEM agent state must not overlap an official Claude or Codex home");
|
|
1111
1805
|
}
|
|
1112
1806
|
}
|
|
1113
1807
|
}
|
|
1114
1808
|
function syncDirectory(directory) {
|
|
1115
1809
|
if (process.platform === "win32") return;
|
|
1116
|
-
const fd =
|
|
1810
|
+
const fd = fs4.openSync(directory, "r");
|
|
1117
1811
|
try {
|
|
1118
|
-
|
|
1812
|
+
fs4.fsyncSync(fd);
|
|
1119
1813
|
} finally {
|
|
1120
|
-
|
|
1814
|
+
fs4.closeSync(fd);
|
|
1121
1815
|
}
|
|
1122
1816
|
}
|
|
1123
1817
|
function migrationComplete(marker) {
|
|
1124
|
-
const
|
|
1125
|
-
if (!
|
|
1126
|
-
if (!
|
|
1818
|
+
const stat22 = statIfPresent(marker);
|
|
1819
|
+
if (!stat22) return false;
|
|
1820
|
+
if (!stat22.isFile() || stat22.isSymbolicLink()) throw new Error("CCEM agent migration marker is invalid");
|
|
1127
1821
|
let version;
|
|
1128
1822
|
try {
|
|
1129
|
-
version = JSON.parse(
|
|
1823
|
+
version = JSON.parse(fs4.readFileSync(marker, "utf8")).version;
|
|
1130
1824
|
} catch {
|
|
1131
1825
|
}
|
|
1132
1826
|
if (version !== 1) throw new Error("CCEM agent migration marker is invalid or unsupported");
|
|
@@ -1139,35 +1833,35 @@ function writeNewFile(file, contents) {
|
|
|
1139
1833
|
if (!existing.isFile()) throw new Error(`CCEM agent file conflicts with a directory: ${file}`);
|
|
1140
1834
|
return;
|
|
1141
1835
|
}
|
|
1142
|
-
const temporary =
|
|
1836
|
+
const temporary = path4.join(path4.dirname(file), `.ccem-copy-${randomUUID3()}.tmp`);
|
|
1143
1837
|
try {
|
|
1144
|
-
const fd =
|
|
1838
|
+
const fd = fs4.openSync(temporary, "wx", 384);
|
|
1145
1839
|
try {
|
|
1146
|
-
|
|
1147
|
-
|
|
1840
|
+
fs4.writeFileSync(fd, contents);
|
|
1841
|
+
fs4.fsyncSync(fd);
|
|
1148
1842
|
} finally {
|
|
1149
|
-
|
|
1843
|
+
fs4.closeSync(fd);
|
|
1150
1844
|
}
|
|
1151
1845
|
try {
|
|
1152
|
-
|
|
1846
|
+
fs4.linkSync(temporary, file);
|
|
1153
1847
|
} catch (error) {
|
|
1154
1848
|
if (error.code !== "EEXIST") throw error;
|
|
1155
1849
|
}
|
|
1156
1850
|
} finally {
|
|
1157
|
-
|
|
1851
|
+
fs4.rmSync(temporary, { force: true });
|
|
1158
1852
|
}
|
|
1159
1853
|
}
|
|
1160
1854
|
function copyLegacyEntry(source, destination) {
|
|
1161
1855
|
const sourceStat = statIfPresent(source);
|
|
1162
1856
|
if (!sourceStat || sourceStat.isSymbolicLink()) return;
|
|
1163
|
-
if (sourceStat.isFile() && /\.(?:sqlite|sqlite3|db)(?:-(?:wal|shm))?$/i.test(
|
|
1857
|
+
if (sourceStat.isFile() && /\.(?:sqlite|sqlite3|db)(?:-(?:wal|shm))?$/i.test(path4.basename(source))) return;
|
|
1164
1858
|
validateNoSymlinks(destination);
|
|
1165
1859
|
const destinationStat = statIfPresent(destination);
|
|
1166
1860
|
if (sourceStat.isDirectory()) {
|
|
1167
1861
|
if (destinationStat && !destinationStat.isDirectory()) throw new Error(`CCEM agent directory conflicts with a file: ${destination}`);
|
|
1168
1862
|
ensureRealDirectory(destination);
|
|
1169
|
-
for (const name of
|
|
1170
|
-
copyLegacyEntry(
|
|
1863
|
+
for (const name of fs4.readdirSync(source)) {
|
|
1864
|
+
copyLegacyEntry(path4.join(source, name), path4.join(destination, name));
|
|
1171
1865
|
}
|
|
1172
1866
|
syncDirectory(destination);
|
|
1173
1867
|
return;
|
|
@@ -1177,63 +1871,63 @@ function copyLegacyEntry(source, destination) {
|
|
|
1177
1871
|
if (!destinationStat.isFile()) throw new Error(`CCEM agent file conflicts with a directory: ${destination}`);
|
|
1178
1872
|
return;
|
|
1179
1873
|
}
|
|
1180
|
-
const temporary =
|
|
1874
|
+
const temporary = path4.join(path4.dirname(destination), `.ccem-copy-${randomUUID3()}.tmp`);
|
|
1181
1875
|
let sourceFd;
|
|
1182
1876
|
let destinationFd;
|
|
1183
1877
|
try {
|
|
1184
|
-
sourceFd =
|
|
1185
|
-
const openedStat =
|
|
1878
|
+
sourceFd = fs4.openSync(source, fs4.constants.O_RDONLY | (fs4.constants.O_NOFOLLOW ?? 0));
|
|
1879
|
+
const openedStat = fs4.fstatSync(sourceFd);
|
|
1186
1880
|
if (!openedStat.isFile()) throw new Error("Legacy agent history changed during migration");
|
|
1187
|
-
destinationFd =
|
|
1881
|
+
destinationFd = fs4.openSync(temporary, "wx", 384);
|
|
1188
1882
|
const buffer = Buffer.alloc(1024 * 1024);
|
|
1189
1883
|
let remaining = openedStat.size;
|
|
1190
1884
|
while (remaining > 0) {
|
|
1191
|
-
const bytesRead =
|
|
1885
|
+
const bytesRead = fs4.readSync(sourceFd, buffer, 0, Math.min(remaining, buffer.length), null);
|
|
1192
1886
|
if (!bytesRead) throw new Error("Legacy agent history changed during migration");
|
|
1193
1887
|
let offset = 0;
|
|
1194
|
-
while (offset < bytesRead) offset +=
|
|
1888
|
+
while (offset < bytesRead) offset += fs4.writeSync(destinationFd, buffer, offset, bytesRead - offset);
|
|
1195
1889
|
remaining -= bytesRead;
|
|
1196
1890
|
}
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1891
|
+
fs4.futimesSync(destinationFd, openedStat.atime, openedStat.mtime);
|
|
1892
|
+
fs4.fsyncSync(destinationFd);
|
|
1893
|
+
fs4.closeSync(destinationFd);
|
|
1200
1894
|
destinationFd = void 0;
|
|
1201
1895
|
try {
|
|
1202
|
-
|
|
1896
|
+
fs4.linkSync(temporary, destination);
|
|
1203
1897
|
} catch (error) {
|
|
1204
1898
|
if (error.code !== "EEXIST") throw error;
|
|
1205
1899
|
}
|
|
1206
1900
|
} finally {
|
|
1207
|
-
if (sourceFd !== void 0)
|
|
1208
|
-
if (destinationFd !== void 0)
|
|
1209
|
-
|
|
1901
|
+
if (sourceFd !== void 0) fs4.closeSync(sourceFd);
|
|
1902
|
+
if (destinationFd !== void 0) fs4.closeSync(destinationFd);
|
|
1903
|
+
fs4.rmSync(temporary, { force: true });
|
|
1210
1904
|
}
|
|
1211
1905
|
}
|
|
1212
1906
|
function acquireMigrationLock(base) {
|
|
1213
|
-
const lockPath =
|
|
1907
|
+
const lockPath = path4.join(base, MIGRATION_LOCK);
|
|
1214
1908
|
const contents = JSON.stringify({ pid: process.pid });
|
|
1215
1909
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1216
1910
|
try {
|
|
1217
|
-
const fd =
|
|
1911
|
+
const fd = fs4.openSync(lockPath, "wx", 384);
|
|
1218
1912
|
try {
|
|
1219
|
-
|
|
1220
|
-
|
|
1913
|
+
fs4.writeFileSync(fd, contents);
|
|
1914
|
+
fs4.fsyncSync(fd);
|
|
1221
1915
|
} catch (error) {
|
|
1222
|
-
const owned =
|
|
1916
|
+
const owned = fs4.fstatSync(fd);
|
|
1223
1917
|
const current = statIfPresent(lockPath);
|
|
1224
|
-
if (current?.ino === owned.ino && current.dev === owned.dev)
|
|
1918
|
+
if (current?.ino === owned.ino && current.dev === owned.dev) fs4.unlinkSync(lockPath);
|
|
1225
1919
|
throw error;
|
|
1226
1920
|
} finally {
|
|
1227
|
-
|
|
1921
|
+
fs4.closeSync(fd);
|
|
1228
1922
|
}
|
|
1229
1923
|
return () => {
|
|
1230
|
-
if (statIfPresent(lockPath)?.isFile() &&
|
|
1924
|
+
if (statIfPresent(lockPath)?.isFile() && fs4.readFileSync(lockPath, "utf8") === contents) fs4.unlinkSync(lockPath);
|
|
1231
1925
|
};
|
|
1232
1926
|
} catch (error) {
|
|
1233
1927
|
if (error.code !== "EEXIST") throw error;
|
|
1234
|
-
const
|
|
1235
|
-
if (!
|
|
1236
|
-
const old =
|
|
1928
|
+
const stat22 = fs4.lstatSync(lockPath);
|
|
1929
|
+
if (!stat22.isFile() || stat22.isSymbolicLink()) throw new Error("CCEM agent migration lock is invalid");
|
|
1930
|
+
const old = fs4.readFileSync(lockPath, "utf8");
|
|
1237
1931
|
let pid;
|
|
1238
1932
|
try {
|
|
1239
1933
|
pid = JSON.parse(old).pid;
|
|
@@ -1244,8 +1938,8 @@ function acquireMigrationLock(base) {
|
|
|
1244
1938
|
process.kill(pid, 0);
|
|
1245
1939
|
} catch (probeError) {
|
|
1246
1940
|
if (probeError.code === "ESRCH" && attempt === 0) {
|
|
1247
|
-
if (
|
|
1248
|
-
|
|
1941
|
+
if (fs4.readFileSync(lockPath, "utf8") !== old) throw new Error("CCEM agent migration lock changed; retry preparation");
|
|
1942
|
+
fs4.unlinkSync(lockPath);
|
|
1249
1943
|
continue;
|
|
1250
1944
|
}
|
|
1251
1945
|
}
|
|
@@ -1259,31 +1953,56 @@ function ensureCcemAgentHome(provider, env = process.env) {
|
|
|
1259
1953
|
const base = getCcemAgentBase(env);
|
|
1260
1954
|
const root = getCcemIsolatedAgentHome(provider, env);
|
|
1261
1955
|
validateAgentBase(base, env);
|
|
1956
|
+
for (const entry of LEGACY_ENTRIES[provider]) validateNoSymlinks(path4.join(root, entry));
|
|
1957
|
+
validateNoSymlinks(path4.join(root, provider === "claude" ? ".claude.json" : "config.toml"));
|
|
1958
|
+
const marker = path4.join(root, AGENT_MIGRATION_MARKER);
|
|
1959
|
+
const source = provider === "codex" ? getOfficialCodexHome(env) : path4.join(userHome(env), ".claude");
|
|
1960
|
+
const historyReady = migrationComplete(marker);
|
|
1961
|
+
if (historyReady) {
|
|
1962
|
+
if (provider !== "claude") return root;
|
|
1963
|
+
try {
|
|
1964
|
+
if (!claudePluginImportPending(source, root) && !claudePluginLinksPending(source, root)) return root;
|
|
1965
|
+
} catch (error) {
|
|
1966
|
+
console.warn(`CCEM plugin import deferred: ${error.message}`);
|
|
1967
|
+
return root;
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1262
1970
|
ensureRealDirectory(base);
|
|
1263
1971
|
ensureRealDirectory(root);
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1972
|
+
let unlock;
|
|
1973
|
+
try {
|
|
1974
|
+
unlock = acquireMigrationLock(base);
|
|
1975
|
+
} catch (error) {
|
|
1976
|
+
if (!historyReady) throw error;
|
|
1977
|
+
console.warn(`CCEM plugin import deferred: ${error.message}`);
|
|
1978
|
+
return root;
|
|
1979
|
+
}
|
|
1269
1980
|
try {
|
|
1270
|
-
if (migrationComplete(marker))
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1981
|
+
if (!migrationComplete(marker)) {
|
|
1982
|
+
if (provider === "codex") {
|
|
1983
|
+
const resolvedBase = resolveExistingParent(base);
|
|
1984
|
+
const resolvedSource = resolveExistingParent(source);
|
|
1985
|
+
if (resolvedBase === resolvedSource || resolvedBase.startsWith(`${resolvedSource}${path4.sep}`) || resolvedSource.startsWith(`${resolvedBase}${path4.sep}`)) {
|
|
1986
|
+
throw new Error("CCEM Codex migration source must not overlap its isolated agent directory");
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
assertNoLegacyAgentWriters(provider, userHome(env), source, root);
|
|
1990
|
+
const sourceStat = statIfPresent(source);
|
|
1991
|
+
if (sourceStat?.isDirectory() && !sourceStat.isSymbolicLink()) {
|
|
1992
|
+
for (const entry of LEGACY_ENTRIES[provider]) copyLegacyEntry(path4.join(source, entry), path4.join(root, entry));
|
|
1277
1993
|
}
|
|
1994
|
+
if (provider === "claude") writeNewFile(path4.join(root, ".claude.json"), JSON.stringify({ hasCompletedOnboarding: true }));
|
|
1995
|
+
writeNewFile(marker, JSON.stringify({ version: 1 }));
|
|
1996
|
+
syncDirectory(root);
|
|
1278
1997
|
}
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1998
|
+
if (provider === "claude") {
|
|
1999
|
+
try {
|
|
2000
|
+
importClaudePlugins(source, root);
|
|
2001
|
+
linkClaudePlugins(source, root);
|
|
2002
|
+
} catch (error) {
|
|
2003
|
+
console.warn(`CCEM plugin import deferred: ${error.message}`);
|
|
2004
|
+
}
|
|
1283
2005
|
}
|
|
1284
|
-
if (provider === "claude") writeNewFile(path2.join(root, ".claude.json"), JSON.stringify({ hasCompletedOnboarding: true }));
|
|
1285
|
-
writeNewFile(marker, JSON.stringify({ version: 1 }));
|
|
1286
|
-
syncDirectory(root);
|
|
1287
2006
|
return root;
|
|
1288
2007
|
} finally {
|
|
1289
2008
|
unlock();
|
|
@@ -1332,14 +2051,14 @@ var LEGACY_KEY = crypto2.scryptSync("claude-code-env-manager-secret", "salt", 32
|
|
|
1332
2051
|
var _installKey = null;
|
|
1333
2052
|
function getOrCreateInstallKey() {
|
|
1334
2053
|
if (_installKey) return _installKey;
|
|
1335
|
-
const keyPath =
|
|
1336
|
-
if (
|
|
1337
|
-
_installKey = Buffer.from(
|
|
2054
|
+
const keyPath = path5.join(getCcemConfigDir(), ".install-key");
|
|
2055
|
+
if (fs5.existsSync(keyPath)) {
|
|
2056
|
+
_installKey = Buffer.from(fs5.readFileSync(keyPath, "utf-8").trim(), "hex");
|
|
1338
2057
|
return _installKey;
|
|
1339
2058
|
}
|
|
1340
2059
|
ensureCcemDir();
|
|
1341
2060
|
_installKey = crypto2.randomBytes(32);
|
|
1342
|
-
|
|
2061
|
+
fs5.writeFileSync(keyPath, _installKey.toString("hex"), { mode: 384 });
|
|
1343
2062
|
return _installKey;
|
|
1344
2063
|
}
|
|
1345
2064
|
var encrypt = (text) => {
|
|
@@ -1373,27 +2092,27 @@ var getHomeDir = () => {
|
|
|
1373
2092
|
return process.env.HOME || process.env.USERPROFILE || os2.homedir() || "";
|
|
1374
2093
|
};
|
|
1375
2094
|
var getCcemConfigDir = () => {
|
|
1376
|
-
return
|
|
2095
|
+
return path5.join(getHomeDir(), ".ccem");
|
|
1377
2096
|
};
|
|
1378
2097
|
var getCcemConfigPath = () => {
|
|
1379
|
-
return
|
|
2098
|
+
return path5.join(getCcemConfigDir(), "config.json");
|
|
1380
2099
|
};
|
|
1381
2100
|
var ensureCcemDir = () => {
|
|
1382
2101
|
const ccemDir = getCcemConfigDir();
|
|
1383
|
-
if (!
|
|
1384
|
-
|
|
2102
|
+
if (!fs5.existsSync(ccemDir)) {
|
|
2103
|
+
fs5.mkdirSync(ccemDir, { recursive: true, mode: 448 });
|
|
1385
2104
|
}
|
|
1386
2105
|
if (process.platform !== "win32") {
|
|
1387
|
-
|
|
2106
|
+
fs5.chmodSync(ccemDir, 448);
|
|
1388
2107
|
}
|
|
1389
2108
|
return ccemDir;
|
|
1390
2109
|
};
|
|
1391
2110
|
var getLegacyConfigPath = () => {
|
|
1392
2111
|
const home = getHomeDir();
|
|
1393
2112
|
if (process.platform === "darwin") {
|
|
1394
|
-
return
|
|
2113
|
+
return path5.join(home, "Library", "Preferences", "claude-code-env-manager-nodejs", "config.json");
|
|
1395
2114
|
}
|
|
1396
|
-
return
|
|
2115
|
+
return path5.join(home, ".config", "claude-code-env-manager-nodejs", "config.json");
|
|
1397
2116
|
};
|
|
1398
2117
|
|
|
1399
2118
|
// src/desktopControl.ts
|
|
@@ -1460,11 +2179,11 @@ function getDesktopControlDescriptorPath() {
|
|
|
1460
2179
|
return process.env.CCEM_CONTROL_FILE?.trim() || getDefaultControlDescriptorPath();
|
|
1461
2180
|
}
|
|
1462
2181
|
function getDefaultControlDescriptorPath() {
|
|
1463
|
-
return
|
|
2182
|
+
return path6.join(getCcemConfigDir(), "control.json");
|
|
1464
2183
|
}
|
|
1465
2184
|
function isDefaultDescriptorPath(descriptorPath) {
|
|
1466
2185
|
try {
|
|
1467
|
-
return
|
|
2186
|
+
return path6.resolve(descriptorPath) === path6.resolve(getDefaultControlDescriptorPath());
|
|
1468
2187
|
} catch {
|
|
1469
2188
|
return false;
|
|
1470
2189
|
}
|
|
@@ -1474,7 +2193,7 @@ function safeRemoveStaleDescriptor(descriptorPath) {
|
|
|
1474
2193
|
return false;
|
|
1475
2194
|
}
|
|
1476
2195
|
try {
|
|
1477
|
-
|
|
2196
|
+
fs6.rmSync(descriptorPath);
|
|
1478
2197
|
return true;
|
|
1479
2198
|
} catch {
|
|
1480
2199
|
return false;
|
|
@@ -1552,10 +2271,10 @@ function isDescriptor(value) {
|
|
|
1552
2271
|
);
|
|
1553
2272
|
}
|
|
1554
2273
|
function resolveDesktopControlDescriptor(descriptorPath = getDesktopControlDescriptorPath()) {
|
|
1555
|
-
if (!
|
|
2274
|
+
if (!fs6.existsSync(descriptorPath)) {
|
|
1556
2275
|
throw new Error(`CCEM Desktop control endpoint not found at ${descriptorPath}. Start CCEM Desktop first.`);
|
|
1557
2276
|
}
|
|
1558
|
-
const parsed = JSON.parse(
|
|
2277
|
+
const parsed = JSON.parse(fs6.readFileSync(descriptorPath, "utf-8"));
|
|
1559
2278
|
const endpoint = parsed.endpoint?.trim();
|
|
1560
2279
|
const token = parsed.token?.trim();
|
|
1561
2280
|
if (!endpoint || !token) {
|
|
@@ -1820,29 +2539,94 @@ import inquirer from "inquirer";
|
|
|
1820
2539
|
import chalk9 from "chalk";
|
|
1821
2540
|
import Table4 from "cli-table3";
|
|
1822
2541
|
import { spawn as spawn4 } from "child_process";
|
|
1823
|
-
import * as
|
|
1824
|
-
import * as
|
|
2542
|
+
import * as fs19 from "fs";
|
|
2543
|
+
import * as path17 from "path";
|
|
1825
2544
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1826
|
-
import { randomUUID as
|
|
2545
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
1827
2546
|
|
|
1828
2547
|
// src/ui.ts
|
|
1829
2548
|
import chalk from "chalk";
|
|
1830
2549
|
import Table from "cli-table3";
|
|
1831
2550
|
|
|
1832
2551
|
// src/usage.ts
|
|
1833
|
-
import * as
|
|
2552
|
+
import * as fs8 from "fs";
|
|
1834
2553
|
import * as fsPromises from "fs/promises";
|
|
1835
|
-
import * as
|
|
2554
|
+
import * as path8 from "path";
|
|
1836
2555
|
import * as os3 from "os";
|
|
1837
|
-
import
|
|
2556
|
+
import { createHash as createHash2 } from "crypto";
|
|
1838
2557
|
import { fileURLToPath } from "url";
|
|
2558
|
+
|
|
2559
|
+
// src/usage-profiles.ts
|
|
2560
|
+
import path7 from "path";
|
|
2561
|
+
import * as fs7 from "fs/promises";
|
|
2562
|
+
async function discoverClaudeUsageFiles(roots) {
|
|
2563
|
+
const files = [];
|
|
2564
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2565
|
+
async function walk(dir, depth) {
|
|
2566
|
+
try {
|
|
2567
|
+
for (const entry of await fs7.readdir(dir, { withFileTypes: true })) {
|
|
2568
|
+
const file = path7.join(dir, entry.name);
|
|
2569
|
+
if (entry.isDirectory() && depth < 4) await walk(file, depth + 1);
|
|
2570
|
+
else if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(file);
|
|
2571
|
+
}
|
|
2572
|
+
} catch {
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
for (const root of roots) {
|
|
2576
|
+
const canonical = await fs7.realpath(root).catch(() => root);
|
|
2577
|
+
if (seen.has(canonical)) continue;
|
|
2578
|
+
seen.add(canonical);
|
|
2579
|
+
await walk(root, 0);
|
|
2580
|
+
}
|
|
2581
|
+
return files;
|
|
2582
|
+
}
|
|
2583
|
+
function logicalPath(file, roots) {
|
|
2584
|
+
for (const root of roots) {
|
|
2585
|
+
const relative2 = path7.relative(root, file);
|
|
2586
|
+
if (relative2 && !relative2.startsWith(`..${path7.sep}`) && relative2 !== ".." && !path7.isAbsolute(relative2)) {
|
|
2587
|
+
return relative2;
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
return file;
|
|
2591
|
+
}
|
|
2592
|
+
function newer(left, right) {
|
|
2593
|
+
const time = (row) => Date.parse(row.timestamp) || 0;
|
|
2594
|
+
const tokens = (row) => row.usage.inputTokens + row.usage.outputTokens + row.usage.cacheReadTokens + row.usage.cacheCreationTokens;
|
|
2595
|
+
return time(left) > time(right) || time(left) === time(right) && tokens(left) > tokens(right);
|
|
2596
|
+
}
|
|
2597
|
+
function mergeClaudeUsage(files, roots) {
|
|
2598
|
+
const merged = /* @__PURE__ */ new Map();
|
|
2599
|
+
for (const [file, data] of Object.entries(files).sort(([a], [b]) => a.localeCompare(b))) {
|
|
2600
|
+
const session = logicalPath(file, roots);
|
|
2601
|
+
const occurrences = /* @__PURE__ */ new Map();
|
|
2602
|
+
for (const [index, row] of data.stats.entries.entries()) {
|
|
2603
|
+
let identity2;
|
|
2604
|
+
if (row.messageId) identity2 = `id:${row.messageId}`;
|
|
2605
|
+
else {
|
|
2606
|
+
const signature = row.recordFingerprint ?? JSON.stringify([file, index]);
|
|
2607
|
+
const occurrence = (occurrences.get(signature) ?? 0) + 1;
|
|
2608
|
+
occurrences.set(signature, occurrence);
|
|
2609
|
+
identity2 = `row:${signature}:${occurrence}`;
|
|
2610
|
+
}
|
|
2611
|
+
const key = JSON.stringify([session, identity2]);
|
|
2612
|
+
const previous = merged.get(key);
|
|
2613
|
+
if (!previous || newer(row, previous)) merged.set(key, row);
|
|
2614
|
+
}
|
|
2615
|
+
}
|
|
2616
|
+
return [...merged.values()];
|
|
2617
|
+
}
|
|
2618
|
+
|
|
2619
|
+
// src/usage.ts
|
|
1839
2620
|
var __filename = fileURLToPath(import.meta.url);
|
|
1840
|
-
var __dirname =
|
|
1841
|
-
var
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
var
|
|
2621
|
+
var __dirname = path8.dirname(__filename);
|
|
2622
|
+
var CLAUDE_PROJECTS_DIRS = [
|
|
2623
|
+
path8.join(getCcemAgentHome("claude"), "projects"),
|
|
2624
|
+
path8.join(os3.homedir(), ".claude", "projects")
|
|
2625
|
+
];
|
|
2626
|
+
var CCEM_DIR = path8.join(os3.homedir(), ".ccem");
|
|
2627
|
+
var CACHE_VERSION = 4;
|
|
2628
|
+
var getCachePath = () => path8.join(CCEM_DIR, "usage-cache.json");
|
|
2629
|
+
var getPricesPath = () => path8.join(CCEM_DIR, "model-prices.json");
|
|
1846
2630
|
async function ensureCcemDir2() {
|
|
1847
2631
|
try {
|
|
1848
2632
|
await fsPromises.access(CCEM_DIR);
|
|
@@ -1852,7 +2636,7 @@ async function ensureCcemDir2() {
|
|
|
1852
2636
|
}
|
|
1853
2637
|
var LITELLM_PRICES_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
|
|
1854
2638
|
var getBundledPricesPath = () => {
|
|
1855
|
-
return
|
|
2639
|
+
return path8.join(__dirname, "..", "model-prices.json");
|
|
1856
2640
|
};
|
|
1857
2641
|
var DEFAULT_PRICES = {
|
|
1858
2642
|
"claude-opus-4-5": {
|
|
@@ -1959,10 +2743,10 @@ function mergeUsage(a, b) {
|
|
|
1959
2743
|
}
|
|
1960
2744
|
async function getFileMetaAsync(filePath) {
|
|
1961
2745
|
try {
|
|
1962
|
-
const
|
|
2746
|
+
const stat3 = await fsPromises.stat(filePath);
|
|
1963
2747
|
return {
|
|
1964
|
-
mtime:
|
|
1965
|
-
size:
|
|
2748
|
+
mtime: stat3.mtimeMs,
|
|
2749
|
+
size: stat3.size
|
|
1966
2750
|
};
|
|
1967
2751
|
} catch {
|
|
1968
2752
|
return null;
|
|
@@ -1971,9 +2755,9 @@ async function getFileMetaAsync(filePath) {
|
|
|
1971
2755
|
function loadCacheSync() {
|
|
1972
2756
|
try {
|
|
1973
2757
|
const cachePath = getCachePath();
|
|
1974
|
-
if (!
|
|
1975
|
-
const data = JSON.parse(
|
|
1976
|
-
if (data.version !== CACHE_VERSION) return null;
|
|
2758
|
+
if (!fs8.existsSync(cachePath)) return null;
|
|
2759
|
+
const data = JSON.parse(fs8.readFileSync(cachePath, "utf-8"));
|
|
2760
|
+
if (data.version !== 3 && data.version !== CACHE_VERSION) return null;
|
|
1977
2761
|
return data;
|
|
1978
2762
|
} catch {
|
|
1979
2763
|
return null;
|
|
@@ -1984,7 +2768,7 @@ async function loadCacheAsync() {
|
|
|
1984
2768
|
const cachePath = getCachePath();
|
|
1985
2769
|
const content = await fsPromises.readFile(cachePath, "utf-8");
|
|
1986
2770
|
const data = JSON.parse(content);
|
|
1987
|
-
if (data.version !== CACHE_VERSION) return null;
|
|
2771
|
+
if (data.version !== 3 && data.version !== CACHE_VERSION) return null;
|
|
1988
2772
|
return data;
|
|
1989
2773
|
} catch {
|
|
1990
2774
|
return null;
|
|
@@ -2005,26 +2789,24 @@ function getUsageStatsFromCache() {
|
|
|
2005
2789
|
byModel: {},
|
|
2006
2790
|
lastUpdated: now.toISOString()
|
|
2007
2791
|
};
|
|
2008
|
-
for (const
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
stats.week = mergeUsage(stats.week, entry.usage);
|
|
2027
|
-
}
|
|
2792
|
+
for (const entry of mergeClaudeUsage(cache.files, CLAUDE_PROJECTS_DIRS)) {
|
|
2793
|
+
const entryTime = new Date(entry.timestamp);
|
|
2794
|
+
const dateKey = entry.timestamp.split("T")[0];
|
|
2795
|
+
stats.total = mergeUsage(stats.total, entry.usage);
|
|
2796
|
+
if (!stats.dailyHistory[dateKey]) {
|
|
2797
|
+
stats.dailyHistory[dateKey] = emptyUsage();
|
|
2798
|
+
}
|
|
2799
|
+
stats.dailyHistory[dateKey] = mergeUsage(stats.dailyHistory[dateKey], entry.usage);
|
|
2800
|
+
const normalizedModel = normalizeModelName(entry.model);
|
|
2801
|
+
if (!stats.byModel[normalizedModel]) {
|
|
2802
|
+
stats.byModel[normalizedModel] = emptyUsage();
|
|
2803
|
+
}
|
|
2804
|
+
stats.byModel[normalizedModel] = mergeUsage(stats.byModel[normalizedModel], entry.usage);
|
|
2805
|
+
if (entryTime >= todayStart) {
|
|
2806
|
+
stats.today = mergeUsage(stats.today, entry.usage);
|
|
2807
|
+
}
|
|
2808
|
+
if (entryTime >= weekStart) {
|
|
2809
|
+
stats.week = mergeUsage(stats.week, entry.usage);
|
|
2028
2810
|
}
|
|
2029
2811
|
}
|
|
2030
2812
|
return stats;
|
|
@@ -2036,21 +2818,31 @@ async function saveCacheAsync(cache) {
|
|
|
2036
2818
|
} catch {
|
|
2037
2819
|
}
|
|
2038
2820
|
}
|
|
2821
|
+
async function* completeLines(stream) {
|
|
2822
|
+
let pending = "";
|
|
2823
|
+
try {
|
|
2824
|
+
for await (const chunk of stream) {
|
|
2825
|
+
pending += chunk.toString();
|
|
2826
|
+
let newline;
|
|
2827
|
+
while ((newline = pending.indexOf("\n")) >= 0) {
|
|
2828
|
+
yield pending.slice(0, newline);
|
|
2829
|
+
pending = pending.slice(newline + 1);
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
} finally {
|
|
2833
|
+
stream.destroy();
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2039
2836
|
async function parseJSONLFileAsync(filePath, prices, signal) {
|
|
2040
2837
|
const entries = [];
|
|
2041
2838
|
const messageEntryIndexes = /* @__PURE__ */ new Map();
|
|
2042
2839
|
try {
|
|
2043
|
-
const fileStream =
|
|
2044
|
-
const rl = readline.createInterface({
|
|
2045
|
-
input: fileStream,
|
|
2046
|
-
crlfDelay: Infinity
|
|
2047
|
-
});
|
|
2840
|
+
const fileStream = fs8.createReadStream(filePath, { encoding: "utf-8" });
|
|
2048
2841
|
let lineCount = 0;
|
|
2049
|
-
for await (const line of
|
|
2842
|
+
for await (const line of completeLines(fileStream)) {
|
|
2050
2843
|
lineCount++;
|
|
2051
2844
|
if (lineCount % 100 === 0) {
|
|
2052
2845
|
if (signal?.aborted) {
|
|
2053
|
-
rl.close();
|
|
2054
2846
|
fileStream.destroy();
|
|
2055
2847
|
throw new Error("Aborted");
|
|
2056
2848
|
}
|
|
@@ -2075,6 +2867,7 @@ async function parseJSONLFileAsync(filePath, prices, signal) {
|
|
|
2075
2867
|
const statsEntry = {
|
|
2076
2868
|
timestamp: entry.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
|
|
2077
2869
|
model,
|
|
2870
|
+
...typeof entry.message.id === "string" && entry.message.id ? { messageId: entry.message.id } : { recordFingerprint: createHash2("sha256").update(line.trim()).digest("hex") },
|
|
2078
2871
|
usage: { ...usage, cost }
|
|
2079
2872
|
};
|
|
2080
2873
|
const messageId = entry.message.id;
|
|
@@ -2096,49 +2889,22 @@ async function parseJSONLFileAsync(filePath, prices, signal) {
|
|
|
2096
2889
|
if (err.message === "Aborted") {
|
|
2097
2890
|
throw err;
|
|
2098
2891
|
}
|
|
2892
|
+
return null;
|
|
2099
2893
|
}
|
|
2100
2894
|
return { entries };
|
|
2101
2895
|
}
|
|
2102
|
-
async function getAllJSONLFilesAsync() {
|
|
2103
|
-
const files = [];
|
|
2104
|
-
try {
|
|
2105
|
-
const projectsDirExists = await fsPromises.access(CLAUDE_PROJECTS_DIR).then(() => true).catch(() => false);
|
|
2106
|
-
if (!projectsDirExists) return files;
|
|
2107
|
-
const projects = await fsPromises.readdir(CLAUDE_PROJECTS_DIR);
|
|
2108
|
-
for (const project of projects) {
|
|
2109
|
-
const projectPath = path5.join(CLAUDE_PROJECTS_DIR, project);
|
|
2110
|
-
try {
|
|
2111
|
-
const stat2 = await fsPromises.lstat(projectPath);
|
|
2112
|
-
if (stat2.isDirectory()) {
|
|
2113
|
-
const projectFiles = await fsPromises.readdir(projectPath);
|
|
2114
|
-
for (const file of projectFiles) {
|
|
2115
|
-
const filePath = path5.join(projectPath, file);
|
|
2116
|
-
if (file.endsWith(".jsonl") && (await fsPromises.lstat(filePath)).isFile()) {
|
|
2117
|
-
files.push(filePath);
|
|
2118
|
-
}
|
|
2119
|
-
}
|
|
2120
|
-
}
|
|
2121
|
-
} catch {
|
|
2122
|
-
}
|
|
2123
|
-
}
|
|
2124
|
-
} catch {
|
|
2125
|
-
}
|
|
2126
|
-
return files;
|
|
2127
|
-
}
|
|
2128
2896
|
async function getUsageStats(signal) {
|
|
2129
2897
|
if (signal?.aborted) throw new Error("Aborted");
|
|
2130
|
-
ensureCcemAgentHome("claude");
|
|
2131
2898
|
const prices = await loadPrices();
|
|
2132
2899
|
if (signal?.aborted) throw new Error("Aborted");
|
|
2133
|
-
const files = await
|
|
2900
|
+
const files = await discoverClaudeUsageFiles(CLAUDE_PROJECTS_DIRS);
|
|
2134
2901
|
if (signal?.aborted) throw new Error("Aborted");
|
|
2135
2902
|
const cache = await loadCacheAsync();
|
|
2136
2903
|
const newCache = {
|
|
2137
2904
|
version: CACHE_VERSION,
|
|
2138
|
-
files: {},
|
|
2905
|
+
files: { ...cache?.files },
|
|
2139
2906
|
lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
|
|
2140
2907
|
};
|
|
2141
|
-
const allEntries = [];
|
|
2142
2908
|
const CONCURRENCY_LIMIT = 5;
|
|
2143
2909
|
const chunks = [];
|
|
2144
2910
|
for (let i = 0; i < files.length; i += CONCURRENCY_LIMIT) {
|
|
@@ -2152,12 +2918,13 @@ async function getUsageStats(signal) {
|
|
|
2152
2918
|
const meta = await getFileMetaAsync(file);
|
|
2153
2919
|
if (!meta) return null;
|
|
2154
2920
|
const cachedFile = cache?.files[file];
|
|
2155
|
-
const cacheValid = cachedFile && cachedFile.meta.mtime === meta.mtime && cachedFile.meta.size === meta.size;
|
|
2921
|
+
const cacheValid = cachedFile && cachedFile.stats.entries.every((entry) => entry.messageId || entry.recordFingerprint) && cachedFile.meta.mtime === meta.mtime && cachedFile.meta.size === meta.size;
|
|
2156
2922
|
let fileStats;
|
|
2157
2923
|
if (cacheValid) {
|
|
2158
2924
|
fileStats = cachedFile.stats;
|
|
2159
2925
|
} else {
|
|
2160
2926
|
fileStats = await parseJSONLFileAsync(file, prices, signal);
|
|
2927
|
+
if (!fileStats) return null;
|
|
2161
2928
|
await new Promise((resolve5) => setTimeout(resolve5, 0));
|
|
2162
2929
|
}
|
|
2163
2930
|
return {
|
|
@@ -2173,7 +2940,6 @@ async function getUsageStats(signal) {
|
|
|
2173
2940
|
meta: result.meta,
|
|
2174
2941
|
stats: result.stats
|
|
2175
2942
|
};
|
|
2176
|
-
allEntries.push(...result.stats.entries);
|
|
2177
2943
|
}
|
|
2178
2944
|
}
|
|
2179
2945
|
if (!signal?.aborted) {
|
|
@@ -2192,7 +2958,7 @@ async function getUsageStats(signal) {
|
|
|
2192
2958
|
byModel: {},
|
|
2193
2959
|
lastUpdated: now.toISOString()
|
|
2194
2960
|
};
|
|
2195
|
-
for (const entry of
|
|
2961
|
+
for (const entry of mergeClaudeUsage(newCache.files, CLAUDE_PROJECTS_DIRS)) {
|
|
2196
2962
|
const entryTime = new Date(entry.timestamp);
|
|
2197
2963
|
const dateKey = entry.timestamp.split("T")[0];
|
|
2198
2964
|
stats.total = mergeUsage(stats.total, entry.usage);
|
|
@@ -2338,10 +3104,10 @@ var renderLogoWithEnvPanel = (envName, env, defaultMode) => {
|
|
|
2338
3104
|
const parsed = new URL(url);
|
|
2339
3105
|
const protocol = parsed.protocol + "//";
|
|
2340
3106
|
const host = parsed.host;
|
|
2341
|
-
const
|
|
3107
|
+
const path18 = parsed.pathname + parsed.search;
|
|
2342
3108
|
const hostStart = host.slice(0, 8);
|
|
2343
3109
|
const hostEnd = host.slice(-4);
|
|
2344
|
-
const pathPart =
|
|
3110
|
+
const pathPart = path18.length > 10 ? path18.slice(0, 7) + "..." : path18;
|
|
2345
3111
|
return `${protocol}${hostStart}...${hostEnd}${pathPart}`;
|
|
2346
3112
|
} catch {
|
|
2347
3113
|
return truncate(url, max);
|
|
@@ -2779,45 +3545,45 @@ var selectEnvWithKeys = (registries, current) => {
|
|
|
2779
3545
|
};
|
|
2780
3546
|
|
|
2781
3547
|
// src/permissions.ts
|
|
2782
|
-
import
|
|
3548
|
+
import fs12 from "fs";
|
|
2783
3549
|
import chalk3 from "chalk";
|
|
2784
3550
|
import Table2 from "cli-table3";
|
|
2785
3551
|
|
|
2786
3552
|
// src/utils.ts
|
|
2787
3553
|
import crypto3 from "crypto";
|
|
2788
|
-
import
|
|
2789
|
-
import
|
|
3554
|
+
import fs9 from "fs";
|
|
3555
|
+
import path9 from "path";
|
|
2790
3556
|
var SECRET_KEY = crypto3.scryptSync("claude-code-env-manager-secret", "salt", 32);
|
|
2791
3557
|
var findProjectRoot = () => {
|
|
2792
3558
|
let currentDir = process.cwd();
|
|
2793
|
-
const root =
|
|
3559
|
+
const root = path9.parse(currentDir).root;
|
|
2794
3560
|
while (currentDir !== root) {
|
|
2795
|
-
if (
|
|
3561
|
+
if (fs9.existsSync(path9.join(currentDir, ".git")) || fs9.existsSync(path9.join(currentDir, "package.json"))) {
|
|
2796
3562
|
return currentDir;
|
|
2797
3563
|
}
|
|
2798
|
-
currentDir =
|
|
3564
|
+
currentDir = path9.dirname(currentDir);
|
|
2799
3565
|
}
|
|
2800
3566
|
return process.cwd();
|
|
2801
3567
|
};
|
|
2802
3568
|
var getSettingsPath = (useLocal = true) => {
|
|
2803
3569
|
const projectRoot = findProjectRoot();
|
|
2804
|
-
const claudeDir =
|
|
3570
|
+
const claudeDir = path9.join(projectRoot, ".claude");
|
|
2805
3571
|
const filename = useLocal ? "settings.local.json" : "settings.json";
|
|
2806
|
-
return
|
|
3572
|
+
return path9.join(claudeDir, filename);
|
|
2807
3573
|
};
|
|
2808
3574
|
var ensureClaudeDir = () => {
|
|
2809
3575
|
const projectRoot = findProjectRoot();
|
|
2810
|
-
const claudeDir =
|
|
2811
|
-
if (!
|
|
2812
|
-
|
|
3576
|
+
const claudeDir = path9.join(projectRoot, ".claude");
|
|
3577
|
+
if (!fs9.existsSync(claudeDir)) {
|
|
3578
|
+
fs9.mkdirSync(claudeDir, { recursive: true });
|
|
2813
3579
|
}
|
|
2814
3580
|
return claudeDir;
|
|
2815
3581
|
};
|
|
2816
3582
|
var getGlobalClaudeConfigPath = () => {
|
|
2817
|
-
return
|
|
3583
|
+
return path9.join(getCcemAgentHome("claude"), ".claude.json");
|
|
2818
3584
|
};
|
|
2819
3585
|
var getGlobalClaudeSettingsPath = () => {
|
|
2820
|
-
return
|
|
3586
|
+
return path9.join(getCcemAgentHome("claude"), "settings.json");
|
|
2821
3587
|
};
|
|
2822
3588
|
var ensureGlobalClaudeDir = () => {
|
|
2823
3589
|
return ensureCcemAgentHome("claude");
|
|
@@ -2825,16 +3591,16 @@ var ensureGlobalClaudeDir = () => {
|
|
|
2825
3591
|
|
|
2826
3592
|
// src/launcher.ts
|
|
2827
3593
|
import { spawn as spawn2 } from "child_process";
|
|
2828
|
-
import * as
|
|
2829
|
-
import * as
|
|
3594
|
+
import * as fs11 from "fs";
|
|
3595
|
+
import * as path11 from "path";
|
|
2830
3596
|
import chalk2 from "chalk";
|
|
2831
3597
|
|
|
2832
3598
|
// src/sessionProvenance.ts
|
|
2833
3599
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
2834
|
-
import
|
|
3600
|
+
import fs10 from "fs";
|
|
2835
3601
|
import { createRequire } from "module";
|
|
2836
3602
|
import os4 from "os";
|
|
2837
|
-
import
|
|
3603
|
+
import path10 from "path";
|
|
2838
3604
|
var DEFAULT_CONFIG_SOURCE = "ccem";
|
|
2839
3605
|
var STATE_DB_FILE_NAME = "state.sqlite";
|
|
2840
3606
|
var BIND_POLL_INTERVAL_MS = 500;
|
|
@@ -2889,7 +3655,7 @@ function startCliClaudeProvenanceTracking(options) {
|
|
|
2889
3655
|
if (!jsonlPath) {
|
|
2890
3656
|
return;
|
|
2891
3657
|
}
|
|
2892
|
-
const sourceSessionId = readClaudeSessionId(jsonlPath) ?? normalizeText(
|
|
3658
|
+
const sourceSessionId = readClaudeSessionId(jsonlPath) ?? normalizeText(path10.parse(jsonlPath).name);
|
|
2893
3659
|
if (!sourceSessionId) {
|
|
2894
3660
|
return;
|
|
2895
3661
|
}
|
|
@@ -3016,7 +3782,7 @@ function bindSourceSessionId(client, ccemSessionId, sourceSessionId) {
|
|
|
3016
3782
|
}
|
|
3017
3783
|
function openNodeSqliteDb(DatabaseSync) {
|
|
3018
3784
|
const dbPath = getStateDbPath();
|
|
3019
|
-
|
|
3785
|
+
fs10.mkdirSync(path10.dirname(dbPath), { recursive: true });
|
|
3020
3786
|
const db = new DatabaseSync(dbPath);
|
|
3021
3787
|
db.exec(schemaSql());
|
|
3022
3788
|
return db;
|
|
@@ -3057,7 +3823,7 @@ function execSqlite3Cli(statementSql) {
|
|
|
3057
3823
|
throw new Error("sqlite3 CLI is unavailable and node:sqlite is not supported by this Node runtime");
|
|
3058
3824
|
}
|
|
3059
3825
|
const dbPath = getStateDbPath();
|
|
3060
|
-
|
|
3826
|
+
fs10.mkdirSync(path10.dirname(dbPath), { recursive: true });
|
|
3061
3827
|
execFileSync2("sqlite3", [dbPath], {
|
|
3062
3828
|
input: `${schemaSql()}
|
|
3063
3829
|
${statementSql}
|
|
@@ -3070,7 +3836,7 @@ function getStateDbPath() {
|
|
|
3070
3836
|
if (override) {
|
|
3071
3837
|
return override;
|
|
3072
3838
|
}
|
|
3073
|
-
return
|
|
3839
|
+
return path10.join(os4.homedir(), ".ccem", STATE_DB_FILE_NAME);
|
|
3074
3840
|
}
|
|
3075
3841
|
function schemaSql() {
|
|
3076
3842
|
return `
|
|
@@ -3096,16 +3862,16 @@ function schemaSql() {
|
|
|
3096
3862
|
`;
|
|
3097
3863
|
}
|
|
3098
3864
|
function discoverClaudeJsonlPath(projectDir, startedAtMs) {
|
|
3099
|
-
const projectsDir =
|
|
3865
|
+
const projectsDir = path10.join(getCcemAgentHome("claude"), "projects");
|
|
3100
3866
|
const earliestModifiedAt = startedAtMs - 15e3;
|
|
3101
3867
|
for (const key of projectDirKeys(projectDir)) {
|
|
3102
|
-
const baseDir =
|
|
3103
|
-
if (!
|
|
3868
|
+
const baseDir = path10.join(projectsDir, key);
|
|
3869
|
+
if (!fs10.existsSync(baseDir)) {
|
|
3104
3870
|
continue;
|
|
3105
3871
|
}
|
|
3106
|
-
const candidates =
|
|
3107
|
-
const fullPath =
|
|
3108
|
-
return { path: fullPath, modifiedAt:
|
|
3872
|
+
const candidates = fs10.readdirSync(baseDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => {
|
|
3873
|
+
const fullPath = path10.join(baseDir, entry.name);
|
|
3874
|
+
return { path: fullPath, modifiedAt: fs10.statSync(fullPath).mtimeMs };
|
|
3109
3875
|
}).filter((candidate) => candidate.modifiedAt >= earliestModifiedAt).sort((left, right) => right.modifiedAt - left.modifiedAt);
|
|
3110
3876
|
if (candidates.length > 0) {
|
|
3111
3877
|
return candidates[0].path;
|
|
@@ -3116,16 +3882,16 @@ function discoverClaudeJsonlPath(projectDir, startedAtMs) {
|
|
|
3116
3882
|
function projectDirKeys(projectDir) {
|
|
3117
3883
|
const candidates = [projectDir];
|
|
3118
3884
|
try {
|
|
3119
|
-
candidates.push(
|
|
3885
|
+
candidates.push(fs10.realpathSync(projectDir));
|
|
3120
3886
|
} catch {
|
|
3121
3887
|
}
|
|
3122
3888
|
if (process.platform === "darwin") {
|
|
3123
3889
|
if (projectDir.startsWith("/private/")) {
|
|
3124
3890
|
candidates.push(projectDir.slice("/private".length));
|
|
3125
3891
|
} else if (projectDir.startsWith("/tmp")) {
|
|
3126
|
-
candidates.push(
|
|
3892
|
+
candidates.push(path10.posix.join("/private", projectDir));
|
|
3127
3893
|
} else if (projectDir.startsWith("/var/")) {
|
|
3128
|
-
candidates.push(
|
|
3894
|
+
candidates.push(path10.posix.join("/private", projectDir));
|
|
3129
3895
|
}
|
|
3130
3896
|
}
|
|
3131
3897
|
return [...new Set(candidates.map(projectDirKey))];
|
|
@@ -3134,7 +3900,7 @@ function projectDirKey(projectDir) {
|
|
|
3134
3900
|
return projectDir.replace(/[\/\\: ]/g, "-");
|
|
3135
3901
|
}
|
|
3136
3902
|
function readClaudeSessionId(jsonlPath) {
|
|
3137
|
-
const lines =
|
|
3903
|
+
const lines = fs10.readFileSync(jsonlPath, "utf8").split("\n");
|
|
3138
3904
|
for (const line of lines) {
|
|
3139
3905
|
if (!line.trim()) {
|
|
3140
3906
|
continue;
|
|
@@ -3209,9 +3975,9 @@ function buildPermArgs(modeName) {
|
|
|
3209
3975
|
return args;
|
|
3210
3976
|
}
|
|
3211
3977
|
function ensureSessionsDir() {
|
|
3212
|
-
const dir =
|
|
3213
|
-
if (!
|
|
3214
|
-
|
|
3978
|
+
const dir = path11.join(ensureCcemDir(), "sessions");
|
|
3979
|
+
if (!fs11.existsSync(dir)) {
|
|
3980
|
+
fs11.mkdirSync(dir, { recursive: true });
|
|
3215
3981
|
}
|
|
3216
3982
|
return dir;
|
|
3217
3983
|
}
|
|
@@ -3282,8 +4048,8 @@ async function launchClaude(options) {
|
|
|
3282
4048
|
provenanceTracking?.stop();
|
|
3283
4049
|
if (sessionId) {
|
|
3284
4050
|
try {
|
|
3285
|
-
|
|
3286
|
-
|
|
4051
|
+
fs11.writeFileSync(
|
|
4052
|
+
path11.join(sessionsDir, `${sessionId}.exit`),
|
|
3287
4053
|
String(code ?? 0)
|
|
3288
4054
|
);
|
|
3289
4055
|
} catch {
|
|
@@ -3353,14 +4119,14 @@ var formatPermissionRulesForDisplay = (rules) => {
|
|
|
3353
4119
|
}).join("\n");
|
|
3354
4120
|
};
|
|
3355
4121
|
var readSettings = (settingsPath) => {
|
|
3356
|
-
if (
|
|
4122
|
+
if (fs12.existsSync(settingsPath)) {
|
|
3357
4123
|
try {
|
|
3358
|
-
const content =
|
|
4124
|
+
const content = fs12.readFileSync(settingsPath, "utf-8");
|
|
3359
4125
|
return JSON.parse(content);
|
|
3360
4126
|
} catch {
|
|
3361
4127
|
console.warn(chalk3.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${settingsPath}\uFF0C\u5C06\u521B\u5EFA\u5907\u4EFD`));
|
|
3362
4128
|
const backupPath = settingsPath + ".error." + Date.now();
|
|
3363
|
-
|
|
4129
|
+
fs12.copyFileSync(settingsPath, backupPath);
|
|
3364
4130
|
console.log(chalk3.gray(`\u5907\u4EFD\u5DF2\u4FDD\u5B58\u5230: ${backupPath}`));
|
|
3365
4131
|
return {};
|
|
3366
4132
|
}
|
|
@@ -3369,7 +4135,7 @@ var readSettings = (settingsPath) => {
|
|
|
3369
4135
|
};
|
|
3370
4136
|
var writeSettings = (settingsPath, config3) => {
|
|
3371
4137
|
ensureClaudeDir();
|
|
3372
|
-
|
|
4138
|
+
fs12.writeFileSync(settingsPath, JSON.stringify(config3, null, 2) + "\n");
|
|
3373
4139
|
};
|
|
3374
4140
|
var mergePermissions = (existing, preset) => {
|
|
3375
4141
|
const existingAllow = normalizePermissionAllowRules(existing.permissions?.allow || []);
|
|
@@ -3402,14 +4168,14 @@ var applyPermissionMode = (modeName) => {
|
|
|
3402
4168
|
};
|
|
3403
4169
|
var resetPermissions = () => {
|
|
3404
4170
|
const settingsPath = getSettingsPath(true);
|
|
3405
|
-
if (!
|
|
4171
|
+
if (!fs12.existsSync(settingsPath)) {
|
|
3406
4172
|
console.log(chalk3.yellow("\u6CA1\u6709\u81EA\u5B9A\u4E49\u6743\u9650\u914D\u7F6E\u9700\u8981\u91CD\u7F6E"));
|
|
3407
4173
|
return;
|
|
3408
4174
|
}
|
|
3409
4175
|
const config3 = readSettings(settingsPath);
|
|
3410
4176
|
delete config3.permissions;
|
|
3411
4177
|
if (Object.keys(config3).length === 0) {
|
|
3412
|
-
|
|
4178
|
+
fs12.unlinkSync(settingsPath);
|
|
3413
4179
|
console.log(chalk3.green("\u5DF2\u5220\u9664\u914D\u7F6E\u6587\u4EF6\uFF08\u6587\u4EF6\u4E3A\u7A7A\uFF09"));
|
|
3414
4180
|
} else {
|
|
3415
4181
|
writeSettings(settingsPath, config3);
|
|
@@ -3419,7 +4185,7 @@ var resetPermissions = () => {
|
|
|
3419
4185
|
};
|
|
3420
4186
|
var showCurrentMode = () => {
|
|
3421
4187
|
const settingsPath = getSettingsPath(true);
|
|
3422
|
-
if (!
|
|
4188
|
+
if (!fs12.existsSync(settingsPath)) {
|
|
3423
4189
|
console.log(chalk3.yellow("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49\u6743\u9650"));
|
|
3424
4190
|
console.log(chalk3.gray(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${settingsPath}`));
|
|
3425
4191
|
return;
|
|
@@ -3478,14 +4244,14 @@ var runWithTempPermissions = async (modeName, envConfig, envName) => {
|
|
|
3478
4244
|
};
|
|
3479
4245
|
|
|
3480
4246
|
// src/environmentMutations.ts
|
|
3481
|
-
import
|
|
3482
|
-
import
|
|
4247
|
+
import fs13 from "fs";
|
|
4248
|
+
import path12 from "path";
|
|
3483
4249
|
function nativeRuntimeStatePath() {
|
|
3484
|
-
return
|
|
4250
|
+
return path12.join(getCcemConfigDir(), "native-runtime-state.json");
|
|
3485
4251
|
}
|
|
3486
4252
|
function resolveMutationAuthority(options) {
|
|
3487
|
-
const descriptorExists = options.descriptorExists ?? (() =>
|
|
3488
|
-
const stateExists = options.stateExists ?? (() =>
|
|
4253
|
+
const descriptorExists = options.descriptorExists ?? (() => fs13.existsSync(getDesktopControlDescriptorPath()));
|
|
4254
|
+
const stateExists = options.stateExists ?? (() => fs13.existsSync(nativeRuntimeStatePath()));
|
|
3489
4255
|
return { descriptorExists, stateExists };
|
|
3490
4256
|
}
|
|
3491
4257
|
function assertOfflineMutationIsSafe(name, stateExists) {
|
|
@@ -3585,13 +4351,13 @@ function deleteEnvironmentFromConfig(config3, name) {
|
|
|
3585
4351
|
}
|
|
3586
4352
|
|
|
3587
4353
|
// src/setup.ts
|
|
3588
|
-
import
|
|
4354
|
+
import fs14 from "fs";
|
|
3589
4355
|
import chalk4 from "chalk";
|
|
3590
4356
|
import { spawn as spawn3 } from "child_process";
|
|
3591
4357
|
var readJsonFile = (filePath) => {
|
|
3592
|
-
if (
|
|
4358
|
+
if (fs14.existsSync(filePath)) {
|
|
3593
4359
|
try {
|
|
3594
|
-
const content =
|
|
4360
|
+
const content = fs14.readFileSync(filePath, "utf-8");
|
|
3595
4361
|
return JSON.parse(content);
|
|
3596
4362
|
} catch {
|
|
3597
4363
|
console.warn(chalk4.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${filePath}`));
|
|
@@ -3601,7 +4367,7 @@ var readJsonFile = (filePath) => {
|
|
|
3601
4367
|
return {};
|
|
3602
4368
|
};
|
|
3603
4369
|
var writeJsonFile = (filePath, data) => {
|
|
3604
|
-
|
|
4370
|
+
fs14.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
|
|
3605
4371
|
};
|
|
3606
4372
|
var setupOnboarding = () => {
|
|
3607
4373
|
const configPath = getGlobalClaudeConfigPath();
|
|
@@ -3635,14 +4401,14 @@ var setupEnvSettings = () => {
|
|
|
3635
4401
|
"DISABLE_ERROR_REPORTING": "1",
|
|
3636
4402
|
"DISABLE_TELEMETRY": "1"
|
|
3637
4403
|
};
|
|
3638
|
-
let
|
|
4404
|
+
let changed2 = false;
|
|
3639
4405
|
for (const [key, value] of Object.entries(envVars)) {
|
|
3640
4406
|
if (env[key] !== value) {
|
|
3641
4407
|
env[key] = value;
|
|
3642
|
-
|
|
4408
|
+
changed2 = true;
|
|
3643
4409
|
}
|
|
3644
4410
|
}
|
|
3645
|
-
if (!
|
|
4411
|
+
if (!changed2) {
|
|
3646
4412
|
console.log(chalk4.gray(" \u2713 \u73AF\u5883\u53D8\u91CF\u5DF2\u914D\u7F6E"));
|
|
3647
4413
|
return true;
|
|
3648
4414
|
}
|
|
@@ -3730,8 +4496,8 @@ var runSetupInit = async (options = {}) => {
|
|
|
3730
4496
|
|
|
3731
4497
|
// src/skills.ts
|
|
3732
4498
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
3733
|
-
import * as
|
|
3734
|
-
import * as
|
|
4499
|
+
import * as fs15 from "fs";
|
|
4500
|
+
import * as path13 from "path";
|
|
3735
4501
|
import chalk5 from "chalk";
|
|
3736
4502
|
var SKILL_GROUPS = {
|
|
3737
4503
|
official: { label: "\u5B98\u65B9", icon: "\u{1F3E2}" },
|
|
@@ -3967,7 +4733,7 @@ function parseGitHubUrl(url) {
|
|
|
3967
4733
|
repo,
|
|
3968
4734
|
branch,
|
|
3969
4735
|
repoPath,
|
|
3970
|
-
repoPath ?
|
|
4736
|
+
repoPath ? path13.basename(repoPath) : repo
|
|
3971
4737
|
);
|
|
3972
4738
|
return { owner, repo, branch, path: repoPath };
|
|
3973
4739
|
} catch {
|
|
@@ -3975,12 +4741,12 @@ function parseGitHubUrl(url) {
|
|
|
3975
4741
|
}
|
|
3976
4742
|
}
|
|
3977
4743
|
function getSkillsDir() {
|
|
3978
|
-
return
|
|
4744
|
+
return path13.join(process.cwd(), ".claude", "skills");
|
|
3979
4745
|
}
|
|
3980
4746
|
function ensureSkillsDir() {
|
|
3981
4747
|
const skillsDir = getSkillsDir();
|
|
3982
|
-
if (!
|
|
3983
|
-
|
|
4748
|
+
if (!fs15.existsSync(skillsDir)) {
|
|
4749
|
+
fs15.mkdirSync(skillsDir, { recursive: true });
|
|
3984
4750
|
} else {
|
|
3985
4751
|
cleanupTempDirs(skillsDir);
|
|
3986
4752
|
}
|
|
@@ -3988,11 +4754,11 @@ function ensureSkillsDir() {
|
|
|
3988
4754
|
}
|
|
3989
4755
|
function cleanupTempDirs(skillsDir) {
|
|
3990
4756
|
try {
|
|
3991
|
-
const entries =
|
|
4757
|
+
const entries = fs15.readdirSync(skillsDir, { withFileTypes: true });
|
|
3992
4758
|
for (const entry of entries) {
|
|
3993
4759
|
if (entry.isDirectory() && entry.name.startsWith(".tmp-")) {
|
|
3994
|
-
const tmpPath =
|
|
3995
|
-
|
|
4760
|
+
const tmpPath = path13.join(skillsDir, entry.name);
|
|
4761
|
+
fs15.rmSync(tmpPath, { recursive: true });
|
|
3996
4762
|
}
|
|
3997
4763
|
}
|
|
3998
4764
|
} catch {
|
|
@@ -4003,27 +4769,27 @@ function downloadSkillWithGit(owner, repo, branch, repoPath, targetName) {
|
|
|
4003
4769
|
try {
|
|
4004
4770
|
validateGitHubInstallParts(owner, repo, branch, repoPath, targetName);
|
|
4005
4771
|
const skillsDir = ensureSkillsDir();
|
|
4006
|
-
const targetDir =
|
|
4007
|
-
if (
|
|
4772
|
+
const targetDir = path13.join(skillsDir, targetName);
|
|
4773
|
+
if (fs15.existsSync(targetDir)) {
|
|
4008
4774
|
console.log(chalk5.yellow(`Skill "${targetName}" already exists. Updating...`));
|
|
4009
|
-
|
|
4775
|
+
fs15.rmSync(targetDir, { recursive: true });
|
|
4010
4776
|
}
|
|
4011
4777
|
const repoUrl = `https://github.com/${owner}/${repo}.git`;
|
|
4012
|
-
tempDir =
|
|
4013
|
-
|
|
4778
|
+
tempDir = path13.join(skillsDir, `.tmp-${Date.now()}`);
|
|
4779
|
+
fs15.mkdirSync(tempDir, { recursive: true });
|
|
4014
4780
|
execFileSync3("git", ["init"], { cwd: tempDir, stdio: "pipe" });
|
|
4015
4781
|
execFileSync3("git", ["remote", "add", "origin", repoUrl], { cwd: tempDir, stdio: "pipe" });
|
|
4016
4782
|
execFileSync3("git", ["config", "core.sparseCheckout", "true"], { cwd: tempDir, stdio: "pipe" });
|
|
4017
|
-
const sparseFile =
|
|
4018
|
-
|
|
4019
|
-
|
|
4783
|
+
const sparseFile = path13.join(tempDir, ".git", "info", "sparse-checkout");
|
|
4784
|
+
fs15.mkdirSync(path13.dirname(sparseFile), { recursive: true });
|
|
4785
|
+
fs15.writeFileSync(sparseFile, repoPath ? `${repoPath}/
|
|
4020
4786
|
` : "*\n");
|
|
4021
4787
|
execFileSync3("git", ["pull", "--depth=1", "origin", branch], {
|
|
4022
4788
|
cwd: tempDir,
|
|
4023
4789
|
stdio: "pipe"
|
|
4024
4790
|
});
|
|
4025
|
-
const sourceDir = repoPath ?
|
|
4026
|
-
if (!
|
|
4791
|
+
const sourceDir = repoPath ? path13.join(tempDir, repoPath) : tempDir;
|
|
4792
|
+
if (!fs15.existsSync(sourceDir)) {
|
|
4027
4793
|
throw new Error(`Path "${repoPath}" not found in repository`);
|
|
4028
4794
|
}
|
|
4029
4795
|
copyDir(sourceDir, targetDir);
|
|
@@ -4034,31 +4800,31 @@ function downloadSkillWithGit(owner, repo, branch, repoPath, targetName) {
|
|
|
4034
4800
|
console.error(chalk5.red(`Failed to download skill: ${errMsg}`));
|
|
4035
4801
|
return false;
|
|
4036
4802
|
} finally {
|
|
4037
|
-
if (tempDir &&
|
|
4038
|
-
|
|
4803
|
+
if (tempDir && fs15.existsSync(tempDir)) {
|
|
4804
|
+
fs15.rmSync(tempDir, { recursive: true });
|
|
4039
4805
|
}
|
|
4040
4806
|
}
|
|
4041
4807
|
}
|
|
4042
4808
|
function copyDir(src, dest) {
|
|
4043
|
-
|
|
4044
|
-
const entries =
|
|
4809
|
+
fs15.mkdirSync(dest, { recursive: true });
|
|
4810
|
+
const entries = fs15.readdirSync(src, { withFileTypes: true });
|
|
4045
4811
|
for (const entry of entries) {
|
|
4046
4812
|
if (entry.name === ".git") continue;
|
|
4047
|
-
const srcPath =
|
|
4048
|
-
const destPath =
|
|
4813
|
+
const srcPath = path13.join(src, entry.name);
|
|
4814
|
+
const destPath = path13.join(dest, entry.name);
|
|
4049
4815
|
if (entry.isDirectory()) {
|
|
4050
4816
|
copyDir(srcPath, destPath);
|
|
4051
4817
|
} else {
|
|
4052
|
-
|
|
4818
|
+
fs15.copyFileSync(srcPath, destPath);
|
|
4053
4819
|
}
|
|
4054
4820
|
}
|
|
4055
4821
|
}
|
|
4056
4822
|
function isSafeSkillName(name) {
|
|
4057
|
-
return name.trim().length > 0 && name !== "." && name !== ".." && !name.startsWith(".") && !
|
|
4823
|
+
return name.trim().length > 0 && name !== "." && name !== ".." && !name.startsWith(".") && !path13.isAbsolute(name) && !name.includes("/") && !name.includes("\\") && !name.includes("\0");
|
|
4058
4824
|
}
|
|
4059
4825
|
function isPathInside(childPath, parentPath) {
|
|
4060
|
-
const relativePath =
|
|
4061
|
-
return relativePath === "" || relativePath.length > 0 && !relativePath.startsWith("..") && !
|
|
4826
|
+
const relativePath = path13.relative(parentPath, childPath);
|
|
4827
|
+
return relativePath === "" || relativePath.length > 0 && !relativePath.startsWith("..") && !path13.isAbsolute(relativePath);
|
|
4062
4828
|
}
|
|
4063
4829
|
function addSkillFromGitHub(urlOrPreset) {
|
|
4064
4830
|
const preset = SKILL_PRESETS.find((p) => p.name === urlOrPreset);
|
|
@@ -4102,7 +4868,7 @@ function addSkillFromGitHub(urlOrPreset) {
|
|
|
4102
4868
|
}
|
|
4103
4869
|
let skillName;
|
|
4104
4870
|
if (parsed.path) {
|
|
4105
|
-
skillName =
|
|
4871
|
+
skillName = path13.basename(parsed.path);
|
|
4106
4872
|
} else {
|
|
4107
4873
|
skillName = parsed.repo;
|
|
4108
4874
|
}
|
|
@@ -4116,13 +4882,13 @@ function addSkillFromGitHub(urlOrPreset) {
|
|
|
4116
4882
|
}
|
|
4117
4883
|
function listInstalledSkills() {
|
|
4118
4884
|
const skillsDir = getSkillsDir();
|
|
4119
|
-
if (!
|
|
4885
|
+
if (!fs15.existsSync(skillsDir)) {
|
|
4120
4886
|
return [];
|
|
4121
4887
|
}
|
|
4122
|
-
const entries =
|
|
4888
|
+
const entries = fs15.readdirSync(skillsDir, { withFileTypes: true });
|
|
4123
4889
|
return entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => ({
|
|
4124
4890
|
name: entry.name,
|
|
4125
|
-
path:
|
|
4891
|
+
path: path13.join(skillsDir, entry.name)
|
|
4126
4892
|
}));
|
|
4127
4893
|
}
|
|
4128
4894
|
function removeSkill(name) {
|
|
@@ -4131,18 +4897,18 @@ function removeSkill(name) {
|
|
|
4131
4897
|
return false;
|
|
4132
4898
|
}
|
|
4133
4899
|
const skillsDir = getSkillsDir();
|
|
4134
|
-
const targetDir =
|
|
4135
|
-
if (!
|
|
4900
|
+
const targetDir = path13.resolve(skillsDir, name);
|
|
4901
|
+
if (!fs15.existsSync(targetDir)) {
|
|
4136
4902
|
console.error(chalk5.red(`Skill "${name}" not found`));
|
|
4137
4903
|
return false;
|
|
4138
4904
|
}
|
|
4139
|
-
const canonicalSkillsDir =
|
|
4140
|
-
const canonicalTargetDir =
|
|
4905
|
+
const canonicalSkillsDir = fs15.realpathSync(skillsDir);
|
|
4906
|
+
const canonicalTargetDir = fs15.realpathSync(targetDir);
|
|
4141
4907
|
if (!isPathInside(canonicalTargetDir, canonicalSkillsDir)) {
|
|
4142
4908
|
console.error(chalk5.red(`Refusing to remove skill outside skills directory: "${name}"`));
|
|
4143
4909
|
return false;
|
|
4144
4910
|
}
|
|
4145
|
-
|
|
4911
|
+
fs15.rmSync(targetDir, { recursive: true });
|
|
4146
4912
|
console.log(chalk5.green(`Removed skill "${name}"`));
|
|
4147
4913
|
return true;
|
|
4148
4914
|
}
|
|
@@ -4697,9 +5463,9 @@ import Table3 from "cli-table3";
|
|
|
4697
5463
|
|
|
4698
5464
|
// src/cron.ts
|
|
4699
5465
|
import crypto5 from "crypto";
|
|
4700
|
-
import * as
|
|
5466
|
+
import * as fs16 from "fs";
|
|
4701
5467
|
import * as os5 from "os";
|
|
4702
|
-
import * as
|
|
5468
|
+
import * as path14 from "path";
|
|
4703
5469
|
function parseHermesNotification(value) {
|
|
4704
5470
|
if (value == null) return null;
|
|
4705
5471
|
const target = value;
|
|
@@ -4763,13 +5529,13 @@ var EXECUTION_PROFILES = /* @__PURE__ */ new Set([
|
|
|
4763
5529
|
"autonomous"
|
|
4764
5530
|
]);
|
|
4765
5531
|
function getCronTasksPath(baseDir = getCcemConfigDir()) {
|
|
4766
|
-
return
|
|
5532
|
+
return path14.join(baseDir, CRON_TASKS_FILE_NAME);
|
|
4767
5533
|
}
|
|
4768
5534
|
function readCronTasks(tasksPath = getCronTasksPath()) {
|
|
4769
|
-
if (!
|
|
5535
|
+
if (!fs16.existsSync(tasksPath)) {
|
|
4770
5536
|
return [];
|
|
4771
5537
|
}
|
|
4772
|
-
const content =
|
|
5538
|
+
const content = fs16.readFileSync(tasksPath, "utf-8").trim();
|
|
4773
5539
|
if (!content) {
|
|
4774
5540
|
return [];
|
|
4775
5541
|
}
|
|
@@ -4784,14 +5550,14 @@ function writeCronTasks(tasks, tasksPath = getCronTasksPath()) {
|
|
|
4784
5550
|
if (tasksPath === getCronTasksPath()) {
|
|
4785
5551
|
ensureCcemDir();
|
|
4786
5552
|
} else {
|
|
4787
|
-
|
|
5553
|
+
fs16.mkdirSync(path14.dirname(tasksPath), { recursive: true });
|
|
4788
5554
|
}
|
|
4789
5555
|
const payload = { tasks };
|
|
4790
5556
|
const content = `${JSON.stringify(payload, null, 2)}
|
|
4791
5557
|
`;
|
|
4792
5558
|
const tempPath = `${tasksPath}.${process.pid}.${Date.now()}.tmp`;
|
|
4793
|
-
|
|
4794
|
-
|
|
5559
|
+
fs16.writeFileSync(tempPath, content, { encoding: "utf-8", mode: 384 });
|
|
5560
|
+
fs16.renameSync(tempPath, tasksPath);
|
|
4795
5561
|
}
|
|
4796
5562
|
function validateCronExpression(cronExpression) {
|
|
4797
5563
|
const fields = cronExpression.trim().split(/\s+/);
|
|
@@ -4918,10 +5684,10 @@ function deleteCronTask(selector, tasksPath = getCronTasksPath()) {
|
|
|
4918
5684
|
}
|
|
4919
5685
|
function resolveJsonInput(raw) {
|
|
4920
5686
|
if (raw === "-") {
|
|
4921
|
-
return
|
|
5687
|
+
return fs16.readFileSync(0, "utf-8");
|
|
4922
5688
|
}
|
|
4923
5689
|
if (raw.startsWith("@")) {
|
|
4924
|
-
return
|
|
5690
|
+
return fs16.readFileSync(path14.resolve(raw.slice(1)), "utf-8");
|
|
4925
5691
|
}
|
|
4926
5692
|
return raw;
|
|
4927
5693
|
}
|
|
@@ -5066,7 +5832,7 @@ function registerCronCommands(program2) {
|
|
|
5066
5832
|
import chalk8 from "chalk";
|
|
5067
5833
|
|
|
5068
5834
|
// src/dsh/provider.ts
|
|
5069
|
-
import { createHash } from "crypto";
|
|
5835
|
+
import { createHash as createHash3 } from "crypto";
|
|
5070
5836
|
var DSH_API_KEY_ENV = "CCEM_DSH_API_KEY";
|
|
5071
5837
|
var DSH_PROTOCOL = "anthropic-messages";
|
|
5072
5838
|
var DSH_TIERS = ["opus", "sonnet", "haiku"];
|
|
@@ -5109,7 +5875,7 @@ function collectDshModels(envName, envConfig) {
|
|
|
5109
5875
|
}
|
|
5110
5876
|
function generateProviderId(envName) {
|
|
5111
5877
|
const slug = envName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24) || "env";
|
|
5112
|
-
const hash =
|
|
5878
|
+
const hash = createHash3("sha256").update(envName).digest("hex").slice(0, 12);
|
|
5113
5879
|
return `ccem-${slug}-${hash}`;
|
|
5114
5880
|
}
|
|
5115
5881
|
function verifyTokenPresence(envConfig) {
|
|
@@ -5198,9 +5964,9 @@ function deriveDshProvider(envName, envConfig, options = {}) {
|
|
|
5198
5964
|
|
|
5199
5965
|
// src/dsh/launcher.ts
|
|
5200
5966
|
import { spawn as defaultSpawn } from "child_process";
|
|
5201
|
-
import * as
|
|
5967
|
+
import * as fs18 from "fs";
|
|
5202
5968
|
import * as os7 from "os";
|
|
5203
|
-
import * as
|
|
5969
|
+
import * as path16 from "path";
|
|
5204
5970
|
|
|
5205
5971
|
// src/dsh/patch.ts
|
|
5206
5972
|
var IDENTIFIER_PATTERN = /^[A-Za-z0-9][\w./-]*$/;
|
|
@@ -5238,9 +6004,9 @@ function renderCordisPatch(spec) {
|
|
|
5238
6004
|
|
|
5239
6005
|
// src/dsh/environment.ts
|
|
5240
6006
|
import { execFile } from "child_process";
|
|
5241
|
-
import * as
|
|
6007
|
+
import * as fs17 from "fs";
|
|
5242
6008
|
import * as os6 from "os";
|
|
5243
|
-
import * as
|
|
6009
|
+
import * as path15 from "path";
|
|
5244
6010
|
import { promisify } from "util";
|
|
5245
6011
|
|
|
5246
6012
|
// src/dsh/version.ts
|
|
@@ -5311,17 +6077,17 @@ function resolveDshRoot(env = process.env) {
|
|
|
5311
6077
|
const inherited = env.DSH_HOME?.trim();
|
|
5312
6078
|
if (inherited) return inherited;
|
|
5313
6079
|
const home = env.HOME?.trim() || os6.homedir();
|
|
5314
|
-
return
|
|
6080
|
+
return path15.join(home, ".dsh");
|
|
5315
6081
|
}
|
|
5316
6082
|
function resolveBinOnPath(name, env = process.env, platform = process.platform) {
|
|
5317
6083
|
if (name.includes("/") || platform === "win32" && name.includes("\\")) {
|
|
5318
6084
|
return fileIsExecutable(name, platform) ? name : null;
|
|
5319
6085
|
}
|
|
5320
|
-
const searchDirs = (env.PATH ?? "").split(
|
|
6086
|
+
const searchDirs = (env.PATH ?? "").split(path15.delimiter).filter(Boolean);
|
|
5321
6087
|
const extensions = platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").toLowerCase().split(";").filter(Boolean) : [""];
|
|
5322
6088
|
for (const dir of searchDirs) {
|
|
5323
6089
|
for (const ext of extensions) {
|
|
5324
|
-
const candidate =
|
|
6090
|
+
const candidate = path15.join(dir, name + ext);
|
|
5325
6091
|
if (fileIsExecutable(candidate, platform)) return candidate;
|
|
5326
6092
|
}
|
|
5327
6093
|
}
|
|
@@ -5330,10 +6096,10 @@ function resolveBinOnPath(name, env = process.env, platform = process.platform)
|
|
|
5330
6096
|
function fileIsExecutable(file, platform = process.platform) {
|
|
5331
6097
|
try {
|
|
5332
6098
|
if (platform === "win32") {
|
|
5333
|
-
return
|
|
6099
|
+
return fs17.statSync(file).isFile();
|
|
5334
6100
|
}
|
|
5335
|
-
|
|
5336
|
-
return
|
|
6101
|
+
fs17.accessSync(file, fs17.constants.X_OK);
|
|
6102
|
+
return fs17.statSync(file).isFile();
|
|
5337
6103
|
} catch {
|
|
5338
6104
|
return false;
|
|
5339
6105
|
}
|
|
@@ -5351,15 +6117,15 @@ function resolveDshInvocation(deps = {}) {
|
|
|
5351
6117
|
function resolveWindowsDshInvocation(env) {
|
|
5352
6118
|
const dshFile = resolveBinOnPath("dsh", env, "win32");
|
|
5353
6119
|
if (!dshFile) return null;
|
|
5354
|
-
const ext =
|
|
6120
|
+
const ext = path15.extname(dshFile).toLowerCase();
|
|
5355
6121
|
if (ext === ".exe" || ext === ".com") {
|
|
5356
6122
|
return { bin: dshFile, prefix: [] };
|
|
5357
6123
|
}
|
|
5358
6124
|
if (ext !== ".cmd") return null;
|
|
5359
|
-
const shimDir =
|
|
6125
|
+
const shimDir = path15.dirname(dshFile);
|
|
5360
6126
|
const candidates = [
|
|
5361
|
-
|
|
5362
|
-
|
|
6127
|
+
path15.join(shimDir, "node_modules", "@deepseek-ai", "dsh"),
|
|
6128
|
+
path15.join(shimDir, "..", "node_modules", "@deepseek-ai", "dsh")
|
|
5363
6129
|
];
|
|
5364
6130
|
for (const pkgDir of candidates) {
|
|
5365
6131
|
const entryScript = verifyDshPackage(pkgDir);
|
|
@@ -5372,18 +6138,18 @@ function resolveWindowsDshInvocation(env) {
|
|
|
5372
6138
|
return null;
|
|
5373
6139
|
}
|
|
5374
6140
|
function verifyDshPackage(pkgDir) {
|
|
5375
|
-
const pkgJsonPath =
|
|
6141
|
+
const pkgJsonPath = path15.join(pkgDir, "package.json");
|
|
5376
6142
|
try {
|
|
5377
|
-
const raw =
|
|
6143
|
+
const raw = fs17.readFileSync(pkgJsonPath, "utf-8");
|
|
5378
6144
|
const pkg2 = JSON.parse(raw);
|
|
5379
6145
|
if (pkg2.name !== "@deepseek-ai/dsh") return null;
|
|
5380
6146
|
const binEntry = typeof pkg2.bin === "string" ? pkg2.bin : pkg2.bin?.dsh ?? null;
|
|
5381
6147
|
if (!binEntry || typeof binEntry !== "string") return null;
|
|
5382
|
-
const entryPath =
|
|
5383
|
-
const realEntry =
|
|
5384
|
-
const realPkgDir =
|
|
5385
|
-
if (!realEntry.startsWith(realPkgDir +
|
|
5386
|
-
if (!
|
|
6148
|
+
const entryPath = path15.resolve(pkgDir, binEntry);
|
|
6149
|
+
const realEntry = fs17.realpathSync(entryPath);
|
|
6150
|
+
const realPkgDir = fs17.realpathSync(pkgDir);
|
|
6151
|
+
if (!realEntry.startsWith(realPkgDir + path15.sep) && realEntry !== realPkgDir) return null;
|
|
6152
|
+
if (!fs17.statSync(realEntry).isFile()) return null;
|
|
5387
6153
|
return realEntry;
|
|
5388
6154
|
} catch {
|
|
5389
6155
|
return null;
|
|
@@ -5521,7 +6287,7 @@ var DSH_PERMISSION_MODES = [
|
|
|
5521
6287
|
];
|
|
5522
6288
|
var DSH_PERMISSION_ENV = "DSH_PERMISSION_MODE";
|
|
5523
6289
|
function cleanupTempDir(dir) {
|
|
5524
|
-
|
|
6290
|
+
fs18.rmSync(dir, { recursive: true, force: true });
|
|
5525
6291
|
}
|
|
5526
6292
|
function signalExitCode(signal) {
|
|
5527
6293
|
if (!signal) return 1;
|
|
@@ -5626,10 +6392,10 @@ async function runDshTask(options) {
|
|
|
5626
6392
|
};
|
|
5627
6393
|
}
|
|
5628
6394
|
const inheritedDshHome = env.DSH_HOME?.trim() || void 0;
|
|
5629
|
-
const tempDir =
|
|
5630
|
-
const patchPath =
|
|
6395
|
+
const tempDir = fs18.mkdtempSync(path16.join(os7.tmpdir(), "ccem-dsh-"));
|
|
6396
|
+
const patchPath = path16.join(tempDir, "cordis.ccem.patch.yml");
|
|
5631
6397
|
const patchContent = renderCordisPatch(options.spec);
|
|
5632
|
-
|
|
6398
|
+
fs18.writeFileSync(patchPath, patchContent, { mode: 384 });
|
|
5633
6399
|
let exitCode = null;
|
|
5634
6400
|
let signal = null;
|
|
5635
6401
|
let spawnError = null;
|
|
@@ -5998,9 +6764,9 @@ Note: Use -- to separate task text from options if the task could be
|
|
|
5998
6764
|
|
|
5999
6765
|
// src/index.ts
|
|
6000
6766
|
var __filename2 = fileURLToPath2(import.meta.url);
|
|
6001
|
-
var __dirname2 =
|
|
6002
|
-
var pkgPath =
|
|
6003
|
-
var pkg = JSON.parse(
|
|
6767
|
+
var __dirname2 = path17.dirname(__filename2);
|
|
6768
|
+
var pkgPath = path17.resolve(__dirname2, "..", "package.json");
|
|
6769
|
+
var pkg = JSON.parse(fs19.readFileSync(pkgPath, "utf-8"));
|
|
6004
6770
|
var program = new Command();
|
|
6005
6771
|
var DEFAULT_OFFICIAL_ENV = {
|
|
6006
6772
|
ANTHROPIC_BASE_URL: "https://api.anthropic.com",
|
|
@@ -6087,13 +6853,13 @@ var recoverRegistriesFromLegacy = (registries) => {
|
|
|
6087
6853
|
return registries;
|
|
6088
6854
|
}
|
|
6089
6855
|
const legacyConfigPath = getLegacyConfigPath();
|
|
6090
|
-
if (!
|
|
6856
|
+
if (!fs19.existsSync(legacyConfigPath)) {
|
|
6091
6857
|
return registries;
|
|
6092
6858
|
}
|
|
6093
6859
|
try {
|
|
6094
|
-
const legacyRaw = JSON.parse(
|
|
6860
|
+
const legacyRaw = JSON.parse(fs19.readFileSync(legacyConfigPath, "utf-8"));
|
|
6095
6861
|
const legacyRegistries = legacyRaw.registries ?? {};
|
|
6096
|
-
let
|
|
6862
|
+
let changed2 = false;
|
|
6097
6863
|
const recovered = { ...registries };
|
|
6098
6864
|
for (const [name, envConfig] of Object.entries(registries)) {
|
|
6099
6865
|
const legacyEnvConfig = legacyRegistries[name];
|
|
@@ -6103,10 +6869,10 @@ var recoverRegistriesFromLegacy = (registries) => {
|
|
|
6103
6869
|
const recoveredEnv = recoverEnvConfigFromLegacy(envConfig, legacyEnvConfig);
|
|
6104
6870
|
if (JSON.stringify(recoveredEnv) !== JSON.stringify(envConfig)) {
|
|
6105
6871
|
recovered[name] = recoveredEnv;
|
|
6106
|
-
|
|
6872
|
+
changed2 = true;
|
|
6107
6873
|
}
|
|
6108
6874
|
}
|
|
6109
|
-
return
|
|
6875
|
+
return changed2 ? recovered : registries;
|
|
6110
6876
|
} catch {
|
|
6111
6877
|
return registries;
|
|
6112
6878
|
}
|
|
@@ -6123,8 +6889,8 @@ var getRegistries = () => {
|
|
|
6123
6889
|
repairedRegistries[OFFICIAL_ENV_NAME] = { ...DEFAULT_OFFICIAL_ENV };
|
|
6124
6890
|
}
|
|
6125
6891
|
assertOfficialEnvironmentInvariant(repairedRegistries);
|
|
6126
|
-
const
|
|
6127
|
-
if (
|
|
6892
|
+
const changed2 = Object.keys(rawRegistries).length !== Object.keys(repairedRegistries).length || JSON.stringify(rawRegistries) !== JSON.stringify(repairedRegistries);
|
|
6893
|
+
if (changed2) {
|
|
6128
6894
|
config2.set("registries", repairedRegistries);
|
|
6129
6895
|
}
|
|
6130
6896
|
return repairedRegistries;
|
|
@@ -6294,15 +7060,15 @@ var switchEnvironment = async (name) => {
|
|
|
6294
7060
|
exportCmds.forEach((cmd) => console.log(cmd));
|
|
6295
7061
|
}
|
|
6296
7062
|
};
|
|
6297
|
-
var getSessionsFilePath = () =>
|
|
6298
|
-
var getRuntimeStateFilePath = () =>
|
|
6299
|
-
var getBotBindRequestFilePath = () =>
|
|
7063
|
+
var getSessionsFilePath = () => path17.join(getCcemConfigDir(), "sessions.json");
|
|
7064
|
+
var getRuntimeStateFilePath = () => path17.join(getCcemConfigDir(), "runtime-state.json");
|
|
7065
|
+
var getBotBindRequestFilePath = () => path17.join(getCcemConfigDir(), "bot-bind-requests.jsonl");
|
|
6300
7066
|
var parseJsonFile = (filePath) => {
|
|
6301
|
-
if (!
|
|
7067
|
+
if (!fs19.existsSync(filePath)) {
|
|
6302
7068
|
return null;
|
|
6303
7069
|
}
|
|
6304
7070
|
try {
|
|
6305
|
-
return JSON.parse(
|
|
7071
|
+
return JSON.parse(fs19.readFileSync(filePath, "utf-8"));
|
|
6306
7072
|
} catch {
|
|
6307
7073
|
return null;
|
|
6308
7074
|
}
|
|
@@ -6394,8 +7160,8 @@ var resolveBotBindRuntimeId = (explicitRuntimeId) => {
|
|
|
6394
7160
|
};
|
|
6395
7161
|
var appendBotBindRequest = (payload) => {
|
|
6396
7162
|
const requestPath = getBotBindRequestFilePath();
|
|
6397
|
-
|
|
6398
|
-
|
|
7163
|
+
fs19.mkdirSync(path17.dirname(requestPath), { recursive: true });
|
|
7164
|
+
fs19.appendFileSync(requestPath, `${JSON.stringify(payload)}
|
|
6399
7165
|
`, "utf-8");
|
|
6400
7166
|
return requestPath;
|
|
6401
7167
|
};
|
|
@@ -6698,12 +7464,12 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
|
|
|
6698
7464
|
const newConfigPath = getCcemConfigPath();
|
|
6699
7465
|
const legacyConfigPath = getLegacyConfigPath();
|
|
6700
7466
|
console.log(chalk9.cyan("\n\u{1F504} \u914D\u7F6E\u8FC1\u79FB\n"));
|
|
6701
|
-
if (!
|
|
7467
|
+
if (!fs19.existsSync(legacyConfigPath)) {
|
|
6702
7468
|
console.log(chalk9.yellow("\u672A\u627E\u5230\u65E7\u7248\u914D\u7F6E\u6587\u4EF6"));
|
|
6703
7469
|
console.log(chalk9.gray(` \u65E7\u8DEF\u5F84: ${legacyConfigPath}`));
|
|
6704
7470
|
return;
|
|
6705
7471
|
}
|
|
6706
|
-
if (
|
|
7472
|
+
if (fs19.existsSync(newConfigPath) && !options.force) {
|
|
6707
7473
|
console.log(chalk9.green("\u2713 \u914D\u7F6E\u5DF2\u5728\u65B0\u8DEF\u5F84"));
|
|
6708
7474
|
console.log(chalk9.gray(` \u8DEF\u5F84: ${newConfigPath}`));
|
|
6709
7475
|
console.log(chalk9.gray("\n\u4F7F\u7528 --force \u5F3A\u5236\u91CD\u65B0\u8FC1\u79FB"));
|
|
@@ -6711,7 +7477,7 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
|
|
|
6711
7477
|
}
|
|
6712
7478
|
try {
|
|
6713
7479
|
ensureCcemDir();
|
|
6714
|
-
const legacyRaw = JSON.parse(
|
|
7480
|
+
const legacyRaw = JSON.parse(fs19.readFileSync(legacyConfigPath, "utf-8"));
|
|
6715
7481
|
const migrated = normalizeCcemConfig(legacyRaw);
|
|
6716
7482
|
if (!migrated.registries[OFFICIAL_ENV_NAME]) {
|
|
6717
7483
|
migrated.registries[OFFICIAL_ENV_NAME] = { ...DEFAULT_OFFICIAL_ENV };
|
|
@@ -6722,10 +7488,10 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
|
|
|
6722
7488
|
console.log(chalk9.gray(` \u4ECE: ${legacyConfigPath}`));
|
|
6723
7489
|
console.log(chalk9.gray(` \u5230: ${newConfigPath}`));
|
|
6724
7490
|
if (options.clean) {
|
|
6725
|
-
|
|
6726
|
-
const legacyDir =
|
|
7491
|
+
fs19.unlinkSync(legacyConfigPath);
|
|
7492
|
+
const legacyDir = path17.dirname(legacyConfigPath);
|
|
6727
7493
|
try {
|
|
6728
|
-
|
|
7494
|
+
fs19.rmdirSync(legacyDir);
|
|
6729
7495
|
} catch {
|
|
6730
7496
|
}
|
|
6731
7497
|
console.log(chalk9.green("\u2713 \u5DF2\u5220\u9664\u65E7\u914D\u7F6E\u6587\u4EF6"));
|
|
@@ -6736,13 +7502,13 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
|
|
|
6736
7502
|
});
|
|
6737
7503
|
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() {
|
|
6738
7504
|
const options = this.opts();
|
|
6739
|
-
const skillDir =
|
|
6740
|
-
const targetPath =
|
|
6741
|
-
if (!
|
|
6742
|
-
|
|
7505
|
+
const skillDir = path17.join(ensureCcemAgentHome("claude"), "skills");
|
|
7506
|
+
const targetPath = path17.join(skillDir, "ccem-cron.md");
|
|
7507
|
+
if (!fs19.existsSync(skillDir)) {
|
|
7508
|
+
fs19.mkdirSync(skillDir, { recursive: true });
|
|
6743
7509
|
console.log(chalk9.gray(`\u521B\u5EFA\u76EE\u5F55: ${skillDir}`));
|
|
6744
7510
|
}
|
|
6745
|
-
if (
|
|
7511
|
+
if (fs19.existsSync(targetPath) && !options.force) {
|
|
6746
7512
|
const { overwrite } = await inquirer.prompt([
|
|
6747
7513
|
{
|
|
6748
7514
|
type: "confirm",
|
|
@@ -6756,7 +7522,7 @@ setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 CCEM \
|
|
|
6756
7522
|
return;
|
|
6757
7523
|
}
|
|
6758
7524
|
}
|
|
6759
|
-
|
|
7525
|
+
fs19.writeFileSync(targetPath, CCEM_CRON_SKILL_CONTENT, "utf-8");
|
|
6760
7526
|
console.log(chalk9.green(`\u2713 \u5DF2\u5B89\u88C5 ccem-cron skill`));
|
|
6761
7527
|
console.log(chalk9.gray(` \u8DEF\u5F84: ${targetPath}`));
|
|
6762
7528
|
console.log(chalk9.cyan(`
|
|
@@ -6764,13 +7530,13 @@ setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 CCEM \
|
|
|
6764
7530
|
});
|
|
6765
7531
|
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() {
|
|
6766
7532
|
const options = this.opts();
|
|
6767
|
-
const skillDir =
|
|
6768
|
-
const targetPath =
|
|
6769
|
-
if (!
|
|
6770
|
-
|
|
7533
|
+
const skillDir = path17.join(ensureCcemAgentHome("claude"), "skills");
|
|
7534
|
+
const targetPath = path17.join(skillDir, "ccem-bot-bind.md");
|
|
7535
|
+
if (!fs19.existsSync(skillDir)) {
|
|
7536
|
+
fs19.mkdirSync(skillDir, { recursive: true });
|
|
6771
7537
|
console.log(chalk9.gray(`\u521B\u5EFA\u76EE\u5F55: ${skillDir}`));
|
|
6772
7538
|
}
|
|
6773
|
-
if (
|
|
7539
|
+
if (fs19.existsSync(targetPath) && !options.force) {
|
|
6774
7540
|
const { overwrite } = await inquirer.prompt([
|
|
6775
7541
|
{
|
|
6776
7542
|
type: "confirm",
|
|
@@ -6784,7 +7550,7 @@ setupCmd.command("bot-bind").description("\u5B89\u88C5 ccem-bot-bind skill \u523
|
|
|
6784
7550
|
return;
|
|
6785
7551
|
}
|
|
6786
7552
|
}
|
|
6787
|
-
|
|
7553
|
+
fs19.writeFileSync(targetPath, CCEM_BOT_BIND_SKILL_CONTENT, "utf-8");
|
|
6788
7554
|
console.log(chalk9.green(`\u2713 \u5DF2\u5B89\u88C5 ccem-bot-bind skill`));
|
|
6789
7555
|
console.log(chalk9.gray(` \u8DEF\u5F84: ${targetPath}`));
|
|
6790
7556
|
console.log(chalk9.cyan(`
|
|
@@ -6961,7 +7727,7 @@ desktopCmd.command("send <runtimeId>").description("Send input to a CCEM Desktop
|
|
|
6961
7727
|
const opts = this.opts();
|
|
6962
7728
|
const result = await requestDesktopControl("ccem.workspace.sendInput", {
|
|
6963
7729
|
runtimeId,
|
|
6964
|
-
clientMessageId: opts.messageId?.trim() || `ccem-cli-${
|
|
7730
|
+
clientMessageId: opts.messageId?.trim() || `ccem-cli-${randomUUID4()}`,
|
|
6965
7731
|
text: opts.text,
|
|
6966
7732
|
displayText: opts.displayText ?? null
|
|
6967
7733
|
});
|