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.
@@ -1,113 +1,55 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { readFileSync } from "node:fs";
3
2
  import { join } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
4
  import { resourceRoot } from "../../common/paths.js";
5
5
  import { requireThat } from "../../common/validation.js";
6
- const exchangeSource = (value) => [value.entryIds, value.text, value.from, value.to, value.completed];
7
- /** Shared prefixes reuse nodes; a partial scan updates observed nodes and retains archived branches. */
8
- export function indexHistory(session, previous, host = previous?.host ?? "pi") {
9
- requireThat(!previous || previous.host === host && previous.sessionId === session.sessionId, "历史会话与归档来源不匹配。");
10
- const id = previous?.id ?? (host === "pi" ? "" : host + "-") + randomUUID();
11
- const old = new Map(previous?.nodes.map(node => [node.id, node]));
12
- const nodes = new Map(previous?.nodes.filter(node => node.kind !== "session").map(node => [node.id, {
13
- ...node, entryIds: [...node.entryIds], children: [...node.children], parents: [],
14
- }]));
15
- const exchanges = session.branches.flat(), observedEnds = new Set(exchanges.map(value => value.entryIds.at(-1)));
16
- const replaced = new Set(session.supersededEntryIds);
17
- const superseded = new Set([...nodes.values()].filter(node => node.kind === "exchange" && !node.completed &&
18
- !observedEnds.has(node.entryIds.at(-1)) && replaced.has(node.entryIds.at(-1)) &&
19
- exchanges.some(exchange => node.entryIds.slice(0, -1).every(entry => exchange.entryIds.includes(entry)))).map(node => node.id));
20
- // Native adapters identify replaced observations along the same branch/turn. Preserve
21
- // terminal forks and interrupted exchanges, then rebuild summaries that used old partials.
22
- for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
23
- if (node.children.some(id => superseded.has(id)))
24
- superseded.add(node.id);
25
- }
26
- for (const key of superseded)
27
- nodes.delete(key);
28
- const observed = new Set(), changed = new Set();
29
- const add = (value, level, children = []) => {
30
- const key = `${id}:${level}:${value.entryIds.at(-1)}`;
31
- if (observed.has(key))
32
- return nodes.get(key);
33
- const before = old.get(key);
34
- if (!level && before && value.entryIds.length < before.entryIds.length &&
35
- value.entryIds.every((entry, index) => entry === before.entryIds[before.entryIds.length - value.entryIds.length + index])) {
36
- observed.add(key);
37
- 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 = { ...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)
44
- changed.add(key);
45
- observed.add(key);
46
- nodes.set(key, node);
47
- return node;
48
- };
49
- for (const branch of session.branches) {
50
- let layer = branch.map(exchange => add(exchange, 0)), level = 1;
51
- while (layer.length >= 4) {
52
- const count = Math.floor(layer.length / 4) * 4, next = [];
53
- for (let i = 0; i < count; i += 4) {
54
- const children = layer.slice(i, i + 4), first = children[0], last = children.at(-1);
55
- next.push(add({ entryIds: [first.entryIds[0], last.entryIds.at(-1)], text: "", from: first.from, to: last.to,
56
- completed: children.every(node => node.completed) }, level, children.map(node => node.id)));
57
- }
58
- layer = next;
59
- level++;
60
- }
61
- }
62
- // Retained summaries can also depend on an observed prefix. Invalidate all affected ancestors.
63
- for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
64
- const children = node.children.map(id => nodes.get(id)), first = children[0], last = children.at(-1);
65
- const value = { entryIds: [first.entryIds[0], last.entryIds.at(-1)], from: first.from, to: last.to,
66
- completed: children.every(child => child.completed) };
67
- if (children.some(child => changed.has(child.id))) {
68
- node.text = "";
69
- node.ready = false;
70
- changed.add(node.id);
71
- }
72
- Object.assign(node, value);
73
- }
74
- const dates = [...nodes.values()].flatMap(node => [node.from, node.to]).sort();
75
- const nested = new Set([...nodes.values()].flatMap(node => node.children));
76
- nodes.set(id, { id, kind: "session", level: -1, entryIds: [], text: session.name, ready: true, completed: [...nodes.values()].every(node => node.completed),
77
- from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [],
78
- children: [...nodes.keys()].filter(key => !nested.has(key)).sort((a, b) => nodes.get(a).from.localeCompare(nodes.get(b).from)) });
79
- for (const node of nodes.values())
80
- for (const child of node.children)
81
- nodes.get(child).parents.push(node.id);
82
- return { host, id, sessionId: session.sessionId, name: session.name, nodes: [...nodes.values()] };
83
- }
6
+ import { historySummaries, historyView, indexHistory, retainHistorySummaries } from "./history-index.js";
84
7
  const page = (values, offset, limit) => ({ values: values.slice(offset, offset + limit),
85
8
  nextOffset: offset + limit < values.length ? offset + limit : null });
86
9
  const brief = ({ host, record }, node) => ({ host, id: node.id, kind: node.kind, sessionId: record.sessionId,
87
10
  name: record.name, preview: node.text.replace(/\s+/g, " ").slice(0, 100), from: node.from, to: node.to, ready: node.ready, completed: node.completed });
88
- const rawSource = (record) => record && JSON.stringify({ name: record.name,
89
- nodes: record.nodes.map(node => [node.id, node.kind, node.level, node.entryIds, node.children,
90
- node.kind === "summary" ? "" : node.text, node.from, node.to, node.completed]) });
11
+ const view = ({ raw, summaries }) => ({ host: raw.host, record: historyView(raw, summaries) });
91
12
  const summarySource = (node) => [node.id, node.kind, node.level, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
92
- /** Validate the exact target and ordered inputs again; another writer's ready summary wins. */
93
- export function completeHistorySummary(record, expected, children, text) {
94
- const node = record.nodes.find(value => value.id === expected.id);
95
- if (!node || node.kind !== "summary" || node.ready || JSON.stringify(summarySource(node)) !== JSON.stringify(summarySource(expected)) ||
96
- JSON.stringify(node.children) !== JSON.stringify(children.map(child => child.id)))
97
- return false;
98
- const current = node.children.map(id => record.nodes.find(value => value.id === id));
99
- if (current.some(value => !value || !value.ready) || JSON.stringify(current.map(value => summarySource(value))) !== JSON.stringify(children.map(summarySource)))
100
- return false;
101
- requireThat(text.trim(), "历史摘要为空。");
102
- node.text = text.trim();
103
- node.ready = true;
104
- return true;
13
+ function nextSummary(archives) {
14
+ for (const { raw, summaries } of archives) {
15
+ if (summaries === null)
16
+ continue;
17
+ const record = historyView(raw, summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
18
+ const node = record.nodes.find(node => node.kind === "summary" && !node.ready && node.children.every(id => lookup.get(id).ready));
19
+ if (node)
20
+ return { record, node, children: node.children.map(id => lookup.get(id)) };
21
+ }
22
+ }
23
+ /** Validate the exact target and ordered inputs under the source lock. Only publish the derived file. */
24
+ export function commitHistorySummary(files, identity, expected, children, text, signal) {
25
+ return files.control(() => {
26
+ signal?.throwIfAborted();
27
+ const current = files.list().find(({ raw }) => raw.host === identity.host && raw.id === identity.id && raw.sessionId === identity.sessionId);
28
+ if (!current || current.summaries === null)
29
+ return;
30
+ const record = historyView(current.raw, current.summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
31
+ const node = lookup.get(expected.id);
32
+ if (!node || node.kind !== "summary" || node.ready || !isDeepStrictEqual(summarySource(node), summarySource(expected)) ||
33
+ !isDeepStrictEqual(node.children, children.map(child => child.id)))
34
+ return;
35
+ for (const child of children) {
36
+ const input = lookup.get(child.id);
37
+ if (!input?.ready || !isDeepStrictEqual(summarySource(input), summarySource(child)))
38
+ return;
39
+ }
40
+ requireThat(text.trim(), "历史摘要为空。");
41
+ node.text = text.trim();
42
+ node.ready = true;
43
+ files.saveSummaries(current.raw, historySummaries(record));
44
+ return record;
45
+ });
105
46
  }
106
47
  export class HistoryService {
107
48
  root;
108
49
  files;
109
50
  source;
110
51
  otherFiles;
52
+ acpSessions;
111
53
  #records = [];
112
54
  #closed = false;
113
55
  #loaded = false;
@@ -116,11 +58,12 @@ export class HistoryService {
116
58
  #controller = new AbortController();
117
59
  #sourceWarnings = [];
118
60
  #summaryError;
119
- constructor(root, files, source, otherFiles = []) {
61
+ constructor(root, files, source, otherFiles = [], acpSessions) {
120
62
  this.root = root;
121
63
  this.files = files;
122
64
  this.source = source;
123
65
  this.otherFiles = otherFiles;
66
+ this.acpSessions = acpSessions;
124
67
  requireThat((source.host === "pi" || source.host === "dsh") && source.host === files.host &&
125
68
  new Set([files.host, ...otherFiles.map(value => value.host)]).size === otherFiles.length + 1, "历史来源与归档目录不匹配。");
126
69
  }
@@ -147,45 +90,57 @@ export class HistoryService {
147
90
  signal?.throwIfAborted();
148
91
  const warnings = [], records = [];
149
92
  const warning = (host, error) => { this.check(); signal?.throwIfAborted(); warnings.push(host + ": " + String(error)); };
150
- let known = [];
93
+ let known = [], sessions = [];
151
94
  try {
152
95
  try {
153
96
  this.files.migrate(this.root);
154
97
  }
155
98
  finally {
156
- known = this.files.list();
157
- }
158
- const before = known;
159
- let sessions = [];
160
- try {
161
- const scanned = await this.source.scan(location, signal);
162
- sessions = scanned.sessions;
163
- warnings.push(...scanned.warnings.map(value => this.files.host + ": " + value));
164
- }
165
- catch (error) {
166
- warning(this.files.host, error);
99
+ known = this.files.list(this.root);
167
100
  }
168
- this.check();
169
- signal?.throwIfAborted();
101
+ const scanned = await this.source.scan(location, signal, this.acpSessions?.().ids[this.files.host]);
102
+ sessions = scanned.sessions;
103
+ warnings.push(...scanned.warnings.map(value => this.files.host + ": " + value));
104
+ }
105
+ catch (error) {
106
+ warning(this.files.host, error);
107
+ }
108
+ this.check();
109
+ signal?.throwIfAborted();
110
+ // The worker binds the actual backend ID before delivery, possibly during the native scan.
111
+ const excluded = this.acpSessions?.();
112
+ if (excluded) {
113
+ warnings.push(...excluded.warnings);
114
+ sessions = sessions.filter(session => !excluded.ids[this.files.host].has(session.sessionId));
115
+ }
116
+ const visible = ({ raw }) => !excluded?.ids[raw.host].has(raw.sessionId);
117
+ try {
170
118
  if (sessions.length) {
119
+ const before = new Map(known.map(({ raw }) => [raw.sessionId, raw]));
171
120
  known = this.files.control(() => {
172
121
  this.check();
173
122
  signal?.throwIfAborted();
174
- const latest = this.files.list(), current = new Map(latest.map(record => [record.sessionId, record]));
123
+ const current = new Map(this.files.list().map(archive => [archive.raw.sessionId, archive]));
175
124
  for (const session of sessions) {
176
- const previous = current.get(session.sessionId), captured = before.find(record => record.sessionId === session.sessionId);
177
- // An unreadable archive may own this session; avoid assigning it a second root ID.
178
- if (!previous && this.files.warnings.length)
125
+ const previous = current.get(session.sessionId);
126
+ // A damaged raw file may own this session; a damaged summary cannot own a root ID.
127
+ if (!previous && this.files.rawWarnings.length)
179
128
  continue;
180
- // A concurrent source update must not be overwritten by this older scan. Summary-only updates remain reusable.
181
- if (captured && rawSource(captured) !== rawSource(previous))
129
+ if (!isDeepStrictEqual(before.get(session.sessionId), previous?.raw))
182
130
  continue;
183
- if (!captured && previous)
131
+ const raw = indexHistory(session, previous?.raw, this.files.host);
132
+ if (isDeepStrictEqual(raw, previous?.raw))
184
133
  continue;
185
- const value = indexHistory(session, previous, this.files.host);
186
- if (JSON.stringify(previous) !== JSON.stringify(value))
187
- this.files.save(value);
188
- current.set(session.sessionId, value);
134
+ let summaries = previous ? previous.summaries : [];
135
+ if (previous && summaries?.length) {
136
+ const retained = retainHistorySummaries(previous.raw, raw, summaries);
137
+ // Invalidate first: even an interrupted two-file update cannot attach old text to a corrected exchange.
138
+ if (!isDeepStrictEqual(summaries, retained))
139
+ this.files.saveSummaries(previous.raw, retained);
140
+ summaries = retained;
141
+ }
142
+ this.files.saveRaw(raw);
143
+ current.set(session.sessionId, { raw, summaries });
189
144
  }
190
145
  return [...current.values()];
191
146
  });
@@ -194,10 +149,10 @@ export class HistoryService {
194
149
  catch (error) {
195
150
  warning(this.files.host, error);
196
151
  }
197
- records.push(...known.map(record => ({ host: record.host, record })));
152
+ records.push(...known.filter(visible).map(view));
198
153
  for (const files of this.otherFiles) {
199
154
  try {
200
- records.push(...files.list(this.root).map(record => ({ host: record.host, record })));
155
+ records.push(...files.list(this.root).filter(visible).map(view));
201
156
  }
202
157
  catch (error) {
203
158
  warning(files.host, error);
@@ -253,11 +208,8 @@ export class HistoryService {
253
208
  for (;;) {
254
209
  this.check();
255
210
  active.throwIfAborted();
256
- const pending = this.files.list().flatMap(record => {
257
- const lookup = new Map(record.nodes.map(node => [node.id, node]));
258
- 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));
259
- return node ? [{ record, node, children: node.children.map(id => lookup.get(id)) }] : [];
260
- })[0];
211
+ const archives = this.files.list(), excluded = this.acpSessions?.().ids[this.files.host];
212
+ const pending = nextSummary(archives.filter(({ raw }) => !excluded?.has(raw.sessionId)));
261
213
  if (!pending)
262
214
  return;
263
215
  const { record, node, children } = pending;
@@ -265,15 +217,7 @@ export class HistoryService {
265
217
  prompt: children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n") }, active);
266
218
  this.check();
267
219
  active.throwIfAborted();
268
- const committed = this.files.control(() => {
269
- this.check();
270
- active.throwIfAborted();
271
- const current = this.files.list().find(value => value.id === record.id && value.sessionId === record.sessionId);
272
- if (!current || !completeHistorySummary(current, node, children, text))
273
- return;
274
- this.files.save(current);
275
- return current;
276
- });
220
+ const committed = commitHistorySummary(this.files, record, node, children, text, active);
277
221
  if (!committed)
278
222
  return;
279
223
  this.#records = this.#records.map(value => value.host === this.files.host && value.record.id === committed.id ? { host: value.host, record: committed } : value);
@@ -0,0 +1,9 @@
1
+ import type { HistoryHost } from "../model/history.js";
2
+ /** A target session can be owned by either coordinator, even when its cwd belongs to another workspace. */
3
+ export declare function acpHistorySessions(directories: {
4
+ pi?: string;
5
+ dsh?: string;
6
+ }): {
7
+ ids: Record<HistoryHost, Set<string>>;
8
+ warnings: string[];
9
+ };
@@ -0,0 +1,45 @@
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 { readJsonFile } from "./atomic-json.js";
6
+ import { acpReference } from "./acp-files.js";
7
+ function memberDirectory(home, host) {
8
+ if (host === "pi" && home.startsWith("file://"))
9
+ return join(fileURLToPath(home), "pbot/subagents");
10
+ const tilde = home === "~" || home.startsWith("~/") || ((host === "dsh" || process.platform === "win32") && home.startsWith("~\\"));
11
+ return join(tilde ? join(homedir(), home.slice(2)) : home, "pbot/subagents");
12
+ }
13
+ /** A target session can be owned by either coordinator, even when its cwd belongs to another workspace. */
14
+ export function acpHistorySessions(directories) {
15
+ const ids = { pi: new Set(), dsh: new Set(), claude: new Set() };
16
+ const warnings = [];
17
+ const warn = (path, error) => {
18
+ if (error.code !== "ENOENT")
19
+ warnings.push(path + ": " + String(error));
20
+ };
21
+ const homes = { pi: process.env.PI_CODING_AGENT_DIR || "~/.pi/agent", dsh: process.env.DSH_HOME?.trim() ? process.env.DSH_HOME : "~/.dsh" };
22
+ for (const host of ["pi", "dsh"]) {
23
+ let directory = directories[host];
24
+ try {
25
+ directory ??= memberDirectory(homes[host], host);
26
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
27
+ if (!entry.isDirectory() || entry.name.startsWith("."))
28
+ continue;
29
+ const path = join(directory, entry.name);
30
+ try {
31
+ const ref = readJsonFile(path, "acp-session.json", acpReference);
32
+ if (ref.sessionId !== null)
33
+ ids[ref.backend].add(ref.sessionId);
34
+ }
35
+ catch (error) {
36
+ warn(path, error);
37
+ }
38
+ }
39
+ }
40
+ catch (error) {
41
+ warn(directory ?? homes[host], error);
42
+ }
43
+ }
44
+ return { ids, warnings };
45
+ }
@@ -1,15 +1,18 @@
1
- import type { HistoryHost, HistoryRecord } from "../model/history.js";
1
+ import type { HistoryArchive, HistoryHost, HistoryIdentity, HistorySummary, RawHistory } from "../model/history.js";
2
2
  export declare class HistoryFiles {
3
3
  #private;
4
4
  readonly directory: string;
5
5
  readonly host: HistoryHost;
6
6
  constructor(directory: string, host?: HistoryHost);
7
7
  get warnings(): readonly string[];
8
- /** A peer can include its legacy directory without migrating or modifying either source. */
9
- list(legacyRoot?: string): HistoryRecord[];
10
- /** Publish each legacy archive with its directory's host before removing the old copy. */
11
- migrate(root: string): void;
8
+ get rawWarnings(): readonly string[];
9
+ list(legacyRoot?: string): HistoryArchive[];
12
10
  /** The callback is synchronous: no SDK reads or model work can hold this source's write lock. */
13
11
  control<T>(operation: () => T): T;
14
- save(value: HistoryRecord): void;
12
+ private writable;
13
+ saveRaw(raw: RawHistory): void;
14
+ saveSummaries(identity: HistoryIdentity, summaries: readonly HistorySummary[]): void;
15
+ private publishSummaries;
16
+ private migrateFile;
17
+ migrate(root: string): void;
15
18
  }