exportLogs.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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 {
  21. createFeedbackDiagnosticArchive,
  22. getAppConfigDir,
  23. getExportLogDir as getDefaultExportLogDir,
  24. getExportLogStageDir as getDefaultExportLogStageDir,
  25. getFeedbackLogArchiveDir as getDefaultFeedbackLogArchiveDir,
  26. } from "@zcode/services/node";
  27. import { createAboutSnapshot, formatAboutDetail, readBuildMetadata } from "./about.js";
  28. import { logger } from "./logger.js";
  29. function getZCodeDataDir() {
  30. return getAppConfigDir();
  31. }
  32. function getZCodeCliDir() {
  33. return join(homedir(), ".zcode", "cli");
  34. }
  35. function getZCodeCliLogDir() {
  36. return join(getZCodeCliDir(), "log");
  37. }
  38. /**
  39. * Computer Use Helper 的运行目录。macOS 上 Helper 由 LaunchServices 启动,stderr 被系统丢弃,
  40. * 所以它把生命周期与后台输入诊断 tee 到 `<socket>.exit.log`(见 zcode-cua
  41. * helperExitLogPathFor)。同目录下还有 `.tokens` broker 凭据,收集时必须按文件名白名单。
  42. */
  43. function getCuaHelperRunDir() {
  44. return join(homedir(), ".zcode", "computer-use", "run");
  45. }
  46. function isCuaHelperDiagnosticFileName(fileName: string): boolean {
  47. return fileName.endsWith(".exit.log");
  48. }
  49. interface LogArchiveFileEntry {
  50. absolutePath: string;
  51. archivePath: string;
  52. }
  53. interface LogArchiveArtifacts {
  54. files: LogArchiveFileEntry[];
  55. aboutContent: string;
  56. }
  57. interface CreateLogArchiveArtifactsOptions {
  58. now?: () => Date;
  59. lookbackDays?: number;
  60. }
  61. interface LogArchiveSkippedFileEntry {
  62. absolutePath: string;
  63. archivePath: string;
  64. error: string;
  65. }
  66. interface ExportLogsDependencies {
  67. now?: () => Date;
  68. getZCodeDataDir?: () => string;
  69. getExportLogStageDir?: () => string;
  70. getExportLogDir?: () => string;
  71. createLogArchiveArtifacts?: (
  72. sourceDir: string,
  73. options?: CreateLogArchiveArtifactsOptions,
  74. ) => Promise<LogArchiveArtifacts>;
  75. writeLogArchiveZip?: (
  76. outputPath: string,
  77. artifacts: LogArchiveArtifacts,
  78. options?: WriteLogArchiveZipOptions,
  79. ) => Promise<void>;
  80. writeLogArchiveDirectory?: (outputPath: string, artifacts: LogArchiveArtifacts) => Promise<void>;
  81. showItemInFolder?: (path: string) => Promise<void> | void;
  82. }
  83. interface WriteLogArchiveZipOptions {
  84. stageRootDir?: string;
  85. }
  86. interface CreateFeedbackLogArchiveFromExportLogsOptions {
  87. now?: () => Date;
  88. outputRootDir?: string;
  89. stageRootDir?: string;
  90. onProgress?: (event: { processedBytes: number; totalBytes: number }) => void;
  91. }
  92. function formatTimestamp(now: Date = new Date()): string {
  93. const pad = (n: number) => String(n).padStart(2, "0");
  94. return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
  95. }
  96. function normalizeArchivePath(path: string): string {
  97. return path.replaceAll("\\", "/");
  98. }
  99. function escapeRegExp(path: string): string {
  100. return path.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
  101. }
  102. function globPatternToRegExp(pattern: string): RegExp {
  103. const normalizedPattern = normalizeArchivePath(pattern);
  104. return new RegExp(`^${normalizedPattern.split("*").map(escapeRegExp).join(".*")}$`);
  105. }
  106. /**
  107. * Glob patterns to exclude from the exported log archive.
  108. * Each pattern is relative to the source directory being archived.
  109. */
  110. const ZIP_EXCLUDE_PATTERNS: string[] = [];
  111. const ZIP_EXCLUDE_REGEXES = ZIP_EXCLUDE_PATTERNS.map(globPatternToRegExp);
  112. const RETIRED_ACP_RUNTIME_ARCHIVE_PATHS = [
  113. "acp-auth",
  114. "acp-config",
  115. "acp-stream-diagnostics",
  116. "acp-traffic-proxy",
  117. ] as const;
  118. const HIGH_VOLUME_RUNTIME_ARCHIVE_PATHS = ["dev"] as const;
  119. const DOCSHOT_ARCHIVE_PATH_PREFIXES = ["docshot-backup-"] as const;
  120. const DOCSHOT_ARCHIVE_PATHS = ["docshot-assets"] as const;
  121. const NON_LOG_STATE_ARCHIVE_PATHS = [
  122. "agent-config",
  123. "certs",
  124. "repo-snapshots",
  125. "repo-wiki",
  126. "sessions",
  127. "session-bindings",
  128. "checkpoints",
  129. ] as const;
  130. const SENSITIVE_CREDENTIAL_ARCHIVE_FILE_NAMES = new Set(["credentials.json", ".credentials.json"]);
  131. const EXCLUDED_ARCHIVE_DIRECTORY_NAMES = new Set(["debug"]);
  132. const DEFAULT_LOG_EXPORT_LOOKBACK_DAYS = 3;
  133. const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
  134. const REDACTED_PLACEHOLDER = "***REDACTED***";
  135. // 敏感键名“族”:只要键名里包含这些子串就视为敏感(兜底通配),
  136. // 从而覆盖自定义命名(如 db_password、my_secret、x-conn-string 等)而不必逐个精确列举。
  137. // 注意:`token` / `auth` 等是宽松子串,配合下方白名单排除误伤项(如 input_tokens、author)。
  138. const SENSITIVE_KEY_SUBSTRING_PATTERN = [
  139. "password",
  140. "passwd",
  141. "pwd",
  142. "secret",
  143. "token",
  144. "credential",
  145. "api(?:_|-)?key",
  146. "access(?:_|-)?key",
  147. "private(?:_|-)?key",
  148. "auth",
  149. "cookie",
  150. "dsn",
  151. "conn(?:ection)?(?:_|-)?str(?:ing)?",
  152. "database(?:_|-)?url",
  153. "db(?:_|-)?url",
  154. ].join("|");
  155. const SENSITIVE_KEY_NAME_REGEX = new RegExp(`(?:${SENSITIVE_KEY_SUBSTRING_PATTERN})`, "i");
  156. // 白名单:命中敏感子串但实际并非密钥的常见键名,避免脱掉排障需要的上下文。
  157. // 不能把任意 "*_tokens" 都白名单化,否则 access_tokens/session_tokens 会被原样导出;
  158. // max_tokens/budget_tokens 是模型输出与思考预算,不是凭据,需保留用于判断 provider 请求是否撞限;
  159. // 因此这里只放行明确的 LLM token 计数/预算字段,以及 author/authority 这类含 "auth" 的普通词。
  160. const NON_SENSITIVE_KEY_NAME_ALLOWLIST_REGEX =
  161. /^(?:public(?:_|-)?key|keywords?|tokenizer|token(?:_|-)?count|(?:prompt|completion|total|input|output|cached|reasoning|max|budget|accepted(?:_|-)?prediction|rejected(?:_|-)?prediction|tool(?:_|-)?use(?:_|-)?prompt)(?:_|-)?tokens|author(?:s|ity|ed)?)$/i;
  162. function isSensitiveKeyName(keyName: string): boolean {
  163. if (NON_SENSITIVE_KEY_NAME_ALLOWLIST_REGEX.test(keyName)) {
  164. return false;
  165. }
  166. return SENSITIVE_KEY_NAME_REGEX.test(keyName);
  167. }
  168. // 以下正则先宽松捕获“键名 + 值”,再由 isSensitiveKeyName 决定是否脱敏,
  169. // 这样键名黑名单不再是硬编码列表,而是“敏感族 + 通配 + 白名单例外”。
  170. const JSON_STYLE_SENSITIVE_VALUE_REGEX =
  171. /(["'])([A-Za-z0-9_.-]+)\1(\s*:\s*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^,\r\n}\]]+)/g;
  172. const ASSIGNMENT_STYLE_SENSITIVE_VALUE_REGEX =
  173. /((?:^|\n)[ \t]*)([A-Za-z0-9_.-]+)([ \t]*=[ \t]*)([^\r\n#]+)/g;
  174. const HEADER_STYLE_SENSITIVE_VALUE_REGEX =
  175. /((?:^|\n)[ \t]*)([A-Za-z0-9-]+)([ \t]*:[ \t]*)([^\r\n]+)/g;
  176. const BEARER_TOKEN_REGEX = /(Bearer\s+)([^\s"']+)/g;
  177. const QUERY_TOKEN_REGEX =
  178. /([?&](?:key|api(?:_|-)?key|access(?:_|-)?token|refresh(?:_|-)?token|token|password|passwd|pwd|secret|client(?:_|-)?secret|auth(?:_|-)?token|session(?:_|-)?token)=)([^&#\s]+)/gi;
  179. // 按“值形态”脱敏:连接串 scheme://user:pass@host 里的凭据部分,
  180. // 不依赖键名即可覆盖 postgres/mysql/mongodb/redis/amqp 等数据库连接信息。保留 scheme 与 host 便于排障。
  181. // 用户名段允许为空以覆盖 redis://:password@host;口令段贪婪匹配到最后一个 @(host 段不含 @),
  182. // 这样口令里含裸 @(如 P@ssw0rd)也能整段脱敏,不残留片段。
  183. const CONNECTION_STRING_CREDENTIALS_REGEX =
  184. /\b([a-z][a-z0-9+.-]*:\/\/)([^:/\s]*):([^/\s]+)@(?=[^@/\s])/gi;
  185. const TEXT_DETECTION_SAMPLE_BYTES = 64 * 1024;
  186. const EMPTY_BOM = Buffer.alloc(0);
  187. type SupportedTextEncoding = "utf-8" | "utf-16le" | "utf-16be";
  188. interface TextFileEncodingInfo {
  189. encoding: SupportedTextEncoding;
  190. bomLength: number;
  191. bomBytes: Buffer;
  192. }
  193. interface TextDecodingScore {
  194. preferredCharRatio: number;
  195. invalidCharRatio: number;
  196. }
  197. function redactValue(rawValue: string): string {
  198. const leadingSpaces = rawValue.match(/^\s*/)?.[0] ?? "";
  199. const trailingSpaces = rawValue.match(/\s*$/)?.[0] ?? "";
  200. const core = rawValue.trim();
  201. const quote =
  202. core.startsWith('"') && core.endsWith('"')
  203. ? '"'
  204. : core.startsWith("'") && core.endsWith("'")
  205. ? "'"
  206. : "";
  207. const redacted = quote ? `${quote}${REDACTED_PLACEHOLDER}${quote}` : REDACTED_PLACEHOLDER;
  208. return `${leadingSpaces}${redacted}${trailingSpaces}`;
  209. }
  210. function redactHeaderValue(rawValue: string): string {
  211. const trimmed = rawValue.trim();
  212. if (/^bearer\s+/i.test(trimmed)) {
  213. return trimmed.replace(/^bearer\s+.+$/i, `Bearer ${REDACTED_PLACEHOLDER}`);
  214. }
  215. return REDACTED_PLACEHOLDER;
  216. }
  217. function redactConnectionStringCredentials(rawContent: string): string {
  218. // postgres://admin:secret@host → postgres://***REDACTED***:***REDACTED***@host
  219. return rawContent.replace(
  220. CONNECTION_STRING_CREDENTIALS_REGEX,
  221. (_match, scheme: string) => `${scheme}${REDACTED_PLACEHOLDER}:${REDACTED_PLACEHOLDER}@`,
  222. );
  223. }
  224. function sanitizeSensitiveLogContent(rawContent: string): string {
  225. // 导出日志不能按文件原样拷贝:会把用户配置和协议日志里的 token/apiKey 一并带出。
  226. // 线上排障需要“保留文件结构和上下文”,但不应该泄露密钥本体;
  227. // 这里在导出阶段统一对常见敏感值做脱敏,字段和日志行仍完整保留,支持继续定位问题。
  228. // 键名不再是硬编码黑名单,而是“敏感键名族 + 子串通配 + 白名单例外”(isSensitiveKeyName),
  229. // 并叠加按值形态的连接串脱敏,以覆盖数据库连接串等自定义命名的敏感信息。
  230. return redactConnectionStringCredentials(rawContent)
  231. .replace(
  232. JSON_STYLE_SENSITIVE_VALUE_REGEX,
  233. (match, quote: string, keyName: string, separator: string, rawValue: string) =>
  234. isSensitiveKeyName(keyName)
  235. ? `${quote}${keyName}${quote}${separator}${redactValue(rawValue)}`
  236. : match,
  237. )
  238. .replace(
  239. ASSIGNMENT_STYLE_SENSITIVE_VALUE_REGEX,
  240. (match, prefix: string, keyName: string, separator: string, rawValue: string) =>
  241. isSensitiveKeyName(keyName)
  242. ? `${prefix}${keyName}${separator}${redactValue(rawValue)}`
  243. : match,
  244. )
  245. .replace(
  246. HEADER_STYLE_SENSITIVE_VALUE_REGEX,
  247. (match, prefix: string, headerName: string, separator: string, rawValue: string) =>
  248. isSensitiveKeyName(headerName)
  249. ? `${prefix}${headerName}${separator}${redactHeaderValue(rawValue)}`
  250. : match,
  251. )
  252. .replace(BEARER_TOKEN_REGEX, `$1${REDACTED_PLACEHOLDER}`)
  253. .replace(QUERY_TOKEN_REGEX, `$1${REDACTED_PLACEHOLDER}`);
  254. }
  255. function detectUtf16EncodingByNullPattern(sample: Buffer): SupportedTextEncoding | null {
  256. if (sample.length < 4) {
  257. return null;
  258. }
  259. let evenByteCount = 0;
  260. let oddByteCount = 0;
  261. let evenNullCount = 0;
  262. let oddNullCount = 0;
  263. for (let index = 0; index < sample.length; index += 1) {
  264. if (index % 2 === 0) {
  265. evenByteCount += 1;
  266. if (sample[index] === 0) {
  267. evenNullCount += 1;
  268. }
  269. continue;
  270. }
  271. oddByteCount += 1;
  272. if (sample[index] === 0) {
  273. oddNullCount += 1;
  274. }
  275. }
  276. const evenNullRatio = evenNullCount / Math.max(evenByteCount, 1);
  277. const oddNullRatio = oddNullCount / Math.max(oddByteCount, 1);
  278. const likelyUtf16Ratio = 0.3;
  279. const noiseThreshold = 0.1;
  280. if (oddNullRatio >= likelyUtf16Ratio && evenNullRatio <= noiseThreshold) {
  281. return "utf-16le";
  282. }
  283. if (evenNullRatio >= likelyUtf16Ratio && oddNullRatio <= noiseThreshold) {
  284. return "utf-16be";
  285. }
  286. return null;
  287. }
  288. function isLikelyAsciiTextByte(byteValue: number): boolean {
  289. return (
  290. byteValue === 0x09 ||
  291. byteValue === 0x0a ||
  292. byteValue === 0x0d ||
  293. (byteValue >= 0x20 && byteValue <= 0x7e)
  294. );
  295. }
  296. function isPreferredTextCodePoint(codePoint: number): boolean {
  297. if (codePoint === 0x09 || codePoint === 0x0a || codePoint === 0x0d || codePoint === 0x20) {
  298. return true;
  299. }
  300. if (codePoint >= 0x20 && codePoint <= 0x7e) {
  301. return true;
  302. }
  303. if (codePoint >= 0x4e00 && codePoint <= 0x9fff) {
  304. return true;
  305. }
  306. if (codePoint >= 0x3400 && codePoint <= 0x4dbf) {
  307. return true;
  308. }
  309. if (codePoint >= 0x3000 && codePoint <= 0x303f) {
  310. return true;
  311. }
  312. if (codePoint >= 0xff00 && codePoint <= 0xffef) {
  313. return true;
  314. }
  315. if (codePoint >= 0x3040 && codePoint <= 0x30ff) {
  316. return true;
  317. }
  318. if (codePoint >= 0xac00 && codePoint <= 0xd7af) {
  319. return true;
  320. }
  321. return false;
  322. }
  323. function scoreDecodedTextForEncodingDetection(decodedText: string): TextDecodingScore {
  324. let totalCodePointCount = 0;
  325. let preferredCodePointCount = 0;
  326. let invalidCodePointCount = 0;
  327. for (const character of decodedText) {
  328. totalCodePointCount += 1;
  329. const codePoint = character.codePointAt(0) ?? 0;
  330. if (
  331. codePoint === 0xfffd ||
  332. codePoint === 0 ||
  333. codePoint === 0x7f ||
  334. (codePoint >= 0xd800 && codePoint <= 0xdfff) ||
  335. (codePoint <= 0x1f && codePoint !== 0x09 && codePoint !== 0x0a && codePoint !== 0x0d)
  336. ) {
  337. invalidCodePointCount += 1;
  338. continue;
  339. }
  340. if (isPreferredTextCodePoint(codePoint)) {
  341. preferredCodePointCount += 1;
  342. }
  343. }
  344. const denominator = Math.max(totalCodePointCount, 1);
  345. return {
  346. preferredCharRatio: preferredCodePointCount / denominator,
  347. invalidCharRatio: invalidCodePointCount / denominator,
  348. };
  349. }
  350. function detectUtf16EncodingByDecodedTextScore(sample: Buffer): SupportedTextEncoding | null {
  351. if (sample.length < 4) {
  352. return null;
  353. }
  354. const normalizedSampleLength = sample.length - (sample.length % 2);
  355. if (normalizedSampleLength < 4) {
  356. return null;
  357. }
  358. const normalizedSample = sample.subarray(0, normalizedSampleLength);
  359. const utf16LeScore = scoreDecodedTextForEncodingDetection(
  360. new TextDecoder("utf-16le").decode(normalizedSample),
  361. );
  362. const utf16BeScore = scoreDecodedTextForEncodingDetection(
  363. new TextDecoder("utf-16be").decode(normalizedSample),
  364. );
  365. const minimumPreferredCharRatio = 0.55;
  366. const maximumInvalidCharRatio = 0.2;
  367. const minimumPreferredCharRatioGap = 0.08;
  368. const utf16LeQualified =
  369. utf16LeScore.preferredCharRatio >= minimumPreferredCharRatio &&
  370. utf16LeScore.invalidCharRatio <= maximumInvalidCharRatio;
  371. const utf16BeQualified =
  372. utf16BeScore.preferredCharRatio >= minimumPreferredCharRatio &&
  373. utf16BeScore.invalidCharRatio <= maximumInvalidCharRatio;
  374. if (utf16LeQualified && !utf16BeQualified) {
  375. return "utf-16le";
  376. }
  377. if (utf16BeQualified && !utf16LeQualified) {
  378. return "utf-16be";
  379. }
  380. if (!utf16LeQualified && !utf16BeQualified) {
  381. return null;
  382. }
  383. const preferredRatioGap = Math.abs(
  384. utf16LeScore.preferredCharRatio - utf16BeScore.preferredCharRatio,
  385. );
  386. if (preferredRatioGap >= minimumPreferredCharRatioGap) {
  387. return utf16LeScore.preferredCharRatio > utf16BeScore.preferredCharRatio
  388. ? "utf-16le"
  389. : "utf-16be";
  390. }
  391. return utf16LeScore.invalidCharRatio <= utf16BeScore.invalidCharRatio ? "utf-16le" : "utf-16be";
  392. }
  393. function isValidUtf8Sample(sample: Buffer): boolean {
  394. try {
  395. new TextDecoder("utf-8", { fatal: true }).decode(sample);
  396. return true;
  397. } catch {
  398. return false;
  399. }
  400. }
  401. function detectUtf16EncodingByAsciiPairPattern(sample: Buffer): SupportedTextEncoding | null {
  402. if (sample.length < 4) {
  403. return null;
  404. }
  405. let utf16LeRunLength = 0;
  406. let utf16BeRunLength = 0;
  407. let utf16LeAsciiRunScore = 0;
  408. let utf16BeAsciiRunScore = 0;
  409. // CJK 文本里会出现“单个码元低字节刚好是 0”的情况(如 U+4E00),
  410. // 直接统计 `0x00 + ASCII` 配对会把这些离散噪声误判成另一端字节序。
  411. // 这里改为统计“连续 ASCII-零字节 run”,只把成段英文 token(api key/header)作为有效信号。
  412. const flushRunScore = (runLength: number): number => (runLength >= 3 ? runLength : 0);
  413. for (let index = 0; index + 1 < sample.length; index += 2) {
  414. const leftByte = sample[index] ?? 0;
  415. const rightByte = sample[index + 1] ?? 0;
  416. if (rightByte === 0 && isLikelyAsciiTextByte(leftByte)) {
  417. utf16LeRunLength += 1;
  418. utf16BeAsciiRunScore += flushRunScore(utf16BeRunLength);
  419. utf16BeRunLength = 0;
  420. continue;
  421. }
  422. if (leftByte === 0 && isLikelyAsciiTextByte(rightByte)) {
  423. utf16BeRunLength += 1;
  424. utf16LeAsciiRunScore += flushRunScore(utf16LeRunLength);
  425. utf16LeRunLength = 0;
  426. continue;
  427. }
  428. utf16LeAsciiRunScore += flushRunScore(utf16LeRunLength);
  429. utf16BeAsciiRunScore += flushRunScore(utf16BeRunLength);
  430. utf16LeRunLength = 0;
  431. utf16BeRunLength = 0;
  432. }
  433. utf16LeAsciiRunScore += flushRunScore(utf16LeRunLength);
  434. utf16BeAsciiRunScore += flushRunScore(utf16BeRunLength);
  435. const minimumAsciiRunScore = 6;
  436. const dominanceRatio = 1.5;
  437. if (
  438. utf16LeAsciiRunScore >= minimumAsciiRunScore &&
  439. utf16LeAsciiRunScore >= utf16BeAsciiRunScore * dominanceRatio
  440. ) {
  441. return "utf-16le";
  442. }
  443. if (
  444. utf16BeAsciiRunScore >= minimumAsciiRunScore &&
  445. utf16BeAsciiRunScore >= utf16LeAsciiRunScore * dominanceRatio
  446. ) {
  447. return "utf-16be";
  448. }
  449. return null;
  450. }
  451. function detectTextFileEncoding(sample: Buffer): TextFileEncodingInfo | null {
  452. if (sample.length === 0) {
  453. return { encoding: "utf-8", bomLength: 0, bomBytes: EMPTY_BOM };
  454. }
  455. if (sample.length >= 3 && sample[0] === 0xef && sample[1] === 0xbb && sample[2] === 0xbf) {
  456. return {
  457. encoding: "utf-8",
  458. bomLength: 3,
  459. bomBytes: Buffer.from([0xef, 0xbb, 0xbf]),
  460. };
  461. }
  462. if (sample.length >= 2 && sample[0] === 0xff && sample[1] === 0xfe) {
  463. return {
  464. encoding: "utf-16le",
  465. bomLength: 2,
  466. bomBytes: Buffer.from([0xff, 0xfe]),
  467. };
  468. }
  469. if (sample.length >= 2 && sample[0] === 0xfe && sample[1] === 0xff) {
  470. return {
  471. encoding: "utf-16be",
  472. bomLength: 2,
  473. bomBytes: Buffer.from([0xfe, 0xff]),
  474. };
  475. }
  476. if (!sample.includes(0) && isValidUtf8Sample(sample)) {
  477. return { encoding: "utf-8", bomLength: 0, bomBytes: EMPTY_BOM };
  478. }
  479. // CJK 占比高的 UTF-16 无 BOM 文本,空字节比例可能很低,
  480. // 仅靠 null-ratio 会被误判为“非文本”并走原样复制,导致敏感字段漏脱敏。
  481. // 这里增加“ASCII-零字节对”兜底检测(例如 `OPENAI_API_KEY=\r\n`),覆盖真实日志中的混合文本场景。
  482. const utf16Encoding =
  483. detectUtf16EncodingByAsciiPairPattern(sample) ??
  484. detectUtf16EncodingByNullPattern(sample) ??
  485. detectUtf16EncodingByDecodedTextScore(sample);
  486. if (!utf16Encoding) {
  487. // 无 BOM 且不含空字节的 UTF-16 文本,在纯 CJK 内容里经常出现。
  488. // 这类样本 UTF-8 fatal decode 会失败;此时按 UTF-8 处理会产生乱码并漏掉敏感字段匹配。
  489. // 兜底策略:UTF-8 合法则按 UTF-8,非法且无法识别成 UTF-16 时才视为二进制。
  490. if (isValidUtf8Sample(sample)) {
  491. return { encoding: "utf-8", bomLength: 0, bomBytes: EMPTY_BOM };
  492. }
  493. return null;
  494. }
  495. return { encoding: utf16Encoding, bomLength: 0, bomBytes: EMPTY_BOM };
  496. }
  497. async function readFileSample(
  498. absolutePath: string,
  499. sampleBytes = TEXT_DETECTION_SAMPLE_BYTES,
  500. ): Promise<Buffer> {
  501. const fileHandle = await open(absolutePath, "r");
  502. try {
  503. const buffer = Buffer.alloc(sampleBytes);
  504. const { bytesRead } = await fileHandle.read(buffer, 0, sampleBytes, 0);
  505. return buffer.subarray(0, bytesRead);
  506. } finally {
  507. await fileHandle.close();
  508. }
  509. }
  510. function encodeTextWithEncoding(text: string, encoding: SupportedTextEncoding): Buffer {
  511. if (encoding === "utf-8") {
  512. return Buffer.from(text, "utf-8");
  513. }
  514. if (encoding === "utf-16le") {
  515. return Buffer.from(text, "utf16le");
  516. }
  517. const encodedBuffer = Buffer.from(text, "utf16le");
  518. encodedBuffer.swap16();
  519. return encodedBuffer;
  520. }
  521. function splitByCompleteLine(content: string): {
  522. completeChunk: string;
  523. pendingChunk: string;
  524. } {
  525. const lastLineFeedIndex = content.lastIndexOf("\n");
  526. if (lastLineFeedIndex >= 0) {
  527. return {
  528. completeChunk: content.slice(0, lastLineFeedIndex + 1),
  529. pendingChunk: content.slice(lastLineFeedIndex + 1),
  530. };
  531. }
  532. const lastCarriageReturnIndex = content.lastIndexOf("\r");
  533. if (lastCarriageReturnIndex >= 0 && lastCarriageReturnIndex < content.length - 1) {
  534. return {
  535. completeChunk: content.slice(0, lastCarriageReturnIndex + 1),
  536. pendingChunk: content.slice(lastCarriageReturnIndex + 1),
  537. };
  538. }
  539. return { completeChunk: "", pendingChunk: content };
  540. }
  541. function createSensitiveContentSanitizerTransform(encoding: SupportedTextEncoding): Transform {
  542. const decoder = new TextDecoder(encoding);
  543. let pendingChunk = "";
  544. return new Transform({
  545. transform(chunk, _chunkEncoding, callback) {
  546. try {
  547. const rawChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
  548. const decodedChunk = decoder.decode(rawChunk, { stream: true });
  549. const mergedChunk = `${pendingChunk}${decodedChunk}`;
  550. const { completeChunk, pendingChunk: nextPendingChunk } = splitByCompleteLine(mergedChunk);
  551. pendingChunk = nextPendingChunk;
  552. if (completeChunk.length === 0) {
  553. callback();
  554. return;
  555. }
  556. const sanitizedChunk = sanitizeSensitiveLogContent(completeChunk);
  557. callback(null, encodeTextWithEncoding(sanitizedChunk, encoding));
  558. } catch (error) {
  559. callback(error as Error);
  560. }
  561. },
  562. flush(callback) {
  563. try {
  564. const remainingContent = `${pendingChunk}${decoder.decode()}`;
  565. if (remainingContent.length === 0) {
  566. callback();
  567. return;
  568. }
  569. const sanitizedChunk = sanitizeSensitiveLogContent(remainingContent);
  570. callback(null, encodeTextWithEncoding(sanitizedChunk, encoding));
  571. } catch (error) {
  572. callback(error as Error);
  573. }
  574. },
  575. });
  576. }
  577. async function sanitizeTextLogFileToDestination(
  578. sourcePath: string,
  579. destinationPath: string,
  580. encodingInfo: TextFileEncodingInfo,
  581. ): Promise<void> {
  582. const readStream = createReadStream(sourcePath, {
  583. start: encodingInfo.bomLength,
  584. });
  585. const writeStream = createWriteStream(destinationPath);
  586. if (encodingInfo.bomLength > 0) {
  587. writeStream.write(encodingInfo.bomBytes);
  588. }
  589. await pipeline(
  590. readStream,
  591. createSensitiveContentSanitizerTransform(encodingInfo.encoding),
  592. writeStream,
  593. );
  594. }
  595. function isExcludedCachePath(relativePath: string): boolean {
  596. const normalizedRelativePath = normalizeArchivePath(relativePath);
  597. return (
  598. normalizedRelativePath === "Library/Caches" ||
  599. normalizedRelativePath.startsWith("Library/Caches/")
  600. );
  601. }
  602. function isRetiredAcpRuntimePath(relativePath: string): boolean {
  603. const normalizedRelativePath = normalizeArchivePath(relativePath);
  604. return RETIRED_ACP_RUNTIME_ARCHIVE_PATHS.some(
  605. (archivePath) =>
  606. normalizedRelativePath === archivePath ||
  607. normalizedRelativePath.startsWith(`${archivePath}/`),
  608. );
  609. }
  610. function isHighVolumeRuntimeArchivePath(relativePath: string): boolean {
  611. const normalizedRelativePath = normalizeArchivePath(relativePath);
  612. return HIGH_VOLUME_RUNTIME_ARCHIVE_PATHS.some(
  613. (archivePath) =>
  614. normalizedRelativePath === archivePath ||
  615. normalizedRelativePath.startsWith(`${archivePath}/`),
  616. );
  617. }
  618. function isDocshotArchivePath(relativePath: string): boolean {
  619. const normalizedRelativePath = normalizeArchivePath(relativePath);
  620. const firstSegment = normalizedRelativePath.split("/")[0] ?? "";
  621. if (DOCSHOT_ARCHIVE_PATHS.includes(firstSegment as (typeof DOCSHOT_ARCHIVE_PATHS)[number])) {
  622. return true;
  623. }
  624. return DOCSHOT_ARCHIVE_PATH_PREFIXES.some((prefix) => firstSegment.startsWith(prefix));
  625. }
  626. function isNonLogStateArchivePath(relativePath: string): boolean {
  627. const normalizedRelativePath = normalizeArchivePath(relativePath);
  628. return NON_LOG_STATE_ARCHIVE_PATHS.some(
  629. (archivePath) =>
  630. normalizedRelativePath === archivePath ||
  631. normalizedRelativePath.startsWith(`${archivePath}/`),
  632. );
  633. }
  634. function isSensitiveCredentialArchivePath(relativePath: string): boolean {
  635. const normalizedRelativePath = normalizeArchivePath(relativePath).toLowerCase();
  636. const fileName = normalizedRelativePath.split("/").at(-1) ?? "";
  637. return SENSITIVE_CREDENTIAL_ARCHIVE_FILE_NAMES.has(fileName);
  638. }
  639. function isExcludedDirectoryArchivePath(relativePath: string): boolean {
  640. const normalizedRelativePath = normalizeArchivePath(relativePath).toLowerCase();
  641. return normalizedRelativePath
  642. .split("/")
  643. .some((segment) => EXCLUDED_ARCHIVE_DIRECTORY_NAMES.has(segment));
  644. }
  645. function isExcludedRelativePath(relativePath: string): boolean {
  646. const normalizedRelativePath = normalizeArchivePath(relativePath);
  647. // 完整日志导出过去只做内容脱敏,仍会把 credentials.json 文件本身放进包。
  648. // 凭据存储文件不是排障日志,且不同提供商可能复用同名文件;因此在收集清单阶段按文件名跳过。
  649. if (isSensitiveCredentialArchivePath(normalizedRelativePath)) {
  650. return true;
  651. }
  652. // debug 目录通常是模型/运行时高频轨迹,不是用户要交付的日志包材料。
  653. // 过去显式收集 ~/.zcode/cli/debug 会把这类上下文带进手动导出和反馈完整日志,这里按目录段统一跳过。
  654. if (isExcludedDirectoryArchivePath(normalizedRelativePath)) {
  655. return true;
  656. }
  657. if (isNonLogStateArchivePath(normalizedRelativePath)) {
  658. return true;
  659. }
  660. // ~/.zcode/v2/dev 保存 stdio-traffic 等高频协议流,真实机器上会累计到 GB 级。
  661. // 远超反馈附件的大小上限,不应随诊断包带出。
  662. if (isHighVolumeRuntimeArchivePath(normalizedRelativePath)) {
  663. return true;
  664. }
  665. // docshot 历史备份和素材目录体积可达 GB 级,
  666. // 且不属于用户反馈所需的诊断日志。
  667. if (isDocshotArchivePath(normalizedRelativePath)) {
  668. return true;
  669. }
  670. // ACP runtime 目录已退役,老用户数据里仍可能残留数百 MB 抓包和旧鉴权文件。
  671. // 当前运行态配置已经迁到 agent-config;继续导出这些旧目录会让导出长时间无反馈,还可能带出旧代理证书私钥。
  672. if (isRetiredAcpRuntimePath(normalizedRelativePath)) {
  673. return true;
  674. }
  675. // Library/Caches 是运行时缓存,不是排障所需日志;导出它只会放大日志包。
  676. if (isExcludedCachePath(normalizedRelativePath)) {
  677. return true;
  678. }
  679. return ZIP_EXCLUDE_REGEXES.some((pattern) => pattern.test(normalizedRelativePath));
  680. }
  681. function shouldApplyLogExportRetention(archivePath: string): boolean {
  682. const normalizedArchivePath = normalizeArchivePath(archivePath);
  683. if (
  684. normalizedArchivePath.startsWith("logs/") ||
  685. normalizedArchivePath.startsWith(".zcode/cli/log/")
  686. ) {
  687. return true;
  688. }
  689. return false;
  690. }
  691. async function filterRecentLogArchiveFiles(
  692. files: LogArchiveFileEntry[],
  693. options: CreateLogArchiveArtifactsOptions = {},
  694. ): Promise<LogArchiveFileEntry[]> {
  695. const lookbackDays = options.lookbackDays ?? DEFAULT_LOG_EXPORT_LOOKBACK_DAYS;
  696. if (lookbackDays <= 0) {
  697. return files;
  698. }
  699. const now = options.now ?? (() => new Date());
  700. const cutoffMs = now().getTime() - lookbackDays * MILLISECONDS_PER_DAY;
  701. const recentFiles: LogArchiveFileEntry[] = [];
  702. for (const file of files) {
  703. if (!shouldApplyLogExportRetention(file.archivePath)) {
  704. recentFiles.push(file);
  705. continue;
  706. }
  707. const fileStats = await stat(file.absolutePath).catch(() => null);
  708. // 导出日志过去按目录全量打包,长时间运行后旧 diagnostics 会把日志包放大到数百 MB。
  709. // 这里仅对“可由时间窗口复现现场”的日志类文件按 mtime 保留近 3 天;
  710. // settings 等排障配置不参与过滤,避免久未修改但仍影响当前行为的配置丢失。
  711. if (fileStats?.isFile() && fileStats.mtimeMs >= cutoffMs) {
  712. recentFiles.push(file);
  713. }
  714. }
  715. return recentFiles;
  716. }
  717. function createAboutContent(): string {
  718. const snapshot = createAboutSnapshot({ buildMetadata: readBuildMetadata() });
  719. return formatAboutDetail(snapshot);
  720. }
  721. function formatErrorMessage(error: unknown): string {
  722. return error instanceof Error ? error.message : String(error);
  723. }
  724. function logSkippedLogArchiveDirectory(
  725. absolutePath: string,
  726. archivePath: string,
  727. error: unknown,
  728. ): void {
  729. logger.warn("[export-logs] 日志目录不可读,已在导出时自动跳过", {
  730. absolutePath,
  731. archivePath,
  732. error: formatErrorMessage(error),
  733. });
  734. }
  735. async function walkLogArchiveDirectory(
  736. absoluteDir: string,
  737. relativeDir: string,
  738. visitedDirs: Set<string>,
  739. files: LogArchiveFileEntry[],
  740. ): Promise<void> {
  741. const resolvedDir = await realpath(absoluteDir).catch(() => absoluteDir);
  742. if (visitedDirs.has(resolvedDir)) {
  743. return;
  744. }
  745. visitedDirs.add(resolvedDir);
  746. const dirents = await readdir(absoluteDir, { withFileTypes: true }).catch((error: unknown) => {
  747. // 用户目录下的日志来源可能包含被系统或第三方 CLI 限制权限的子目录。
  748. // 单个目录 scandir 失败时跳过该目录,避免一次 EACCES 把整个日志包导出中断。
  749. logSkippedLogArchiveDirectory(absoluteDir, relativeDir, error);
  750. return null;
  751. });
  752. if (!dirents) {
  753. return;
  754. }
  755. dirents.sort((left, right) => left.name.localeCompare(right.name));
  756. for (const dirent of dirents) {
  757. const archivePath = relativeDir ? posix.join(relativeDir, dirent.name) : dirent.name;
  758. if (isExcludedRelativePath(archivePath)) {
  759. continue;
  760. }
  761. const absolutePath = join(absoluteDir, dirent.name);
  762. if (dirent.isDirectory()) {
  763. await walkLogArchiveDirectory(absolutePath, archivePath, visitedDirs, files);
  764. continue;
  765. }
  766. if (dirent.isFile()) {
  767. files.push({ absolutePath, archivePath });
  768. continue;
  769. }
  770. if (!dirent.isSymbolicLink()) {
  771. continue;
  772. }
  773. const targetStats = await stat(absolutePath).catch(() => null);
  774. if (!targetStats) {
  775. continue;
  776. }
  777. // 日志目录里存在 provider 共享资源的软链入口。
  778. // 这里按目标类型处理并配合 realpath 去重,避免递归跟随时把同一份内容重复打进包,甚至形成循环遍历。
  779. if (targetStats.isDirectory()) {
  780. await walkLogArchiveDirectory(absolutePath, archivePath, visitedDirs, files);
  781. continue;
  782. }
  783. if (targetStats.isFile()) {
  784. files.push({ absolutePath, archivePath });
  785. }
  786. }
  787. }
  788. async function collectLogArchiveFilesFromDirectory(
  789. absoluteDir: string,
  790. relativeDir: string,
  791. visitedDirs: Set<string>,
  792. files: LogArchiveFileEntry[],
  793. ): Promise<void> {
  794. const directoryStats = await stat(absoluteDir).catch(() => null);
  795. if (!directoryStats?.isDirectory()) {
  796. return;
  797. }
  798. await walkLogArchiveDirectory(absoluteDir, relativeDir, visitedDirs, files);
  799. }
  800. /**
  801. * 按文件名白名单收集单层目录,不递归。用于运行目录这类"诊断文件与凭据同放"的场景:
  802. * 递归收集会把 .tokens 之类的机密带进用户会转发出去的日志包,而 EXCLUDED 名单是
  803. * 事后补救、天然滞后。白名单则默认拒绝——目录里以后多出什么都不会跟着漏出去。
  804. */
  805. async function collectLogArchiveFilesByName(
  806. absoluteDir: string,
  807. relativeDir: string,
  808. isCollectableFileName: (fileName: string) => boolean,
  809. files: LogArchiveFileEntry[],
  810. ): Promise<void> {
  811. const dirents = await readdir(absoluteDir, { withFileTypes: true }).catch(() => null);
  812. if (!dirents) {
  813. return;
  814. }
  815. dirents.sort((left, right) => left.name.localeCompare(right.name));
  816. for (const dirent of dirents) {
  817. if (!dirent.isFile() || !isCollectableFileName(dirent.name)) {
  818. continue;
  819. }
  820. await collectLogArchiveFile(
  821. join(absoluteDir, dirent.name),
  822. posix.join(relativeDir, dirent.name),
  823. files,
  824. );
  825. }
  826. }
  827. async function collectLogArchiveFile(
  828. absolutePath: string,
  829. archivePath: string,
  830. files: LogArchiveFileEntry[],
  831. ): Promise<void> {
  832. if (isExcludedRelativePath(archivePath)) {
  833. return;
  834. }
  835. const fileStats = await stat(absolutePath).catch(() => null);
  836. if (!fileStats?.isFile()) {
  837. return;
  838. }
  839. files.push({ absolutePath, archivePath });
  840. }
  841. export async function collectLogArchiveFiles(sourceDir: string): Promise<LogArchiveFileEntry[]> {
  842. const files: LogArchiveFileEntry[] = [];
  843. const visitedDirs = new Set<string>();
  844. await collectLogArchiveFilesFromDirectory(sourceDir, "", visitedDirs, files);
  845. files.sort((left, right) => left.archivePath.localeCompare(right.archivePath));
  846. return files;
  847. }
  848. export async function createLogArchiveArtifacts(
  849. sourceDir: string,
  850. options: CreateLogArchiveArtifactsOptions = {},
  851. ): Promise<LogArchiveArtifacts> {
  852. const files: LogArchiveFileEntry[] = [];
  853. const visitedDirs = new Set<string>();
  854. await collectLogArchiveFilesFromDirectory(sourceDir, "", visitedDirs, files);
  855. const zcodeCliLogDir = getZCodeCliLogDir();
  856. // GLM / zcode-cli 的运行日志写在 ~/.zcode/cli/log,不在应用主数据目录 ~/.zcode/v2 下。
  857. // 如果导出日志只扫描 v2,定位 agent CLI 启动、协议或崩溃问题时会缺少最关键的原生侧日志。
  858. await collectLogArchiveFilesFromDirectory(
  859. zcodeCliLogDir,
  860. posix.join(".zcode", "cli", "log"),
  861. visitedDirs,
  862. files,
  863. );
  864. const zcodeCliDir = getZCodeCliDir();
  865. // 排查 agent CLI 问题还需要它的运行配置与模型 IO 轨迹。
  866. // config.json 是当前生效配置;rollout 是 model-io 调用轨迹,
  867. // 二者都不在 ~/.zcode/cli/log 下,需要额外收集才能完整还原现场。
  868. await collectLogArchiveFile(
  869. join(zcodeCliDir, "config.json"),
  870. posix.join(".zcode", "cli", "config.json"),
  871. files,
  872. );
  873. await collectLogArchiveFilesFromDirectory(
  874. join(zcodeCliDir, "rollout"),
  875. posix.join(".zcode", "cli", "rollout"),
  876. visitedDirs,
  877. files,
  878. );
  879. // Computer Use Helper 的结构化诊断必须进日志包:否则反馈包里
  880. // grep "background keyboard begin rejected" 命中 0,
  881. // 因为 Helper 由 LaunchServices 启动、stderr 被系统丢弃,它把诊断 tee 到
  882. // ~/.zcode/computer-use/run/<socket>.exit.log,既不在 app data 也不在 ~/.zcode/cli 下。
  883. // 同目录下有 .tokens broker 凭据,因此按文件名白名单只收 *.exit.log,不递归该目录。
  884. await collectLogArchiveFilesByName(
  885. getCuaHelperRunDir(),
  886. posix.join(".zcode", "computer-use", "run"),
  887. isCuaHelperDiagnosticFileName,
  888. files,
  889. );
  890. const recentFiles = await filterRecentLogArchiveFiles(files, options);
  891. recentFiles.sort((left, right) => left.archivePath.localeCompare(right.archivePath));
  892. return {
  893. files: recentFiles,
  894. aboutContent: createAboutContent(),
  895. };
  896. }
  897. async function copyLogArchiveFilesToDirectory(
  898. outputPath: string,
  899. files: LogArchiveFileEntry[],
  900. ): Promise<LogArchiveSkippedFileEntry[]> {
  901. const skippedFiles: LogArchiveSkippedFileEntry[] = [];
  902. for (const file of files) {
  903. const destinationPath = join(outputPath, ...file.archivePath.split("/"));
  904. await mkdir(dirname(destinationPath), { recursive: true });
  905. const sourceStats = await stat(file.absolutePath).catch((error: unknown) => {
  906. skippedFiles.push({
  907. absolutePath: file.absolutePath,
  908. archivePath: file.archivePath,
  909. error: formatErrorMessage(error),
  910. });
  911. return null;
  912. });
  913. if (!sourceStats?.isFile()) {
  914. continue;
  915. }
  916. const sourceReadable = await access(file.absolutePath, constants.R_OK)
  917. .then(() => true)
  918. .catch((error: unknown) => {
  919. skippedFiles.push({
  920. absolutePath: file.absolutePath,
  921. archivePath: file.archivePath,
  922. error: formatErrorMessage(error),
  923. });
  924. return false;
  925. });
  926. if (!sourceReadable) {
  927. continue;
  928. }
  929. try {
  930. // 这里改为“采样识别编码 + 流式脱敏”,避免全量 readFile 带来的大文件内存峰值。
  931. // 同时显式支持 UTF-16 文本(含 BOM/无 BOM 常见形态),防止被误判成二进制后原样泄露敏感字段。
  932. const sourceSample = await readFileSample(file.absolutePath);
  933. const textEncodingInfo = detectTextFileEncoding(sourceSample);
  934. if (!textEncodingInfo) {
  935. await copyFile(file.absolutePath, destinationPath);
  936. } else {
  937. await sanitizeTextLogFileToDestination(
  938. file.absolutePath,
  939. destinationPath,
  940. textEncodingInfo,
  941. );
  942. }
  943. } catch (error) {
  944. const sourceStatsAfterFailure = await stat(file.absolutePath).catch(() => null);
  945. const sourceReadableAfterFailure = sourceStatsAfterFailure?.isFile()
  946. ? await access(file.absolutePath, constants.R_OK)
  947. .then(() => true)
  948. .catch(() => false)
  949. : false;
  950. // telemetry/agent 日志文件可能在“扫描完待导出列表”之后被后台轮转、删除或改权限,
  951. // 软链目标也可能在这段窗口里失效。复制失败后再核一次源文件可读性;
  952. // 如果源头已经不可读,就把它当成坏文件跳过,避免单个 ENOENT/EACCES 让导出整体失败。
  953. if (!sourceReadableAfterFailure) {
  954. skippedFiles.push({
  955. absolutePath: file.absolutePath,
  956. archivePath: file.archivePath,
  957. error: formatErrorMessage(error),
  958. });
  959. continue;
  960. }
  961. throw error;
  962. }
  963. }
  964. return skippedFiles;
  965. }
  966. function logSkippedLogArchiveFiles(skippedFiles: LogArchiveSkippedFileEntry[]): void {
  967. if (skippedFiles.length === 0) {
  968. return;
  969. }
  970. logger.warn("[export-logs] 检测到不可读日志文件,已在导出时自动跳过", {
  971. skippedCount: skippedFiles.length,
  972. skippedFiles: skippedFiles.slice(0, 10),
  973. });
  974. }
  975. export async function writeLogArchiveZip(
  976. outputPath: string,
  977. artifacts: LogArchiveArtifacts,
  978. options: WriteLogArchiveZipOptions = {},
  979. ): Promise<void> {
  980. const stageRootDir = options.stageRootDir ?? getDefaultExportLogStageDir();
  981. await mkdir(stageRootDir, { recursive: true });
  982. const stagingDir = await mkdtemp(join(stageRootDir, "stage-"));
  983. try {
  984. // yazl.addFile 内部会再次对源路径执行 fs.stat/createReadStream。
  985. // 对于软链目标或正在被轮转的 telemetry 文件,这一步仍然可能异步抛错并触发未监听的 error 事件。
  986. // 这里先把可读文件稳定复制到临时目录,再从临时目录压缩,保证 zip 阶段只面对我们自己控制的常规文件。
  987. await writeLogArchiveDirectory(stagingDir, artifacts);
  988. const zipFile = new ZipFile();
  989. const stageFiles = await collectLogArchiveFiles(stagingDir);
  990. const outputStream = createWriteStream(outputPath);
  991. zipFile.once("error", (error) => {
  992. outputStream.destroy(error instanceof Error ? error : new Error(String(error)));
  993. });
  994. for (const file of stageFiles) {
  995. zipFile.addFile(file.absolutePath, file.archivePath);
  996. }
  997. const writePromise = pipeline(zipFile.outputStream, outputStream);
  998. zipFile.end();
  999. await writePromise;
  1000. } finally {
  1001. await rm(stagingDir, { recursive: true, force: true }).catch(() => {});
  1002. }
  1003. }
  1004. export async function writeLogArchiveDirectory(
  1005. outputPath: string,
  1006. artifacts: LogArchiveArtifacts,
  1007. ): Promise<void> {
  1008. await mkdir(outputPath, { recursive: true });
  1009. const skippedFiles = await copyLogArchiveFilesToDirectory(outputPath, artifacts.files);
  1010. logSkippedLogArchiveFiles(skippedFiles);
  1011. await writeFile(join(outputPath, "about.txt"), artifacts.aboutContent, "utf-8");
  1012. }
  1013. export async function createFeedbackLogArchiveFromExportLogs(
  1014. sourceDir: string,
  1015. options: CreateFeedbackLogArchiveFromExportLogsOptions = {},
  1016. ): Promise<{ path: string; size: number }> {
  1017. return createFeedbackDiagnosticArchive({
  1018. sources: [
  1019. { directory: join(sourceDir, "logs"), archivePrefix: "logs" },
  1020. { directory: getZCodeCliLogDir(), archivePrefix: ".zcode/cli/log" },
  1021. {
  1022. directory: getZCodeCliDir(),
  1023. archivePrefix: ".zcode/cli",
  1024. includeFileNames: ["config.json"],
  1025. onlyCurrentDay: false,
  1026. contentPolicy: "cli-config",
  1027. },
  1028. {
  1029. directory: join(getZCodeCliDir(), "rollout"),
  1030. archivePrefix: ".zcode/cli/rollout",
  1031. },
  1032. {
  1033. directory: getCuaHelperRunDir(),
  1034. archivePrefix: ".zcode/computer-use/run",
  1035. exitLogsOnly: true,
  1036. },
  1037. ],
  1038. outputRootDir: options.outputRootDir ?? getDefaultFeedbackLogArchiveDir(),
  1039. now: options.now,
  1040. onProgress: options.onProgress,
  1041. });
  1042. }
  1043. export async function exportLogs(
  1044. dependencies: ExportLogsDependencies = {},
  1045. ): Promise<{ success: boolean; path?: string; error?: string }> {
  1046. try {
  1047. const now = dependencies.now ?? (() => new Date());
  1048. const getSourceDir = dependencies.getZCodeDataDir ?? getZCodeDataDir;
  1049. const buildArtifacts = dependencies.createLogArchiveArtifacts ?? createLogArchiveArtifacts;
  1050. const writeZip = dependencies.writeLogArchiveZip ?? writeLogArchiveZip;
  1051. const writeDirectory = dependencies.writeLogArchiveDirectory ?? writeLogArchiveDirectory;
  1052. const showItemInFolder =
  1053. dependencies.showItemInFolder ??
  1054. (async (path: string) => {
  1055. const { shell } = await import("electron");
  1056. shell.showItemInFolder(path);
  1057. });
  1058. const getStageRootDir = dependencies.getExportLogStageDir ?? getDefaultExportLogStageDir;
  1059. const getOutputRootDir = dependencies.getExportLogDir ?? getDefaultExportLogDir;
  1060. const sourceDir = getSourceDir();
  1061. const timestamp = formatTimestamp(now());
  1062. const exportBaseName = `zcode-logs-${timestamp}`;
  1063. const outputRootDir = getOutputRootDir();
  1064. await mkdir(outputRootDir, { recursive: true });
  1065. const outputDir = await mkdtemp(join(outputRootDir, `${exportBaseName}-`));
  1066. const zipPath = join(outputDir, `${exportBaseName}.zip`);
  1067. const directoryPath = join(outputDir, exportBaseName);
  1068. logger.info("[export-logs] 开始打包日志", {
  1069. source: sourceDir,
  1070. zipDest: zipPath,
  1071. directoryDest: directoryPath,
  1072. });
  1073. const artifacts = await buildArtifacts(sourceDir, { now });
  1074. try {
  1075. await writeZip(zipPath, artifacts, { stageRootDir: getStageRootDir() });
  1076. await showItemInFolder(zipPath);
  1077. logger.info("[export-logs] 日志导出完成", {
  1078. path: zipPath,
  1079. format: "zip",
  1080. });
  1081. return { success: true, path: zipPath };
  1082. } catch (zipError) {
  1083. const zipErrorMessage = zipError instanceof Error ? zipError.message : String(zipError);
  1084. // Windows 的压缩能力不再依赖 PowerShell/.NET,但归档写入仍可能被杀软、磁盘策略等外部因素打断。
  1085. // 这里回退为目录导出,保证用户至少能稳定拿到原始日志,而不是直接报错。
  1086. logger.warn("[export-logs] zip 导出失败,回退到目录导出", {
  1087. error: zipErrorMessage,
  1088. zipPath,
  1089. fallbackPath: directoryPath,
  1090. });
  1091. await rm(zipPath, { force: true }).catch(() => {});
  1092. try {
  1093. await writeDirectory(directoryPath, artifacts);
  1094. } catch (directoryError) {
  1095. const directoryErrorMessage =
  1096. directoryError instanceof Error ? directoryError.message : String(directoryError);
  1097. throw new Error(`zip 导出失败:${zipErrorMessage};目录导出失败:${directoryErrorMessage}`);
  1098. }
  1099. await showItemInFolder(directoryPath);
  1100. logger.info("[export-logs] 日志导出完成", {
  1101. path: directoryPath,
  1102. format: "directory",
  1103. });
  1104. return { success: true, path: directoryPath };
  1105. }
  1106. } catch (err) {
  1107. const message = formatErrorMessage(err);
  1108. logger.error("[export-logs] 日志导出失败", { error: message });
  1109. return { success: false, error: message };
  1110. }
  1111. }