exportLogs.ts 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. /* eslint-disable max-lines -- 导出日志流程涉及文件收集、脱敏与打包,集中维护便于排查与一致性 */
  2. import { constants, createReadStream, createWriteStream } from "node:fs";
  3. import {
  4. access,
  5. copyFile,
  6. mkdir,
  7. mkdtemp,
  8. open,
  9. readdir,
  10. realpath,
  11. rm,
  12. stat,
  13. writeFile,
  14. } from "node:fs/promises";
  15. import { homedir } from "node:os";
  16. import { dirname, join, posix } from "node:path";
  17. import { Transform } from "node:stream";
  18. import { pipeline } from "node:stream/promises";
  19. import { ZipFile } from "yazl";
  20. import { CLI_MEMORY_DIAGNOSTIC_DIRECTORY, CLI_MEMORY_FILE_PATTERN } from "@zcode/shared";
  21. import {
  22. createFeedbackDiagnosticArchive,
  23. getAppConfigDir,
  24. getExportLogDir as getDefaultExportLogDir,
  25. getExportLogStageDir as getDefaultExportLogStageDir,
  26. getFeedbackLogArchiveDir as getDefaultFeedbackLogArchiveDir,
  27. } from "@zcode/services/node";
  28. import { createAboutSnapshot, formatAboutDetail, readBuildMetadata } from "./about.js";
  29. import { logger } from "./logger.js";
  30. function getZCodeDataDir() {
  31. return getAppConfigDir();
  32. }
  33. function getZCodeCliDir() {
  34. return join(homedir(), ".zcode", "cli");
  35. }
  36. function getZCodeCliLogDir() {
  37. return join(getZCodeCliDir(), "log");
  38. }
  39. /**
  40. * Computer Use Helper 的运行目录。macOS 上 Helper 由 LaunchServices 启动,stderr 被系统丢弃,
  41. * 所以它把生命周期与后台输入诊断 tee 到 `<socket>.exit.log`(见 zcode-cua
  42. * helperExitLogPathFor)。同目录下还有 `.tokens` broker 凭据,收集时必须按文件名白名单。
  43. */
  44. function getCuaHelperRunDir() {
  45. return join(homedir(), ".zcode", "computer-use", "run");
  46. }
  47. function isCuaHelperDiagnosticFileName(fileName: string): boolean {
  48. return fileName.endsWith(".exit.log");
  49. }
  50. interface LogArchiveFileEntry {
  51. absolutePath: string;
  52. archivePath: string;
  53. }
  54. interface LogArchiveArtifacts {
  55. files: LogArchiveFileEntry[];
  56. aboutContent: string;
  57. }
  58. interface CreateLogArchiveArtifactsOptions {
  59. now?: () => Date;
  60. lookbackDays?: number;
  61. }
  62. interface LogArchiveSkippedFileEntry {
  63. absolutePath: string;
  64. archivePath: string;
  65. error: string;
  66. }
  67. interface ExportLogsDependencies {
  68. now?: () => Date;
  69. getZCodeDataDir?: () => string;
  70. getExportLogStageDir?: () => string;
  71. getExportLogDir?: () => string;
  72. createLogArchiveArtifacts?: (
  73. sourceDir: string,
  74. options?: CreateLogArchiveArtifactsOptions,
  75. ) => Promise<LogArchiveArtifacts>;
  76. writeLogArchiveZip?: (
  77. outputPath: string,
  78. artifacts: LogArchiveArtifacts,
  79. options?: WriteLogArchiveZipOptions,
  80. ) => Promise<void>;
  81. writeLogArchiveDirectory?: (outputPath: string, artifacts: LogArchiveArtifacts) => Promise<void>;
  82. showItemInFolder?: (path: string) => Promise<void> | void;
  83. }
  84. interface WriteLogArchiveZipOptions {
  85. stageRootDir?: string;
  86. }
  87. interface CreateFeedbackLogArchiveFromExportLogsOptions {
  88. now?: () => Date;
  89. outputRootDir?: string;
  90. stageRootDir?: string;
  91. onProgress?: (event: { processedBytes: number; totalBytes: number }) => void;
  92. }
  93. function formatTimestamp(now: Date = new Date()): string {
  94. const pad = (n: number) => String(n).padStart(2, "0");
  95. return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
  96. }
  97. function normalizeArchivePath(path: string): string {
  98. return path.replaceAll("\\", "/");
  99. }
  100. function escapeRegExp(path: string): string {
  101. return path.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
  102. }
  103. function globPatternToRegExp(pattern: string): RegExp {
  104. const normalizedPattern = normalizeArchivePath(pattern);
  105. return new RegExp(`^${normalizedPattern.split("*").map(escapeRegExp).join(".*")}$`);
  106. }
  107. /**
  108. * Glob patterns to exclude from the exported log archive.
  109. * Each pattern is relative to the source directory being archived.
  110. */
  111. const ZIP_EXCLUDE_PATTERNS: string[] = [];
  112. const ZIP_EXCLUDE_REGEXES = ZIP_EXCLUDE_PATTERNS.map(globPatternToRegExp);
  113. const RETIRED_ACP_RUNTIME_ARCHIVE_PATHS = [
  114. "acp-auth",
  115. "acp-config",
  116. "acp-stream-diagnostics",
  117. "acp-traffic-proxy",
  118. ] as const;
  119. const HIGH_VOLUME_RUNTIME_ARCHIVE_PATHS = ["dev"] as const;
  120. const DOCSHOT_ARCHIVE_PATH_PREFIXES = ["docshot-backup-"] as const;
  121. const DOCSHOT_ARCHIVE_PATHS = ["docshot-assets"] as const;
  122. const NON_LOG_STATE_ARCHIVE_PATHS = [
  123. "agent-config",
  124. "certs",
  125. "repo-snapshots",
  126. "repo-wiki",
  127. "sessions",
  128. "session-bindings",
  129. "checkpoints",
  130. ] as const;
  131. const SENSITIVE_CREDENTIAL_ARCHIVE_FILE_NAMES = new Set(["credentials.json", ".credentials.json"]);
  132. const EXCLUDED_ARCHIVE_DIRECTORY_NAMES = new Set(["debug"]);
  133. const DEFAULT_LOG_EXPORT_LOOKBACK_DAYS = 3;
  134. const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
  135. const REDACTED_PLACEHOLDER = "***REDACTED***";
  136. // 敏感键名“族”:只要键名里包含这些子串就视为敏感(兜底通配),
  137. // 从而覆盖自定义命名(如 db_password、my_secret、x-conn-string 等)而不必逐个精确列举。
  138. // 注意:`token` / `auth` 等是宽松子串,配合下方白名单排除误伤项(如 input_tokens、author)。
  139. const SENSITIVE_KEY_SUBSTRING_PATTERN = [
  140. "password",
  141. "passwd",
  142. "pwd",
  143. "secret",
  144. "token",
  145. "credential",
  146. "api(?:_|-)?key",
  147. "access(?:_|-)?key",
  148. "private(?:_|-)?key",
  149. "auth",
  150. "cookie",
  151. "dsn",
  152. "conn(?:ection)?(?:_|-)?str(?:ing)?",
  153. "database(?:_|-)?url",
  154. "db(?:_|-)?url",
  155. ].join("|");
  156. const SENSITIVE_KEY_NAME_REGEX = new RegExp(`(?:${SENSITIVE_KEY_SUBSTRING_PATTERN})`, "i");
  157. // 白名单:命中敏感子串但实际并非密钥的常见键名,避免脱掉排障需要的上下文。
  158. // 不能把任意 "*_tokens" 都白名单化,否则 access_tokens/session_tokens 会被原样导出;
  159. // max_tokens/budget_tokens 是模型输出与思考预算,不是凭据,需保留用于判断 provider 请求是否撞限;
  160. // 因此这里只放行明确的 LLM token 计数/预算字段,以及 author/authority 这类含 "auth" 的普通词。
  161. // 敏感键下的数字也会被脱敏,计数键必须逐个列进来:前缀只由“计数用词”组成(不含 access/session/
  162. // refresh/id/read/write 单独出现),覆盖各家 provider 的用量字段(cache_read_input_tokens、
  163. // ephemeral_5m_input_tokens、*_tokens_details、max_completion_tokens、*TokenCount)和 ZCode 内部的
  164. // camelCase 计数(cacheReadTokens、maxOutputTokens)。buildSnapshot 是快照耗时,误中了 "dsn" 子串。
  165. // 下面的 "_" 是键名分隔符占位,组装完整个正则后统一换成“可选的 _ 或 -”(兼容 camelCase)。
  166. const TOKEN_COUNT_KEY_PREFIX_PATTERN = [
  167. "prompt",
  168. "completion",
  169. "total",
  170. "input",
  171. "output",
  172. "reasoning",
  173. "max",
  174. "budget",
  175. "audio",
  176. "candidates",
  177. "thoughts",
  178. "accepted_prediction",
  179. "rejected_prediction",
  180. "tool_use_prompt",
  181. "max_output",
  182. "max_completion",
  183. "prompt_cache_(?:hit|miss)",
  184. "(?:un)?cached(?:_(?:read|write|content))?(?:_input)?",
  185. "cache_(?:read|write|creation)(?:_input)?",
  186. "ephemeral_\\d+[mh]_input",
  187. ].join("|");
  188. const NON_SENSITIVE_KEY_NAME_ALLOWLIST_REGEX = new RegExp(
  189. [
  190. "^(?:public_key|keywords?|tokenizer|token_count|build_snapshot|author(?:s|ity|ed)?",
  191. `|(?:total_)?(?:${TOKEN_COUNT_KEY_PREFIX_PATTERN})_(?:tokens(?:_details)?|token_count))$`,
  192. ]
  193. .join("")
  194. .replaceAll("_", "(?:_|-)?"),
  195. "i",
  196. );
  197. function isSensitiveKeyName(keyName: string): boolean {
  198. if (NON_SENSITIVE_KEY_NAME_ALLOWLIST_REGEX.test(keyName)) {
  199. return false;
  200. }
  201. return SENSITIVE_KEY_NAME_REGEX.test(keyName);
  202. }
  203. // 以下正则先宽松捕获“键名 + 值”,再由 isSensitiveKeyName 决定是否脱敏,
  204. // 这样键名黑名单不再是硬编码列表,而是“敏感族 + 通配 + 白名单例外”。
  205. // 第三个分支只取对象/数组的开括号,由 redactJsonStyleValues 按括号配对整段替换(见该函数)。
  206. const JSON_STYLE_SENSITIVE_VALUE_REGEX =
  207. /(["'])([A-Za-z0-9_.-]+)\1(\s*:\s*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[[{]|[^,\r\n}\]]+)/g;
  208. const ASSIGNMENT_STYLE_SENSITIVE_VALUE_REGEX =
  209. /((?:^|\n)[ \t]*)([A-Za-z0-9_.-]+)([ \t]*=[ \t]*)([^\r\n#]+)/g;
  210. const HEADER_STYLE_SENSITIVE_VALUE_REGEX =
  211. /((?:^|\n)[ \t]*)([A-Za-z0-9-]+)([ \t]*:[ \t]*)([^\r\n]+)/g;
  212. // Bearer、URL query、连接串三条规则与 staging 一致:值里的引号和反斜杠一律当内容。
  213. // JSONL 行已按结构脱敏,这里只处理已解码的字符串和解析不了的文本行;为保护文本里内嵌的 JSON
  214. // 而在引号处停下,会让 `p"a"s`、`ex'ample` 这类口令整段或部分原样导出(审查两次复现)。
  215. // 代价是文本行里的内嵌 JSON 可能被多替换一段(例如吞到下一个字段的 @),只损失上下文,不泄露。
  216. const BEARER_TOKEN_REGEX = /(Bearer\s+)([^\s"']+)/g;
  217. const QUERY_TOKEN_REGEX =
  218. /([?&](?:key|api(?:_|-)?key|access(?:_|-)?token|refresh(?:_|-)?token|token|password|passwd|pwd|secret|client(?:_|-)?secret|auth(?:_|-)?token|session(?:_|-)?token)=)([^&#\s]+)/gi;
  219. // 按“值形态”脱敏:连接串 scheme://user:pass@host 里的凭据部分,
  220. // 不依赖键名即可覆盖 postgres/mysql/mongodb/redis/amqp 等数据库连接信息。保留 scheme 与 host 便于排障。
  221. // 用户名段允许为空以覆盖 redis://:password@host;口令段贪婪匹配到最后一个 @(host 段不含 @),
  222. // 这样口令里含裸 @(如 P@ssw0rd)也能整段脱敏,不残留片段。
  223. const CONNECTION_STRING_CREDENTIALS_REGEX =
  224. /\b([a-z][a-z0-9+.-]*:\/\/)([^:/\s]*):([^/\s]+)@(?=[^@/\s])/gi;
  225. // 结构化脱敏的递归深度上限。真实日志不到几十层;超限的行整行换成占位行,避免栈溢出中断导出。
  226. const MAX_JSON_REDACTION_DEPTH = 256;
  227. const JSON_DEPTH_EXCEEDED = Symbol("json-redaction-depth-exceeded");
  228. const JSON_DEPTH_EXCEEDED_LINE = JSON.stringify({
  229. exportRedaction: `line replaced: JSON nested deeper than ${MAX_JSON_REDACTION_DEPTH} levels`,
  230. });
  231. const TEXT_DETECTION_SAMPLE_BYTES = 64 * 1024;
  232. const EMPTY_BOM = Buffer.alloc(0);
  233. type SupportedTextEncoding = "utf-8" | "utf-16le" | "utf-16be";
  234. interface TextFileEncodingInfo {
  235. encoding: SupportedTextEncoding;
  236. bomLength: number;
  237. bomBytes: Buffer;
  238. }
  239. interface TextDecodingScore {
  240. preferredCharRatio: number;
  241. invalidCharRatio: number;
  242. }
  243. function redactValue(rawValue: string, quoteBareValue = false): string {
  244. const leadingSpaces = rawValue.match(/^\s*/)?.[0] ?? "";
  245. const trailingSpaces = rawValue.match(/\s*$/)?.[0] ?? "";
  246. const core = rawValue.trim();
  247. // JSON 键(双引号)下的裸值(数字、布尔、null)换成带引号的占位符,保证该行仍是合法 JSON。
  248. const quote =
  249. core.startsWith('"') && core.endsWith('"')
  250. ? '"'
  251. : core.startsWith("'") && core.endsWith("'")
  252. ? "'"
  253. : quoteBareValue
  254. ? '"'
  255. : "";
  256. const redacted = quote ? `${quote}${REDACTED_PLACEHOLDER}${quote}` : REDACTED_PLACEHOLDER;
  257. return `${leadingSpaces}${redacted}${trailingSpaces}`;
  258. }
  259. function redactHeaderValue(rawValue: string): string {
  260. const trimmed = rawValue.trim();
  261. if (/^bearer\s+/i.test(trimmed)) {
  262. return trimmed.replace(/^bearer\s+.+$/i, `Bearer ${REDACTED_PLACEHOLDER}`);
  263. }
  264. return REDACTED_PLACEHOLDER;
  265. }
  266. function redactConnectionStringCredentials(rawContent: string): string {
  267. // postgres://admin:secret@host → postgres://***REDACTED***:***REDACTED***@host
  268. return rawContent.replace(
  269. CONNECTION_STRING_CREDENTIALS_REGEX,
  270. (_match, scheme: string) => `${scheme}${REDACTED_PLACEHOLDER}:${REDACTED_PLACEHOLDER}@`,
  271. );
  272. }
  273. /** 从开括号位置起按字符串感知的括号配对找结束位置(结束括号之后);同一行内配不上返回 -1。 */
  274. function findBracketedValueEnd(content: string, start: number): number {
  275. let depth = 0;
  276. let stringQuote = "";
  277. for (let index = start; index < content.length; index += 1) {
  278. const char = content[index];
  279. if (char === "\n" || char === "\r") return -1;
  280. if (stringQuote) {
  281. if (char === "\\") index += 1;
  282. else if (char === stringQuote) stringQuote = "";
  283. continue;
  284. }
  285. if (char === '"' || char === "'") stringQuote = char;
  286. else if (char === "{" || char === "[") depth += 1;
  287. else if (char === "}" || char === "]") {
  288. depth -= 1;
  289. if (depth === 0) return index + 1;
  290. }
  291. }
  292. return -1;
  293. }
  294. /**
  295. * 文本里 `"key": value` 形式的敏感值。对象/数组值不能只看第一个字段:内层键名不敏感时
  296. * (`{"token":{"value":"…"}}`)凭据会原样导出,因此按括号配对整段换成带引号的占位符;
  297. * 同一行内配不上(截断的 JSON)就替换到行尾。只有开括号、后面没有内容的行是多行格式化 JSON
  298. * (config.json)的开头,保持原样,后续行仍逐行按键名脱敏,不破坏文件结构。
  299. */
  300. function redactJsonStyleValues(content: string): string {
  301. const pattern = JSON_STYLE_SENSITIVE_VALUE_REGEX;
  302. pattern.lastIndex = 0;
  303. let output = "";
  304. let cursor = 0;
  305. for (let match = pattern.exec(content); match; match = pattern.exec(content)) {
  306. // 四个捕获组在正则里都是必选的,默认值只为满足 noUncheckedIndexedAccess。
  307. const [whole, quote = '"', keyName = "", , rawValue = ""] = match;
  308. if (!isSensitiveKeyName(keyName)) continue;
  309. const valueStart = match.index + whole.length - rawValue.length;
  310. let valueEnd = valueStart + rawValue.length;
  311. let replacement: string;
  312. if (rawValue === "{" || rawValue === "[") {
  313. const bracketEnd = findBracketedValueEnd(content, valueStart);
  314. if (bracketEnd === -1) {
  315. const lineBreak = content.slice(valueStart).search(/[\r\n]/);
  316. const lineEnd = lineBreak === -1 ? content.length : valueStart + lineBreak;
  317. if (content.slice(valueStart + 1, lineEnd).trim() === "") continue;
  318. valueEnd = lineEnd;
  319. } else {
  320. valueEnd = bracketEnd;
  321. }
  322. replacement = `${quote}${REDACTED_PLACEHOLDER}${quote}`;
  323. } else {
  324. replacement = redactValue(rawValue, quote === '"');
  325. }
  326. output += content.slice(cursor, valueStart) + replacement;
  327. cursor = valueEnd;
  328. pattern.lastIndex = valueEnd;
  329. }
  330. pattern.lastIndex = 0;
  331. return output + content.slice(cursor);
  332. }
  333. function sanitizeSensitiveLogContent(rawContent: string): string {
  334. // 导出日志不能按文件原样拷贝:会把用户配置和协议日志里的 token/apiKey 一并带出。
  335. // 线上排障需要“保留文件结构和上下文”,但不应该泄露密钥本体;
  336. // 这里在导出阶段统一对常见敏感值做脱敏,字段和日志行仍完整保留,支持继续定位问题。
  337. // 键名不再是硬编码黑名单,而是“敏感键名族 + 子串通配 + 白名单例外”(isSensitiveKeyName),
  338. // 并叠加按值形态的连接串脱敏,以覆盖数据库连接串等自定义命名的敏感信息。
  339. return redactJsonStyleValues(redactConnectionStringCredentials(rawContent))
  340. .replace(
  341. ASSIGNMENT_STYLE_SENSITIVE_VALUE_REGEX,
  342. (match, prefix: string, keyName: string, separator: string, rawValue: string) =>
  343. isSensitiveKeyName(keyName)
  344. ? `${prefix}${keyName}${separator}${redactValue(rawValue)}`
  345. : match,
  346. )
  347. .replace(
  348. HEADER_STYLE_SENSITIVE_VALUE_REGEX,
  349. (match, prefix: string, headerName: string, separator: string, rawValue: string) =>
  350. isSensitiveKeyName(headerName)
  351. ? `${prefix}${headerName}${separator}${redactHeaderValue(rawValue)}`
  352. : match,
  353. )
  354. .replace(BEARER_TOKEN_REGEX, `$1${REDACTED_PLACEHOLDER}`)
  355. .replace(QUERY_TOKEN_REGEX, `$1${REDACTED_PLACEHOLDER}`);
  356. }
  357. interface JsonRedactionState {
  358. changed: boolean;
  359. }
  360. type JsonRedactionResult =
  361. | { kind: "invalid" }
  362. | { kind: "unchanged" }
  363. | { kind: "changed"; text: string };
  364. // TS 6 的 lib 还没有 JSON.rawJSON / JSON.isRawJSON 的声明;Electron 44(V8 15)已支持。
  365. const RAW_JSON = JSON as unknown as {
  366. rawJSON?: (text: string) => unknown;
  367. isRawJSON?: (value: unknown) => boolean;
  368. };
  369. function isRawJsonNumber(value: unknown): boolean {
  370. return RAW_JSON.isRawJSON?.(value) === true;
  371. }
  372. /**
  373. * 重写一行时数字按原始字面量写回:超过 2^53 的整数(请求 id、纳秒时间戳)和 `1.50` 这类写法
  374. * 经 Number 往返会被改写。只包装往返后会变的数字,其余仍是普通 number。
  375. */
  376. function parseJsonPreservingNumbers(text: string): unknown {
  377. const rawJSON = RAW_JSON.rawJSON;
  378. if (!rawJSON) return JSON.parse(text) as unknown;
  379. return JSON.parse(text, (_key, value: unknown, context?: { source?: string }) =>
  380. typeof value === "number" && context?.source !== undefined && String(value) !== context.source
  381. ? rawJSON(context.source)
  382. : value,
  383. ) as unknown;
  384. }
  385. /**
  386. * 解析并脱敏一段 JSON 文本。先用普通 JSON.parse 判断是否需要改;只有需要改时才按原始数字字面量
  387. * 重新解析再写回,未命中的行不承担 reviver 的开销,也不会被重新序列化。
  388. */
  389. function redactJsonText(text: string, depth: number): JsonRedactionResult {
  390. const parsed = parseJsonLine(text);
  391. if (parsed === undefined) return { kind: "invalid" };
  392. const probe: JsonRedactionState = { changed: false };
  393. redactJsonValue(parsed.value, false, probe, depth);
  394. if (!probe.changed) return { kind: "unchanged" };
  395. const state: JsonRedactionState = { changed: false };
  396. const redacted = redactJsonValue(parseJsonPreservingNumbers(text), false, state, depth);
  397. return { kind: "changed", text: JSON.stringify(redacted) };
  398. }
  399. function redactJsonStringValue(value: string, state: JsonRedactionState, depth: number): string {
  400. const trimmed = value.trim();
  401. if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
  402. // 字符串里嵌着的 JSON(请求体、工具参数)按结构递归,否则内层的 api_key 会被当成普通文本漏掉。
  403. // 嵌套 JSON 与外层共用深度预算,字符串里一层套一层也不能绕过上限。
  404. const nested = redactJsonText(trimmed, depth + 1);
  405. if (nested.kind === "unchanged") return value;
  406. if (nested.kind === "changed") {
  407. state.changed = true;
  408. return nested.text;
  409. }
  410. }
  411. const sanitized = sanitizeSensitiveLogContent(value);
  412. if (sanitized !== value) state.changed = true;
  413. return sanitized;
  414. }
  415. /**
  416. * 对象键也可能是凭据:连接串、带 token 的 URL、`Bearer …` 被当作键时,按值形态脱敏后再写回。
  417. * 两个键脱敏后可能相同,加序号避免后写的覆盖先写的。
  418. *
  419. * `nextSuffix` 按对象记录每个脱敏结果下次从哪个序号试起:敏感父字段下的键全部脱敏成同一个占位符,
  420. * 每个键都从 ` (2)` 重新试会是 O(n²),一行几千个键就会长时间阻塞主进程。试过的候选都已被占用,
  421. * 占用只增不减(结果对象只增加键、原对象不变),所以接着上次往后试,结果与逐个从头试完全相同。
  422. */
  423. function redactJsonObjectKey(
  424. key: string,
  425. source: object,
  426. result: Record<string, unknown>,
  427. nextSuffix: Map<string, number>,
  428. state: JsonRedactionState,
  429. sensitive: boolean,
  430. ): string {
  431. let sanitized: string;
  432. if (sensitive) {
  433. // 敏感父字段下的键本身就可能是凭据(`{"token":{"tok_…":{…}}}` 这类以 token 为键的映射),
  434. // 不能指望它带有连接串、URL、Bearer 等可识别的形态:和值一样整体换成占位符,重名加序号。
  435. sanitized = REDACTED_PLACEHOLDER;
  436. } else {
  437. // 绝大多数键是标识符:文本规则都要求 `://`、`=`、`:`、空格、`?`、`&` 或引号之一,纯标识符
  438. // 不可能命中,跳过以免每个键都跑一遍全部正则(本机 10 万行日志里这一步占了新增耗时的大头)。
  439. if (!/[^\w.$-]/.test(key)) return key;
  440. sanitized = sanitizeSensitiveLogContent(key);
  441. if (sanitized === key) return key;
  442. }
  443. state.changed = true;
  444. // 序号 1 表示不加后缀的原样结果。
  445. let index = nextSuffix.get(sanitized) ?? 1;
  446. let candidate = index === 1 ? sanitized : `${sanitized} (${index})`;
  447. while (Object.hasOwn(result, candidate) || Object.hasOwn(source, candidate)) {
  448. index += 1;
  449. candidate = `${sanitized} (${index})`;
  450. }
  451. nextSuffix.set(sanitized, index + 1);
  452. return candidate;
  453. }
  454. function redactJsonValue(
  455. value: unknown,
  456. sensitive: boolean,
  457. state: JsonRedactionState,
  458. depth = 0,
  459. ): unknown {
  460. if (depth > MAX_JSON_REDACTION_DEPTH) throw JSON_DEPTH_EXCEEDED;
  461. if (typeof value === "string") {
  462. if (sensitive) {
  463. state.changed = true;
  464. return REDACTED_PLACEHOLDER;
  465. }
  466. return redactJsonStringValue(value, state, depth);
  467. }
  468. const isNumber = typeof value === "number" || isRawJsonNumber(value);
  469. if (isNumber && sensitive) {
  470. // 数字可能就是凭据本身(纯数字密码、PIN):敏感键下换成字符串占位符,该行仍是合法 JSON。
  471. // 非敏感键下的数字(token 计数、耗时)原样保留;计数键靠上面的白名单免于误伤。
  472. state.changed = true;
  473. return REDACTED_PLACEHOLDER;
  474. }
  475. if (isNumber) return value;
  476. if (Array.isArray(value)) {
  477. return value.map((item) => redactJsonValue(item, sensitive, state, depth + 1));
  478. }
  479. if (value !== null && typeof value === "object") {
  480. // 用无原型对象重建:普通 {} 上写 `__proto__` 会触发原型 setter,这个键会从导出里消失。
  481. const result = Object.create(null) as Record<string, unknown>;
  482. const nextSuffix = new Map<string, number>();
  483. for (const [key, item] of Object.entries(value)) {
  484. // 键名是否敏感按原键判断;父字段已敏感时,键自己也按敏感处理。
  485. const outputKey = redactJsonObjectKey(key, value, result, nextSuffix, state, sensitive);
  486. result[outputKey] = redactJsonValue(
  487. item,
  488. sensitive || isSensitiveKeyName(key),
  489. state,
  490. depth + 1,
  491. );
  492. }
  493. return result;
  494. }
  495. // 布尔和 null 只有 true/false/null 三个取值,承载不了凭据,即使在敏感键下(auth 开关、
  496. // token: null 表示未配置)也原样保留,排障时能看出“有没有配置”。
  497. return value;
  498. }
  499. function parseJsonLine(line: string): { value: unknown } | undefined {
  500. try {
  501. return { value: JSON.parse(line) as unknown };
  502. } catch {
  503. return undefined;
  504. }
  505. }
  506. /**
  507. * 整行是 JSON(model-io / CLI 日志的 JSONL)时按结构脱敏再序列化,导出后每行仍能 JSON.parse。
  508. * 根因:文本正则直接改 JSON 文本,会留下未加引号的占位符、吞掉 `\"` 的反斜杠、把对象值切掉半截。
  509. * 未命中敏感内容的行原样输出;命中的行重写时数字保留原始字面量。
  510. * 顶层是 JSON 字符串的行(`"{\"password\":…}"`)也按结构处理,否则转义后的内层凭据只经过文本规则。
  511. */
  512. function sanitizeSensitiveJsonLine(line: string): string | undefined {
  513. const trimmed = line.trim();
  514. if (!/^[[{"]/.test(trimmed)) return undefined;
  515. let result: JsonRedactionResult;
  516. try {
  517. result = redactJsonText(trimmed, 0);
  518. } catch (error) {
  519. // 超深的行无法安全逐层判断,整行换成说明占位(仍是合法 JSON),导出继续,原文不进归档。
  520. if (error === JSON_DEPTH_EXCEEDED) return JSON_DEPTH_EXCEEDED_LINE;
  521. throw error;
  522. }
  523. if (result.kind === "invalid") return undefined;
  524. if (result.kind === "unchanged") return line;
  525. const leading = line.match(/^\s*/)?.[0] ?? "";
  526. const trailing = line.match(/\s*$/)?.[0] ?? "";
  527. return `${leading}${result.text}${trailing}`;
  528. }
  529. function sanitizeSensitiveLogChunk(chunk: string): string {
  530. return chunk.replace(
  531. /[^\r\n]+/g,
  532. (line) => sanitizeSensitiveJsonLine(line) ?? sanitizeSensitiveLogContent(line),
  533. );
  534. }
  535. function detectUtf16EncodingByNullPattern(sample: Buffer): SupportedTextEncoding | null {
  536. if (sample.length < 4) {
  537. return null;
  538. }
  539. let evenByteCount = 0;
  540. let oddByteCount = 0;
  541. let evenNullCount = 0;
  542. let oddNullCount = 0;
  543. for (let index = 0; index < sample.length; index += 1) {
  544. if (index % 2 === 0) {
  545. evenByteCount += 1;
  546. if (sample[index] === 0) {
  547. evenNullCount += 1;
  548. }
  549. continue;
  550. }
  551. oddByteCount += 1;
  552. if (sample[index] === 0) {
  553. oddNullCount += 1;
  554. }
  555. }
  556. const evenNullRatio = evenNullCount / Math.max(evenByteCount, 1);
  557. const oddNullRatio = oddNullCount / Math.max(oddByteCount, 1);
  558. const likelyUtf16Ratio = 0.3;
  559. const noiseThreshold = 0.1;
  560. if (oddNullRatio >= likelyUtf16Ratio && evenNullRatio <= noiseThreshold) {
  561. return "utf-16le";
  562. }
  563. if (evenNullRatio >= likelyUtf16Ratio && oddNullRatio <= noiseThreshold) {
  564. return "utf-16be";
  565. }
  566. return null;
  567. }
  568. function isLikelyAsciiTextByte(byteValue: number): boolean {
  569. return (
  570. byteValue === 0x09 ||
  571. byteValue === 0x0a ||
  572. byteValue === 0x0d ||
  573. (byteValue >= 0x20 && byteValue <= 0x7e)
  574. );
  575. }
  576. function isPreferredTextCodePoint(codePoint: number): boolean {
  577. if (codePoint === 0x09 || codePoint === 0x0a || codePoint === 0x0d || codePoint === 0x20) {
  578. return true;
  579. }
  580. if (codePoint >= 0x20 && codePoint <= 0x7e) {
  581. return true;
  582. }
  583. if (codePoint >= 0x4e00 && codePoint <= 0x9fff) {
  584. return true;
  585. }
  586. if (codePoint >= 0x3400 && codePoint <= 0x4dbf) {
  587. return true;
  588. }
  589. if (codePoint >= 0x3000 && codePoint <= 0x303f) {
  590. return true;
  591. }
  592. if (codePoint >= 0xff00 && codePoint <= 0xffef) {
  593. return true;
  594. }
  595. if (codePoint >= 0x3040 && codePoint <= 0x30ff) {
  596. return true;
  597. }
  598. if (codePoint >= 0xac00 && codePoint <= 0xd7af) {
  599. return true;
  600. }
  601. return false;
  602. }
  603. function scoreDecodedTextForEncodingDetection(decodedText: string): TextDecodingScore {
  604. let totalCodePointCount = 0;
  605. let preferredCodePointCount = 0;
  606. let invalidCodePointCount = 0;
  607. for (const character of decodedText) {
  608. totalCodePointCount += 1;
  609. const codePoint = character.codePointAt(0) ?? 0;
  610. if (
  611. codePoint === 0xfffd ||
  612. codePoint === 0 ||
  613. codePoint === 0x7f ||
  614. (codePoint >= 0xd800 && codePoint <= 0xdfff) ||
  615. (codePoint <= 0x1f && codePoint !== 0x09 && codePoint !== 0x0a && codePoint !== 0x0d)
  616. ) {
  617. invalidCodePointCount += 1;
  618. continue;
  619. }
  620. if (isPreferredTextCodePoint(codePoint)) {
  621. preferredCodePointCount += 1;
  622. }
  623. }
  624. const denominator = Math.max(totalCodePointCount, 1);
  625. return {
  626. preferredCharRatio: preferredCodePointCount / denominator,
  627. invalidCharRatio: invalidCodePointCount / denominator,
  628. };
  629. }
  630. function detectUtf16EncodingByDecodedTextScore(sample: Buffer): SupportedTextEncoding | null {
  631. if (sample.length < 4) {
  632. return null;
  633. }
  634. const normalizedSampleLength = sample.length - (sample.length % 2);
  635. if (normalizedSampleLength < 4) {
  636. return null;
  637. }
  638. const normalizedSample = sample.subarray(0, normalizedSampleLength);
  639. const utf16LeScore = scoreDecodedTextForEncodingDetection(
  640. new TextDecoder("utf-16le").decode(normalizedSample),
  641. );
  642. const utf16BeScore = scoreDecodedTextForEncodingDetection(
  643. new TextDecoder("utf-16be").decode(normalizedSample),
  644. );
  645. const minimumPreferredCharRatio = 0.55;
  646. const maximumInvalidCharRatio = 0.2;
  647. const minimumPreferredCharRatioGap = 0.08;
  648. const utf16LeQualified =
  649. utf16LeScore.preferredCharRatio >= minimumPreferredCharRatio &&
  650. utf16LeScore.invalidCharRatio <= maximumInvalidCharRatio;
  651. const utf16BeQualified =
  652. utf16BeScore.preferredCharRatio >= minimumPreferredCharRatio &&
  653. utf16BeScore.invalidCharRatio <= maximumInvalidCharRatio;
  654. if (utf16LeQualified && !utf16BeQualified) {
  655. return "utf-16le";
  656. }
  657. if (utf16BeQualified && !utf16LeQualified) {
  658. return "utf-16be";
  659. }
  660. if (!utf16LeQualified && !utf16BeQualified) {
  661. return null;
  662. }
  663. const preferredRatioGap = Math.abs(
  664. utf16LeScore.preferredCharRatio - utf16BeScore.preferredCharRatio,
  665. );
  666. if (preferredRatioGap >= minimumPreferredCharRatioGap) {
  667. return utf16LeScore.preferredCharRatio > utf16BeScore.preferredCharRatio
  668. ? "utf-16le"
  669. : "utf-16be";
  670. }
  671. return utf16LeScore.invalidCharRatio <= utf16BeScore.invalidCharRatio ? "utf-16le" : "utf-16be";
  672. }
  673. function isValidUtf8Sample(sample: Buffer): boolean {
  674. try {
  675. new TextDecoder("utf-8", { fatal: true }).decode(sample);
  676. return true;
  677. } catch {
  678. return false;
  679. }
  680. }
  681. function detectUtf16EncodingByAsciiPairPattern(sample: Buffer): SupportedTextEncoding | null {
  682. if (sample.length < 4) {
  683. return null;
  684. }
  685. let utf16LeRunLength = 0;
  686. let utf16BeRunLength = 0;
  687. let utf16LeAsciiRunScore = 0;
  688. let utf16BeAsciiRunScore = 0;
  689. // CJK 文本里会出现“单个码元低字节刚好是 0”的情况(如 U+4E00),
  690. // 直接统计 `0x00 + ASCII` 配对会把这些离散噪声误判成另一端字节序。
  691. // 这里改为统计“连续 ASCII-零字节 run”,只把成段英文 token(api key/header)作为有效信号。
  692. const flushRunScore = (runLength: number): number => (runLength >= 3 ? runLength : 0);
  693. for (let index = 0; index + 1 < sample.length; index += 2) {
  694. const leftByte = sample[index] ?? 0;
  695. const rightByte = sample[index + 1] ?? 0;
  696. if (rightByte === 0 && isLikelyAsciiTextByte(leftByte)) {
  697. utf16LeRunLength += 1;
  698. utf16BeAsciiRunScore += flushRunScore(utf16BeRunLength);
  699. utf16BeRunLength = 0;
  700. continue;
  701. }
  702. if (leftByte === 0 && isLikelyAsciiTextByte(rightByte)) {
  703. utf16BeRunLength += 1;
  704. utf16LeAsciiRunScore += flushRunScore(utf16LeRunLength);
  705. utf16LeRunLength = 0;
  706. continue;
  707. }
  708. utf16LeAsciiRunScore += flushRunScore(utf16LeRunLength);
  709. utf16BeAsciiRunScore += flushRunScore(utf16BeRunLength);
  710. utf16LeRunLength = 0;
  711. utf16BeRunLength = 0;
  712. }
  713. utf16LeAsciiRunScore += flushRunScore(utf16LeRunLength);
  714. utf16BeAsciiRunScore += flushRunScore(utf16BeRunLength);
  715. const minimumAsciiRunScore = 6;
  716. const dominanceRatio = 1.5;
  717. if (
  718. utf16LeAsciiRunScore >= minimumAsciiRunScore &&
  719. utf16LeAsciiRunScore >= utf16BeAsciiRunScore * dominanceRatio
  720. ) {
  721. return "utf-16le";
  722. }
  723. if (
  724. utf16BeAsciiRunScore >= minimumAsciiRunScore &&
  725. utf16BeAsciiRunScore >= utf16LeAsciiRunScore * dominanceRatio
  726. ) {
  727. return "utf-16be";
  728. }
  729. return null;
  730. }
  731. function detectTextFileEncoding(sample: Buffer): TextFileEncodingInfo | null {
  732. if (sample.length === 0) {
  733. return { encoding: "utf-8", bomLength: 0, bomBytes: EMPTY_BOM };
  734. }
  735. if (sample.length >= 3 && sample[0] === 0xef && sample[1] === 0xbb && sample[2] === 0xbf) {
  736. return {
  737. encoding: "utf-8",
  738. bomLength: 3,
  739. bomBytes: Buffer.from([0xef, 0xbb, 0xbf]),
  740. };
  741. }
  742. if (sample.length >= 2 && sample[0] === 0xff && sample[1] === 0xfe) {
  743. return {
  744. encoding: "utf-16le",
  745. bomLength: 2,
  746. bomBytes: Buffer.from([0xff, 0xfe]),
  747. };
  748. }
  749. if (sample.length >= 2 && sample[0] === 0xfe && sample[1] === 0xff) {
  750. return {
  751. encoding: "utf-16be",
  752. bomLength: 2,
  753. bomBytes: Buffer.from([0xfe, 0xff]),
  754. };
  755. }
  756. if (!sample.includes(0) && isValidUtf8Sample(sample)) {
  757. return { encoding: "utf-8", bomLength: 0, bomBytes: EMPTY_BOM };
  758. }
  759. // CJK 占比高的 UTF-16 无 BOM 文本,空字节比例可能很低,
  760. // 仅靠 null-ratio 会被误判为“非文本”并走原样复制,导致敏感字段漏脱敏。
  761. // 这里增加“ASCII-零字节对”兜底检测(例如 `OPENAI_API_KEY=\r\n`),覆盖真实日志中的混合文本场景。
  762. const utf16Encoding =
  763. detectUtf16EncodingByAsciiPairPattern(sample) ??
  764. detectUtf16EncodingByNullPattern(sample) ??
  765. detectUtf16EncodingByDecodedTextScore(sample);
  766. if (!utf16Encoding) {
  767. // 无 BOM 且不含空字节的 UTF-16 文本,在纯 CJK 内容里经常出现。
  768. // 这类样本 UTF-8 fatal decode 会失败;此时按 UTF-8 处理会产生乱码并漏掉敏感字段匹配。
  769. // 兜底策略:UTF-8 合法则按 UTF-8,非法且无法识别成 UTF-16 时才视为二进制。
  770. if (isValidUtf8Sample(sample)) {
  771. return { encoding: "utf-8", bomLength: 0, bomBytes: EMPTY_BOM };
  772. }
  773. return null;
  774. }
  775. return { encoding: utf16Encoding, bomLength: 0, bomBytes: EMPTY_BOM };
  776. }
  777. async function readFileSample(
  778. absolutePath: string,
  779. sampleBytes = TEXT_DETECTION_SAMPLE_BYTES,
  780. ): Promise<Buffer> {
  781. const fileHandle = await open(absolutePath, "r");
  782. try {
  783. const buffer = Buffer.alloc(sampleBytes);
  784. const { bytesRead } = await fileHandle.read(buffer, 0, sampleBytes, 0);
  785. return buffer.subarray(0, bytesRead);
  786. } finally {
  787. await fileHandle.close();
  788. }
  789. }
  790. function encodeTextWithEncoding(text: string, encoding: SupportedTextEncoding): Buffer {
  791. if (encoding === "utf-8") {
  792. return Buffer.from(text, "utf-8");
  793. }
  794. if (encoding === "utf-16le") {
  795. return Buffer.from(text, "utf16le");
  796. }
  797. const encodedBuffer = Buffer.from(text, "utf16le");
  798. encodedBuffer.swap16();
  799. return encodedBuffer;
  800. }
  801. function splitByCompleteLine(content: string): {
  802. completeChunk: string;
  803. pendingChunk: string;
  804. } {
  805. const lastLineFeedIndex = content.lastIndexOf("\n");
  806. if (lastLineFeedIndex >= 0) {
  807. return {
  808. completeChunk: content.slice(0, lastLineFeedIndex + 1),
  809. pendingChunk: content.slice(lastLineFeedIndex + 1),
  810. };
  811. }
  812. const lastCarriageReturnIndex = content.lastIndexOf("\r");
  813. if (lastCarriageReturnIndex >= 0 && lastCarriageReturnIndex < content.length - 1) {
  814. return {
  815. completeChunk: content.slice(0, lastCarriageReturnIndex + 1),
  816. pendingChunk: content.slice(lastCarriageReturnIndex + 1),
  817. };
  818. }
  819. return { completeChunk: "", pendingChunk: content };
  820. }
  821. function createSensitiveContentSanitizerTransform(encoding: SupportedTextEncoding): Transform {
  822. const decoder = new TextDecoder(encoding);
  823. let pendingChunk = "";
  824. return new Transform({
  825. transform(chunk, _chunkEncoding, callback) {
  826. try {
  827. const rawChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
  828. const decodedChunk = decoder.decode(rawChunk, { stream: true });
  829. const mergedChunk = `${pendingChunk}${decodedChunk}`;
  830. const { completeChunk, pendingChunk: nextPendingChunk } = splitByCompleteLine(mergedChunk);
  831. pendingChunk = nextPendingChunk;
  832. if (completeChunk.length === 0) {
  833. callback();
  834. return;
  835. }
  836. const sanitizedChunk = sanitizeSensitiveLogChunk(completeChunk);
  837. callback(null, encodeTextWithEncoding(sanitizedChunk, encoding));
  838. } catch (error) {
  839. callback(error as Error);
  840. }
  841. },
  842. flush(callback) {
  843. try {
  844. const remainingContent = `${pendingChunk}${decoder.decode()}`;
  845. if (remainingContent.length === 0) {
  846. callback();
  847. return;
  848. }
  849. const sanitizedChunk = sanitizeSensitiveLogChunk(remainingContent);
  850. callback(null, encodeTextWithEncoding(sanitizedChunk, encoding));
  851. } catch (error) {
  852. callback(error as Error);
  853. }
  854. },
  855. });
  856. }
  857. async function sanitizeTextLogFileToDestination(
  858. sourcePath: string,
  859. destinationPath: string,
  860. encodingInfo: TextFileEncodingInfo,
  861. ): Promise<void> {
  862. const readStream = createReadStream(sourcePath, {
  863. start: encodingInfo.bomLength,
  864. });
  865. const writeStream = createWriteStream(destinationPath);
  866. if (encodingInfo.bomLength > 0) {
  867. writeStream.write(encodingInfo.bomBytes);
  868. }
  869. await pipeline(
  870. readStream,
  871. createSensitiveContentSanitizerTransform(encodingInfo.encoding),
  872. writeStream,
  873. );
  874. }
  875. function isExcludedCachePath(relativePath: string): boolean {
  876. const normalizedRelativePath = normalizeArchivePath(relativePath);
  877. return (
  878. normalizedRelativePath === "Library/Caches" ||
  879. normalizedRelativePath.startsWith("Library/Caches/")
  880. );
  881. }
  882. function isRetiredAcpRuntimePath(relativePath: string): boolean {
  883. const normalizedRelativePath = normalizeArchivePath(relativePath);
  884. return RETIRED_ACP_RUNTIME_ARCHIVE_PATHS.some(
  885. (archivePath) =>
  886. normalizedRelativePath === archivePath ||
  887. normalizedRelativePath.startsWith(`${archivePath}/`),
  888. );
  889. }
  890. function isHighVolumeRuntimeArchivePath(relativePath: string): boolean {
  891. const normalizedRelativePath = normalizeArchivePath(relativePath);
  892. return HIGH_VOLUME_RUNTIME_ARCHIVE_PATHS.some(
  893. (archivePath) =>
  894. normalizedRelativePath === archivePath ||
  895. normalizedRelativePath.startsWith(`${archivePath}/`),
  896. );
  897. }
  898. function isDocshotArchivePath(relativePath: string): boolean {
  899. const normalizedRelativePath = normalizeArchivePath(relativePath);
  900. const firstSegment = normalizedRelativePath.split("/")[0] ?? "";
  901. if (DOCSHOT_ARCHIVE_PATHS.includes(firstSegment as (typeof DOCSHOT_ARCHIVE_PATHS)[number])) {
  902. return true;
  903. }
  904. return DOCSHOT_ARCHIVE_PATH_PREFIXES.some((prefix) => firstSegment.startsWith(prefix));
  905. }
  906. function isNonLogStateArchivePath(relativePath: string): boolean {
  907. const normalizedRelativePath = normalizeArchivePath(relativePath);
  908. return NON_LOG_STATE_ARCHIVE_PATHS.some(
  909. (archivePath) =>
  910. normalizedRelativePath === archivePath ||
  911. normalizedRelativePath.startsWith(`${archivePath}/`),
  912. );
  913. }
  914. function isSensitiveCredentialArchivePath(relativePath: string): boolean {
  915. const normalizedRelativePath = normalizeArchivePath(relativePath).toLowerCase();
  916. const fileName = normalizedRelativePath.split("/").at(-1) ?? "";
  917. return SENSITIVE_CREDENTIAL_ARCHIVE_FILE_NAMES.has(fileName);
  918. }
  919. function isExcludedDirectoryArchivePath(relativePath: string): boolean {
  920. const normalizedRelativePath = normalizeArchivePath(relativePath).toLowerCase();
  921. return normalizedRelativePath
  922. .split("/")
  923. .some((segment) => EXCLUDED_ARCHIVE_DIRECTORY_NAMES.has(segment));
  924. }
  925. function isExcludedRelativePath(relativePath: string): boolean {
  926. const normalizedRelativePath = normalizeArchivePath(relativePath);
  927. // 完整日志导出过去只做内容脱敏,仍会把 credentials.json 文件本身放进包。
  928. // 凭据存储文件不是排障日志,且不同提供商可能复用同名文件;因此在收集清单阶段按文件名跳过。
  929. if (isSensitiveCredentialArchivePath(normalizedRelativePath)) {
  930. return true;
  931. }
  932. // debug 目录通常是模型/运行时高频轨迹,不是用户要交付的日志包材料。
  933. // 过去显式收集 ~/.zcode/cli/debug 会把这类上下文带进手动导出和反馈完整日志,这里按目录段统一跳过。
  934. if (isExcludedDirectoryArchivePath(normalizedRelativePath)) {
  935. return true;
  936. }
  937. if (isNonLogStateArchivePath(normalizedRelativePath)) {
  938. return true;
  939. }
  940. // ~/.zcode/v2/dev 保存 stdio-traffic 等高频协议流,真实机器上会累计到 GB 级。
  941. // 远超反馈附件的大小上限,不应随诊断包带出。
  942. if (isHighVolumeRuntimeArchivePath(normalizedRelativePath)) {
  943. return true;
  944. }
  945. // docshot 历史备份和素材目录体积可达 GB 级,
  946. // 且不属于用户反馈所需的诊断日志。
  947. if (isDocshotArchivePath(normalizedRelativePath)) {
  948. return true;
  949. }
  950. // ACP runtime 目录已退役,老用户数据里仍可能残留数百 MB 抓包和旧鉴权文件。
  951. // 当前运行态配置已经迁到 agent-config;继续导出这些旧目录会让导出长时间无反馈,还可能带出旧代理证书私钥。
  952. if (isRetiredAcpRuntimePath(normalizedRelativePath)) {
  953. return true;
  954. }
  955. // Library/Caches 是运行时缓存,不是排障所需日志;导出它只会放大日志包。
  956. if (isExcludedCachePath(normalizedRelativePath)) {
  957. return true;
  958. }
  959. return ZIP_EXCLUDE_REGEXES.some((pattern) => pattern.test(normalizedRelativePath));
  960. }
  961. function shouldApplyLogExportRetention(archivePath: string): boolean {
  962. const normalizedArchivePath = normalizeArchivePath(archivePath);
  963. if (
  964. normalizedArchivePath.startsWith("logs/") ||
  965. normalizedArchivePath.startsWith(".zcode/cli/log/")
  966. ) {
  967. return true;
  968. }
  969. return false;
  970. }
  971. async function filterRecentLogArchiveFiles(
  972. files: LogArchiveFileEntry[],
  973. options: CreateLogArchiveArtifactsOptions = {},
  974. ): Promise<LogArchiveFileEntry[]> {
  975. const lookbackDays = options.lookbackDays ?? DEFAULT_LOG_EXPORT_LOOKBACK_DAYS;
  976. if (lookbackDays <= 0) {
  977. return files;
  978. }
  979. const now = options.now ?? (() => new Date());
  980. const cutoffMs = now().getTime() - lookbackDays * MILLISECONDS_PER_DAY;
  981. const recentFiles: LogArchiveFileEntry[] = [];
  982. for (const file of files) {
  983. if (!shouldApplyLogExportRetention(file.archivePath)) {
  984. recentFiles.push(file);
  985. continue;
  986. }
  987. const fileStats = await stat(file.absolutePath).catch(() => null);
  988. // 导出日志过去按目录全量打包,长时间运行后旧 diagnostics 会把日志包放大到数百 MB。
  989. // 这里仅对“可由时间窗口复现现场”的日志类文件按 mtime 保留近 3 天;
  990. // settings 等排障配置不参与过滤,避免久未修改但仍影响当前行为的配置丢失。
  991. if (fileStats?.isFile() && fileStats.mtimeMs >= cutoffMs) {
  992. recentFiles.push(file);
  993. }
  994. }
  995. return recentFiles;
  996. }
  997. function createAboutContent(): string {
  998. const snapshot = createAboutSnapshot({ buildMetadata: readBuildMetadata() });
  999. return formatAboutDetail(snapshot);
  1000. }
  1001. function formatErrorMessage(error: unknown): string {
  1002. return error instanceof Error ? error.message : String(error);
  1003. }
  1004. function logSkippedLogArchiveDirectory(
  1005. absolutePath: string,
  1006. archivePath: string,
  1007. error: unknown,
  1008. ): void {
  1009. logger.warn("[export-logs] 日志目录不可读,已在导出时自动跳过", {
  1010. absolutePath,
  1011. archivePath,
  1012. error: formatErrorMessage(error),
  1013. });
  1014. }
  1015. async function walkLogArchiveDirectory(
  1016. absoluteDir: string,
  1017. relativeDir: string,
  1018. visitedDirs: Set<string>,
  1019. files: LogArchiveFileEntry[],
  1020. ): Promise<void> {
  1021. const resolvedDir = await realpath(absoluteDir).catch(() => absoluteDir);
  1022. if (visitedDirs.has(resolvedDir)) {
  1023. return;
  1024. }
  1025. visitedDirs.add(resolvedDir);
  1026. const dirents = await readdir(absoluteDir, { withFileTypes: true }).catch((error: unknown) => {
  1027. // 用户目录下的日志来源可能包含被系统或第三方 CLI 限制权限的子目录。
  1028. // 单个目录 scandir 失败时跳过该目录,避免一次 EACCES 把整个日志包导出中断。
  1029. logSkippedLogArchiveDirectory(absoluteDir, relativeDir, error);
  1030. return null;
  1031. });
  1032. if (!dirents) {
  1033. return;
  1034. }
  1035. dirents.sort((left, right) => left.name.localeCompare(right.name));
  1036. for (const dirent of dirents) {
  1037. const archivePath = relativeDir ? posix.join(relativeDir, dirent.name) : dirent.name;
  1038. if (isExcludedRelativePath(archivePath)) {
  1039. continue;
  1040. }
  1041. const absolutePath = join(absoluteDir, dirent.name);
  1042. if (dirent.isDirectory()) {
  1043. await walkLogArchiveDirectory(absolutePath, archivePath, visitedDirs, files);
  1044. continue;
  1045. }
  1046. if (dirent.isFile()) {
  1047. files.push({ absolutePath, archivePath });
  1048. continue;
  1049. }
  1050. if (!dirent.isSymbolicLink()) {
  1051. continue;
  1052. }
  1053. const targetStats = await stat(absolutePath).catch(() => null);
  1054. if (!targetStats) {
  1055. continue;
  1056. }
  1057. // 日志目录里存在 provider 共享资源的软链入口。
  1058. // 这里按目标类型处理并配合 realpath 去重,避免递归跟随时把同一份内容重复打进包,甚至形成循环遍历。
  1059. if (targetStats.isDirectory()) {
  1060. await walkLogArchiveDirectory(absolutePath, archivePath, visitedDirs, files);
  1061. continue;
  1062. }
  1063. if (targetStats.isFile()) {
  1064. files.push({ absolutePath, archivePath });
  1065. }
  1066. }
  1067. }
  1068. async function collectLogArchiveFilesFromDirectory(
  1069. absoluteDir: string,
  1070. relativeDir: string,
  1071. visitedDirs: Set<string>,
  1072. files: LogArchiveFileEntry[],
  1073. ): Promise<void> {
  1074. const directoryStats = await stat(absoluteDir).catch(() => null);
  1075. if (!directoryStats?.isDirectory()) {
  1076. return;
  1077. }
  1078. await walkLogArchiveDirectory(absoluteDir, relativeDir, visitedDirs, files);
  1079. }
  1080. /**
  1081. * 按文件名白名单收集单层目录,不递归。用于运行目录这类"诊断文件与凭据同放"的场景:
  1082. * 递归收集会把 .tokens 之类的机密带进用户会转发出去的日志包,而 EXCLUDED 名单是
  1083. * 事后补救、天然滞后。白名单则默认拒绝——目录里以后多出什么都不会跟着漏出去。
  1084. */
  1085. async function collectLogArchiveFilesByName(
  1086. absoluteDir: string,
  1087. relativeDir: string,
  1088. isCollectableFileName: (fileName: string) => boolean,
  1089. files: LogArchiveFileEntry[],
  1090. ): Promise<void> {
  1091. const dirents = await readdir(absoluteDir, { withFileTypes: true }).catch(() => null);
  1092. if (!dirents) {
  1093. return;
  1094. }
  1095. dirents.sort((left, right) => left.name.localeCompare(right.name));
  1096. for (const dirent of dirents) {
  1097. if (!dirent.isFile() || !isCollectableFileName(dirent.name)) {
  1098. continue;
  1099. }
  1100. await collectLogArchiveFile(
  1101. join(absoluteDir, dirent.name),
  1102. posix.join(relativeDir, dirent.name),
  1103. files,
  1104. );
  1105. }
  1106. }
  1107. async function collectLogArchiveFile(
  1108. absolutePath: string,
  1109. archivePath: string,
  1110. files: LogArchiveFileEntry[],
  1111. ): Promise<void> {
  1112. if (isExcludedRelativePath(archivePath)) {
  1113. return;
  1114. }
  1115. const fileStats = await stat(absolutePath).catch(() => null);
  1116. if (!fileStats?.isFile()) {
  1117. return;
  1118. }
  1119. files.push({ absolutePath, archivePath });
  1120. }
  1121. export async function collectLogArchiveFiles(sourceDir: string): Promise<LogArchiveFileEntry[]> {
  1122. const files: LogArchiveFileEntry[] = [];
  1123. const visitedDirs = new Set<string>();
  1124. await collectLogArchiveFilesFromDirectory(sourceDir, "", visitedDirs, files);
  1125. files.sort((left, right) => left.archivePath.localeCompare(right.archivePath));
  1126. return files;
  1127. }
  1128. export async function createLogArchiveArtifacts(
  1129. sourceDir: string,
  1130. options: CreateLogArchiveArtifactsOptions = {},
  1131. ): Promise<LogArchiveArtifacts> {
  1132. const files: LogArchiveFileEntry[] = [];
  1133. const visitedDirs = new Set<string>();
  1134. await collectLogArchiveFilesFromDirectory(sourceDir, "", visitedDirs, files);
  1135. const zcodeCliLogDir = getZCodeCliLogDir();
  1136. // GLM / zcode-cli 的运行日志写在 ~/.zcode/cli/log,不在应用主数据目录 ~/.zcode/v2 下。
  1137. // 如果导出日志只扫描 v2,定位 agent CLI 启动、协议或崩溃问题时会缺少最关键的原生侧日志。
  1138. await collectLogArchiveFilesFromDirectory(
  1139. zcodeCliLogDir,
  1140. posix.join(".zcode", "cli", "log"),
  1141. visitedDirs,
  1142. files,
  1143. );
  1144. const zcodeCliDir = getZCodeCliDir();
  1145. await collectLogArchiveFilesByName(
  1146. join(zcodeCliDir, CLI_MEMORY_DIAGNOSTIC_DIRECTORY),
  1147. posix.join(".zcode", "cli", CLI_MEMORY_DIAGNOSTIC_DIRECTORY),
  1148. (name) => CLI_MEMORY_FILE_PATTERN.test(name),
  1149. files,
  1150. );
  1151. // 排查 agent CLI 问题还需要它的运行配置与模型 IO 轨迹。
  1152. // config.json 是当前生效配置;rollout 是 model-io 调用轨迹,
  1153. // 二者都不在 ~/.zcode/cli/log 下,需要额外收集才能完整还原现场。
  1154. await collectLogArchiveFile(
  1155. join(zcodeCliDir, "config.json"),
  1156. posix.join(".zcode", "cli", "config.json"),
  1157. files,
  1158. );
  1159. await collectLogArchiveFilesFromDirectory(
  1160. join(zcodeCliDir, "rollout"),
  1161. posix.join(".zcode", "cli", "rollout"),
  1162. visitedDirs,
  1163. files,
  1164. );
  1165. // Computer Use Helper 的结构化诊断必须进日志包:否则反馈包里
  1166. // grep "background keyboard begin rejected" 命中 0,
  1167. // 因为 Helper 由 LaunchServices 启动、stderr 被系统丢弃,它把诊断 tee 到
  1168. // ~/.zcode/computer-use/run/<socket>.exit.log,既不在 app data 也不在 ~/.zcode/cli 下。
  1169. // 同目录下有 .tokens broker 凭据,因此按文件名白名单只收 *.exit.log,不递归该目录。
  1170. await collectLogArchiveFilesByName(
  1171. getCuaHelperRunDir(),
  1172. posix.join(".zcode", "computer-use", "run"),
  1173. isCuaHelperDiagnosticFileName,
  1174. files,
  1175. );
  1176. const recentFiles = await filterRecentLogArchiveFiles(files, options);
  1177. recentFiles.sort((left, right) => left.archivePath.localeCompare(right.archivePath));
  1178. return {
  1179. files: recentFiles,
  1180. aboutContent: createAboutContent(),
  1181. };
  1182. }
  1183. async function copyLogArchiveFilesToDirectory(
  1184. outputPath: string,
  1185. files: LogArchiveFileEntry[],
  1186. ): Promise<LogArchiveSkippedFileEntry[]> {
  1187. const skippedFiles: LogArchiveSkippedFileEntry[] = [];
  1188. for (const file of files) {
  1189. const destinationPath = join(outputPath, ...file.archivePath.split("/"));
  1190. await mkdir(dirname(destinationPath), { recursive: true });
  1191. const sourceStats = await stat(file.absolutePath).catch((error: unknown) => {
  1192. skippedFiles.push({
  1193. absolutePath: file.absolutePath,
  1194. archivePath: file.archivePath,
  1195. error: formatErrorMessage(error),
  1196. });
  1197. return null;
  1198. });
  1199. if (!sourceStats?.isFile()) {
  1200. continue;
  1201. }
  1202. const sourceReadable = await access(file.absolutePath, constants.R_OK)
  1203. .then(() => true)
  1204. .catch((error: unknown) => {
  1205. skippedFiles.push({
  1206. absolutePath: file.absolutePath,
  1207. archivePath: file.archivePath,
  1208. error: formatErrorMessage(error),
  1209. });
  1210. return false;
  1211. });
  1212. if (!sourceReadable) {
  1213. continue;
  1214. }
  1215. try {
  1216. // 这里改为“采样识别编码 + 流式脱敏”,避免全量 readFile 带来的大文件内存峰值。
  1217. // 同时显式支持 UTF-16 文本(含 BOM/无 BOM 常见形态),防止被误判成二进制后原样泄露敏感字段。
  1218. const sourceSample = await readFileSample(file.absolutePath);
  1219. const textEncodingInfo = detectTextFileEncoding(sourceSample);
  1220. if (!textEncodingInfo) {
  1221. await copyFile(file.absolutePath, destinationPath);
  1222. } else {
  1223. await sanitizeTextLogFileToDestination(
  1224. file.absolutePath,
  1225. destinationPath,
  1226. textEncodingInfo,
  1227. );
  1228. }
  1229. } catch (error) {
  1230. const sourceStatsAfterFailure = await stat(file.absolutePath).catch(() => null);
  1231. const sourceReadableAfterFailure = sourceStatsAfterFailure?.isFile()
  1232. ? await access(file.absolutePath, constants.R_OK)
  1233. .then(() => true)
  1234. .catch(() => false)
  1235. : false;
  1236. // telemetry/agent 日志文件可能在“扫描完待导出列表”之后被后台轮转、删除或改权限,
  1237. // 软链目标也可能在这段窗口里失效。复制失败后再核一次源文件可读性;
  1238. // 如果源头已经不可读,就把它当成坏文件跳过,避免单个 ENOENT/EACCES 让导出整体失败。
  1239. if (!sourceReadableAfterFailure) {
  1240. skippedFiles.push({
  1241. absolutePath: file.absolutePath,
  1242. archivePath: file.archivePath,
  1243. error: formatErrorMessage(error),
  1244. });
  1245. continue;
  1246. }
  1247. throw error;
  1248. }
  1249. }
  1250. return skippedFiles;
  1251. }
  1252. function logSkippedLogArchiveFiles(skippedFiles: LogArchiveSkippedFileEntry[]): void {
  1253. if (skippedFiles.length === 0) {
  1254. return;
  1255. }
  1256. logger.warn("[export-logs] 检测到不可读日志文件,已在导出时自动跳过", {
  1257. skippedCount: skippedFiles.length,
  1258. skippedFiles: skippedFiles.slice(0, 10),
  1259. });
  1260. }
  1261. export async function writeLogArchiveZip(
  1262. outputPath: string,
  1263. artifacts: LogArchiveArtifacts,
  1264. options: WriteLogArchiveZipOptions = {},
  1265. ): Promise<void> {
  1266. const stageRootDir = options.stageRootDir ?? getDefaultExportLogStageDir();
  1267. await mkdir(stageRootDir, { recursive: true });
  1268. const stagingDir = await mkdtemp(join(stageRootDir, "stage-"));
  1269. try {
  1270. // yazl.addFile 内部会再次对源路径执行 fs.stat/createReadStream。
  1271. // 对于软链目标或正在被轮转的 telemetry 文件,这一步仍然可能异步抛错并触发未监听的 error 事件。
  1272. // 这里先把可读文件稳定复制到临时目录,再从临时目录压缩,保证 zip 阶段只面对我们自己控制的常规文件。
  1273. await writeLogArchiveDirectory(stagingDir, artifacts);
  1274. const zipFile = new ZipFile();
  1275. const stageFiles = await collectLogArchiveFiles(stagingDir);
  1276. const outputStream = createWriteStream(outputPath);
  1277. zipFile.once("error", (error) => {
  1278. outputStream.destroy(error instanceof Error ? error : new Error(String(error)));
  1279. });
  1280. for (const file of stageFiles) {
  1281. zipFile.addFile(file.absolutePath, file.archivePath);
  1282. }
  1283. const writePromise = pipeline(zipFile.outputStream, outputStream);
  1284. zipFile.end();
  1285. await writePromise;
  1286. } finally {
  1287. await rm(stagingDir, { recursive: true, force: true }).catch(() => {});
  1288. }
  1289. }
  1290. export async function writeLogArchiveDirectory(
  1291. outputPath: string,
  1292. artifacts: LogArchiveArtifacts,
  1293. ): Promise<void> {
  1294. await mkdir(outputPath, { recursive: true });
  1295. const skippedFiles = await copyLogArchiveFilesToDirectory(outputPath, artifacts.files);
  1296. logSkippedLogArchiveFiles(skippedFiles);
  1297. await writeFile(join(outputPath, "about.txt"), artifacts.aboutContent, "utf-8");
  1298. }
  1299. export async function createFeedbackLogArchiveFromExportLogs(
  1300. sourceDir: string,
  1301. options: CreateFeedbackLogArchiveFromExportLogsOptions = {},
  1302. ): Promise<{ path: string; size: number }> {
  1303. return createFeedbackDiagnosticArchive({
  1304. sources: [
  1305. {
  1306. directory: join(getZCodeCliDir(), CLI_MEMORY_DIAGNOSTIC_DIRECTORY),
  1307. archivePrefix: ".zcode/cli/memory-diagnostics",
  1308. contentPolicy: "cli-memory",
  1309. onlyCurrentDay: false,
  1310. },
  1311. { directory: join(sourceDir, "logs"), archivePrefix: "logs" },
  1312. { directory: getZCodeCliLogDir(), archivePrefix: ".zcode/cli/log" },
  1313. {
  1314. directory: getZCodeCliDir(),
  1315. archivePrefix: ".zcode/cli",
  1316. includeFileNames: ["config.json"],
  1317. onlyCurrentDay: false,
  1318. contentPolicy: "cli-config",
  1319. },
  1320. {
  1321. directory: join(getZCodeCliDir(), "rollout"),
  1322. archivePrefix: ".zcode/cli/rollout",
  1323. },
  1324. {
  1325. directory: getCuaHelperRunDir(),
  1326. archivePrefix: ".zcode/computer-use/run",
  1327. exitLogsOnly: true,
  1328. },
  1329. ],
  1330. outputRootDir: options.outputRootDir ?? getDefaultFeedbackLogArchiveDir(),
  1331. now: options.now,
  1332. onProgress: options.onProgress,
  1333. });
  1334. }
  1335. export async function exportLogs(
  1336. dependencies: ExportLogsDependencies = {},
  1337. ): Promise<{ success: boolean; path?: string; error?: string }> {
  1338. try {
  1339. const now = dependencies.now ?? (() => new Date());
  1340. const getSourceDir = dependencies.getZCodeDataDir ?? getZCodeDataDir;
  1341. const buildArtifacts = dependencies.createLogArchiveArtifacts ?? createLogArchiveArtifacts;
  1342. const writeZip = dependencies.writeLogArchiveZip ?? writeLogArchiveZip;
  1343. const writeDirectory = dependencies.writeLogArchiveDirectory ?? writeLogArchiveDirectory;
  1344. const showItemInFolder =
  1345. dependencies.showItemInFolder ??
  1346. (async (path: string) => {
  1347. const { shell } = await import("electron");
  1348. shell.showItemInFolder(path);
  1349. });
  1350. const getStageRootDir = dependencies.getExportLogStageDir ?? getDefaultExportLogStageDir;
  1351. const getOutputRootDir = dependencies.getExportLogDir ?? getDefaultExportLogDir;
  1352. const sourceDir = getSourceDir();
  1353. const timestamp = formatTimestamp(now());
  1354. const exportBaseName = `zcode-logs-${timestamp}`;
  1355. const outputRootDir = getOutputRootDir();
  1356. await mkdir(outputRootDir, { recursive: true });
  1357. const outputDir = await mkdtemp(join(outputRootDir, `${exportBaseName}-`));
  1358. const zipPath = join(outputDir, `${exportBaseName}.zip`);
  1359. const directoryPath = join(outputDir, exportBaseName);
  1360. logger.info("[export-logs] 开始打包日志", {
  1361. source: sourceDir,
  1362. zipDest: zipPath,
  1363. directoryDest: directoryPath,
  1364. });
  1365. const artifacts = await buildArtifacts(sourceDir, { now });
  1366. try {
  1367. await writeZip(zipPath, artifacts, { stageRootDir: getStageRootDir() });
  1368. await showItemInFolder(zipPath);
  1369. logger.info("[export-logs] 日志导出完成", {
  1370. path: zipPath,
  1371. format: "zip",
  1372. });
  1373. return { success: true, path: zipPath };
  1374. } catch (zipError) {
  1375. const zipErrorMessage = zipError instanceof Error ? zipError.message : String(zipError);
  1376. // Windows 的压缩能力不再依赖 PowerShell/.NET,但归档写入仍可能被杀软、磁盘策略等外部因素打断。
  1377. // 这里回退为目录导出,保证用户至少能稳定拿到原始日志,而不是直接报错。
  1378. logger.warn("[export-logs] zip 导出失败,回退到目录导出", {
  1379. error: zipErrorMessage,
  1380. zipPath,
  1381. fallbackPath: directoryPath,
  1382. });
  1383. await rm(zipPath, { force: true }).catch(() => {});
  1384. try {
  1385. await writeDirectory(directoryPath, artifacts);
  1386. } catch (directoryError) {
  1387. const directoryErrorMessage =
  1388. directoryError instanceof Error ? directoryError.message : String(directoryError);
  1389. throw new Error(`zip 导出失败:${zipErrorMessage};目录导出失败:${directoryErrorMessage}`);
  1390. }
  1391. await showItemInFolder(directoryPath);
  1392. logger.info("[export-logs] 日志导出完成", {
  1393. path: directoryPath,
  1394. format: "directory",
  1395. });
  1396. return { success: true, path: directoryPath };
  1397. }
  1398. } catch (err) {
  1399. const message = formatErrorMessage(err);
  1400. logger.error("[export-logs] 日志导出失败", { error: message });
  1401. return { success: false, error: message };
  1402. }
  1403. }