personal-bot 0.2.16 → 0.2.18

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 (35) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CONTEXT.md +13 -1
  4. package/README.md +2 -2
  5. package/README.zh-CN.md +2 -2
  6. package/docs/file-storage.md +9 -2
  7. package/docs/history.md +5 -7
  8. package/docs/technical-design.md +3 -3
  9. package/lib/dsh.js +4 -4
  10. package/lib/extension/dsh/acp-member.js +2 -1
  11. package/lib/extension/dsh/workspace.js +2 -1
  12. package/lib/integrations/dsh/history.js +1 -2
  13. package/lib/integrations/dsh/root-agents.d.ts +4 -0
  14. package/lib/integrations/dsh/root-agents.js +3 -0
  15. package/lib/model/history.d.ts +26 -7
  16. package/lib/services/history/history-index.d.ts +8 -0
  17. package/lib/services/history/history-index.js +134 -0
  18. package/lib/services/history/history-service.d.ts +3 -5
  19. package/lib/services/history/history-service.js +59 -124
  20. package/lib/storage/history-files.d.ts +9 -6
  21. package/lib/storage/history-files.js +297 -83
  22. package/lib/storage/history-format.d.ts +15 -0
  23. package/lib/storage/history-format.js +86 -0
  24. package/package.json +1 -1
  25. package/src/dsh.ts +3 -2
  26. package/src/extension/dsh/acp-member.ts +2 -1
  27. package/src/extension/dsh/workspace.ts +2 -1
  28. package/src/integrations/dsh/history.ts +1 -2
  29. package/src/integrations/dsh/root-agents.ts +5 -0
  30. package/src/integrations/pi/history.ts +1 -4
  31. package/src/model/history.ts +24 -7
  32. package/src/services/history/history-index.ts +125 -0
  33. package/src/services/history/history-service.ts +56 -106
  34. package/src/storage/history-files.ts +233 -74
  35. package/src/storage/history-format.ts +98 -0
@@ -1,108 +1,185 @@
1
- import { existsSync, mkdirSync, readdirSync, rmdirSync, unlinkSync } from "node:fs";
2
- import { dirname, join } from "node:path";
3
- import { canonical, object } from "../common/json.js";
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";
4
5
  import { requireThat } from "../common/validation.js";
5
6
  import { internalPath, readJsonFile, syncDirectory, writeJsonFile } from "./atomic-json.js";
6
- import { fileId } from "./file-access.js";
7
- const strings = (value) => Array.isArray(value) && value.every(item => typeof item === "string");
8
- function record(value) {
9
- requireThat(object(value) && (value.host === "pi" || value.host === "dsh" || value.host === "claude") &&
10
- typeof value.id === "string" && typeof value.sessionId === "string" &&
11
- typeof value.name === "string" && Array.isArray(value.nodes), "历史索引无效。");
12
- for (const node of value.nodes)
13
- requireThat(object(node) && typeof node.id === "string" &&
14
- ["session", "exchange", "summary"].includes(String(node.kind)) && Number.isInteger(node.level) &&
15
- strings(node.entryIds) && strings(node.parents) && strings(node.children) && typeof node.text === "string" &&
16
- typeof node.from === "string" && typeof node.to === "string" && typeof node.ready === "boolean" && typeof node.completed === "boolean", "历史节点无效。");
17
- const result = value, ids = new Set(result.nodes.map(node => node.id));
18
- requireThat(ids.size === result.nodes.length && result.nodes.some(node => node.id === result.id && node.kind === "session") &&
19
- result.nodes.every(node => [...node.parents, ...node.children].every(id => ids.has(id))), "历史节点关系无效。");
20
- return result;
7
+ import { fileId, privateDirectory } from "./file-access.js";
8
+ import { hierarchicalHistory, isHistoryHost, legacyHistory, matchIdentity, rawHistory, splitLegacy, summaryData } from "./history-format.js";
9
+ function ordinaryDirectory(path) {
10
+ const stat = lstatSync(path, { throwIfNoEntry: false });
11
+ if (!stat)
12
+ return false;
13
+ requireThat(stat.isDirectory(), "历史目录必须使用普通目录:" + path);
14
+ return true;
15
+ }
16
+ function sharedDirectory(path) {
17
+ const parent = dirname(path);
18
+ return (basename(parent) !== ".pbot" || ordinaryDirectory(parent)) && ordinaryDirectory(path);
19
+ }
20
+ function ensureDirectory(path) {
21
+ if (sharedDirectory(path))
22
+ 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, host) {
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) {
37
+ try {
38
+ rmdirSync(directory);
39
+ syncDirectory(dirname(directory));
40
+ }
41
+ catch (error) {
42
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
43
+ throw error;
44
+ }
45
+ }
46
+ const names = (directory) => readdirSync(directory).filter(name => name.endsWith(".json"));
47
+ const filename = (id) => fileId(id) + ".json";
48
+ const diagnostic = (path, error) => path + ": " + String(error);
49
+ function optional(read) {
50
+ try {
51
+ return read();
52
+ }
53
+ catch (error) {
54
+ if (error.code !== "ENOENT")
55
+ throw error;
56
+ }
57
+ }
58
+ function namedRaw(value, name) {
59
+ const raw = rawHistory(value);
60
+ requireThat(name === filename(raw.id), "历史文件名与根 ID 不匹配。");
61
+ return raw;
62
+ }
63
+ const readRaw = (directory, name) => readJsonFile(directory, "raw/" + name, value => namedRaw(value, name));
64
+ const readSummaries = (directory, layer, raw) => optional(() => readJsonFile(directory, layer + "/" + filename(raw.id), value => hierarchicalHistory(value, raw)));
65
+ function oldFile(value, name, privateHost) {
66
+ if (privateHost === undefined && object(value) && !("nodes" in value))
67
+ return { raw: namedRaw(value, name) };
68
+ const mixed = legacyHistory(value, privateHost);
69
+ requireThat(name === filename(mixed.id), "历史文件名与根 ID 不匹配。");
70
+ return { ...splitLegacy(mixed), mixed };
71
+ }
72
+ /** Relocate an already validated file without reserializing it. A separate mount needs an atomic JSON copy instead. */
73
+ function linkArchive(directory, from, to) {
74
+ const target = internalPath(directory, to);
75
+ try {
76
+ linkSync(internalPath(directory, from), target);
77
+ }
78
+ catch (error) {
79
+ if (error.code === "EXDEV")
80
+ return false;
81
+ throw error;
82
+ }
83
+ syncDirectory(dirname(target));
84
+ return true;
85
+ }
86
+ function retire(directory, relative) {
87
+ const path = internalPath(directory, relative);
88
+ unlinkSync(path);
89
+ syncDirectory(dirname(path));
21
90
  }
22
91
  export class HistoryFiles {
23
92
  directory;
24
93
  host;
25
94
  #warnings = [];
95
+ #rawWarnings = [];
26
96
  constructor(directory, host = "pi") {
27
97
  this.directory = directory;
28
98
  this.host = host;
99
+ requireThat(isHistoryHost(host), "历史来源无效。");
29
100
  }
30
101
  get warnings() { return this.#warnings; }
31
- /** A peer can include its legacy directory without migrating or modifying either source. */
102
+ get rawWarnings() { return this.#rawWarnings; }
32
103
  list(legacyRoot) {
33
104
  this.#warnings = [];
34
- const records = new Map();
35
- const directories = [this.directory, ...(legacyRoot && this.host !== "claude" ? [join(legacyRoot, "." + this.host, "pbot/history")] : [])];
36
- for (const directory of directories) {
37
- if (!existsSync(directory))
38
- continue;
39
- for (const name of readdirSync(directory).filter(name => name.endsWith(".json"))) {
105
+ this.#rawWarnings = [];
106
+ const archives = new Map();
107
+ const rawWarning = (path, error) => {
108
+ const message = diagnostic(path, error);
109
+ this.#warnings.push(message);
110
+ this.#rawWarnings.push(message);
111
+ };
112
+ const scan = (directory, layout) => {
113
+ for (const name of names(directory)) {
114
+ const path = join(directory, name);
40
115
  try {
41
- const value = readJsonFile(directory, name, value => {
42
- if (directory === this.directory)
43
- return record(value);
44
- requireThat(object(value) && (value.host === undefined || value.host === this.host), "旧历史归档与来源目录不匹配。");
45
- return record({ ...value, host: this.host });
46
- });
47
- requireThat(name === fileId(value.id) + ".json", "历史文件名与根 ID 不匹配。");
48
- if (value.host === this.host && !records.has(value.id))
49
- records.set(value.id, value);
116
+ for (;;) {
117
+ const before = lstatSync(path, { bigint: true });
118
+ const file = readJsonFile(directory, name, (value) => {
119
+ if (layout !== "private" && object(value) && isHistoryHost(value.host) && value.host !== this.host)
120
+ return undefined;
121
+ return layout === "raw" ? { raw: namedRaw(value, name) } : oldFile(value, name, layout === "private" ? this.host : undefined);
122
+ });
123
+ if (!file)
124
+ break;
125
+ const { raw } = file;
126
+ if (file.summaries) {
127
+ archives.set(raw.id, { raw, summaries: file.summaries });
128
+ break;
129
+ }
130
+ const layer = layout === "raw" ? "summary" : "hierarchical";
131
+ let summaries, warning;
132
+ try {
133
+ summaries = readSummaries(this.directory, layer, raw)?.summaries ?? [];
134
+ }
135
+ catch (error) {
136
+ warning = diagnostic(join(this.directory, layer, name), error);
137
+ summaries = null;
138
+ }
139
+ // Peers take no lock. Retry if a native update replaced the raw file between reads.
140
+ const after = lstatSync(path, { bigint: true });
141
+ if (before.ino !== after.ino || before.ctimeNs !== after.ctimeNs)
142
+ continue;
143
+ if (warning)
144
+ this.#warnings.push(warning);
145
+ archives.set(raw.id, { raw, summaries });
146
+ break;
147
+ }
50
148
  }
51
149
  catch (error) {
52
- this.#warnings.push(join(directory, name) + ": " + String(error));
53
- }
54
- }
55
- }
56
- return [...records.values()];
57
- }
58
- /** Publish each legacy archive with its directory's host before removing the old copy. */
59
- migrate(root) {
60
- if (this.host !== "pi" && this.host !== "dsh")
61
- return;
62
- const directory = join(root, "." + this.host, "pbot/history");
63
- if (!existsSync(directory))
64
- return;
65
- this.control(() => {
66
- if (!existsSync(directory))
67
- return;
68
- const legacyLock = join(directory, ".write");
69
- mkdirSync(legacyLock, { mode: 0o700 });
70
- try {
71
- for (const name of readdirSync(directory).filter(name => name.endsWith(".json"))) {
72
- const source = internalPath(directory, name), target = internalPath(this.directory, name);
73
- requireThat(source !== target, "新旧历史目录指向同一位置。");
74
- const value = readJsonFile(directory, name, value => {
75
- requireThat(object(value) && (value.host === undefined || value.host === this.host), "旧历史归档与来源目录不匹配。");
76
- return record({ ...value, host: this.host });
77
- });
78
- requireThat(name === fileId(value.id) + ".json", "历史文件名与根 ID 不匹配。");
79
- if (!writeJsonFile(this.directory, name, value, record, true)) {
80
- requireThat(canonical(readJsonFile(this.directory, name, record)) === canonical(value), "历史归档迁移冲突,请核对新旧文件:" + name);
81
- }
82
- syncDirectory(this.directory);
83
- unlinkSync(source);
84
- syncDirectory(directory);
150
+ if (error.code !== "ENOENT")
151
+ rawWarning(path, error);
85
152
  }
86
153
  }
87
- finally {
88
- rmdirSync(legacyLock);
89
- }
90
- rmdirSync(directory);
91
- const parent = dirname(directory);
92
- syncDirectory(parent);
154
+ };
155
+ // Read the destinations last: a concurrent migration publishes both files before retiring its source.
156
+ if (legacyRoot && this.host !== "claude") {
93
157
  try {
94
- rmdirSync(parent);
95
- syncDirectory(dirname(parent));
158
+ const directory = legacyDirectory(legacyRoot, this.host);
159
+ if (directory)
160
+ scan(directory, "private");
96
161
  }
97
162
  catch (error) {
98
- if (!["ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
99
- throw error;
163
+ rawWarning(join(legacyRoot, "." + this.host, "pbot/history"), error);
100
164
  }
101
- });
165
+ }
166
+ try {
167
+ if (sharedDirectory(this.directory)) {
168
+ scan(this.directory, "shared");
169
+ const directory = join(this.directory, "raw");
170
+ if (ordinaryDirectory(directory))
171
+ scan(directory, "raw");
172
+ }
173
+ }
174
+ catch (error) {
175
+ rawWarning(this.directory, error);
176
+ }
177
+ return [...archives.values()];
102
178
  }
103
179
  /** The callback is synchronous: no SDK reads or model work can hold this source's write lock. */
104
180
  control(operation) {
105
- mkdirSync(this.directory, { recursive: true, mode: 0o700 });
181
+ requireThat(this.host !== "claude", "Claude 历史归档只读。");
182
+ ensureDirectory(this.directory);
106
183
  const lock = join(this.directory, ".write-" + this.host);
107
184
  try {
108
185
  mkdirSync(lock, { mode: 0o700 });
@@ -119,9 +196,146 @@ export class HistoryFiles {
119
196
  rmdirSync(lock);
120
197
  }
121
198
  }
122
- save(value) {
123
- requireThat(value.host === this.host, "历史归档与来源不匹配。");
124
- mkdirSync(this.directory, { recursive: true, mode: 0o700 });
125
- writeJsonFile(this.directory, fileId(value.id) + ".json", value, record);
199
+ writable(identity) {
200
+ requireThat(this.host !== "claude" && identity.host === this.host, "历史归档只允许所属 Pi/dsh 来源写入。");
201
+ const name = filename(identity.id);
202
+ requireThat(!lstatSync(join(this.directory, name), { throwIfNoEntry: false }), "根 ID 已有旧历史归档:" + name);
203
+ return name;
204
+ }
205
+ saveRaw(raw) {
206
+ const name = this.writable(raw);
207
+ rawHistory(raw);
208
+ ensureDirectory(this.directory);
209
+ const current = optional(() => readRaw(this.directory, name));
210
+ if (current) {
211
+ matchIdentity(current, raw);
212
+ if (isDeepStrictEqual(current, raw))
213
+ return;
214
+ }
215
+ else {
216
+ for (const layer of ["summary", "hierarchical"]) {
217
+ const directory = join(this.directory, layer);
218
+ if (lstatSync(directory, { throwIfNoEntry: false })?.isDirectory()) {
219
+ requireThat(!lstatSync(join(directory, name), { throwIfNoEntry: false }), "历史根 ID 已有关联的摘要文件:" + name);
220
+ }
221
+ }
222
+ privateDirectory(this.directory, "raw");
223
+ }
224
+ requireThat(writeJsonFile(this.directory, "raw/" + name, raw, rawHistory, !current), "历史根 ID 已被占用:" + name);
225
+ }
226
+ saveSummaries(identity, summaries) {
227
+ const name = this.writable(identity);
228
+ requireThat(sharedDirectory(this.directory), "历史原文目录不存在:" + this.directory);
229
+ const raw = readRaw(this.directory, name);
230
+ matchIdentity(raw, identity);
231
+ this.publishSummaries(raw, summaries);
232
+ }
233
+ publishSummaries(raw, summaries, source) {
234
+ const { host, id, sessionId } = raw, path = "summary/" + filename(id);
235
+ const validate = (data) => hierarchicalHistory(data, raw);
236
+ const value = validate({ host, id, sessionId, summaries: summaries.map(summaryData) });
237
+ const previous = readSummaries(this.directory, "summary", raw);
238
+ if (previous) {
239
+ if (isDeepStrictEqual(previous, value)) {
240
+ if (source)
241
+ syncDirectory(join(this.directory, "summary"));
242
+ return;
243
+ }
244
+ requireThat(!source, "历史摘要迁移冲突,请核对已有文件:" + path);
245
+ }
246
+ else {
247
+ privateDirectory(this.directory, "summary");
248
+ if (source === "hierarchical" && linkArchive(this.directory, "hierarchical/" + filename(id), path))
249
+ return;
250
+ }
251
+ requireThat(writeJsonFile(this.directory, path, value, validate, !previous), "历史摘要文件已被占用:" + path);
252
+ }
253
+ migrateFile(name, privateDir) {
254
+ const readOld = (directory, host) => readJsonFile(directory, name, value => oldFile(value, name, host));
255
+ const shared = optional(() => readOld(this.directory)), local = privateDir ? readOld(privateDir, this.host) : undefined;
256
+ const source = shared ?? local;
257
+ if (!source)
258
+ return;
259
+ const { raw } = source;
260
+ if (!local && raw.host !== this.host)
261
+ return;
262
+ if (shared && local)
263
+ requireThat(isDeepStrictEqual(shared.raw, local.raw) && (!shared.mixed || isDeepStrictEqual(shared.mixed, local.mixed)), "历史归档迁移冲突,请核对新旧文件:" + name);
264
+ const target = optional(() => readRaw(this.directory, name));
265
+ requireThat(!target || isDeepStrictEqual(target, raw), "历史原文迁移冲突,请核对已有文件:" + name);
266
+ const oldLayer = readSummaries(this.directory, "hierarchical", raw), embedded = source.summaries ?? local?.summaries;
267
+ requireThat(!oldLayer || !embedded || isDeepStrictEqual(oldLayer.summaries, embedded), "旧历史摘要不一致:" + name);
268
+ const summaries = embedded ?? oldLayer?.summaries;
269
+ // The raw file makes this pair discoverable. Publish summaries first; never overwrite a migration conflict.
270
+ if (summaries)
271
+ this.publishSummaries(raw, summaries, oldLayer ? "hierarchical" : "mixed");
272
+ else
273
+ requireThat(!readSummaries(this.directory, "summary", raw) || target, "历史摘要迁移冲突:" + name);
274
+ if (!target) {
275
+ privateDirectory(this.directory, "raw");
276
+ const path = "raw/" + name;
277
+ if (!shared || shared.mixed || !linkArchive(this.directory, name, path)) {
278
+ requireThat(writeJsonFile(this.directory, path, raw, rawHistory, true), "历史原文迁移冲突:" + name);
279
+ }
280
+ }
281
+ else
282
+ syncDirectory(join(this.directory, "raw"));
283
+ syncDirectory(this.directory);
284
+ if (oldLayer) {
285
+ retire(this.directory, "hierarchical/" + name);
286
+ removeEmptyDirectory(join(this.directory, "hierarchical"));
287
+ }
288
+ if (shared)
289
+ retire(this.directory, name);
290
+ if (privateDir)
291
+ retire(privateDir, name);
292
+ }
293
+ migrate(root) {
294
+ if (this.host === "claude")
295
+ return;
296
+ const legacy = legacyDirectory(root, this.host);
297
+ const shared = sharedDirectory(this.directory) ? names(this.directory).filter(name => {
298
+ try {
299
+ return readJsonFile(this.directory, name, value => object(value) && value.host === this.host);
300
+ }
301
+ catch {
302
+ return false;
303
+ } // list reports unreadable roots.
304
+ }) : [];
305
+ if (!legacy && !shared.length)
306
+ return;
307
+ this.control(() => {
308
+ const directory = legacy && legacyDirectory(root, this.host), errors = [];
309
+ const migrateFiles = (local) => {
310
+ const privateNames = new Set(local);
311
+ for (const name of new Set([...local, ...shared])) {
312
+ try {
313
+ this.migrateFile(name, privateNames.has(name) ? directory : undefined);
314
+ }
315
+ catch (error) {
316
+ if (error.code)
317
+ throw error;
318
+ errors.push(diagnostic(name, error));
319
+ }
320
+ }
321
+ };
322
+ if (directory) {
323
+ requireThat(realpathSync(directory) !== realpathSync(this.directory), "新旧历史目录指向同一位置。");
324
+ const lock = join(directory, ".write");
325
+ mkdirSync(lock, { mode: 0o700 });
326
+ try {
327
+ migrateFiles(names(directory));
328
+ }
329
+ finally {
330
+ rmdirSync(lock);
331
+ }
332
+ removeEmptyDirectory(directory);
333
+ removeEmptyDirectory(dirname(directory));
334
+ }
335
+ else
336
+ migrateFiles([]);
337
+ if (errors.length)
338
+ throw new Error(errors.join("\n"));
339
+ });
126
340
  }
127
341
  }
@@ -0,0 +1,15 @@
1
+ import type { HistoryHost, HistoryIdentity, HistoryRecord, HistorySummary, RawHistory } from "../model/history.js";
2
+ export declare const isHistoryHost: (value: unknown) => value is HistoryHost;
3
+ export declare function matchIdentity(value: HistoryIdentity, expected: HistoryIdentity): void;
4
+ export declare function rawHistory(value: unknown): RawHistory;
5
+ export interface HierarchicalHistory extends HistoryIdentity {
6
+ summaries: HistorySummary[];
7
+ }
8
+ export declare function hierarchicalHistory(value: unknown, raw: RawHistory): HierarchicalHistory;
9
+ /** Old private directories carried the host in their path. Shared records must declare it. */
10
+ export declare function legacyHistory(value: unknown, host?: HistoryHost): HistoryRecord;
11
+ export declare function summaryData(item: HistorySummary): HistorySummary;
12
+ export declare function splitLegacy(record: HistoryRecord): {
13
+ raw: RawHistory;
14
+ summaries: HistorySummary[];
15
+ };
@@ -0,0 +1,86 @@
1
+ import { object } from "../common/json.js";
2
+ import { requireThat } from "../common/validation.js";
3
+ import { fileId } from "./file-access.js";
4
+ const strings = (value) => Array.isArray(value) && value.every(item => typeof item === "string");
5
+ const fields = (value, names) => Object.keys(value).every(key => names.includes(key));
6
+ const rawFields = ["host", "id", "sessionId", "name", "exchanges", "branches"];
7
+ const hierarchyFields = ["host", "id", "sessionId", "summaries"];
8
+ const exchangeFields = ["id", "entryIds", "text", "from", "to", "completed"];
9
+ const summaryFields = [...exchangeFields, "level", "children", "ready"];
10
+ export const isHistoryHost = (value) => value === "pi" || value === "dsh" || value === "claude";
11
+ function identity(value) {
12
+ requireThat(object(value) && isHistoryHost(value.host) && typeof value.id === "string" &&
13
+ typeof value.sessionId === "string" && value.sessionId.length > 0, "历史归档身份无效。");
14
+ fileId(value.id);
15
+ }
16
+ export function matchIdentity(value, expected) {
17
+ for (const key of ["host", "id", "sessionId"]) {
18
+ requireThat(value[key] === expected[key], `历史归档 ${key} 不匹配,预期 ${expected[key]},实际 ${value[key]}。`);
19
+ }
20
+ }
21
+ function exchange(value) {
22
+ return object(value) && typeof value.id === "string" && value.id.length > 0 && strings(value.entryIds) &&
23
+ typeof value.text === "string" && typeof value.from === "string" && typeof value.to === "string" && typeof value.completed === "boolean";
24
+ }
25
+ export function rawHistory(value) {
26
+ identity(value);
27
+ requireThat(object(value) && fields(value, rawFields) && typeof value.name === "string" &&
28
+ Array.isArray(value.exchanges) && Array.isArray(value.branches), "历史原文归档无效。");
29
+ const ids = new Set();
30
+ for (const item of value.exchanges) {
31
+ requireThat(exchange(item) && fields(item, exchangeFields) && item.entryIds.length > 0, "历史问答或其来源消息 ID 无效。");
32
+ requireThat(item.id !== value.id && !ids.has(item.id), "历史问答 ID 重复:" + item.id);
33
+ ids.add(item.id);
34
+ }
35
+ for (const branch of value.branches)
36
+ requireThat(strings(branch) && new Set(branch).size === branch.length && branch.every(id => ids.has(id)), "历史分支包含重复或未知的问答 ID。");
37
+ return value;
38
+ }
39
+ export function hierarchicalHistory(value, raw) {
40
+ identity(value);
41
+ matchIdentity(value, raw);
42
+ requireThat(object(value) && fields(value, hierarchyFields) && Array.isArray(value.summaries), "历史摘要归档无效。");
43
+ const levels = new Map(raw.exchanges.map(item => [item.id, 0]));
44
+ for (const item of value.summaries) {
45
+ requireThat(object(item) && exchange(item) && fields(item, summaryFields) && item.entryIds.length > 0 &&
46
+ typeof item.level === "number" && Number.isSafeInteger(item.level) && item.level > 0 && strings(item.children) && typeof item.ready === "boolean", "历史摘要节点无效。");
47
+ requireThat(item.id !== raw.id && !levels.has(item.id), "历史摘要 ID 重复:" + item.id);
48
+ levels.set(item.id, item.level);
49
+ }
50
+ const result = value;
51
+ for (const item of result.summaries)
52
+ requireThat(item.children.length > 0 && new Set(item.children).size === item.children.length &&
53
+ item.children.every(id => levels.get(id) === item.level - 1), "历史摘要子节点缺失、重复或层级不匹配:" + item.id);
54
+ return result;
55
+ }
56
+ /** Old private directories carried the host in their path. Shared records must declare it. */
57
+ export function legacyHistory(value, host) {
58
+ if (host !== undefined) {
59
+ requireThat(object(value) && (value.host === undefined || value.host === host), "旧历史归档与来源目录不匹配。");
60
+ value = { ...value, host };
61
+ }
62
+ identity(value);
63
+ requireThat(object(value) && typeof value.name === "string" && Array.isArray(value.nodes) &&
64
+ !("exchanges" in value) && !("branches" in value) && !("summaries" in value), "旧历史归档无效。");
65
+ for (const node of value.nodes)
66
+ requireThat(object(node) && exchange(node) &&
67
+ (node.kind === "session" || node.kind === "exchange" || node.kind === "summary") && Number.isInteger(node.level) &&
68
+ strings(node.parents) && strings(node.children) && typeof node.ready === "boolean", "旧历史节点无效。");
69
+ const result = value, ids = new Set(result.nodes.map(node => node.id));
70
+ const roots = result.nodes.filter(node => node.kind === "session");
71
+ requireThat(ids.size === result.nodes.length && roots.length === 1 && roots[0].id === result.id &&
72
+ result.nodes.every(node => [...node.parents, ...node.children].every(id => ids.has(id))), "旧历史节点关系无效。");
73
+ return result;
74
+ }
75
+ function exchangeData({ id, entryIds, text, from, to, completed }) {
76
+ return { id, entryIds, text, from, to, completed };
77
+ }
78
+ export function summaryData(item) {
79
+ return { ...exchangeData(item), level: item.level, children: item.children, ready: item.ready };
80
+ }
81
+ export function splitLegacy(record) {
82
+ const { host, id, sessionId, name } = record;
83
+ const raw = rawHistory({ host, id, sessionId, name, exchanges: record.nodes.filter(node => node.kind === "exchange").map(exchangeData), branches: [] });
84
+ const summaries = record.nodes.filter(node => node.kind === "summary").map(summaryData);
85
+ return { raw, summaries: hierarchicalHistory({ host, id, sessionId, summaries }, raw).summaries };
86
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "personal-bot",
3
- "version": "0.2.16",
3
+ "version": "0.2.18",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/realqiyan/personal-bot.git"
package/src/dsh.ts CHANGED
@@ -3,6 +3,7 @@ import { registerDshCommand } from "./extension/dsh/command.js";
3
3
  import { registerDshManagement } from "./extension/dsh/management.js";
4
4
  import { DshWorkspaces, dshDependencies } from "./extension/dsh/workspace.js";
5
5
  import { requireThat } from "./common/validation.js";
6
+ import { rootAgents } from "./integrations/dsh/root-agents.js";
6
7
 
7
8
  export const name = "personal-bot";
8
9
  export const inject = ["commands", "typert", ...dshDependencies];
@@ -16,7 +17,7 @@ export async function apply(ctx: Context) {
16
17
  const management = registerDshManagement(ctx, workspaces);
17
18
  registerDshCommand(ctx, workspaces, management);
18
19
  ctx.on("agent/created", async ({ agent }) => {
19
- if (ctx.agents.roots().includes(agent) && agent.session.header.origin !== "subagent") await workspaces.open(agent);
20
+ if (rootAgents(ctx.agents).includes(agent)) await workspaces.open(agent);
20
21
  });
21
- for (const agent of ctx.agents.roots()) if (agent.session.header.origin !== "subagent") await workspaces.open(agent);
22
+ for (const agent of rootAgents(ctx.agents)) await workspaces.open(agent);
22
23
  }
@@ -1,6 +1,7 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { AcpInput } from "../../model/acp.js";
3
3
  import { acpMember } from "../acp-member.js";
4
+ import { rootAgents } from "../../integrations/dsh/root-agents.js";
4
5
  import { dshResources, dshExpertTools } from "../../integrations/dsh/resources.js";
5
6
  import { registerDshSkills } from "../../integrations/dsh/skills.js";
6
7
  import { finalDshAnswer } from "../../integrations/dsh/messages.js";
@@ -17,7 +18,7 @@ export async function apply(ctx: Context) {
17
18
  member.input(); return next();
18
19
  });
19
20
  ctx.on("agent/created", async ({ agent, source }) => {
20
- if (!ctx.agents.roots().includes(agent)) return;
21
+ if (!rootAgents(ctx.agents).includes(agent)) return;
21
22
  if (source === "resume") agent.inbox.clear();
22
23
  const reference = member.files.reference(member.id);
23
24
  requireThat(reference.host === "acp" && reference.backend === "dsh" && agent.session.header.cwd === member.d.cwd &&
@@ -6,6 +6,7 @@ import type { FileBlock, ImageBlock } from "@deepseek-ai/dsh-llm";
6
6
  import { AgentBackends } from "../../integrations/acp/agents.js";
7
7
  import type { AcpCommands } from "../../model/acp.js";
8
8
  import type { AgentOwner } from "../../model/agent.js";
9
+ import { rootAgents } from "../../integrations/dsh/root-agents.js";
9
10
  import { DshAgents } from "../../integrations/dsh/dsh-agents.js";
10
11
  import { dshResources, dshExpertTools } from "../../integrations/dsh/resources.js";
11
12
  import { AgentService } from "../../services/agents/agent-service.js";
@@ -157,7 +158,7 @@ export class DshWorkspaces {
157
158
 
158
159
  async open(agent: Agent) {
159
160
  this.#lifetime.signal.throwIfAborted();
160
- requireThat(this.ctx.agents.roots().includes(agent) && agent.session.header.origin !== "subagent", "专家不拥有协调者管理入口。");
161
+ requireThat(rootAgents(this.ctx.agents).includes(agent), "专家不拥有协调者管理入口。");
161
162
  const current = this.#parents.get(agent);
162
163
  if (current) return current;
163
164
  const opening = (async () => {
@@ -42,8 +42,7 @@ export function projectDshHistory(header: SessionHeader, events: readonly Sessio
42
42
  else if (event.type === "turn/end") finish(event.data.reason.kind === "completed");
43
43
  }
44
44
  finish();
45
- return { sessionId: header.id, name: name || exchanges[0]?.text.replace(/\s+/g, " ").slice(0, 80) || "",
46
- branches: exchanges.length ? [exchanges] : [], supersededEntryIds };
45
+ return { sessionId: header.id, name, branches: exchanges.length ? [exchanges] : [], supersededEntryIds };
47
46
  }
48
47
 
49
48
  export class DshHistory implements HistorySource {
@@ -0,0 +1,5 @@
1
+ import type { Agent, AgentRegistry } from "@deepseek-ai/dsh-agent";
2
+
3
+ export function rootAgents(registry: Pick<AgentRegistry, "list"> & { roots?: () => Agent[] }): Agent[] {
4
+ return (registry.roots?.() ?? registry.list()).filter(agent => agent.session.header.origin !== "subagent");
5
+ }
@@ -66,10 +66,7 @@ export class PiHistory implements HistorySource {
66
66
  signal?.throwIfAborted();
67
67
  try {
68
68
  const session = projectHistory(await readFile(file, { encoding: "utf8", signal }));
69
- if (session.branches.length) {
70
- session.name ||= session.branches[0]![0]!.text.replace(/\s+/g, " ").slice(0, 80);
71
- sessions.push(session);
72
- }
69
+ if (session.branches.length) sessions.push(session);
73
70
  } catch (error) {
74
71
  signal?.throwIfAborted();
75
72
  // Pi reserves a filename before the first message; copied archives may also outlive their native files.