personal-bot 0.2.12 → 0.2.13

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 (79) 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 +13 -5
  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/extension/acp-worker.js +6 -3
  28. package/lib/extension/claude-hooks.d.ts +15 -0
  29. package/lib/extension/claude-hooks.js +104 -0
  30. package/lib/extension/dsh/history.js +1 -1
  31. package/lib/integrations/agent-resources.d.ts +1 -1
  32. package/lib/integrations/agent-resources.js +3 -1
  33. package/lib/integrations/dsh/history-summary.js +5 -9
  34. package/lib/integrations/dsh/history.js +13 -5
  35. package/lib/integrations/history-summary.d.ts +2 -0
  36. package/lib/integrations/history-summary.js +21 -10
  37. package/lib/model/agent.d.ts +1 -1
  38. package/lib/model/history.d.ts +11 -4
  39. package/lib/services/history/history-service.d.ts +8 -6
  40. package/lib/services/history/history-service.js +90 -48
  41. package/lib/services/workspace/python-environment-service.d.ts +6 -0
  42. package/lib/services/workspace/python-environment-service.js +25 -9
  43. package/lib/storage/agent-files.js +3 -0
  44. package/lib/storage/history-files.d.ts +2 -1
  45. package/lib/storage/history-files.js +26 -15
  46. package/lib/tools/history/contract.d.ts +7 -7
  47. package/lib/tools/history/contract.js +2 -2
  48. package/lib/ui/dsh/management.js +1 -1
  49. package/npm-shrinkwrap.json +10 -27
  50. package/package.json +33 -29
  51. package/python/README.md +17 -14
  52. package/resources/agents/coordinator.md +1 -1
  53. package/resources/claude/agents/general-purpose.md +12 -0
  54. package/resources/claude/skills/pbot/SKILL.md +17 -0
  55. package/resources/prompts/claude-coordinator.md +1 -0
  56. package/resources/prompts/native-coordinator.md +1 -0
  57. package/resources/prompts/workspace.md +2 -2
  58. package/resources/references/compute.md +2 -2
  59. package/resources/references/task-conductor.md +3 -2
  60. package/resources/skills/provider-connections/SKILL.md +17 -1
  61. package/scripts/README.md +24 -6
  62. package/src/claude.ts +19 -0
  63. package/src/extension/acp-worker.ts +2 -2
  64. package/src/extension/claude-hooks.ts +94 -0
  65. package/src/extension/dsh/history.ts +1 -1
  66. package/src/integrations/agent-resources.ts +2 -1
  67. package/src/integrations/dsh/history-summary.ts +5 -9
  68. package/src/integrations/dsh/history.ts +12 -6
  69. package/src/integrations/history-summary.ts +18 -8
  70. package/src/integrations/pi/history.ts +16 -15
  71. package/src/model/agent.ts +1 -1
  72. package/src/model/history.ts +12 -4
  73. package/src/pbot.ts +2 -2
  74. package/src/services/history/history-service.ts +82 -41
  75. package/src/services/workspace/python-environment-service.ts +26 -9
  76. package/src/storage/agent-files.ts +4 -1
  77. package/src/storage/history-files.ts +20 -11
  78. package/src/tools/history/contract.ts +2 -2
  79. package/src/ui/dsh/management.ts +1 -1
@@ -0,0 +1,94 @@
1
+ import { readFile, realpath, stat } from "node:fs/promises";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { object } from "../common/json.js";
4
+ import { resourceRoot } from "../common/paths.js";
5
+ import { packageVersion } from "../common/version.js";
6
+ import { requireThat } from "../common/validation.js";
7
+ import { agentText } from "../integrations/agent-resources.js";
8
+ import { PythonEnvironmentService } from "../services/workspace/python-environment-service.js";
9
+ import { readWorkspaceConfig } from "../services/workspace/workspace-config.js";
10
+ import { initializeWorkspace } from "../services/workspace/workspace-preparation.js";
11
+
12
+ export async function claudeWorkspaceRoot(cwd: string, projectDirectory = process.env.CLAUDE_PROJECT_DIR): Promise<string> {
13
+ const directory = projectDirectory || cwd;
14
+ requireThat(isAbsolute(directory), "Claude 工作区需要绝对路径。");
15
+ const root = await realpath(directory);
16
+ requireThat((await stat(root)).isDirectory(), "Claude 工作区需要目录。");
17
+ return root;
18
+ }
19
+
20
+ async function pythonStatus(root: string, prepare: boolean, force = false) {
21
+ const python = new PythonEnvironmentService(root);
22
+ try {
23
+ if (force) await python.setup();
24
+ else {
25
+ const current = await python.inspect();
26
+ if (prepare && current.state === "unprepared") await python.setup();
27
+ }
28
+ } catch { /* The service retains the preparation or inspection error for status. */ }
29
+ finally { await python.close(); }
30
+ const status = python.status;
31
+ return { ...status, ...(status.state === "ready" ? { executable: join(status.directory!, "bin/python") } : {}) };
32
+ }
33
+
34
+ function disabled(configuration: Awaited<ReturnType<typeof readWorkspaceConfig>>) {
35
+ return configuration.error ?? "Personal Bot 未在此工作区启用。运行 /personal-bot:pbot init;配置文件:" + configuration.path;
36
+ }
37
+
38
+ export async function claudeCommand(args: readonly string[], cwd: string) {
39
+ const root = await claudeWorkspaceRoot(cwd);
40
+ const action = args.join(" ");
41
+ requireThat(["init", "status", "python setup"].includes(action), "用法:node <插件目录>/lib/claude.js init|status|python setup");
42
+ if (action === "init") await initializeWorkspace(root);
43
+ const configuration = await readWorkspaceConfig(root);
44
+ if (action === "python setup") requireThat(configuration.enabled, disabled(configuration));
45
+ return { version: packageVersion, workspaceRoot: root, resourceRoot, configuration,
46
+ python: configuration.enabled ? await pythonStatus(root, action !== "status", action === "python setup") : { state: "unprepared" as const } };
47
+ }
48
+
49
+ /** Standard command hooks consume documented stdin fields; native sessions remain entirely host-owned. */
50
+ export async function claudeHook(value: unknown): Promise<Record<string, unknown>> {
51
+ requireThat(object(value) && typeof value.hook_event_name === "string", "Claude hook 输入无效。");
52
+ if (process.env.PBOT_SUBAGENT_RUN_ID) return {};
53
+ const event = value.hook_event_name;
54
+ requireThat(["SessionStart", "UserPromptSubmit", "SubagentStart", "PreToolUse", "UserPromptExpansion"].includes(event), "Claude hook 事件未支持。");
55
+ const skillCheck = event === "PreToolUse" || event === "UserPromptExpansion";
56
+ if (skillCheck) {
57
+ const skill = event === "UserPromptExpansion"
58
+ ? value.expansion_type === "slash_command" ? value.command_name : undefined
59
+ : value.tool_name === "Skill" && object(value.tool_input) ? value.tool_input.skill : undefined;
60
+ if (typeof skill !== "string" || !skill.startsWith("personal-bot:") || skill === "personal-bot:pbot") return {};
61
+ }
62
+ requireThat(typeof value.cwd === "string", "Claude hook 缺少工作目录。");
63
+ const root = await claudeWorkspaceRoot(value.cwd);
64
+ const configuration = await readWorkspaceConfig(root);
65
+ if (skillCheck) {
66
+ if (configuration.enabled) return {};
67
+ return event === "UserPromptExpansion" ? { decision: "block", reason: disabled(configuration) } : { hookSpecificOutput: {
68
+ hookEventName: event, permissionDecision: "deny", permissionDecisionReason: disabled(configuration),
69
+ } };
70
+ }
71
+ if (!configuration.enabled) return event === "SubagentStart" ? {} : {
72
+ hookSpecificOutput: { hookEventName: event, additionalContext: disabled(configuration) },
73
+ };
74
+ if (event === "SubagentStart" && value.agent_type !== "personal-bot:general-purpose") return {};
75
+ const python = await pythonStatus(root, event === "SessionStart" || event === "UserPromptSubmit");
76
+ if (event === "SessionStart") return python.state === "error" ? { systemMessage: python.error } : {};
77
+ const member = event === "SubagentStart" || typeof value.agent_id === "string";
78
+ const role = event === "SubagentStart" ? readFile(join(root, "agents/general-purpose.md"), "utf8").catch(error => {
79
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
80
+ throw error;
81
+ }) : agentText(member ? "general-purpose" : "coordinator", root, "claude");
82
+ const [workspace, duties, agents] = await Promise.all([
83
+ readFile(join(resourceRoot, "prompts/workspace.md"), "utf8"),
84
+ role,
85
+ readFile(join(root, "AGENTS.md"), "utf8").catch(error => {
86
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
87
+ throw error;
88
+ }),
89
+ ]);
90
+ return { ...(python.state === "error" ? { systemMessage: python.error } : {}),
91
+ hookSpecificOutput: { hookEventName: event, additionalContext: [
92
+ workspace, duties, agents, JSON.stringify({ workspaceRoot: root, resourceRoot, python }),
93
+ ].filter(Boolean).join("\n\n") } };
94
+ }
@@ -20,7 +20,7 @@ export class DshHistoryWork {
20
20
  const agents = new AgentFiles(dshHomePath("pbot", "subagents"), "dsh");
21
21
  this.service = new HistoryService(root, new HistoryFiles(join(root, ".pbot/history"), "dsh"),
22
22
  new DshHistory(ctx, root, () => agents.list().filter(value => value.workspace === root).map(value => value.agentId)),
23
- new HistoryFiles(join(root, ".pbot/history")));
23
+ [new HistoryFiles(join(root, ".pbot/history"), "pi"), new HistoryFiles(join(root, ".pbot/history"), "claude")]);
24
24
  }
25
25
  attach(agent: Agent) { this.#parents.add(agent); return () => { this.#parents.delete(agent); }; }
26
26
  cancel() { this.#controller?.abort(); }
@@ -3,9 +3,10 @@ import { join } from "node:path";
3
3
  import { resourceRoot } from "../common/paths.js";
4
4
  import { requireThat } from "../common/validation.js";
5
5
 
6
- export async function agentText(agent: "coordinator" | "general-purpose", root: string) {
6
+ export async function agentText(agent: "coordinator" | "general-purpose", root: string, host: "pi" | "dsh" | "claude" = "pi") {
7
7
  requireThat(agent === "coordinator" || agent === "general-purpose", "未知职责。");
8
8
  let text = await readFile(join(resourceRoot, "agents", agent + ".md"), "utf8");
9
+ if (agent === "coordinator") text += "\n\n" + await readFile(join(resourceRoot, "prompts", host === "claude" ? "claude-coordinator.md" : "native-coordinator.md"), "utf8");
9
10
  try {
10
11
  const local = await readFile(join(root, "agents", agent + ".md"), "utf8");
11
12
  text += "\n\n工作区职责补充:\n" + local;
@@ -1,11 +1,8 @@
1
- import { readFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
1
  import type { Context } from "@deepseek-ai/cordis";
4
2
  import type { Agent } from "@deepseek-ai/dsh-agent";
5
3
  import type { SessionId } from "@deepseek-ai/dsh-session";
6
4
  import { BlockAssembler, type PreparedLlmCall } from "@deepseek-ai/dsh-llm";
7
5
  import type { HistorySummarizer } from "../../model/history.js";
8
- import { resourceRoot } from "../../common/paths.js";
9
6
  import { requireThat } from "../../common/validation.js";
10
7
  import { reduceHistorySummary } from "../history-summary.js";
11
8
 
@@ -15,19 +12,18 @@ declare module "@deepseek-ai/dsh-llm" {
15
12
 
16
13
  /** Independent text calls through the host's routing and authentication; no Agent or Session messages. */
17
14
  export function dshHistorySummarizer(ctx: Context, selection: ReturnType<Agent["model"]["current"]>, sessionId: SessionId): HistorySummarizer {
18
- return async (text, signal) => {
15
+ return async (request, signal) => {
19
16
  requireThat(selection, "请先选择 dsh 模型。"); signal.throwIfAborted();
20
- const system = await readFile(join(resourceRoot, "prompts/history-summary.md"), { encoding: "utf8", signal });
21
- const prepare = () => ctx.llm.prepareCall({ provider: selection.provider, model: selection.model, maxTokens: 2048 }, signal,
17
+ const prepare = () => ctx.llm.prepareCall({ provider: selection.provider, model: selection.model, maxTokens: request.maxTokens }, signal,
22
18
  (controls, model) => ({ ...controls, ...(model.reasoning?.efforts[0] ? { reasoningEffort: model.reasoning.efforts[0].id } : {}) }));
23
19
  let first: PreparedLlmCall | undefined = await prepare();
24
20
  const budget = Math.max(2000, Math.min(24000, Math.floor((first.context?.contextWindow ?? 12000) / 2)));
25
- const ask: HistorySummarizer = async (content, signal) => {
21
+ const ask: HistorySummarizer = async ({ system, prompt }, signal) => {
26
22
  signal.throwIfAborted();
27
23
  const prepared = first ?? await prepare(); first = undefined;
28
24
  const assembler = new BlockAssembler(); let finished = false;
29
25
  for await (const chunk of prepared.stream({ ...prepared.config, system, sessionId, purpose: "pbot-history", signal, tools: [],
30
- messages: [{ role: "user", content: [{ type: "text", text: content }] }] })) {
26
+ messages: [{ role: "user", content: [{ type: "text", text: prompt }] }] })) {
31
27
  signal.throwIfAborted(); assembler.push(chunk); if (chunk.type === "finish") finished = true;
32
28
  }
33
29
  signal.throwIfAborted();
@@ -38,6 +34,6 @@ export function dshHistorySummarizer(ctx: Context, selection: ReturnType<Agent["
38
34
  const answer = blocks.filter(block => block.type === "text").map(block => block.text).join("\n").trim();
39
35
  requireThat(answer, "历史摘要为空。"); return answer;
40
36
  };
41
- return reduceHistorySummary(budget, ask)(text, signal);
37
+ return reduceHistorySummary(budget, ask)(request, signal);
42
38
  };
43
39
  }
@@ -15,8 +15,8 @@ const text = (content: Question["data"]["content"]) => content.flatMap(block =>
15
15
 
16
16
  /** Archive questions and the final/partial answer; raw tool records stay in the native log. */
17
17
  export function projectDshHistory(header: SessionHeader, events: readonly SessionEvent[], name = ""): HistorySession {
18
- const exchanges: HistoryExchange[] = [];
19
- let users: Question[] = [], answer: Answer | undefined;
18
+ const exchanges: HistoryExchange[] = [], supersededEntryIds: string[] = [];
19
+ let users: Question[] = [], answer: Answer | undefined, observed: string[] = [];
20
20
  const finish = (completed = false) => {
21
21
  if (users.length) {
22
22
  const entries = [...users, ...(answer ? [answer] : [])];
@@ -27,17 +27,23 @@ export function projectDshHistory(header: SessionHeader, events: readonly Sessio
27
27
  text: users.map(event => (event.data.source.kind === "user" ? "用户:\n" : "协调者要求:\n") + text(event.data.content)).join("\n\n") +
28
28
  (body ? "\n\n助手:\n" + body : "") });
29
29
  }
30
- users = []; answer = undefined;
30
+ const last = (answer ?? users.at(-1))?.seq;
31
+ supersededEntryIds.push(...observed.filter(id => id !== "dsh:" + last));
32
+ users = []; answer = undefined; observed = [];
31
33
  };
32
34
  for (const event of events) {
33
35
  if (event.type === "turn/start") finish();
34
- else if (event.type === "user/message" && ["user", "pbot-input"].includes(event.data.source.kind)) users.push(event);
35
- else if (event.type === "assistant/message" && users.length) answer = event;
36
+ else if (event.type === "user/message" && ["user", "pbot-input"].includes(event.data.source.kind)) {
37
+ if (!answer) observed.push("dsh:" + event.seq);
38
+ users.push(event);
39
+ } else if (event.type === "assistant/message" && users.length) {
40
+ answer = event; observed.push("dsh:" + event.seq);
41
+ }
36
42
  else if (event.type === "turn/end") finish(event.data.reason.kind === "completed");
37
43
  }
38
44
  finish();
39
45
  return { sessionId: header.id, name: name || exchanges[0]?.text.replace(/\s+/g, " ").slice(0, 80) || "",
40
- branches: exchanges.length ? [exchanges] : [] };
46
+ branches: exchanges.length ? [exchanges] : [], supersededEntryIds };
41
47
  }
42
48
 
43
49
  export class DshHistory implements HistorySource {
@@ -1,20 +1,30 @@
1
1
  import type { HistorySummarizer } from "../model/history.js";
2
- import { requireThat } from "../common/validation.js";
2
+
3
+ /** Split Pi/dsh summary inputs within the model's character budget. */
4
+ export function splitHistorySummary(text: string, budget: number): string[] {
5
+ if (!Number.isInteger(budget) || budget < 2) throw new Error("历史摘要分段预算无效。");
6
+ const parts: string[] = [];
7
+ for (let offset = 0; offset < text.length;) {
8
+ let end = Math.min(text.length, offset + budget);
9
+ if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]!)) end--;
10
+ parts.push(text.slice(offset, end)); offset = end;
11
+ }
12
+ return parts;
13
+ }
3
14
 
4
15
  export function reduceHistorySummary(budget: number, ask: HistorySummarizer): HistorySummarizer {
5
- return async (text, signal) => {
16
+ return async (request, signal) => {
17
+ let text = request.prompt;
6
18
  while (text.length > budget) {
7
19
  const parts: string[] = [];
8
- for (let offset = 0; offset < text.length;) {
20
+ for (const prompt of splitHistorySummary(text, budget)) {
9
21
  signal.throwIfAborted();
10
- let end = Math.min(text.length, offset + budget);
11
- if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]!)) end--;
12
- parts.push(await ask(text.slice(offset, end), signal)); offset = end;
22
+ parts.push(await ask({ ...request, prompt }, signal));
13
23
  }
14
24
  const smaller = parts.join("\n\n");
15
- requireThat(smaller.length < text.length, "历史摘要未缩短,稍后重试。");
25
+ if (smaller.length >= text.length) throw new Error("历史摘要未缩短,稍后重试。");
16
26
  text = smaller;
17
27
  }
18
- signal.throwIfAborted(); return ask(text, signal);
28
+ signal.throwIfAborted(); return ask({ ...request, prompt: text }, signal);
19
29
  };
20
30
  }
@@ -1,9 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
2
  import { parseSessionEntries, SessionManager, type ExtensionContext, type SessionEntry, type SessionMessageEntry } from "@earendil-works/pi-coding-agent";
4
3
  import type { HistoryExchange, HistoryLocation, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
5
4
  import { requireThat } from "../../common/validation.js";
6
- import { resourceRoot } from "../../common/paths.js";
7
5
  import { reduceHistorySummary } from "../history-summary.js";
8
6
 
9
7
  function text(content: unknown): string {
@@ -11,30 +9,32 @@ function text(content: unknown): string {
11
9
  if (!Array.isArray(content)) return "";
12
10
  return content.flatMap(block => block.type === "text" ? [String(block.text)] : block.type === "image" ? ["[图片]"] : []).join("\n");
13
11
  }
14
- function exchanges(branch: SessionEntry[]): HistoryExchange[] {
15
- const result: HistoryExchange[] = [];
16
- let users: SessionMessageEntry[] = [], partial: SessionMessageEntry | undefined;
12
+ function exchanges(branch: SessionEntry[]) {
13
+ const result: HistoryExchange[] = [], supersededEntryIds: string[] = [];
14
+ let users: SessionMessageEntry[] = [], partial: SessionMessageEntry | undefined, observed: string[] = [];
17
15
  const finish = (answer?: SessionMessageEntry, completed = false) => {
18
16
  if (!users.length) return;
19
17
  const entries = [...users, ...(answer ? [answer] : [])];
20
18
  result.push({ entryIds: entries.map(entry => entry.id), from: users[0]!.timestamp, to: entries.at(-1)!.timestamp, completed,
21
19
  text: users.map(entry => "用户:\n" + text("content" in entry.message ? entry.message.content : "")).join("\n\n") +
22
20
  (answer && "content" in answer.message ? "\n\n助手:\n" + text(answer.message.content) : "") });
23
- users = []; partial = undefined;
21
+ supersededEntryIds.push(...observed.filter(id => id !== entries.at(-1)!.id));
22
+ users = []; partial = undefined; observed = [];
24
23
  };
25
24
  for (const entry of branch) {
26
25
  if (entry.type !== "message") continue;
27
26
  const message = entry.message;
28
27
  if (message.role === "user") {
29
28
  if (partial?.message.role === "assistant" && ["aborted", "error"].includes(partial.message.stopReason)) finish(partial);
29
+ if (!partial) observed.push(entry.id);
30
30
  users.push(entry);
31
31
  } else if (message.role === "assistant" && users.length) {
32
- partial = entry;
32
+ partial = entry; observed.push(entry.id);
33
33
  if (message.stopReason === "stop" && !message.content.some(block => block.type === "toolCall")) finish(entry, true);
34
34
  }
35
35
  }
36
36
  finish(partial);
37
- return result;
37
+ return { exchanges: result, supersededEntryIds };
38
38
  }
39
39
 
40
40
  /** Parse in memory; never open a writable SessionManager or migrate native JSONL. */
@@ -44,18 +44,20 @@ export function projectHistory(content: string): HistorySession {
44
44
  const manager = SessionManager.inMemory(header.cwd, undefined, parsed), entries = manager.getEntries();
45
45
  const parents = new Set(entries.map(entry => entry.parentId));
46
46
  const tips = entries.filter(entry => !parents.has(entry.id));
47
- return { sessionId: header.id, name: manager.getSessionName() ?? "", branches: tips.map(tip => exchanges(manager.getBranch(tip.id))).filter(branch => branch.length) };
47
+ const branches = tips.map(tip => exchanges(manager.getBranch(tip.id)));
48
+ return { sessionId: header.id, name: manager.getSessionName() ?? "", branches: branches.map(value => value.exchanges).filter(branch => branch.length),
49
+ supersededEntryIds: [...new Set(branches.flatMap(value => value.supersededEntryIds))] };
48
50
  }
49
51
 
50
52
  export const historyLocation = (ctx: ExtensionContext): HistoryLocation => {
51
53
  const file = ctx.sessionManager.getSessionFile();
52
- return { directory: ctx.sessionManager.getSessionDir(), ...(file ? { file } : {}) };
54
+ return { host: "pi", directory: ctx.sessionManager.getSessionDir(), ...(file ? { file } : {}) };
53
55
  };
54
56
  export class PiHistory implements HistorySource {
55
57
  readonly host = "pi";
56
58
  constructor(private readonly root: string, private readonly relatedFiles: () => string[] = () => []) {}
57
59
  async scan(location: HistoryLocation, signal?: AbortSignal) {
58
- requireThat(location.host !== "dsh", "Pi 历史只读取 Pi 原生会话。");
60
+ requireThat(location.host === "pi", "Pi 历史只读取 Pi 原生会话。");
59
61
  const lists = await Promise.all([SessionManager.list(this.root, undefined, undefined, signal),
60
62
  SessionManager.list(this.root, location.directory, undefined, signal)]);
61
63
  const files = new Set([...lists.flat().map(session => session.path), ...this.relatedFiles(), ...(location.file ? [location.file] : [])]);
@@ -81,12 +83,11 @@ export class PiHistory implements HistorySource {
81
83
  export async function historySummarizer(ctx: ExtensionContext): Promise<HistorySummarizer> {
82
84
  const model = ctx.model;
83
85
  requireThat(model, "请先选择 Pi 模型。");
84
- const systemPrompt = await readFile(join(resourceRoot, "prompts/history-summary.md"), "utf8");
85
86
  const budget = Math.max(2000, Math.min(24000, Math.floor(model.contextWindow / 2)));
86
- const ask = async (content: string, signal: AbortSignal) => {
87
+ const ask: HistorySummarizer = async ({ system, prompt, maxTokens }, signal) => {
87
88
  signal.throwIfAborted();
88
- const response = await ctx.modelRegistry.streamSimple(model, { systemPrompt,
89
- messages: [{ role: "user", content, timestamp: Date.now() }] }, { signal, reasoning: "low", maxTokens: 2048, transport: "sse" }).result();
89
+ const response = await ctx.modelRegistry.streamSimple(model, { systemPrompt: system,
90
+ messages: [{ role: "user", content: prompt, timestamp: Date.now() }] }, { signal, reasoning: "low", maxTokens, transport: "sse" }).result();
90
91
  signal.throwIfAborted();
91
92
  requireThat(response.stopReason === "stop", response.errorMessage ?? "历史摘要未完成:" + response.stopReason);
92
93
  const answer = response.content.filter(part => part.type === "text").map(part => part.text).join("\n").trim();
@@ -13,8 +13,8 @@ export interface AgentDescriptor {
13
13
  }
14
14
  /** null means no conversation input has been handed to Pi yet. */
15
15
  export interface AgentSessionRef { file: string | null }
16
- /** Native references are interpreted only by their owning host adapter. */
17
16
  export type NativeAgentHost = "pi" | "dsh";
17
+ /** Native references are interpreted only by their owning host adapter. */
18
18
  export type AgentSessionReference = { host: "pi"; file: string | null } | { host: "dsh"; sessionId: string } | AcpSessionReference;
19
19
  export interface AgentLaunch { generation: string; name: string; sequence: number; stop: boolean; startedAt: number }
20
20
  export interface AgentMessage { requestId: string; generation: string; sequence: number; message: string; delivery: "steer" | "followUp"; files: string[] }
@@ -9,6 +9,8 @@ export interface HistorySession {
9
9
  sessionId: string;
10
10
  name: string;
11
11
  branches: HistoryExchange[][];
12
+ /** Earlier partial observations replaced along the same native branch or turn; never persisted. */
13
+ supersededEntryIds?: string[];
12
14
  }
13
15
  export interface HistoryNode extends HistoryExchange {
14
16
  id: string;
@@ -25,10 +27,16 @@ export interface HistoryRecord {
25
27
  name: string;
26
28
  nodes: HistoryNode[];
27
29
  }
28
- export type HistoryHost = "pi" | "dsh";
29
- export type HistoryLocation = { host?: "pi"; directory: string; file?: string } | { host: "dsh"; sessionId?: string };
30
+ export type HistoryHost = "pi" | "dsh" | "claude";
31
+ export type HistoryLocation = { host: "pi"; directory: string; file?: string } |
32
+ { host: "dsh"; sessionId?: string };
30
33
  export interface HistorySource {
31
- readonly host: HistoryHost;
34
+ readonly host: HistoryLocation["host"];
32
35
  scan(location: HistoryLocation, signal?: AbortSignal): Promise<{ sessions: HistorySession[]; warnings: string[] }>;
33
36
  }
34
- export type HistorySummarizer = (text: string, signal: AbortSignal) => Promise<string>;
37
+ export interface HistorySummaryRequest {
38
+ system: string;
39
+ prompt: string;
40
+ maxTokens: number;
41
+ }
42
+ export type HistorySummarizer = (request: HistorySummaryRequest, signal: AbortSignal) => Promise<string>;
package/src/pbot.ts CHANGED
@@ -23,11 +23,11 @@ export default function pbot(pi: ExtensionAPI) {
23
23
  const confirmations = new Confirmations(), registry = new ToolRegistry(pi);
24
24
  const lifecycle = new Lifecycle((root, configuration) => {
25
25
  const agents = new AgentService(root, agentDirectory(), new AgentBackends(new PiAgents(), agentDirectory(), configuration.acp));
26
- const history = new HistoryService(root, new HistoryFiles(join(root, ".pbot/history")), new PiHistory(root, () =>
26
+ const history = new HistoryService(root, new HistoryFiles(join(root, ".pbot/history"), "pi"), new PiHistory(root, () =>
27
27
  agents.files.list().filter(agent => agent.workspace === root).flatMap(agent => {
28
28
  const file = agents.files.optional(agent.agentId, "session-ref.json", sessionRef)?.file;
29
29
  return file ? [file] : [];
30
- })), new HistoryFiles(join(root, ".pbot/history"), "dsh"));
30
+ })), [new HistoryFiles(join(root, ".pbot/history"), "dsh"), new HistoryFiles(join(root, ".pbot/history"), "claude")]);
31
31
  return new WorkspaceInstance(root, new PythonEnvironmentService(root), agents, new TeamService(root, agents.files, agents.teamFiles), history);
32
32
  }, instance => registry.register(mainTools(instance.agents, instance.teams, instance.history, instance)), () => registry.hide());
33
33
  registerCommand(pi, lifecycle, confirmations);
@@ -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
  }