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.
@@ -12,18 +12,35 @@ export interface HistorySession {
12
12
  /** Earlier partial observations replaced along the same native branch or turn; never persisted. */
13
13
  supersededEntryIds?: string[];
14
14
  }
15
- export interface HistoryNode extends HistoryExchange {
15
+ export interface HistoryIdentity {
16
+ host: HistoryHost;
17
+ id: string;
18
+ sessionId: string;
19
+ }
20
+ export interface RawHistory extends HistoryIdentity {
21
+ name: string;
22
+ /** One entry per archived exchange; array order does not describe a conversation. */
23
+ exchanges: (HistoryExchange & { id: string })[];
24
+ /** Ordered paths observed in the native source. Legacy exchanges can have no known path. */
25
+ branches: string[][];
26
+ }
27
+ export interface HistorySummary extends HistoryExchange {
16
28
  id: string;
17
- kind: "session" | "exchange" | "summary";
18
29
  level: number;
19
30
  children: string[];
20
- parents: string[];
21
31
  ready: boolean;
22
32
  }
23
- export interface HistoryRecord {
24
- host: HistoryHost;
25
- id: string;
26
- sessionId: string;
33
+ export interface HistoryArchive {
34
+ raw: RawHistory;
35
+ /** Empty if absent; null if the derived file is unreadable. */
36
+ summaries: HistorySummary[] | null;
37
+ }
38
+ export interface HistoryNode extends HistorySummary {
39
+ kind: "session" | "exchange" | "summary";
40
+ parents: string[];
41
+ }
42
+ /** Query view and legacy on-disk format. New writers persist raw exchanges and summaries separately. */
43
+ export interface HistoryRecord extends HistoryIdentity {
27
44
  name: string;
28
45
  nodes: HistoryNode[];
29
46
  }
@@ -32,7 +49,7 @@ export type HistoryLocation = { host: "pi"; directory: string; file?: string } |
32
49
  { host: "dsh"; sessionId?: string };
33
50
  export interface HistorySource {
34
51
  readonly host: HistoryLocation["host"];
35
- scan(location: HistoryLocation, signal?: AbortSignal): Promise<{ sessions: HistorySession[]; warnings: string[] }>;
52
+ scan(location: HistoryLocation, signal?: AbortSignal, excluded?: ReadonlySet<string>): Promise<{ sessions: HistorySession[]; warnings: string[] }>;
36
53
  }
37
54
  export interface HistorySummaryRequest {
38
55
  system: string;
package/src/pbot.ts CHANGED
@@ -13,6 +13,7 @@ import { HistoryService } from "./services/history/history-service.js";
13
13
  import { HistoryFiles } from "./storage/history-files.js";
14
14
  import { PiHistory } from "./integrations/pi/history.js";
15
15
  import { sessionRef } from "./storage/agent-files.js";
16
+ import { acpHistorySessions } from "./storage/acp-history.js";
16
17
  import { join } from "node:path";
17
18
  import { registerHistoryEvents } from "./extension/history.js";
18
19
 
@@ -26,7 +27,8 @@ export default function pbot(pi: ExtensionAPI) {
26
27
  agents.files.list().filter(agent => agent.workspace === root).flatMap(agent => {
27
28
  const file = agents.files.optional(agent.agentId, "session-ref.json", sessionRef)?.file;
28
29
  return file ? [file] : [];
29
- })), [new HistoryFiles(join(root, ".pbot/history"), "dsh"), new HistoryFiles(join(root, ".pbot/history"), "claude")]);
30
+ })), [new HistoryFiles(join(root, ".pbot/history"), "dsh"), new HistoryFiles(join(root, ".pbot/history"), "claude")],
31
+ () => acpHistorySessions({ pi: agents.files.root }));
30
32
  return new WorkspaceInstance(root, agents, new TeamService(root, agents.files, agents.teamFiles), history);
31
33
  }, instance => registry.register(mainTools(instance.agents, instance.teams, instance.history, instance)), () => registry.hide());
32
34
  registerCommand(pi, lifecycle, confirmations);
@@ -0,0 +1,125 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import type { HistoryExchange, HistoryHost, HistoryNode, HistoryRecord, HistorySession, HistorySummary, RawHistory } from "../../model/history.js";
4
+ import { requireThat } from "../../common/validation.js";
5
+
6
+ /** Each native entry has one predecessor. A shortened observation can extend a known path, not erase its prefix. */
7
+ function mergeBranches(previous: string[][], observed: string[][], removed: Set<string>): string[][] {
8
+ const parents = new Map<string, string | undefined>();
9
+ for (const branch of [...previous, ...observed]) {
10
+ let parent: string | undefined;
11
+ for (const id of branch) {
12
+ if (removed.has(id)) { parent = undefined; continue; }
13
+ if (parent !== undefined || !parents.has(id)) parents.set(id, parent);
14
+ parent = id;
15
+ }
16
+ }
17
+ const internal = new Set(parents.values()), seen = new Set<string>(), branches: string[][] = [];
18
+ for (const tip of parents.keys()) {
19
+ if (internal.has(tip)) continue;
20
+ const path: string[] = [];
21
+ for (let id: string | undefined = tip; id !== undefined; id = parents.get(id)) {
22
+ requireThat(path.length < parents.size, "历史分支包含循环引用。");
23
+ path.push(id); seen.add(id);
24
+ }
25
+ branches.push(path.reverse());
26
+ }
27
+ requireThat(seen.size === parents.size, "历史分支包含循环引用。");
28
+ return branches;
29
+ }
30
+
31
+ /** Only a native observation can change exchanges or establish branch order. */
32
+ export function indexHistory(session: HistorySession, previous?: RawHistory, host: HistoryHost = previous?.host ?? "pi"): RawHistory {
33
+ requireThat(!previous || previous.host === host && previous.sessionId === session.sessionId, "历史会话与归档来源不匹配。");
34
+ const id = previous?.id ?? (host === "pi" ? "" : host + "-") + randomUUID();
35
+ const exchanges = new Map(previous?.exchanges.map(item => [item.id, item]));
36
+ const byEnd = new Map(previous?.exchanges.map(item => [item.entryIds.at(-1)!, item.id]));
37
+ const observed = new Map<string, HistoryExchange>();
38
+ const branches = session.branches.map(branch => branch.map(value => {
39
+ const end = value.entryIds.at(-1)!;
40
+ const key = byEnd.get(end) ?? `${id}:0:${end}`;
41
+ if (!observed.has(end)) {
42
+ observed.set(end, value);
43
+ const before = exchanges.get(key);
44
+ // Compaction can leave only the last inputs and answer of an already archived exchange.
45
+ if (!(before && value.entryIds.length < before.entryIds.length &&
46
+ value.entryIds.every((entry, i) => entry === before.entryIds[before.entryIds.length - value.entryIds.length + i]))) {
47
+ exchanges.set(key, { ...value, entryIds: [...value.entryIds], id: key });
48
+ }
49
+ }
50
+ return key;
51
+ }));
52
+ const removed = new Set<string>();
53
+ for (const end of session.supersededEntryIds ?? []) {
54
+ const key = byEnd.get(end), item = key === undefined ? undefined : exchanges.get(key);
55
+ if (item && !item.completed && !observed.has(end) && [...observed.values()].some(value =>
56
+ item.entryIds.slice(0, -1).every(entry => value.entryIds.includes(entry)))) {
57
+ removed.add(item.id); exchanges.delete(item.id);
58
+ }
59
+ }
60
+ return { host, id, sessionId: session.sessionId, name: session.name, exchanges: [...exchanges.values()],
61
+ branches: mergeBranches(previous?.branches ?? [], branches, removed) };
62
+ }
63
+
64
+ function span(children: HistoryExchange[]) {
65
+ const first = children[0]!, last = children.at(-1)!;
66
+ return { entryIds: [first.entryIds[0]!, last.entryIds.at(-1)!], from: first.from, to: last.to, completed: children.every(child => child.completed) };
67
+ }
68
+
69
+ /** Retire results using changed inputs before publishing a native correction. New groups need no disk write. */
70
+ export function retainHistorySummaries(before: RawHistory, after: RawHistory, summaries: HistorySummary[]): HistorySummary[] {
71
+ const inputs = new Map<string, HistoryExchange>(after.exchanges.map(item => [item.id, item]));
72
+ const changed = new Set(before.exchanges.filter(item => !isDeepStrictEqual(item, inputs.get(item.id))).map(item => item.id));
73
+ if (!changed.size || !summaries.length) return summaries;
74
+ const retained = new Map<string, HistorySummary>();
75
+ for (const item of [...summaries].sort((a, b) => a.level - b.level)) {
76
+ const children = item.children.map(id => inputs.get(id));
77
+ if (!children.length || !children.every(child => child !== undefined)) { changed.add(item.id); continue; }
78
+ let summary = item;
79
+ if (item.children.some(id => changed.has(id))) {
80
+ summary = { ...item, ...span(children), text: "", ready: false }; changed.add(item.id);
81
+ }
82
+ retained.set(item.id, summary); inputs.set(item.id, summary);
83
+ }
84
+ return summaries.flatMap(item => retained.get(item.id) ?? []);
85
+ }
86
+
87
+ /** The four-way tree is a query view, never the source of native branch order. */
88
+ export function historyView(raw: RawHistory, saved: readonly HistorySummary[] | null = []): HistoryRecord {
89
+ const nodes = new Map<string, HistoryNode>(raw.exchanges.map(value => [value.id,
90
+ { ...value, kind: "exchange", level: 0, ready: true, children: [], parents: [] }]));
91
+ const stored = new Map(saved?.map(value => [value.id, value]));
92
+ const groups = new Map<string, Pick<HistorySummary, "id" | "level" | "children">>(stored);
93
+ for (const branch of raw.branches) {
94
+ let layer = branch.map(id => ({ id, end: nodes.get(id)!.entryIds.at(-1)! }));
95
+ for (let level = 1; layer.length >= 4; level++) {
96
+ const next: typeof layer = [];
97
+ for (let i = 0; i + 4 <= layer.length; i += 4) {
98
+ const end = layer[i + 3]!.end, id = `${raw.id}:${level}:${end}`;
99
+ groups.set(id, { id, level, children: layer.slice(i, i + 4).map(child => child.id) });
100
+ next.push({ id, end });
101
+ }
102
+ layer = next;
103
+ }
104
+ }
105
+ for (const group of [...groups.values()].sort((a, b) => a.level - b.level)) {
106
+ const children = group.children.map(id => nodes.get(id));
107
+ if (!children.length || !children.every(child => child !== undefined)) continue;
108
+ const old = stored.get(group.id);
109
+ const summary = old && isDeepStrictEqual(old.children, group.children) && (!old.ready || children.every(child => child.ready)) ? old :
110
+ { ...group, ...span(children), text: "", ready: false };
111
+ nodes.set(group.id, { ...summary, kind: "summary", parents: [] });
112
+ }
113
+ for (const node of nodes.values()) for (const child of node.children) nodes.get(child)!.parents.push(node.id);
114
+ const top = [...nodes.values()].filter(node => !node.parents.length).sort((a, b) => a.from.localeCompare(b.from));
115
+ for (const child of top) child.parents.push(raw.id);
116
+ const dates = raw.exchanges.flatMap(item => [item.from, item.to]).sort();
117
+ const name = raw.name || raw.exchanges[0]?.text.replace(/\s+/g, " ").slice(0, 80) || "";
118
+ nodes.set(raw.id, { id: raw.id, kind: "session", level: -1, entryIds: [], text: name, ready: true,
119
+ completed: raw.exchanges.every(item => item.completed), from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [], children: top.map(node => node.id) });
120
+ return { host: raw.host, id: raw.id, sessionId: raw.sessionId, name, nodes: [...nodes.values()] };
121
+ }
122
+
123
+ export function historySummaries(record: HistoryRecord): HistorySummary[] {
124
+ return record.nodes.filter(node => node.kind === "summary").map(({ kind: _kind, parents: _parents, ...summary }) => summary);
125
+ }
@@ -1,76 +1,11 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { readFileSync } from "node:fs";
3
2
  import { join } from "node:path";
4
- import type { HistoryExchange, HistoryHost, HistoryLocation, HistoryNode, HistoryRecord, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import type { HistoryArchive, HistoryHost, HistoryIdentity, HistoryLocation, HistoryNode, HistoryRecord, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
5
5
  import type { HistoryFiles } from "../../storage/history-files.js";
6
6
  import { resourceRoot } from "../../common/paths.js";
7
7
  import { requireThat } from "../../common/validation.js";
8
-
9
- const exchangeSource = (value: HistoryExchange) => [value.entryIds, value.text, value.from, value.to, value.completed];
10
-
11
- /** Shared prefixes reuse nodes; a partial scan updates observed nodes and retains archived branches. */
12
- export function indexHistory(session: HistorySession, previous?: HistoryRecord, host: HistoryHost = previous?.host ?? "pi"): HistoryRecord {
13
- requireThat(!previous || previous.host === host && previous.sessionId === session.sessionId, "历史会话与归档来源不匹配。");
14
- const id = previous?.id ?? (host === "pi" ? "" : host + "-") + randomUUID();
15
- const old = new Map(previous?.nodes.map(node => [node.id, node]));
16
- const nodes = new Map<string, HistoryNode>(previous?.nodes.filter(node => node.kind !== "session").map(node => [node.id, {
17
- ...node, entryIds: [...node.entryIds], children: [...node.children], parents: [],
18
- }] satisfies [string, HistoryNode]));
19
- const exchanges = session.branches.flat(), observedEnds = new Set(exchanges.map(value => value.entryIds.at(-1)));
20
- const replaced = new Set(session.supersededEntryIds);
21
- const superseded = new Set([...nodes.values()].filter(node => node.kind === "exchange" && !node.completed &&
22
- !observedEnds.has(node.entryIds.at(-1)) && replaced.has(node.entryIds.at(-1)!) &&
23
- exchanges.some(exchange => node.entryIds.slice(0, -1).every(entry => exchange.entryIds.includes(entry)))).map(node => node.id));
24
- // Native adapters identify replaced observations along the same branch/turn. Preserve
25
- // terminal forks and interrupted exchanges, then rebuild summaries that used old partials.
26
- for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
27
- if (node.children.some(id => superseded.has(id))) superseded.add(node.id);
28
- }
29
- for (const key of superseded) nodes.delete(key);
30
- const observed = new Set<string>(), changed = new Set<string>();
31
- const add = (value: HistoryExchange, level: number, children: string[] = []): HistoryNode => {
32
- const key = `${id}:${level}:${value.entryIds.at(-1)}`;
33
- if (observed.has(key)) return nodes.get(key)!;
34
- const before = old.get(key);
35
- if (!level && before && value.entryIds.length < before.entryIds.length &&
36
- value.entryIds.every((entry, index) => entry === before.entryIds[before.entryIds.length - value.entryIds.length + index])) {
37
- observed.add(key); return nodes.get(key)!;
38
- }
39
- const same = before && JSON.stringify(before.children) === JSON.stringify(children) &&
40
- JSON.stringify(exchangeSource({ ...before, text: level ? "" : before.text })) === JSON.stringify(exchangeSource(value));
41
- const node: HistoryNode = { ...value, entryIds: [...value.entryIds], id: key, kind: level ? "summary" : "exchange", level, children, parents: [],
42
- text: level ? same ? before.text : "" : value.text, ready: level ? Boolean(same && before.ready) : true };
43
- if (!same) changed.add(key);
44
- observed.add(key); nodes.set(key, node); return node;
45
- };
46
- for (const branch of session.branches) {
47
- let layer = branch.map(exchange => add(exchange, 0)), level = 1;
48
- while (layer.length >= 4) {
49
- const count = Math.floor(layer.length / 4) * 4, next: HistoryNode[] = [];
50
- for (let i = 0; i < count; i += 4) {
51
- const children = layer.slice(i, i + 4), first = children[0]!, last = children.at(-1)!;
52
- next.push(add({ entryIds: [first.entryIds[0]!, last.entryIds.at(-1)!], text: "", from: first.from, to: last.to,
53
- completed: children.every(node => node.completed) }, level, children.map(node => node.id)));
54
- }
55
- layer = next; level++;
56
- }
57
- }
58
- // Retained summaries can also depend on an observed prefix. Invalidate all affected ancestors.
59
- for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
60
- const children = node.children.map(id => nodes.get(id)!), first = children[0]!, last = children.at(-1)!;
61
- const value = { entryIds: [first.entryIds[0]!, last.entryIds.at(-1)!], from: first.from, to: last.to,
62
- completed: children.every(child => child.completed) };
63
- if (children.some(child => changed.has(child.id))) { node.text = ""; node.ready = false; changed.add(node.id); }
64
- Object.assign(node, value);
65
- }
66
- const dates = [...nodes.values()].flatMap(node => [node.from, node.to]).sort();
67
- const nested = new Set([...nodes.values()].flatMap(node => node.children));
68
- nodes.set(id, { id, kind: "session", level: -1, entryIds: [], text: session.name, ready: true, completed: [...nodes.values()].every(node => node.completed),
69
- from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [],
70
- children: [...nodes.keys()].filter(key => !nested.has(key)).sort((a, b) => nodes.get(a)!.from.localeCompare(nodes.get(b)!.from)) });
71
- for (const node of nodes.values()) for (const child of node.children) nodes.get(child)!.parents.push(node.id);
72
- return { host, id, sessionId: session.sessionId, name: session.name, nodes: [...nodes.values()] };
73
- }
8
+ import { historySummaries, historyView, indexHistory, retainHistorySummaries } from "./history-index.js";
74
9
 
75
10
  export interface HistoryQuery { host?: HistoryHost; query?: string; sessionId?: string; from?: string; to?: string; offset?: number; limit?: number }
76
11
  type LocatedRecord = { host: HistoryHost; record: HistoryRecord };
@@ -79,20 +14,38 @@ const page = <T>(values: T[], offset: number, limit: number) => ({ values: value
79
14
  nextOffset: offset + limit < values.length ? offset + limit : null });
80
15
  const brief = ({ host, record }: LocatedRecord, node: HistoryNode) => ({ host, id: node.id, kind: node.kind, sessionId: record.sessionId,
81
16
  name: record.name, preview: node.text.replace(/\s+/g, " ").slice(0, 100), from: node.from, to: node.to, ready: node.ready, completed: node.completed });
82
- const rawSource = (record?: HistoryRecord) => record && JSON.stringify({ name: record.name,
83
- nodes: record.nodes.map(node => [node.id, node.kind, node.level, node.entryIds, node.children,
84
- node.kind === "summary" ? "" : node.text, node.from, node.to, node.completed]) });
17
+ const view = ({ raw, summaries }: HistoryArchive): LocatedRecord => ({ host: raw.host, record: historyView(raw, summaries) });
85
18
  const summarySource = (node: HistoryNode) => [node.id, node.kind, node.level, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
86
19
 
87
- /** Validate the exact target and ordered inputs again; another writer's ready summary wins. */
88
- export function completeHistorySummary(record: HistoryRecord, expected: HistoryNode, children: readonly HistoryNode[], text: string) {
89
- const node = record.nodes.find(value => value.id === expected.id);
90
- if (!node || node.kind !== "summary" || node.ready || JSON.stringify(summarySource(node)) !== JSON.stringify(summarySource(expected)) ||
91
- JSON.stringify(node.children) !== JSON.stringify(children.map(child => child.id))) return false;
92
- const current = node.children.map(id => record.nodes.find(value => value.id === id));
93
- if (current.some(value => !value || !value.ready) || JSON.stringify(current.map(value => summarySource(value!))) !== JSON.stringify(children.map(summarySource))) return false;
94
- requireThat(text.trim(), "历史摘要为空。");
95
- node.text = text.trim(); node.ready = true; return true;
20
+ function nextSummary(archives: HistoryArchive[]) {
21
+ for (const { raw, summaries } of archives) {
22
+ if (summaries === null) continue;
23
+ const record = historyView(raw, summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
24
+ const node = record.nodes.find(node => node.kind === "summary" && !node.ready && node.children.every(id => lookup.get(id)!.ready));
25
+ if (node) return { record, node, children: node.children.map(id => lookup.get(id)!) };
26
+ }
27
+ }
28
+
29
+ /** Validate the exact target and ordered inputs under the source lock. Only publish the derived file. */
30
+ export function commitHistorySummary(files: Pick<HistoryFiles, "control" | "list" | "saveSummaries">, identity: HistoryIdentity,
31
+ expected: HistoryNode, children: readonly HistoryNode[], text: string, signal?: AbortSignal): HistoryRecord | undefined {
32
+ return files.control(() => {
33
+ signal?.throwIfAborted();
34
+ const current = files.list().find(({ raw }) => raw.host === identity.host && raw.id === identity.id && raw.sessionId === identity.sessionId);
35
+ if (!current || current.summaries === null) return;
36
+ const record = historyView(current.raw, current.summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
37
+ const node = lookup.get(expected.id);
38
+ if (!node || node.kind !== "summary" || node.ready || !isDeepStrictEqual(summarySource(node), summarySource(expected)) ||
39
+ !isDeepStrictEqual(node.children, children.map(child => child.id))) return;
40
+ for (const child of children) {
41
+ const input = lookup.get(child.id);
42
+ if (!input?.ready || !isDeepStrictEqual(summarySource(input), summarySource(child))) return;
43
+ }
44
+ requireThat(text.trim(), "历史摘要为空。");
45
+ node.text = text.trim(); node.ready = true;
46
+ files.saveSummaries(current.raw, historySummaries(record));
47
+ return record;
48
+ });
96
49
  }
97
50
 
98
51
  export class HistoryService {
@@ -105,7 +58,8 @@ export class HistoryService {
105
58
  #sourceWarnings: string[] = [];
106
59
  #summaryError: string | undefined;
107
60
  constructor(readonly root: string, private readonly files: HistoryFiles, private readonly source: HistorySource,
108
- private readonly otherFiles: readonly HistoryReader[] = []) {
61
+ private readonly otherFiles: readonly HistoryReader[] = [],
62
+ private readonly acpSessions?: () => { ids: Record<HistoryHost, ReadonlySet<string>>; warnings: string[] }) {
109
63
  requireThat((source.host === "pi" || source.host === "dsh") && source.host === files.host &&
110
64
  new Set([files.host, ...otherFiles.map(value => value.host)]).size === otherFiles.length + 1,
111
65
  "历史来源与归档目录不匹配。");
@@ -126,38 +80,50 @@ export class HistoryService {
126
80
  this.check(); signal?.throwIfAborted();
127
81
  const warnings: string[] = [], records: LocatedRecord[] = [];
128
82
  const warning = (host: HistoryHost, error: unknown) => { this.check(); signal?.throwIfAborted(); warnings.push(host + ": " + String(error)); };
129
- let known: HistoryRecord[] = [];
83
+ let known: HistoryArchive[] = [], sessions: HistorySession[] = [];
84
+ try {
85
+ try { this.files.migrate(this.root); } finally { known = this.files.list(this.root); }
86
+ const scanned = await this.source.scan(location, signal, this.acpSessions?.().ids[this.files.host]); sessions = scanned.sessions;
87
+ warnings.push(...scanned.warnings.map(value => this.files.host + ": " + value));
88
+ } catch (error) { warning(this.files.host, error); }
89
+ this.check(); signal?.throwIfAborted();
90
+ // The worker binds the actual backend ID before delivery, possibly during the native scan.
91
+ const excluded = this.acpSessions?.();
92
+ if (excluded) {
93
+ warnings.push(...excluded.warnings);
94
+ sessions = sessions.filter(session => !excluded.ids[this.files.host].has(session.sessionId));
95
+ }
96
+ const visible = ({ raw }: HistoryArchive) => !excluded?.ids[raw.host].has(raw.sessionId);
130
97
  try {
131
- try { this.files.migrate(this.root); } finally { known = this.files.list(); }
132
- const before = known;
133
- let sessions: HistorySession[] = [];
134
- try {
135
- const scanned = await this.source.scan(location, signal); sessions = scanned.sessions;
136
- warnings.push(...scanned.warnings.map(value => this.files.host + ": " + value));
137
- } catch (error) { warning(this.files.host, error); }
138
- this.check(); signal?.throwIfAborted();
139
98
  if (sessions.length) {
99
+ const before = new Map(known.map(({ raw }) => [raw.sessionId, raw]));
140
100
  known = this.files.control(() => {
141
101
  this.check(); signal?.throwIfAborted();
142
- const latest = this.files.list(), current = new Map(latest.map(record => [record.sessionId, record]));
102
+ const current = new Map(this.files.list().map(archive => [archive.raw.sessionId, archive]));
143
103
  for (const session of sessions) {
144
- const previous = current.get(session.sessionId), captured = before.find(record => record.sessionId === session.sessionId);
145
- // An unreadable archive may own this session; avoid assigning it a second root ID.
146
- if (!previous && this.files.warnings.length) continue;
147
- // A concurrent source update must not be overwritten by this older scan. Summary-only updates remain reusable.
148
- if (captured && rawSource(captured) !== rawSource(previous)) continue;
149
- if (!captured && previous) continue;
150
- const value = indexHistory(session, previous, this.files.host);
151
- if (JSON.stringify(previous) !== JSON.stringify(value)) this.files.save(value);
152
- current.set(session.sessionId, value);
104
+ const previous = current.get(session.sessionId);
105
+ // A damaged raw file may own this session; a damaged summary cannot own a root ID.
106
+ if (!previous && this.files.rawWarnings.length) continue;
107
+ if (!isDeepStrictEqual(before.get(session.sessionId), previous?.raw)) continue;
108
+ const raw = indexHistory(session, previous?.raw, this.files.host);
109
+ if (isDeepStrictEqual(raw, previous?.raw)) continue;
110
+ let summaries = previous ? previous.summaries : [];
111
+ if (previous && summaries?.length) {
112
+ const retained = retainHistorySummaries(previous.raw, raw, summaries);
113
+ // Invalidate first: even an interrupted two-file update cannot attach old text to a corrected exchange.
114
+ if (!isDeepStrictEqual(summaries, retained)) this.files.saveSummaries(previous.raw, retained);
115
+ summaries = retained;
116
+ }
117
+ this.files.saveRaw(raw);
118
+ current.set(session.sessionId, { raw, summaries });
153
119
  }
154
120
  return [...current.values()];
155
121
  });
156
122
  }
157
123
  } catch (error) { warning(this.files.host, error); }
158
- records.push(...known.map(record => ({ host: record.host, record })));
124
+ records.push(...known.filter(visible).map(view));
159
125
  for (const files of this.otherFiles) {
160
- try { records.push(...files.list(this.root).map(record => ({ host: record.host, record }))); }
126
+ try { records.push(...files.list(this.root).filter(visible).map(view)); }
161
127
  catch (error) { warning(files.host, error); }
162
128
  }
163
129
  this.check(); signal?.throwIfAborted(); this.#records = records; this.#sourceWarnings = warnings; this.#loaded = true;
@@ -203,22 +169,14 @@ export class HistoryService {
203
169
  const run = async () => {
204
170
  for (;;) {
205
171
  this.check(); active.throwIfAborted();
206
- const pending = this.files.list().flatMap(record => {
207
- const lookup = new Map(record.nodes.map(node => [node.id, node]));
208
- const node = [...record.nodes].sort((a, b) => a.level - b.level).find(node => node.kind === "summary" && !node.ready && node.children.every(id => lookup.get(id)!.ready));
209
- return node ? [{ record, node, children: node.children.map(id => lookup.get(id)!) }] : [];
210
- })[0];
172
+ const archives = this.files.list(), excluded = this.acpSessions?.().ids[this.files.host];
173
+ const pending = nextSummary(archives.filter(({ raw }) => !excluded?.has(raw.sessionId)));
211
174
  if (!pending) return;
212
175
  const { record, node, children } = pending;
213
176
  const text = await summarize({ system: readFileSync(join(resourceRoot, "prompts/history-summary.md"), "utf8"), maxTokens: 2048,
214
177
  prompt: children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n") }, active);
215
178
  this.check(); active.throwIfAborted();
216
- const committed = this.files.control(() => {
217
- this.check(); active.throwIfAborted();
218
- const current = this.files.list().find(value => value.id === record.id && value.sessionId === record.sessionId);
219
- if (!current || !completeHistorySummary(current, node, children, text)) return;
220
- this.files.save(current); return current;
221
- });
179
+ const committed = commitHistorySummary(this.files, record, node, children, text, active);
222
180
  if (!committed) return;
223
181
  this.#records = this.#records.map(value => value.host === this.files.host && value.record.id === committed.id ? { host: value.host, record: committed } : value);
224
182
  }
@@ -0,0 +1,38 @@
1
+ import { readdirSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import type { HistoryHost } from "../model/history.js";
6
+ import { readJsonFile } from "./atomic-json.js";
7
+ import { acpReference } from "./acp-files.js";
8
+
9
+ function memberDirectory(home: string, host: "pi" | "dsh") {
10
+ if (host === "pi" && home.startsWith("file://")) return join(fileURLToPath(home), "pbot/subagents");
11
+ const tilde = home === "~" || home.startsWith("~/") || ((host === "dsh" || process.platform === "win32") && home.startsWith("~\\"));
12
+ return join(tilde ? join(homedir(), home.slice(2)) : home, "pbot/subagents");
13
+ }
14
+
15
+ /** A target session can be owned by either coordinator, even when its cwd belongs to another workspace. */
16
+ export function acpHistorySessions(directories: { pi?: string; dsh?: string }) {
17
+ const ids: Record<HistoryHost, Set<string>> = { pi: new Set(), dsh: new Set(), claude: new Set() };
18
+ const warnings: string[] = [];
19
+ const warn = (path: string, error: unknown) => {
20
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") warnings.push(path + ": " + String(error));
21
+ };
22
+ const homes = { pi: process.env.PI_CODING_AGENT_DIR || "~/.pi/agent", dsh: process.env.DSH_HOME?.trim() ? process.env.DSH_HOME : "~/.dsh" };
23
+ for (const host of ["pi", "dsh"] as const) {
24
+ let directory = directories[host];
25
+ try {
26
+ directory ??= memberDirectory(homes[host], host);
27
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
28
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
29
+ const path = join(directory, entry.name);
30
+ try {
31
+ const ref = readJsonFile(path, "acp-session.json", acpReference);
32
+ if (ref.sessionId !== null) ids[ref.backend].add(ref.sessionId);
33
+ } catch (error) { warn(path, error); }
34
+ }
35
+ } catch (error) { warn(directory ?? homes[host], error); }
36
+ }
37
+ return { ids, warnings };
38
+ }