personal-bot 0.2.12 → 0.2.14

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 (97) hide show
  1. package/.claude-plugin/marketplace.json +18 -0
  2. package/.claude-plugin/plugin.json +15 -0
  3. package/CONTEXT.md +11 -5
  4. package/README.md +33 -16
  5. package/README.zh-CN.md +33 -16
  6. package/docs/README.md +6 -4
  7. package/docs/adr/0001-claude-skill-discovery.md +3 -0
  8. package/docs/adr/0002-claude-native-collaboration.md +3 -0
  9. package/docs/agent-collaboration.md +20 -8
  10. package/docs/architecture-guidelines.md +1 -1
  11. package/docs/capability-design.md +10 -4
  12. package/docs/claude-code-design.md +45 -0
  13. package/docs/claude-code.md +64 -0
  14. package/docs/dsh.md +3 -3
  15. package/docs/file-storage.md +18 -9
  16. package/docs/history.md +17 -9
  17. package/docs/interaction-design.md +9 -1
  18. package/docs/model-context.md +37 -14
  19. package/docs/model-instruction-guidelines.md +3 -3
  20. package/docs/release.md +14 -6
  21. package/docs/technical-design.md +40 -18
  22. package/docs/workspace-configuration.md +34 -26
  23. package/hooks/hooks.json +19 -0
  24. package/lib/claude.d.ts +1 -0
  25. package/lib/claude.js +20 -0
  26. package/lib/client.js +1 -1
  27. package/lib/common/schema.d.ts +2 -0
  28. package/lib/common/schema.js +10 -0
  29. package/lib/common/validation.d.ts +0 -2
  30. package/lib/common/validation.js +0 -10
  31. package/lib/extension/acp-worker.js +6 -3
  32. package/lib/extension/claude-hooks.d.ts +15 -0
  33. package/lib/extension/claude-hooks.js +104 -0
  34. package/lib/extension/dsh/command.js +2 -1
  35. package/lib/extension/dsh/history.js +1 -1
  36. package/lib/extension/dsh/management.js +2 -1
  37. package/lib/integrations/agent-resources.d.ts +1 -1
  38. package/lib/integrations/agent-resources.js +3 -1
  39. package/lib/integrations/dsh/history-summary.js +5 -9
  40. package/lib/integrations/dsh/history.js +13 -5
  41. package/lib/integrations/history-summary.d.ts +2 -0
  42. package/lib/integrations/history-summary.js +21 -10
  43. package/lib/model/agent.d.ts +1 -1
  44. package/lib/model/history.d.ts +11 -4
  45. package/lib/services/history/history-service.d.ts +8 -6
  46. package/lib/services/history/history-service.js +90 -48
  47. package/lib/services/workspace/python-environment-service.d.ts +6 -0
  48. package/lib/services/workspace/python-environment-service.js +25 -9
  49. package/lib/storage/agent-files.js +3 -0
  50. package/lib/storage/history-files.d.ts +2 -1
  51. package/lib/storage/history-files.js +26 -15
  52. package/lib/tools/agents/dsh-tool.js +2 -1
  53. package/lib/tools/history/contract.d.ts +7 -7
  54. package/lib/tools/history/contract.js +4 -3
  55. package/lib/tools/history/dsh-tool.js +2 -1
  56. package/lib/tools/teams/dsh-tool.js +2 -1
  57. package/lib/ui/dsh/management.js +1 -1
  58. package/package.json +33 -30
  59. package/python/README.md +17 -14
  60. package/resources/agents/coordinator.md +1 -1
  61. package/resources/claude/agents/general-purpose.md +12 -0
  62. package/resources/claude/skills/pbot/SKILL.md +17 -0
  63. package/resources/prompts/claude-coordinator.md +1 -0
  64. package/resources/prompts/native-coordinator.md +1 -0
  65. package/resources/prompts/workspace.md +2 -2
  66. package/resources/references/compute.md +2 -2
  67. package/resources/references/task-conductor.md +3 -2
  68. package/resources/skills/provider-connections/SKILL.md +17 -1
  69. package/scripts/README.md +25 -7
  70. package/src/claude.ts +19 -0
  71. package/src/common/schema.ts +11 -0
  72. package/src/common/validation.ts +0 -11
  73. package/src/extension/acp-worker.ts +2 -2
  74. package/src/extension/claude-hooks.ts +94 -0
  75. package/src/extension/dsh/command.ts +2 -1
  76. package/src/extension/dsh/history.ts +1 -1
  77. package/src/extension/dsh/management.ts +2 -1
  78. package/src/integrations/agent-resources.ts +2 -1
  79. package/src/integrations/dsh/history-summary.ts +5 -9
  80. package/src/integrations/dsh/history.ts +12 -6
  81. package/src/integrations/history-summary.ts +18 -8
  82. package/src/integrations/pi/history.ts +16 -15
  83. package/src/model/agent.ts +1 -1
  84. package/src/model/history.ts +12 -4
  85. package/src/pbot.ts +2 -2
  86. package/src/services/history/history-service.ts +82 -41
  87. package/src/services/workspace/python-environment-service.ts +26 -9
  88. package/src/storage/agent-files.ts +4 -1
  89. package/src/storage/history-files.ts +20 -11
  90. package/src/tools/agents/dsh-tool.ts +2 -1
  91. package/src/tools/agents/tool.ts +2 -1
  92. package/src/tools/history/contract.ts +4 -3
  93. package/src/tools/history/dsh-tool.ts +2 -1
  94. package/src/tools/teams/dsh-tool.ts +2 -1
  95. package/src/tools/teams/tool.ts +2 -1
  96. package/src/ui/dsh/management.ts +1 -1
  97. package/npm-shrinkwrap.json +0 -13561
@@ -1,28 +1,52 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
2
4
  import type { HistoryExchange, HistoryHost, HistoryLocation, HistoryNode, HistoryRecord, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
3
5
  import type { HistoryFiles } from "../../storage/history-files.js";
6
+ import { resourceRoot } from "../../common/paths.js";
4
7
  import { requireThat } from "../../common/validation.js";
5
8
 
6
- /** Shared prefixes reuse nodes; only consecutive exchanges on one native branch can merge. */
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. */
7
12
  export function indexHistory(session: HistorySession, previous?: HistoryRecord, host: HistoryHost = previous?.host ?? "pi"): HistoryRecord {
8
- const id = previous?.id ?? (host === "dsh" ? "dsh-" : "") + randomUUID(), nodes = new Map<string, HistoryNode>();
9
- const old = new Map(previous?.nodes.map(node => [node.id, node])), changed = new Set<string>();
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>();
10
31
  const add = (value: HistoryExchange, level: number, children: string[] = []): HistoryNode => {
11
- const key = `${id}:${level}:${value.entryIds.at(-1)}`, found = nodes.get(key);
12
- if (found) return found;
13
- const before = old.get(key), same = before && JSON.stringify(before.children) === JSON.stringify(children) &&
14
- (level ? children.every(child => !changed.has(child)) : before.text === value.text && before.completed === value.completed);
15
- const node: HistoryNode = { ...value, id: key, kind: level ? "summary" : "exchange", level, children, parents: [],
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: [],
16
42
  text: level ? same ? before.text : "" : value.text, ready: level ? Boolean(same && before.ready) : true };
17
43
  if (!same) changed.add(key);
18
- nodes.set(key, node); return node;
44
+ observed.add(key); nodes.set(key, node); return node;
19
45
  };
20
- const roots = new Set<string>();
21
46
  for (const branch of session.branches) {
22
47
  let layer = branch.map(exchange => add(exchange, 0)), level = 1;
23
48
  while (layer.length >= 4) {
24
49
  const count = Math.floor(layer.length / 4) * 4, next: HistoryNode[] = [];
25
- layer.slice(count).forEach(node => roots.add(node.id));
26
50
  for (let i = 0; i < count; i += 4) {
27
51
  const children = layer.slice(i, i + 4), first = children[0]!, last = children.at(-1)!;
28
52
  next.push(add({ entryIds: [first.entryIds[0]!, last.entryIds.at(-1)!], text: "", from: first.from, to: last.to,
@@ -30,32 +54,43 @@ export function indexHistory(session: HistorySession, previous?: HistoryRecord,
30
54
  }
31
55
  layer = next; level++;
32
56
  }
33
- layer.forEach(node => roots.add(node.id));
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);
34
65
  }
35
66
  const dates = [...nodes.values()].flatMap(node => [node.from, node.to]).sort();
67
+ const nested = new Set([...nodes.values()].flatMap(node => node.children));
36
68
  nodes.set(id, { id, kind: "session", level: -1, entryIds: [], text: session.name, ready: true, completed: [...nodes.values()].every(node => node.completed),
37
69
  from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [],
38
- children: [...roots].sort((a, b) => nodes.get(a)!.from.localeCompare(nodes.get(b)!.from)) });
70
+ children: [...nodes.keys()].filter(key => !nested.has(key)).sort((a, b) => nodes.get(a)!.from.localeCompare(nodes.get(b)!.from)) });
39
71
  for (const node of nodes.values()) for (const child of node.children) nodes.get(child)!.parents.push(node.id);
40
72
  return { host, id, sessionId: session.sessionId, name: session.name, nodes: [...nodes.values()] };
41
73
  }
42
74
 
43
75
  export interface HistoryQuery { host?: HistoryHost; query?: string; sessionId?: string; from?: string; to?: string; offset?: number; limit?: number }
44
76
  type LocatedRecord = { host: HistoryHost; record: HistoryRecord };
77
+ type HistoryReader = Pick<HistoryFiles, "host" | "list" | "warnings">;
45
78
  const page = <T>(values: T[], offset: number, limit: number) => ({ values: values.slice(offset, offset + limit),
46
79
  nextOffset: offset + limit < values.length ? offset + limit : null });
47
80
  const brief = ({ host, record }: LocatedRecord, node: HistoryNode) => ({ host, id: node.id, kind: node.kind, sessionId: record.sessionId,
48
81
  name: record.name, preview: node.text.replace(/\s+/g, " ").slice(0, 100), from: node.from, to: node.to, ready: node.ready, completed: node.completed });
49
82
  const rawSource = (record?: HistoryRecord) => record && JSON.stringify({ name: record.name,
50
- exchanges: record.nodes.filter(node => node.kind === "exchange").map(node => [node.id, node.entryIds, node.text, node.from, node.to, node.completed]) });
51
- const summarySource = (node: HistoryNode) => [node.id, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
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]) });
85
+ const summarySource = (node: HistoryNode) => [node.id, node.kind, node.level, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
52
86
 
53
- /** Validate the exact inputs again under the source lock; another writer's ready summary wins. */
54
- export function completeHistorySummary(record: HistoryRecord, id: string, children: HistoryNode[], text: string) {
55
- const node = record.nodes.find(value => value.id === id);
56
- if (!node || node.kind !== "summary" || node.ready || JSON.stringify(node.children) !== JSON.stringify(children.map(child => child.id))) return false;
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;
57
92
  const current = node.children.map(id => record.nodes.find(value => value.id === id));
58
- if (current.some(value => !value) || JSON.stringify(current.map(value => summarySource(value!))) !== JSON.stringify(children.map(summarySource))) return false;
93
+ if (current.some(value => !value || !value.ready) || JSON.stringify(current.map(value => summarySource(value!))) !== JSON.stringify(children.map(summarySource))) return false;
59
94
  requireThat(text.trim(), "历史摘要为空。");
60
95
  node.text = text.trim(); node.ready = true; return true;
61
96
  }
@@ -66,19 +101,22 @@ export class HistoryService {
66
101
  #loaded = false;
67
102
  #refresh: Promise<void> | undefined;
68
103
  #work: Promise<void> | undefined;
104
+ readonly #controller = new AbortController();
69
105
  #sourceWarnings: string[] = [];
70
106
  #summaryError: string | undefined;
71
107
  constructor(readonly root: string, private readonly files: HistoryFiles, private readonly source: HistorySource,
72
- private readonly otherFiles?: HistoryFiles) {
73
- requireThat(source.host === files.host && (!otherFiles || otherFiles.host !== files.host), "历史来源与归档目录不匹配。");
108
+ private readonly otherFiles: readonly HistoryReader[] = []) {
109
+ requireThat((source.host === "pi" || source.host === "dsh") && source.host === files.host &&
110
+ new Set([files.host, ...otherFiles.map(value => value.host)]).size === otherFiles.length + 1,
111
+ "历史来源与归档目录不匹配。");
74
112
  }
75
113
  check() { requireThat(!this.#closed, "历史服务已关闭。"); }
76
- get warnings() { return [...new Set([...this.#sourceWarnings, ...this.files.warnings, ...(this.otherFiles?.warnings ?? []),
114
+ get warnings() { return [...new Set([...this.#sourceWarnings, ...this.files.warnings, ...this.otherFiles.flatMap(value => value.warnings),
77
115
  ...(this.#summaryError ? [this.files.host + " 摘要:" + this.#summaryError] : [])])]; }
78
116
  get status() { return { loaded: this.#loaded, organizing: Boolean(this.#work), pending: this.#loaded ? this.#records.filter(value => value.host === this.files.host)
79
117
  .reduce((total, value) => total + value.record.nodes.filter(node => node.kind === "summary" && !node.ready).length, 0) : null, warnings: this.warnings }; }
80
118
  refresh(location: HistoryLocation, signal?: AbortSignal): Promise<void> {
81
- this.check();
119
+ this.check(); requireThat(location.host === this.source.host, "历史位置与来源不匹配。");
82
120
  // Each caller keeps its own cancellation. A closed page cannot cancel a server-owned refresh.
83
121
  const work = (this.#refresh ?? Promise.resolve()).catch(() => {}).then(() => this.load(location, signal));
84
122
  this.#refresh = work;
@@ -118,10 +156,9 @@ export class HistoryService {
118
156
  }
119
157
  } catch (error) { warning(this.files.host, error); }
120
158
  records.push(...known.map(record => ({ host: record.host, record })));
121
- if (this.otherFiles) {
122
- try { this.otherFiles.migrate(this.root); } catch (error) { warning(this.otherFiles.host, error); }
123
- try { records.push(...this.otherFiles.list().map(record => ({ host: record.host, record }))); }
124
- catch (error) { warning(this.otherFiles.host, error); }
159
+ for (const files of this.otherFiles) {
160
+ try { records.push(...files.list(this.root).map(record => ({ host: record.host, record }))); }
161
+ catch (error) { warning(files.host, error); }
125
162
  }
126
163
  this.check(); signal?.throwIfAborted(); this.#records = records; this.#sourceWarnings = warnings; this.#loaded = true;
127
164
  }
@@ -159,26 +196,27 @@ export class HistoryService {
159
196
  parents: node.parents.map(id => brief(value, lookup.get(id)!)), children: children.values.map(id => brief(value, lookup.get(id)!)),
160
197
  nextChildrenOffset: children.nextOffset, source: { host: value.host, sessionId: value.record.sessionId, entryIds: node.entryIds }, warnings: this.warnings };
161
198
  }
162
- /** Only this source is organized. Model calls run outside the write lock. */
199
+ /** Retain exact inputs only for this call; model work never holds the source write lock. */
163
200
  organize(summarize: HistorySummarizer, signal: AbortSignal): Promise<void> {
164
201
  this.check();
202
+ const active = AbortSignal.any([signal, this.#controller.signal]);
165
203
  const run = async () => {
166
204
  for (;;) {
167
- this.check(); signal.throwIfAborted();
168
- let pending: { record: HistoryRecord; node: HistoryNode; children: HistoryNode[] } | undefined;
169
- for (const record of this.files.list()) {
205
+ this.check(); active.throwIfAborted();
206
+ const pending = this.files.list().flatMap(record => {
170
207
  const lookup = new Map(record.nodes.map(node => [node.id, node]));
171
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));
172
- if (node) { pending = { record, node, children: node.children.map(id => lookup.get(id)!) }; break; }
173
- }
209
+ return node ? [{ record, node, children: node.children.map(id => lookup.get(id)!) }] : [];
210
+ })[0];
174
211
  if (!pending) return;
175
212
  const { record, node, children } = pending;
176
- const text = await summarize(children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n"), signal);
177
- this.check(); signal.throwIfAborted();
213
+ const text = await summarize({ system: readFileSync(join(resourceRoot, "prompts/history-summary.md"), "utf8"), maxTokens: 2048,
214
+ prompt: children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n") }, active);
215
+ this.check(); active.throwIfAborted();
178
216
  const committed = this.files.control(() => {
179
- this.check(); signal.throwIfAborted();
180
- const current = this.files.list().find(value => value.id === record.id);
181
- if (!current || !completeHistorySummary(current, node.id, children, text)) return;
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;
182
220
  this.files.save(current); return current;
183
221
  });
184
222
  if (!committed) return;
@@ -186,11 +224,14 @@ export class HistoryService {
186
224
  }
187
225
  };
188
226
  const work = (this.#work ?? Promise.resolve()).catch(() => {}).then(run).then(() => { this.#summaryError = undefined; }).catch(error => {
189
- if (!signal.aborted && !this.#closed) this.#summaryError = String(error);
227
+ if (!active.aborted && !this.#closed) this.#summaryError = String(error);
190
228
  throw error;
191
229
  });
192
230
  this.#work = work;
193
231
  return work.finally(() => { if (this.#work === work) this.#work = undefined; });
194
232
  }
195
- async close() { this.#closed = true; await Promise.allSettled([this.#work, this.#refresh]); this.#records = []; this.#loaded = false; }
233
+ async close() {
234
+ this.#closed = true; this.#controller.abort();
235
+ await Promise.allSettled([this.#work, this.#refresh]); this.#records = []; this.#loaded = false;
236
+ }
196
237
  }
@@ -11,6 +11,30 @@ export class PythonEnvironmentService {
11
11
  constructor(private readonly root: string) {}
12
12
  get status() { return { ...this.#status }; }
13
13
 
14
+ private async run(checkOnly: boolean, signal: AbortSignal) {
15
+ const environment: Record<string, string> = {};
16
+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) environment[key] = value;
17
+ const result = await runCommand("/bin/sh", ["-c", 'exec "$(command -v python3 || command -v python)" "$@"',
18
+ "pbot-python", "-I", "-B", join(resourceRoot, "../scripts/setup-python.py"), ...(checkOnly ? ["--check"] : [])],
19
+ undefined, this.root, environment, signal, { timeoutMs: 15 * 60_000 });
20
+ signal.throwIfAborted();
21
+ requireThat(result.success && object(result.data) && typeof result.data.directory === "string" && typeof result.data.python === "string",
22
+ "共享 Python 环境未就绪;修复后执行 Python 准备入口。\n" + JSON.stringify(result.data).slice(-6000));
23
+ return { directory: result.data.directory, python: result.data.python, action: result.data.action };
24
+ }
25
+
26
+ async inspect(signal?: AbortSignal) {
27
+ const cancel = signal ? AbortSignal.any([this.#shutdown.signal, signal]) : this.#shutdown.signal;
28
+ try {
29
+ const result = await this.run(true, cancel);
30
+ this.#status = result.action === "verify" ? { state: "ready", directory: result.directory } : { state: "unprepared" };
31
+ return this.status;
32
+ } catch (error) {
33
+ this.#status = { state: "error", error: error instanceof Error ? error.message : String(error) };
34
+ throw error;
35
+ }
36
+ }
37
+
14
38
  setup(signal?: AbortSignal): Promise<{ directory: string; python: string }> {
15
39
  const cancel = signal ? AbortSignal.any([this.#shutdown.signal, signal]) : this.#shutdown.signal;
16
40
  if (cancel.aborted) return Promise.reject(cancel.reason);
@@ -18,15 +42,8 @@ export class PythonEnvironmentService {
18
42
  this.#status = { state: "preparing" };
19
43
  this.#pending = (async () => {
20
44
  try {
21
- const environment: Record<string, string> = {};
22
- for (const [key, value] of Object.entries(process.env)) if (value !== undefined) environment[key] = value;
23
- const result = await runCommand("/bin/sh", ["-c", 'exec "$(command -v python3 || command -v python)" "$@"',
24
- "pbot-python", "-I", "-B", join(resourceRoot, "../scripts/setup-python.py")],
25
- undefined, this.root, environment, cancel, { timeoutMs: 15 * 60_000 });
26
- cancel.throwIfAborted();
27
- requireThat(result.success && object(result.data) && typeof result.data.directory === "string" && typeof result.data.python === "string",
28
- "共享 Python 环境未就绪;修复后执行 /pbot python setup。\n" + JSON.stringify(result.data).slice(-6000));
29
- const ready = { directory: result.data.directory, python: result.data.python };
45
+ const result = await this.run(false, cancel);
46
+ const ready = { directory: result.directory, python: result.python };
30
47
  this.#status = { state: "ready", directory: ready.directory };
31
48
  return ready;
32
49
  } catch (error) {
@@ -48,7 +48,9 @@ export function status(v: unknown): AgentStatus {
48
48
  }
49
49
  export class AgentFiles {
50
50
  #failure: unknown;
51
- constructor(readonly root: string, readonly host: NativeAgentHost = "pi") {}
51
+ constructor(readonly root: string, readonly host: NativeAgentHost = "pi") {
52
+ requireThat(host === "pi" || host === "dsh", "子会话所属宿主无效。");
53
+ }
52
54
  check() { if (this.#failure) throw this.#failure; }
53
55
  fail(error: unknown) { this.#failure = error; }
54
56
  directory(id: string) { return join(this.root, fileId(id)); }
@@ -65,6 +67,7 @@ export class AgentFiles {
65
67
  }
66
68
  create(value: AgentDescriptor, run: AgentLaunch, acp?: AcpSessionReference) {
67
69
  this.check();
70
+ if (acp) acpReference(acp);
68
71
  mkdirSync(this.root, { recursive: true, mode: 0o700 });
69
72
  mkdirSync(this.directory(value.agentId), { mode: 0o700 });
70
73
  for (const dir of ["inbox", "completions"]) privateDirectory(this.directory(value.agentId), dir);
@@ -8,7 +8,7 @@ import { fileId } from "./file-access.js";
8
8
 
9
9
  const strings = (value: unknown): value is string[] => Array.isArray(value) && value.every(item => typeof item === "string");
10
10
  function record(value: unknown): HistoryRecord {
11
- requireThat(object(value) && (value.host === "pi" || value.host === "dsh") &&
11
+ requireThat(object(value) && (value.host === "pi" || value.host === "dsh" || value.host === "claude") &&
12
12
  typeof value.id === "string" && typeof value.sessionId === "string" &&
13
13
  typeof value.name === "string" && Array.isArray(value.nodes), "历史索引无效。");
14
14
  for (const node of value.nodes) requireThat(object(node) && typeof node.id === "string" &&
@@ -24,21 +24,30 @@ export class HistoryFiles {
24
24
  #warnings: string[] = [];
25
25
  constructor(readonly directory: string, readonly host: HistoryHost = "pi") {}
26
26
  get warnings(): readonly string[] { return this.#warnings; }
27
- list() {
27
+ /** A peer can include its legacy directory without migrating or modifying either source. */
28
+ list(legacyRoot?: string) {
28
29
  this.#warnings = [];
29
- if (!existsSync(this.directory)) return [];
30
- const records: HistoryRecord[] = [];
31
- for (const name of readdirSync(this.directory).filter(name => name.endsWith(".json"))) {
32
- try {
33
- const value = readJsonFile(this.directory, name, record);
34
- requireThat(name === fileId(value.id) + ".json", "历史文件名与根 ID 不匹配。");
35
- if (value.host === this.host) records.push(value);
36
- } catch (error) { this.#warnings.push(join(this.directory, name) + ": " + String(error)); }
30
+ const records = new Map<string, HistoryRecord>();
31
+ const directories = [this.directory, ...(legacyRoot && this.host !== "claude" ? [join(legacyRoot, "." + this.host, "pbot/history")] : [])];
32
+ for (const directory of directories) {
33
+ if (!existsSync(directory)) continue;
34
+ for (const name of readdirSync(directory).filter(name => name.endsWith(".json"))) {
35
+ try {
36
+ const value = readJsonFile(directory, name, value => {
37
+ if (directory === this.directory) return record(value);
38
+ requireThat(object(value) && (value.host === undefined || value.host === this.host), "旧历史归档与来源目录不匹配。");
39
+ return record({ ...value, host: this.host });
40
+ });
41
+ requireThat(name === fileId(value.id) + ".json", "历史文件名与根 ID 不匹配。");
42
+ if (value.host === this.host && !records.has(value.id)) records.set(value.id, value);
43
+ } catch (error) { this.#warnings.push(join(directory, name) + ": " + String(error)); }
44
+ }
37
45
  }
38
- return records;
46
+ return [...records.values()];
39
47
  }
40
48
  /** Publish each legacy archive with its directory's host before removing the old copy. */
41
49
  migrate(root: string) {
50
+ if (this.host !== "pi" && this.host !== "dsh") return;
42
51
  const directory = join(root, "." + this.host, "pbot/history");
43
52
  if (!existsSync(directory)) return;
44
53
  this.control(() => {
@@ -4,7 +4,8 @@ import { dshParameters, dshOutputSchema } from "../../integrations/dsh/schema.js
4
4
  import type { AgentService } from "../../services/agents/agent-service.js";
5
5
  import type { AgentOwner } from "../../model/agent.js";
6
6
  import { object, json } from "../../common/json.js";
7
- import { requireThat, schema } from "../../common/validation.js";
7
+ import { requireThat } from "../../common/validation.js";
8
+ import { schema } from "../../common/schema.js";
8
9
  import { markdownFields } from "../../common/markdown.js";
9
10
  import { executeAgent, type AgentInput } from "./actions.js";
10
11
  import { agentDescription, agentResultSchema } from "./contract.js";
@@ -2,7 +2,8 @@ import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import type { AgentService } from "../../services/agents/agent-service.js";
3
3
  import { agentOwner } from "../../integrations/pi/agent-context.js";
4
4
  import type { CallAccess } from "../access.js";
5
- import { requireThat, schema } from "../../common/validation.js";
5
+ import { requireThat } from "../../common/validation.js";
6
+ import { schema } from "../../common/schema.js";
6
7
  import { executeAgent } from "./actions.js";
7
8
  import { agentDescription, agentActionSchema, agentParametersSchema, agentResultSchema } from "./contract.js";
8
9
 
@@ -1,7 +1,8 @@
1
1
  import { Type, type Static } from "typebox";
2
- import { requireThat, schema } from "../../common/validation.js";
2
+ import { requireThat } from "../../common/validation.js";
3
+ import { schema } from "../../common/schema.js";
3
4
 
4
- const host = Type.Union([Type.Literal("pi"), Type.Literal("dsh")]);
5
+ const host = Type.Union([Type.Literal("pi"), Type.Literal("dsh"), Type.Literal("claude")]);
5
6
  const nullableOffset = Type.Union([Type.Integer(), Type.Null()]);
6
7
  const node = Type.Object({ host, id: Type.String(), kind: Type.Union([Type.Literal("session"), Type.Literal("exchange"), Type.Literal("summary")]),
7
8
  sessionId: Type.String(), name: Type.String(), preview: Type.String(), from: Type.String(), to: Type.String(), ready: Type.Boolean(), completed: Type.Boolean() });
@@ -13,7 +14,7 @@ export const historyResultSchema = Type.Object({
13
14
  source: Type.Object({ host, sessionId: Type.String({ description: "原始宿主会话 ID。" }), entryIds: Type.Array(Type.String()) }), warnings: Type.Array(Type.String()) })),
14
15
  warnings: Type.Array(Type.String()),
15
16
  });
16
- export const historyDescription = "查询当前工作区的 Pi/dsh 问答归档,host 可筛选来源。search 按不区分大小写的连续文本匹配原文和摘要;无匹配时换词,省略 query 列会话。read 按 parents/children 的 id 展开,nextOffset 续读正文,nextChildrenOffset 续读子节点。需要对话细节时读取 exchange 原文;需要工具日志时查所属宿主的原始会话。";
17
+ export const historyDescription = "查询当前工作区的 Pi/dsh 问答与已有 Claude 归档,host 可筛选来源。search 按不区分大小写的连续文本匹配原文和摘要;无匹配时换词,省略 query 列会话。read 按 parents/children 的 id 展开,nextOffset 续读正文,nextChildrenOffset 续读子节点。需要对话细节时读取 exchange 原文;需要工具日志时查所属宿主的原始会话。";
17
18
  export const historyParameters = Type.Object({ action: Type.Union([Type.Literal("search"), Type.Literal("read")]),
18
19
  host: Type.Optional(host), query: Type.Optional(Type.String()), sessionId: Type.Optional(Type.String()),
19
20
  from: Type.Optional(Type.String({ description: "search:ISO 日期或时间,下界。" })),
@@ -2,7 +2,8 @@ import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { Agent } from "@deepseek-ai/dsh-agent";
3
3
  import type { HistoryService } from "../../services/history/history-service.js";
4
4
  import { dshParameters, dshOutputSchema } from "../../integrations/dsh/schema.js";
5
- import { requireThat, schema } from "../../common/validation.js";
5
+ import { requireThat } from "../../common/validation.js";
6
+ import { schema } from "../../common/schema.js";
6
7
  import { json } from "../../common/json.js";
7
8
  import { markdownFields } from "../../common/markdown.js";
8
9
  import { historyDescription, historyInput, historyParameters, historyResultSchema } from "./contract.js";
@@ -7,7 +7,8 @@ import type { AgentService } from "../../services/agents/agent-service.js";
7
7
  import type { AgentOwner } from "../../model/agent.js";
8
8
  import type { TeamActor } from "../../model/team.js";
9
9
  import { object } from "../../common/json.js";
10
- import { requireThat, schema } from "../../common/validation.js";
10
+ import { requireThat } from "../../common/validation.js";
11
+ import { schema } from "../../common/schema.js";
11
12
  import { markdownFields } from "../../common/markdown.js";
12
13
  import { teamMessagesMarkdown } from "../../integrations/team-context.js";
13
14
  import { executeTeam, executeTeamMessage } from "./actions.js";
@@ -3,7 +3,8 @@ import type { TeamService } from "../../services/agents/team-service.js";
3
3
  import type { AgentService } from "../../services/agents/agent-service.js";
4
4
  import type { TeamActor } from "../../model/team.js";
5
5
  import { agentOwner } from "../../integrations/pi/agent-context.js";
6
- import { requireThat, schema } from "../../common/validation.js";
6
+ import { requireThat } from "../../common/validation.js";
7
+ import { schema } from "../../common/schema.js";
7
8
  import type { CallAccess } from "../access.js";
8
9
  import { executeTeam, executeTeamMessage } from "./actions.js";
9
10
  import { teamDescription, teamMessageDescription, teamParametersSchema, teamActionSchema, teamResultSchema, teamMessageParametersSchema, teamMessageActionSchema, teamMessageResultSchema } from "./contract.js";
@@ -301,7 +301,7 @@ export function showManagement(ctx: Context, parentSessionId: SessionId) {
301
301
 
302
302
  const history = section("history", "历史"); pageTitle(history, "历史", "");
303
303
  const searchForm = form(history); searchForm.className = "pbot-search";
304
- const historyQuery = field(searchForm, "关键词"), host = select(searchForm, "来源", [["", "全部"], ["pi", "Pi"], ["dsh", "dsh"]]);
304
+ const historyQuery = field(searchForm, "关键词"), host = select(searchForm, "来源", [["", "全部"], ["pi", "Pi"], ["dsh", "dsh"], ["claude", "Claude Code"]]);
305
305
  historyQuery.placeholder = "留空查看最近会话"; submit(searchForm, "查询", () => searchHistory());
306
306
  const dateFilters = details(history, "时间范围"), dateGrid = group(dateFilters, "pbot-grid");
307
307
  const historyFrom = field(dateGrid, "开始时间"), historyTo = field(dateGrid, "结束时间");