personal-bot 0.2.17 → 0.2.19
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/CONTEXT.md +13 -1
- package/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/docs/file-storage.md +9 -2
- package/docs/history.md +8 -8
- package/docs/technical-design.md +3 -3
- package/lib/extension/dsh/history.js +2 -1
- package/lib/integrations/dsh/history.d.ts +1 -1
- package/lib/integrations/dsh/history.js +9 -6
- package/lib/model/history.d.ts +27 -8
- package/lib/services/history/history-index.d.ts +8 -0
- package/lib/services/history/history-index.js +134 -0
- package/lib/services/history/history-service.d.ts +8 -6
- package/lib/services/history/history-service.js +81 -137
- package/lib/storage/acp-history.d.ts +9 -0
- package/lib/storage/acp-history.js +45 -0
- package/lib/storage/history-files.d.ts +9 -6
- package/lib/storage/history-files.js +297 -83
- package/lib/storage/history-format.d.ts +15 -0
- package/lib/storage/history-format.js +86 -0
- package/package.json +1 -1
- package/src/extension/dsh/history.ts +3 -1
- package/src/integrations/dsh/history.ts +8 -6
- package/src/integrations/pi/history.ts +7 -6
- package/src/model/history.ts +25 -8
- package/src/pbot.ts +3 -1
- package/src/services/history/history-index.ts +125 -0
- package/src/services/history/history-service.ts +71 -113
- package/src/storage/acp-history.ts +38 -0
- package/src/storage/history-files.ts +233 -74
- package/src/storage/history-format.ts +98 -0
|
@@ -1,86 +1,135 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
1
|
+
import { linkSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmdirSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
import { object } from "../common/json.js";
|
|
5
5
|
import { requireThat } from "../common/validation.js";
|
|
6
|
+
import type { HistoryArchive, HistoryHost, HistoryIdentity, HistoryRecord, HistorySummary, RawHistory } from "../model/history.js";
|
|
6
7
|
import { internalPath, readJsonFile, syncDirectory, writeJsonFile } from "./atomic-json.js";
|
|
7
|
-
import { fileId } from "./file-access.js";
|
|
8
|
+
import { fileId, privateDirectory } from "./file-access.js";
|
|
9
|
+
import { hierarchicalHistory, isHistoryHost, legacyHistory, matchIdentity, rawHistory, splitLegacy, summaryData } from "./history-format.js";
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
for (const node of value.nodes) requireThat(object(node) && typeof node.id === "string" &&
|
|
15
|
-
["session", "exchange", "summary"].includes(String(node.kind)) && Number.isInteger(node.level) &&
|
|
16
|
-
strings(node.entryIds) && strings(node.parents) && strings(node.children) && typeof node.text === "string" &&
|
|
17
|
-
typeof node.from === "string" && typeof node.to === "string" && typeof node.ready === "boolean" && typeof node.completed === "boolean", "历史节点无效。");
|
|
18
|
-
const result = value as unknown as HistoryRecord, ids = new Set(result.nodes.map(node => node.id));
|
|
19
|
-
requireThat(ids.size === result.nodes.length && result.nodes.some(node => node.id === result.id && node.kind === "session") &&
|
|
20
|
-
result.nodes.every(node => [...node.parents, ...node.children].every(id => ids.has(id))), "历史节点关系无效。");
|
|
21
|
-
return result;
|
|
11
|
+
function ordinaryDirectory(path: string) {
|
|
12
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
13
|
+
if (!stat) return false;
|
|
14
|
+
requireThat(stat.isDirectory(), "历史目录必须使用普通目录:" + path);
|
|
15
|
+
return true;
|
|
22
16
|
}
|
|
17
|
+
function sharedDirectory(path: string) {
|
|
18
|
+
const parent = dirname(path);
|
|
19
|
+
return (basename(parent) !== ".pbot" || ordinaryDirectory(parent)) && ordinaryDirectory(path);
|
|
20
|
+
}
|
|
21
|
+
function ensureDirectory(path: string) {
|
|
22
|
+
if (sharedDirectory(path)) return;
|
|
23
|
+
const first = mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
24
|
+
requireThat(sharedDirectory(path), "无法创建历史目录:" + path);
|
|
25
|
+
if (first) {
|
|
26
|
+
const existing = dirname(resolve(first));
|
|
27
|
+
for (let child = resolve(path); child !== existing && child !== dirname(child); child = dirname(child)) {
|
|
28
|
+
syncDirectory(realpathSync(dirname(child)));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function legacyDirectory(root: string, host: HistoryHost) {
|
|
33
|
+
const source = join(root, "." + host), parent = join(source, "pbot"), directory = join(parent, "history");
|
|
34
|
+
return ordinaryDirectory(source) && ordinaryDirectory(parent) && ordinaryDirectory(directory) ? directory : undefined;
|
|
35
|
+
}
|
|
36
|
+
function removeEmptyDirectory(directory: string) {
|
|
37
|
+
try { rmdirSync(directory); syncDirectory(dirname(directory)); }
|
|
38
|
+
catch (error) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
|
|
39
|
+
}
|
|
40
|
+
const names = (directory: string) => readdirSync(directory).filter(name => name.endsWith(".json"));
|
|
41
|
+
const filename = (id: string) => fileId(id) + ".json";
|
|
42
|
+
const diagnostic = (path: string, error: unknown) => path + ": " + String(error);
|
|
43
|
+
function optional<T>(read: () => T): T | undefined {
|
|
44
|
+
try { return read(); }
|
|
45
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
46
|
+
}
|
|
47
|
+
function namedRaw(value: unknown, name: string): RawHistory {
|
|
48
|
+
const raw = rawHistory(value);
|
|
49
|
+
requireThat(name === filename(raw.id), "历史文件名与根 ID 不匹配。");
|
|
50
|
+
return raw;
|
|
51
|
+
}
|
|
52
|
+
const readRaw = (directory: string, name: string) => readJsonFile(directory, "raw/" + name, value => namedRaw(value, name));
|
|
53
|
+
const readSummaries = (directory: string, layer: "summary" | "hierarchical", raw: RawHistory) =>
|
|
54
|
+
optional(() => readJsonFile(directory, layer + "/" + filename(raw.id), value => hierarchicalHistory(value, raw)));
|
|
55
|
+
|
|
56
|
+
type OldFile = { raw: RawHistory; mixed?: HistoryRecord; summaries?: HistorySummary[] };
|
|
57
|
+
function oldFile(value: unknown, name: string, privateHost?: HistoryHost): OldFile {
|
|
58
|
+
if (privateHost === undefined && object(value) && !("nodes" in value)) return { raw: namedRaw(value, name) };
|
|
59
|
+
const mixed = legacyHistory(value, privateHost);
|
|
60
|
+
requireThat(name === filename(mixed.id), "历史文件名与根 ID 不匹配。");
|
|
61
|
+
return { ...splitLegacy(mixed), mixed };
|
|
62
|
+
}
|
|
63
|
+
/** Relocate an already validated file without reserializing it. A separate mount needs an atomic JSON copy instead. */
|
|
64
|
+
function linkArchive(directory: string, from: string, to: string) {
|
|
65
|
+
const target = internalPath(directory, to);
|
|
66
|
+
try { linkSync(internalPath(directory, from), target); }
|
|
67
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "EXDEV") return false; throw error; }
|
|
68
|
+
syncDirectory(dirname(target)); return true;
|
|
69
|
+
}
|
|
70
|
+
function retire(directory: string, relative: string) {
|
|
71
|
+
const path = internalPath(directory, relative);
|
|
72
|
+
unlinkSync(path); syncDirectory(dirname(path));
|
|
73
|
+
}
|
|
74
|
+
|
|
23
75
|
export class HistoryFiles {
|
|
24
76
|
#warnings: string[] = [];
|
|
25
|
-
|
|
77
|
+
#rawWarnings: string[] = [];
|
|
78
|
+
constructor(readonly directory: string, readonly host: HistoryHost = "pi") { requireThat(isHistoryHost(host), "历史来源无效。"); }
|
|
26
79
|
get warnings(): readonly string[] { return this.#warnings; }
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
80
|
+
get rawWarnings(): readonly string[] { return this.#rawWarnings; }
|
|
81
|
+
|
|
82
|
+
list(legacyRoot?: string): HistoryArchive[] {
|
|
83
|
+
this.#warnings = []; this.#rawWarnings = [];
|
|
84
|
+
const archives = new Map<string, HistoryArchive>();
|
|
85
|
+
const rawWarning = (path: string, error: unknown) => {
|
|
86
|
+
const message = diagnostic(path, error); this.#warnings.push(message); this.#rawWarnings.push(message);
|
|
87
|
+
};
|
|
88
|
+
const scan = (directory: string, layout: "private" | "shared" | "raw") => {
|
|
89
|
+
for (const name of names(directory)) {
|
|
90
|
+
const path = join(directory, name);
|
|
35
91
|
try {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
92
|
+
for (;;) {
|
|
93
|
+
const before = lstatSync(path, { bigint: true });
|
|
94
|
+
const file = readJsonFile(directory, name, (value): OldFile | undefined => {
|
|
95
|
+
if (layout !== "private" && object(value) && isHistoryHost(value.host) && value.host !== this.host) return undefined;
|
|
96
|
+
return layout === "raw" ? { raw: namedRaw(value, name) } : oldFile(value, name, layout === "private" ? this.host : undefined);
|
|
97
|
+
});
|
|
98
|
+
if (!file) break;
|
|
99
|
+
const { raw } = file;
|
|
100
|
+
if (file.summaries) { archives.set(raw.id, { raw, summaries: file.summaries }); break; }
|
|
101
|
+
const layer = layout === "raw" ? "summary" : "hierarchical";
|
|
102
|
+
let summaries: HistorySummary[] | null, warning: string | undefined;
|
|
103
|
+
try { summaries = readSummaries(this.directory, layer, raw)?.summaries ?? []; }
|
|
104
|
+
catch (error) { warning = diagnostic(join(this.directory, layer, name), error); summaries = null; }
|
|
105
|
+
// Peers take no lock. Retry if a native update replaced the raw file between reads.
|
|
106
|
+
const after = lstatSync(path, { bigint: true });
|
|
107
|
+
if (before.ino !== after.ino || before.ctimeNs !== after.ctimeNs) continue;
|
|
108
|
+
if (warning) this.#warnings.push(warning);
|
|
109
|
+
archives.set(raw.id, { raw, summaries }); break;
|
|
110
|
+
}
|
|
111
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") rawWarning(path, error); }
|
|
44
112
|
}
|
|
113
|
+
};
|
|
114
|
+
// Read the destinations last: a concurrent migration publishes both files before retiring its source.
|
|
115
|
+
if (legacyRoot && this.host !== "claude") {
|
|
116
|
+
try { const directory = legacyDirectory(legacyRoot, this.host); if (directory) scan(directory, "private"); }
|
|
117
|
+
catch (error) { rawWarning(join(legacyRoot, "." + this.host, "pbot/history"), error); }
|
|
45
118
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (!existsSync(directory)) return;
|
|
55
|
-
const legacyLock = join(directory, ".write");
|
|
56
|
-
mkdirSync(legacyLock, { mode: 0o700 });
|
|
57
|
-
try {
|
|
58
|
-
for (const name of readdirSync(directory).filter(name => name.endsWith(".json"))) {
|
|
59
|
-
const source = internalPath(directory, name), target = internalPath(this.directory, name);
|
|
60
|
-
requireThat(source !== target, "新旧历史目录指向同一位置。");
|
|
61
|
-
const value = readJsonFile(directory, name, value => {
|
|
62
|
-
requireThat(object(value) && (value.host === undefined || value.host === this.host), "旧历史归档与来源目录不匹配。");
|
|
63
|
-
return record({ ...value, host: this.host });
|
|
64
|
-
});
|
|
65
|
-
requireThat(name === fileId(value.id) + ".json", "历史文件名与根 ID 不匹配。");
|
|
66
|
-
if (!writeJsonFile(this.directory, name, value, record, true)) {
|
|
67
|
-
requireThat(canonical(readJsonFile(this.directory, name, record)) === canonical(value),
|
|
68
|
-
"历史归档迁移冲突,请核对新旧文件:" + name);
|
|
69
|
-
}
|
|
70
|
-
syncDirectory(this.directory);
|
|
71
|
-
unlinkSync(source); syncDirectory(directory);
|
|
72
|
-
}
|
|
73
|
-
} finally { rmdirSync(legacyLock); }
|
|
74
|
-
rmdirSync(directory);
|
|
75
|
-
const parent = dirname(directory);
|
|
76
|
-
syncDirectory(parent);
|
|
77
|
-
try { rmdirSync(parent); syncDirectory(dirname(parent)); }
|
|
78
|
-
catch (error) { if (!["ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
|
|
79
|
-
});
|
|
119
|
+
try {
|
|
120
|
+
if (sharedDirectory(this.directory)) {
|
|
121
|
+
scan(this.directory, "shared");
|
|
122
|
+
const directory = join(this.directory, "raw");
|
|
123
|
+
if (ordinaryDirectory(directory)) scan(directory, "raw");
|
|
124
|
+
}
|
|
125
|
+
} catch (error) { rawWarning(this.directory, error); }
|
|
126
|
+
return [...archives.values()];
|
|
80
127
|
}
|
|
128
|
+
|
|
81
129
|
/** The callback is synchronous: no SDK reads or model work can hold this source's write lock. */
|
|
82
130
|
control<T>(operation: () => T): T {
|
|
83
|
-
|
|
131
|
+
requireThat(this.host !== "claude", "Claude 历史归档只读。");
|
|
132
|
+
ensureDirectory(this.directory);
|
|
84
133
|
const lock = join(this.directory, ".write-" + this.host);
|
|
85
134
|
try { mkdirSync(lock, { mode: 0o700 }); }
|
|
86
135
|
catch (error) {
|
|
@@ -89,9 +138,119 @@ export class HistoryFiles {
|
|
|
89
138
|
}
|
|
90
139
|
try { return operation(); } finally { rmdirSync(lock); }
|
|
91
140
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
141
|
+
|
|
142
|
+
private writable(identity: HistoryIdentity) {
|
|
143
|
+
requireThat(this.host !== "claude" && identity.host === this.host, "历史归档只允许所属 Pi/dsh 来源写入。");
|
|
144
|
+
const name = filename(identity.id);
|
|
145
|
+
requireThat(!lstatSync(join(this.directory, name), { throwIfNoEntry: false }), "根 ID 已有旧历史归档:" + name);
|
|
146
|
+
return name;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
saveRaw(raw: RawHistory) {
|
|
150
|
+
const name = this.writable(raw);
|
|
151
|
+
rawHistory(raw); ensureDirectory(this.directory);
|
|
152
|
+
const current = optional(() => readRaw(this.directory, name));
|
|
153
|
+
if (current) {
|
|
154
|
+
matchIdentity(current, raw);
|
|
155
|
+
if (isDeepStrictEqual(current, raw)) return;
|
|
156
|
+
} else {
|
|
157
|
+
for (const layer of ["summary", "hierarchical"]) {
|
|
158
|
+
const directory = join(this.directory, layer);
|
|
159
|
+
if (lstatSync(directory, { throwIfNoEntry: false })?.isDirectory()) {
|
|
160
|
+
requireThat(!lstatSync(join(directory, name), { throwIfNoEntry: false }), "历史根 ID 已有关联的摘要文件:" + name);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
privateDirectory(this.directory, "raw");
|
|
164
|
+
}
|
|
165
|
+
requireThat(writeJsonFile(this.directory, "raw/" + name, raw, rawHistory, !current), "历史根 ID 已被占用:" + name);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
saveSummaries(identity: HistoryIdentity, summaries: readonly HistorySummary[]) {
|
|
169
|
+
const name = this.writable(identity);
|
|
170
|
+
requireThat(sharedDirectory(this.directory), "历史原文目录不存在:" + this.directory);
|
|
171
|
+
const raw = readRaw(this.directory, name);
|
|
172
|
+
matchIdentity(raw, identity);
|
|
173
|
+
this.publishSummaries(raw, summaries);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
private publishSummaries(raw: RawHistory, summaries: readonly HistorySummary[], source?: "mixed" | "hierarchical") {
|
|
177
|
+
const { host, id, sessionId } = raw, path = "summary/" + filename(id);
|
|
178
|
+
const validate = (data: unknown) => hierarchicalHistory(data, raw);
|
|
179
|
+
const value = validate({ host, id, sessionId, summaries: summaries.map(summaryData) });
|
|
180
|
+
const previous = readSummaries(this.directory, "summary", raw);
|
|
181
|
+
if (previous) {
|
|
182
|
+
if (isDeepStrictEqual(previous, value)) {
|
|
183
|
+
if (source) syncDirectory(join(this.directory, "summary"));
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
requireThat(!source, "历史摘要迁移冲突,请核对已有文件:" + path);
|
|
187
|
+
} else {
|
|
188
|
+
privateDirectory(this.directory, "summary");
|
|
189
|
+
if (source === "hierarchical" && linkArchive(this.directory, "hierarchical/" + filename(id), path)) return;
|
|
190
|
+
}
|
|
191
|
+
requireThat(writeJsonFile(this.directory, path, value, validate, !previous), "历史摘要文件已被占用:" + path);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private migrateFile(name: string, privateDir?: string) {
|
|
195
|
+
const readOld = (directory: string, host?: HistoryHost) => readJsonFile(directory, name, value => oldFile(value, name, host));
|
|
196
|
+
const shared = optional(() => readOld(this.directory)), local = privateDir ? readOld(privateDir, this.host) : undefined;
|
|
197
|
+
const source = shared ?? local;
|
|
198
|
+
if (!source) return;
|
|
199
|
+
const { raw } = source;
|
|
200
|
+
if (!local && raw.host !== this.host) return;
|
|
201
|
+
if (shared && local) requireThat(isDeepStrictEqual(shared.raw, local.raw) && (!shared.mixed || isDeepStrictEqual(shared.mixed, local.mixed)),
|
|
202
|
+
"历史归档迁移冲突,请核对新旧文件:" + name);
|
|
203
|
+
const target = optional(() => readRaw(this.directory, name));
|
|
204
|
+
requireThat(!target || isDeepStrictEqual(target, raw), "历史原文迁移冲突,请核对已有文件:" + name);
|
|
205
|
+
const oldLayer = readSummaries(this.directory, "hierarchical", raw), embedded = source.summaries ?? local?.summaries;
|
|
206
|
+
requireThat(!oldLayer || !embedded || isDeepStrictEqual(oldLayer.summaries, embedded), "旧历史摘要不一致:" + name);
|
|
207
|
+
const summaries = embedded ?? oldLayer?.summaries;
|
|
208
|
+
// The raw file makes this pair discoverable. Publish summaries first; never overwrite a migration conflict.
|
|
209
|
+
if (summaries) this.publishSummaries(raw, summaries, oldLayer ? "hierarchical" : "mixed");
|
|
210
|
+
else requireThat(!readSummaries(this.directory, "summary", raw) || target, "历史摘要迁移冲突:" + name);
|
|
211
|
+
if (!target) {
|
|
212
|
+
privateDirectory(this.directory, "raw");
|
|
213
|
+
const path = "raw/" + name;
|
|
214
|
+
if (!shared || shared.mixed || !linkArchive(this.directory, name, path)) {
|
|
215
|
+
requireThat(writeJsonFile(this.directory, path, raw, rawHistory, true), "历史原文迁移冲突:" + name);
|
|
216
|
+
}
|
|
217
|
+
} else syncDirectory(join(this.directory, "raw"));
|
|
218
|
+
syncDirectory(this.directory);
|
|
219
|
+
if (oldLayer) {
|
|
220
|
+
retire(this.directory, "hierarchical/" + name);
|
|
221
|
+
removeEmptyDirectory(join(this.directory, "hierarchical"));
|
|
222
|
+
}
|
|
223
|
+
if (shared) retire(this.directory, name);
|
|
224
|
+
if (privateDir) retire(privateDir, name);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
migrate(root: string) {
|
|
228
|
+
if (this.host === "claude") return;
|
|
229
|
+
const legacy = legacyDirectory(root, this.host);
|
|
230
|
+
const shared = sharedDirectory(this.directory) ? names(this.directory).filter(name => {
|
|
231
|
+
try { return readJsonFile(this.directory, name, value => object(value) && value.host === this.host); }
|
|
232
|
+
catch { return false; } // list reports unreadable roots.
|
|
233
|
+
}) : [];
|
|
234
|
+
if (!legacy && !shared.length) return;
|
|
235
|
+
this.control(() => {
|
|
236
|
+
const directory = legacy && legacyDirectory(root, this.host), errors: string[] = [];
|
|
237
|
+
const migrateFiles = (local: string[]) => {
|
|
238
|
+
const privateNames = new Set(local);
|
|
239
|
+
for (const name of new Set([...local, ...shared])) {
|
|
240
|
+
try { this.migrateFile(name, privateNames.has(name) ? directory : undefined); }
|
|
241
|
+
catch (error) {
|
|
242
|
+
if ((error as NodeJS.ErrnoException).code) throw error;
|
|
243
|
+
errors.push(diagnostic(name, error));
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
if (directory) {
|
|
248
|
+
requireThat(realpathSync(directory) !== realpathSync(this.directory), "新旧历史目录指向同一位置。");
|
|
249
|
+
const lock = join(directory, ".write"); mkdirSync(lock, { mode: 0o700 });
|
|
250
|
+
try { migrateFiles(names(directory)); } finally { rmdirSync(lock); }
|
|
251
|
+
removeEmptyDirectory(directory); removeEmptyDirectory(dirname(directory));
|
|
252
|
+
} else migrateFiles([]);
|
|
253
|
+
if (errors.length) throw new Error(errors.join("\n"));
|
|
254
|
+
});
|
|
96
255
|
}
|
|
97
256
|
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { object } from "../common/json.js";
|
|
2
|
+
import { requireThat } from "../common/validation.js";
|
|
3
|
+
import type { HistoryExchange, HistoryHost, HistoryIdentity, HistoryRecord, HistorySummary, RawHistory } from "../model/history.js";
|
|
4
|
+
import { fileId } from "./file-access.js";
|
|
5
|
+
|
|
6
|
+
const strings = (value: unknown): value is string[] => Array.isArray(value) && value.every(item => typeof item === "string");
|
|
7
|
+
const fields = (value: object, names: readonly string[]) => Object.keys(value).every(key => names.includes(key));
|
|
8
|
+
const rawFields = ["host", "id", "sessionId", "name", "exchanges", "branches"];
|
|
9
|
+
const hierarchyFields = ["host", "id", "sessionId", "summaries"];
|
|
10
|
+
const exchangeFields = ["id", "entryIds", "text", "from", "to", "completed"];
|
|
11
|
+
const summaryFields = [...exchangeFields, "level", "children", "ready"];
|
|
12
|
+
|
|
13
|
+
export const isHistoryHost = (value: unknown): value is HistoryHost => value === "pi" || value === "dsh" || value === "claude";
|
|
14
|
+
|
|
15
|
+
function identity(value: unknown): asserts value is HistoryIdentity {
|
|
16
|
+
requireThat(object(value) && isHistoryHost(value.host) && typeof value.id === "string" &&
|
|
17
|
+
typeof value.sessionId === "string" && value.sessionId.length > 0, "历史归档身份无效。");
|
|
18
|
+
fileId(value.id);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function matchIdentity(value: HistoryIdentity, expected: HistoryIdentity) {
|
|
22
|
+
for (const key of ["host", "id", "sessionId"] as const) {
|
|
23
|
+
requireThat(value[key] === expected[key], `历史归档 ${key} 不匹配,预期 ${expected[key]},实际 ${value[key]}。`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function exchange(value: unknown): value is HistoryExchange & { id: string } {
|
|
28
|
+
return object(value) && typeof value.id === "string" && value.id.length > 0 && strings(value.entryIds) &&
|
|
29
|
+
typeof value.text === "string" && typeof value.from === "string" && typeof value.to === "string" && typeof value.completed === "boolean";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function rawHistory(value: unknown): RawHistory {
|
|
33
|
+
identity(value);
|
|
34
|
+
requireThat(object(value) && fields(value, rawFields) && typeof value.name === "string" &&
|
|
35
|
+
Array.isArray(value.exchanges) && Array.isArray(value.branches), "历史原文归档无效。");
|
|
36
|
+
const ids = new Set<string>();
|
|
37
|
+
for (const item of value.exchanges) {
|
|
38
|
+
requireThat(exchange(item) && fields(item, exchangeFields) && item.entryIds.length > 0, "历史问答或其来源消息 ID 无效。");
|
|
39
|
+
requireThat(item.id !== value.id && !ids.has(item.id), "历史问答 ID 重复:" + item.id);
|
|
40
|
+
ids.add(item.id);
|
|
41
|
+
}
|
|
42
|
+
for (const branch of value.branches) requireThat(strings(branch) && new Set(branch).size === branch.length && branch.every(id => ids.has(id)),
|
|
43
|
+
"历史分支包含重复或未知的问答 ID。");
|
|
44
|
+
return value as unknown as RawHistory;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface HierarchicalHistory extends HistoryIdentity { summaries: HistorySummary[] }
|
|
48
|
+
|
|
49
|
+
export function hierarchicalHistory(value: unknown, raw: RawHistory): HierarchicalHistory {
|
|
50
|
+
identity(value);
|
|
51
|
+
matchIdentity(value, raw);
|
|
52
|
+
requireThat(object(value) && fields(value, hierarchyFields) && Array.isArray(value.summaries), "历史摘要归档无效。");
|
|
53
|
+
const levels = new Map(raw.exchanges.map(item => [item.id, 0]));
|
|
54
|
+
for (const item of value.summaries) {
|
|
55
|
+
requireThat(object(item) && exchange(item) && fields(item, summaryFields) && item.entryIds.length > 0 &&
|
|
56
|
+
typeof item.level === "number" && Number.isSafeInteger(item.level) && item.level > 0 && strings(item.children) && typeof item.ready === "boolean", "历史摘要节点无效。");
|
|
57
|
+
requireThat(item.id !== raw.id && !levels.has(item.id), "历史摘要 ID 重复:" + item.id);
|
|
58
|
+
levels.set(item.id, item.level);
|
|
59
|
+
}
|
|
60
|
+
const result = value as unknown as HierarchicalHistory;
|
|
61
|
+
for (const item of result.summaries) requireThat(item.children.length > 0 && new Set(item.children).size === item.children.length &&
|
|
62
|
+
item.children.every(id => levels.get(id) === item.level - 1), "历史摘要子节点缺失、重复或层级不匹配:" + item.id);
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Old private directories carried the host in their path. Shared records must declare it. */
|
|
67
|
+
export function legacyHistory(value: unknown, host?: HistoryHost): HistoryRecord {
|
|
68
|
+
if (host !== undefined) {
|
|
69
|
+
requireThat(object(value) && (value.host === undefined || value.host === host), "旧历史归档与来源目录不匹配。");
|
|
70
|
+
value = { ...value, host };
|
|
71
|
+
}
|
|
72
|
+
identity(value);
|
|
73
|
+
requireThat(object(value) && typeof value.name === "string" && Array.isArray(value.nodes) &&
|
|
74
|
+
!("exchanges" in value) && !("branches" in value) && !("summaries" in value), "旧历史归档无效。");
|
|
75
|
+
for (const node of value.nodes) requireThat(object(node) && exchange(node) &&
|
|
76
|
+
(node.kind === "session" || node.kind === "exchange" || node.kind === "summary") && Number.isInteger(node.level) &&
|
|
77
|
+
strings(node.parents) && strings(node.children) && typeof node.ready === "boolean", "旧历史节点无效。");
|
|
78
|
+
const result = value as unknown as HistoryRecord, ids = new Set(result.nodes.map(node => node.id));
|
|
79
|
+
const roots = result.nodes.filter(node => node.kind === "session");
|
|
80
|
+
requireThat(ids.size === result.nodes.length && roots.length === 1 && roots[0]!.id === result.id &&
|
|
81
|
+
result.nodes.every(node => [...node.parents, ...node.children].every(id => ids.has(id))), "旧历史节点关系无效。");
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function exchangeData({ id, entryIds, text, from, to, completed }: HistoryExchange & { id: string }) {
|
|
86
|
+
return { id, entryIds, text, from, to, completed };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function summaryData(item: HistorySummary): HistorySummary {
|
|
90
|
+
return { ...exchangeData(item), level: item.level, children: item.children, ready: item.ready };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function splitLegacy(record: HistoryRecord): { raw: RawHistory; summaries: HistorySummary[] } {
|
|
94
|
+
const { host, id, sessionId, name } = record;
|
|
95
|
+
const raw = rawHistory({ host, id, sessionId, name, exchanges: record.nodes.filter(node => node.kind === "exchange").map(exchangeData), branches: [] });
|
|
96
|
+
const summaries = record.nodes.filter(node => node.kind === "summary").map(summaryData);
|
|
97
|
+
return { raw, summaries: hierarchicalHistory({ host, id, sessionId, summaries }, raw).summaries };
|
|
98
|
+
}
|