ccem 2.89.0 → 2.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1963 -1889
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,16 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/index.ts
4
- import { Command } from "commander";
5
- import Conf2 from "conf";
6
- import inquirer from "inquirer";
7
- import chalk8 from "chalk";
8
- import Table3 from "cli-table3";
9
- import { spawn as spawn3 } from "child_process";
10
- import * as fs14 from "fs";
11
- import * as path12 from "path";
12
- import { fileURLToPath as fileURLToPath2 } from "url";
13
- import { randomUUID } from "crypto";
3
+ // src/remoteBridge.ts
4
+ import { spawn } from "child_process";
5
+ import { TextDecoder } from "util";
6
+
7
+ // src/desktopControl.ts
8
+ import fs2 from "fs";
9
+ import path2 from "path";
14
10
 
15
11
  // ../../packages/core/dist/chunk-4WH3CEOL.js
16
12
  var DEFAULT_ROUTER_PORT = 17820;
@@ -815,2063 +811,2096 @@ var getLegacyConfigPath = () => {
815
811
  return path.join(home, ".config", "claude-code-env-manager-nodejs", "config.json");
816
812
  };
817
813
 
818
- // src/ui.ts
819
- import chalk from "chalk";
820
- import Table from "cli-table3";
821
-
822
- // src/usage.ts
823
- import * as fs2 from "fs";
824
- import * as fsPromises from "fs/promises";
825
- import * as path2 from "path";
826
- import * as os2 from "os";
827
- import * as readline from "readline";
828
- import { fileURLToPath } from "url";
829
- var __filename = fileURLToPath(import.meta.url);
830
- var __dirname = path2.dirname(__filename);
831
- var CLAUDE_PROJECTS_DIR = path2.join(os2.homedir(), ".claude", "projects");
832
- var CCEM_DIR = path2.join(os2.homedir(), ".ccem");
833
- var CACHE_VERSION = 2;
834
- var getCachePath = () => path2.join(CCEM_DIR, "usage-cache.json");
835
- var getPricesPath = () => path2.join(CCEM_DIR, "model-prices.json");
836
- async function ensureCcemDir2() {
837
- try {
838
- await fsPromises.access(CCEM_DIR);
839
- } catch {
840
- await fsPromises.mkdir(CCEM_DIR, { recursive: true });
814
+ // src/desktopControl.ts
815
+ function validateDesktopTaskModel(provider, model) {
816
+ if (model === void 0 || model === null) return void 0;
817
+ if (provider !== "codex") {
818
+ throw new Error("MODEL_PROVIDER_UNSUPPORTED: task model selection is only available for Codex sessions.");
819
+ }
820
+ if (typeof model !== "string" || model !== model.trim() || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/.test(model)) {
821
+ throw new Error("MODEL_INVALID: expected a model identifier (1-256 ASCII letters, digits, dots, underscores, colons, slashes or hyphens; starting with a letter or digit).");
841
822
  }
823
+ return model;
842
824
  }
843
- var LITELLM_PRICES_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
844
- var getBundledPricesPath = () => {
845
- return path2.join(__dirname, "..", "model-prices.json");
825
+ function requireTaskModelCapability(health) {
826
+ const capability = health?.capabilities?.taskModelSelection;
827
+ if (capability?.version !== 1 || !Array.isArray(capability.providers) || !capability.providers.includes("codex")) {
828
+ throw new Error("MODEL_SELECTION_UNSUPPORTED: this Desktop does not advertise Codex task model selection v1. No session was created.");
829
+ }
830
+ }
831
+ var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
832
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
833
+ var ENDPOINT_UNREACHABLE_CODES = /* @__PURE__ */ new Set([
834
+ "ECONNREFUSED",
835
+ "ECONNRESET",
836
+ "ENOTCONN",
837
+ "EHOSTUNREACH",
838
+ "ECONNABORTED"
839
+ ]);
840
+ var ROUTER_BINDING_KEY = /^(?:background|subagent:\*|subagent:[A-Za-z0-9._:-]{1,128})$/;
841
+ var StaleDesktopControlDescriptorError = class extends Error {
842
+ name = "StaleDesktopControlDescriptorError";
843
+ reason;
844
+ descriptorPath;
845
+ pid;
846
+ cleanedUp;
847
+ cause;
848
+ constructor(details) {
849
+ const subject = details.pid !== null ? `process ${details.pid}` : "the publishing process";
850
+ const symptom = details.reason === "dead-pid" ? `${subject} is no longer running` : details.reason === "endpoint-unreachable" ? "the control endpoint refused the connection" : `the control request timed out after ${details.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS}ms`;
851
+ const remedy = details.cleanedUp ? "The stale descriptor was removed automatically; start CCEM Desktop and rerun the command." : details.pid !== null ? "Restart CCEM Desktop so it republishes a fresh control endpoint." : "Restart CCEM Desktop to refresh the descriptor, or remove the stale file manually if it is no longer managed.";
852
+ super(
853
+ `CCEM Desktop control descriptor at ${details.descriptorPath} is stale: ${symptom}. ${remedy}`
854
+ );
855
+ this.reason = details.reason;
856
+ this.descriptorPath = details.descriptorPath;
857
+ this.pid = details.pid;
858
+ this.cleanedUp = details.cleanedUp;
859
+ if (details.cause !== void 0) {
860
+ this.cause = details.cause;
861
+ }
862
+ }
846
863
  };
847
- var DEFAULT_PRICES = {
848
- "claude-opus-4-5": {
849
- input_cost_per_token: 5e-6,
850
- output_cost_per_token: 25e-6,
851
- cache_read_input_token_cost: 5e-7,
852
- cache_creation_input_token_cost: 625e-8
853
- },
854
- "claude-sonnet-4-5": {
855
- input_cost_per_token: 3e-6,
856
- output_cost_per_token: 15e-6,
857
- cache_read_input_token_cost: 3e-7,
858
- cache_creation_input_token_cost: 375e-8
859
- },
860
- "claude-haiku-4-5": {
861
- input_cost_per_token: 1e-6,
862
- output_cost_per_token: 5e-6,
863
- cache_read_input_token_cost: 1e-7,
864
- cache_creation_input_token_cost: 125e-8
864
+ var DesktopControlRpcError = class extends Error {
865
+ code;
866
+ data;
867
+ constructor(message, code, data) {
868
+ super(message);
869
+ this.name = "DesktopControlRpcError";
870
+ this.code = code;
871
+ this.data = data;
865
872
  }
866
873
  };
867
- function normalizeModelName(model) {
868
- const normalized = model.replace(/-20\d{6}.*$/, "").replace(/-v\d+:\d+$/, "").replace(/^anthropic\./, "").replace(/^vertex_ai\//, "").replace(/@.*$/, "");
869
- return normalized;
874
+ function getDesktopControlDescriptorPath() {
875
+ return process.env.CCEM_CONTROL_FILE?.trim() || getDefaultControlDescriptorPath();
870
876
  }
871
- var pricesCache = null;
872
- async function loadPrices() {
873
- if (pricesCache) return pricesCache;
874
- await ensureCcemDir2();
875
- const pricesPath = getPricesPath();
877
+ function getDefaultControlDescriptorPath() {
878
+ return path2.join(getCcemConfigDir(), "control.json");
879
+ }
880
+ function isDefaultDescriptorPath(descriptorPath) {
876
881
  try {
877
- const response = await fetch(LITELLM_PRICES_URL, { signal: AbortSignal.timeout(1e3) });
878
- if (response.ok) {
879
- const data = await response.json();
880
- const prices = {};
881
- for (const [key, value] of Object.entries(data)) {
882
- if (value.input_cost_per_token && value.output_cost_per_token) {
883
- prices[key] = {
884
- input_cost_per_token: value.input_cost_per_token,
885
- output_cost_per_token: value.output_cost_per_token,
886
- cache_read_input_token_cost: value.cache_read_input_token_cost,
887
- cache_creation_input_token_cost: value.cache_creation_input_token_cost
888
- };
889
- }
890
- }
891
- await fsPromises.writeFile(pricesPath, JSON.stringify(prices, null, 2));
892
- pricesCache = prices;
893
- return prices;
894
- }
882
+ return path2.resolve(descriptorPath) === path2.resolve(getDefaultControlDescriptorPath());
895
883
  } catch {
884
+ return false;
896
885
  }
897
- try {
898
- const content = await fsPromises.readFile(pricesPath, "utf-8");
899
- const data = JSON.parse(content);
900
- pricesCache = data;
901
- return data;
902
- } catch {
886
+ }
887
+ function safeRemoveStaleDescriptor(descriptorPath) {
888
+ if (!isDefaultDescriptorPath(descriptorPath)) {
889
+ return false;
903
890
  }
904
891
  try {
905
- const bundledPath = getBundledPricesPath();
906
- const content = await fsPromises.readFile(bundledPath, "utf-8");
907
- const data = JSON.parse(content);
908
- pricesCache = data;
909
- return data;
892
+ fs2.rmSync(descriptorPath);
893
+ return true;
910
894
  } catch {
895
+ return false;
911
896
  }
912
- pricesCache = DEFAULT_PRICES;
913
- return DEFAULT_PRICES;
914
897
  }
915
- function getModelPrice(model, prices) {
916
- if (prices[model]) return prices[model];
917
- const normalized = normalizeModelName(model);
918
- if (prices[normalized]) return prices[normalized];
919
- for (const [key, value] of Object.entries(prices)) {
920
- if (key.includes(normalized) || normalized.includes(normalizeModelName(key))) {
921
- return value;
922
- }
923
- }
924
- if (model.includes("opus")) return DEFAULT_PRICES["claude-opus-4-5"];
925
- if (model.includes("sonnet")) return DEFAULT_PRICES["claude-sonnet-4-5"];
926
- if (model.includes("haiku")) return DEFAULT_PRICES["claude-haiku-4-5"];
927
- return DEFAULT_PRICES["claude-sonnet-4-5"];
898
+ function readErrnoCode(error) {
899
+ if (!error || typeof error !== "object") return void 0;
900
+ const candidate = error;
901
+ return candidate.code ?? candidate.cause?.code;
928
902
  }
929
- function calculateCost(usage, price) {
930
- return usage.inputTokens * price.input_cost_per_token + usage.outputTokens * price.output_cost_per_token + usage.cacheReadTokens * (price.cache_read_input_token_cost || 0) + usage.cacheCreationTokens * (price.cache_creation_input_token_cost || 0);
903
+ function readPid(value) {
904
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
931
905
  }
932
- function emptyUsage() {
933
- return {
934
- inputTokens: 0,
935
- outputTokens: 0,
936
- cacheReadTokens: 0,
937
- cacheCreationTokens: 0,
938
- cost: 0
939
- };
906
+ function isLoopbackHost(host) {
907
+ const normalized = host.trim().toLowerCase().replace(/^\[|\]$/g, "");
908
+ if (LOOPBACK_HOSTS.has(normalized)) {
909
+ return true;
910
+ }
911
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized)) {
912
+ return true;
913
+ }
914
+ if (normalized === "::1" || normalized === "0:0:0:0:0:0:0:1") {
915
+ return true;
916
+ }
917
+ return false;
940
918
  }
941
- function mergeUsage(a, b) {
942
- return {
943
- inputTokens: a.inputTokens + b.inputTokens,
944
- outputTokens: a.outputTokens + b.outputTokens,
945
- cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,
946
- cacheCreationTokens: a.cacheCreationTokens + b.cacheCreationTokens,
947
- cost: a.cost + b.cost
948
- };
919
+ function extractHost(endpoint) {
920
+ const withoutScheme = endpoint.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
921
+ const hostPort = withoutScheme.split(/[\/?#]/)[0] || "";
922
+ if (hostPort.startsWith("[")) {
923
+ const end = hostPort.indexOf("]");
924
+ if (end === -1) return null;
925
+ return hostPort.slice(1, end);
926
+ }
927
+ const colonIndex = hostPort.lastIndexOf(":");
928
+ if (colonIndex === -1) return hostPort;
929
+ return hostPort.slice(0, colonIndex);
949
930
  }
950
- async function getFileMetaAsync(filePath) {
931
+ function validateLoopbackEndpoint(endpoint) {
932
+ const host = extractHost(endpoint);
933
+ if (!host) {
934
+ throw new Error(
935
+ `CCEM Desktop control endpoint '${redactEndpoint(endpoint)}' is missing a host. Refusing to continue.`
936
+ );
937
+ }
938
+ if (!isLoopbackHost(host)) {
939
+ throw new Error(
940
+ `CCEM Desktop control endpoint '${redactEndpoint(endpoint)}' is not bound to loopback. Only 127.0.0.1, localhost, or ::1 are allowed.`
941
+ );
942
+ }
943
+ }
944
+ function isPidAlive(pid) {
945
+ if (!Number.isFinite(pid) || pid <= 0) return false;
951
946
  try {
952
- const stat2 = await fsPromises.stat(filePath);
953
- return {
954
- mtime: stat2.mtimeMs,
955
- size: stat2.size
956
- };
957
- } catch {
958
- return null;
947
+ process.kill(pid, 0);
948
+ return true;
949
+ } catch (error) {
950
+ const code = error.code;
951
+ if (code === "ESRCH") return false;
952
+ if (code === "EPERM") return true;
953
+ return false;
959
954
  }
960
955
  }
961
- function loadCacheSync() {
956
+ function redactEndpoint(endpoint) {
962
957
  try {
963
- const cachePath = getCachePath();
964
- if (!fs2.existsSync(cachePath)) return null;
965
- const data = JSON.parse(fs2.readFileSync(cachePath, "utf-8"));
966
- if (data.version !== CACHE_VERSION) return null;
967
- return data;
958
+ const url = new URL(endpoint);
959
+ return `${url.protocol}//${url.host}${url.pathname}`;
968
960
  } catch {
969
- return null;
961
+ return "<invalid endpoint>";
970
962
  }
971
963
  }
972
- async function loadCacheAsync() {
973
- try {
974
- const cachePath = getCachePath();
975
- const content = await fsPromises.readFile(cachePath, "utf-8");
976
- const data = JSON.parse(content);
977
- if (data.version !== CACHE_VERSION) return null;
978
- return data;
979
- } catch {
980
- return null;
981
- }
964
+ function isDescriptor(value) {
965
+ return Boolean(
966
+ value && typeof value === "object" && typeof value.endpoint === "string" && typeof value.token === "string"
967
+ );
982
968
  }
983
- function getUsageStatsFromCache() {
984
- const cache = loadCacheSync();
985
- if (!cache) return null;
986
- const now = /* @__PURE__ */ new Date();
987
- const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
988
- const weekStart = new Date(todayStart);
989
- weekStart.setDate(weekStart.getDate() - weekStart.getDay());
990
- const stats = {
991
- today: emptyUsage(),
992
- week: emptyUsage(),
993
- total: emptyUsage(),
994
- dailyHistory: {},
995
- byModel: {},
996
- lastUpdated: now.toISOString()
997
- };
998
- for (const fileData of Object.values(cache.files)) {
999
- for (const entry of fileData.stats.entries) {
1000
- const entryTime = new Date(entry.timestamp);
1001
- const dateKey = entry.timestamp.split("T")[0];
1002
- stats.total = mergeUsage(stats.total, entry.usage);
1003
- if (!stats.dailyHistory[dateKey]) {
1004
- stats.dailyHistory[dateKey] = emptyUsage();
1005
- }
1006
- stats.dailyHistory[dateKey] = mergeUsage(stats.dailyHistory[dateKey], entry.usage);
1007
- const normalizedModel = normalizeModelName(entry.model);
1008
- if (!stats.byModel[normalizedModel]) {
1009
- stats.byModel[normalizedModel] = emptyUsage();
1010
- }
1011
- stats.byModel[normalizedModel] = mergeUsage(stats.byModel[normalizedModel], entry.usage);
1012
- if (entryTime >= todayStart) {
1013
- stats.today = mergeUsage(stats.today, entry.usage);
1014
- }
1015
- if (entryTime >= weekStart) {
1016
- stats.week = mergeUsage(stats.week, entry.usage);
1017
- }
1018
- }
969
+ function resolveDesktopControlDescriptor(descriptorPath = getDesktopControlDescriptorPath()) {
970
+ if (!fs2.existsSync(descriptorPath)) {
971
+ throw new Error(`CCEM Desktop control endpoint not found at ${descriptorPath}. Start CCEM Desktop first.`);
1019
972
  }
1020
- return stats;
1021
- }
1022
- async function saveCacheAsync(cache) {
1023
- try {
1024
- await ensureCcemDir2();
1025
- await fsPromises.writeFile(getCachePath(), JSON.stringify(cache, null, 2));
1026
- } catch {
973
+ const parsed = JSON.parse(fs2.readFileSync(descriptorPath, "utf-8"));
974
+ const endpoint = parsed.endpoint?.trim();
975
+ const token = parsed.token?.trim();
976
+ if (!endpoint || !token) {
977
+ throw new Error(`Invalid CCEM Desktop control descriptor at ${descriptorPath}`);
978
+ }
979
+ validateLoopbackEndpoint(endpoint);
980
+ const pid = readPid(parsed.pid);
981
+ if (pid !== null && !isPidAlive(pid)) {
982
+ const cleanedUp = safeRemoveStaleDescriptor(descriptorPath);
983
+ throw new StaleDesktopControlDescriptorError({
984
+ reason: "dead-pid",
985
+ descriptorPath,
986
+ pid,
987
+ cleanedUp
988
+ });
1027
989
  }
990
+ return { endpoint, token, pid };
1028
991
  }
1029
- async function parseJSONLFileAsync(filePath, prices, signal) {
1030
- const entries = [];
1031
- const messageEntryIndexes = /* @__PURE__ */ new Map();
1032
- try {
1033
- const fileStream = fs2.createReadStream(filePath, { encoding: "utf-8" });
1034
- const rl = readline.createInterface({
1035
- input: fileStream,
1036
- crlfDelay: Infinity
992
+ async function requestDesktopControl(method, params, descriptorOrOptions, maybeOptions = {}) {
993
+ const descriptorPath = getDesktopControlDescriptorPath();
994
+ const hasInjectedDescriptor = isDescriptor(descriptorOrOptions);
995
+ const descriptor = hasInjectedDescriptor ? descriptorOrOptions : resolveDesktopControlDescriptor(descriptorPath);
996
+ const options = hasInjectedDescriptor ? maybeOptions : descriptorOrOptions ?? maybeOptions ?? {};
997
+ const timeoutMs = options.timeoutMs ?? options.fetchTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
998
+ const pid = readPid(descriptor.pid);
999
+ validateLoopbackEndpoint(descriptor.endpoint);
1000
+ if (pid !== null && !isPidAlive(pid)) {
1001
+ const cleanedUp = hasInjectedDescriptor ? false : safeRemoveStaleDescriptor(descriptorPath);
1002
+ throw new StaleDesktopControlDescriptorError({
1003
+ reason: "dead-pid",
1004
+ descriptorPath,
1005
+ pid,
1006
+ cleanedUp
1037
1007
  });
1038
- let lineCount = 0;
1039
- for await (const line of rl) {
1040
- lineCount++;
1041
- if (lineCount % 100 === 0) {
1042
- if (signal?.aborted) {
1043
- rl.close();
1044
- fileStream.destroy();
1045
- throw new Error("Aborted");
1046
- }
1047
- if (lineCount % 1e3 === 0) {
1048
- await new Promise((resolve5) => setTimeout(resolve5, 0));
1049
- }
1050
- }
1051
- if (!line.trim()) continue;
1052
- try {
1053
- const entry = JSON.parse(line);
1054
- if (entry.type !== "assistant" || !entry.message?.usage) continue;
1055
- const model = entry.message.model || "unknown";
1056
- const rawUsage = entry.message.usage;
1057
- const usage = {
1058
- inputTokens: rawUsage.input_tokens || 0,
1059
- outputTokens: rawUsage.output_tokens || 0,
1060
- cacheReadTokens: rawUsage.cache_read_input_tokens || 0,
1061
- cacheCreationTokens: rawUsage.cache_creation_input_tokens || 0
1062
- };
1063
- const price = getModelPrice(model, prices);
1064
- const cost = calculateCost(usage, price);
1065
- const statsEntry = {
1066
- timestamp: entry.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
1067
- model,
1068
- usage: { ...usage, cost }
1069
- };
1070
- const messageId = entry.message.id;
1071
- if (typeof messageId === "string" && messageId.length > 0) {
1072
- const index = messageEntryIndexes.get(messageId);
1073
- if (index !== void 0) {
1074
- entries[index] = statsEntry;
1075
- } else {
1076
- messageEntryIndexes.set(messageId, entries.length);
1077
- entries.push(statsEntry);
1078
- }
1079
- } else {
1080
- entries.push(statsEntry);
1081
- }
1082
- } catch {
1083
- }
1084
- }
1085
- } catch (err) {
1086
- if (err.message === "Aborted") {
1087
- throw err;
1008
+ }
1009
+ const id = `ccem-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1010
+ const controller = new AbortController();
1011
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1012
+ const externalSignal = options.signal;
1013
+ const onExternalAbort = () => controller.abort();
1014
+ if (externalSignal) {
1015
+ if (externalSignal.aborted) {
1016
+ clearTimeout(timer);
1017
+ controller.abort();
1018
+ } else {
1019
+ externalSignal.addEventListener("abort", onExternalAbort, { once: true });
1088
1020
  }
1089
1021
  }
1090
- return { entries };
1091
- }
1092
- async function getAllJSONLFilesAsync() {
1093
- const files = [];
1022
+ let response;
1094
1023
  try {
1095
- const projectsDirExists = await fsPromises.access(CLAUDE_PROJECTS_DIR).then(() => true).catch(() => false);
1096
- if (!projectsDirExists) return files;
1097
- const projects = await fsPromises.readdir(CLAUDE_PROJECTS_DIR);
1098
- for (const project of projects) {
1099
- const projectPath = path2.join(CLAUDE_PROJECTS_DIR, project);
1100
- try {
1101
- const stat2 = await fsPromises.stat(projectPath);
1102
- if (stat2.isDirectory()) {
1103
- const projectFiles = await fsPromises.readdir(projectPath);
1104
- for (const file of projectFiles) {
1105
- if (file.endsWith(".jsonl")) {
1106
- files.push(path2.join(projectPath, file));
1107
- }
1108
- }
1109
- }
1110
- } catch {
1111
- }
1024
+ response = await fetch(descriptor.endpoint, {
1025
+ method: "POST",
1026
+ headers: {
1027
+ authorization: `Bearer ${descriptor.token}`,
1028
+ "content-type": "application/json"
1029
+ },
1030
+ body: JSON.stringify({
1031
+ jsonrpc: "2.0",
1032
+ id,
1033
+ method,
1034
+ params: params ?? {}
1035
+ }),
1036
+ signal: controller.signal
1037
+ });
1038
+ } catch (error) {
1039
+ if (controller.signal.aborted) {
1040
+ throw new StaleDesktopControlDescriptorError({
1041
+ reason: "request-timeout",
1042
+ descriptorPath,
1043
+ pid,
1044
+ cleanedUp: false,
1045
+ timeoutMs,
1046
+ cause: error
1047
+ });
1048
+ }
1049
+ const code = readErrnoCode(error);
1050
+ if (code && ENDPOINT_UNREACHABLE_CODES.has(code)) {
1051
+ throw new StaleDesktopControlDescriptorError({
1052
+ reason: "endpoint-unreachable",
1053
+ descriptorPath,
1054
+ pid,
1055
+ cleanedUp: false,
1056
+ cause: error
1057
+ });
1058
+ }
1059
+ throw error;
1060
+ } finally {
1061
+ clearTimeout(timer);
1062
+ if (externalSignal) {
1063
+ externalSignal.removeEventListener("abort", onExternalAbort);
1112
1064
  }
1113
- } catch {
1114
1065
  }
1115
- return files;
1066
+ if (!response.ok) {
1067
+ throw new Error(`CCEM Desktop control request failed: HTTP ${response.status}`);
1068
+ }
1069
+ const payload = await response.json();
1070
+ if (payload.error) {
1071
+ throw new DesktopControlRpcError(
1072
+ payload.error.message || `CCEM Desktop control error ${payload.error.code ?? ""}`.trim(),
1073
+ payload.error.code,
1074
+ payload.error.data
1075
+ );
1076
+ }
1077
+ return payload.result;
1116
1078
  }
1117
- async function getUsageStats(signal) {
1118
- if (signal?.aborted) throw new Error("Aborted");
1119
- const prices = await loadPrices();
1120
- if (signal?.aborted) throw new Error("Aborted");
1121
- const files = await getAllJSONLFilesAsync();
1122
- if (signal?.aborted) throw new Error("Aborted");
1123
- const cache = await loadCacheAsync();
1124
- const newCache = {
1125
- version: CACHE_VERSION,
1126
- files: {},
1127
- lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
1128
- };
1129
- const allEntries = [];
1130
- const CONCURRENCY_LIMIT = 5;
1131
- const chunks = [];
1132
- for (let i = 0; i < files.length; i += CONCURRENCY_LIMIT) {
1133
- chunks.push(files.slice(i, i + CONCURRENCY_LIMIT));
1079
+ function parseSinceOption(raw) {
1080
+ if (raw === void 0 || raw === null || raw === "") return null;
1081
+ const value = Number(raw);
1082
+ if (!Number.isFinite(value) || value < 0 || !Number.isInteger(value)) {
1083
+ throw new Error(
1084
+ `Invalid --since value '${raw}'. Expected a non-negative integer sequence number (e.g. 0, 42).`
1085
+ );
1134
1086
  }
1135
- for (const chunk of chunks) {
1136
- if (signal?.aborted) {
1137
- throw new Error("Aborted");
1138
- }
1139
- const chunkPromises = chunk.map(async (file) => {
1140
- const meta = await getFileMetaAsync(file);
1141
- if (!meta) return null;
1142
- const cachedFile = cache?.files[file];
1143
- const cacheValid = cachedFile && cachedFile.meta.mtime === meta.mtime && cachedFile.meta.size === meta.size;
1144
- let fileStats;
1145
- if (cacheValid) {
1146
- fileStats = cachedFile.stats;
1147
- } else {
1148
- fileStats = await parseJSONLFileAsync(file, prices, signal);
1149
- await new Promise((resolve5) => setTimeout(resolve5, 0));
1150
- }
1151
- return {
1152
- file,
1153
- meta,
1154
- stats: fileStats
1155
- };
1156
- });
1157
- const chunkResults = await Promise.all(chunkPromises);
1158
- for (const result of chunkResults) {
1159
- if (!result) continue;
1160
- newCache.files[result.file] = {
1161
- meta: result.meta,
1162
- stats: result.stats
1163
- };
1164
- allEntries.push(...result.stats.entries);
1165
- }
1087
+ return value;
1088
+ }
1089
+ function parseLimitOption(raw) {
1090
+ if (raw === void 0 || raw === null || raw === "") return null;
1091
+ const value = Number(raw);
1092
+ if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {
1093
+ throw new Error(
1094
+ `Invalid --limit value '${raw}'. Expected a positive integer (e.g. 1, 100).`
1095
+ );
1166
1096
  }
1167
- if (!signal?.aborted) {
1168
- saveCacheAsync(newCache).catch(() => {
1169
- });
1097
+ return value;
1098
+ }
1099
+ function parseRouteBinding(raw, optionName) {
1100
+ const separator = raw.indexOf("=");
1101
+ const key = separator > 0 ? raw.slice(0, separator).trim() : "";
1102
+ const env = separator > 0 ? raw.slice(separator + 1).trim() : "";
1103
+ if (!key || !env) {
1104
+ throw new Error(`Invalid ${optionName} value '${raw}'. Expected key=env.`);
1170
1105
  }
1171
- const now = /* @__PURE__ */ new Date();
1172
- const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
1173
- const weekStart = new Date(todayStart);
1174
- weekStart.setDate(weekStart.getDate() - weekStart.getDay());
1175
- const stats = {
1176
- today: emptyUsage(),
1177
- week: emptyUsage(),
1178
- total: emptyUsage(),
1179
- dailyHistory: {},
1180
- byModel: {},
1181
- lastUpdated: now.toISOString()
1182
- };
1183
- for (const entry of allEntries) {
1184
- const entryTime = new Date(entry.timestamp);
1185
- const dateKey = entry.timestamp.split("T")[0];
1186
- stats.total = mergeUsage(stats.total, entry.usage);
1187
- if (!stats.dailyHistory[dateKey]) {
1188
- stats.dailyHistory[dateKey] = emptyUsage();
1189
- }
1190
- stats.dailyHistory[dateKey] = mergeUsage(stats.dailyHistory[dateKey], entry.usage);
1191
- const normalizedModel = normalizeModelName(entry.model);
1192
- if (!stats.byModel[normalizedModel]) {
1193
- stats.byModel[normalizedModel] = emptyUsage();
1194
- }
1195
- stats.byModel[normalizedModel] = mergeUsage(stats.byModel[normalizedModel], entry.usage);
1196
- if (entryTime >= todayStart) {
1197
- stats.today = mergeUsage(stats.today, entry.usage);
1198
- }
1199
- if (entryTime >= weekStart) {
1200
- stats.week = mergeUsage(stats.week, entry.usage);
1106
+ if (!ROUTER_BINDING_KEY.test(key)) {
1107
+ throw new Error(
1108
+ `Invalid route key '${key}' in ${optionName}. Expected background, subagent:*, or subagent:<safe-agent-name>.`
1109
+ );
1110
+ }
1111
+ return { key, env };
1112
+ }
1113
+ function parseRoutesJson(raw) {
1114
+ let parsed;
1115
+ try {
1116
+ parsed = JSON.parse(raw);
1117
+ } catch {
1118
+ throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
1119
+ }
1120
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1121
+ throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
1122
+ }
1123
+ const routes = {};
1124
+ for (const [key, value] of Object.entries(parsed)) {
1125
+ if (typeof value !== "string") {
1126
+ throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
1201
1127
  }
1128
+ const binding = parseRouteBinding(`${key}=${value}`, "--route");
1129
+ routes[binding.key] = binding.env;
1202
1130
  }
1203
- return stats;
1131
+ return routes;
1204
1132
  }
1205
- function formatTokens(n) {
1206
- if (n >= 1e6) {
1207
- return (n / 1e6).toFixed(1) + "M";
1133
+ function parseDesktopRoutes(routeValues = [], routesJson) {
1134
+ if (routesJson === void 0 && routeValues.length === 0) {
1135
+ return void 0;
1208
1136
  }
1209
- if (n >= 1e3) {
1210
- return (n / 1e3).toFixed(1) + "K";
1137
+ const routes = routesJson === void 0 ? {} : parseRoutesJson(routesJson);
1138
+ for (const raw of routeValues) {
1139
+ const binding = parseRouteBinding(raw, "--route");
1140
+ routes[binding.key] = binding.env;
1211
1141
  }
1212
- return n.toString();
1142
+ return routes;
1213
1143
  }
1214
- function formatCost(n) {
1215
- if (n >= 1) {
1216
- return "$" + n.toFixed(2);
1144
+ function isDesktopSessionRouterState(value) {
1145
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1146
+ const state = value;
1147
+ if (!Number.isSafeInteger(state.revision) || state.revision < 0) return false;
1148
+ if (!state.bindings || typeof state.bindings !== "object" || Array.isArray(state.bindings)) return false;
1149
+ if (!Object.entries(state.bindings).every(([key, env]) => key.trim() && typeof env === "string")) {
1150
+ return false;
1217
1151
  }
1218
- if (n >= 0.01) {
1219
- return "$" + n.toFixed(2);
1152
+ return Array.isArray(state.allowedEnvs) && state.allowedEnvs.every((env) => typeof env === "string");
1153
+ }
1154
+ function buildDesktopRouterUpdateParams(runtimeId, current, setValue) {
1155
+ if (!isDesktopSessionRouterState(current)) {
1156
+ throw new Error("Invalid router state returned by CCEM Desktop.");
1220
1157
  }
1221
- return "$" + n.toFixed(4);
1158
+ const binding = parseRouteBinding(setValue, "--set");
1159
+ const bindings = { ...current.bindings, [binding.key]: binding.env };
1160
+ const allowedEnvs = current.allowedEnvs.includes(binding.env) ? [...current.allowedEnvs] : [...current.allowedEnvs, binding.env];
1161
+ return {
1162
+ runtimeId,
1163
+ expectedRevision: current.revision,
1164
+ patch: { bindings, allowedEnvs }
1165
+ };
1222
1166
  }
1223
- function getTotalTokens(usage) {
1224
- return usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.cacheCreationTokens;
1167
+ async function getOrUpdateDesktopRoutes(runtimeId, setValue, requester = requestDesktopControl) {
1168
+ const current = await requester("ccem.workspace.getRouter", { runtimeId });
1169
+ if (setValue === void 0) {
1170
+ return current;
1171
+ }
1172
+ const update = buildDesktopRouterUpdateParams(runtimeId, current, setValue);
1173
+ return requester("ccem.workspace.updateRouter", update);
1174
+ }
1175
+ function isNullableString(value) {
1176
+ return value === null || typeof value === "string";
1177
+ }
1178
+ function isDesktopEnvironmentRenameResult(value) {
1179
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1180
+ const result = value;
1181
+ return result.ok === true && result.operation === "rename" && typeof result.oldName === "string" && typeof result.newName === "string" && Number.isSafeInteger(result.updatedSessions) && result.updatedSessions >= 0 && isNullableString(result.current);
1182
+ }
1183
+ function isDesktopEnvironmentDeleteResult(value) {
1184
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1185
+ const result = value;
1186
+ return result.ok === true && result.operation === "delete" && typeof result.name === "string" && isNullableString(result.current);
1187
+ }
1188
+ async function renameDesktopEnvironment(oldName, newName, requester = requestDesktopControl) {
1189
+ const result = await requester("ccem.environment.rename", { oldName, newName });
1190
+ if (!isDesktopEnvironmentRenameResult(result)) {
1191
+ throw new Error("Invalid environment mutation response from CCEM Desktop.");
1192
+ }
1193
+ return result;
1194
+ }
1195
+ async function deleteDesktopEnvironment(name, requester = requestDesktopControl) {
1196
+ const result = await requester("ccem.environment.delete", { name });
1197
+ if (!isDesktopEnvironmentDeleteResult(result)) {
1198
+ throw new Error("Invalid environment mutation response from CCEM Desktop.");
1199
+ }
1200
+ return result;
1201
+ }
1202
+ function printJson(value) {
1203
+ console.log(JSON.stringify(value, null, 2));
1225
1204
  }
1226
1205
 
1227
- // src/logo-generated.ts
1228
- var LOGO_MINIMAL = {
1229
- width: 8,
1230
- height: 5,
1231
- ansi: ` \x1B[38;5;1m \x1B[38;5;103m\u2582\x1B[38;5;109m\u2584\x1B[7m\x1B[38;5;60m\u2583\x1B[38;5;61m\u2598\x1B[0m\x1B[38;5;60;48;5;67m\u2583\x1B[38;5;23m\u2596\x1B[38;5;67;48;5;239m\u2586\x1B[0m\x1B[38;5;60m\u259E \x1B[7m\x1B[38;5;24m\u2586\x1B[38;5;25m\u2585\x1B[38;5;24m\u2583\u2582\x1B[0m\x1B[38;5;1m \x1B[0m
1232
- \x1B[38;5;1m \x1B[38;5;103m\u2584\x1B[7m\u2582\x1B[38;5;110m\u2585\x1B[0m\x1B[38;5;60m\u2597\x1B[38;5;67m\u259E\x1B[7m\x1B[38;5;240m\u2586\x1B[38;5;25m\u258D\x1B[0m\x1B[38;5;23m\u258E\x1B[38;5;67m\u258C\x1B[7m\u2596\x1B[0m\x1B[38;5;67m\u2596\x1B[7m\x1B[38;5;60m\u2584\x1B[0m\x1B[38;5;1m \x1B[0m
1233
- \x1B[38;5;1m \x1B[38;5;60m\u2597\x1B[7m\u2584\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;25m\u258F\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;67m\u2583\x1B[0m\x1B[38;5;1m \x1B[0m
1234
- \x1B[38;5;1m \x1B[7m\x1B[38;5;25m\u2585\x1B[0m\x1B[38;5;1m \x1B[0m
1235
- \x1B[?25h`
1236
- };
1237
- var LOGO_COMPACT = {
1238
- width: 12,
1239
- height: 6,
1240
- ansi: ` \x1B[38;5;1m \x1B[38;5;239m\u2581\x1B[38;5;60m\u2583 \x1B[38;5;103m\u2581\x1B[38;5;110m\u2584 \x1B[38;5;61m\u2586\x1B[38;5;67m\u2586\u2586\x1B[38;5;68m\u2586\x1B[38;5;67m\u2582\x1B[38;5;66m\u2584 \x1B[38;5;23m\u259D\x1B[7m\x1B[38;5;24m\u2583\x1B[0m\x1B[38;5;24m\u2586\x1B[38;5;25m\u2585\u2584 \x1B[0m
1241
- \x1B[38;5;1m \x1B[38;5;66m\u2581\x1B[38;5;110m\u2584\u2586\x1B[7m\u2584\x1B[0m\x1B[38;5;239m\u2597\x1B[38;5;68m\u259E\x1B[7m\x1B[38;5;67m\u2585\x1B[38;5;25m\u258D\x1B[0m\x1B[38;5;25m\u258E\x1B[38;5;109m\u258C\x1B[38;5;239;48;5;68m\u2596\x1B[0m\x1B[38;5;67m\u2596\x1B[7m\u2585\x1B[0m\x1B[38;5;66m\u2585 \x1B[0m
1242
- \x1B[38;5;1m \x1B[7m\x1B[38;5;110m\u2583\x1B[38;5;67m\u2585\x1B[0m\x1B[38;5;1m \x1B[38;5;68m\u2597\x1B[7m\x1B[38;5;61m\u2597\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;25m\u258F\x1B[0m\x1B[38;5;23m\u258E\x1B[7m\x1B[38;5;103m\u258D\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;68m\u2596\x1B[0m\x1B[38;5;68m\u2596 \x1B[7m\x1B[38;5;67m\u2585\x1B[0m\x1B[38;5;60m\u2584 \x1B[0m
1243
- \x1B[38;5;1m \x1B[38;5;60m\u259D\x1B[38;5;67m\u2598 \x1B[7m\x1B[38;5;24m\u258A\x1B[0m\x1B[38;5;24;48;5;25m\u2595\x1B[0m\x1B[38;5;24m \x1B[7m\x1B[38;5;68m\u2584\x1B[0m\x1B[38;5;1m \x1B[0m
1244
- \x1B[38;5;1m \x1B[7m\x1B[38;5;24m\u2585\x1B[0m\x1B[38;5;1m \x1B[0m
1245
- \x1B[?25h`
1246
- };
1247
- var LOGO_FULL = {
1248
- width: 19,
1249
- height: 9,
1250
- ansi: ` \x1B[38;5;1m \x1B[38;5;109m\u2597\x1B[38;5;67m\u2581\x1B[38;5;23m\u2584\u2581 \x1B[7m\x1B[38;5;68m\u2596\u259D\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;110m\u258E\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;25m\u258B\x1B[0m\x1B[38;5;237;48;5;25m\u2595\x1B[0m\x1B[38;5;237m \x1B[7m\x1B[38;5;110m\u2598\u2583\x1B[0m\x1B[38;5;60m\u258C\x1B[38;5;24m\u2598 \x1B[0m
1251
- \x1B[38;5;1m \x1B[7m\x1B[38;5;110m\u2585\x1B[38;5;67m\u259E\x1B[0m\x1B[38;5;110m\u2583\x1B[7m\x1B[38;5;23m\u259E\x1B[0m\x1B[38;5;24m\u2583 \x1B[7m\x1B[38;5;68m\u2596\u259D\x1B[38;5;103m\u258B\x1B[0m\x1B[38;5;109m\u258D\x1B[7m\x1B[38;5;25m\u258C\x1B[0m\x1B[38;5;25m\u258B \x1B[38;5;103m\u2584\x1B[7m\x1B[38;5;110m\u2597\x1B[38;5;61m\u259E\x1B[38;5;24m\u2583\x1B[0m\x1B[38;5;1m \x1B[38;5;60m\u2582\x1B[38;5;67m\u2584\x1B[38;5;60m\u2585\x1B[7m\u2584\x1B[0m\x1B[38;5;1m \x1B[0m
1252
- \x1B[38;5;1m \x1B[38;5;24m\u2597\x1B[38;5;25m\u2585\u2584\u2583\x1B[38;5;61m\u2581\x1B[7m\x1B[38;5;60m\u2586\x1B[38;5;103m\u2584\x1B[0m\x1B[38;5;67m\u2585\x1B[7m\x1B[38;5;60m\u2597\x1B[0m\x1B[38;5;24m\u2585\x1B[48;5;68m\u2596\x1B[0m\x1B[7m\x1B[38;5;68m\u259D\x1B[0m\x1B[38;5;103m\u258A\x1B[7m\x1B[38;5;25m\u258E\x1B[0m\x1B[38;5;68;48;5;24m\u2584\x1B[0m\x1B[38;5;110m\u259E\x1B[7m\x1B[38;5;67m\u259E\x1B[0m\x1B[38;5;25m\u259E\x1B[38;5;67m\u2581\x1B[38;5;68m\u2583\x1B[38;5;60m\u2586\x1B[7m\x1B[38;5;67m\u2583\x1B[38;5;68m\u2585\x1B[0m\x1B[38;5;61m\u2594 \x1B[0m
1253
- \x1B[38;5;1m \x1B[38;5;238m\u2594\x1B[38;5;23m\u2594\x1B[38;5;24m\u2594 \x1B[38;5;95m\u2582\x1B[38;5;131m\u2583\x1B[38;5;66m\u2594 \x1B[38;5;131m\u2582\u2583\x1B[38;5;60m\u2594\x1B[38;5;95m\u2582\x1B[38;5;131m\u2583\x1B[38;5;94m\u2596\x1B[38;5;95m\u2597 \x1B[38;5;60m\u2594\x1B[38;5;95m\u2583 \x1B[0m
1254
- \x1B[38;5;1m \x1B[7m\x1B[38;5;95m\u258B\x1B[0m\x1B[38;5;131m\u258C \x1B[38;5;95m\u2581\x1B[7m\x1B[38;5;131m\u258C\x1B[0m\x1B[38;5;131m\u258D \x1B[38;5;95m\u2581\x1B[7m\x1B[38;5;131m\u258D\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;131m\u258D\x1B[38;5;95m\u2596\x1B[0m\x1B[38;5;131m\u2584\x1B[7m\u2596\x1B[0m\x1B[38;5;131m\u258E \x1B[0m
1255
- \x1B[38;5;1m \x1B[7m\x1B[38;5;95m\u2584\x1B[38;5;94m\u2583\x1B[38;5;95m\u2585\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;95m\u2584\x1B[38;5;94m\u2584\x1B[0m\x1B[38;5;95m\u2598\x1B[38;5;167m\u259D\x1B[7m\x1B[38;5;95m\u2584\u2585\x1B[0m\x1B[38;5;131m\u259D \x1B[38;5;95m\u2594\x1B[38;5;238m\u259D\x1B[38;5;131m\u2598 \x1B[0m
1256
- \x1B[38;5;1m \x1B[38;5;60m\u2583\x1B[38;5;240m\u2596 \x1B[38;5;109m\u2582\x1B[38;5;110m\u2584\x1B[7m\x1B[38;5;67m\u2583\x1B[38;5;60m\u259E\x1B[0m\x1B[38;5;240;48;5;68m\u2594\x1B[0m\x1B[7m\x1B[38;5;67m\u2596\x1B[38;5;61m\u2597\x1B[0m\x1B[38;5;67;48;5;110m\u2594\x1B[0m\x1B[38;5;68m\u2585\x1B[7m\x1B[38;5;60m\u2597\x1B[0m\x1B[38;5;66m\u2585\x1B[38;5;60m\u2581\x1B[7m\x1B[38;5;25m\u2586\u2584\u2583\u2582\u2594\x1B[0m\x1B[38;5;25m\u2585\x1B[38;5;24m\u2596 \x1B[0m
1257
- \x1B[38;5;1m \x1B[38;5;60m\u2594\x1B[38;5;67m\u2582\x1B[38;5;110m\u2584\x1B[7m\u2594\u2584\x1B[0m\x1B[38;5;1m \x1B[38;5;61m\u2584\x1B[7m\x1B[38;5;67m\u2597\x1B[38;5;60m\u2597\x1B[38;5;25m\u258E\x1B[0m\x1B[38;5;25m\u258D\x1B[7m\x1B[38;5;110m\u259E\x1B[38;5;67m\u2596\x1B[0m\x1B[38;5;60;48;5;68m\u259D\x1B[0m\x1B[38;5;60m\u2598\x1B[7m\x1B[38;5;109m\u2585\x1B[0m\x1B[38;5;67m\u2585 \x1B[38;5;24m\u2594 \x1B[0m
1258
- \x1B[38;5;1m \x1B[38;5;66m\u2597\x1B[38;5;153m\u2586\x1B[7m\x1B[38;5;110m\u2582\u2585\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;68m\u2598\x1B[38;5;61m\u2584\x1B[0m\x1B[38;5;1m \x1B[38;5;24;48;5;25m\u258F\x1B[0m\x1B[38;5;24m\u258E\x1B[7m\x1B[38;5;110m\u258B\x1B[0m\x1B[38;5;103m\u258D\x1B[7m\x1B[38;5;61m\u2596\x1B[0m\x1B[38;5;239;48;5;68m\u259D\x1B[0m\x1B[38;5;60m\u2596 \x1B[7m\x1B[38;5;109m\u2585\x1B[38;5;66m\u259D\x1B[0m\x1B[38;5;1m \x1B[0m
1259
- `
1260
- };
1206
+ // src/remoteBridge.ts
1207
+ function parseRemoteCursor(raw) {
1208
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) {
1209
+ throw new Error("Expected a non-negative safe integer event cursor.");
1210
+ }
1211
+ return Number(raw);
1212
+ }
1213
+ var REMOTE_WRITE_UNAVAILABLE = "CAPABILITY_UNAVAILABLE: Remote input requires a scoped bridge token, trusted chat confirmation and durable input deduplication. CLI source/confirmation arguments cannot authorize it.";
1214
+ var REMOTE_RELAY_UNAVAILABLE = "CAPABILITY_UNAVAILABLE: Remote relay requires a verified managed Hermes transport. Standalone CLI sends can replace a live gateway connection or change a thread target.";
1215
+ function registerRemoteBridge(program2) {
1216
+ const remote = program2.command("remote").description("Local administrative event inspection; managed Hermes integration is not enabled");
1217
+ remote.command("status <runtimeId>").action(async (runtimeId) => {
1218
+ printJson(await requestDesktopControl("ccem.workspace.getSession", { runtimeId }));
1219
+ });
1220
+ remote.command("events <runtimeId>").option("--since <seq>", "Last acknowledged event sequence", "0").action(async (runtimeId, opts) => {
1221
+ printJson(await requestDesktopControl("ccem.remote.getEvents", { runtimeId, sinceSeq: parseRemoteCursor(opts.since), limit: 100 }));
1222
+ });
1223
+ remote.command("relay <runtimeId>").requiredOption("--to <target>", "Explicit Hermes platform:chat_id[:thread_id]").requiredOption("--since <seq>", "Last acknowledged cursor; explicit 0 replays available history").description("Unavailable until managed transport capability checks pass").action(() => {
1224
+ throw new Error(REMOTE_RELAY_UNAVAILABLE);
1225
+ });
1226
+ remote.command("send <runtimeId>").requiredOption("--platform <platform>", "Authenticated Hermes source platform").requiredOption("--chat-id <id>", "Authenticated Hermes source chat").requiredOption("--message-id <id>", "Stable platform message ID for idempotency").requiredOption("--text <text>", "Confirmed input").requiredOption("--confirm <runtimeId>", "Repeat the runtime ID after obtaining user confirmation").description("Unavailable until trusted inbound bridge capability checks pass").action(() => {
1227
+ throw new Error(REMOTE_WRITE_UNAVAILABLE);
1228
+ });
1229
+ }
1230
+
1231
+ // src/index.ts
1232
+ import { Command } from "commander";
1233
+ import Conf2 from "conf";
1234
+ import inquirer from "inquirer";
1235
+ import chalk8 from "chalk";
1236
+ import Table3 from "cli-table3";
1237
+ import { spawn as spawn4 } from "child_process";
1238
+ import * as fs14 from "fs";
1239
+ import * as path12 from "path";
1240
+ import { fileURLToPath as fileURLToPath2 } from "url";
1241
+ import { randomUUID } from "crypto";
1261
1242
 
1262
1243
  // src/ui.ts
1263
- var theme = {
1264
- primary: chalk.hex("#89B4FA"),
1265
- // 亮蓝
1266
- accent: chalk.hex("#CBA6F7"),
1267
- // 亮紫
1268
- success: chalk.hex("#A6E3A1"),
1269
- // 亮绿
1270
- warning: chalk.hex("#F9E2AF"),
1271
- // 亮黄
1272
- danger: chalk.hex("#F38BA8"),
1273
- // 亮红
1274
- text: chalk.white,
1275
- muted: chalk.hex("#6C7086"),
1276
- // 中灰
1277
- dim: chalk.hex("#45475A")
1278
- // 暗灰
1279
- };
1280
- var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1281
- var spinnerIndex = 0;
1282
- var spinnerInterval = null;
1283
- var getSpinnerFrame = () => {
1284
- return theme.primary(SPINNER_FRAMES[spinnerIndex]);
1285
- };
1286
- var startSpinner = (onFrame) => {
1287
- if (spinnerInterval) return;
1288
- spinnerInterval = setInterval(() => {
1289
- spinnerIndex = (spinnerIndex + 1) % SPINNER_FRAMES.length;
1290
- onFrame();
1291
- }, 80);
1292
- };
1293
- var stopSpinner = () => {
1294
- if (spinnerInterval) {
1295
- clearInterval(spinnerInterval);
1296
- spinnerInterval = null;
1244
+ import chalk from "chalk";
1245
+ import Table from "cli-table3";
1246
+
1247
+ // src/usage.ts
1248
+ import * as fs3 from "fs";
1249
+ import * as fsPromises from "fs/promises";
1250
+ import * as path3 from "path";
1251
+ import * as os2 from "os";
1252
+ import * as readline from "readline";
1253
+ import { fileURLToPath } from "url";
1254
+ var __filename = fileURLToPath(import.meta.url);
1255
+ var __dirname = path3.dirname(__filename);
1256
+ var CLAUDE_PROJECTS_DIR = path3.join(os2.homedir(), ".claude", "projects");
1257
+ var CCEM_DIR = path3.join(os2.homedir(), ".ccem");
1258
+ var CACHE_VERSION = 2;
1259
+ var getCachePath = () => path3.join(CCEM_DIR, "usage-cache.json");
1260
+ var getPricesPath = () => path3.join(CCEM_DIR, "model-prices.json");
1261
+ async function ensureCcemDir2() {
1262
+ try {
1263
+ await fsPromises.access(CCEM_DIR);
1264
+ } catch {
1265
+ await fsPromises.mkdir(CCEM_DIR, { recursive: true });
1297
1266
  }
1267
+ }
1268
+ var LITELLM_PRICES_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
1269
+ var getBundledPricesPath = () => {
1270
+ return path3.join(__dirname, "..", "model-prices.json");
1298
1271
  };
1299
- var getTerminalWidth = () => {
1300
- return process.stdout.columns || 80;
1301
- };
1302
- var selectLogo = (termWidth) => {
1303
- if (termWidth < 45) return LOGO_MINIMAL;
1304
- if (termWidth < 60) return LOGO_COMPACT;
1305
- return LOGO_FULL;
1306
- };
1307
- var renderLogoWithEnvPanel = (envName, env, defaultMode) => {
1308
- const displayEnv = resolveEnvConfigForRuntime(envName, env);
1309
- const termWidth = getTerminalWidth();
1310
- const isNarrow = termWidth < 60;
1311
- const isVeryNarrow = termWidth < 45;
1312
- const logo = selectLogo(termWidth);
1313
- const logoLines = logo.ansi.split("\n").filter((l) => l.length > 0);
1314
- const title = theme.primary("CCEM") + " " + theme.muted("Claude Code Env Manager");
1315
- const titleShort = theme.primary("CCEM");
1316
- const envLabel = theme.muted("Env: ") + theme.primary(envName);
1317
- const baseUrl = displayEnv.ANTHROPIC_BASE_URL || "-";
1318
- const runtimeModel = displayEnv.ANTHROPIC_MODEL || "-";
1319
- const opusModel = displayEnv.ANTHROPIC_DEFAULT_OPUS_MODEL || (envName === "official" ? "Claude default" : "-");
1320
- const haikuModel = displayEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL || "-";
1321
- const authToken = displayEnv.ANTHROPIC_AUTH_TOKEN ? displayEnv.ANTHROPIC_AUTH_TOKEN.slice(0, 2) + "\u2022\u2022\u2022\u2022" + displayEnv.ANTHROPIC_AUTH_TOKEN.slice(-4) : "-";
1322
- const truncate = (s, max) => s.length > max ? s.slice(0, max - 3) + "..." : s;
1323
- const maskUrl = (url, max) => {
1324
- if (url.length <= max) return url;
1325
- try {
1326
- const parsed = new URL(url);
1327
- const protocol = parsed.protocol + "//";
1328
- const host = parsed.host;
1329
- const path13 = parsed.pathname + parsed.search;
1330
- const hostStart = host.slice(0, 8);
1331
- const hostEnd = host.slice(-4);
1332
- const pathPart = path13.length > 10 ? path13.slice(0, 7) + "..." : path13;
1333
- return `${protocol}${hostStart}...${hostEnd}${pathPart}`;
1334
- } catch {
1335
- return truncate(url, max);
1336
- }
1337
- };
1338
- const labelWidth = 7;
1339
- let envLines;
1340
- if (isNarrow) {
1341
- envLines = [
1342
- envLabel,
1343
- theme.muted("Opus:".padEnd(labelWidth)) + theme.dim(truncate(opusModel, 25)),
1344
- theme.muted("Token:".padEnd(labelWidth)) + theme.dim(authToken)
1345
- ];
1346
- } else {
1347
- envLines = [
1348
- envLabel + (defaultMode && PERMISSION_PRESETS[defaultMode] ? " " + theme.accent(`[${PERMISSION_PRESETS[defaultMode].name}]`) : ""),
1349
- theme.muted("URL:".padEnd(labelWidth)) + theme.dim(maskUrl(baseUrl, 40)),
1350
- theme.muted("Run:".padEnd(labelWidth)) + theme.dim(truncate(runtimeModel, 12)) + " " + theme.muted("Opus:".padEnd(labelWidth)) + theme.dim(truncate(opusModel, 15)),
1351
- theme.muted("Haiku:".padEnd(labelWidth)) + theme.dim(truncate(haikuModel, 15)) + " " + theme.muted("Token:".padEnd(labelWidth)) + theme.dim(authToken)
1352
- ];
1272
+ var DEFAULT_PRICES = {
1273
+ "claude-opus-4-5": {
1274
+ input_cost_per_token: 5e-6,
1275
+ output_cost_per_token: 25e-6,
1276
+ cache_read_input_token_cost: 5e-7,
1277
+ cache_creation_input_token_cost: 625e-8
1278
+ },
1279
+ "claude-sonnet-4-5": {
1280
+ input_cost_per_token: 3e-6,
1281
+ output_cost_per_token: 15e-6,
1282
+ cache_read_input_token_cost: 3e-7,
1283
+ cache_creation_input_token_cost: 375e-8
1284
+ },
1285
+ "claude-haiku-4-5": {
1286
+ input_cost_per_token: 1e-6,
1287
+ output_cost_per_token: 5e-6,
1288
+ cache_read_input_token_cost: 1e-7,
1289
+ cache_creation_input_token_cost: 125e-8
1353
1290
  }
1354
- const lines = [];
1355
- if (isVeryNarrow) {
1356
- logoLines.forEach((line) => lines.push(line));
1357
- lines.push("");
1358
- lines.push(titleShort);
1359
- lines.push("");
1360
- envLines.forEach((line) => lines.push(line));
1361
- } else {
1362
- const gap = isNarrow ? " " : " ";
1363
- lines.push("");
1364
- const maxLines = Math.max(logoLines.length, envLines.length + 3);
1365
- for (let i = 0; i < maxLines; i++) {
1366
- const logoLine = logoLines[i] || "";
1367
- if (i === 0) {
1368
- const visibleWidth2 = logoLine.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
1369
- const padding2 = " ".repeat(Math.max(0, logo.width - visibleWidth2));
1370
- lines.push(logoLine + padding2);
1371
- continue;
1372
- }
1373
- if (i === 1) {
1374
- const visibleWidth2 = logoLine.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
1375
- const padding2 = " ".repeat(Math.max(0, logo.width - visibleWidth2));
1376
- lines.push(logoLine + padding2 + gap + (isNarrow ? titleShort : title));
1377
- continue;
1378
- }
1379
- if (i === 2) {
1380
- const visibleWidth2 = logoLine.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
1381
- const padding2 = " ".repeat(Math.max(0, logo.width - visibleWidth2));
1382
- lines.push(logoLine + padding2);
1383
- continue;
1291
+ };
1292
+ function normalizeModelName(model) {
1293
+ const normalized = model.replace(/-20\d{6}.*$/, "").replace(/-v\d+:\d+$/, "").replace(/^anthropic\./, "").replace(/^vertex_ai\//, "").replace(/@.*$/, "");
1294
+ return normalized;
1295
+ }
1296
+ var pricesCache = null;
1297
+ async function loadPrices() {
1298
+ if (pricesCache) return pricesCache;
1299
+ await ensureCcemDir2();
1300
+ const pricesPath = getPricesPath();
1301
+ try {
1302
+ const response = await fetch(LITELLM_PRICES_URL, { signal: AbortSignal.timeout(1e3) });
1303
+ if (response.ok) {
1304
+ const data = await response.json();
1305
+ const prices = {};
1306
+ for (const [key, value] of Object.entries(data)) {
1307
+ if (value.input_cost_per_token && value.output_cost_per_token) {
1308
+ prices[key] = {
1309
+ input_cost_per_token: value.input_cost_per_token,
1310
+ output_cost_per_token: value.output_cost_per_token,
1311
+ cache_read_input_token_cost: value.cache_read_input_token_cost,
1312
+ cache_creation_input_token_cost: value.cache_creation_input_token_cost
1313
+ };
1314
+ }
1384
1315
  }
1385
- const envLine = envLines[i - 3] || "";
1386
- const visibleWidth = logoLine.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
1387
- const padding = " ".repeat(Math.max(0, logo.width - visibleWidth));
1388
- lines.push(logoLine + padding + gap + envLine);
1316
+ await fsPromises.writeFile(pricesPath, JSON.stringify(prices, null, 2));
1317
+ pricesCache = prices;
1318
+ return prices;
1389
1319
  }
1320
+ } catch {
1390
1321
  }
1391
- return lines.join("\n");
1392
- };
1393
- var renderUsageLine = (stats, loading) => {
1394
- if (loading) {
1395
- return theme.muted(" Usage: ") + getSpinnerFrame() + theme.dim(" Loading...");
1322
+ try {
1323
+ const content = await fsPromises.readFile(pricesPath, "utf-8");
1324
+ const data = JSON.parse(content);
1325
+ pricesCache = data;
1326
+ return data;
1327
+ } catch {
1396
1328
  }
1397
- if (!stats) {
1398
- return theme.muted(" Usage: ") + theme.dim("No data");
1329
+ try {
1330
+ const bundledPath = getBundledPricesPath();
1331
+ const content = await fsPromises.readFile(bundledPath, "utf-8");
1332
+ const data = JSON.parse(content);
1333
+ pricesCache = data;
1334
+ return data;
1335
+ } catch {
1399
1336
  }
1400
- const termWidth = getTerminalWidth();
1401
- const isNarrow = termWidth < 70;
1402
- const todayTokens = getTotalTokens(stats.today);
1403
- const weekTokens = getTotalTokens(stats.week);
1404
- const totalTokens = getTotalTokens(stats.total);
1405
- if (isNarrow) {
1406
- return theme.muted(" Usage: ") + theme.text("Today ") + theme.primary(formatTokens(todayTokens)) + theme.dim(" | ") + theme.text("Week ") + theme.primary(formatTokens(weekTokens)) + theme.dim(" | ") + theme.text("Total ") + theme.primary(formatTokens(totalTokens));
1337
+ pricesCache = DEFAULT_PRICES;
1338
+ return DEFAULT_PRICES;
1339
+ }
1340
+ function getModelPrice(model, prices) {
1341
+ if (prices[model]) return prices[model];
1342
+ const normalized = normalizeModelName(model);
1343
+ if (prices[normalized]) return prices[normalized];
1344
+ for (const [key, value] of Object.entries(prices)) {
1345
+ if (key.includes(normalized) || normalized.includes(normalizeModelName(key))) {
1346
+ return value;
1347
+ }
1407
1348
  }
1408
- return theme.muted(" Usage: ") + theme.text("Today ") + theme.primary(formatTokens(todayTokens).padStart(6)) + theme.dim(` (${formatCost(stats.today.cost)})`) + theme.dim(" | ") + theme.text("Week ") + theme.primary(formatTokens(weekTokens).padStart(6)) + theme.dim(` (${formatCost(stats.week.cost)})`) + theme.dim(" | ") + theme.text("Total ") + theme.primary(formatTokens(totalTokens).padStart(6)) + theme.dim(` (${formatCost(stats.total.cost)})`);
1409
- };
1410
- var renderCompactHeader = () => {
1411
- const width = process.stdout.columns || 80;
1412
- return theme.dim("\u2500".repeat(width));
1413
- };
1414
- var getMainMenuChoices = (defaultMode) => {
1415
- let startLabel = "Start Claude Code";
1416
- if (defaultMode && PERMISSION_PRESETS[defaultMode]) {
1417
- startLabel = `Start Claude Code ${theme.muted(`(${PERMISSION_PRESETS[defaultMode].name})`)}`;
1349
+ if (model.includes("opus")) return DEFAULT_PRICES["claude-opus-4-5"];
1350
+ if (model.includes("sonnet")) return DEFAULT_PRICES["claude-sonnet-4-5"];
1351
+ if (model.includes("haiku")) return DEFAULT_PRICES["claude-haiku-4-5"];
1352
+ return DEFAULT_PRICES["claude-sonnet-4-5"];
1353
+ }
1354
+ function calculateCost(usage, price) {
1355
+ return usage.inputTokens * price.input_cost_per_token + usage.outputTokens * price.output_cost_per_token + usage.cacheReadTokens * (price.cache_read_input_token_cost || 0) + usage.cacheCreationTokens * (price.cache_creation_input_token_cost || 0);
1356
+ }
1357
+ function emptyUsage() {
1358
+ return {
1359
+ inputTokens: 0,
1360
+ outputTokens: 0,
1361
+ cacheReadTokens: 0,
1362
+ cacheCreationTokens: 0,
1363
+ cost: 0
1364
+ };
1365
+ }
1366
+ function mergeUsage(a, b) {
1367
+ return {
1368
+ inputTokens: a.inputTokens + b.inputTokens,
1369
+ outputTokens: a.outputTokens + b.outputTokens,
1370
+ cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,
1371
+ cacheCreationTokens: a.cacheCreationTokens + b.cacheCreationTokens,
1372
+ cost: a.cost + b.cost
1373
+ };
1374
+ }
1375
+ async function getFileMetaAsync(filePath) {
1376
+ try {
1377
+ const stat2 = await fsPromises.stat(filePath);
1378
+ return {
1379
+ mtime: stat2.mtimeMs,
1380
+ size: stat2.size
1381
+ };
1382
+ } catch {
1383
+ return null;
1418
1384
  }
1419
- return [
1420
- { name: theme.success(startLabel), value: "start", short: "Start" },
1421
- { name: theme.primary("Switch Environment"), value: "switch", short: "Switch" },
1422
- { name: theme.primary("Permission Mode"), value: "perm", short: "Permission" },
1423
- { name: theme.accent("View Usage"), value: "usage", short: "Usage" },
1424
- { name: theme.text("Set Default Mode"), value: "setDefault", short: "Default" },
1425
- { name: theme.muted("Exit"), value: "exit", short: "Exit" }
1426
- ];
1427
- };
1428
- var modeColors = {
1429
- yolo: theme.danger,
1430
- dev: theme.success,
1431
- readonly: theme.primary,
1432
- safe: theme.warning,
1433
- ci: theme.accent,
1434
- audit: theme.primary
1435
- };
1436
- var getPermModeChoices = (currentMode, showCurrent = false) => {
1437
- const modes = ["yolo", "dev", "readonly", "safe", "ci", "audit"];
1438
- const choices = modes.map((mode) => {
1439
- const preset = PERMISSION_PRESETS[mode];
1440
- const colorFn = modeColors[mode];
1441
- const isCurrent = showCurrent && mode === currentMode;
1442
- const tag = isCurrent ? theme.success(" *") : "";
1443
- return {
1444
- name: colorFn(preset.name.padEnd(12)) + theme.muted(preset.description) + tag,
1445
- value: mode,
1446
- short: preset.name
1447
- };
1448
- });
1449
- if (showCurrent) {
1450
- choices.push({
1451
- name: theme.muted("Clear default"),
1452
- value: "clear",
1453
- short: "Clear"
1454
- });
1385
+ }
1386
+ function loadCacheSync() {
1387
+ try {
1388
+ const cachePath = getCachePath();
1389
+ if (!fs3.existsSync(cachePath)) return null;
1390
+ const data = JSON.parse(fs3.readFileSync(cachePath, "utf-8"));
1391
+ if (data.version !== CACHE_VERSION) return null;
1392
+ return data;
1393
+ } catch {
1394
+ return null;
1455
1395
  }
1456
- choices.push({
1457
- name: theme.muted("Back"),
1458
- value: "back",
1459
- short: "Back"
1460
- });
1461
- return choices;
1462
- };
1463
- var msg = {
1464
- success: (text) => console.log(theme.success("\u2713 ") + theme.text(text)),
1465
- error: (text) => console.log(theme.danger("\u2717 ") + theme.text(text)),
1466
- warning: (text) => console.log(theme.warning("! ") + theme.text(text)),
1467
- info: (text) => console.log(theme.primary("\u203A ") + theme.text(text))
1468
- };
1469
- var renderStarting = () => {
1470
- return theme.muted("Starting Claude Code...");
1471
- };
1472
- var renderCalendarHeatmap = (stats, months = 6) => {
1473
- const lines = [];
1474
- const now = /* @__PURE__ */ new Date();
1475
- const startDate = new Date(now);
1476
- startDate.setMonth(startDate.getMonth() - months);
1477
- const day = startDate.getDay();
1478
- const diff = startDate.getDate() - day + (day === 0 ? -6 : 1);
1479
- startDate.setDate(diff);
1480
- startDate.setHours(0, 0, 0, 0);
1481
- const dates = [];
1482
- const d = new Date(startDate);
1483
- while (d <= now || d.getDay() !== 1) {
1484
- dates.push(d.toISOString().split("T")[0]);
1485
- d.setDate(d.getDate() + 1);
1486
- if (d > now && d.getDay() === 1) break;
1396
+ }
1397
+ async function loadCacheAsync() {
1398
+ try {
1399
+ const cachePath = getCachePath();
1400
+ const content = await fsPromises.readFile(cachePath, "utf-8");
1401
+ const data = JSON.parse(content);
1402
+ if (data.version !== CACHE_VERSION) return null;
1403
+ return data;
1404
+ } catch {
1405
+ return null;
1487
1406
  }
1488
- let maxTokens = 0;
1489
- for (const date of dates) {
1490
- const usage = stats.dailyHistory[date];
1491
- if (usage) {
1492
- const tokens = getTotalTokens(usage);
1493
- if (tokens > maxTokens) maxTokens = tokens;
1407
+ }
1408
+ function getUsageStatsFromCache() {
1409
+ const cache = loadCacheSync();
1410
+ if (!cache) return null;
1411
+ const now = /* @__PURE__ */ new Date();
1412
+ const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
1413
+ const weekStart = new Date(todayStart);
1414
+ weekStart.setDate(weekStart.getDate() - weekStart.getDay());
1415
+ const stats = {
1416
+ today: emptyUsage(),
1417
+ week: emptyUsage(),
1418
+ total: emptyUsage(),
1419
+ dailyHistory: {},
1420
+ byModel: {},
1421
+ lastUpdated: now.toISOString()
1422
+ };
1423
+ for (const fileData of Object.values(cache.files)) {
1424
+ for (const entry of fileData.stats.entries) {
1425
+ const entryTime = new Date(entry.timestamp);
1426
+ const dateKey = entry.timestamp.split("T")[0];
1427
+ stats.total = mergeUsage(stats.total, entry.usage);
1428
+ if (!stats.dailyHistory[dateKey]) {
1429
+ stats.dailyHistory[dateKey] = emptyUsage();
1430
+ }
1431
+ stats.dailyHistory[dateKey] = mergeUsage(stats.dailyHistory[dateKey], entry.usage);
1432
+ const normalizedModel = normalizeModelName(entry.model);
1433
+ if (!stats.byModel[normalizedModel]) {
1434
+ stats.byModel[normalizedModel] = emptyUsage();
1435
+ }
1436
+ stats.byModel[normalizedModel] = mergeUsage(stats.byModel[normalizedModel], entry.usage);
1437
+ if (entryTime >= todayStart) {
1438
+ stats.today = mergeUsage(stats.today, entry.usage);
1439
+ }
1440
+ if (entryTime >= weekStart) {
1441
+ stats.week = mergeUsage(stats.week, entry.usage);
1442
+ }
1494
1443
  }
1495
1444
  }
1496
- let header = " ";
1497
- let currentMonth = -1;
1498
- const weeks = Math.ceil(dates.length / 7);
1499
- for (let w = 0; w < weeks; w++) {
1500
- const dateIndex = w * 7;
1501
- if (dateIndex < dates.length) {
1502
- const date = new Date(dates[dateIndex]);
1503
- const month = date.getMonth();
1504
- if (month !== currentMonth && w < weeks - 1) {
1505
- const monthName = date.toLocaleString("default", { month: "short" });
1506
- header += theme.muted(monthName);
1507
- currentMonth = month;
1445
+ return stats;
1446
+ }
1447
+ async function saveCacheAsync(cache) {
1448
+ try {
1449
+ await ensureCcemDir2();
1450
+ await fsPromises.writeFile(getCachePath(), JSON.stringify(cache, null, 2));
1451
+ } catch {
1452
+ }
1453
+ }
1454
+ async function parseJSONLFileAsync(filePath, prices, signal) {
1455
+ const entries = [];
1456
+ const messageEntryIndexes = /* @__PURE__ */ new Map();
1457
+ try {
1458
+ const fileStream = fs3.createReadStream(filePath, { encoding: "utf-8" });
1459
+ const rl = readline.createInterface({
1460
+ input: fileStream,
1461
+ crlfDelay: Infinity
1462
+ });
1463
+ let lineCount = 0;
1464
+ for await (const line of rl) {
1465
+ lineCount++;
1466
+ if (lineCount % 100 === 0) {
1467
+ if (signal?.aborted) {
1468
+ rl.close();
1469
+ fileStream.destroy();
1470
+ throw new Error("Aborted");
1471
+ }
1472
+ if (lineCount % 1e3 === 0) {
1473
+ await new Promise((resolve5) => setTimeout(resolve5, 0));
1474
+ }
1475
+ }
1476
+ if (!line.trim()) continue;
1477
+ try {
1478
+ const entry = JSON.parse(line);
1479
+ if (entry.type !== "assistant" || !entry.message?.usage) continue;
1480
+ const model = entry.message.model || "unknown";
1481
+ const rawUsage = entry.message.usage;
1482
+ const usage = {
1483
+ inputTokens: rawUsage.input_tokens || 0,
1484
+ outputTokens: rawUsage.output_tokens || 0,
1485
+ cacheReadTokens: rawUsage.cache_read_input_tokens || 0,
1486
+ cacheCreationTokens: rawUsage.cache_creation_input_tokens || 0
1487
+ };
1488
+ const price = getModelPrice(model, prices);
1489
+ const cost = calculateCost(usage, price);
1490
+ const statsEntry = {
1491
+ timestamp: entry.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
1492
+ model,
1493
+ usage: { ...usage, cost }
1494
+ };
1495
+ const messageId = entry.message.id;
1496
+ if (typeof messageId === "string" && messageId.length > 0) {
1497
+ const index = messageEntryIndexes.get(messageId);
1498
+ if (index !== void 0) {
1499
+ entries[index] = statsEntry;
1500
+ } else {
1501
+ messageEntryIndexes.set(messageId, entries.length);
1502
+ entries.push(statsEntry);
1503
+ }
1504
+ } else {
1505
+ entries.push(statsEntry);
1506
+ }
1507
+ } catch {
1508
1508
  }
1509
1509
  }
1510
- }
1511
- header = " ";
1512
- let lastMonth = -1;
1513
- for (let w = 0; w < weeks; w++) {
1514
- const dateIndex = w * 7;
1515
- if (dateIndex >= dates.length) break;
1516
- const date = new Date(dates[dateIndex]);
1517
- const month = date.getMonth();
1518
- if (month !== lastMonth) {
1519
- const monthName = date.toLocaleString("default", { month: "short" });
1520
- header += theme.muted(monthName.padEnd(4));
1521
- w++;
1522
- lastMonth = month;
1523
- } else {
1524
- header += " ";
1510
+ } catch (err) {
1511
+ if (err.message === "Aborted") {
1512
+ throw err;
1525
1513
  }
1526
1514
  }
1527
- lines.push(header);
1528
- const dayLabels = ["Mon", "", "Wed", "", "Fri", "", "Sun"];
1529
- const levels = [" ", "\u2591", "\u2592", "\u2593", "\u2588"];
1530
- for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
1531
- let row = theme.muted((dayLabels[dayOfWeek] || "").padEnd(4) + " ");
1532
- for (let w = 0; w < weeks; w++) {
1533
- const dateIndex = w * 7 + dayOfWeek;
1534
- if (dateIndex < dates.length) {
1535
- const dateKey = dates[dateIndex];
1536
- if (new Date(dateKey) > now) {
1537
- row += " ";
1538
- } else {
1539
- const usage = stats.dailyHistory[dateKey];
1540
- const tokens = usage ? getTotalTokens(usage) : 0;
1541
- let level = 0;
1542
- if (tokens > 0) {
1543
- if (maxTokens === 0) level = 0;
1544
- else {
1545
- level = Math.ceil(tokens / maxTokens * 4);
1515
+ return { entries };
1516
+ }
1517
+ async function getAllJSONLFilesAsync() {
1518
+ const files = [];
1519
+ try {
1520
+ const projectsDirExists = await fsPromises.access(CLAUDE_PROJECTS_DIR).then(() => true).catch(() => false);
1521
+ if (!projectsDirExists) return files;
1522
+ const projects = await fsPromises.readdir(CLAUDE_PROJECTS_DIR);
1523
+ for (const project of projects) {
1524
+ const projectPath = path3.join(CLAUDE_PROJECTS_DIR, project);
1525
+ try {
1526
+ const stat2 = await fsPromises.stat(projectPath);
1527
+ if (stat2.isDirectory()) {
1528
+ const projectFiles = await fsPromises.readdir(projectPath);
1529
+ for (const file of projectFiles) {
1530
+ if (file.endsWith(".jsonl")) {
1531
+ files.push(path3.join(projectPath, file));
1546
1532
  }
1547
1533
  }
1548
- row += (level === 0 ? theme.dim("\xB7") : theme.primary(levels[level])) + " ";
1549
1534
  }
1535
+ } catch {
1550
1536
  }
1551
1537
  }
1552
- lines.push(row);
1538
+ } catch {
1553
1539
  }
1554
- lines.push("");
1555
- lines.push(" " + theme.dim("Less ") + theme.dim("\xB7") + " " + theme.primary(levels[1]) + " " + theme.primary(levels[2]) + " " + theme.primary(levels[3]) + " " + theme.primary(levels[4]) + " " + theme.dim(" More"));
1556
- return lines.join("\n");
1557
- };
1558
- var renderUsageDetail = (stats) => {
1559
- const lines = [];
1560
- lines.push("");
1561
- lines.push(theme.primary(" Token Usage Statistics"));
1562
- lines.push(theme.dim("\u2500".repeat(60)));
1563
- lines.push("");
1564
- lines.push(renderCalendarHeatmap(stats));
1565
- lines.push("");
1566
- lines.push(theme.dim("\u2500".repeat(60)));
1567
- const periodTable = new Table({
1568
- head: [
1569
- theme.muted("Period"),
1570
- theme.muted("Input"),
1571
- theme.muted("Output"),
1572
- theme.muted("Cache Read"),
1573
- theme.muted("Cost")
1574
- ],
1575
- style: { head: [], border: [] },
1576
- chars: {
1577
- "top": "",
1578
- "top-mid": "",
1579
- "top-left": "",
1580
- "top-right": "",
1581
- "bottom": "",
1582
- "bottom-mid": "",
1583
- "bottom-left": "",
1584
- "bottom-right": "",
1585
- "left": " ",
1586
- "left-mid": "",
1587
- "mid": "",
1588
- "mid-mid": "",
1589
- "right": "",
1590
- "right-mid": "",
1591
- "middle": " "
1540
+ return files;
1541
+ }
1542
+ async function getUsageStats(signal) {
1543
+ if (signal?.aborted) throw new Error("Aborted");
1544
+ const prices = await loadPrices();
1545
+ if (signal?.aborted) throw new Error("Aborted");
1546
+ const files = await getAllJSONLFilesAsync();
1547
+ if (signal?.aborted) throw new Error("Aborted");
1548
+ const cache = await loadCacheAsync();
1549
+ const newCache = {
1550
+ version: CACHE_VERSION,
1551
+ files: {},
1552
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
1553
+ };
1554
+ const allEntries = [];
1555
+ const CONCURRENCY_LIMIT = 5;
1556
+ const chunks = [];
1557
+ for (let i = 0; i < files.length; i += CONCURRENCY_LIMIT) {
1558
+ chunks.push(files.slice(i, i + CONCURRENCY_LIMIT));
1559
+ }
1560
+ for (const chunk of chunks) {
1561
+ if (signal?.aborted) {
1562
+ throw new Error("Aborted");
1592
1563
  }
1593
- });
1594
- const formatRow = (label, usage) => [
1595
- theme.text(label),
1596
- theme.primary(formatTokens(usage.inputTokens)),
1597
- theme.primary(formatTokens(usage.outputTokens)),
1598
- theme.primary(formatTokens(usage.cacheReadTokens)),
1599
- theme.success(formatCost(usage.cost))
1600
- ];
1601
- periodTable.push(formatRow("Today", stats.today));
1602
- periodTable.push(formatRow("This Week", stats.week));
1603
- periodTable.push(formatRow("All Time", stats.total));
1604
- lines.push(periodTable.toString());
1605
- const modelEntries = Object.entries(stats.byModel).sort((a, b) => b[1].cost - a[1].cost);
1606
- if (modelEntries.length > 0) {
1607
- lines.push("");
1608
- lines.push(theme.dim("\u2500".repeat(60)));
1609
- lines.push(theme.muted(" By Model"));
1610
- lines.push("");
1611
- const modelTable = new Table({
1612
- head: [
1613
- theme.muted("Model"),
1614
- theme.muted("Tokens"),
1615
- theme.muted("Cost")
1616
- ],
1617
- style: { head: [], border: [] },
1618
- chars: {
1619
- "top": "",
1620
- "top-mid": "",
1621
- "top-left": "",
1622
- "top-right": "",
1623
- "bottom": "",
1624
- "bottom-mid": "",
1625
- "bottom-left": "",
1626
- "bottom-right": "",
1627
- "left": " ",
1628
- "left-mid": "",
1629
- "mid": "",
1630
- "mid-mid": "",
1631
- "right": "",
1632
- "right-mid": "",
1633
- "middle": " "
1564
+ const chunkPromises = chunk.map(async (file) => {
1565
+ const meta = await getFileMetaAsync(file);
1566
+ if (!meta) return null;
1567
+ const cachedFile = cache?.files[file];
1568
+ const cacheValid = cachedFile && cachedFile.meta.mtime === meta.mtime && cachedFile.meta.size === meta.size;
1569
+ let fileStats;
1570
+ if (cacheValid) {
1571
+ fileStats = cachedFile.stats;
1572
+ } else {
1573
+ fileStats = await parseJSONLFileAsync(file, prices, signal);
1574
+ await new Promise((resolve5) => setTimeout(resolve5, 0));
1634
1575
  }
1576
+ return {
1577
+ file,
1578
+ meta,
1579
+ stats: fileStats
1580
+ };
1635
1581
  });
1636
- for (const [model, usage] of modelEntries) {
1637
- const totalTokens = getTotalTokens(usage);
1638
- modelTable.push([
1639
- theme.text(model),
1640
- theme.primary(formatTokens(totalTokens)),
1641
- theme.success(formatCost(usage.cost))
1642
- ]);
1582
+ const chunkResults = await Promise.all(chunkPromises);
1583
+ for (const result of chunkResults) {
1584
+ if (!result) continue;
1585
+ newCache.files[result.file] = {
1586
+ meta: result.meta,
1587
+ stats: result.stats
1588
+ };
1589
+ allEntries.push(...result.stats.entries);
1643
1590
  }
1644
- lines.push(modelTable.toString());
1645
1591
  }
1646
- lines.push("");
1647
- lines.push(theme.dim("\u2500".repeat(60)));
1648
- lines.push(theme.muted(` Last updated: ${new Date(stats.lastUpdated).toLocaleString()}`));
1649
- return lines.join("\n");
1592
+ if (!signal?.aborted) {
1593
+ saveCacheAsync(newCache).catch(() => {
1594
+ });
1595
+ }
1596
+ const now = /* @__PURE__ */ new Date();
1597
+ const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
1598
+ const weekStart = new Date(todayStart);
1599
+ weekStart.setDate(weekStart.getDate() - weekStart.getDay());
1600
+ const stats = {
1601
+ today: emptyUsage(),
1602
+ week: emptyUsage(),
1603
+ total: emptyUsage(),
1604
+ dailyHistory: {},
1605
+ byModel: {},
1606
+ lastUpdated: now.toISOString()
1607
+ };
1608
+ for (const entry of allEntries) {
1609
+ const entryTime = new Date(entry.timestamp);
1610
+ const dateKey = entry.timestamp.split("T")[0];
1611
+ stats.total = mergeUsage(stats.total, entry.usage);
1612
+ if (!stats.dailyHistory[dateKey]) {
1613
+ stats.dailyHistory[dateKey] = emptyUsage();
1614
+ }
1615
+ stats.dailyHistory[dateKey] = mergeUsage(stats.dailyHistory[dateKey], entry.usage);
1616
+ const normalizedModel = normalizeModelName(entry.model);
1617
+ if (!stats.byModel[normalizedModel]) {
1618
+ stats.byModel[normalizedModel] = emptyUsage();
1619
+ }
1620
+ stats.byModel[normalizedModel] = mergeUsage(stats.byModel[normalizedModel], entry.usage);
1621
+ if (entryTime >= todayStart) {
1622
+ stats.today = mergeUsage(stats.today, entry.usage);
1623
+ }
1624
+ if (entryTime >= weekStart) {
1625
+ stats.week = mergeUsage(stats.week, entry.usage);
1626
+ }
1627
+ }
1628
+ return stats;
1629
+ }
1630
+ function formatTokens(n) {
1631
+ if (n >= 1e6) {
1632
+ return (n / 1e6).toFixed(1) + "M";
1633
+ }
1634
+ if (n >= 1e3) {
1635
+ return (n / 1e3).toFixed(1) + "K";
1636
+ }
1637
+ return n.toString();
1638
+ }
1639
+ function formatCost(n) {
1640
+ if (n >= 1) {
1641
+ return "$" + n.toFixed(2);
1642
+ }
1643
+ if (n >= 0.01) {
1644
+ return "$" + n.toFixed(2);
1645
+ }
1646
+ return "$" + n.toFixed(4);
1647
+ }
1648
+ function getTotalTokens(usage) {
1649
+ return usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.cacheCreationTokens;
1650
+ }
1651
+
1652
+ // src/logo-generated.ts
1653
+ var LOGO_MINIMAL = {
1654
+ width: 8,
1655
+ height: 5,
1656
+ ansi: ` \x1B[38;5;1m \x1B[38;5;103m\u2582\x1B[38;5;109m\u2584\x1B[7m\x1B[38;5;60m\u2583\x1B[38;5;61m\u2598\x1B[0m\x1B[38;5;60;48;5;67m\u2583\x1B[38;5;23m\u2596\x1B[38;5;67;48;5;239m\u2586\x1B[0m\x1B[38;5;60m\u259E \x1B[7m\x1B[38;5;24m\u2586\x1B[38;5;25m\u2585\x1B[38;5;24m\u2583\u2582\x1B[0m\x1B[38;5;1m \x1B[0m
1657
+ \x1B[38;5;1m \x1B[38;5;103m\u2584\x1B[7m\u2582\x1B[38;5;110m\u2585\x1B[0m\x1B[38;5;60m\u2597\x1B[38;5;67m\u259E\x1B[7m\x1B[38;5;240m\u2586\x1B[38;5;25m\u258D\x1B[0m\x1B[38;5;23m\u258E\x1B[38;5;67m\u258C\x1B[7m\u2596\x1B[0m\x1B[38;5;67m\u2596\x1B[7m\x1B[38;5;60m\u2584\x1B[0m\x1B[38;5;1m \x1B[0m
1658
+ \x1B[38;5;1m \x1B[38;5;60m\u2597\x1B[7m\u2584\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;25m\u258F\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;67m\u2583\x1B[0m\x1B[38;5;1m \x1B[0m
1659
+ \x1B[38;5;1m \x1B[7m\x1B[38;5;25m\u2585\x1B[0m\x1B[38;5;1m \x1B[0m
1660
+ \x1B[?25h`
1650
1661
  };
1651
- var renderFooterHints = (hints) => {
1652
- const termWidth = process.stdout.columns || 80;
1653
- const full = hints.map((h) => theme.primary(h.key) + theme.dim(h.label)).join(" ");
1654
- const medium = hints.map((h) => theme.primary(h.key) + theme.dim(h.short || h.label)).join(" ");
1655
- const minimal = hints.map((h) => theme.primary(h.key)).join(" ");
1656
- const stripAnsi = (s) => s.replace(/\x1B\[[0-9;]*m/g, "");
1657
- if (stripAnsi(full).length <= termWidth) return full;
1658
- if (stripAnsi(medium).length <= termWidth) return medium;
1659
- return minimal;
1662
+ var LOGO_COMPACT = {
1663
+ width: 12,
1664
+ height: 6,
1665
+ ansi: ` \x1B[38;5;1m \x1B[38;5;239m\u2581\x1B[38;5;60m\u2583 \x1B[38;5;103m\u2581\x1B[38;5;110m\u2584 \x1B[38;5;61m\u2586\x1B[38;5;67m\u2586\u2586\x1B[38;5;68m\u2586\x1B[38;5;67m\u2582\x1B[38;5;66m\u2584 \x1B[38;5;23m\u259D\x1B[7m\x1B[38;5;24m\u2583\x1B[0m\x1B[38;5;24m\u2586\x1B[38;5;25m\u2585\u2584 \x1B[0m
1666
+ \x1B[38;5;1m \x1B[38;5;66m\u2581\x1B[38;5;110m\u2584\u2586\x1B[7m\u2584\x1B[0m\x1B[38;5;239m\u2597\x1B[38;5;68m\u259E\x1B[7m\x1B[38;5;67m\u2585\x1B[38;5;25m\u258D\x1B[0m\x1B[38;5;25m\u258E\x1B[38;5;109m\u258C\x1B[38;5;239;48;5;68m\u2596\x1B[0m\x1B[38;5;67m\u2596\x1B[7m\u2585\x1B[0m\x1B[38;5;66m\u2585 \x1B[0m
1667
+ \x1B[38;5;1m \x1B[7m\x1B[38;5;110m\u2583\x1B[38;5;67m\u2585\x1B[0m\x1B[38;5;1m \x1B[38;5;68m\u2597\x1B[7m\x1B[38;5;61m\u2597\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;25m\u258F\x1B[0m\x1B[38;5;23m\u258E\x1B[7m\x1B[38;5;103m\u258D\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;68m\u2596\x1B[0m\x1B[38;5;68m\u2596 \x1B[7m\x1B[38;5;67m\u2585\x1B[0m\x1B[38;5;60m\u2584 \x1B[0m
1668
+ \x1B[38;5;1m \x1B[38;5;60m\u259D\x1B[38;5;67m\u2598 \x1B[7m\x1B[38;5;24m\u258A\x1B[0m\x1B[38;5;24;48;5;25m\u2595\x1B[0m\x1B[38;5;24m \x1B[7m\x1B[38;5;68m\u2584\x1B[0m\x1B[38;5;1m \x1B[0m
1669
+ \x1B[38;5;1m \x1B[7m\x1B[38;5;24m\u2585\x1B[0m\x1B[38;5;1m \x1B[0m
1670
+ \x1B[?25h`
1660
1671
  };
1661
- var selectEnvWithKeys = (registries, current) => {
1662
- return new Promise((resolve5) => {
1663
- const envNames = Object.keys(registries);
1664
- let selectedIndex = envNames.indexOf(current);
1665
- if (selectedIndex === -1) selectedIndex = 0;
1666
- const stdin = process.stdin;
1667
- const wasRaw = stdin.isRaw;
1668
- stdin.setRawMode(true);
1669
- stdin.resume();
1670
- const footerHints = [
1671
- { key: "[\u2191\u2193]", label: " navigate", short: " nav" },
1672
- { key: "[Enter]", label: " select", short: " sel" },
1673
- { key: "[e]", label: "dit", short: "" },
1674
- { key: "[r]", label: "ename", short: "en" },
1675
- { key: "[c]", label: "opy", short: "py" },
1676
- { key: "[d]", label: "elete", short: "el" }
1677
- ];
1678
- const totalLines = envNames.length + 1;
1679
- const renderItem = (index) => {
1680
- const name = envNames[index];
1681
- const isCurrent = name === current;
1682
- const isSelected = index === selectedIndex;
1683
- const prefix = isSelected ? theme.primary("\u276F ") : " ";
1684
- const tag = isCurrent ? theme.success(" *") : "";
1685
- const nameText = isSelected ? theme.primary(name) : isCurrent ? theme.primary(name) : theme.text(name);
1686
- return prefix + nameText + tag;
1687
- };
1688
- const updateLine = (lineIndex, content) => {
1689
- const moveUp = totalLines - lineIndex;
1690
- process.stdout.write(`\x1B[${moveUp}A`);
1691
- process.stdout.write("\x1B[2K");
1692
- process.stdout.write("\x1B[G");
1693
- process.stdout.write(content);
1694
- process.stdout.write(`\x1B[${moveUp}B`);
1695
- process.stdout.write("\x1B[G");
1696
- };
1697
- const initialRender = () => {
1698
- process.stdout.write("\x1B[?25l");
1699
- envNames.forEach((_, i) => {
1700
- console.log(renderItem(i));
1701
- });
1702
- console.log(renderFooterHints(footerHints));
1703
- };
1704
- const handleSelectionChange = (oldIndex, newIndex) => {
1705
- if (oldIndex === newIndex) return;
1706
- selectedIndex = newIndex;
1707
- updateLine(oldIndex, renderItem(oldIndex));
1708
- updateLine(newIndex, renderItem(newIndex));
1709
- };
1710
- initialRender();
1711
- const cleanup = () => {
1712
- stdin.setRawMode(wasRaw ?? false);
1713
- stdin.removeListener("data", onKeypress);
1714
- process.stdout.write("\x1B[?25h");
1715
- };
1716
- const onKeypress = (key) => {
1717
- const char = key.toString();
1718
- if (char === "") {
1719
- cleanup();
1720
- process.exit(0);
1721
- }
1722
- if (char === "\x1B" && key.length === 1) {
1723
- cleanup();
1724
- resolve5({ action: "cancel" });
1725
- return;
1726
- }
1727
- if (char === "\x1B[A" || char === "k") {
1728
- const oldIndex = selectedIndex;
1729
- const newIndex = Math.max(0, selectedIndex - 1);
1730
- handleSelectionChange(oldIndex, newIndex);
1731
- return;
1732
- }
1733
- if (char === "\x1B[B" || char === "j") {
1734
- const oldIndex = selectedIndex;
1735
- const newIndex = Math.min(envNames.length - 1, selectedIndex + 1);
1736
- handleSelectionChange(oldIndex, newIndex);
1737
- return;
1738
- }
1739
- if (char === "\r" || char === "\n") {
1740
- cleanup();
1741
- resolve5({ action: "select", name: envNames[selectedIndex] });
1742
- return;
1743
- }
1744
- if (char === "e" || char === "E") {
1745
- cleanup();
1746
- resolve5({ action: "edit", name: envNames[selectedIndex] });
1747
- return;
1748
- }
1749
- if (char === "r" || char === "R") {
1750
- cleanup();
1751
- resolve5({ action: "rename", name: envNames[selectedIndex] });
1752
- return;
1753
- }
1754
- if (char === "c" || char === "C") {
1755
- cleanup();
1756
- resolve5({ action: "copy", name: envNames[selectedIndex] });
1757
- return;
1758
- }
1759
- if (char === "d" || char === "D") {
1760
- cleanup();
1761
- resolve5({ action: "delete", name: envNames[selectedIndex] });
1762
- return;
1763
- }
1764
- };
1765
- stdin.on("data", onKeypress);
1766
- });
1672
+ var LOGO_FULL = {
1673
+ width: 19,
1674
+ height: 9,
1675
+ ansi: ` \x1B[38;5;1m \x1B[38;5;109m\u2597\x1B[38;5;67m\u2581\x1B[38;5;23m\u2584\u2581 \x1B[7m\x1B[38;5;68m\u2596\u259D\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;110m\u258E\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;25m\u258B\x1B[0m\x1B[38;5;237;48;5;25m\u2595\x1B[0m\x1B[38;5;237m \x1B[7m\x1B[38;5;110m\u2598\u2583\x1B[0m\x1B[38;5;60m\u258C\x1B[38;5;24m\u2598 \x1B[0m
1676
+ \x1B[38;5;1m \x1B[7m\x1B[38;5;110m\u2585\x1B[38;5;67m\u259E\x1B[0m\x1B[38;5;110m\u2583\x1B[7m\x1B[38;5;23m\u259E\x1B[0m\x1B[38;5;24m\u2583 \x1B[7m\x1B[38;5;68m\u2596\u259D\x1B[38;5;103m\u258B\x1B[0m\x1B[38;5;109m\u258D\x1B[7m\x1B[38;5;25m\u258C\x1B[0m\x1B[38;5;25m\u258B \x1B[38;5;103m\u2584\x1B[7m\x1B[38;5;110m\u2597\x1B[38;5;61m\u259E\x1B[38;5;24m\u2583\x1B[0m\x1B[38;5;1m \x1B[38;5;60m\u2582\x1B[38;5;67m\u2584\x1B[38;5;60m\u2585\x1B[7m\u2584\x1B[0m\x1B[38;5;1m \x1B[0m
1677
+ \x1B[38;5;1m \x1B[38;5;24m\u2597\x1B[38;5;25m\u2585\u2584\u2583\x1B[38;5;61m\u2581\x1B[7m\x1B[38;5;60m\u2586\x1B[38;5;103m\u2584\x1B[0m\x1B[38;5;67m\u2585\x1B[7m\x1B[38;5;60m\u2597\x1B[0m\x1B[38;5;24m\u2585\x1B[48;5;68m\u2596\x1B[0m\x1B[7m\x1B[38;5;68m\u259D\x1B[0m\x1B[38;5;103m\u258A\x1B[7m\x1B[38;5;25m\u258E\x1B[0m\x1B[38;5;68;48;5;24m\u2584\x1B[0m\x1B[38;5;110m\u259E\x1B[7m\x1B[38;5;67m\u259E\x1B[0m\x1B[38;5;25m\u259E\x1B[38;5;67m\u2581\x1B[38;5;68m\u2583\x1B[38;5;60m\u2586\x1B[7m\x1B[38;5;67m\u2583\x1B[38;5;68m\u2585\x1B[0m\x1B[38;5;61m\u2594 \x1B[0m
1678
+ \x1B[38;5;1m \x1B[38;5;238m\u2594\x1B[38;5;23m\u2594\x1B[38;5;24m\u2594 \x1B[38;5;95m\u2582\x1B[38;5;131m\u2583\x1B[38;5;66m\u2594 \x1B[38;5;131m\u2582\u2583\x1B[38;5;60m\u2594\x1B[38;5;95m\u2582\x1B[38;5;131m\u2583\x1B[38;5;94m\u2596\x1B[38;5;95m\u2597 \x1B[38;5;60m\u2594\x1B[38;5;95m\u2583 \x1B[0m
1679
+ \x1B[38;5;1m \x1B[7m\x1B[38;5;95m\u258B\x1B[0m\x1B[38;5;131m\u258C \x1B[38;5;95m\u2581\x1B[7m\x1B[38;5;131m\u258C\x1B[0m\x1B[38;5;131m\u258D \x1B[38;5;95m\u2581\x1B[7m\x1B[38;5;131m\u258D\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;131m\u258D\x1B[38;5;95m\u2596\x1B[0m\x1B[38;5;131m\u2584\x1B[7m\u2596\x1B[0m\x1B[38;5;131m\u258E \x1B[0m
1680
+ \x1B[38;5;1m \x1B[7m\x1B[38;5;95m\u2584\x1B[38;5;94m\u2583\x1B[38;5;95m\u2585\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;95m\u2584\x1B[38;5;94m\u2584\x1B[0m\x1B[38;5;95m\u2598\x1B[38;5;167m\u259D\x1B[7m\x1B[38;5;95m\u2584\u2585\x1B[0m\x1B[38;5;131m\u259D \x1B[38;5;95m\u2594\x1B[38;5;238m\u259D\x1B[38;5;131m\u2598 \x1B[0m
1681
+ \x1B[38;5;1m \x1B[38;5;60m\u2583\x1B[38;5;240m\u2596 \x1B[38;5;109m\u2582\x1B[38;5;110m\u2584\x1B[7m\x1B[38;5;67m\u2583\x1B[38;5;60m\u259E\x1B[0m\x1B[38;5;240;48;5;68m\u2594\x1B[0m\x1B[7m\x1B[38;5;67m\u2596\x1B[38;5;61m\u2597\x1B[0m\x1B[38;5;67;48;5;110m\u2594\x1B[0m\x1B[38;5;68m\u2585\x1B[7m\x1B[38;5;60m\u2597\x1B[0m\x1B[38;5;66m\u2585\x1B[38;5;60m\u2581\x1B[7m\x1B[38;5;25m\u2586\u2584\u2583\u2582\u2594\x1B[0m\x1B[38;5;25m\u2585\x1B[38;5;24m\u2596 \x1B[0m
1682
+ \x1B[38;5;1m \x1B[38;5;60m\u2594\x1B[38;5;67m\u2582\x1B[38;5;110m\u2584\x1B[7m\u2594\u2584\x1B[0m\x1B[38;5;1m \x1B[38;5;61m\u2584\x1B[7m\x1B[38;5;67m\u2597\x1B[38;5;60m\u2597\x1B[38;5;25m\u258E\x1B[0m\x1B[38;5;25m\u258D\x1B[7m\x1B[38;5;110m\u259E\x1B[38;5;67m\u2596\x1B[0m\x1B[38;5;60;48;5;68m\u259D\x1B[0m\x1B[38;5;60m\u2598\x1B[7m\x1B[38;5;109m\u2585\x1B[0m\x1B[38;5;67m\u2585 \x1B[38;5;24m\u2594 \x1B[0m
1683
+ \x1B[38;5;1m \x1B[38;5;66m\u2597\x1B[38;5;153m\u2586\x1B[7m\x1B[38;5;110m\u2582\u2585\x1B[0m\x1B[38;5;1m \x1B[7m\x1B[38;5;68m\u2598\x1B[38;5;61m\u2584\x1B[0m\x1B[38;5;1m \x1B[38;5;24;48;5;25m\u258F\x1B[0m\x1B[38;5;24m\u258E\x1B[7m\x1B[38;5;110m\u258B\x1B[0m\x1B[38;5;103m\u258D\x1B[7m\x1B[38;5;61m\u2596\x1B[0m\x1B[38;5;239;48;5;68m\u259D\x1B[0m\x1B[38;5;60m\u2596 \x1B[7m\x1B[38;5;109m\u2585\x1B[38;5;66m\u259D\x1B[0m\x1B[38;5;1m \x1B[0m
1684
+ `
1767
1685
  };
1768
1686
 
1769
- // src/permissions.ts
1770
- import fs6 from "fs";
1771
- import chalk3 from "chalk";
1772
- import Table2 from "cli-table3";
1773
-
1774
- // src/utils.ts
1775
- import crypto3 from "crypto";
1776
- import fs3 from "fs";
1777
- import os3 from "os";
1778
- import path3 from "path";
1779
- var SECRET_KEY = crypto3.scryptSync("claude-code-env-manager-secret", "salt", 32);
1780
- var findProjectRoot = () => {
1781
- let currentDir = process.cwd();
1782
- const root = path3.parse(currentDir).root;
1783
- while (currentDir !== root) {
1784
- if (fs3.existsSync(path3.join(currentDir, ".git")) || fs3.existsSync(path3.join(currentDir, "package.json"))) {
1785
- return currentDir;
1786
- }
1787
- currentDir = path3.dirname(currentDir);
1788
- }
1789
- return process.cwd();
1790
- };
1791
- var getSettingsPath = (useLocal = true) => {
1792
- const projectRoot = findProjectRoot();
1793
- const claudeDir = path3.join(projectRoot, ".claude");
1794
- const filename = useLocal ? "settings.local.json" : "settings.json";
1795
- return path3.join(claudeDir, filename);
1687
+ // src/ui.ts
1688
+ var theme = {
1689
+ primary: chalk.hex("#89B4FA"),
1690
+ // 亮蓝
1691
+ accent: chalk.hex("#CBA6F7"),
1692
+ // 亮紫
1693
+ success: chalk.hex("#A6E3A1"),
1694
+ // 亮绿
1695
+ warning: chalk.hex("#F9E2AF"),
1696
+ // 亮黄
1697
+ danger: chalk.hex("#F38BA8"),
1698
+ // 亮红
1699
+ text: chalk.white,
1700
+ muted: chalk.hex("#6C7086"),
1701
+ // 中灰
1702
+ dim: chalk.hex("#45475A")
1703
+ // 暗灰
1796
1704
  };
1797
- var ensureClaudeDir = () => {
1798
- const projectRoot = findProjectRoot();
1799
- const claudeDir = path3.join(projectRoot, ".claude");
1800
- if (!fs3.existsSync(claudeDir)) {
1801
- fs3.mkdirSync(claudeDir, { recursive: true });
1802
- }
1803
- return claudeDir;
1705
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1706
+ var spinnerIndex = 0;
1707
+ var spinnerInterval = null;
1708
+ var getSpinnerFrame = () => {
1709
+ return theme.primary(SPINNER_FRAMES[spinnerIndex]);
1804
1710
  };
1805
- var getHomeDir2 = () => {
1806
- return process.env.HOME || process.env.USERPROFILE || os3.homedir() || "";
1711
+ var startSpinner = (onFrame) => {
1712
+ if (spinnerInterval) return;
1713
+ spinnerInterval = setInterval(() => {
1714
+ spinnerIndex = (spinnerIndex + 1) % SPINNER_FRAMES.length;
1715
+ onFrame();
1716
+ }, 80);
1807
1717
  };
1808
- var getGlobalClaudeConfigPath = () => {
1809
- return path3.join(getHomeDir2(), ".claude.json");
1718
+ var stopSpinner = () => {
1719
+ if (spinnerInterval) {
1720
+ clearInterval(spinnerInterval);
1721
+ spinnerInterval = null;
1722
+ }
1810
1723
  };
1811
- var getGlobalClaudeSettingsPath = () => {
1812
- return path3.join(getHomeDir2(), ".claude", "settings.json");
1724
+ var getTerminalWidth = () => {
1725
+ return process.stdout.columns || 80;
1813
1726
  };
1814
- var ensureGlobalClaudeDir = () => {
1815
- const claudeDir = path3.join(getHomeDir2(), ".claude");
1816
- if (!fs3.existsSync(claudeDir)) {
1817
- fs3.mkdirSync(claudeDir, { recursive: true });
1818
- }
1819
- return claudeDir;
1727
+ var selectLogo = (termWidth) => {
1728
+ if (termWidth < 45) return LOGO_MINIMAL;
1729
+ if (termWidth < 60) return LOGO_COMPACT;
1730
+ return LOGO_FULL;
1820
1731
  };
1821
-
1822
- // src/launcher.ts
1823
- import { spawn } from "child_process";
1824
- import * as fs5 from "fs";
1825
- import * as path5 from "path";
1826
- import chalk2 from "chalk";
1827
-
1828
- // src/sessionProvenance.ts
1829
- import { execFileSync } from "child_process";
1830
- import fs4 from "fs";
1831
- import { createRequire } from "module";
1832
- import os4 from "os";
1833
- import path4 from "path";
1834
- var DEFAULT_CONFIG_SOURCE = "ccem";
1835
- var STATE_DB_FILE_NAME = "state.sqlite";
1836
- var BIND_POLL_INTERVAL_MS = 500;
1837
- var BIND_POLL_TIMEOUT_MS = 2e4;
1838
- var SQLITE_EXPERIMENTAL_WARNING = "SQLite is an experimental feature";
1839
- var require2 = createRequire(import.meta.url);
1840
- var databaseSyncCtor = null;
1841
- var databaseSyncResolved = false;
1842
- var sqlite3CliAvailable = null;
1843
- function startCliClaudeProvenanceTracking(options) {
1844
- const envName = normalizeText(options.envName) ?? "unknown";
1845
- const workingDir = normalizeText(options.workingDir);
1846
- if (!workingDir) {
1847
- return null;
1848
- }
1849
- const ccemSessionId = normalizeText(options.ccemSessionId) ?? `cli-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1850
- try {
1851
- registerLaunch({
1852
- ccemSessionId,
1853
- client: "claude",
1854
- envName,
1855
- configSource: DEFAULT_CONFIG_SOURCE,
1856
- workingDir,
1857
- permMode: normalizeText(options.permMode),
1858
- launchMode: "cli_external",
1859
- startedVia: "cli",
1860
- sourceSessionId: normalizeText(options.resumeSessionId)
1861
- });
1862
- } catch (error) {
1863
- reportTrackingError("register launch", error);
1864
- return null;
1865
- }
1866
- let timer = null;
1867
- const stop = () => {
1868
- if (timer) {
1869
- clearInterval(timer);
1870
- timer = null;
1871
- }
1872
- };
1873
- const resumeSessionId = normalizeText(options.resumeSessionId);
1874
- if (resumeSessionId) {
1875
- return { ccemSessionId, stop };
1876
- }
1877
- const startedAtMs = Date.now();
1878
- timer = setInterval(() => {
1879
- if (Date.now() - startedAtMs > BIND_POLL_TIMEOUT_MS) {
1880
- stop();
1881
- return;
1882
- }
1883
- try {
1884
- const jsonlPath = discoverClaudeJsonlPath(workingDir, startedAtMs);
1885
- if (!jsonlPath) {
1886
- return;
1887
- }
1888
- const sourceSessionId = readClaudeSessionId(jsonlPath) ?? normalizeText(path4.parse(jsonlPath).name);
1889
- if (!sourceSessionId) {
1890
- return;
1891
- }
1892
- bindSourceSessionId("claude", ccemSessionId, sourceSessionId);
1893
- stop();
1894
- } catch (error) {
1895
- reportTrackingError("bind source session id", error);
1896
- stop();
1897
- }
1898
- }, BIND_POLL_INTERVAL_MS);
1899
- return { ccemSessionId, stop };
1900
- }
1901
- function registerLaunch(options) {
1902
- const now = (/* @__PURE__ */ new Date()).toISOString();
1903
- const DatabaseSync = getDatabaseSyncCtor();
1904
- if (DatabaseSync) {
1905
- const db = openNodeSqliteDb(DatabaseSync);
1906
- try {
1907
- const statement = db.prepare(`
1908
- INSERT INTO session_provenance (
1909
- ccem_session_id,
1910
- client,
1911
- env_name,
1912
- config_source,
1913
- working_dir,
1914
- perm_mode,
1915
- launch_mode,
1916
- started_via,
1917
- source_session_id,
1918
- created_at,
1919
- updated_at
1920
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1921
- ON CONFLICT(ccem_session_id) DO UPDATE SET
1922
- client = excluded.client,
1923
- env_name = excluded.env_name,
1924
- config_source = COALESCE(excluded.config_source, session_provenance.config_source),
1925
- working_dir = excluded.working_dir,
1926
- perm_mode = COALESCE(excluded.perm_mode, session_provenance.perm_mode),
1927
- launch_mode = excluded.launch_mode,
1928
- started_via = excluded.started_via,
1929
- source_session_id = COALESCE(excluded.source_session_id, session_provenance.source_session_id),
1930
- updated_at = excluded.updated_at
1931
- `);
1932
- statement.run(
1933
- options.ccemSessionId,
1934
- options.client,
1935
- options.envName,
1936
- normalizeText(options.configSource),
1937
- options.workingDir,
1938
- normalizeText(options.permMode),
1939
- options.launchMode,
1940
- options.startedVia,
1941
- normalizeText(options.sourceSessionId),
1942
- now,
1943
- now
1944
- );
1945
- return;
1946
- } finally {
1947
- db.close();
1948
- }
1949
- }
1950
- execSqlite3Cli(`
1951
- INSERT INTO session_provenance (
1952
- ccem_session_id,
1953
- client,
1954
- env_name,
1955
- config_source,
1956
- working_dir,
1957
- perm_mode,
1958
- launch_mode,
1959
- started_via,
1960
- source_session_id,
1961
- created_at,
1962
- updated_at
1963
- ) VALUES (
1964
- ${sqliteLiteral(options.ccemSessionId)},
1965
- ${sqliteLiteral(options.client)},
1966
- ${sqliteLiteral(options.envName)},
1967
- ${sqliteLiteral(normalizeText(options.configSource))},
1968
- ${sqliteLiteral(options.workingDir)},
1969
- ${sqliteLiteral(normalizeText(options.permMode))},
1970
- ${sqliteLiteral(options.launchMode)},
1971
- ${sqliteLiteral(options.startedVia)},
1972
- ${sqliteLiteral(normalizeText(options.sourceSessionId))},
1973
- ${sqliteLiteral(now)},
1974
- ${sqliteLiteral(now)}
1975
- )
1976
- ON CONFLICT(ccem_session_id) DO UPDATE SET
1977
- client = excluded.client,
1978
- env_name = excluded.env_name,
1979
- config_source = COALESCE(excluded.config_source, session_provenance.config_source),
1980
- working_dir = excluded.working_dir,
1981
- perm_mode = COALESCE(excluded.perm_mode, session_provenance.perm_mode),
1982
- launch_mode = excluded.launch_mode,
1983
- started_via = excluded.started_via,
1984
- source_session_id = COALESCE(excluded.source_session_id, session_provenance.source_session_id),
1985
- updated_at = excluded.updated_at;
1986
- `);
1987
- }
1988
- function bindSourceSessionId(client, ccemSessionId, sourceSessionId) {
1989
- const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1990
- const DatabaseSync = getDatabaseSyncCtor();
1991
- if (DatabaseSync) {
1992
- const db = openNodeSqliteDb(DatabaseSync);
1732
+ var renderLogoWithEnvPanel = (envName, env, defaultMode) => {
1733
+ const displayEnv = resolveEnvConfigForRuntime(envName, env);
1734
+ const termWidth = getTerminalWidth();
1735
+ const isNarrow = termWidth < 60;
1736
+ const isVeryNarrow = termWidth < 45;
1737
+ const logo = selectLogo(termWidth);
1738
+ const logoLines = logo.ansi.split("\n").filter((l) => l.length > 0);
1739
+ const title = theme.primary("CCEM") + " " + theme.muted("Claude Code Env Manager");
1740
+ const titleShort = theme.primary("CCEM");
1741
+ const envLabel = theme.muted("Env: ") + theme.primary(envName);
1742
+ const baseUrl = displayEnv.ANTHROPIC_BASE_URL || "-";
1743
+ const runtimeModel = displayEnv.ANTHROPIC_MODEL || "-";
1744
+ const opusModel = displayEnv.ANTHROPIC_DEFAULT_OPUS_MODEL || (envName === "official" ? "Claude default" : "-");
1745
+ const haikuModel = displayEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL || "-";
1746
+ const authToken = displayEnv.ANTHROPIC_AUTH_TOKEN ? displayEnv.ANTHROPIC_AUTH_TOKEN.slice(0, 2) + "\u2022\u2022\u2022\u2022" + displayEnv.ANTHROPIC_AUTH_TOKEN.slice(-4) : "-";
1747
+ const truncate = (s, max) => s.length > max ? s.slice(0, max - 3) + "..." : s;
1748
+ const maskUrl = (url, max) => {
1749
+ if (url.length <= max) return url;
1993
1750
  try {
1994
- const statement = db.prepare(`
1995
- UPDATE session_provenance
1996
- SET source_session_id = ?, updated_at = ?
1997
- WHERE ccem_session_id = ? AND client = ?
1998
- `);
1999
- statement.run(sourceSessionId, updatedAt, ccemSessionId, client);
2000
- return;
2001
- } finally {
2002
- db.close();
1751
+ const parsed = new URL(url);
1752
+ const protocol = parsed.protocol + "//";
1753
+ const host = parsed.host;
1754
+ const path13 = parsed.pathname + parsed.search;
1755
+ const hostStart = host.slice(0, 8);
1756
+ const hostEnd = host.slice(-4);
1757
+ const pathPart = path13.length > 10 ? path13.slice(0, 7) + "..." : path13;
1758
+ return `${protocol}${hostStart}...${hostEnd}${pathPart}`;
1759
+ } catch {
1760
+ return truncate(url, max);
2003
1761
  }
1762
+ };
1763
+ const labelWidth = 7;
1764
+ let envLines;
1765
+ if (isNarrow) {
1766
+ envLines = [
1767
+ envLabel,
1768
+ theme.muted("Opus:".padEnd(labelWidth)) + theme.dim(truncate(opusModel, 25)),
1769
+ theme.muted("Token:".padEnd(labelWidth)) + theme.dim(authToken)
1770
+ ];
1771
+ } else {
1772
+ envLines = [
1773
+ envLabel + (defaultMode && PERMISSION_PRESETS[defaultMode] ? " " + theme.accent(`[${PERMISSION_PRESETS[defaultMode].name}]`) : ""),
1774
+ theme.muted("URL:".padEnd(labelWidth)) + theme.dim(maskUrl(baseUrl, 40)),
1775
+ theme.muted("Run:".padEnd(labelWidth)) + theme.dim(truncate(runtimeModel, 12)) + " " + theme.muted("Opus:".padEnd(labelWidth)) + theme.dim(truncate(opusModel, 15)),
1776
+ theme.muted("Haiku:".padEnd(labelWidth)) + theme.dim(truncate(haikuModel, 15)) + " " + theme.muted("Token:".padEnd(labelWidth)) + theme.dim(authToken)
1777
+ ];
2004
1778
  }
2005
- execSqlite3Cli(`
2006
- UPDATE session_provenance
2007
- SET source_session_id = ${sqliteLiteral(sourceSessionId)},
2008
- updated_at = ${sqliteLiteral(updatedAt)}
2009
- WHERE ccem_session_id = ${sqliteLiteral(ccemSessionId)}
2010
- AND client = ${sqliteLiteral(client)};
2011
- `);
2012
- }
2013
- function openNodeSqliteDb(DatabaseSync) {
2014
- const dbPath = getStateDbPath();
2015
- fs4.mkdirSync(path4.dirname(dbPath), { recursive: true });
2016
- const db = new DatabaseSync(dbPath);
2017
- db.exec(schemaSql());
2018
- return db;
2019
- }
2020
- function getDatabaseSyncCtor() {
2021
- if (databaseSyncResolved) {
2022
- return databaseSyncCtor;
2023
- }
2024
- const originalEmitWarning = process.emitWarning;
2025
- process.emitWarning = ((warning, ...args) => {
2026
- const message = typeof warning === "string" ? warning : warning instanceof Error ? warning.message : String(warning);
2027
- if (message.includes(SQLITE_EXPERIMENTAL_WARNING)) {
2028
- return;
1779
+ const lines = [];
1780
+ if (isVeryNarrow) {
1781
+ logoLines.forEach((line) => lines.push(line));
1782
+ lines.push("");
1783
+ lines.push(titleShort);
1784
+ lines.push("");
1785
+ envLines.forEach((line) => lines.push(line));
1786
+ } else {
1787
+ const gap = isNarrow ? " " : " ";
1788
+ lines.push("");
1789
+ const maxLines = Math.max(logoLines.length, envLines.length + 3);
1790
+ for (let i = 0; i < maxLines; i++) {
1791
+ const logoLine = logoLines[i] || "";
1792
+ if (i === 0) {
1793
+ const visibleWidth2 = logoLine.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
1794
+ const padding2 = " ".repeat(Math.max(0, logo.width - visibleWidth2));
1795
+ lines.push(logoLine + padding2);
1796
+ continue;
1797
+ }
1798
+ if (i === 1) {
1799
+ const visibleWidth2 = logoLine.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
1800
+ const padding2 = " ".repeat(Math.max(0, logo.width - visibleWidth2));
1801
+ lines.push(logoLine + padding2 + gap + (isNarrow ? titleShort : title));
1802
+ continue;
1803
+ }
1804
+ if (i === 2) {
1805
+ const visibleWidth2 = logoLine.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
1806
+ const padding2 = " ".repeat(Math.max(0, logo.width - visibleWidth2));
1807
+ lines.push(logoLine + padding2);
1808
+ continue;
1809
+ }
1810
+ const envLine = envLines[i - 3] || "";
1811
+ const visibleWidth = logoLine.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").length;
1812
+ const padding = " ".repeat(Math.max(0, logo.width - visibleWidth));
1813
+ lines.push(logoLine + padding + gap + envLine);
2029
1814
  }
2030
- return originalEmitWarning(warning, ...args);
2031
- });
2032
- try {
2033
- const loaded = require2("node:sqlite");
2034
- databaseSyncCtor = loaded.DatabaseSync;
2035
- } catch {
2036
- databaseSyncCtor = null;
2037
- } finally {
2038
- process.emitWarning = originalEmitWarning;
2039
- databaseSyncResolved = true;
2040
1815
  }
2041
- return databaseSyncCtor;
2042
- }
2043
- function execSqlite3Cli(statementSql) {
2044
- if (sqlite3CliAvailable == null) {
2045
- try {
2046
- execFileSync("sqlite3", ["-version"], { stdio: "ignore" });
2047
- sqlite3CliAvailable = true;
2048
- } catch {
2049
- sqlite3CliAvailable = false;
2050
- }
1816
+ return lines.join("\n");
1817
+ };
1818
+ var renderUsageLine = (stats, loading) => {
1819
+ if (loading) {
1820
+ return theme.muted(" Usage: ") + getSpinnerFrame() + theme.dim(" Loading...");
2051
1821
  }
2052
- if (!sqlite3CliAvailable) {
2053
- throw new Error("sqlite3 CLI is unavailable and node:sqlite is not supported by this Node runtime");
1822
+ if (!stats) {
1823
+ return theme.muted(" Usage: ") + theme.dim("No data");
2054
1824
  }
2055
- const dbPath = getStateDbPath();
2056
- fs4.mkdirSync(path4.dirname(dbPath), { recursive: true });
2057
- execFileSync("sqlite3", [dbPath], {
2058
- input: `${schemaSql()}
2059
- ${statementSql}
2060
- `,
2061
- stdio: ["pipe", "ignore", "pipe"]
2062
- });
2063
- }
2064
- function getStateDbPath() {
2065
- const override = normalizeText(process.env.CCEM_STATE_DB_PATH);
2066
- if (override) {
2067
- return override;
1825
+ const termWidth = getTerminalWidth();
1826
+ const isNarrow = termWidth < 70;
1827
+ const todayTokens = getTotalTokens(stats.today);
1828
+ const weekTokens = getTotalTokens(stats.week);
1829
+ const totalTokens = getTotalTokens(stats.total);
1830
+ if (isNarrow) {
1831
+ return theme.muted(" Usage: ") + theme.text("Today ") + theme.primary(formatTokens(todayTokens)) + theme.dim(" | ") + theme.text("Week ") + theme.primary(formatTokens(weekTokens)) + theme.dim(" | ") + theme.text("Total ") + theme.primary(formatTokens(totalTokens));
2068
1832
  }
2069
- return path4.join(os4.homedir(), ".ccem", STATE_DB_FILE_NAME);
2070
- }
2071
- function schemaSql() {
2072
- return `
2073
- PRAGMA journal_mode = WAL;
2074
- PRAGMA synchronous = NORMAL;
2075
- CREATE TABLE IF NOT EXISTS session_provenance (
2076
- ccem_session_id TEXT PRIMARY KEY,
2077
- client TEXT NOT NULL,
2078
- env_name TEXT NOT NULL,
2079
- config_source TEXT,
2080
- working_dir TEXT NOT NULL,
2081
- perm_mode TEXT,
2082
- launch_mode TEXT NOT NULL,
2083
- started_via TEXT NOT NULL,
2084
- source_session_id TEXT,
2085
- created_at TEXT NOT NULL,
2086
- updated_at TEXT NOT NULL
2087
- );
2088
- CREATE INDEX IF NOT EXISTS idx_session_provenance_client_source
2089
- ON session_provenance (client, source_session_id);
2090
- CREATE INDEX IF NOT EXISTS idx_session_provenance_client_updated
2091
- ON session_provenance (client, updated_at DESC);
2092
- `;
2093
- }
2094
- function discoverClaudeJsonlPath(projectDir, startedAtMs) {
2095
- const projectsDir = path4.join(os4.homedir(), ".claude", "projects");
2096
- const earliestModifiedAt = startedAtMs - 15e3;
2097
- for (const key of projectDirKeys(projectDir)) {
2098
- const baseDir = path4.join(projectsDir, key);
2099
- if (!fs4.existsSync(baseDir)) {
2100
- continue;
2101
- }
2102
- const candidates = fs4.readdirSync(baseDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => {
2103
- const fullPath = path4.join(baseDir, entry.name);
2104
- return { path: fullPath, modifiedAt: fs4.statSync(fullPath).mtimeMs };
2105
- }).filter((candidate) => candidate.modifiedAt >= earliestModifiedAt).sort((left, right) => right.modifiedAt - left.modifiedAt);
2106
- if (candidates.length > 0) {
2107
- return candidates[0].path;
2108
- }
1833
+ return theme.muted(" Usage: ") + theme.text("Today ") + theme.primary(formatTokens(todayTokens).padStart(6)) + theme.dim(` (${formatCost(stats.today.cost)})`) + theme.dim(" | ") + theme.text("Week ") + theme.primary(formatTokens(weekTokens).padStart(6)) + theme.dim(` (${formatCost(stats.week.cost)})`) + theme.dim(" | ") + theme.text("Total ") + theme.primary(formatTokens(totalTokens).padStart(6)) + theme.dim(` (${formatCost(stats.total.cost)})`);
1834
+ };
1835
+ var renderCompactHeader = () => {
1836
+ const width = process.stdout.columns || 80;
1837
+ return theme.dim("\u2500".repeat(width));
1838
+ };
1839
+ var getMainMenuChoices = (defaultMode) => {
1840
+ let startLabel = "Start Claude Code";
1841
+ if (defaultMode && PERMISSION_PRESETS[defaultMode]) {
1842
+ startLabel = `Start Claude Code ${theme.muted(`(${PERMISSION_PRESETS[defaultMode].name})`)}`;
2109
1843
  }
2110
- return null;
2111
- }
2112
- function projectDirKeys(projectDir) {
2113
- const candidates = [projectDir];
2114
- try {
2115
- candidates.push(fs4.realpathSync(projectDir));
2116
- } catch {
1844
+ return [
1845
+ { name: theme.success(startLabel), value: "start", short: "Start" },
1846
+ { name: theme.primary("Switch Environment"), value: "switch", short: "Switch" },
1847
+ { name: theme.primary("Permission Mode"), value: "perm", short: "Permission" },
1848
+ { name: theme.accent("View Usage"), value: "usage", short: "Usage" },
1849
+ { name: theme.text("Set Default Mode"), value: "setDefault", short: "Default" },
1850
+ { name: theme.muted("Exit"), value: "exit", short: "Exit" }
1851
+ ];
1852
+ };
1853
+ var modeColors = {
1854
+ yolo: theme.danger,
1855
+ dev: theme.success,
1856
+ readonly: theme.primary,
1857
+ safe: theme.warning,
1858
+ ci: theme.accent,
1859
+ audit: theme.primary
1860
+ };
1861
+ var getPermModeChoices = (currentMode, showCurrent = false) => {
1862
+ const modes = ["yolo", "dev", "readonly", "safe", "ci", "audit"];
1863
+ const choices = modes.map((mode) => {
1864
+ const preset = PERMISSION_PRESETS[mode];
1865
+ const colorFn = modeColors[mode];
1866
+ const isCurrent = showCurrent && mode === currentMode;
1867
+ const tag = isCurrent ? theme.success(" *") : "";
1868
+ return {
1869
+ name: colorFn(preset.name.padEnd(12)) + theme.muted(preset.description) + tag,
1870
+ value: mode,
1871
+ short: preset.name
1872
+ };
1873
+ });
1874
+ if (showCurrent) {
1875
+ choices.push({
1876
+ name: theme.muted("Clear default"),
1877
+ value: "clear",
1878
+ short: "Clear"
1879
+ });
1880
+ }
1881
+ choices.push({
1882
+ name: theme.muted("Back"),
1883
+ value: "back",
1884
+ short: "Back"
1885
+ });
1886
+ return choices;
1887
+ };
1888
+ var msg = {
1889
+ success: (text) => console.log(theme.success("\u2713 ") + theme.text(text)),
1890
+ error: (text) => console.log(theme.danger("\u2717 ") + theme.text(text)),
1891
+ warning: (text) => console.log(theme.warning("! ") + theme.text(text)),
1892
+ info: (text) => console.log(theme.primary("\u203A ") + theme.text(text))
1893
+ };
1894
+ var renderStarting = () => {
1895
+ return theme.muted("Starting Claude Code...");
1896
+ };
1897
+ var renderCalendarHeatmap = (stats, months = 6) => {
1898
+ const lines = [];
1899
+ const now = /* @__PURE__ */ new Date();
1900
+ const startDate = new Date(now);
1901
+ startDate.setMonth(startDate.getMonth() - months);
1902
+ const day = startDate.getDay();
1903
+ const diff = startDate.getDate() - day + (day === 0 ? -6 : 1);
1904
+ startDate.setDate(diff);
1905
+ startDate.setHours(0, 0, 0, 0);
1906
+ const dates = [];
1907
+ const d = new Date(startDate);
1908
+ while (d <= now || d.getDay() !== 1) {
1909
+ dates.push(d.toISOString().split("T")[0]);
1910
+ d.setDate(d.getDate() + 1);
1911
+ if (d > now && d.getDay() === 1) break;
2117
1912
  }
2118
- if (process.platform === "darwin") {
2119
- if (projectDir.startsWith("/private/")) {
2120
- candidates.push(projectDir.slice("/private".length));
2121
- } else if (projectDir.startsWith("/tmp")) {
2122
- candidates.push(path4.posix.join("/private", projectDir));
2123
- } else if (projectDir.startsWith("/var/")) {
2124
- candidates.push(path4.posix.join("/private", projectDir));
1913
+ let maxTokens = 0;
1914
+ for (const date of dates) {
1915
+ const usage = stats.dailyHistory[date];
1916
+ if (usage) {
1917
+ const tokens = getTotalTokens(usage);
1918
+ if (tokens > maxTokens) maxTokens = tokens;
2125
1919
  }
2126
1920
  }
2127
- return [...new Set(candidates.map(projectDirKey))];
2128
- }
2129
- function projectDirKey(projectDir) {
2130
- return projectDir.replace(/[\/\\: ]/g, "-");
2131
- }
2132
- function readClaudeSessionId(jsonlPath) {
2133
- const lines = fs4.readFileSync(jsonlPath, "utf8").split("\n");
2134
- for (const line of lines) {
2135
- if (!line.trim()) {
2136
- continue;
2137
- }
2138
- try {
2139
- const value = JSON.parse(line);
2140
- const sessionId = normalizeText(value.sessionId);
2141
- if (sessionId) {
2142
- return sessionId;
1921
+ let header = " ";
1922
+ let currentMonth = -1;
1923
+ const weeks = Math.ceil(dates.length / 7);
1924
+ for (let w = 0; w < weeks; w++) {
1925
+ const dateIndex = w * 7;
1926
+ if (dateIndex < dates.length) {
1927
+ const date = new Date(dates[dateIndex]);
1928
+ const month = date.getMonth();
1929
+ if (month !== currentMonth && w < weeks - 1) {
1930
+ const monthName = date.toLocaleString("default", { month: "short" });
1931
+ header += theme.muted(monthName);
1932
+ currentMonth = month;
2143
1933
  }
2144
- } catch {
2145
1934
  }
2146
1935
  }
2147
- return null;
2148
- }
2149
- function normalizeText(value) {
2150
- const trimmed = value?.trim();
2151
- return trimmed ? trimmed : void 0;
2152
- }
2153
- function sqliteLiteral(value) {
2154
- if (!value) {
2155
- return "NULL";
2156
- }
2157
- return `'${value.replace(/'/g, "''")}'`;
2158
- }
2159
- function reportTrackingError(stage, error) {
2160
- const message = error instanceof Error ? error.message : String(error);
2161
- console.error(`[ccem] Failed to ${stage}: ${message}`);
2162
- }
2163
-
2164
- // src/launcher.ts
2165
- var MANAGED_CLAUDE_ENV_KEYS = [
2166
- "ANTHROPIC_BASE_URL",
2167
- "ANTHROPIC_AUTH_TOKEN",
2168
- "ANTHROPIC_DEFAULT_OPUS_MODEL",
2169
- "ANTHROPIC_DEFAULT_SONNET_MODEL",
2170
- "ANTHROPIC_DEFAULT_HAIKU_MODEL",
2171
- "ANTHROPIC_MODEL",
2172
- "CLAUDE_CODE_SUBAGENT_MODEL",
2173
- "ANTHROPIC_API_KEY",
2174
- "ANTHROPIC_SMALL_FAST_MODEL"
2175
- ];
2176
- function buildEnvVars(envName, envConfig, options = {}) {
2177
- const runtimeEnv = resolveEnvConfigForRuntime(envName, envConfig);
2178
- const authToken = runtimeEnv.ANTHROPIC_AUTH_TOKEN ? decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN) : void 0;
2179
- if (!options.allowDesktopProxyOverride || !isTrustedDesktopProxyBaseUrl(runtimeEnv.ANTHROPIC_BASE_URL)) {
2180
- assertClaudeEnvironmentAuthBoundary(
2181
- envName,
2182
- runtimeEnv.ANTHROPIC_BASE_URL,
2183
- authToken
2184
- );
2185
- }
2186
- const vars = {};
2187
- if (runtimeEnv.ANTHROPIC_BASE_URL) vars.ANTHROPIC_BASE_URL = runtimeEnv.ANTHROPIC_BASE_URL;
2188
- if (authToken) vars.ANTHROPIC_AUTH_TOKEN = authToken;
2189
- if (runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL) vars.ANTHROPIC_DEFAULT_OPUS_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL;
2190
- if (runtimeEnv.ANTHROPIC_DEFAULT_SONNET_MODEL) vars.ANTHROPIC_DEFAULT_SONNET_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_SONNET_MODEL;
2191
- if (runtimeEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL) vars.ANTHROPIC_DEFAULT_HAIKU_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL;
2192
- if (runtimeEnv.ANTHROPIC_MODEL) vars.ANTHROPIC_MODEL = runtimeEnv.ANTHROPIC_MODEL;
2193
- if (runtimeEnv.CLAUDE_CODE_SUBAGENT_MODEL) vars.CLAUDE_CODE_SUBAGENT_MODEL = runtimeEnv.CLAUDE_CODE_SUBAGENT_MODEL;
2194
- return vars;
2195
- }
2196
- function isTrustedDesktopProxyBaseUrl(value) {
2197
- if (!value) return false;
2198
- try {
2199
- const url = new URL(value);
2200
- return url.protocol === "http:" && url.hostname === "127.0.0.1" && !url.username && !url.password && !url.search && !url.hash && url.pathname.startsWith("/proxy/claude/");
2201
- } catch {
2202
- return false;
2203
- }
2204
- }
2205
- function buildPermArgs(modeName) {
2206
- const preset = PERMISSION_PRESETS[modeName];
2207
- if (!preset) return [];
2208
- const args = ["--permission-mode", preset.permissionMode];
2209
- const allowRules = normalizePermissionAllowRules(preset.permissions.allow);
2210
- if (allowRules.length > 0) {
2211
- args.push("--allowedTools", ...allowRules);
2212
- }
2213
- if (preset.permissions.deny.length > 0) {
2214
- args.push("--disallowedTools", ...preset.permissions.deny);
2215
- }
2216
- return args;
2217
- }
2218
- function ensureSessionsDir() {
2219
- const dir = path5.join(ensureCcemDir(), "sessions");
2220
- if (!fs5.existsSync(dir)) {
2221
- fs5.mkdirSync(dir, { recursive: true });
2222
- }
2223
- return dir;
2224
- }
2225
- async function launchClaude(options) {
2226
- const {
2227
- envName,
2228
- envConfig,
2229
- permMode,
2230
- workingDir,
2231
- sessionId,
2232
- resumeSessionId,
2233
- silent,
2234
- allowDesktopProxyOverride
2235
- } = options;
2236
- const ccemRuntimeId = sessionId ?? `cli-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
2237
- const env = { ...process.env };
2238
- for (const key of MANAGED_CLAUDE_ENV_KEYS) {
2239
- delete env[key];
1936
+ header = " ";
1937
+ let lastMonth = -1;
1938
+ for (let w = 0; w < weeks; w++) {
1939
+ const dateIndex = w * 7;
1940
+ if (dateIndex >= dates.length) break;
1941
+ const date = new Date(dates[dateIndex]);
1942
+ const month = date.getMonth();
1943
+ if (month !== lastMonth) {
1944
+ const monthName = date.toLocaleString("default", { month: "short" });
1945
+ header += theme.muted(monthName.padEnd(4));
1946
+ w++;
1947
+ lastMonth = month;
1948
+ } else {
1949
+ header += " ";
1950
+ }
2240
1951
  }
2241
- if (envConfig) {
2242
- Object.assign(env, buildEnvVars(envName, envConfig, { allowDesktopProxyOverride }));
1952
+ lines.push(header);
1953
+ const dayLabels = ["Mon", "", "Wed", "", "Fri", "", "Sun"];
1954
+ const levels = [" ", "\u2591", "\u2592", "\u2593", "\u2588"];
1955
+ for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
1956
+ let row = theme.muted((dayLabels[dayOfWeek] || "").padEnd(4) + " ");
1957
+ for (let w = 0; w < weeks; w++) {
1958
+ const dateIndex = w * 7 + dayOfWeek;
1959
+ if (dateIndex < dates.length) {
1960
+ const dateKey = dates[dateIndex];
1961
+ if (new Date(dateKey) > now) {
1962
+ row += " ";
1963
+ } else {
1964
+ const usage = stats.dailyHistory[dateKey];
1965
+ const tokens = usage ? getTotalTokens(usage) : 0;
1966
+ let level = 0;
1967
+ if (tokens > 0) {
1968
+ if (maxTokens === 0) level = 0;
1969
+ else {
1970
+ level = Math.ceil(tokens / maxTokens * 4);
1971
+ }
1972
+ }
1973
+ row += (level === 0 ? theme.dim("\xB7") : theme.primary(levels[level])) + " ";
1974
+ }
1975
+ }
1976
+ }
1977
+ lines.push(row);
2243
1978
  }
2244
- delete env.CLAUDECODE;
2245
- env.CCEM_RUNTIME_ID = ccemRuntimeId;
2246
- env.CCEM_SESSION_ID = ccemRuntimeId;
2247
- const args = [];
2248
- if (permMode) {
2249
- const preset = PERMISSION_PRESETS[permMode];
2250
- if (preset) {
2251
- if (!silent) {
2252
- console.log(chalk2.green(`\u5DF2\u5E94\u7528 ${preset.name}\uFF08\u4E34\u65F6\uFF09`));
2253
- console.log(chalk2.gray(`\u8BF4\u660E: ${preset.description}`));
2254
- console.log("");
1979
+ lines.push("");
1980
+ lines.push(" " + theme.dim("Less ") + theme.dim("\xB7") + " " + theme.primary(levels[1]) + " " + theme.primary(levels[2]) + " " + theme.primary(levels[3]) + " " + theme.primary(levels[4]) + " " + theme.dim(" More"));
1981
+ return lines.join("\n");
1982
+ };
1983
+ var renderUsageDetail = (stats) => {
1984
+ const lines = [];
1985
+ lines.push("");
1986
+ lines.push(theme.primary(" Token Usage Statistics"));
1987
+ lines.push(theme.dim("\u2500".repeat(60)));
1988
+ lines.push("");
1989
+ lines.push(renderCalendarHeatmap(stats));
1990
+ lines.push("");
1991
+ lines.push(theme.dim("\u2500".repeat(60)));
1992
+ const periodTable = new Table({
1993
+ head: [
1994
+ theme.muted("Period"),
1995
+ theme.muted("Input"),
1996
+ theme.muted("Output"),
1997
+ theme.muted("Cache Read"),
1998
+ theme.muted("Cost")
1999
+ ],
2000
+ style: { head: [], border: [] },
2001
+ chars: {
2002
+ "top": "",
2003
+ "top-mid": "",
2004
+ "top-left": "",
2005
+ "top-right": "",
2006
+ "bottom": "",
2007
+ "bottom-mid": "",
2008
+ "bottom-left": "",
2009
+ "bottom-right": "",
2010
+ "left": " ",
2011
+ "left-mid": "",
2012
+ "mid": "",
2013
+ "mid-mid": "",
2014
+ "right": "",
2015
+ "right-mid": "",
2016
+ "middle": " "
2017
+ }
2018
+ });
2019
+ const formatRow = (label, usage) => [
2020
+ theme.text(label),
2021
+ theme.primary(formatTokens(usage.inputTokens)),
2022
+ theme.primary(formatTokens(usage.outputTokens)),
2023
+ theme.primary(formatTokens(usage.cacheReadTokens)),
2024
+ theme.success(formatCost(usage.cost))
2025
+ ];
2026
+ periodTable.push(formatRow("Today", stats.today));
2027
+ periodTable.push(formatRow("This Week", stats.week));
2028
+ periodTable.push(formatRow("All Time", stats.total));
2029
+ lines.push(periodTable.toString());
2030
+ const modelEntries = Object.entries(stats.byModel).sort((a, b) => b[1].cost - a[1].cost);
2031
+ if (modelEntries.length > 0) {
2032
+ lines.push("");
2033
+ lines.push(theme.dim("\u2500".repeat(60)));
2034
+ lines.push(theme.muted(" By Model"));
2035
+ lines.push("");
2036
+ const modelTable = new Table({
2037
+ head: [
2038
+ theme.muted("Model"),
2039
+ theme.muted("Tokens"),
2040
+ theme.muted("Cost")
2041
+ ],
2042
+ style: { head: [], border: [] },
2043
+ chars: {
2044
+ "top": "",
2045
+ "top-mid": "",
2046
+ "top-left": "",
2047
+ "top-right": "",
2048
+ "bottom": "",
2049
+ "bottom-mid": "",
2050
+ "bottom-left": "",
2051
+ "bottom-right": "",
2052
+ "left": " ",
2053
+ "left-mid": "",
2054
+ "mid": "",
2055
+ "mid-mid": "",
2056
+ "right": "",
2057
+ "right-mid": "",
2058
+ "middle": " "
2255
2059
  }
2256
- args.push(...buildPermArgs(permMode));
2060
+ });
2061
+ for (const [model, usage] of modelEntries) {
2062
+ const totalTokens = getTotalTokens(usage);
2063
+ modelTable.push([
2064
+ theme.text(model),
2065
+ theme.primary(formatTokens(totalTokens)),
2066
+ theme.success(formatCost(usage.cost))
2067
+ ]);
2257
2068
  }
2069
+ lines.push(modelTable.toString());
2258
2070
  }
2259
- if (resumeSessionId) {
2260
- args.push("--resume", resumeSessionId);
2261
- }
2262
- if (workingDir) {
2263
- process.chdir(workingDir);
2264
- }
2265
- const effectiveWorkingDir = process.cwd();
2266
- if (!silent && !permMode) {
2267
- console.log(renderStarting());
2268
- }
2269
- const sessionsDir = ensureSessionsDir();
2071
+ lines.push("");
2072
+ lines.push(theme.dim("\u2500".repeat(60)));
2073
+ lines.push(theme.muted(` Last updated: ${new Date(stats.lastUpdated).toLocaleString()}`));
2074
+ return lines.join("\n");
2075
+ };
2076
+ var renderFooterHints = (hints) => {
2077
+ const termWidth = process.stdout.columns || 80;
2078
+ const full = hints.map((h) => theme.primary(h.key) + theme.dim(h.label)).join(" ");
2079
+ const medium = hints.map((h) => theme.primary(h.key) + theme.dim(h.short || h.label)).join(" ");
2080
+ const minimal = hints.map((h) => theme.primary(h.key)).join(" ");
2081
+ const stripAnsi = (s) => s.replace(/\x1B\[[0-9;]*m/g, "");
2082
+ if (stripAnsi(full).length <= termWidth) return full;
2083
+ if (stripAnsi(medium).length <= termWidth) return medium;
2084
+ return minimal;
2085
+ };
2086
+ var selectEnvWithKeys = (registries, current) => {
2270
2087
  return new Promise((resolve5) => {
2271
- let provenanceTracking = null;
2272
- const child = spawn("claude", args, {
2273
- stdio: "inherit",
2274
- shell: false,
2275
- // 直接执行二进制,避免 shell 注入风险
2276
- env
2277
- });
2278
- child.once("spawn", () => {
2279
- if (sessionId) {
2088
+ const envNames = Object.keys(registries);
2089
+ let selectedIndex = envNames.indexOf(current);
2090
+ if (selectedIndex === -1) selectedIndex = 0;
2091
+ const stdin = process.stdin;
2092
+ const wasRaw = stdin.isRaw;
2093
+ stdin.setRawMode(true);
2094
+ stdin.resume();
2095
+ const footerHints = [
2096
+ { key: "[\u2191\u2193]", label: " navigate", short: " nav" },
2097
+ { key: "[Enter]", label: " select", short: " sel" },
2098
+ { key: "[e]", label: "dit", short: "" },
2099
+ { key: "[r]", label: "ename", short: "en" },
2100
+ { key: "[c]", label: "opy", short: "py" },
2101
+ { key: "[d]", label: "elete", short: "el" }
2102
+ ];
2103
+ const totalLines = envNames.length + 1;
2104
+ const renderItem = (index) => {
2105
+ const name = envNames[index];
2106
+ const isCurrent = name === current;
2107
+ const isSelected = index === selectedIndex;
2108
+ const prefix = isSelected ? theme.primary("\u276F ") : " ";
2109
+ const tag = isCurrent ? theme.success(" *") : "";
2110
+ const nameText = isSelected ? theme.primary(name) : isCurrent ? theme.primary(name) : theme.text(name);
2111
+ return prefix + nameText + tag;
2112
+ };
2113
+ const updateLine = (lineIndex, content) => {
2114
+ const moveUp = totalLines - lineIndex;
2115
+ process.stdout.write(`\x1B[${moveUp}A`);
2116
+ process.stdout.write("\x1B[2K");
2117
+ process.stdout.write("\x1B[G");
2118
+ process.stdout.write(content);
2119
+ process.stdout.write(`\x1B[${moveUp}B`);
2120
+ process.stdout.write("\x1B[G");
2121
+ };
2122
+ const initialRender = () => {
2123
+ process.stdout.write("\x1B[?25l");
2124
+ envNames.forEach((_, i) => {
2125
+ console.log(renderItem(i));
2126
+ });
2127
+ console.log(renderFooterHints(footerHints));
2128
+ };
2129
+ const handleSelectionChange = (oldIndex, newIndex) => {
2130
+ if (oldIndex === newIndex) return;
2131
+ selectedIndex = newIndex;
2132
+ updateLine(oldIndex, renderItem(oldIndex));
2133
+ updateLine(newIndex, renderItem(newIndex));
2134
+ };
2135
+ initialRender();
2136
+ const cleanup = () => {
2137
+ stdin.setRawMode(wasRaw ?? false);
2138
+ stdin.removeListener("data", onKeypress);
2139
+ process.stdout.write("\x1B[?25h");
2140
+ };
2141
+ const onKeypress = (key) => {
2142
+ const char = key.toString();
2143
+ if (char === "") {
2144
+ cleanup();
2145
+ process.exit(0);
2146
+ }
2147
+ if (char === "\x1B" && key.length === 1) {
2148
+ cleanup();
2149
+ resolve5({ action: "cancel" });
2280
2150
  return;
2281
2151
  }
2282
- provenanceTracking = startCliClaudeProvenanceTracking({
2283
- ccemSessionId: ccemRuntimeId,
2284
- envName: envName ?? "unknown",
2285
- workingDir: effectiveWorkingDir,
2286
- permMode,
2287
- resumeSessionId
2288
- });
2289
- });
2290
- child.on("exit", (code) => {
2291
- provenanceTracking?.stop();
2292
- if (sessionId) {
2293
- try {
2294
- fs5.writeFileSync(
2295
- path5.join(sessionsDir, `${sessionId}.exit`),
2296
- String(code ?? 0)
2297
- );
2298
- } catch {
2299
- }
2152
+ if (char === "\x1B[A" || char === "k") {
2153
+ const oldIndex = selectedIndex;
2154
+ const newIndex = Math.max(0, selectedIndex - 1);
2155
+ handleSelectionChange(oldIndex, newIndex);
2156
+ return;
2300
2157
  }
2301
- process.exit(code ?? 0);
2302
- });
2303
- child.on("error", (err) => {
2304
- provenanceTracking?.stop();
2305
- if (err.code === "ENOENT") {
2306
- console.error("");
2307
- console.error(chalk2.red.bold("\u2718 \u672A\u627E\u5230 Claude Code"));
2308
- console.error("");
2309
- console.error(chalk2.white(" CCEM \u9700\u8981 Claude Code CLI \u624D\u80FD\u542F\u52A8\u4F1A\u8BDD\uFF0C\u4F46\u5728\u7CFB\u7EDF\u4E2D\u672A\u68C0\u6D4B\u5230 ") + chalk2.cyan("claude") + chalk2.white(" \u547D\u4EE4\u3002"));
2310
- console.error("");
2311
- console.error(chalk2.white(" \u8BF7\u5148\u5B89\u88C5 Claude Code:"));
2312
- console.error(chalk2.cyan(" npm install -g @anthropic-ai/claude-code"));
2313
- console.error("");
2314
- console.error(chalk2.gray(" \u5982\u679C\u5DF2\u5B89\u88C5\u4F46\u4ECD\u62A5\u9519\uFF0C\u8BF7\u68C0\u67E5:"));
2315
- console.error(chalk2.gray(" 1. \u8FD0\u884C claude --version \u786E\u8BA4\u5B89\u88C5\u6210\u529F"));
2316
- console.error(chalk2.gray(" 2. \u786E\u4FDD npm \u5168\u5C40\u76EE\u5F55\u5728\u7CFB\u7EDF PATH \u4E2D\uFF08npm config get prefix\uFF09"));
2317
- console.error(chalk2.gray(" 3. \u5B89\u88C5\u540E\u8BF7\u91CD\u542F\u7EC8\u7AEF"));
2318
- console.error("");
2319
- } else {
2320
- console.error(chalk2.red(`\u542F\u52A8 Claude Code \u5931\u8D25: ${err.message}`));
2158
+ if (char === "\x1B[B" || char === "j") {
2159
+ const oldIndex = selectedIndex;
2160
+ const newIndex = Math.min(envNames.length - 1, selectedIndex + 1);
2161
+ handleSelectionChange(oldIndex, newIndex);
2162
+ return;
2321
2163
  }
2322
- process.exit(1);
2323
- });
2164
+ if (char === "\r" || char === "\n") {
2165
+ cleanup();
2166
+ resolve5({ action: "select", name: envNames[selectedIndex] });
2167
+ return;
2168
+ }
2169
+ if (char === "e" || char === "E") {
2170
+ cleanup();
2171
+ resolve5({ action: "edit", name: envNames[selectedIndex] });
2172
+ return;
2173
+ }
2174
+ if (char === "r" || char === "R") {
2175
+ cleanup();
2176
+ resolve5({ action: "rename", name: envNames[selectedIndex] });
2177
+ return;
2178
+ }
2179
+ if (char === "c" || char === "C") {
2180
+ cleanup();
2181
+ resolve5({ action: "copy", name: envNames[selectedIndex] });
2182
+ return;
2183
+ }
2184
+ if (char === "d" || char === "D") {
2185
+ cleanup();
2186
+ resolve5({ action: "delete", name: envNames[selectedIndex] });
2187
+ return;
2188
+ }
2189
+ };
2190
+ stdin.on("data", onKeypress);
2324
2191
  });
2325
- }
2192
+ };
2326
2193
 
2327
2194
  // src/permissions.ts
2328
- var PERMISSION_RULE_LINE_WIDTH = 100;
2329
- var wrapPermissionRule = (rule) => {
2330
- return rule.split("\n").flatMap((line) => {
2331
- const characters = Array.from(line);
2332
- if (characters.length === 0) return [""];
2333
- const chunks = [];
2334
- for (let index = 0; index < characters.length; index += PERMISSION_RULE_LINE_WIDTH) {
2335
- chunks.push(characters.slice(index, index + PERMISSION_RULE_LINE_WIDTH).join(""));
2336
- }
2337
- return chunks;
2338
- });
2339
- };
2340
- var formatPermissionRulesForDisplay = (rules) => {
2341
- if (rules.length === 0) return " (\u65E0)";
2342
- const numberWidth = String(rules.length).length;
2343
- return rules.flatMap((rule, index) => {
2344
- const prefix = `${String(index + 1).padStart(numberWidth)}. `;
2345
- const continuationPrefix = " ".repeat(prefix.length);
2346
- return wrapPermissionRule(rule).map(
2347
- (line, lineIndex) => `${lineIndex === 0 ? prefix : continuationPrefix}${line}`
2348
- );
2349
- }).join("\n");
2350
- };
2351
- var readSettings = (settingsPath) => {
2352
- if (fs6.existsSync(settingsPath)) {
2353
- try {
2354
- const content = fs6.readFileSync(settingsPath, "utf-8");
2355
- return JSON.parse(content);
2356
- } catch {
2357
- console.warn(chalk3.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${settingsPath}\uFF0C\u5C06\u521B\u5EFA\u5907\u4EFD`));
2358
- const backupPath = settingsPath + ".error." + Date.now();
2359
- fs6.copyFileSync(settingsPath, backupPath);
2360
- console.log(chalk3.gray(`\u5907\u4EFD\u5DF2\u4FDD\u5B58\u5230: ${backupPath}`));
2361
- return {};
2362
- }
2363
- }
2364
- return {};
2365
- };
2366
- var writeSettings = (settingsPath, config3) => {
2367
- ensureClaudeDir();
2368
- fs6.writeFileSync(settingsPath, JSON.stringify(config3, null, 2) + "\n");
2369
- };
2370
- var mergePermissions = (existing, preset) => {
2371
- const existingAllow = normalizePermissionAllowRules(existing.permissions?.allow || []);
2372
- const existingDeny = existing.permissions?.deny || [];
2373
- const presetAllow = normalizePermissionAllowRules(preset.allow);
2374
- const mergedAllow = [.../* @__PURE__ */ new Set([...presetAllow, ...existingAllow])];
2375
- const mergedDeny = [.../* @__PURE__ */ new Set([...preset.deny, ...existingDeny])];
2376
- return {
2377
- ...existing,
2378
- permissions: {
2379
- allow: mergedAllow,
2380
- deny: mergedDeny
2195
+ import fs7 from "fs";
2196
+ import chalk3 from "chalk";
2197
+ import Table2 from "cli-table3";
2198
+
2199
+ // src/utils.ts
2200
+ import crypto3 from "crypto";
2201
+ import fs4 from "fs";
2202
+ import os3 from "os";
2203
+ import path4 from "path";
2204
+ var SECRET_KEY = crypto3.scryptSync("claude-code-env-manager-secret", "salt", 32);
2205
+ var findProjectRoot = () => {
2206
+ let currentDir = process.cwd();
2207
+ const root = path4.parse(currentDir).root;
2208
+ while (currentDir !== root) {
2209
+ if (fs4.existsSync(path4.join(currentDir, ".git")) || fs4.existsSync(path4.join(currentDir, "package.json"))) {
2210
+ return currentDir;
2381
2211
  }
2382
- };
2383
- };
2384
- var applyPermissionMode = (modeName) => {
2385
- const preset = PERMISSION_PRESETS[modeName];
2386
- if (!preset) {
2387
- console.error(chalk3.red(`\u672A\u77E5\u7684\u6743\u9650\u6A21\u5F0F: ${modeName}`));
2388
- console.log(chalk3.yellow("\u53EF\u7528\u6A21\u5F0F: " + getPermissionModeNames().join(", ")));
2389
- process.exit(1);
2212
+ currentDir = path4.dirname(currentDir);
2390
2213
  }
2391
- const settingsPath = getSettingsPath(true);
2392
- const existing = readSettings(settingsPath);
2393
- const merged = mergePermissions(existing, preset.permissions);
2394
- writeSettings(settingsPath, merged);
2395
- console.log(chalk3.green(`\u5DF2\u5E94\u7528 ${preset.name}`));
2396
- console.log(chalk3.gray(`\u914D\u7F6E\u5DF2\u5199\u5165: ${settingsPath}`));
2397
- console.log(chalk3.gray(`\u8BF4\u660E: ${preset.description}`));
2214
+ return process.cwd();
2398
2215
  };
2399
- var resetPermissions = () => {
2400
- const settingsPath = getSettingsPath(true);
2401
- if (!fs6.existsSync(settingsPath)) {
2402
- console.log(chalk3.yellow("\u6CA1\u6709\u81EA\u5B9A\u4E49\u6743\u9650\u914D\u7F6E\u9700\u8981\u91CD\u7F6E"));
2403
- return;
2404
- }
2405
- const config3 = readSettings(settingsPath);
2406
- delete config3.permissions;
2407
- if (Object.keys(config3).length === 0) {
2408
- fs6.unlinkSync(settingsPath);
2409
- console.log(chalk3.green("\u5DF2\u5220\u9664\u914D\u7F6E\u6587\u4EF6\uFF08\u6587\u4EF6\u4E3A\u7A7A\uFF09"));
2410
- } else {
2411
- writeSettings(settingsPath, config3);
2412
- console.log(chalk3.green("\u6743\u9650\u914D\u7F6E\u5DF2\u91CD\u7F6E"));
2413
- }
2414
- console.log(chalk3.gray(`\u6587\u4EF6: ${settingsPath}`));
2216
+ var getSettingsPath = (useLocal = true) => {
2217
+ const projectRoot = findProjectRoot();
2218
+ const claudeDir = path4.join(projectRoot, ".claude");
2219
+ const filename = useLocal ? "settings.local.json" : "settings.json";
2220
+ return path4.join(claudeDir, filename);
2415
2221
  };
2416
- var showCurrentMode = () => {
2417
- const settingsPath = getSettingsPath(true);
2418
- if (!fs6.existsSync(settingsPath)) {
2419
- console.log(chalk3.yellow("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49\u6743\u9650"));
2420
- console.log(chalk3.gray(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${settingsPath}`));
2421
- return;
2422
- }
2423
- const config3 = readSettings(settingsPath);
2424
- if (!config3.permissions) {
2425
- console.log(chalk3.yellow("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49\u6743\u9650"));
2426
- return;
2427
- }
2428
- const matchedPreset = Object.entries(PERMISSION_PRESETS).find(([_, preset]) => {
2429
- const configAllow = new Set(config3.permissions?.allow || []);
2430
- const configDeny = new Set(config3.permissions?.deny || []);
2431
- const presetAllow = new Set(preset.permissions.allow);
2432
- const presetDeny = new Set(preset.permissions.deny);
2433
- const allowMatch = preset.permissions.allow.every((p) => configAllow.has(p));
2434
- const denyMatch = preset.permissions.deny.every((p) => configDeny.has(p));
2435
- return allowMatch && denyMatch;
2436
- });
2437
- if (matchedPreset) {
2438
- console.log(chalk3.green(`\u5F53\u524D\u6A21\u5F0F: ${matchedPreset[0]} (${matchedPreset[1].name})`));
2439
- } else {
2440
- console.log(chalk3.yellow("\u5F53\u524D\u6A21\u5F0F: \u81EA\u5B9A\u4E49"));
2222
+ var ensureClaudeDir = () => {
2223
+ const projectRoot = findProjectRoot();
2224
+ const claudeDir = path4.join(projectRoot, ".claude");
2225
+ if (!fs4.existsSync(claudeDir)) {
2226
+ fs4.mkdirSync(claudeDir, { recursive: true });
2441
2227
  }
2442
- console.log(chalk3.gray(`\u914D\u7F6E\u6587\u4EF6: ${settingsPath}`));
2443
- const allowRules = config3.permissions.allow || [];
2444
- const denyRules = config3.permissions.deny || [];
2445
- console.log(chalk3.cyan(`
2446
- Allow (${allowRules.length})`));
2447
- console.log(formatPermissionRulesForDisplay(allowRules));
2448
- console.log(chalk3.cyan(`
2449
- Deny (${denyRules.length})`));
2450
- console.log(formatPermissionRulesForDisplay(denyRules));
2228
+ return claudeDir;
2451
2229
  };
2452
- var listAvailableModes = () => {
2453
- const table = new Table2({
2454
- head: ["\u6A21\u5F0F", "\u6807\u5FD7", "\u8BF4\u660E"],
2455
- style: { head: ["cyan"] },
2456
- colWidths: [15, 15, 50]
2457
- });
2458
- Object.entries(PERMISSION_PRESETS).forEach(([key, preset]) => {
2459
- table.push([preset.name, `--${key}`, preset.description]);
2460
- });
2461
- console.log(chalk3.bold("\u53EF\u7528\u6743\u9650\u6A21\u5F0F:\n"));
2462
- console.log(table.toString());
2463
- console.log(chalk3.gray("\n\u4E34\u65F6\u6A21\u5F0F: ccem <mode>"));
2464
- console.log(chalk3.gray("\u6C38\u4E45\u6A21\u5F0F: ccem setup perms --<mode>"));
2230
+ var getHomeDir2 = () => {
2231
+ return process.env.HOME || process.env.USERPROFILE || os3.homedir() || "";
2465
2232
  };
2466
- var runWithTempPermissions = async (modeName, envConfig, envName) => {
2467
- const preset = PERMISSION_PRESETS[modeName];
2468
- if (!preset) {
2469
- console.error(chalk3.red(`\u672A\u77E5\u7684\u6743\u9650\u6A21\u5F0F: ${modeName}`));
2470
- console.log(chalk3.yellow("\u53EF\u7528\u6A21\u5F0F: " + getPermissionModeNames().join(", ")));
2471
- process.exit(1);
2233
+ var getGlobalClaudeConfigPath = () => {
2234
+ return path4.join(getHomeDir2(), ".claude.json");
2235
+ };
2236
+ var getGlobalClaudeSettingsPath = () => {
2237
+ return path4.join(getHomeDir2(), ".claude", "settings.json");
2238
+ };
2239
+ var ensureGlobalClaudeDir = () => {
2240
+ const claudeDir = path4.join(getHomeDir2(), ".claude");
2241
+ if (!fs4.existsSync(claudeDir)) {
2242
+ fs4.mkdirSync(claudeDir, { recursive: true });
2472
2243
  }
2473
- await launchClaude({ envConfig, envName, permMode: modeName });
2244
+ return claudeDir;
2474
2245
  };
2475
2246
 
2476
- // src/environmentMutations.ts
2477
- import fs8 from "fs";
2478
- import path7 from "path";
2247
+ // src/launcher.ts
2248
+ import { spawn as spawn2 } from "child_process";
2249
+ import * as fs6 from "fs";
2250
+ import * as path6 from "path";
2251
+ import chalk2 from "chalk";
2479
2252
 
2480
- // src/desktopControl.ts
2481
- import fs7 from "fs";
2482
- import path6 from "path";
2483
- function validateDesktopTaskModel(provider, model) {
2484
- if (model === void 0 || model === null) return void 0;
2485
- if (provider !== "codex") {
2486
- throw new Error("MODEL_PROVIDER_UNSUPPORTED: task model selection is only available for Codex sessions.");
2253
+ // src/sessionProvenance.ts
2254
+ import { execFileSync } from "child_process";
2255
+ import fs5 from "fs";
2256
+ import { createRequire } from "module";
2257
+ import os4 from "os";
2258
+ import path5 from "path";
2259
+ var DEFAULT_CONFIG_SOURCE = "ccem";
2260
+ var STATE_DB_FILE_NAME = "state.sqlite";
2261
+ var BIND_POLL_INTERVAL_MS = 500;
2262
+ var BIND_POLL_TIMEOUT_MS = 2e4;
2263
+ var SQLITE_EXPERIMENTAL_WARNING = "SQLite is an experimental feature";
2264
+ var require2 = createRequire(import.meta.url);
2265
+ var databaseSyncCtor = null;
2266
+ var databaseSyncResolved = false;
2267
+ var sqlite3CliAvailable = null;
2268
+ function startCliClaudeProvenanceTracking(options) {
2269
+ const envName = normalizeText(options.envName) ?? "unknown";
2270
+ const workingDir = normalizeText(options.workingDir);
2271
+ if (!workingDir) {
2272
+ return null;
2487
2273
  }
2488
- if (typeof model !== "string" || model !== model.trim() || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/.test(model)) {
2489
- throw new Error("MODEL_INVALID: expected a model identifier (1-256 ASCII letters, digits, dots, underscores, colons, slashes or hyphens; starting with a letter or digit).");
2274
+ const ccemSessionId = normalizeText(options.ccemSessionId) ?? `cli-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
2275
+ try {
2276
+ registerLaunch({
2277
+ ccemSessionId,
2278
+ client: "claude",
2279
+ envName,
2280
+ configSource: DEFAULT_CONFIG_SOURCE,
2281
+ workingDir,
2282
+ permMode: normalizeText(options.permMode),
2283
+ launchMode: "cli_external",
2284
+ startedVia: "cli",
2285
+ sourceSessionId: normalizeText(options.resumeSessionId)
2286
+ });
2287
+ } catch (error) {
2288
+ reportTrackingError("register launch", error);
2289
+ return null;
2490
2290
  }
2491
- return model;
2492
- }
2493
- function requireTaskModelCapability(health) {
2494
- const capability = health?.capabilities?.taskModelSelection;
2495
- if (capability?.version !== 1 || !Array.isArray(capability.providers) || !capability.providers.includes("codex")) {
2496
- throw new Error("MODEL_SELECTION_UNSUPPORTED: this Desktop does not advertise Codex task model selection v1. No session was created.");
2291
+ let timer = null;
2292
+ const stop = () => {
2293
+ if (timer) {
2294
+ clearInterval(timer);
2295
+ timer = null;
2296
+ }
2297
+ };
2298
+ const resumeSessionId = normalizeText(options.resumeSessionId);
2299
+ if (resumeSessionId) {
2300
+ return { ccemSessionId, stop };
2497
2301
  }
2302
+ const startedAtMs = Date.now();
2303
+ timer = setInterval(() => {
2304
+ if (Date.now() - startedAtMs > BIND_POLL_TIMEOUT_MS) {
2305
+ stop();
2306
+ return;
2307
+ }
2308
+ try {
2309
+ const jsonlPath = discoverClaudeJsonlPath(workingDir, startedAtMs);
2310
+ if (!jsonlPath) {
2311
+ return;
2312
+ }
2313
+ const sourceSessionId = readClaudeSessionId(jsonlPath) ?? normalizeText(path5.parse(jsonlPath).name);
2314
+ if (!sourceSessionId) {
2315
+ return;
2316
+ }
2317
+ bindSourceSessionId("claude", ccemSessionId, sourceSessionId);
2318
+ stop();
2319
+ } catch (error) {
2320
+ reportTrackingError("bind source session id", error);
2321
+ stop();
2322
+ }
2323
+ }, BIND_POLL_INTERVAL_MS);
2324
+ return { ccemSessionId, stop };
2498
2325
  }
2499
- var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
2500
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
2501
- var ENDPOINT_UNREACHABLE_CODES = /* @__PURE__ */ new Set([
2502
- "ECONNREFUSED",
2503
- "ECONNRESET",
2504
- "ENOTCONN",
2505
- "EHOSTUNREACH",
2506
- "ECONNABORTED"
2507
- ]);
2508
- var ROUTER_BINDING_KEY = /^(?:background|subagent:\*|subagent:[A-Za-z0-9._:-]{1,128})$/;
2509
- var StaleDesktopControlDescriptorError = class extends Error {
2510
- name = "StaleDesktopControlDescriptorError";
2511
- reason;
2512
- descriptorPath;
2513
- pid;
2514
- cleanedUp;
2515
- cause;
2516
- constructor(details) {
2517
- const subject = details.pid !== null ? `process ${details.pid}` : "the publishing process";
2518
- const symptom = details.reason === "dead-pid" ? `${subject} is no longer running` : details.reason === "endpoint-unreachable" ? "the control endpoint refused the connection" : `the control request timed out after ${details.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS}ms`;
2519
- const remedy = details.cleanedUp ? "The stale descriptor was removed automatically; start CCEM Desktop and rerun the command." : details.pid !== null ? "Restart CCEM Desktop so it republishes a fresh control endpoint." : "Restart CCEM Desktop to refresh the descriptor, or remove the stale file manually if it is no longer managed.";
2520
- super(
2521
- `CCEM Desktop control descriptor at ${details.descriptorPath} is stale: ${symptom}. ${remedy}`
2522
- );
2523
- this.reason = details.reason;
2524
- this.descriptorPath = details.descriptorPath;
2525
- this.pid = details.pid;
2526
- this.cleanedUp = details.cleanedUp;
2527
- if (details.cause !== void 0) {
2528
- this.cause = details.cause;
2326
+ function registerLaunch(options) {
2327
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2328
+ const DatabaseSync = getDatabaseSyncCtor();
2329
+ if (DatabaseSync) {
2330
+ const db = openNodeSqliteDb(DatabaseSync);
2331
+ try {
2332
+ const statement = db.prepare(`
2333
+ INSERT INTO session_provenance (
2334
+ ccem_session_id,
2335
+ client,
2336
+ env_name,
2337
+ config_source,
2338
+ working_dir,
2339
+ perm_mode,
2340
+ launch_mode,
2341
+ started_via,
2342
+ source_session_id,
2343
+ created_at,
2344
+ updated_at
2345
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2346
+ ON CONFLICT(ccem_session_id) DO UPDATE SET
2347
+ client = excluded.client,
2348
+ env_name = excluded.env_name,
2349
+ config_source = COALESCE(excluded.config_source, session_provenance.config_source),
2350
+ working_dir = excluded.working_dir,
2351
+ perm_mode = COALESCE(excluded.perm_mode, session_provenance.perm_mode),
2352
+ launch_mode = excluded.launch_mode,
2353
+ started_via = excluded.started_via,
2354
+ source_session_id = COALESCE(excluded.source_session_id, session_provenance.source_session_id),
2355
+ updated_at = excluded.updated_at
2356
+ `);
2357
+ statement.run(
2358
+ options.ccemSessionId,
2359
+ options.client,
2360
+ options.envName,
2361
+ normalizeText(options.configSource),
2362
+ options.workingDir,
2363
+ normalizeText(options.permMode),
2364
+ options.launchMode,
2365
+ options.startedVia,
2366
+ normalizeText(options.sourceSessionId),
2367
+ now,
2368
+ now
2369
+ );
2370
+ return;
2371
+ } finally {
2372
+ db.close();
2529
2373
  }
2530
2374
  }
2531
- };
2532
- var DesktopControlRpcError = class extends Error {
2533
- code;
2534
- data;
2535
- constructor(message, code, data) {
2536
- super(message);
2537
- this.name = "DesktopControlRpcError";
2538
- this.code = code;
2539
- this.data = data;
2375
+ execSqlite3Cli(`
2376
+ INSERT INTO session_provenance (
2377
+ ccem_session_id,
2378
+ client,
2379
+ env_name,
2380
+ config_source,
2381
+ working_dir,
2382
+ perm_mode,
2383
+ launch_mode,
2384
+ started_via,
2385
+ source_session_id,
2386
+ created_at,
2387
+ updated_at
2388
+ ) VALUES (
2389
+ ${sqliteLiteral(options.ccemSessionId)},
2390
+ ${sqliteLiteral(options.client)},
2391
+ ${sqliteLiteral(options.envName)},
2392
+ ${sqliteLiteral(normalizeText(options.configSource))},
2393
+ ${sqliteLiteral(options.workingDir)},
2394
+ ${sqliteLiteral(normalizeText(options.permMode))},
2395
+ ${sqliteLiteral(options.launchMode)},
2396
+ ${sqliteLiteral(options.startedVia)},
2397
+ ${sqliteLiteral(normalizeText(options.sourceSessionId))},
2398
+ ${sqliteLiteral(now)},
2399
+ ${sqliteLiteral(now)}
2400
+ )
2401
+ ON CONFLICT(ccem_session_id) DO UPDATE SET
2402
+ client = excluded.client,
2403
+ env_name = excluded.env_name,
2404
+ config_source = COALESCE(excluded.config_source, session_provenance.config_source),
2405
+ working_dir = excluded.working_dir,
2406
+ perm_mode = COALESCE(excluded.perm_mode, session_provenance.perm_mode),
2407
+ launch_mode = excluded.launch_mode,
2408
+ started_via = excluded.started_via,
2409
+ source_session_id = COALESCE(excluded.source_session_id, session_provenance.source_session_id),
2410
+ updated_at = excluded.updated_at;
2411
+ `);
2412
+ }
2413
+ function bindSourceSessionId(client, ccemSessionId, sourceSessionId) {
2414
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2415
+ const DatabaseSync = getDatabaseSyncCtor();
2416
+ if (DatabaseSync) {
2417
+ const db = openNodeSqliteDb(DatabaseSync);
2418
+ try {
2419
+ const statement = db.prepare(`
2420
+ UPDATE session_provenance
2421
+ SET source_session_id = ?, updated_at = ?
2422
+ WHERE ccem_session_id = ? AND client = ?
2423
+ `);
2424
+ statement.run(sourceSessionId, updatedAt, ccemSessionId, client);
2425
+ return;
2426
+ } finally {
2427
+ db.close();
2428
+ }
2540
2429
  }
2541
- };
2542
- function getDesktopControlDescriptorPath() {
2543
- return process.env.CCEM_CONTROL_FILE?.trim() || getDefaultControlDescriptorPath();
2430
+ execSqlite3Cli(`
2431
+ UPDATE session_provenance
2432
+ SET source_session_id = ${sqliteLiteral(sourceSessionId)},
2433
+ updated_at = ${sqliteLiteral(updatedAt)}
2434
+ WHERE ccem_session_id = ${sqliteLiteral(ccemSessionId)}
2435
+ AND client = ${sqliteLiteral(client)};
2436
+ `);
2544
2437
  }
2545
- function getDefaultControlDescriptorPath() {
2546
- return path6.join(getCcemConfigDir(), "control.json");
2438
+ function openNodeSqliteDb(DatabaseSync) {
2439
+ const dbPath = getStateDbPath();
2440
+ fs5.mkdirSync(path5.dirname(dbPath), { recursive: true });
2441
+ const db = new DatabaseSync(dbPath);
2442
+ db.exec(schemaSql());
2443
+ return db;
2547
2444
  }
2548
- function isDefaultDescriptorPath(descriptorPath) {
2445
+ function getDatabaseSyncCtor() {
2446
+ if (databaseSyncResolved) {
2447
+ return databaseSyncCtor;
2448
+ }
2449
+ const originalEmitWarning = process.emitWarning;
2450
+ process.emitWarning = ((warning, ...args) => {
2451
+ const message = typeof warning === "string" ? warning : warning instanceof Error ? warning.message : String(warning);
2452
+ if (message.includes(SQLITE_EXPERIMENTAL_WARNING)) {
2453
+ return;
2454
+ }
2455
+ return originalEmitWarning(warning, ...args);
2456
+ });
2549
2457
  try {
2550
- return path6.resolve(descriptorPath) === path6.resolve(getDefaultControlDescriptorPath());
2458
+ const loaded = require2("node:sqlite");
2459
+ databaseSyncCtor = loaded.DatabaseSync;
2551
2460
  } catch {
2552
- return false;
2461
+ databaseSyncCtor = null;
2462
+ } finally {
2463
+ process.emitWarning = originalEmitWarning;
2464
+ databaseSyncResolved = true;
2553
2465
  }
2466
+ return databaseSyncCtor;
2554
2467
  }
2555
- function safeRemoveStaleDescriptor(descriptorPath) {
2556
- if (!isDefaultDescriptorPath(descriptorPath)) {
2557
- return false;
2468
+ function execSqlite3Cli(statementSql) {
2469
+ if (sqlite3CliAvailable == null) {
2470
+ try {
2471
+ execFileSync("sqlite3", ["-version"], { stdio: "ignore" });
2472
+ sqlite3CliAvailable = true;
2473
+ } catch {
2474
+ sqlite3CliAvailable = false;
2475
+ }
2558
2476
  }
2559
- try {
2560
- fs7.rmSync(descriptorPath);
2561
- return true;
2562
- } catch {
2563
- return false;
2477
+ if (!sqlite3CliAvailable) {
2478
+ throw new Error("sqlite3 CLI is unavailable and node:sqlite is not supported by this Node runtime");
2564
2479
  }
2480
+ const dbPath = getStateDbPath();
2481
+ fs5.mkdirSync(path5.dirname(dbPath), { recursive: true });
2482
+ execFileSync("sqlite3", [dbPath], {
2483
+ input: `${schemaSql()}
2484
+ ${statementSql}
2485
+ `,
2486
+ stdio: ["pipe", "ignore", "pipe"]
2487
+ });
2565
2488
  }
2566
- function readErrnoCode(error) {
2567
- if (!error || typeof error !== "object") return void 0;
2568
- const candidate = error;
2569
- return candidate.code ?? candidate.cause?.code;
2489
+ function getStateDbPath() {
2490
+ const override = normalizeText(process.env.CCEM_STATE_DB_PATH);
2491
+ if (override) {
2492
+ return override;
2493
+ }
2494
+ return path5.join(os4.homedir(), ".ccem", STATE_DB_FILE_NAME);
2570
2495
  }
2571
- function readPid(value) {
2572
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
2496
+ function schemaSql() {
2497
+ return `
2498
+ PRAGMA journal_mode = WAL;
2499
+ PRAGMA synchronous = NORMAL;
2500
+ CREATE TABLE IF NOT EXISTS session_provenance (
2501
+ ccem_session_id TEXT PRIMARY KEY,
2502
+ client TEXT NOT NULL,
2503
+ env_name TEXT NOT NULL,
2504
+ config_source TEXT,
2505
+ working_dir TEXT NOT NULL,
2506
+ perm_mode TEXT,
2507
+ launch_mode TEXT NOT NULL,
2508
+ started_via TEXT NOT NULL,
2509
+ source_session_id TEXT,
2510
+ created_at TEXT NOT NULL,
2511
+ updated_at TEXT NOT NULL
2512
+ );
2513
+ CREATE INDEX IF NOT EXISTS idx_session_provenance_client_source
2514
+ ON session_provenance (client, source_session_id);
2515
+ CREATE INDEX IF NOT EXISTS idx_session_provenance_client_updated
2516
+ ON session_provenance (client, updated_at DESC);
2517
+ `;
2573
2518
  }
2574
- function isLoopbackHost(host) {
2575
- const normalized = host.trim().toLowerCase().replace(/^\[|\]$/g, "");
2576
- if (LOOPBACK_HOSTS.has(normalized)) {
2577
- return true;
2519
+ function discoverClaudeJsonlPath(projectDir, startedAtMs) {
2520
+ const projectsDir = path5.join(os4.homedir(), ".claude", "projects");
2521
+ const earliestModifiedAt = startedAtMs - 15e3;
2522
+ for (const key of projectDirKeys(projectDir)) {
2523
+ const baseDir = path5.join(projectsDir, key);
2524
+ if (!fs5.existsSync(baseDir)) {
2525
+ continue;
2526
+ }
2527
+ const candidates = fs5.readdirSync(baseDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => {
2528
+ const fullPath = path5.join(baseDir, entry.name);
2529
+ return { path: fullPath, modifiedAt: fs5.statSync(fullPath).mtimeMs };
2530
+ }).filter((candidate) => candidate.modifiedAt >= earliestModifiedAt).sort((left, right) => right.modifiedAt - left.modifiedAt);
2531
+ if (candidates.length > 0) {
2532
+ return candidates[0].path;
2533
+ }
2578
2534
  }
2579
- if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized)) {
2580
- return true;
2535
+ return null;
2536
+ }
2537
+ function projectDirKeys(projectDir) {
2538
+ const candidates = [projectDir];
2539
+ try {
2540
+ candidates.push(fs5.realpathSync(projectDir));
2541
+ } catch {
2581
2542
  }
2582
- if (normalized === "::1" || normalized === "0:0:0:0:0:0:0:1") {
2583
- return true;
2543
+ if (process.platform === "darwin") {
2544
+ if (projectDir.startsWith("/private/")) {
2545
+ candidates.push(projectDir.slice("/private".length));
2546
+ } else if (projectDir.startsWith("/tmp")) {
2547
+ candidates.push(path5.posix.join("/private", projectDir));
2548
+ } else if (projectDir.startsWith("/var/")) {
2549
+ candidates.push(path5.posix.join("/private", projectDir));
2550
+ }
2584
2551
  }
2585
- return false;
2552
+ return [...new Set(candidates.map(projectDirKey))];
2586
2553
  }
2587
- function extractHost(endpoint) {
2588
- const withoutScheme = endpoint.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
2589
- const hostPort = withoutScheme.split(/[\/?#]/)[0] || "";
2590
- if (hostPort.startsWith("[")) {
2591
- const end = hostPort.indexOf("]");
2592
- if (end === -1) return null;
2593
- return hostPort.slice(1, end);
2554
+ function projectDirKey(projectDir) {
2555
+ return projectDir.replace(/[\/\\: ]/g, "-");
2556
+ }
2557
+ function readClaudeSessionId(jsonlPath) {
2558
+ const lines = fs5.readFileSync(jsonlPath, "utf8").split("\n");
2559
+ for (const line of lines) {
2560
+ if (!line.trim()) {
2561
+ continue;
2562
+ }
2563
+ try {
2564
+ const value = JSON.parse(line);
2565
+ const sessionId = normalizeText(value.sessionId);
2566
+ if (sessionId) {
2567
+ return sessionId;
2568
+ }
2569
+ } catch {
2570
+ }
2594
2571
  }
2595
- const colonIndex = hostPort.lastIndexOf(":");
2596
- if (colonIndex === -1) return hostPort;
2597
- return hostPort.slice(0, colonIndex);
2572
+ return null;
2598
2573
  }
2599
- function validateLoopbackEndpoint(endpoint) {
2600
- const host = extractHost(endpoint);
2601
- if (!host) {
2602
- throw new Error(
2603
- `CCEM Desktop control endpoint '${redactEndpoint(endpoint)}' is missing a host. Refusing to continue.`
2604
- );
2574
+ function normalizeText(value) {
2575
+ const trimmed = value?.trim();
2576
+ return trimmed ? trimmed : void 0;
2577
+ }
2578
+ function sqliteLiteral(value) {
2579
+ if (!value) {
2580
+ return "NULL";
2605
2581
  }
2606
- if (!isLoopbackHost(host)) {
2607
- throw new Error(
2608
- `CCEM Desktop control endpoint '${redactEndpoint(endpoint)}' is not bound to loopback. Only 127.0.0.1, localhost, or ::1 are allowed.`
2582
+ return `'${value.replace(/'/g, "''")}'`;
2583
+ }
2584
+ function reportTrackingError(stage, error) {
2585
+ const message = error instanceof Error ? error.message : String(error);
2586
+ console.error(`[ccem] Failed to ${stage}: ${message}`);
2587
+ }
2588
+
2589
+ // src/launcher.ts
2590
+ var MANAGED_CLAUDE_ENV_KEYS = [
2591
+ "ANTHROPIC_BASE_URL",
2592
+ "ANTHROPIC_AUTH_TOKEN",
2593
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
2594
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
2595
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
2596
+ "ANTHROPIC_MODEL",
2597
+ "CLAUDE_CODE_SUBAGENT_MODEL",
2598
+ "ANTHROPIC_API_KEY",
2599
+ "ANTHROPIC_SMALL_FAST_MODEL"
2600
+ ];
2601
+ function buildEnvVars(envName, envConfig, options = {}) {
2602
+ const runtimeEnv = resolveEnvConfigForRuntime(envName, envConfig);
2603
+ const authToken = runtimeEnv.ANTHROPIC_AUTH_TOKEN ? decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN) : void 0;
2604
+ if (!options.allowDesktopProxyOverride || !isTrustedDesktopProxyBaseUrl(runtimeEnv.ANTHROPIC_BASE_URL)) {
2605
+ assertClaudeEnvironmentAuthBoundary(
2606
+ envName,
2607
+ runtimeEnv.ANTHROPIC_BASE_URL,
2608
+ authToken
2609
2609
  );
2610
2610
  }
2611
+ const vars = {};
2612
+ if (runtimeEnv.ANTHROPIC_BASE_URL) vars.ANTHROPIC_BASE_URL = runtimeEnv.ANTHROPIC_BASE_URL;
2613
+ if (authToken) vars.ANTHROPIC_AUTH_TOKEN = authToken;
2614
+ if (runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL) vars.ANTHROPIC_DEFAULT_OPUS_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL;
2615
+ if (runtimeEnv.ANTHROPIC_DEFAULT_SONNET_MODEL) vars.ANTHROPIC_DEFAULT_SONNET_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_SONNET_MODEL;
2616
+ if (runtimeEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL) vars.ANTHROPIC_DEFAULT_HAIKU_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL;
2617
+ if (runtimeEnv.ANTHROPIC_MODEL) vars.ANTHROPIC_MODEL = runtimeEnv.ANTHROPIC_MODEL;
2618
+ if (runtimeEnv.CLAUDE_CODE_SUBAGENT_MODEL) vars.CLAUDE_CODE_SUBAGENT_MODEL = runtimeEnv.CLAUDE_CODE_SUBAGENT_MODEL;
2619
+ return vars;
2611
2620
  }
2612
- function isPidAlive(pid) {
2613
- if (!Number.isFinite(pid) || pid <= 0) return false;
2614
- try {
2615
- process.kill(pid, 0);
2616
- return true;
2617
- } catch (error) {
2618
- const code = error.code;
2619
- if (code === "ESRCH") return false;
2620
- if (code === "EPERM") return true;
2621
- return false;
2622
- }
2623
- }
2624
- function redactEndpoint(endpoint) {
2621
+ function isTrustedDesktopProxyBaseUrl(value) {
2622
+ if (!value) return false;
2625
2623
  try {
2626
- const url = new URL(endpoint);
2627
- return `${url.protocol}//${url.host}${url.pathname}`;
2624
+ const url = new URL(value);
2625
+ return url.protocol === "http:" && url.hostname === "127.0.0.1" && !url.username && !url.password && !url.search && !url.hash && url.pathname.startsWith("/proxy/claude/");
2628
2626
  } catch {
2629
- return "<invalid endpoint>";
2627
+ return false;
2630
2628
  }
2631
2629
  }
2632
- function isDescriptor(value) {
2633
- return Boolean(
2634
- value && typeof value === "object" && typeof value.endpoint === "string" && typeof value.token === "string"
2635
- );
2636
- }
2637
- function resolveDesktopControlDescriptor(descriptorPath = getDesktopControlDescriptorPath()) {
2638
- if (!fs7.existsSync(descriptorPath)) {
2639
- throw new Error(`CCEM Desktop control endpoint not found at ${descriptorPath}. Start CCEM Desktop first.`);
2630
+ function buildPermArgs(modeName) {
2631
+ const preset = PERMISSION_PRESETS[modeName];
2632
+ if (!preset) return [];
2633
+ const args = ["--permission-mode", preset.permissionMode];
2634
+ const allowRules = normalizePermissionAllowRules(preset.permissions.allow);
2635
+ if (allowRules.length > 0) {
2636
+ args.push("--allowedTools", ...allowRules);
2640
2637
  }
2641
- const parsed = JSON.parse(fs7.readFileSync(descriptorPath, "utf-8"));
2642
- const endpoint = parsed.endpoint?.trim();
2643
- const token = parsed.token?.trim();
2644
- if (!endpoint || !token) {
2645
- throw new Error(`Invalid CCEM Desktop control descriptor at ${descriptorPath}`);
2638
+ if (preset.permissions.deny.length > 0) {
2639
+ args.push("--disallowedTools", ...preset.permissions.deny);
2646
2640
  }
2647
- validateLoopbackEndpoint(endpoint);
2648
- const pid = readPid(parsed.pid);
2649
- if (pid !== null && !isPidAlive(pid)) {
2650
- const cleanedUp = safeRemoveStaleDescriptor(descriptorPath);
2651
- throw new StaleDesktopControlDescriptorError({
2652
- reason: "dead-pid",
2653
- descriptorPath,
2654
- pid,
2655
- cleanedUp
2656
- });
2641
+ return args;
2642
+ }
2643
+ function ensureSessionsDir() {
2644
+ const dir = path6.join(ensureCcemDir(), "sessions");
2645
+ if (!fs6.existsSync(dir)) {
2646
+ fs6.mkdirSync(dir, { recursive: true });
2657
2647
  }
2658
- return { endpoint, token, pid };
2648
+ return dir;
2659
2649
  }
2660
- async function requestDesktopControl(method, params, descriptorOrOptions, maybeOptions = {}) {
2661
- const descriptorPath = getDesktopControlDescriptorPath();
2662
- const hasInjectedDescriptor = isDescriptor(descriptorOrOptions);
2663
- const descriptor = hasInjectedDescriptor ? descriptorOrOptions : resolveDesktopControlDescriptor(descriptorPath);
2664
- const options = hasInjectedDescriptor ? maybeOptions : descriptorOrOptions ?? maybeOptions ?? {};
2665
- const timeoutMs = options.timeoutMs ?? options.fetchTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
2666
- const pid = readPid(descriptor.pid);
2667
- validateLoopbackEndpoint(descriptor.endpoint);
2668
- if (pid !== null && !isPidAlive(pid)) {
2669
- const cleanedUp = hasInjectedDescriptor ? false : safeRemoveStaleDescriptor(descriptorPath);
2670
- throw new StaleDesktopControlDescriptorError({
2671
- reason: "dead-pid",
2672
- descriptorPath,
2673
- pid,
2674
- cleanedUp
2675
- });
2650
+ async function launchClaude(options) {
2651
+ const {
2652
+ envName,
2653
+ envConfig,
2654
+ permMode,
2655
+ workingDir,
2656
+ sessionId,
2657
+ resumeSessionId,
2658
+ silent,
2659
+ allowDesktopProxyOverride
2660
+ } = options;
2661
+ const ccemRuntimeId = sessionId ?? `cli-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
2662
+ const env = { ...process.env };
2663
+ for (const key of MANAGED_CLAUDE_ENV_KEYS) {
2664
+ delete env[key];
2676
2665
  }
2677
- const id = `ccem-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
2678
- const controller = new AbortController();
2679
- const timer = setTimeout(() => controller.abort(), timeoutMs);
2680
- const externalSignal = options.signal;
2681
- const onExternalAbort = () => controller.abort();
2682
- if (externalSignal) {
2683
- if (externalSignal.aborted) {
2684
- clearTimeout(timer);
2685
- controller.abort();
2686
- } else {
2687
- externalSignal.addEventListener("abort", onExternalAbort, { once: true });
2688
- }
2666
+ if (envConfig) {
2667
+ Object.assign(env, buildEnvVars(envName, envConfig, { allowDesktopProxyOverride }));
2689
2668
  }
2690
- let response;
2691
- try {
2692
- response = await fetch(descriptor.endpoint, {
2693
- method: "POST",
2694
- headers: {
2695
- authorization: `Bearer ${descriptor.token}`,
2696
- "content-type": "application/json"
2697
- },
2698
- body: JSON.stringify({
2699
- jsonrpc: "2.0",
2700
- id,
2701
- method,
2702
- params: params ?? {}
2703
- }),
2704
- signal: controller.signal
2705
- });
2706
- } catch (error) {
2707
- if (controller.signal.aborted) {
2708
- throw new StaleDesktopControlDescriptorError({
2709
- reason: "request-timeout",
2710
- descriptorPath,
2711
- pid,
2712
- cleanedUp: false,
2713
- timeoutMs,
2714
- cause: error
2715
- });
2716
- }
2717
- const code = readErrnoCode(error);
2718
- if (code && ENDPOINT_UNREACHABLE_CODES.has(code)) {
2719
- throw new StaleDesktopControlDescriptorError({
2720
- reason: "endpoint-unreachable",
2721
- descriptorPath,
2722
- pid,
2723
- cleanedUp: false,
2724
- cause: error
2725
- });
2726
- }
2727
- throw error;
2728
- } finally {
2729
- clearTimeout(timer);
2730
- if (externalSignal) {
2731
- externalSignal.removeEventListener("abort", onExternalAbort);
2669
+ delete env.CLAUDECODE;
2670
+ env.CCEM_RUNTIME_ID = ccemRuntimeId;
2671
+ env.CCEM_SESSION_ID = ccemRuntimeId;
2672
+ const args = [];
2673
+ if (permMode) {
2674
+ const preset = PERMISSION_PRESETS[permMode];
2675
+ if (preset) {
2676
+ if (!silent) {
2677
+ console.log(chalk2.green(`\u5DF2\u5E94\u7528 ${preset.name}\uFF08\u4E34\u65F6\uFF09`));
2678
+ console.log(chalk2.gray(`\u8BF4\u660E: ${preset.description}`));
2679
+ console.log("");
2680
+ }
2681
+ args.push(...buildPermArgs(permMode));
2732
2682
  }
2733
2683
  }
2734
- if (!response.ok) {
2735
- throw new Error(`CCEM Desktop control request failed: HTTP ${response.status}`);
2736
- }
2737
- const payload = await response.json();
2738
- if (payload.error) {
2739
- throw new DesktopControlRpcError(
2740
- payload.error.message || `CCEM Desktop control error ${payload.error.code ?? ""}`.trim(),
2741
- payload.error.code,
2742
- payload.error.data
2743
- );
2684
+ if (resumeSessionId) {
2685
+ args.push("--resume", resumeSessionId);
2744
2686
  }
2745
- return payload.result;
2746
- }
2747
- function parseSinceOption(raw) {
2748
- if (raw === void 0 || raw === null || raw === "") return null;
2749
- const value = Number(raw);
2750
- if (!Number.isFinite(value) || value < 0 || !Number.isInteger(value)) {
2751
- throw new Error(
2752
- `Invalid --since value '${raw}'. Expected a non-negative integer sequence number (e.g. 0, 42).`
2753
- );
2687
+ if (workingDir) {
2688
+ process.chdir(workingDir);
2754
2689
  }
2755
- return value;
2756
- }
2757
- function parseLimitOption(raw) {
2758
- if (raw === void 0 || raw === null || raw === "") return null;
2759
- const value = Number(raw);
2760
- if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {
2761
- throw new Error(
2762
- `Invalid --limit value '${raw}'. Expected a positive integer (e.g. 1, 100).`
2763
- );
2690
+ const effectiveWorkingDir = process.cwd();
2691
+ if (!silent && !permMode) {
2692
+ console.log(renderStarting());
2764
2693
  }
2765
- return value;
2694
+ const sessionsDir = ensureSessionsDir();
2695
+ return new Promise((resolve5) => {
2696
+ let provenanceTracking = null;
2697
+ const child = spawn2("claude", args, {
2698
+ stdio: "inherit",
2699
+ shell: false,
2700
+ // 直接执行二进制,避免 shell 注入风险
2701
+ env
2702
+ });
2703
+ child.once("spawn", () => {
2704
+ if (sessionId) {
2705
+ return;
2706
+ }
2707
+ provenanceTracking = startCliClaudeProvenanceTracking({
2708
+ ccemSessionId: ccemRuntimeId,
2709
+ envName: envName ?? "unknown",
2710
+ workingDir: effectiveWorkingDir,
2711
+ permMode,
2712
+ resumeSessionId
2713
+ });
2714
+ });
2715
+ child.on("exit", (code) => {
2716
+ provenanceTracking?.stop();
2717
+ if (sessionId) {
2718
+ try {
2719
+ fs6.writeFileSync(
2720
+ path6.join(sessionsDir, `${sessionId}.exit`),
2721
+ String(code ?? 0)
2722
+ );
2723
+ } catch {
2724
+ }
2725
+ }
2726
+ process.exit(code ?? 0);
2727
+ });
2728
+ child.on("error", (err) => {
2729
+ provenanceTracking?.stop();
2730
+ if (err.code === "ENOENT") {
2731
+ console.error("");
2732
+ console.error(chalk2.red.bold("\u2718 \u672A\u627E\u5230 Claude Code"));
2733
+ console.error("");
2734
+ console.error(chalk2.white(" CCEM \u9700\u8981 Claude Code CLI \u624D\u80FD\u542F\u52A8\u4F1A\u8BDD\uFF0C\u4F46\u5728\u7CFB\u7EDF\u4E2D\u672A\u68C0\u6D4B\u5230 ") + chalk2.cyan("claude") + chalk2.white(" \u547D\u4EE4\u3002"));
2735
+ console.error("");
2736
+ console.error(chalk2.white(" \u8BF7\u5148\u5B89\u88C5 Claude Code:"));
2737
+ console.error(chalk2.cyan(" npm install -g @anthropic-ai/claude-code"));
2738
+ console.error("");
2739
+ console.error(chalk2.gray(" \u5982\u679C\u5DF2\u5B89\u88C5\u4F46\u4ECD\u62A5\u9519\uFF0C\u8BF7\u68C0\u67E5:"));
2740
+ console.error(chalk2.gray(" 1. \u8FD0\u884C claude --version \u786E\u8BA4\u5B89\u88C5\u6210\u529F"));
2741
+ console.error(chalk2.gray(" 2. \u786E\u4FDD npm \u5168\u5C40\u76EE\u5F55\u5728\u7CFB\u7EDF PATH \u4E2D\uFF08npm config get prefix\uFF09"));
2742
+ console.error(chalk2.gray(" 3. \u5B89\u88C5\u540E\u8BF7\u91CD\u542F\u7EC8\u7AEF"));
2743
+ console.error("");
2744
+ } else {
2745
+ console.error(chalk2.red(`\u542F\u52A8 Claude Code \u5931\u8D25: ${err.message}`));
2746
+ }
2747
+ process.exit(1);
2748
+ });
2749
+ });
2766
2750
  }
2767
- function parseRouteBinding(raw, optionName) {
2768
- const separator = raw.indexOf("=");
2769
- const key = separator > 0 ? raw.slice(0, separator).trim() : "";
2770
- const env = separator > 0 ? raw.slice(separator + 1).trim() : "";
2771
- if (!key || !env) {
2772
- throw new Error(`Invalid ${optionName} value '${raw}'. Expected key=env.`);
2773
- }
2774
- if (!ROUTER_BINDING_KEY.test(key)) {
2775
- throw new Error(
2776
- `Invalid route key '${key}' in ${optionName}. Expected background, subagent:*, or subagent:<safe-agent-name>.`
2751
+
2752
+ // src/permissions.ts
2753
+ var PERMISSION_RULE_LINE_WIDTH = 100;
2754
+ var wrapPermissionRule = (rule) => {
2755
+ return rule.split("\n").flatMap((line) => {
2756
+ const characters = Array.from(line);
2757
+ if (characters.length === 0) return [""];
2758
+ const chunks = [];
2759
+ for (let index = 0; index < characters.length; index += PERMISSION_RULE_LINE_WIDTH) {
2760
+ chunks.push(characters.slice(index, index + PERMISSION_RULE_LINE_WIDTH).join(""));
2761
+ }
2762
+ return chunks;
2763
+ });
2764
+ };
2765
+ var formatPermissionRulesForDisplay = (rules) => {
2766
+ if (rules.length === 0) return " (\u65E0)";
2767
+ const numberWidth = String(rules.length).length;
2768
+ return rules.flatMap((rule, index) => {
2769
+ const prefix = `${String(index + 1).padStart(numberWidth)}. `;
2770
+ const continuationPrefix = " ".repeat(prefix.length);
2771
+ return wrapPermissionRule(rule).map(
2772
+ (line, lineIndex) => `${lineIndex === 0 ? prefix : continuationPrefix}${line}`
2777
2773
  );
2778
- }
2779
- return { key, env };
2780
- }
2781
- function parseRoutesJson(raw) {
2782
- let parsed;
2783
- try {
2784
- parsed = JSON.parse(raw);
2785
- } catch {
2786
- throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
2787
- }
2788
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2789
- throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
2790
- }
2791
- const routes = {};
2792
- for (const [key, value] of Object.entries(parsed)) {
2793
- if (typeof value !== "string") {
2794
- throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
2774
+ }).join("\n");
2775
+ };
2776
+ var readSettings = (settingsPath) => {
2777
+ if (fs7.existsSync(settingsPath)) {
2778
+ try {
2779
+ const content = fs7.readFileSync(settingsPath, "utf-8");
2780
+ return JSON.parse(content);
2781
+ } catch {
2782
+ console.warn(chalk3.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${settingsPath}\uFF0C\u5C06\u521B\u5EFA\u5907\u4EFD`));
2783
+ const backupPath = settingsPath + ".error." + Date.now();
2784
+ fs7.copyFileSync(settingsPath, backupPath);
2785
+ console.log(chalk3.gray(`\u5907\u4EFD\u5DF2\u4FDD\u5B58\u5230: ${backupPath}`));
2786
+ return {};
2795
2787
  }
2796
- const binding = parseRouteBinding(`${key}=${value}`, "--route");
2797
- routes[binding.key] = binding.env;
2798
2788
  }
2799
- return routes;
2800
- }
2801
- function parseDesktopRoutes(routeValues = [], routesJson) {
2802
- if (routesJson === void 0 && routeValues.length === 0) {
2803
- return void 0;
2789
+ return {};
2790
+ };
2791
+ var writeSettings = (settingsPath, config3) => {
2792
+ ensureClaudeDir();
2793
+ fs7.writeFileSync(settingsPath, JSON.stringify(config3, null, 2) + "\n");
2794
+ };
2795
+ var mergePermissions = (existing, preset) => {
2796
+ const existingAllow = normalizePermissionAllowRules(existing.permissions?.allow || []);
2797
+ const existingDeny = existing.permissions?.deny || [];
2798
+ const presetAllow = normalizePermissionAllowRules(preset.allow);
2799
+ const mergedAllow = [.../* @__PURE__ */ new Set([...presetAllow, ...existingAllow])];
2800
+ const mergedDeny = [.../* @__PURE__ */ new Set([...preset.deny, ...existingDeny])];
2801
+ return {
2802
+ ...existing,
2803
+ permissions: {
2804
+ allow: mergedAllow,
2805
+ deny: mergedDeny
2806
+ }
2807
+ };
2808
+ };
2809
+ var applyPermissionMode = (modeName) => {
2810
+ const preset = PERMISSION_PRESETS[modeName];
2811
+ if (!preset) {
2812
+ console.error(chalk3.red(`\u672A\u77E5\u7684\u6743\u9650\u6A21\u5F0F: ${modeName}`));
2813
+ console.log(chalk3.yellow("\u53EF\u7528\u6A21\u5F0F: " + getPermissionModeNames().join(", ")));
2814
+ process.exit(1);
2804
2815
  }
2805
- const routes = routesJson === void 0 ? {} : parseRoutesJson(routesJson);
2806
- for (const raw of routeValues) {
2807
- const binding = parseRouteBinding(raw, "--route");
2808
- routes[binding.key] = binding.env;
2816
+ const settingsPath = getSettingsPath(true);
2817
+ const existing = readSettings(settingsPath);
2818
+ const merged = mergePermissions(existing, preset.permissions);
2819
+ writeSettings(settingsPath, merged);
2820
+ console.log(chalk3.green(`\u5DF2\u5E94\u7528 ${preset.name}`));
2821
+ console.log(chalk3.gray(`\u914D\u7F6E\u5DF2\u5199\u5165: ${settingsPath}`));
2822
+ console.log(chalk3.gray(`\u8BF4\u660E: ${preset.description}`));
2823
+ };
2824
+ var resetPermissions = () => {
2825
+ const settingsPath = getSettingsPath(true);
2826
+ if (!fs7.existsSync(settingsPath)) {
2827
+ console.log(chalk3.yellow("\u6CA1\u6709\u81EA\u5B9A\u4E49\u6743\u9650\u914D\u7F6E\u9700\u8981\u91CD\u7F6E"));
2828
+ return;
2809
2829
  }
2810
- return routes;
2811
- }
2812
- function isDesktopSessionRouterState(value) {
2813
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2814
- const state = value;
2815
- if (!Number.isSafeInteger(state.revision) || state.revision < 0) return false;
2816
- if (!state.bindings || typeof state.bindings !== "object" || Array.isArray(state.bindings)) return false;
2817
- if (!Object.entries(state.bindings).every(([key, env]) => key.trim() && typeof env === "string")) {
2818
- return false;
2830
+ const config3 = readSettings(settingsPath);
2831
+ delete config3.permissions;
2832
+ if (Object.keys(config3).length === 0) {
2833
+ fs7.unlinkSync(settingsPath);
2834
+ console.log(chalk3.green("\u5DF2\u5220\u9664\u914D\u7F6E\u6587\u4EF6\uFF08\u6587\u4EF6\u4E3A\u7A7A\uFF09"));
2835
+ } else {
2836
+ writeSettings(settingsPath, config3);
2837
+ console.log(chalk3.green("\u6743\u9650\u914D\u7F6E\u5DF2\u91CD\u7F6E"));
2819
2838
  }
2820
- return Array.isArray(state.allowedEnvs) && state.allowedEnvs.every((env) => typeof env === "string");
2821
- }
2822
- function buildDesktopRouterUpdateParams(runtimeId, current, setValue) {
2823
- if (!isDesktopSessionRouterState(current)) {
2824
- throw new Error("Invalid router state returned by CCEM Desktop.");
2839
+ console.log(chalk3.gray(`\u6587\u4EF6: ${settingsPath}`));
2840
+ };
2841
+ var showCurrentMode = () => {
2842
+ const settingsPath = getSettingsPath(true);
2843
+ if (!fs7.existsSync(settingsPath)) {
2844
+ console.log(chalk3.yellow("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49\u6743\u9650"));
2845
+ console.log(chalk3.gray(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${settingsPath}`));
2846
+ return;
2825
2847
  }
2826
- const binding = parseRouteBinding(setValue, "--set");
2827
- const bindings = { ...current.bindings, [binding.key]: binding.env };
2828
- const allowedEnvs = current.allowedEnvs.includes(binding.env) ? [...current.allowedEnvs] : [...current.allowedEnvs, binding.env];
2829
- return {
2830
- runtimeId,
2831
- expectedRevision: current.revision,
2832
- patch: { bindings, allowedEnvs }
2833
- };
2834
- }
2835
- async function getOrUpdateDesktopRoutes(runtimeId, setValue, requester = requestDesktopControl) {
2836
- const current = await requester("ccem.workspace.getRouter", { runtimeId });
2837
- if (setValue === void 0) {
2838
- return current;
2848
+ const config3 = readSettings(settingsPath);
2849
+ if (!config3.permissions) {
2850
+ console.log(chalk3.yellow("\u672A\u914D\u7F6E\u81EA\u5B9A\u4E49\u6743\u9650"));
2851
+ return;
2839
2852
  }
2840
- const update = buildDesktopRouterUpdateParams(runtimeId, current, setValue);
2841
- return requester("ccem.workspace.updateRouter", update);
2842
- }
2843
- function isNullableString(value) {
2844
- return value === null || typeof value === "string";
2845
- }
2846
- function isDesktopEnvironmentRenameResult(value) {
2847
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2848
- const result = value;
2849
- return result.ok === true && result.operation === "rename" && typeof result.oldName === "string" && typeof result.newName === "string" && Number.isSafeInteger(result.updatedSessions) && result.updatedSessions >= 0 && isNullableString(result.current);
2850
- }
2851
- function isDesktopEnvironmentDeleteResult(value) {
2852
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2853
- const result = value;
2854
- return result.ok === true && result.operation === "delete" && typeof result.name === "string" && isNullableString(result.current);
2855
- }
2856
- async function renameDesktopEnvironment(oldName, newName, requester = requestDesktopControl) {
2857
- const result = await requester("ccem.environment.rename", { oldName, newName });
2858
- if (!isDesktopEnvironmentRenameResult(result)) {
2859
- throw new Error("Invalid environment mutation response from CCEM Desktop.");
2853
+ const matchedPreset = Object.entries(PERMISSION_PRESETS).find(([_, preset]) => {
2854
+ const configAllow = new Set(config3.permissions?.allow || []);
2855
+ const configDeny = new Set(config3.permissions?.deny || []);
2856
+ const presetAllow = new Set(preset.permissions.allow);
2857
+ const presetDeny = new Set(preset.permissions.deny);
2858
+ const allowMatch = preset.permissions.allow.every((p) => configAllow.has(p));
2859
+ const denyMatch = preset.permissions.deny.every((p) => configDeny.has(p));
2860
+ return allowMatch && denyMatch;
2861
+ });
2862
+ if (matchedPreset) {
2863
+ console.log(chalk3.green(`\u5F53\u524D\u6A21\u5F0F: ${matchedPreset[0]} (${matchedPreset[1].name})`));
2864
+ } else {
2865
+ console.log(chalk3.yellow("\u5F53\u524D\u6A21\u5F0F: \u81EA\u5B9A\u4E49"));
2860
2866
  }
2861
- return result;
2862
- }
2863
- async function deleteDesktopEnvironment(name, requester = requestDesktopControl) {
2864
- const result = await requester("ccem.environment.delete", { name });
2865
- if (!isDesktopEnvironmentDeleteResult(result)) {
2866
- throw new Error("Invalid environment mutation response from CCEM Desktop.");
2867
+ console.log(chalk3.gray(`\u914D\u7F6E\u6587\u4EF6: ${settingsPath}`));
2868
+ const allowRules = config3.permissions.allow || [];
2869
+ const denyRules = config3.permissions.deny || [];
2870
+ console.log(chalk3.cyan(`
2871
+ Allow (${allowRules.length})`));
2872
+ console.log(formatPermissionRulesForDisplay(allowRules));
2873
+ console.log(chalk3.cyan(`
2874
+ Deny (${denyRules.length})`));
2875
+ console.log(formatPermissionRulesForDisplay(denyRules));
2876
+ };
2877
+ var listAvailableModes = () => {
2878
+ const table = new Table2({
2879
+ head: ["\u6A21\u5F0F", "\u6807\u5FD7", "\u8BF4\u660E"],
2880
+ style: { head: ["cyan"] },
2881
+ colWidths: [15, 15, 50]
2882
+ });
2883
+ Object.entries(PERMISSION_PRESETS).forEach(([key, preset]) => {
2884
+ table.push([preset.name, `--${key}`, preset.description]);
2885
+ });
2886
+ console.log(chalk3.bold("\u53EF\u7528\u6743\u9650\u6A21\u5F0F:\n"));
2887
+ console.log(table.toString());
2888
+ console.log(chalk3.gray("\n\u4E34\u65F6\u6A21\u5F0F: ccem <mode>"));
2889
+ console.log(chalk3.gray("\u6C38\u4E45\u6A21\u5F0F: ccem setup perms --<mode>"));
2890
+ };
2891
+ var runWithTempPermissions = async (modeName, envConfig, envName) => {
2892
+ const preset = PERMISSION_PRESETS[modeName];
2893
+ if (!preset) {
2894
+ console.error(chalk3.red(`\u672A\u77E5\u7684\u6743\u9650\u6A21\u5F0F: ${modeName}`));
2895
+ console.log(chalk3.yellow("\u53EF\u7528\u6A21\u5F0F: " + getPermissionModeNames().join(", ")));
2896
+ process.exit(1);
2867
2897
  }
2868
- return result;
2869
- }
2870
- function printJson(value) {
2871
- console.log(JSON.stringify(value, null, 2));
2872
- }
2898
+ await launchClaude({ envConfig, envName, permMode: modeName });
2899
+ };
2873
2900
 
2874
2901
  // src/environmentMutations.ts
2902
+ import fs8 from "fs";
2903
+ import path7 from "path";
2875
2904
  function nativeRuntimeStatePath() {
2876
2905
  return path7.join(getCcemConfigDir(), "native-runtime-state.json");
2877
2906
  }
@@ -2979,7 +3008,7 @@ function deleteEnvironmentFromConfig(config3, name) {
2979
3008
  // src/setup.ts
2980
3009
  import fs9 from "fs";
2981
3010
  import chalk4 from "chalk";
2982
- import { spawn as spawn2 } from "child_process";
3011
+ import { spawn as spawn3 } from "child_process";
2983
3012
  var readJsonFile = (filePath) => {
2984
3013
  if (fs9.existsSync(filePath)) {
2985
3014
  try {
@@ -3051,7 +3080,7 @@ var setupEnvSettings = () => {
3051
3080
  var setupMcpTool = () => {
3052
3081
  return new Promise((resolve5) => {
3053
3082
  console.log(chalk4.cyan(" \u2192 \u6B63\u5728\u6DFB\u52A0 chrome-devtools MCP \u5DE5\u5177..."));
3054
- const child = spawn2("claude", [
3083
+ const child = spawn3("claude", [
3055
3084
  "mcp",
3056
3085
  "add",
3057
3086
  "chrome-devtools",
@@ -3992,6 +4021,9 @@ If the request is specific enough, create the task directly. Ask a follow-up onl
3992
4021
  - Timeout: default to 300 seconds unless the task clearly needs longer.
3993
4022
  - Execution profile: use \`conservative\`, \`standard\`, or \`autonomous\` based on risk.
3994
4023
 
4024
+ - Hermes result delivery: when the user asks to send results to a bot, run \`ccem cron notification-targets --json\`. Select the paired recipient matching the user's request; ask when multiple recipients match. Never invent chat IDs or silently fall back to another channel on lookup failure.
4025
+ - Set \`hermesNotification: { routeId, generation }\` using that exact returned target. This grants only this task's completion notifications and does not require workspace access. Without an explicit notification request leave it null. Do not supply subscriptionId.
4026
+
3995
4027
  Common cron patterns:
3996
4028
 
3997
4029
  \`\`\`text
@@ -4066,6 +4098,29 @@ import crypto5 from "crypto";
4066
4098
  import * as fs11 from "fs";
4067
4099
  import * as os5 from "os";
4068
4100
  import * as path9 from "path";
4101
+ function parseHermesNotification(value) {
4102
+ if (value == null) return null;
4103
+ const target = value;
4104
+ if (typeof target.routeId !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(target.routeId) || !Number.isSafeInteger(target.generation) || Number(target.generation) <= 0) {
4105
+ throw new Error("hermesNotification requires a paired routeId and its current positive generation");
4106
+ }
4107
+ return { routeId: target.routeId, generation: target.generation };
4108
+ }
4109
+ async function getCronNotificationTargets(request = requestDesktopControl) {
4110
+ const result = await request("ccem.cron.notificationTargets");
4111
+ if (!Array.isArray(result)) throw new Error("Invalid notification targets response");
4112
+ return result;
4113
+ }
4114
+ async function createCronTaskWithNotifications(input, tasksPath = getCronTasksPath(), request = requestDesktopControl) {
4115
+ const target = parseHermesNotification(input.hermesNotification);
4116
+ if (target) {
4117
+ const targets = await getCronNotificationTargets(request);
4118
+ if (!targets.some((entry) => entry.routeId === target.routeId && entry.generation === target.generation)) {
4119
+ throw new Error("Hermes notification target is unavailable or has changed. Run ccem cron notification-targets --json and choose again.");
4120
+ }
4121
+ }
4122
+ return createCronTask({ ...input, hermesNotification: target }, tasksPath);
4123
+ }
4069
4124
  var CRON_TASKS_FILE_NAME = "cron-tasks.json";
4070
4125
  var EXECUTION_PROFILES = /* @__PURE__ */ new Set([
4071
4126
  "conservative",
@@ -4160,6 +4215,7 @@ function parseWecomNotification(value) {
4160
4215
  };
4161
4216
  }
4162
4217
  function createCronTask(input, tasksPath = getCronTasksPath()) {
4218
+ const hermesTarget = parseHermesNotification(input.hermesNotification);
4163
4219
  const name = input.name?.trim();
4164
4220
  if (!name) {
4165
4221
  throw new Error("Task name is required");
@@ -4197,6 +4253,7 @@ function createCronTask(input, tasksPath = getCronTasksPath()) {
4197
4253
  timeoutSecs,
4198
4254
  templateId: input.templateId?.trim() || null,
4199
4255
  wecomNotification: normalizeWecomNotification(input.wecomNotification),
4256
+ hermesNotification: hermesTarget ? { ...hermesTarget, subscriptionId: crypto5.randomUUID() } : null,
4200
4257
  triggerType: "schedule",
4201
4258
  parentTaskId: null,
4202
4259
  createdAt: now,
@@ -4249,7 +4306,8 @@ function parseCronCreateJson(raw) {
4249
4306
  enabled: typeof parsed.enabled === "boolean" ? parsed.enabled : null,
4250
4307
  timeoutSecs: typeof parsed.timeoutSecs === "number" ? parsed.timeoutSecs : null,
4251
4308
  templateId: typeof parsed.templateId === "string" ? parsed.templateId : null,
4252
- wecomNotification: parseWecomNotification(wecomNotification)
4309
+ wecomNotification: parseWecomNotification(wecomNotification),
4310
+ hermesNotification: parseHermesNotification(parsed.hermesNotification)
4253
4311
  };
4254
4312
  }
4255
4313
  function formatCronTaskTableRows(tasks) {
@@ -5574,7 +5632,7 @@ var findAttachSession = (id) => {
5574
5632
  var attachTmuxTarget = (target) => {
5575
5633
  const args = process.env.TMUX ? ["switch-client", "-t", target] : ["attach-session", "-t", target];
5576
5634
  return new Promise((resolve5, reject) => {
5577
- const child = spawn3("tmux", args, { stdio: "inherit" });
5635
+ const child = spawn4("tmux", args, { stdio: "inherit" });
5578
5636
  child.on("error", reject);
5579
5637
  child.on("exit", (code) => {
5580
5638
  if (code === 0 || code === null) {
@@ -5838,7 +5896,7 @@ program.command("run <command...>").description("Run a command with the current
5838
5896
  clearManagedClaudeEnv(env);
5839
5897
  Object.assign(env, buildResolvedEnvVars(current, envConfig));
5840
5898
  const [cmd, ...args] = command;
5841
- const child = spawn3(cmd, args, {
5899
+ const child = spawn4(cmd, args, {
5842
5900
  env,
5843
5901
  stdio: "inherit",
5844
5902
  shell: true
@@ -5869,7 +5927,22 @@ cronCmd.command("list").description("List CCEM cron tasks").option("--json", "Ou
5869
5927
  process.exitCode = 1;
5870
5928
  }
5871
5929
  });
5872
- cronCmd.command("create").description("Create a CCEM cron task").option("--from-json <json>", "Read task input from inline JSON, @file, or - for stdin").option("--name <name>", "Task name").option("--cron-expression <expr>", "5-field cron expression").option("--schedule <expr>", "Alias for --cron-expression").option("--prompt <prompt>", "Prompt to run when the task fires").option("--working-dir <dir>", "Task working directory").option("--env-name <name>", "CCEM environment name").option("--execution-profile <profile>", "conservative, standard, or autonomous").option("--max-budget-usd <amount>", "Optional max budget in USD").option("--allowed-tools <items>", "Comma-separated or JSON array of allowed tools").option("--disallowed-tools <items>", "Comma-separated or JSON array of disallowed tools").option("--timeout-secs <seconds>", "Task timeout in seconds").option("--template-id <id>", "Optional template id").option("--wecom-result", "Send cron result summary to the configured WeCom default target").option("--wecom-bot-id <id>", "WeCom bot id for cron result notifications").option("--wecom-peer-id <id>", "WeCom peer id for cron result notifications").option("--disabled", "Create task disabled").option("--json", "Output as JSON").action((options) => {
5930
+ cronCmd.command("notification-targets").description("List paired Hermes recipients for task result notifications (Desktop must be running)").option("--json", "Output as JSON").action(async (options) => {
5931
+ try {
5932
+ const targets = await getCronNotificationTargets();
5933
+ if (options.json) {
5934
+ console.log(JSON.stringify(targets, null, 2));
5935
+ return;
5936
+ }
5937
+ const table = new Table3({ head: ["Bot", "Platform", "Chat", "Route ID", "Generation"] });
5938
+ table.push(...targets.map((target) => [target.label, target.platform, target.chatId, target.routeId, String(target.generation)]));
5939
+ console.log(targets.length ? table.toString() : "No paired Hermes notification targets. Pair a bot in CCEM Remote Control first.");
5940
+ } catch (err) {
5941
+ console.error(chalk8.red(`\u2717 ${err instanceof Error ? err.message : String(err)}`));
5942
+ process.exitCode = 1;
5943
+ }
5944
+ });
5945
+ cronCmd.command("create").description("Create a CCEM cron task").option("--from-json <json>", "Read task input from inline JSON, @file, or - for stdin").option("--name <name>", "Task name").option("--cron-expression <expr>", "5-field cron expression").option("--schedule <expr>", "Alias for --cron-expression").option("--prompt <prompt>", "Prompt to run when the task fires").option("--working-dir <dir>", "Task working directory").option("--env-name <name>", "CCEM environment name").option("--execution-profile <profile>", "conservative, standard, or autonomous").option("--max-budget-usd <amount>", "Optional max budget in USD").option("--allowed-tools <items>", "Comma-separated or JSON array of allowed tools").option("--disallowed-tools <items>", "Comma-separated or JSON array of disallowed tools").option("--timeout-secs <seconds>", "Task timeout in seconds").option("--template-id <id>", "Optional template id").option("--wecom-result", "Send cron result summary to the configured WeCom default target").option("--wecom-bot-id <id>", "WeCom bot id for cron result notifications").option("--wecom-peer-id <id>", "WeCom peer id for cron result notifications").option("--disabled", "Create task disabled").option("--json", "Output as JSON").action(async (options) => {
5873
5946
  try {
5874
5947
  const input = options.fromJson ? parseCronCreateJson(options.fromJson) : {
5875
5948
  name: options.name,
@@ -5890,7 +5963,7 @@ cronCmd.command("create").description("Create a CCEM cron task").option("--from-
5890
5963
  enabled: true
5891
5964
  } : null
5892
5965
  };
5893
- const task = createCronTask(input);
5966
+ const task = await createCronTaskWithNotifications(input);
5894
5967
  if (options.json) {
5895
5968
  console.log(JSON.stringify(task, null, 2));
5896
5969
  return;
@@ -6481,4 +6554,5 @@ registerDshCommands(program, {
6481
6554
  getRegistries,
6482
6555
  getCurrentEnvName: () => config2.get("current") ?? ""
6483
6556
  });
6557
+ registerRemoteBridge(program);
6484
6558
  await program.parseAsync(process.argv).catch(handleCliError);