dsh-config-manager 0.8.1 → 0.8.2

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.
@@ -63,5 +63,16 @@ export declare function traeVscdbPaths(userDir: string, platform: ForeignPlatfor
63
63
  */
64
64
  export declare function readTrae(opts: RootProbeOptions & {
65
65
  readonly maxFiles?: number;
66
+ readonly maxEncryptedDbBytes?: number;
66
67
  }): Promise<SessionReadOutcome<TraeSessionFile>>;
68
+ /**
69
+ * detect 期的**轻量预告**(issue #134 的第二半):让 `/foreign-sources` 在用户点导入前就把
70
+ * 「为什么这里没有会话」摆出来,而不是等 build 的 400 才闪一下。
71
+ *
72
+ * 代价(刻意接受):只读**页头**与 **ItemTable 的 key 列**,绝不读正文、绝不枚举会话 ——
73
+ * 4 个发行版的加密库最多各解密 1 页,旧库只是 `SELECT key`。因此 detect 仍是有界的只读探测。
74
+ */
75
+ export declare function traeDetectSkips(opts: RootProbeOptions & {
76
+ readonly maxEncryptedDbBytes?: number;
77
+ }): Promise<ForeignSkip[]>;
67
78
  export {};
@@ -21,6 +21,11 @@
21
21
  * · 会话容器的字段级 schema **未取证**:本层用**结构自证**的窄口径(必须有「消息数组 + 至少一条
22
22
  * 带 role/type 的消息」)识别会话,容器必须自带字符串 id(否则铸稳定兜底 id);cwd 只认明文
23
23
  * 绝对路径字段,找不到就交给下游落 session-missing-cwd(**绝不猜 cwd**)。
24
+ *
25
+ * 2.3.x 起多了一条通道(issue #134):会话迁到 `<User>/ModularData/ai-agent/database.db`,
26
+ * **整库 SQLCipher 加密**。解密、临时明文、页头校验都在 trae-sqlcipher.ts(只交出中性行);
27
+ * 本文件只负责「读表结果 → 统一会话形态」的语义映射(role/正文/cwd 口径与旧通道**同一份代码**)。
28
+ * 两条通道按会话 id 去重、**先加密库后旧库**(迁移后的库才是权威),并存时只计一份。
24
29
  */
25
30
  import { isAbsoluteFor, joinFor, normalizePlatform, vscodeUserDataDir } from './platform-paths.js';
26
31
  import { isFile, listDirNames, statOrNull } from './session-read.js';
@@ -30,6 +35,7 @@ import { cellBytes, cellText, openSqliteIfShape, sqliteCapability } from './sqli
30
35
  // SQLite 批的**唯一**时间口径(秒/毫秒自适应 + 安全整数)在本文件的共享模块里,不再抄第二份
31
36
  import { msTime } from './read-opencode.js';
32
37
  import { isRecord } from '../utils/guards.js';
38
+ import { probeTraeEncryptedDatabase, readTraeEncryptedDatabase, traeDbPathFor, traeDbSkipOf } from './trae-sqlcipher.js';
33
39
  /** 四个发行版名(顺序 = chat-import traeUserDataDirs 的判定顺序) */
34
40
  export const TRAE_PRODUCTS = ['Trae', 'Trae CN', 'TRAE SOLO CN', 'TRAE SOLO'];
35
41
  export const TRAE_VSCDB_NAME = 'state.vscdb';
@@ -406,12 +412,66 @@ export async function readTrae(opts) {
406
412
  extraCounts: { 'trae.vscdb': 0 },
407
413
  };
408
414
  }
415
+ const extraSkips = [];
416
+ let truncated = false;
417
+ // ① 加密库通道(2.3.x):先读 —— 迁移后的库才是权威,同 id 冲突以它为准
418
+ const encryptedDbs = [];
419
+ for (const userDir of traeUserDataDirs(opts)) {
420
+ const dbPath = traeDbPathFor(userDir, platform);
421
+ if (await isFile(dbPath))
422
+ encryptedDbs.push(dbPath);
423
+ }
424
+ let encryptedSessions = 0;
425
+ for (const dbPath of encryptedDbs) {
426
+ const outcome = await readTraeEncryptedDatabase(dbPath, {
427
+ env: opts.env,
428
+ platform,
429
+ ...(opts.maxEncryptedDbBytes !== undefined ? { maxBytes: opts.maxEncryptedDbBytes } : {}),
430
+ maxSessions: maxFiles,
431
+ });
432
+ // 密钥错/超限/截断/表结构不符 ⇒ 稳定码(绝不静默 0 会话);旧库有货时继续走旧库
433
+ if (outcome.problem !== undefined) {
434
+ extraSkips.push(traeDbSkipOf(outcome.problem));
435
+ continue;
436
+ }
437
+ if (outcome.dropped !== undefined && outcome.dropped > 0) {
438
+ findings.push({ code: 'source-unreadable', origin: 'trae', detail: 'encrypted-row-json-error', count: outcome.dropped });
439
+ }
440
+ if (outcome.skipped !== undefined && outcome.skipped > 0) {
441
+ findings.push({ code: 'source-unreadable', origin: 'trae', detail: 'encrypted-session-without-id', count: outcome.skipped });
442
+ }
443
+ if (outcome.truncated === true)
444
+ truncated = true;
445
+ for (const session of outcome.sessions) {
446
+ if (files.length >= maxFiles) {
447
+ truncated = true;
448
+ break;
449
+ }
450
+ const id = isSafeIrId(session.id) ? session.id : safeFragment('trae-db-' + session.id);
451
+ if (seen.has(id))
452
+ continue;
453
+ const ignored = {};
454
+ const parsed = recordsOf(session.items, ignored);
455
+ seen.add(id);
456
+ files.push({
457
+ id,
458
+ cwd: session.cwd,
459
+ createdAt: session.createdAt,
460
+ title: session.title ?? '',
461
+ records: parsed.records,
462
+ raw: parsed.raw,
463
+ bad: 0,
464
+ ignored,
465
+ });
466
+ encryptedSessions += 1;
467
+ }
468
+ }
469
+ // ② 旧 state.vscdb 通道(保留):同 id 已被加密库计入的不再重复
409
470
  const dbs = [];
410
471
  for (const userDir of traeUserDataDirs(opts)) {
411
472
  dbs.push(...await traeVscdbPaths(userDir, platform));
412
473
  }
413
474
  let candidateKeys = 0;
414
- let truncated = false;
415
475
  for (const dbPath of dbs) {
416
476
  if (files.length >= maxFiles) {
417
477
  truncated = true;
@@ -471,8 +531,8 @@ export async function readTrae(opts) {
471
531
  if (truncated)
472
532
  break;
473
533
  }
474
- const extraSkips = [];
475
- if (files.length === 0 && candidateKeys === 0 && dbs.length > 0) {
534
+ // 加密库存在时,「旧库没有候选键」不是用户需要的解释(真因已由 trae-db-* 说明)
535
+ if (files.length === 0 && candidateKeys === 0 && dbs.length > 0 && encryptedDbs.length === 0) {
476
536
  extraSkips.push({ code: 'sessions-not-migrated', origin: 'trae', detail: 'chat-storage-key-not-found' });
477
537
  }
478
538
  else if (files.length === 0 && candidateKeys > 0) {
@@ -486,7 +546,67 @@ export async function readTrae(opts) {
486
546
  files,
487
547
  readFindings: findings,
488
548
  extraSkips,
489
- extraCounts: { 'trae.vscdb': dbs.length, 'trae.chatStorageKeys': candidateKeys },
549
+ extraCounts: {
550
+ 'trae.vscdb': dbs.length,
551
+ 'trae.chatStorageKeys': candidateKeys,
552
+ 'trae.encryptedDb': encryptedDbs.length,
553
+ 'trae.encryptedSessions': encryptedSessions,
554
+ },
490
555
  };
491
556
  }
557
+ /**
558
+ * detect 期的**轻量预告**(issue #134 的第二半):让 `/foreign-sources` 在用户点导入前就把
559
+ * 「为什么这里没有会话」摆出来,而不是等 build 的 400 才闪一下。
560
+ *
561
+ * 代价(刻意接受):只读**页头**与 **ItemTable 的 key 列**,绝不读正文、绝不枚举会话 ——
562
+ * 4 个发行版的加密库最多各解密 1 页,旧库只是 `SELECT key`。因此 detect 仍是有界的只读探测。
563
+ */
564
+ export async function traeDetectSkips(opts) {
565
+ const platform = normalizePlatform(opts.platform);
566
+ const skips = [];
567
+ let encryptedFound = 0;
568
+ for (const userDir of traeUserDataDirs(opts)) {
569
+ const dbPath = traeDbPathFor(userDir, platform);
570
+ if (!await isFile(dbPath))
571
+ continue;
572
+ encryptedFound += 1;
573
+ const problem = await probeTraeEncryptedDatabase(dbPath, {
574
+ env: opts.env,
575
+ ...(opts.maxEncryptedDbBytes !== undefined ? { maxBytes: opts.maxEncryptedDbBytes } : {}),
576
+ });
577
+ if (problem !== null)
578
+ skips.push(traeDbSkipOf(problem));
579
+ }
580
+ // 加密库在场时不再猜旧库:迁移后旧库多半只是残留,混进「没有候选键」会误导用户
581
+ if (encryptedFound > 0)
582
+ return skips;
583
+ const capability = await sqliteCapability();
584
+ if (!capability.available)
585
+ return skips;
586
+ const dbs = [];
587
+ for (const userDir of traeUserDataDirs(opts)) {
588
+ dbs.push(...await traeVscdbPaths(userDir, platform));
589
+ }
590
+ if (dbs.length === 0)
591
+ return skips;
592
+ let candidateKeys = 0;
593
+ for (const dbPath of dbs) {
594
+ const db = await openSqliteIfShape(dbPath, { ItemTable: ['key'] });
595
+ if (db === null)
596
+ continue;
597
+ const rows = db.all('SELECT key FROM ItemTable');
598
+ db.close();
599
+ if (rows === null)
600
+ continue;
601
+ for (const row of rows) {
602
+ const key = cellText(row, 'key');
603
+ if (key !== undefined && isTraeChatStorageKey(key))
604
+ candidateKeys += 1;
605
+ }
606
+ }
607
+ if (candidateKeys === 0) {
608
+ skips.push({ code: 'sessions-not-migrated', origin: 'trae', detail: 'chat-storage-key-not-found' });
609
+ }
610
+ return skips;
611
+ }
492
612
  //# sourceMappingURL=read-trae.js.map
@@ -191,8 +191,14 @@ export interface SessionSourceWiring<TFile extends {
191
191
  readonly probePaths: (opts: RootProbeOptions) => readonly string[];
192
192
  /** 命中即报 source-location-overridden 的环境变量(只报键名,绝不报值) */
193
193
  readonly probeEnvKeys?: readonly string[] | undefined;
194
- /** 探测期的附加提示(如 chatgpt 的「无自动根」) */
195
- readonly probeSkips?: ((opts: RootProbeOptions, probed: readonly string[]) => readonly ForeignSkip[]) | undefined;
194
+ /**
195
+ * 探测期的附加提示(如 chatgpt 的「无自动根」)。
196
+ *
197
+ * 允许返回 Promise:少数来源需要**有界**地读一点内容才能给出可判定的预告(trae 的加密库
198
+ * 只解密第 1 页、旧库只读 key 列)。这类探测必须自证「有界、只读、不枚举会话」,
199
+ * 否则 detect 会被 30 个来源拖慢。
200
+ */
201
+ readonly probeSkips?: ((opts: RootProbeOptions, probed: readonly string[]) => readonly ForeignSkip[] | Promise<readonly ForeignSkip[]>) | undefined;
196
202
  readonly read: (opts: SessionSourceHostOptions) => Promise<SessionReadOutcome<TFile>>;
197
203
  readonly draftOf: (file: TFile) => SessionDraft | {
198
204
  readonly skip: {
@@ -205,8 +211,10 @@ export interface SessionSourceWiring<TFile extends {
205
211
  /**
206
212
  * 把一个会话来源装配成 `ForeignSource`。
207
213
  *
208
- * **detect 只 stat 真值表里的位置**(绝不读内容、绝不枚举会话)—— 界面对 30 个来源各调一次
209
- * detect,任何一处读全文都会把面板拖慢;真正的枚举发生在 build。
214
+ * **detect 默认只 stat 真值表里的位置**(绝不读内容、绝不枚举会话)—— 界面对 30 个来源各调一次
215
+ * detect,任何一处读全文都会把面板拖慢;真正的枚举发生在 build。唯一例外是来源在 `probeSkips`
216
+ * 里显式声明的**有界轻量探测**(trae:加密库只解密第 1 页、旧库只读 key 列),因为它们要回答的
217
+ * 正是「为什么这里没有会话」,而这件事只有看内容才知道。
210
218
  *
211
219
  * platform 的兜底只在**这一处**:`ctx.platform ?? process.platform`(装配层碰运行平台是允许的,
212
220
  * 真值表函数本身一律显式收参)。
@@ -400,8 +400,10 @@ export function recordIdOf(raw, index) {
400
400
  /**
401
401
  * 把一个会话来源装配成 `ForeignSource`。
402
402
  *
403
- * **detect 只 stat 真值表里的位置**(绝不读内容、绝不枚举会话)—— 界面对 30 个来源各调一次
404
- * detect,任何一处读全文都会把面板拖慢;真正的枚举发生在 build。
403
+ * **detect 默认只 stat 真值表里的位置**(绝不读内容、绝不枚举会话)—— 界面对 30 个来源各调一次
404
+ * detect,任何一处读全文都会把面板拖慢;真正的枚举发生在 build。唯一例外是来源在 `probeSkips`
405
+ * 里显式声明的**有界轻量探测**(trae:加密库只解密第 1 页、旧库只读 key 列),因为它们要回答的
406
+ * 正是「为什么这里没有会话」,而这件事只有看内容才知道。
405
407
  *
406
408
  * platform 的兜底只在**这一处**:`ctx.platform ?? process.platform`(装配层碰运行平台是允许的,
407
409
  * 真值表函数本身一律显式收参)。
@@ -425,7 +427,7 @@ export function sessionSourceOf(wiring) {
425
427
  if (envValue(ctx.env, key) !== undefined)
426
428
  skipped.push({ code: 'source-location-overridden', origin: key });
427
429
  }
428
- skipped.push(...(wiring.probeSkips?.(opts, probed.paths) ?? []));
430
+ skipped.push(...((await wiring.probeSkips?.(opts, probed.paths)) ?? []));
429
431
  return { found: probed.paths.length > 0, paths: [...probed.paths], skipped };
430
432
  },
431
433
  async build(ctx) {
@@ -0,0 +1,127 @@
1
+ import type { ForeignPlatform } from './platform-paths.ts';
2
+ import type { ForeignSkip } from './types.ts';
3
+ /** 加密库相对 `<User>` 的路径段(4 个发行版共用同一命名) */
4
+ export declare const TRAE_DB_REL_SEGMENTS: readonly string[];
5
+ /** SQLCipher 4.x 的页大小(该库固定 4096) */
6
+ export declare const TRAE_DB_PAGE_SIZE = 4096;
7
+ /** 每页尾保留字节:IV(16) + HMAC-SHA512(64) */
8
+ export declare const TRAE_DB_RESERVE_BYTES = 80;
9
+ /** IV 长度(AES 块大小) */
10
+ export declare const TRAE_DB_IV_BYTES = 16;
11
+ /** 第 1 页开头的 salt 长度(不是密文,也不参与解密) */
12
+ export declare const TRAE_DB_SALT_BYTES = 16;
13
+ /** raw AES-256 密钥长度 */
14
+ export declare const TRAE_DB_KEY_BYTES = 32;
15
+ /**
16
+ * 缺省密钥:参考实现 xitula/trae-session-export 公开的 raw key 常量。
17
+ *
18
+ * **为什么可以内置**:它是产品级的固定 key(不是用户口令),参考实现公开分发;本插件只读、
19
+ * 且不写回任何 Trae 数据。换版后 key 变化 ⇒ 页头校验失败 ⇒ `trae-db-key-invalid`(可判定)。
20
+ */
21
+ export declare const TRAE_DB_DEFAULT_KEY = "3605f6691095a993f03d5009c918352ef5be31ae31e8f000212b81ff058da773";
22
+ /** 覆盖密钥的环境变量名(只报键名,绝不回显值) */
23
+ export declare const TRAE_DB_KEY_ENV = "DCM_TRAE_DB_KEY";
24
+ /**
25
+ * 加密库的体积上限(**按来源独立**,2 GiB 覆盖 1.4 GB 量级;超限走既有 copy-too-large 语义)。
26
+ * 刻意不碰 sqlite.ts 的 `DEFAULT_MAX_COPY_BYTES`(1 GiB,全局兜底)。
27
+ */
28
+ export declare const TRAE_DB_MAX_BYTES: number;
29
+ /** 会话表(调研确证) */
30
+ export declare const TRAE_DB_TABLE_SESSION = "chat_session";
31
+ /** 正文表(调研确证:消息在 `messages` 的 `raw_messages[]`) */
32
+ export declare const TRAE_DB_TABLE_HISTORY = "history_v2";
33
+ /** 表结构**最小**签名:只钉确证过的表与列,其余列按候选自证 */
34
+ export declare const TRAE_DB_REQUIRED_SCHEMA: Readonly<Record<string, readonly string[]>>;
35
+ /** 会话上限(与 read-trae 的 MAX_SESSIONS 同量级;由调用方再收窄) */
36
+ export declare const TRAE_DB_MAX_SESSIONS = 5000;
37
+ /** 解密/读表失败的**稳定码**(与 types.ts 的 ForeignSkipCode 一一对应) */
38
+ export type TraeDbProblemCode = 'trae-db-key-invalid' | 'trae-db-too-large' | 'trae-db-decrypt-failed' | 'trae-db-schema-mismatch';
39
+ /** 失败原因(`detail` 只放可枚举的短标签,绝不放密钥/明文片段) */
40
+ export interface TraeDbProblem {
41
+ readonly code: TraeDbProblemCode;
42
+ readonly detail: string;
43
+ readonly count?: number | undefined;
44
+ }
45
+ /** 读表交出的**中性**会话行(ID 校验与角色映射在 read-trae 里做,口径一处不改) */
46
+ export interface TraeDbSession {
47
+ readonly id: string;
48
+ readonly cwd?: string | undefined;
49
+ readonly title?: string | undefined;
50
+ readonly createdAt?: number | undefined;
51
+ readonly items: readonly unknown[];
52
+ }
53
+ /** 一次加密库读取的结果 */
54
+ export interface TraeDbReadOutcome {
55
+ readonly sessions: readonly TraeDbSession[];
56
+ readonly problem?: TraeDbProblem | undefined;
57
+ /** 解密出的页数(明文直读时为 undefined) */
58
+ readonly pages?: number | undefined;
59
+ /** `decrypted` = 走解密;`plaintext` = 库本身已是明文(旧版/已被解密的形态) */
60
+ readonly mode?: 'decrypted' | 'plaintext' | undefined;
61
+ /** 消息单元格解析不出的行数(如实计入,绝不伪造正文) */
62
+ readonly dropped?: number | undefined;
63
+ /** 缺 id 而无法建会话的行数 */
64
+ readonly skipped?: number | undefined;
65
+ /** 会话数触顶(调用方的 maxSessions) */
66
+ readonly truncated?: boolean | undefined;
67
+ }
68
+ /** 读表选项 */
69
+ export interface TraeDbReadOptions {
70
+ readonly env: Readonly<Record<string, string | undefined>>;
71
+ readonly platform: ForeignPlatform;
72
+ /** 体积上限(缺省 `TRAE_DB_MAX_BYTES`;单测用它造超限,不必造 2 GiB 文件) */
73
+ readonly maxBytes?: number | undefined;
74
+ /** 会话数上限(缺省 `TRAE_DB_MAX_SESSIONS`) */
75
+ readonly maxSessions?: number | undefined;
76
+ }
77
+ /** 密钥解析结果:要么给出 32 字节 raw key,要么给出可判定失败 */
78
+ export type TraeDbKeyResolution = {
79
+ readonly key: Buffer;
80
+ readonly source: 'default' | 'env';
81
+ } | {
82
+ readonly problem: TraeDbProblem;
83
+ };
84
+ /** 一个 `<User>` 根下的加密库位置(**绝不硬编码分隔符**) */
85
+ export declare function traeDbPathFor(userDir: string, platform: ForeignPlatform): string;
86
+ /**
87
+ * 解析密钥:环境变量优先,缺省内置常量。
88
+ *
89
+ * 环境变量**设了但不合法**时直接报 `trae-db-key-invalid`(detail=key-format),
90
+ * 绝不悄悄回落到内置 key —— 那会让「我换了密钥但没生效」变成静默 0 会话。
91
+ */
92
+ export declare function resolveTraeDbKey(env: Readonly<Record<string, string | undefined>>): TraeDbKeyResolution;
93
+ /**
94
+ * 校验解密出的第 1 页明文(`plain` = 明文页的 `[16, 4016)`,即文件 offset 16 起的 4000 B)。
95
+ *
96
+ * 返回 null = 通过;返回字符串 = 可判定的失败 detail(一律映射成 `trae-db-key-invalid`)。
97
+ */
98
+ export declare function validateTraePageOne(plain: Buffer, pages: number | null): string | null;
99
+ /**
100
+ * 把一个加密库逐页解密成明文库(**覆盖写 `destPath`**,目标不存在才写)。
101
+ *
102
+ * 只读源库;内存占用恒为一页;失败时返回稳定码,**不留半截明文**(由调用方的临时目录统一清理)。
103
+ */
104
+ export declare function decryptTraeDatabase(sourcePath: string, destPath: string, key: Buffer): Promise<{
105
+ ok: true;
106
+ pages: number;
107
+ } | {
108
+ ok: false;
109
+ problem: TraeDbProblem;
110
+ }>;
111
+ /**
112
+ * 探测期的**单页**校验(detect 用):只解密第 1 页、只读 4 KB,用来抢在 build 之前把
113
+ * 「密钥错 / 截断 / 超限」这三类可判定失败摆到界面上(#134 的第二半)。
114
+ *
115
+ * 返回 null = 没发现问题(或库不存在 / 已是明文)。
116
+ */
117
+ export declare function probeTraeEncryptedDatabase(sourcePath: string, options: Pick<TraeDbReadOptions, 'env' | 'maxBytes'>): Promise<TraeDbProblem | null>;
118
+ /** 正文容器 → 消息数组(`raw_messages` 第一顺位;数组本身也接受) */
119
+ export declare function messageItemsOf(value: unknown): unknown[] | null;
120
+ /**
121
+ * 读一个加密库:体积上限 → 密钥 → 解密(或明文直读)→ 只读读表 → 删临时明文。
122
+ *
123
+ * **绝不抛出**:所有失败都收成 `problem`(稳定码 + detail),调用方据此推 skip。
124
+ */
125
+ export declare function readTraeEncryptedDatabase(sourcePath: string, options: TraeDbReadOptions): Promise<TraeDbReadOutcome>;
126
+ /** problem → skip(origin 固定 'trae';count 只在有意义时带上) */
127
+ export declare function traeDbSkipOf(problem: TraeDbProblem): ForeignSkip;