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
@@ -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
+ }
@@ -2,7 +2,8 @@ import type { Context } from "@deepseek-ai/cordis";
2
2
  import type {} from "@deepseek-ai/dsh-commands";
3
3
  import { Type, type Static } from "typebox";
4
4
  import { object, json } from "../../common/json.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, type AgentInput } from "../../tools/agents/actions.js";
7
8
  import { dshAgentActionSchema } from "../../tools/agents/dsh-contract.js";
8
9
  import { executeTeam, executeTeamMessage } from "../../tools/teams/actions.js";
@@ -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(); }
@@ -6,7 +6,8 @@ import { SessionId } from "@deepseek-ai/dsh-session";
6
6
  import { extractSessionEventText } from "@deepseek-ai/dsh-session-query";
7
7
  import { Type, type Static } from "typebox";
8
8
  import { json, type Json } from "../../common/json.js";
9
- import { requireThat, schema } from "../../common/validation.js";
9
+ import { requireThat } from "../../common/validation.js";
10
+ import { schema } from "../../common/schema.js";
10
11
  import { packageVersion } from "../../common/version.js";
11
12
  import { historyInput } from "../../tools/history/contract.js";
12
13
  import { executeHistory } from "../../tools/history/actions.js";
@@ -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);