@myclaw163/diagnostics-dsh 0.0.0-stage → 0.2.2-rc.5-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/cordis.patch.yml +5 -0
  2. package/icon.svg +23 -0
  3. package/lib/client.js +3 -0
  4. package/lib/client.js.map +1 -0
  5. package/lib/index.js +664 -0
  6. package/lib/types/account-scopes.d.ts +20 -0
  7. package/lib/types/account-scopes.d.ts.map +1 -0
  8. package/lib/types/account-scopes.js.map +1 -0
  9. package/lib/types/client/DiagnosticsDialog.d.ts +14 -0
  10. package/lib/types/client/DiagnosticsDialog.d.ts.map +1 -0
  11. package/lib/types/client/DiagnosticsDialog.js.map +1 -0
  12. package/lib/types/client/Entry.d.ts +8 -0
  13. package/lib/types/client/Entry.d.ts.map +1 -0
  14. package/lib/types/client/Entry.js.map +1 -0
  15. package/lib/types/client/diagnostics-controller.d.ts +39 -0
  16. package/lib/types/client/diagnostics-controller.d.ts.map +1 -0
  17. package/lib/types/client/diagnostics-controller.js.map +1 -0
  18. package/lib/types/client/download.d.ts +8 -0
  19. package/lib/types/client/download.d.ts.map +1 -0
  20. package/lib/types/client/download.js.map +1 -0
  21. package/lib/types/client/index.d.ts +13 -0
  22. package/lib/types/client/index.d.ts.map +1 -0
  23. package/lib/types/client/index.js.map +1 -0
  24. package/lib/types/client/locales.d.ts +147 -0
  25. package/lib/types/client/locales.d.ts.map +1 -0
  26. package/lib/types/client/locales.js.map +1 -0
  27. package/lib/types/diagnostic-journal.d.ts +42 -0
  28. package/lib/types/diagnostic-journal.d.ts.map +1 -0
  29. package/lib/types/diagnostic-journal.js.map +1 -0
  30. package/lib/types/diagnostics-host.d.ts +24 -0
  31. package/lib/types/diagnostics-host.d.ts.map +1 -0
  32. package/lib/types/diagnostics-host.js.map +1 -0
  33. package/lib/types/diagnostics.d.ts +84 -0
  34. package/lib/types/diagnostics.d.ts.map +1 -0
  35. package/lib/types/diagnostics.js.map +1 -0
  36. package/lib/types/index.d.ts +38 -0
  37. package/lib/types/index.d.ts.map +1 -0
  38. package/lib/types/index.js.map +1 -0
  39. package/lib/types/release-info.d.ts +16 -0
  40. package/lib/types/release-info.d.ts.map +1 -0
  41. package/lib/types/release-info.js.map +1 -0
  42. package/locale/de.json +6 -0
  43. package/locale/en.json +6 -0
  44. package/locale/es.json +6 -0
  45. package/locale/fr.json +6 -0
  46. package/locale/ja.json +6 -0
  47. package/locale/pt.json +6 -0
  48. package/locale/ru.json +6 -0
  49. package/locale/zh.json +6 -0
  50. package/package.json +65 -3
  51. package/README.md +0 -3
package/lib/index.js ADDED
@@ -0,0 +1,664 @@
1
+ import { createRequire } from "node:module";
2
+ import Schema from "@deepseek-ai/schemastery";
3
+ import { format } from "node:util";
4
+ import { appendFile, mkdir, readFile, readdir, stat, unlink } from "node:fs/promises";
5
+ import { createHash, randomUUID } from "node:crypto";
6
+ import { isAbsolute, join } from "node:path";
7
+ import { brandString } from "@deepseek-ai/dsh-brand";
8
+ import { readFileSync } from "node:fs";
9
+ import { strToU8, zip } from "fflate";
10
+ import { Context } from "@deepseek-ai/cordis";
11
+ import { Config as Config$1, apply as apply$1 } from "@deepseek-ai/dsh-session-persistence-jsonl";
12
+ import { SessionLogOffset } from "@deepseek-ai/dsh-session";
13
+ //#region lib/types/account-scopes.js
14
+ /** 只读枚举 Desktop 管理的账号数据目录,历史未归属目录不自动认领。 */
15
+ /**
16
+ * 枚举账号元数据,逐个报告损坏来源,继续读取其他账号。
17
+ * @param root - Desktop 管理的 accounts 根目录。
18
+ * @param signal - 导出取消信号。
19
+ * @returns 可读取账号及无法读取的来源。
20
+ */
21
+ async function diagnosticAccountScopes(root, signal) {
22
+ const scopes = [], failures = [];
23
+ let entries;
24
+ try {
25
+ entries = await readdir(root, { withFileTypes: true });
26
+ } catch (error) {
27
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
28
+ scopes,
29
+ failures
30
+ };
31
+ throw error;
32
+ }
33
+ for (const entry of entries) {
34
+ signal.throwIfAborted();
35
+ if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;
36
+ try {
37
+ const value = JSON.parse(await readFile(join(root, entry.name, "account.json"), {
38
+ encoding: "utf8",
39
+ signal
40
+ }));
41
+ if (typeof value !== "object" || value === null || !("authority" in value) || !("id" in value) || typeof value.authority !== "string" || !value.authority || typeof value.id !== "string" || !value.id || createHash("sha256").update(JSON.stringify([value.authority, value.id])).digest("hex") !== entry.name) throw new Error("Invalid account metadata");
42
+ scopes.push({
43
+ directory: join(root, entry.name),
44
+ account: {
45
+ authority: value.authority,
46
+ id: brandString(value.id),
47
+ directory: entry.name
48
+ }
49
+ });
50
+ } catch (_error) {
51
+ signal.throwIfAborted();
52
+ failures.push({
53
+ source: `accounts/${entry.name}`,
54
+ reason: "account-metadata-unavailable"
55
+ });
56
+ }
57
+ }
58
+ return {
59
+ scopes,
60
+ failures
61
+ };
62
+ }
63
+ //#endregion
64
+ //#region lib/types/release-info.js
65
+ /** ZIP 内的发行信息只包含已知插件的公开清单字段。 */
66
+ const target = "clawclaw-dsh";
67
+ function knownPlugin(name) {
68
+ return /^@myclaw163\/(?:clawclaw|clawpet|diagnostics)(?:-dsh|-leihuo)?$/u.test(name) || /^@deepseek-ai\/dsh-(?:experimental-clawclaw(?:-pet)?|diagnostics)$/u.test(name);
69
+ }
70
+ const versionPattern = /^\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/u;
71
+ function version(value) {
72
+ return typeof value === "string" && value.length <= 128 && versionPattern.test(value) ? value : null;
73
+ }
74
+ function readManifest(name, anchor) {
75
+ const path = createRequire(anchor).resolve(name);
76
+ return JSON.parse(readFileSync(path, "utf8"));
77
+ }
78
+ function runtimeVersion() {
79
+ try {
80
+ return version(readManifest("@deepseek-ai/dsh-session/package.json", import.meta.url).version);
81
+ } catch (_error) {
82
+ return null;
83
+ }
84
+ }
85
+ function packageInfo(name, anchor, self = false) {
86
+ try {
87
+ const manifest = readManifest(self ? "../package.json" : name + "/package.json", anchor);
88
+ const peer = name.includes("clawclaw") && !name.endsWith("-pet") ? "@deepseek-ai/dsh-agent" : "@deepseek-ai/dsh-session";
89
+ return {
90
+ name: typeof manifest.name === "string" && knownPlugin(manifest.name) ? manifest.name : name,
91
+ version: version(manifest.version),
92
+ supportedDshVersion: version(manifest.peerDependencies?.[peer])
93
+ };
94
+ } catch (_error) {
95
+ return {
96
+ name,
97
+ version: null,
98
+ supportedDshVersion: null
99
+ };
100
+ }
101
+ }
102
+ /** 读取诊断导出器及当前活动游戏和桌宠插件的安装清单。
103
+ * @param ctx - 运行中的 Loader 上下文;独立导出器可以省略。
104
+ * @returns 发行目标、宿主上报版本及本次可观测的插件版本。
105
+ */
106
+ function diagnosticReleaseInfo(ctx) {
107
+ const diagnostics = packageInfo("@myclaw163/diagnostics-dsh", import.meta.url, true);
108
+ const plugins = [diagnostics];
109
+ for (const entry of ctx?.get("loader")?.entries() ?? []) {
110
+ const name = entry.options.name;
111
+ if (entry.fiber?.state !== 2 || !knownPlugin(name) || name === diagnostics.name) continue;
112
+ const anchor = entry.parent.tree.ctx.baseUrl;
113
+ plugins.push(anchor ? packageInfo(name, anchor) : {
114
+ name,
115
+ version: null,
116
+ supportedDshVersion: null
117
+ });
118
+ }
119
+ const { DSH_CLIENT_VERSION } = process.env;
120
+ return {
121
+ distributionTarget: target,
122
+ hostDshVersion: version(DSH_CLIENT_VERSION),
123
+ sessionRuntimeVersion: runtimeVersion(),
124
+ plugins
125
+ };
126
+ }
127
+ //#endregion
128
+ //#region lib/types/diagnostics.js
129
+ /** 插件诊断采集器与受限、脱敏的本地 ZIP 导出。 */
130
+ /**
131
+ * 清理诊断文本中的凭据;保留会话、房间与对局关联标识。
132
+ * @param text - 待导出的诊断文本。
133
+ * @returns 不包含已识别凭据的文本。
134
+ */
135
+ function redactDiagnosticText(text) {
136
+ const scrub = (value, depth) => {
137
+ if (depth > 64) throw new Error("DIAGNOSTIC_REDACTION_DEPTH");
138
+ if (typeof value === "string") {
139
+ if (/^\s*[\[{]/.test(value)) {
140
+ let nested;
141
+ try {
142
+ nested = JSON.parse(value);
143
+ } catch (_error) {
144
+ return redactPlainText(value);
145
+ }
146
+ return JSON.stringify(scrub(nested, depth + 1));
147
+ }
148
+ return redactPlainText(value);
149
+ }
150
+ if (Array.isArray(value)) return value.map((item) => scrub(item, depth + 1));
151
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, /^(?:api[-_]?key|claw[-_]?key|access[-_]?token|refresh[-_]?token|password|secret|token|ticket|authorization|cookie|set-cookie|ANTHROPIC_AUTH_TOKEN)$/i.test(key) ? "[redacted]" : scrub(item, depth + 1)]));
152
+ return value;
153
+ };
154
+ let parsed;
155
+ try {
156
+ parsed = JSON.parse(text);
157
+ } catch (_error) {
158
+ return text.split("\n").map((line) => {
159
+ let record;
160
+ try {
161
+ record = JSON.parse(line);
162
+ } catch (_error) {
163
+ return redactPlainText(line);
164
+ }
165
+ return JSON.stringify(scrub(record, 0));
166
+ }).join("\n");
167
+ }
168
+ return JSON.stringify(scrub(parsed, 0));
169
+ }
170
+ function redactPlainText(text) {
171
+ return text.replace(/\b(?:sk-[A-Za-z0-9_\-]+|claw_[A-Za-z0-9_\-]+)\b/g, "[redacted]").replace(/([?&#](?:token|t|code|api_key|access_token)=)[^\s&#"<>]+/gi, "$1[redacted]").replace(/\bBearer\s+[^\s,"}]+/gi, "Bearer [redacted]").replace(/((?:api[-_]?key|claw[-_]?key|access[-_]?token|refresh[-_]?token|password|secret|token|ticket)\s*=\s*)[^\s,;]+/gi, "$1[redacted]").replace(/(authorization\s*[":= ]+)(?:Bearer\s+)?[^\s,"}]+/gi, "$1[redacted]").replace(/("(?:apiKey|api_key|clawKey|access_token|refresh_token|password|secret|token|ticket|authorization|cookie|set-cookie|ANTHROPIC_AUTH_TOKEN)"\s*:\s*)"(?:\\.|[^"\\])*"/gi, "$1\"[redacted]\"");
172
+ }
173
+ /** 按采集器隔离故障,生成带缺失清单的诊断归档。 */
174
+ var DiagnosticExportRegistry = class {
175
+ limits;
176
+ releaseInfo;
177
+ collectors = /* @__PURE__ */ new Map();
178
+ /** @param limits - 已由宿主验证的压缩选项。 @param releaseInfo - 导出时读取当前发行信息。 */
179
+ constructor(limits, releaseInfo = () => diagnosticReleaseInfo()) {
180
+ this.limits = limits;
181
+ this.releaseInfo = releaseInfo;
182
+ }
183
+ /**
184
+ * 注册插件采集器;重复 id 不允许覆盖已有来源。
185
+ * @param collector - 只读采集器。
186
+ * @returns 只撤回本次注册的 disposer。
187
+ */
188
+ register(collector) {
189
+ if (!/^[a-z][a-z0-9-]*$/.test(collector.id) || this.collectors.has(collector.id)) throw new Error("DIAGNOSTIC_COLLECTOR_CONFLICT");
190
+ this.collectors.set(collector.id, collector);
191
+ return () => {
192
+ if (this.collectors.get(collector.id) === collector) this.collectors.delete(collector.id);
193
+ };
194
+ }
195
+ /**
196
+ * 导出一次范围快照;采集失败写入 manifest,取消则不返回文件。
197
+ * @param request - 用户选择的时间、会话和取消信号。
198
+ * @returns 脱敏后的 ZIP 字节。
199
+ */
200
+ async export(request) {
201
+ const files = {};
202
+ const failures = [];
203
+ const account = this.limits.account;
204
+ const discovered = this.limits.accountsDirectory !== void 0 && request.sessionId === void 0 ? await diagnosticAccountScopes(this.limits.accountsDirectory, request.signal) : {
205
+ scopes: [],
206
+ failures: []
207
+ };
208
+ failures.push(...discovered.failures);
209
+ const scopes = this.limits.accountsDirectory === void 0 || request.sessionId !== void 0 ? [void 0] : discovered.scopes;
210
+ if (this.limits.accountsDirectory !== void 0 && this.limits.legacyDirectory !== void 0 && request.sessionId === void 0) scopes.push({
211
+ directory: this.limits.legacyDirectory,
212
+ account: null
213
+ });
214
+ const prefixOf = (owner) => owner === null ? "unassigned/" : owner === void 0 ? "" : `accounts/${owner.directory}/`;
215
+ for (const scope of scopes) {
216
+ const owner = scope === void 0 ? account : scope.account;
217
+ if (owner) files[`${prefixOf(owner)}account.json`] = strToU8(JSON.stringify(owner, null, 2));
218
+ }
219
+ for (const collector of [...this.collectors.values()]) {
220
+ if (collector.id === "sessions" ? request.includeSessions === false : request.includePlugins === false) continue;
221
+ for (const scope of collector.scope === "shared" ? [void 0] : scopes) {
222
+ request.signal.throwIfAborted();
223
+ const owner = scope === void 0 ? account : scope.account;
224
+ const prefix = collector.scope === "shared" && this.limits.accountsDirectory !== void 0 ? "shared/" : prefixOf(owner);
225
+ try {
226
+ const selected = scope === void 0 ? {
227
+ ...request,
228
+ ...account === void 0 ? {} : { account }
229
+ } : {
230
+ ...request,
231
+ dataDirectory: scope.directory,
232
+ account: scope.account
233
+ };
234
+ for await (const file of collector.collect(selected)) {
235
+ request.signal.throwIfAborted();
236
+ if (!file.path || file.path.startsWith("/") || file.path.includes("\\") || file.path.split("/").some((part) => part === ".." || part === "." || part === "")) throw new Error("DIAGNOSTIC_INVALID_PATH");
237
+ const path = `${file.shared ? this.limits.accountsDirectory === void 0 ? "" : "shared/" : file.account === void 0 ? prefix : prefixOf(file.account)}${collector.id}/${file.path}`;
238
+ if (Object.hasOwn(files, path)) throw new Error("DIAGNOSTIC_DUPLICATE_PATH");
239
+ const data = strToU8(redactDiagnosticText(file.text));
240
+ if (file.partial !== void 0) failures.push({
241
+ source: path,
242
+ reason: file.partial
243
+ });
244
+ files[path] = data;
245
+ }
246
+ } catch (error) {
247
+ request.signal.throwIfAborted();
248
+ failures.push({
249
+ source: `${prefix}${collector.id}`,
250
+ reason: error instanceof Error && error.message.startsWith("DIAGNOSTIC_") ? error.message : "collection-failed"
251
+ });
252
+ }
253
+ }
254
+ }
255
+ const accounts = scopes.flatMap((scope) => {
256
+ const value = scope === void 0 ? account : scope.account;
257
+ return value ? [value] : [];
258
+ });
259
+ let release = null;
260
+ try {
261
+ release = this.releaseInfo();
262
+ } catch (_error) {
263
+ failures.push({
264
+ source: "manifest/release",
265
+ reason: "collection-failed"
266
+ });
267
+ }
268
+ files["manifest.json"] = strToU8(JSON.stringify({
269
+ format: "dsh.diagnostics.v1",
270
+ release,
271
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
272
+ since: request.since,
273
+ sessionId: request.sessionId ?? null,
274
+ requestedByAccount: account ?? null,
275
+ accounts,
276
+ files: Object.keys(files),
277
+ failures,
278
+ complete: failures.length === 0
279
+ }, null, 2));
280
+ request.signal.throwIfAborted();
281
+ const result = await new Promise((resolve, reject) => {
282
+ const cancel = zip(files, { level: this.limits.compressionLevel ?? 6 }, (error, data) => {
283
+ request.signal.removeEventListener("abort", abort);
284
+ if (error) reject(error);
285
+ else resolve(data);
286
+ });
287
+ const abort = () => {
288
+ cancel();
289
+ reject(new DOMException("Diagnostic export cancelled", "AbortError"));
290
+ };
291
+ request.signal.addEventListener("abort", abort, { once: true });
292
+ if (request.signal.aborted) abort();
293
+ });
294
+ request.signal.throwIfAborted();
295
+ return result;
296
+ }
297
+ };
298
+ //#endregion
299
+ //#region lib/types/diagnostic-journal.js
300
+ /** 持久诊断日志;只管理本目录内自身命名的分段,不接触会话文件。 */
301
+ const managed = /^host-(\d+)-[0-9a-f-]+\.jsonl$/;
302
+ /** 串行写入、轮转与收集;关闭时等待已接收的记录落盘。 */
303
+ var DiagnosticJournal = class {
304
+ policy;
305
+ now;
306
+ tail = Promise.resolve();
307
+ active;
308
+ bytes = 0;
309
+ born = 0;
310
+ closed = false;
311
+ failure;
312
+ /** @param policy - 已验证的磁盘保留策略。 @param now - 时钟。 */
313
+ constructor(policy, now = Date.now) {
314
+ this.policy = policy;
315
+ this.now = now;
316
+ if (!isAbsolute(policy.directory)) throw new Error("Diagnostic directory must be absolute");
317
+ if (![
318
+ policy.segmentBytes,
319
+ policy.totalBytes,
320
+ policy.retentionMs
321
+ ].every((value) => Number.isSafeInteger(value) && value > 0) || policy.totalBytes < policy.segmentBytes) throw new Error("Invalid diagnostic retention policy");
322
+ }
323
+ /** 准备日志目录并执行保留策略。
324
+ * @returns 目录准备和历史清理完成后返回;失败阻止启用。
325
+ */
326
+ async start() {
327
+ await mkdir(this.policy.directory, {
328
+ recursive: true,
329
+ mode: 448
330
+ });
331
+ await this.prune();
332
+ }
333
+ /** 将日志脱敏后加入顺序写入队列;关闭或写入失败后不再接收。
334
+ * @param record - 待脱敏的 JSON 日志记录。
335
+ */
336
+ append(record) {
337
+ if (this.closed || this.failure !== void 0) return;
338
+ const line = redactDiagnosticText(JSON.stringify(record)) + "\n";
339
+ this.tail = this.tail.then(async () => {
340
+ if (this.failure !== void 0) return;
341
+ const size = Buffer.byteLength(line);
342
+ let active = this.active;
343
+ const rotate = active === void 0 || this.bytes + size > this.policy.segmentBytes || this.now() - this.born >= this.policy.retentionMs;
344
+ if (active === void 0 || rotate) {
345
+ this.born = this.now();
346
+ active = `host-${this.born}-${randomUUID()}.jsonl`;
347
+ this.active = active;
348
+ this.bytes = 0;
349
+ }
350
+ await appendFile(join(this.policy.directory, active), line, { mode: 384 });
351
+ this.bytes += size;
352
+ if (rotate) await this.prune();
353
+ }).catch((error) => {
354
+ this.failure = error;
355
+ console.error("Diagnostic journal write failed; export will report an incomplete source");
356
+ });
357
+ }
358
+ /** 定期清理已轮转日志,失败时让诊断导出明确报告。 */
359
+ maintain() {
360
+ if (this.closed) return;
361
+ this.tail = this.tail.then(() => this.prune()).catch((error) => {
362
+ this.failure = error;
363
+ });
364
+ }
365
+ /** 停止接收记录并等待写入收尾。
366
+ * @returns 已接收记录写完后返回;错误由导出清单报告。
367
+ */
368
+ async close() {
369
+ this.closed = true;
370
+ await this.tail;
371
+ }
372
+ /** 在已接收写入完成后收集保留目录内的日志。
373
+ * @param request - 诊断时间范围与取消信号。
374
+ * @returns 持久日志中符合范围的记录;已有写入故障时拒绝导出该来源。
375
+ */
376
+ async *collect(request) {
377
+ const snapshot = this.tail.then(async () => {
378
+ const files = [];
379
+ if (this.failure !== void 0) throw new Error("DIAGNOSTIC_JOURNAL_WRITE_FAILED");
380
+ for (const entry of await readdir(this.policy.directory, { withFileTypes: true })) {
381
+ request.signal.throwIfAborted();
382
+ if (!entry.isFile() || !managed.test(entry.name)) continue;
383
+ const text = await readFile(join(this.policy.directory, entry.name), "utf8");
384
+ const groups = /* @__PURE__ */ new Map();
385
+ let malformed = false;
386
+ for (const line of text.split("\n")) {
387
+ if (!line) continue;
388
+ try {
389
+ const value = JSON.parse(line);
390
+ if (typeof value !== "object" || value === null || !("time" in value) || typeof value.time !== "number") {
391
+ malformed = true;
392
+ continue;
393
+ }
394
+ if (value.time < request.since) continue;
395
+ let account = null;
396
+ const raw = "account" in value ? value.account : void 0;
397
+ const shared = raw === null;
398
+ if (raw !== void 0 && raw !== null) if (typeof raw !== "object" || !("id" in raw) || typeof raw.id !== "string" || !("authority" in raw) || typeof raw.authority !== "string" || !("directory" in raw) || typeof raw.directory !== "string" || !/^[a-zA-Z0-9_-]+$/.test(raw.directory)) malformed = true;
399
+ else account = {
400
+ authority: raw.authority,
401
+ id: brandString(raw.id),
402
+ directory: raw.directory
403
+ };
404
+ if (request.sessionId !== void 0 && request.account && !shared && (account?.id !== request.account.id || account.authority !== request.account.authority)) continue;
405
+ const key = account?.directory ?? (shared ? "shared" : "unassigned");
406
+ const group = groups.get(key) ?? {
407
+ account,
408
+ shared,
409
+ lines: []
410
+ };
411
+ group.lines.push(line);
412
+ groups.set(key, group);
413
+ } catch (_error) {
414
+ malformed = true;
415
+ }
416
+ }
417
+ for (const group of groups.values()) files.push({
418
+ path: entry.name,
419
+ text: group.lines.join("\n") + "\n",
420
+ account: group.account,
421
+ shared: group.shared
422
+ });
423
+ if (malformed) files.push({
424
+ path: `${entry.name}.metadata.json`,
425
+ text: JSON.stringify({ malformedRecords: true }),
426
+ account: null,
427
+ partial: "malformed-records"
428
+ });
429
+ }
430
+ return files;
431
+ });
432
+ this.tail = snapshot.then(() => void 0, () => void 0);
433
+ yield* await snapshot;
434
+ }
435
+ async prune() {
436
+ if (this.active !== void 0 && this.now() - this.born >= this.policy.retentionMs) {
437
+ this.active = void 0;
438
+ this.bytes = 0;
439
+ }
440
+ const files = [];
441
+ for (const entry of await readdir(this.policy.directory, { withFileTypes: true })) {
442
+ const match = managed.exec(entry.name);
443
+ if (!entry.isFile() || !match) continue;
444
+ const path = join(this.policy.directory, entry.name);
445
+ files.push({
446
+ name: entry.name,
447
+ path,
448
+ time: Number(match[1]),
449
+ size: (await stat(path)).size
450
+ });
451
+ }
452
+ files.sort((a, b) => a.time - b.time || a.name.localeCompare(b.name));
453
+ let total = files.reduce((sum, file) => sum + file.size, 0);
454
+ for (const file of files) {
455
+ if (file.name === this.active) continue;
456
+ if (this.now() - file.time < this.policy.retentionMs && total <= this.policy.totalBytes) continue;
457
+ await unlink(file.path);
458
+ total -= file.size;
459
+ }
460
+ }
461
+ };
462
+ //#endregion
463
+ //#region lib/types/diagnostics-host.js
464
+ /**
465
+ * Install the session collector and authenticated diagnostic route.
466
+ * @param ctx - Host providing session query when available.
467
+ * @param connection - Existing authenticated fetch registry.
468
+ * @param registry - Plugin-owned archive service.
469
+ * @param journal - Persisted logs when configured; otherwise the current-process buffer.
470
+ * @param account - Current Host account; historical accounts use detached read-only persistence.
471
+ */
472
+ function registerDiagnostics(ctx, connection, registry, journal, account) {
473
+ ctx.effect(() => registry.register({
474
+ id: "platform",
475
+ scope: "shared",
476
+ async *collect(request) {
477
+ if (journal) {
478
+ yield* journal.collect(request);
479
+ return;
480
+ }
481
+ yield {
482
+ path: "runtime.json",
483
+ text: JSON.stringify({
484
+ node: process.version,
485
+ platform: process.platform,
486
+ arch: process.arch,
487
+ scope: "current-process-buffer",
488
+ sessionScope: "shared",
489
+ retainedRecords: ctx.logger.buffer.length
490
+ })
491
+ };
492
+ yield {
493
+ path: "host.jsonl",
494
+ partial: "current-process-buffer",
495
+ text: ctx.logger.buffer.filter((message) => message.ts >= request.since).map((message) => {
496
+ const args = message.args;
497
+ return JSON.stringify({
498
+ time: message.ts,
499
+ level: message.type,
500
+ name: message.name,
501
+ message: format(...args)
502
+ });
503
+ }).join("\n")
504
+ };
505
+ }
506
+ }), "diagnostics: platform collector");
507
+ ctx.effect(() => registry.register({
508
+ id: "sessions",
509
+ async *collect(request) {
510
+ if (request.dataDirectory !== void 0 && (request.account === null || request.account?.directory !== account?.directory)) {
511
+ yield* collectStoredSessions(request.dataDirectory, request);
512
+ return;
513
+ }
514
+ const query = ctx.get("sessionQuery");
515
+ if (!query) throw new Error("Session query unavailable");
516
+ const ids = request.sessionId ? [request.sessionId] : (await query.listSessions(request.signal)).map((record) => record.header.id);
517
+ for (const id of ids) {
518
+ request.signal.throwIfAborted();
519
+ const snapshot = await query.readSession(id);
520
+ const events = snapshot.events.filter((event) => event.time >= request.since);
521
+ if (events.length === 0) continue;
522
+ const header = JSON.stringify(snapshot.session);
523
+ yield {
524
+ path: `${encodeURIComponent(id)}.jsonl`,
525
+ text: [header, ...events.map((event) => JSON.stringify(event))].join("\n") + "\n"
526
+ };
527
+ }
528
+ }
529
+ }), "diagnostics: session collector");
530
+ ctx.effect(() => connection.fetch.register({
531
+ path: "/api/diagnostics.export",
532
+ methods: ["GET"],
533
+ requestBody: "buffered",
534
+ async fetch(request) {
535
+ const query = new URL(request.url).searchParams;
536
+ const hours = Number(query.get("hours"));
537
+ const sessions = query.get("sessions"), plugins = query.get("plugins");
538
+ const id = query.get("sessionId");
539
+ if (hours !== 8 || !["true", "false"].includes(sessions ?? "") || !["true", "false"].includes(plugins ?? "") || sessions === "false" && plugins === "false" || id === "") return new Response("Invalid diagnostic scope", { status: 400 });
540
+ try {
541
+ const data = await registry.export({
542
+ since: Date.now() - hours * 36e5,
543
+ signal: request.signal,
544
+ includeSessions: sessions === "true",
545
+ includePlugins: plugins === "true",
546
+ ...id === null ? {} : { sessionId: brandString(id) }
547
+ });
548
+ return new Response(Buffer.from(data), { headers: {
549
+ "content-type": "application/zip",
550
+ "cache-control": "no-store",
551
+ "content-disposition": "attachment; filename=\"dsh-diagnostics.zip\""
552
+ } });
553
+ } catch (_error) {
554
+ request.signal.throwIfAborted();
555
+ return new Response("Diagnostic export failed", { status: 500 });
556
+ }
557
+ }
558
+ }), "diagnostics: download route");
559
+ }
560
+ /** 历史账号仅使用独立的只读持久化服务,不创建 Agent 或迁移磁盘记录。 */
561
+ async function* collectStoredSessions(directory, request) {
562
+ const reader = new Context();
563
+ try {
564
+ await reader.plugin({
565
+ apply: apply$1,
566
+ Config: Config$1
567
+ }, { root: join(directory, "sessions") });
568
+ for (const record of await reader.sessionPersistence.list({ signal: request.signal })) {
569
+ request.signal.throwIfAborted();
570
+ try {
571
+ const handle = await reader.sessionPersistence.open(record.header.id, "read", { signal: request.signal });
572
+ try {
573
+ const events = (await handle.read(SessionLogOffset(0), void 0, { signal: request.signal })).events.filter((event) => event.time >= request.since);
574
+ if (events.length) yield {
575
+ path: `${encodeURIComponent(record.header.id)}.jsonl`,
576
+ text: [JSON.stringify(handle.header), ...events.map((event) => JSON.stringify(event))].join("\n") + "\n"
577
+ };
578
+ } finally {
579
+ await handle.close();
580
+ }
581
+ } catch (_error) {
582
+ request.signal.throwIfAborted();
583
+ yield {
584
+ path: `${encodeURIComponent(record.header.id)}.metadata.json`,
585
+ text: JSON.stringify({ status: "unavailable" }),
586
+ partial: "unavailable-source"
587
+ };
588
+ }
589
+ }
590
+ } finally {
591
+ await reader.fiber.dispose();
592
+ }
593
+ }
594
+ //#endregion
595
+ //#region lib/types/index.js
596
+ const name = "diagnostics";
597
+ const inject = ["connection"];
598
+ /** 校验诊断导出配置。 */
599
+ const Config = Schema.object({
600
+ accountsDirectory: Schema.string(),
601
+ legacyDirectory: Schema.string(),
602
+ account: Schema.union([Schema.const(void 0), Schema.object({
603
+ authority: Schema.string().required(),
604
+ id: Schema.string().required(),
605
+ directory: Schema.string().pattern(/^[a-zA-Z0-9_-]+$/).required()
606
+ })]),
607
+ diagnosticDirectory: Schema.string(),
608
+ diagnosticMaintenanceMs: Schema.number().step(1).min(1).default(6e4),
609
+ diagnosticSegmentBytes: Schema.number().step(1).min(1).default(67108864),
610
+ diagnosticRetentionBytes: Schema.number().step(1).min(1).default(536870912),
611
+ diagnosticRetentionMs: Schema.number().step(1).min(1).default(6048e5),
612
+ compressionLevel: Schema.number().step(1).min(0).max(9).default(6)
613
+ });
614
+ /**
615
+ * 注册诊断服务,采集器和下载路由随插件卸载撤回。
616
+ * @param ctx 宿主上下文。
617
+ * @param config 日志目录与保留策略。
618
+ * @returns 完成日志初始化与服务注册。
619
+ */
620
+ async function apply(ctx, config = {}) {
621
+ const diagnostics = new DiagnosticExportRegistry({
622
+ ...config.accountsDirectory === void 0 ? {} : { accountsDirectory: config.accountsDirectory },
623
+ ...config.legacyDirectory === void 0 ? {} : { legacyDirectory: config.legacyDirectory },
624
+ ...config.account === void 0 ? {} : { account: config.account },
625
+ compressionLevel: config.compressionLevel ?? 6
626
+ }, () => diagnosticReleaseInfo(ctx));
627
+ ctx.provide("diagnostics", diagnostics);
628
+ let journal;
629
+ if (config.diagnosticDirectory !== void 0) {
630
+ const persistent = new DiagnosticJournal({
631
+ directory: config.diagnosticDirectory,
632
+ segmentBytes: config.diagnosticSegmentBytes ?? 67108864,
633
+ totalBytes: config.diagnosticRetentionBytes ?? 536870912,
634
+ retentionMs: config.diagnosticRetentionMs ?? 6048e5
635
+ });
636
+ await persistent.start();
637
+ journal = persistent;
638
+ ctx.effect(() => () => persistent.close(), "diagnostics: flush journal");
639
+ ctx.effect(() => {
640
+ const timer = setInterval(() => {
641
+ persistent.maintain();
642
+ }, config.diagnosticMaintenanceMs ?? 6e4);
643
+ timer.unref();
644
+ return () => {
645
+ clearInterval(timer);
646
+ };
647
+ }, "diagnostics: disk maintenance");
648
+ const writeMessage = (message) => {
649
+ const args = message.args;
650
+ persistent.append({
651
+ time: message.ts,
652
+ level: message.type,
653
+ name: message.name,
654
+ message: format(...args),
655
+ account: config.account ?? null
656
+ });
657
+ };
658
+ for (const message of ctx.logger.buffer) writeMessage(message);
659
+ ctx.logger.exporter({ export: writeMessage });
660
+ }
661
+ registerDiagnostics(ctx, ctx.connection, diagnostics, journal, config.account);
662
+ }
663
+ //#endregion
664
+ export { Config, apply, inject, name };
@@ -0,0 +1,20 @@
1
+ import type { DiagnosticAccount } from './diagnostics.ts';
2
+ /** 一次导出使用的只读数据来源。 */
3
+ export interface DiagnosticScope {
4
+ readonly directory: string;
5
+ readonly account: DiagnosticAccount | null;
6
+ }
7
+ /**
8
+ * 枚举账号元数据,逐个报告损坏来源,继续读取其他账号。
9
+ * @param root - Desktop 管理的 accounts 根目录。
10
+ * @param signal - 导出取消信号。
11
+ * @returns 可读取账号及无法读取的来源。
12
+ */
13
+ export declare function diagnosticAccountScopes(root: string, signal: AbortSignal): Promise<{
14
+ scopes: DiagnosticScope[];
15
+ failures: {
16
+ source: string;
17
+ reason: string;
18
+ }[];
19
+ }>;
20
+ //# sourceMappingURL=account-scopes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-scopes.d.ts","sourceRoot":"","sources":["../../src/account-scopes.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AAEzD,qBAAqB;AACrB,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,CAAA;CAC3C;AAED;;;;;GAKG;AACH,wBAAsB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC;IACxF,MAAM,EAAE,eAAe,EAAE,CAAA;IACzB,QAAQ,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;CAC/C,CAAC,CAuBD"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-scopes.js","sourceRoot":"","sources":["../../src/account-scopes.ts"],"names":[],"mappings":"AAAA,2CAA2C;AAC3C,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EAAE,U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