personal-bot 0.3.1 → 0.3.2

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 (256) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +1 -1
  4. package/README.zh-CN.md +1 -1
  5. package/bin/pbot-pi-acp.mjs +27 -11
  6. package/bin/pbot.mjs +1 -1
  7. package/docs/README.md +1 -1
  8. package/docs/architecture/design.md +23 -10
  9. package/docs/architecture/extensibility.md +20 -18
  10. package/docs/architecture/model-context.md +2 -2
  11. package/docs/architecture/principles.md +4 -3
  12. package/docs/guides/capabilities.md +3 -3
  13. package/docs/guides/history.md +50 -16
  14. package/docs/guides/workspace-configuration.md +31 -6
  15. package/docs/hosts/antigravity.md +2 -0
  16. package/docs/hosts/claude-code.md +1 -1
  17. package/docs/hosts/dsh.md +1 -1
  18. package/docs/hosts/pi.md +1 -1
  19. package/hooks/hooks.json +3 -0
  20. package/lib/antigravity-plugin/hooks.json +7 -0
  21. package/lib/antigravity-plugin/lib/claude.js +2 -2
  22. package/lib/antigravity-plugin/lib/extension/acp-worker.js +156 -11
  23. package/lib/antigravity-plugin/lib/extension/{plugin-runtime.d.ts → hosts/plugin-runtime.d.ts} +2 -2
  24. package/lib/antigravity-plugin/lib/extension/{plugin-runtime.js → hosts/plugin-runtime.js} +34 -8
  25. package/lib/antigravity-plugin/lib/extension/mcp.js +1113 -78
  26. package/lib/antigravity-plugin/lib/integrations/agent-resources.d.ts +1 -0
  27. package/lib/antigravity-plugin/lib/integrations/agent-resources.js +5 -1
  28. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity/adapter.d.ts +6 -0
  29. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity/adapter.js +171 -0
  30. package/lib/antigravity-plugin/lib/integrations/hosts/{claude.d.ts → claude/adapter.d.ts} +1 -1
  31. package/lib/antigravity-plugin/lib/integrations/hosts/{claude.js → claude/adapter.js} +32 -4
  32. package/lib/antigravity-plugin/lib/integrations/hosts/{registry.js → plugin-registry.js} +2 -2
  33. package/lib/antigravity-plugin/lib/model/history.d.ts +169 -0
  34. package/lib/antigravity-plugin/lib/model/plugin-host.d.ts +26 -0
  35. package/lib/antigravity-plugin/lib/model/workspace-config.d.ts +25 -0
  36. package/lib/antigravity-plugin/lib/plugin.js +2 -2
  37. package/lib/antigravity-plugin/lib/services/history/history-capture.d.ts +4 -0
  38. package/lib/antigravity-plugin/lib/services/history/history-capture.js +86 -0
  39. package/lib/antigravity-plugin/lib/services/history/history-index.d.ts +17 -0
  40. package/lib/antigravity-plugin/lib/services/history/history-index.js +112 -0
  41. package/lib/antigravity-plugin/lib/services/history/history-migrate.d.ts +12 -0
  42. package/lib/antigravity-plugin/lib/services/history/history-migrate.js +88 -0
  43. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/monthly.d.ts +7 -0
  44. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/monthly.js +121 -0
  45. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/session.d.ts +7 -0
  46. package/lib/antigravity-plugin/lib/services/history/summary-dimensions/session.js +124 -0
  47. package/lib/antigravity-plugin/lib/services/history/summary-registry.d.ts +7 -0
  48. package/lib/antigravity-plugin/lib/services/history/summary-registry.js +36 -0
  49. package/lib/antigravity-plugin/lib/services/history/summary-runner.d.ts +37 -0
  50. package/lib/antigravity-plugin/lib/services/history/summary-runner.js +301 -0
  51. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.d.ts +5 -1
  52. package/lib/antigravity-plugin/lib/services/workspace/workspace-config.js +73 -4
  53. package/lib/antigravity-plugin/lib/storage/file-access.d.ts +2 -0
  54. package/lib/antigravity-plugin/lib/storage/file-access.js +26 -0
  55. package/lib/antigravity-plugin/lib/storage/history-files.d.ts +54 -0
  56. package/lib/antigravity-plugin/lib/storage/history-files.js +467 -0
  57. package/lib/antigravity-plugin/lib/storage/history-format.d.ts +6 -0
  58. package/lib/antigravity-plugin/lib/storage/history-format.js +62 -0
  59. package/lib/antigravity-plugin/package.json +1 -1
  60. package/lib/antigravity-plugin/plugin.json +1 -1
  61. package/lib/antigravity-plugin/skills/provider-connections/SKILL.md +22 -12
  62. package/lib/claude.js +2 -2
  63. package/lib/client.js +21 -11
  64. package/lib/dsh.js +4 -4
  65. package/lib/extension/{acp-member.d.ts → acp/member.d.ts} +5 -5
  66. package/lib/extension/{acp-member.js → acp/member.js} +6 -6
  67. package/lib/extension/acp/worker.d.ts +1 -0
  68. package/lib/extension/acp/worker.js +384 -0
  69. package/lib/extension/acp-worker.js +156 -11
  70. package/lib/extension/{dsh → hosts/dsh}/acp-member.js +8 -8
  71. package/lib/extension/hosts/dsh/command.js +92 -0
  72. package/lib/extension/{dsh → hosts/dsh}/files.js +3 -3
  73. package/lib/extension/hosts/dsh/history.d.ts +4 -0
  74. package/lib/extension/hosts/dsh/history.js +62 -0
  75. package/lib/extension/{dsh → hosts/dsh}/management.d.ts +1 -1
  76. package/lib/extension/{dsh → hosts/dsh}/management.js +12 -10
  77. package/lib/extension/{dsh → hosts/dsh}/workspace.d.ts +3 -9
  78. package/lib/extension/{dsh → hosts/dsh}/workspace.js +32 -70
  79. package/lib/extension/{plugin-runtime.d.ts → hosts/plugin-runtime.d.ts} +2 -2
  80. package/lib/extension/{plugin-runtime.js → hosts/plugin-runtime.js} +34 -8
  81. package/lib/extension/{mcp-bridge.d.ts → mcp/bridge.d.ts} +1 -1
  82. package/lib/extension/{mcp-bridge.js → mcp/bridge.js} +4 -4
  83. package/lib/extension/{mcp-workers.d.ts → mcp/workers.d.ts} +222 -2
  84. package/lib/extension/{mcp-workers.js → mcp/workers.js} +229 -63
  85. package/lib/extension/mcp.js +1113 -78
  86. package/lib/extension/{setup-cli.js → setup/cli.js} +9 -9
  87. package/lib/integrations/acp/connection.d.ts +11 -10
  88. package/lib/integrations/acp/connection.js +6 -0
  89. package/lib/integrations/acp/harnesses/claude.js +1 -1
  90. package/lib/integrations/acp/harnesses/dsh.js +1 -1
  91. package/lib/integrations/acp/history-summary.d.ts +17 -0
  92. package/lib/integrations/acp/history-summary.js +100 -0
  93. package/lib/integrations/agent-resources.d.ts +1 -0
  94. package/lib/integrations/agent-resources.js +5 -1
  95. package/lib/integrations/hosts/antigravity/adapter.d.ts +6 -0
  96. package/lib/integrations/hosts/antigravity/adapter.js +171 -0
  97. package/lib/integrations/hosts/{claude.d.ts → claude/adapter.d.ts} +1 -1
  98. package/lib/integrations/hosts/{claude.js → claude/adapter.js} +32 -4
  99. package/lib/integrations/{dsh → hosts/dsh}/mcp.d.ts +1 -1
  100. package/lib/integrations/{dsh → hosts/dsh}/resources.d.ts +1 -1
  101. package/lib/integrations/{dsh → hosts/dsh}/resources.js +4 -4
  102. package/lib/integrations/{dsh → hosts/dsh}/schema.js +1 -1
  103. package/lib/integrations/{dsh → hosts/dsh}/skills.js +1 -1
  104. package/lib/integrations/hosts/{registry.js → plugin-registry.js} +2 -2
  105. package/lib/integrations/installation/pi-setup.js +1 -1
  106. package/lib/model/history.d.ts +133 -34
  107. package/lib/model/plugin-host.d.ts +26 -0
  108. package/lib/model/workspace-config.d.ts +25 -0
  109. package/lib/plugin.js +2 -2
  110. package/lib/services/agents/agent-run.d.ts +1 -1
  111. package/lib/services/history/history-capture.d.ts +4 -0
  112. package/lib/services/history/history-capture.js +86 -0
  113. package/lib/services/history/history-index.d.ts +16 -7
  114. package/lib/services/history/history-index.js +48 -70
  115. package/lib/services/history/history-migrate.d.ts +12 -0
  116. package/lib/services/history/history-migrate.js +88 -0
  117. package/lib/services/history/history-query.d.ts +51 -0
  118. package/lib/services/history/history-query.js +371 -0
  119. package/lib/services/history/summary-command.d.ts +20 -0
  120. package/lib/services/history/summary-command.js +68 -0
  121. package/lib/services/history/summary-dimensions/monthly.d.ts +7 -0
  122. package/lib/services/history/summary-dimensions/monthly.js +121 -0
  123. package/lib/services/history/summary-dimensions/session.d.ts +7 -0
  124. package/lib/services/history/summary-dimensions/session.js +124 -0
  125. package/lib/services/history/summary-registry.d.ts +7 -0
  126. package/lib/services/history/summary-registry.js +36 -0
  127. package/lib/services/history/summary-runner.d.ts +37 -0
  128. package/lib/services/history/summary-runner.js +301 -0
  129. package/lib/services/workspace/workspace-config.d.ts +5 -1
  130. package/lib/services/workspace/workspace-config.js +73 -4
  131. package/lib/storage/history-files.d.ts +45 -9
  132. package/lib/storage/history-files.js +373 -247
  133. package/lib/storage/history-format.d.ts +3 -12
  134. package/lib/storage/history-format.js +26 -50
  135. package/lib/tools/history/actions.d.ts +3 -68
  136. package/lib/tools/history/actions.js +7 -5
  137. package/lib/tools/history/contract.d.ts +14 -7
  138. package/lib/tools/history/contract.js +58 -18
  139. package/lib/tools/history/dsh-tool.d.ts +1 -2
  140. package/lib/tools/history/dsh-tool.js +11 -5
  141. package/lib/ui/dsh/management.js +18 -5
  142. package/package.json +1 -1
  143. package/resources/prompts/history-coordinator.md +1 -1
  144. package/resources/prompts/history-monthly-summary.md +13 -0
  145. package/resources/prompts/history-summary.md +10 -4
  146. package/resources/skills/provider-connections/SKILL.md +22 -12
  147. package/src/claude.ts +2 -2
  148. package/src/dsh.ts +4 -4
  149. package/src/extension/{acp-member.ts → acp/member.ts} +7 -7
  150. package/src/extension/{acp-worker.ts → acp/worker.ts} +131 -17
  151. package/src/extension/{dsh → hosts/dsh}/acp-member.ts +9 -9
  152. package/src/extension/hosts/dsh/command.ts +92 -0
  153. package/src/extension/{dsh → hosts/dsh}/files.ts +3 -3
  154. package/src/extension/hosts/dsh/history.ts +67 -0
  155. package/src/extension/{dsh → hosts/dsh}/management.ts +11 -9
  156. package/src/extension/{dsh → hosts/dsh}/workspace.ts +31 -50
  157. package/src/extension/{pi-acp-member.ts → hosts/pi/acp-member.ts} +9 -9
  158. package/src/extension/hosts/pi/command.ts +158 -0
  159. package/src/extension/{events.ts → hosts/pi/events.ts} +14 -4
  160. package/src/extension/hosts/pi/history.ts +45 -0
  161. package/src/extension/{lifecycle.ts → hosts/pi/lifecycle.ts} +7 -11
  162. package/src/extension/{plugin-runtime.ts → hosts/plugin-runtime.ts} +29 -9
  163. package/src/extension/{mcp-bridge.ts → mcp/bridge.ts} +5 -5
  164. package/src/extension/{mcp-workers.ts → mcp/workers.ts} +237 -64
  165. package/src/extension/{setup-cli.ts → setup/cli.ts} +11 -11
  166. package/src/integrations/acp/connection.ts +6 -0
  167. package/src/integrations/acp/harnesses/claude.ts +1 -1
  168. package/src/integrations/acp/harnesses/dsh.ts +1 -1
  169. package/src/integrations/acp/history-summary.ts +108 -0
  170. package/src/integrations/agent-resources.ts +6 -0
  171. package/src/integrations/hosts/antigravity/adapter.ts +161 -0
  172. package/src/integrations/hosts/{claude.ts → claude/adapter.ts} +28 -5
  173. package/src/integrations/{dsh → hosts/dsh}/mcp.ts +1 -1
  174. package/src/integrations/{dsh → hosts/dsh}/resources.ts +5 -5
  175. package/src/integrations/{dsh → hosts/dsh}/schema.ts +1 -1
  176. package/src/integrations/{dsh → hosts/dsh}/session.ts +2 -2
  177. package/src/integrations/{dsh → hosts/dsh}/skills.ts +1 -1
  178. package/src/integrations/{pi → hosts/pi}/mcp.ts +1 -1
  179. package/src/integrations/{pi → hosts/pi}/skills.ts +1 -1
  180. package/src/integrations/hosts/{registry.ts → plugin-registry.ts} +2 -2
  181. package/src/integrations/installation/pi-setup.ts +1 -1
  182. package/src/mcp.ts +1 -1
  183. package/src/model/history.ts +151 -26
  184. package/src/model/plugin-host.ts +26 -2
  185. package/src/model/workspace-config.ts +30 -0
  186. package/src/pbot.ts +13 -22
  187. package/src/plugin.ts +2 -2
  188. package/src/services/history/history-capture.ts +83 -0
  189. package/src/services/history/history-index.ts +48 -62
  190. package/src/services/history/history-migrate.ts +89 -0
  191. package/src/services/history/history-query.ts +415 -0
  192. package/src/services/history/summary-command.ts +69 -0
  193. package/src/services/history/summary-dimensions/monthly.ts +139 -0
  194. package/src/services/history/summary-dimensions/session.ts +149 -0
  195. package/src/services/history/summary-registry.ts +44 -0
  196. package/src/services/history/summary-runner.ts +352 -0
  197. package/src/services/workspace/workspace-config.ts +91 -5
  198. package/src/storage/history-files.ts +408 -188
  199. package/src/storage/history-format.ts +46 -60
  200. package/src/tools/history/actions.ts +8 -6
  201. package/src/tools/history/contract.ts +65 -20
  202. package/src/tools/history/dsh-tool.ts +17 -8
  203. package/src/tools/history/pi-tool.ts +21 -0
  204. package/src/tools/register.ts +3 -4
  205. package/src/ui/dsh/management.ts +27 -11
  206. package/src/ui/{confirmation.ts → pi/confirmation.ts} +1 -1
  207. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.d.ts +0 -4
  208. package/lib/antigravity-plugin/lib/integrations/hosts/antigravity.js +0 -79
  209. package/lib/extension/dsh/command.js +0 -50
  210. package/lib/extension/dsh/history.d.ts +0 -15
  211. package/lib/extension/dsh/history.js +0 -87
  212. package/lib/integrations/dsh/history-summary.d.ts +0 -11
  213. package/lib/integrations/dsh/history-summary.js +0 -36
  214. package/lib/integrations/dsh/history.d.ts +0 -16
  215. package/lib/integrations/dsh/history.js +0 -167
  216. package/lib/integrations/history-summary.d.ts +0 -4
  217. package/lib/integrations/history-summary.js +0 -32
  218. package/lib/integrations/hosts/antigravity.d.ts +0 -4
  219. package/lib/integrations/hosts/antigravity.js +0 -79
  220. package/lib/services/history/history-service.d.ts +0 -106
  221. package/lib/services/history/history-service.js +0 -242
  222. package/lib/storage/acp-history.d.ts +0 -10
  223. package/lib/storage/acp-history.js +0 -57
  224. package/src/extension/command.ts +0 -76
  225. package/src/extension/dsh/command.ts +0 -54
  226. package/src/extension/dsh/history.ts +0 -74
  227. package/src/extension/history.ts +0 -26
  228. package/src/integrations/dsh/history-summary.ts +0 -39
  229. package/src/integrations/dsh/history.ts +0 -84
  230. package/src/integrations/history-summary.ts +0 -30
  231. package/src/integrations/hosts/antigravity.ts +0 -83
  232. package/src/integrations/pi/history.ts +0 -99
  233. package/src/services/history/history-service.ts +0 -195
  234. package/src/storage/acp-history.ts +0 -49
  235. package/src/tools/history/tool.ts +0 -19
  236. /package/lib/antigravity-plugin/lib/integrations/hosts/{registry.d.ts → plugin-registry.d.ts} +0 -0
  237. /package/lib/{extension/acp-worker.d.ts → antigravity-plugin/lib/model/history.js} +0 -0
  238. /package/lib/extension/{dsh → hosts/dsh}/acp-member.d.ts +0 -0
  239. /package/lib/extension/{dsh → hosts/dsh}/command.d.ts +0 -0
  240. /package/lib/extension/{dsh → hosts/dsh}/files.d.ts +0 -0
  241. /package/lib/extension/{setup-guard.js → setup/guard.js} +0 -0
  242. /package/lib/integrations/acp/{claude.d.ts → claude-settings.d.ts} +0 -0
  243. /package/lib/integrations/acp/{claude.js → claude-settings.js} +0 -0
  244. /package/lib/integrations/{dsh → hosts/dsh}/mcp.js +0 -0
  245. /package/lib/integrations/{dsh → hosts/dsh}/messages.d.ts +0 -0
  246. /package/lib/integrations/{dsh → hosts/dsh}/messages.js +0 -0
  247. /package/lib/integrations/{dsh → hosts/dsh}/root-agents.d.ts +0 -0
  248. /package/lib/integrations/{dsh → hosts/dsh}/root-agents.js +0 -0
  249. /package/lib/integrations/{dsh → hosts/dsh}/schema.d.ts +0 -0
  250. /package/lib/integrations/{dsh → hosts/dsh}/skills.d.ts +0 -0
  251. /package/lib/integrations/hosts/{registry.d.ts → plugin-registry.d.ts} +0 -0
  252. /package/src/extension/{setup-guard.ts → setup/guard.ts} +0 -0
  253. /package/src/integrations/acp/{claude.ts → claude-settings.ts} +0 -0
  254. /package/src/integrations/{dsh → hosts/dsh}/messages.ts +0 -0
  255. /package/src/integrations/{dsh → hosts/dsh}/root-agents.ts +0 -0
  256. /package/src/integrations/{pi → hosts/pi}/agent-tools.ts +0 -0
@@ -1,84 +0,0 @@
1
- import { realpath } from "node:fs/promises";
2
- import type { Context } from "@deepseek-ai/cordis";
3
- import type { SessionEvent, SessionHeader } from "@deepseek-ai/dsh-session";
4
- import { SessionId } from "@deepseek-ai/dsh-session";
5
- import type {} from "@deepseek-ai/dsh-session-query";
6
- import type { HistoryExchange, HistoryLocation, HistorySession, HistorySource } from "../../model/history.js";
7
- import { requireThat } from "../../common/validation.js";
8
- import { finalDshAnswer } from "./messages.js";
9
-
10
- type Question = Extract<SessionEvent, { type: "user/message" }>;
11
- type Answer = Extract<SessionEvent, { type: "assistant/message" }>;
12
- const text = (content: Question["data"]["content"]) => content.flatMap(block => block.type === "text" ? [block.text] :
13
- block.type === "image" ? ["[图片 " + (block.attachment.name ?? block.attachment.attachmentId) + "]"] :
14
- block.type === "file" ? ["[附件 " + (block.attachment.name ?? block.attachment.attachmentId) + "]"] : []).join("\n");
15
-
16
- /** Archive questions and the final/partial answer; raw tool records stay in the native log. */
17
- export function projectDshHistory(header: SessionHeader, events: readonly SessionEvent[], name = ""): HistorySession {
18
- const exchanges: HistoryExchange[] = [], supersededEntryIds: string[] = [];
19
- let users: Question[] = [], answer: Answer | undefined, observed: string[] = [];
20
- const finish = (completed = false) => {
21
- if (users.length) {
22
- const entries = [...users, ...(answer ? [answer] : [])];
23
- const body = answer ? answer.data.message.content.filter(block => block.type === "text").map(block => block.text).join("\n") : "";
24
- exchanges.push({ entryIds: entries.map(event => "dsh:" + event.seq), from: new Date(users[0]!.time).toISOString(),
25
- to: new Date(entries.at(-1)!.time).toISOString(),
26
- completed: completed && Boolean(answer && finalDshAnswer(answer).trim()),
27
- text: users.map(event => (event.data.source.kind === "user" ? "用户:\n" : "协调者要求:\n") + text(event.data.content)).join("\n\n") +
28
- (body ? "\n\n助手:\n" + body : "") });
29
- }
30
- const last = (answer ?? users.at(-1))?.seq;
31
- supersededEntryIds.push(...observed.filter(id => id !== "dsh:" + last));
32
- users = []; answer = undefined; observed = [];
33
- };
34
- for (const event of events) {
35
- if (event.type === "turn/start") finish();
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
- }
42
- else if (event.type === "turn/end") finish(event.data.reason.kind === "completed");
43
- }
44
- finish();
45
- return { sessionId: header.id, name, branches: exchanges.length ? [exchanges] : [], supersededEntryIds };
46
- }
47
-
48
- export class DshHistory implements HistorySource {
49
- readonly host = "dsh";
50
- constructor(private readonly ctx: Context, private readonly root: string, private readonly relatedSessions: () => string[] = () => []) {}
51
- async scan(location: HistoryLocation, signal?: AbortSignal, excluded?: ReadonlySet<string>) {
52
- requireThat(location.host === "dsh", "dsh 历史只读取 dsh 原生会话。");
53
- signal?.throwIfAborted();
54
- const records = (await this.ctx.sessionQuery.listSessions(signal)).filter(record => !excluded?.has(record.header.id));
55
- const selected = new Set<string>(), warnings: string[] = [];
56
- // Expert records also name ACP members and sessions that dsh no longer stores; only real dsh sessions are readable.
57
- const stored = new Set<string>(records.map(record => record.header.id));
58
- try { for (const id of this.relatedSessions()) if (stored.has(id)) selected.add(id); } catch (error) { warnings.push("专家引用:" + String(error)); }
59
- if (location.sessionId && !excluded?.has(location.sessionId)) selected.add(location.sessionId);
60
- for (const record of records) {
61
- signal?.throwIfAborted();
62
- if ((record.header.origin !== "subagent" || !record.header.parentSession) && record.header.cwd &&
63
- await realpath(record.header.cwd).catch(() => record.header.cwd) === this.root) selected.add(record.header.id);
64
- }
65
- // Native subagents may use a different cwd while still belonging to a workspace's parent.
66
- for (let changed = true; changed;) {
67
- changed = false;
68
- for (const record of records) if (record.header.origin === "subagent" && record.header.parentSession && selected.has(record.header.parentSession) && !selected.has(record.header.id)) {
69
- selected.add(record.header.id); changed = true;
70
- }
71
- }
72
- const sessions: HistorySession[] = [];
73
- for (const id of selected) {
74
- signal?.throwIfAborted();
75
- try {
76
- using observation = await this.ctx.sessionQuery.observeSession(SessionId(id), { ...(signal ? { signal } : {}), projectionMode: "none" });
77
- const title = await this.ctx.sessionQuery.readTitle(SessionId(id), signal);
78
- const session = projectDshHistory(observation.header, observation.events, title?.title);
79
- if (session.branches.length) sessions.push(session);
80
- } catch (error) { signal?.throwIfAborted(); warnings.push(id + ": " + String(error)); }
81
- }
82
- return { sessions, warnings };
83
- }
84
- }
@@ -1,30 +0,0 @@
1
- import type { HistorySummarizer } from "../model/history.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
- }
14
-
15
- export function reduceHistorySummary(budget: number, ask: HistorySummarizer): HistorySummarizer {
16
- return async (request, signal) => {
17
- let text = request.prompt;
18
- while (text.length > budget) {
19
- const parts: string[] = [];
20
- for (const prompt of splitHistorySummary(text, budget)) {
21
- signal.throwIfAborted();
22
- parts.push(await ask({ ...request, prompt }, signal));
23
- }
24
- const smaller = parts.join("\n\n");
25
- if (smaller.length >= text.length) throw new Error("历史摘要未缩短,稍后重试。");
26
- text = smaller;
27
- }
28
- signal.throwIfAborted(); return ask({ ...request, prompt: text }, signal);
29
- };
30
- }
@@ -1,83 +0,0 @@
1
- import { realpath, stat } from "node:fs/promises";
2
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
- import { object } from "../../common/json.js";
4
- import { resourceRoot } from "../../common/paths.js";
5
- import { requireThat } from "../../common/validation.js";
6
- import type { HostEvent, PluginHostAdapter } from "../../model/plugin-host.js";
7
-
8
- const supportedEvents = ["SessionStart", "PreToolUse"];
9
-
10
- function workspaceFromPayload(cwd: string, payload?: unknown): string {
11
- if (object(payload) && Array.isArray(payload.workspacePaths)) {
12
- const first = payload.workspacePaths.find(value => typeof value === "string" && value.length > 0);
13
- if (typeof first === "string") return first;
14
- }
15
- return cwd;
16
- }
17
-
18
- function skillFromReadPath(targetPath: string, pluginRoot = process.env.PLUGIN_ROOT || resolve(resourceRoot, "..")): string | undefined {
19
- const skillsRoot = resolve(pluginRoot, "skills");
20
- const rel = relative(skillsRoot, resolve(targetPath));
21
- if (!rel || rel.startsWith("..") || isAbsolute(rel)) return undefined;
22
- const skill = rel.split(sep)[0];
23
- if (!skill || skill === "pbot") return undefined;
24
- return skill;
25
- }
26
-
27
- function isPreToolUse(payload: unknown): boolean {
28
- return object(payload) && payload.hookEventName === "PreToolUse";
29
- }
30
-
31
- export async function antigravityWorkspaceRoot(cwd: string, payload?: unknown): Promise<string> {
32
- const directory = workspaceFromPayload(cwd, payload);
33
- requireThat(isAbsolute(directory), "Antigravity 工作区需要绝对路径。");
34
- const root = await realpath(directory);
35
- requireThat((await stat(root)).isDirectory(), "Antigravity 工作区需要目录。");
36
- return root;
37
- }
38
-
39
- export const antigravityAdapter: PluginHostAdapter = {
40
- host: "antigravity",
41
- nativeRootAgents: true,
42
- nativeWorkspaceSkills: true,
43
- coordinatorPrompt: "plugin-coordinator.md",
44
- initCommandHint: "/pbot init",
45
- usage: "用法:node <插件目录>/lib/plugin.js antigravity init|status",
46
- resolveRoot(cwd, rawPayload) {
47
- return antigravityWorkspaceRoot(cwd, rawPayload);
48
- },
49
- parseEvent(value): HostEvent {
50
- requireThat(object(value) && typeof value.hookEventName === "string", "Antigravity hook 输入无效。");
51
- const event = value.hookEventName;
52
- requireThat(supportedEvents.includes(event), "Antigravity hook 事件未支持。");
53
- const cwd = typeof value.cwd === "string" && value.cwd ? value.cwd : workspaceFromPayload("", value);
54
- requireThat(cwd, "Antigravity hook 缺少工作目录。");
55
- if (event === "SessionStart") {
56
- return { kind: "inject-context", role: "coordinator", cwd, raw: value };
57
- }
58
- if (!object(value.toolCall) || typeof value.toolCall.name !== "string" || !object(value.toolCall.args)) {
59
- return { kind: "ignore" };
60
- }
61
- const { name, args } = value.toolCall;
62
- if (name === "read_file" && typeof args.Path === "string") {
63
- const skill = skillFromReadPath(args.Path);
64
- if (skill) return { kind: "check-skill", skill, cwd, raw: value };
65
- }
66
- return { kind: "ignore" };
67
- },
68
- formatPass(payload) {
69
- return isPreToolUse(payload) ? { decision: "allow" } : {};
70
- },
71
- formatContext(_event, context) {
72
- return {
73
- injectSteps: [
74
- { systemMessage: { systemMessage: context.text } },
75
- ],
76
- };
77
- },
78
- formatDeny(_event, reason) {
79
- return { decision: "deny", reason };
80
- },
81
- };
82
-
83
- export const antigravitySkillPath = (pluginRoot: string, skill: string) => join(pluginRoot, "skills", skill, "SKILL.md");
@@ -1,99 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import { parseSessionEntries, SessionManager, type ExtensionContext, type SessionEntry, type SessionMessageEntry } from "@earendil-works/pi-coding-agent";
3
- import type { HistoryExchange, HistoryLocation, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
4
- import { requireThat } from "../../common/validation.js";
5
- import { reduceHistorySummary } from "../history-summary.js";
6
-
7
- function text(content: unknown): string {
8
- if (typeof content === "string") return content;
9
- if (!Array.isArray(content)) return "";
10
- return content.flatMap(block => block.type === "text" ? [String(block.text)] : block.type === "image" ? ["[图片]"] : []).join("\n");
11
- }
12
- function exchanges(branch: SessionEntry[]) {
13
- const result: HistoryExchange[] = [], supersededEntryIds: string[] = [];
14
- let users: SessionMessageEntry[] = [], partial: SessionMessageEntry | undefined, observed: string[] = [];
15
- const finish = (answer?: SessionMessageEntry, completed = false) => {
16
- if (!users.length) return;
17
- const entries = [...users, ...(answer ? [answer] : [])];
18
- result.push({ entryIds: entries.map(entry => entry.id), from: users[0]!.timestamp, to: entries.at(-1)!.timestamp, completed,
19
- text: users.map(entry => "用户:\n" + text("content" in entry.message ? entry.message.content : "")).join("\n\n") +
20
- (answer && "content" in answer.message ? "\n\n助手:\n" + text(answer.message.content) : "") });
21
- supersededEntryIds.push(...observed.filter(id => id !== entries.at(-1)!.id));
22
- users = []; partial = undefined; observed = [];
23
- };
24
- for (const entry of branch) {
25
- if (entry.type !== "message") continue;
26
- const message = entry.message;
27
- if (message.role === "user") {
28
- if (partial?.message.role === "assistant" && ["aborted", "error"].includes(partial.message.stopReason)) finish(partial);
29
- if (!partial) observed.push(entry.id);
30
- users.push(entry);
31
- } else if (message.role === "assistant" && users.length) {
32
- partial = entry; observed.push(entry.id);
33
- if (message.stopReason === "stop" && !message.content.some(block => block.type === "toolCall")) finish(entry, true);
34
- }
35
- }
36
- finish(partial);
37
- return { exchanges: result, supersededEntryIds };
38
- }
39
-
40
- /** Parse in memory; never open a writable SessionManager or migrate native JSONL. */
41
- export function projectHistory(content: string): HistorySession {
42
- const parsed = parseSessionEntries(content), header = parsed[0];
43
- requireThat(header?.type === "session", "缺少 Pi 会话头。");
44
- const manager = SessionManager.inMemory(header.cwd, undefined, parsed), entries = manager.getEntries();
45
- const parents = new Set(entries.map(entry => entry.parentId));
46
- const tips = entries.filter(entry => !parents.has(entry.id));
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))] };
50
- }
51
-
52
- export const historyLocation = (ctx: ExtensionContext): HistoryLocation => {
53
- const file = ctx.sessionManager.getSessionFile();
54
- return { host: "pi", directory: ctx.sessionManager.getSessionDir(), ...(file ? { file } : {}) };
55
- };
56
- export class PiHistory implements HistorySource {
57
- readonly host = "pi";
58
- constructor(private readonly root: string, private readonly relatedFiles: () => string[] = () => []) {}
59
- async scan(location: HistoryLocation, signal?: AbortSignal, excluded?: ReadonlySet<string>) {
60
- requireThat(location.host === "pi", "Pi 历史只读取 Pi 原生会话。");
61
- const lists = await Promise.all([SessionManager.list(this.root, undefined, undefined, signal),
62
- SessionManager.list(this.root, location.directory, undefined, signal)]);
63
- const files = new Set([...this.relatedFiles(), ...(location.file ? [location.file] : [])]);
64
- for (const session of lists.flat()) {
65
- if (excluded?.has(session.id)) files.delete(session.path);
66
- else files.add(session.path);
67
- }
68
- const sessions: HistorySession[] = [], warnings: string[] = [];
69
- for (const file of files) {
70
- signal?.throwIfAborted();
71
- try {
72
- const session = projectHistory(await readFile(file, { encoding: "utf8", signal }));
73
- if (session.branches.length && !excluded?.has(session.sessionId)) sessions.push(session);
74
- } catch (error) {
75
- signal?.throwIfAborted();
76
- // Pi reserves a filename before the first message; copied archives may also outlive their native files.
77
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") warnings.push(`${file}: ${String(error)}`);
78
- }
79
- }
80
- return { sessions, warnings };
81
- }
82
- }
83
-
84
- export async function historySummarizer(ctx: ExtensionContext): Promise<HistorySummarizer> {
85
- const model = ctx.model;
86
- requireThat(model, "请先选择 Pi 模型。");
87
- const budget = Math.max(2000, Math.min(24000, Math.floor(model.contextWindow / 2)));
88
- const ask: HistorySummarizer = async ({ system, prompt, maxTokens }, signal) => {
89
- signal.throwIfAborted();
90
- const response = await ctx.modelRegistry.streamSimple(model, { systemPrompt: system,
91
- messages: [{ role: "user", content: prompt, timestamp: Date.now() }] }, { signal, reasoning: "low", maxTokens, transport: "sse" }).result();
92
- signal.throwIfAborted();
93
- requireThat(response.stopReason === "stop", response.errorMessage ?? "历史摘要未完成:" + response.stopReason);
94
- const answer = response.content.filter(part => part.type === "text").map(part => part.text).join("\n").trim();
95
- requireThat(answer, "历史摘要为空。");
96
- return answer;
97
- };
98
- return reduceHistorySummary(budget, ask);
99
- }
@@ -1,195 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { isDeepStrictEqual } from "node:util";
4
- import type { HistoryArchive, HistoryHost, HistoryIdentity, HistoryLocation, HistoryNode, HistoryRecord, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
5
- import type { HistoryFiles } from "../../storage/history-files.js";
6
- import { resourceRoot } from "../../common/paths.js";
7
- import { requireThat } from "../../common/validation.js";
8
- import { historySummaries, historyView, indexHistory, retainHistorySummaries } from "./history-index.js";
9
-
10
- export interface HistoryQuery { host?: HistoryHost; query?: string; sessionId?: string; from?: string; to?: string; offset?: number; limit?: number }
11
- type LocatedRecord = { host: HistoryHost; record: HistoryRecord };
12
- type HistoryReader = Pick<HistoryFiles, "host" | "list" | "warnings">;
13
- const page = <T>(values: T[], offset: number, limit: number) => ({ values: values.slice(offset, offset + limit),
14
- nextOffset: offset + limit < values.length ? offset + limit : null });
15
- const brief = ({ host, record }: LocatedRecord, node: HistoryNode) => ({ host, id: node.id, kind: node.kind, sessionId: record.sessionId,
16
- name: record.name, preview: node.text.replace(/\s+/g, " ").slice(0, 100), from: node.from, to: node.to, ready: node.ready, completed: node.completed });
17
- const view = ({ raw, summaries }: HistoryArchive): LocatedRecord => ({ host: raw.host, record: historyView(raw, summaries) });
18
- const summarySource = (node: HistoryNode) => [node.id, node.kind, node.level, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
19
-
20
- function nextSummary(archives: HistoryArchive[]) {
21
- for (const { raw, summaries } of archives) {
22
- if (summaries === null) continue;
23
- const record = historyView(raw, summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
24
- const node = record.nodes.find(node => node.kind === "summary" && !node.ready && node.children.every(id => lookup.get(id)!.ready));
25
- if (node) return { record, node, children: node.children.map(id => lookup.get(id)!) };
26
- }
27
- }
28
-
29
- /** Validate the exact target and ordered inputs under the source lock. Only publish the derived file. */
30
- export function commitHistorySummary(files: Pick<HistoryFiles, "control" | "list" | "saveSummaries">, identity: HistoryIdentity,
31
- expected: HistoryNode, children: readonly HistoryNode[], text: string, signal?: AbortSignal): HistoryRecord | undefined {
32
- return files.control(() => {
33
- signal?.throwIfAborted();
34
- const current = files.list().find(({ raw }) => raw.host === identity.host && raw.id === identity.id && raw.sessionId === identity.sessionId);
35
- if (!current || current.summaries === null) return;
36
- const record = historyView(current.raw, current.summaries), lookup = new Map(record.nodes.map(node => [node.id, node]));
37
- const node = lookup.get(expected.id);
38
- if (!node || node.kind !== "summary" || node.ready || !isDeepStrictEqual(summarySource(node), summarySource(expected)) ||
39
- !isDeepStrictEqual(node.children, children.map(child => child.id))) return;
40
- for (const child of children) {
41
- const input = lookup.get(child.id);
42
- if (!input?.ready || !isDeepStrictEqual(summarySource(input), summarySource(child))) return;
43
- }
44
- requireThat(text.trim(), "历史摘要为空。");
45
- node.text = text.trim(); node.ready = true;
46
- files.saveSummaries(current.raw, historySummaries(record));
47
- return record;
48
- });
49
- }
50
-
51
- export class HistoryService {
52
- #records: LocatedRecord[] = [];
53
- #closed = false;
54
- #loaded = false;
55
- #refresh: Promise<void> | undefined;
56
- #work: Promise<void> | undefined;
57
- readonly #controller = new AbortController();
58
- #sourceWarnings: string[] = [];
59
- #summaryError: string | undefined;
60
- constructor(readonly root: string, private readonly files: HistoryFiles, private readonly source: HistorySource,
61
- private readonly otherFiles: readonly HistoryReader[] = [],
62
- private readonly acpSessions?: () => { ids: Record<HistoryHost, ReadonlySet<string>>; warnings: string[] }) {
63
- requireThat((source.host === "pi" || source.host === "dsh") && source.host === files.host &&
64
- new Set([files.host, ...otherFiles.map(value => value.host)]).size === otherFiles.length + 1,
65
- "历史来源与归档目录不匹配。");
66
- }
67
- check() { requireThat(!this.#closed, "历史服务已关闭。"); }
68
- get warnings() { return [...new Set([...this.#sourceWarnings, ...this.files.warnings, ...this.otherFiles.flatMap(value => value.warnings),
69
- ...(this.#summaryError ? [this.files.host + " 摘要:" + this.#summaryError] : [])])]; }
70
- get status() { return { loaded: this.#loaded, organizing: Boolean(this.#work), pending: this.#loaded ? this.#records.filter(value => value.host === this.files.host)
71
- .reduce((total, value) => total + value.record.nodes.filter(node => node.kind === "summary" && !node.ready).length, 0) : null, warnings: this.warnings }; }
72
- refresh(location: HistoryLocation, signal?: AbortSignal): Promise<void> {
73
- this.check(); requireThat(location.host === this.source.host, "历史位置与来源不匹配。");
74
- // Each caller keeps its own cancellation. A closed page cannot cancel a server-owned refresh.
75
- const work = (this.#refresh ?? Promise.resolve()).catch(() => {}).then(() => this.load(location, signal));
76
- this.#refresh = work;
77
- return work.finally(() => { if (this.#refresh === work) this.#refresh = undefined; });
78
- }
79
- private async load(location: HistoryLocation, signal?: AbortSignal) {
80
- this.check(); signal?.throwIfAborted();
81
- const warnings: string[] = [], records: LocatedRecord[] = [];
82
- const warning = (host: HistoryHost, error: unknown) => { this.check(); signal?.throwIfAborted(); warnings.push(host + ": " + String(error)); };
83
- let known: HistoryArchive[] = [], sessions: HistorySession[] = [];
84
- try {
85
- try { this.files.migrate(this.root); } finally { known = this.files.list(this.root); }
86
- const scanned = await this.source.scan(location, signal, this.acpSessions?.().ids[this.files.host]); sessions = scanned.sessions;
87
- warnings.push(...scanned.warnings.map(value => this.files.host + ": " + value));
88
- } catch (error) { warning(this.files.host, error); }
89
- this.check(); signal?.throwIfAborted();
90
- // The worker binds the actual backend ID before delivery, possibly during the native scan.
91
- const excluded = this.acpSessions?.();
92
- if (excluded) {
93
- warnings.push(...excluded.warnings);
94
- sessions = sessions.filter(session => !excluded.ids[this.files.host].has(session.sessionId));
95
- }
96
- const visible = ({ raw }: HistoryArchive) => !excluded?.ids[raw.host].has(raw.sessionId);
97
- try {
98
- if (sessions.length) {
99
- const before = new Map(known.map(({ raw }) => [raw.sessionId, raw]));
100
- known = this.files.control(() => {
101
- this.check(); signal?.throwIfAborted();
102
- const current = new Map(this.files.list().map(archive => [archive.raw.sessionId, archive]));
103
- for (const session of sessions) {
104
- const previous = current.get(session.sessionId);
105
- // A damaged raw file may own this session; a damaged summary cannot own a root ID.
106
- if (!previous && this.files.rawWarnings.length) continue;
107
- if (!isDeepStrictEqual(before.get(session.sessionId), previous?.raw)) continue;
108
- const raw = indexHistory(session, previous?.raw, this.files.host);
109
- if (isDeepStrictEqual(raw, previous?.raw)) continue;
110
- let summaries = previous ? previous.summaries : [];
111
- if (previous && summaries?.length) {
112
- const retained = retainHistorySummaries(previous.raw, raw, summaries);
113
- // Invalidate first: even an interrupted two-file update cannot attach old text to a corrected exchange.
114
- if (!isDeepStrictEqual(summaries, retained)) this.files.saveSummaries(previous.raw, retained);
115
- summaries = retained;
116
- }
117
- this.files.saveRaw(raw);
118
- current.set(session.sessionId, { raw, summaries });
119
- }
120
- return [...current.values()];
121
- });
122
- }
123
- } catch (error) { warning(this.files.host, error); }
124
- records.push(...known.filter(visible).map(view));
125
- for (const files of this.otherFiles) {
126
- try { records.push(...files.list(this.root).filter(visible).map(view)); }
127
- catch (error) { warning(files.host, error); }
128
- }
129
- this.check(); signal?.throwIfAborted(); this.#records = records; this.#sourceWarnings = warnings; this.#loaded = true;
130
- }
131
- search({ host, query = "", sessionId, from, to, offset = 0, limit = 20 }: HistoryQuery = {}) {
132
- this.check();
133
- const needle = query.trim().toLowerCase(), after = from === undefined ? -Infinity : Date.parse(from), before = to === undefined ? Infinity : Date.parse(to);
134
- requireThat(!Number.isNaN(after) && !Number.isNaN(before) && after <= before, "时间范围无效,请使用 ISO 日期或时间。");
135
- const matches = this.#records.filter(value => (!host || value.host === host) && (!sessionId || value.record.sessionId === sessionId)).flatMap(value => value.record.nodes
136
- .filter(node => (needle ? node.kind !== "session" && node.ready && node.text.toLowerCase().includes(needle) : node.kind === "session") &&
137
- Date.parse(node.to) >= after && Date.parse(node.from) <= before)
138
- .map(node => {
139
- const start = Math.max(0, node.text.toLowerCase().indexOf(needle) - 80);
140
- return { ...brief(value, node), parents: node.parents, snippet: node.text.slice(start, start + 400) };
141
- })).sort((a, b) => b.to.localeCompare(a.to) || a.id.localeCompare(b.id));
142
- const result = page(matches, offset, limit);
143
- return { matches: result.values, total: matches.length, nextOffset: result.nextOffset, warnings: this.warnings };
144
- }
145
- private find(id: string, host?: HistoryHost) {
146
- const values = this.#records.filter(value => (!host || value.host === host) && value.record.nodes.some(node => node.id === id));
147
- requireThat(values.length, "历史节点不存在,请重新搜索。");
148
- requireThat(values.length === 1, "历史节点来源不明确,请指定 host。");
149
- const value = values[0]!, node = value.record.nodes.find(node => node.id === id)!;
150
- return { value, node };
151
- }
152
- read(id: string, offset = 0, limit = 12000, childrenOffset = 0, host?: HistoryHost) {
153
- this.check();
154
- const { value, node } = this.find(id, host), lookup = new Map(value.record.nodes.map(node => [node.id, node]));
155
- requireThat(offset <= node.text.length, "读取位置超出正文。");
156
- if (offset && /[\uDC00-\uDFFF]/.test(node.text[offset] ?? "")) offset--;
157
- let end = Math.min(node.text.length, offset + limit);
158
- if (end < node.text.length && /[\uD800-\uDBFF]/.test(node.text[end - 1] ?? "")) end += end - offset === 1 ? 1 : -1;
159
- const children = page(node.children, childrenOffset, 20);
160
- return { ...brief(value, node), text: node.text.slice(offset, end), totalLength: node.text.length,
161
- nextOffset: end < node.text.length ? end : null,
162
- parents: node.parents.map(id => brief(value, lookup.get(id)!)), children: children.values.map(id => brief(value, lookup.get(id)!)),
163
- nextChildrenOffset: children.nextOffset, source: { host: value.host, sessionId: value.record.sessionId, entryIds: node.entryIds }, warnings: this.warnings };
164
- }
165
- /** Retain exact inputs only for this call; model work never holds the source write lock. */
166
- organize(summarize: HistorySummarizer, signal: AbortSignal): Promise<void> {
167
- this.check();
168
- const active = AbortSignal.any([signal, this.#controller.signal]);
169
- const run = async () => {
170
- for (;;) {
171
- this.check(); active.throwIfAborted();
172
- const archives = this.files.list(), excluded = this.acpSessions?.().ids[this.files.host];
173
- const pending = nextSummary(archives.filter(({ raw }) => !excluded?.has(raw.sessionId)));
174
- if (!pending) return;
175
- const { record, node, children } = pending;
176
- const text = await summarize({ system: readFileSync(join(resourceRoot, "prompts/history-summary.md"), "utf8"), maxTokens: 2048,
177
- prompt: children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n") }, active);
178
- this.check(); active.throwIfAborted();
179
- const committed = commitHistorySummary(this.files, record, node, children, text, active);
180
- if (!committed) return;
181
- this.#records = this.#records.map(value => value.host === this.files.host && value.record.id === committed.id ? { host: value.host, record: committed } : value);
182
- }
183
- };
184
- const work = (this.#work ?? Promise.resolve()).catch(() => {}).then(run).then(() => { this.#summaryError = undefined; }).catch(error => {
185
- if (!active.aborted && !this.#closed) this.#summaryError = String(error);
186
- throw error;
187
- });
188
- this.#work = work;
189
- return work.finally(() => { if (this.#work === work) this.#work = undefined; });
190
- }
191
- async close() {
192
- this.#closed = true; this.#controller.abort();
193
- await Promise.allSettled([this.#work, this.#refresh]); this.#records = []; this.#loaded = false;
194
- }
195
- }
@@ -1,49 +0,0 @@
1
- import { readdirSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import type { HistoryHost } from "../model/history.js";
6
- import { readJsonFile } from "./atomic-json.js";
7
- import { acpReference } from "./acp-files.js";
8
- import { isHistoryHost } from "./history-format.js";
9
-
10
- function memberDirectory(home: string, host: "pi" | "dsh") {
11
- if (host === "pi" && home.startsWith("file://")) return join(fileURLToPath(home), "pbot/subagents");
12
- const tilde = home === "~" || home.startsWith("~/") || ((host === "dsh" || process.platform === "win32") && home.startsWith("~\\"));
13
- return join(tilde ? join(homedir(), home.slice(2)) : home, "pbot/subagents");
14
- }
15
-
16
- function defaultMcpWorkerDirectories(): string[] {
17
- const dirs = [join(homedir(), ".pbot/subagents")];
18
- if (process.env.PBOT_MCP_AGENT_DIR) dirs.push(process.env.PBOT_MCP_AGENT_DIR);
19
- if (process.env.PLUGIN_DATA) dirs.push(join(process.env.PLUGIN_DATA, "subagents"));
20
- return dirs;
21
- }
22
-
23
- /** Exclude ACP worker sessions owned by MCP or legacy Pi/dsh control directories from native history. */
24
- export function acpHistorySessions(directories: { pi?: string; dsh?: string; mcp?: string } = {}) {
25
- const ids: Record<HistoryHost, Set<string>> = { pi: new Set(), dsh: new Set(), claude: new Set() };
26
- const warnings: string[] = [];
27
- const warn = (path: string, error: unknown) => {
28
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") warnings.push(path + ": " + String(error));
29
- };
30
- const homes = { pi: process.env.PI_CODING_AGENT_DIR || "~/.pi/agent", dsh: process.env.DSH_HOME?.trim() ? process.env.DSH_HOME : "~/.dsh" };
31
- const scanDirs = new Set<string>([
32
- directories.pi ?? memberDirectory(homes.pi, "pi"),
33
- directories.dsh ?? memberDirectory(homes.dsh, "dsh"),
34
- ...(directories.mcp ? [directories.mcp] : defaultMcpWorkerDirectories()),
35
- ]);
36
- for (const directory of scanDirs) {
37
- try {
38
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
39
- if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
40
- const path = join(directory, entry.name);
41
- try {
42
- const ref = readJsonFile(path, "acp-session.json", acpReference);
43
- if (ref.sessionId !== null && isHistoryHost(ref.backend)) ids[ref.backend].add(ref.sessionId);
44
- } catch (error) { warn(path, error); }
45
- }
46
- } catch (error) { warn(directory, error); }
47
- }
48
- return { ids, warnings };
49
- }
@@ -1,19 +0,0 @@
1
- import { defineTool } from "@earendil-works/pi-coding-agent";
2
- import type { HistoryService } from "../../services/history/history-service.js";
3
- import type { CallAccess } from "../access.js";
4
- import { historyLocation } from "../../integrations/pi/history.js";
5
- import { markdownResult } from "../result.js";
6
- import { historyDescription, historyInput, historyParameters, historyResultSchema } from "./contract.js";
7
- import { executeHistory } from "./actions.js";
8
-
9
- export function historyTool(service: HistoryService, access: CallAccess) {
10
- return defineTool({ name: "pbot_history", label: "历史对话", description: historyDescription,
11
- parameters: historyParameters, outputSchema: historyResultSchema,
12
- async execute(_id, args, signal, _update, ctx) {
13
- access.check();
14
- const result = await executeHistory(service, historyInput(args), historyLocation(ctx), signal);
15
- access.check();
16
- return markdownResult(result, args.action === "search" ? "历史搜索" : "历史正文");
17
- },
18
- });
19
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes