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
@@ -0,0 +1,89 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { requireThat } from "../../common/validation.js";
4
+ import type { HistoryMigrationConflict, HistoryMigrationItem, HistoryMigrationReport } from "../../model/history.js";
5
+ import { HistoryFiles, rawHistoryBucket, summaryArtifactBucket } from "../../storage/history-files.js";
6
+ import { readWorkspaceHistoryLayoutSync } from "../workspace/workspace-config.js";
7
+
8
+ export interface MigrateHistoryOptions {
9
+ dryRun?: boolean;
10
+ }
11
+
12
+ /** Read-only check for unmigrated flat history files when running under monthly layout. */
13
+ export function checkHistoryMigrationNotice(root: string): string | undefined {
14
+ const layout = readWorkspaceHistoryLayoutSync(root);
15
+ if (layout !== "monthly") return undefined;
16
+ const files = new HistoryFiles(join(root, ".pbot/history"), "pi", layout);
17
+ return files.detectFlatFiles().message;
18
+ }
19
+
20
+ /**
21
+ * Explicitly migrate flat .pbot/history/raw/*.json and .pbot/history/summaries/<dim>/*.json
22
+ * into UTC YYYY/MM/ (or unknown/) buckets. Moves files directly without keeping duplicates
23
+ * and never modifies .pbot/config.json or overwrites existing destinations.
24
+ */
25
+ export function migrateWorkspaceHistory(root: string, options: MigrateHistoryOptions = {}): HistoryMigrationReport {
26
+ const layout = readWorkspaceHistoryLayoutSync(root);
27
+ requireThat(
28
+ layout === "monthly",
29
+ '当前工作区配置为平铺布局(history.layout: "flat"),无需迁移到年月目录;如需迁移,请先在 .pbot/config.json 中将 history.layout 设为 "monthly" 或移除该配置项。',
30
+ );
31
+ const dryRun = Boolean(options.dryRun);
32
+ const files = new HistoryFiles(join(root, ".pbot/history"), "pi", "monthly");
33
+ const moved: HistoryMigrationItem[] = [];
34
+ const skipped: HistoryMigrationConflict[] = [];
35
+ const errors: { path: string; error: string }[] = [];
36
+
37
+ const run = () => {
38
+ for (const name of files.listFlatRawFiles()) {
39
+ const from = `raw/${name}`;
40
+ try {
41
+ const raw = files.readFlatRawFile(name);
42
+ const bucket = rawHistoryBucket(raw);
43
+ const to = `raw/${bucket}/${name}`;
44
+ if (dryRun) {
45
+ if (lstatSync(join(files.directory, to), { throwIfNoEntry: false })) {
46
+ skipped.push({ kind: "raw", from, to, reason: "目标路径已存在同名文件。" });
47
+ } else {
48
+ moved.push({ kind: "raw", id: raw.id, from, to });
49
+ }
50
+ } else {
51
+ const outcome = files.moveHistoryFile(from, to);
52
+ if (outcome === "moved") moved.push({ kind: "raw", id: raw.id, from, to });
53
+ else skipped.push({ kind: "raw", from, to, reason: "目标路径已存在同名文件。" });
54
+ }
55
+ } catch (error) {
56
+ errors.push({ path: join(files.directory, from), error: error instanceof Error ? error.message : String(error) });
57
+ }
58
+ }
59
+
60
+ for (const dimension of files.listDimensions()) {
61
+ for (const name of files.listFlatSummaryFiles(dimension)) {
62
+ const from = `summaries/${dimension}/${name}`;
63
+ try {
64
+ const artifact = files.readFlatSummaryFile(dimension, name);
65
+ const bucket = summaryArtifactBucket(artifact);
66
+ const to = `summaries/${dimension}/${bucket}/${name}`;
67
+ if (dryRun) {
68
+ if (lstatSync(join(files.directory, to), { throwIfNoEntry: false })) {
69
+ skipped.push({ kind: "summary", dimension, from, to, reason: "目标路径已存在同名文件。" });
70
+ } else {
71
+ moved.push({ kind: "summary", dimension, id: artifact.id, from, to });
72
+ }
73
+ } else {
74
+ const outcome = files.moveHistoryFile(from, to);
75
+ if (outcome === "moved") moved.push({ kind: "summary", dimension, id: artifact.id, from, to });
76
+ else skipped.push({ kind: "summary", dimension, from, to, reason: "目标路径已存在同名文件。" });
77
+ }
78
+ } catch (error) {
79
+ errors.push({ path: join(files.directory, from), error: error instanceof Error ? error.message : String(error) });
80
+ }
81
+ }
82
+ }
83
+ };
84
+
85
+ if (dryRun) run();
86
+ else files.controlMigration(run);
87
+
88
+ return { layout, dryRun, moved, skipped, errors };
89
+ }
@@ -0,0 +1,415 @@
1
+ import { join } from "node:path";
2
+ import { requireThat } from "../../common/validation.js";
3
+ import type { HistoryHost, HistoryQuery, RawHistory, SummaryArtifact } from "../../model/history.js";
4
+ import {
5
+ HistoryFiles,
6
+ historyBucketFromTimestamp,
7
+ rawHistoryBucket,
8
+ unknownHistoryBucket,
9
+ } from "../../storage/history-files.js";
10
+ import { readWorkspaceHistoryLayoutSync } from "../workspace/workspace-config.js";
11
+ import { orderedRawExchanges, rawSessionSpan, rawSessionTitle } from "./history-index.js";
12
+
13
+ const summaryIdPrefix = "summary:";
14
+
15
+ export interface HistoryNodeBrief {
16
+ host: HistoryHost;
17
+ id: string;
18
+ kind: "session" | "exchange" | "summary";
19
+ dimension?: string;
20
+ sessionId: string;
21
+ name: string;
22
+ preview: string;
23
+ from: string;
24
+ to: string;
25
+ ready: boolean;
26
+ completed: boolean;
27
+ }
28
+
29
+ export interface HistorySearchMatch extends HistoryNodeBrief {
30
+ parents: string[];
31
+ snippet: string;
32
+ }
33
+
34
+ export interface HistorySearchResult {
35
+ matches: HistorySearchMatch[];
36
+ total: number;
37
+ nextOffset: number | null;
38
+ warnings: string[];
39
+ }
40
+
41
+ export interface HistoryReadNode extends HistoryNodeBrief {
42
+ text: string;
43
+ totalLength: number;
44
+ nextOffset: number | null;
45
+ parents: HistoryNodeBrief[];
46
+ children: HistoryNodeBrief[];
47
+ nextChildrenOffset: number | null;
48
+ source: {
49
+ host: HistoryHost;
50
+ sessionId: string;
51
+ entryIds: string[];
52
+ dimension?: string;
53
+ };
54
+ warnings: string[];
55
+ }
56
+
57
+ const page = <T>(values: readonly T[], offset: number, limit: number) => ({
58
+ values: values.slice(offset, offset + limit),
59
+ nextOffset: offset + limit < values.length ? offset + limit : null,
60
+ });
61
+
62
+ const previewText = (text: string) => text.replace(/\s+/g, " ").trim().slice(0, 100);
63
+
64
+ export function summaryNodeId(dimension: string, artifactId: string): string {
65
+ return `${summaryIdPrefix}${dimension}:${artifactId}`;
66
+ }
67
+
68
+ export function parseSummaryNodeId(id: string): { dimension: string; artifactId: string } | undefined {
69
+ if (!id.startsWith(summaryIdPrefix)) return undefined;
70
+ const rest = id.slice(summaryIdPrefix.length);
71
+ const sep = rest.indexOf(":");
72
+ if (sep <= 0 || sep === rest.length - 1) return undefined;
73
+ return { dimension: rest.slice(0, sep), artifactId: rest.slice(sep + 1) };
74
+ }
75
+
76
+ function parseExchangeNodeId(id: string): { rawId: string } | undefined {
77
+ const index = id.indexOf(":0:");
78
+ if (index <= 0) return undefined;
79
+ return { rawId: id.slice(0, index) };
80
+ }
81
+
82
+ function sessionBrief(raw: RawHistory, summaryPreview?: string): HistoryNodeBrief {
83
+ const ordered = orderedRawExchanges(raw);
84
+ const span = rawSessionSpan(ordered);
85
+ const name = rawSessionTitle(raw);
86
+ return {
87
+ host: raw.host,
88
+ id: raw.id,
89
+ kind: "session",
90
+ sessionId: raw.sessionId,
91
+ name,
92
+ preview: summaryPreview ? previewText(summaryPreview) : previewText(name || ordered[0]?.text || ""),
93
+ from: span.from,
94
+ to: span.to,
95
+ ready: true,
96
+ completed: span.completed,
97
+ };
98
+ }
99
+
100
+ function exchangeBrief(raw: RawHistory, exchange: RawHistory["exchanges"][number], title: string): HistoryNodeBrief {
101
+ return {
102
+ host: raw.host,
103
+ id: exchange.id,
104
+ kind: "exchange",
105
+ sessionId: raw.sessionId,
106
+ name: title,
107
+ preview: previewText(exchange.text),
108
+ from: exchange.from,
109
+ to: exchange.to,
110
+ ready: true,
111
+ completed: exchange.completed,
112
+ };
113
+ }
114
+
115
+ function summaryBrief(artifact: SummaryArtifact): HistoryNodeBrief {
116
+ return {
117
+ host: artifact.host ?? "workspace",
118
+ id: summaryNodeId(artifact.dimension, artifact.id),
119
+ kind: "summary",
120
+ dimension: artifact.dimension,
121
+ sessionId: artifact.sessionId ?? artifact.id,
122
+ name: artifact.title,
123
+ preview: previewText(artifact.text),
124
+ from: artifact.from,
125
+ to: artifact.to,
126
+ ready: true,
127
+ completed: true,
128
+ };
129
+ }
130
+
131
+ function sliceSnippet(text: string, needle: string): string {
132
+ if (!needle) return text.slice(0, 400);
133
+ const start = Math.max(0, text.toLowerCase().indexOf(needle) - 80);
134
+ return text.slice(start, start + 400);
135
+ }
136
+
137
+ function inTimeRange(from: string, to: string, after: number, before: number): boolean {
138
+ const fromMs = from ? Date.parse(from) : NaN;
139
+ const toMs = to ? Date.parse(to) : NaN;
140
+ if (after !== -Infinity && !Number.isNaN(toMs) && toMs < after) return false;
141
+ if (before !== Infinity && !Number.isNaN(fromMs) && fromMs > before) return false;
142
+ return true;
143
+ }
144
+
145
+ /**
146
+ * Isolated, stateless read-only search over .pbot/history/raw/ and .pbot/history/summaries/<dimension>/.
147
+ * Uses ripgrep (with automatic Node fallback) to pre-filter candidate JSON files before parsing.
148
+ */
149
+ export function searchWorkspaceHistory(root: string, query: HistoryQuery = {}): HistorySearchResult {
150
+ const { host, sessionId, dimension, from, to, offset = 0, limit = 20 } = query;
151
+ const needle = (query.query ?? "").trim().toLowerCase();
152
+ const after = from === undefined ? -Infinity : Date.parse(from);
153
+ const before = to === undefined ? Infinity : Date.parse(to);
154
+ requireThat(!Number.isNaN(after) && !Number.isNaN(before) && after <= before, "时间范围无效,请使用 ISO 日期或时间。");
155
+
156
+ const layout = readWorkspaceHistoryLayoutSync(root);
157
+ const files = new HistoryFiles(join(root, ".pbot/history"), "pi", layout);
158
+ const warnings: string[] = [];
159
+ if (layout === "monthly") {
160
+ const flatNotice = files.detectFlatFiles().message;
161
+ if (flatNotice) warnings.push(flatNotice);
162
+ }
163
+ const matches: HistorySearchMatch[] = [];
164
+
165
+ if (!needle) {
166
+ // Empty query: list sessions (default / dimension="raw") or list summaries of a specific dimension.
167
+ if (dimension && dimension !== "raw") {
168
+ const summaries = files.listSummaries(dimension);
169
+ warnings.push(...files.warnings);
170
+ for (const artifact of summaries) {
171
+ if (host && artifact.host !== host) continue;
172
+ if (sessionId && artifact.sessionId !== sessionId) continue;
173
+ if (!inTimeRange(artifact.from, artifact.to, after, before)) continue;
174
+ const brief = summaryBrief(artifact);
175
+ matches.push({
176
+ ...brief,
177
+ parents: artifact.dimension === "monthly" ? [] : artifact.source.rawIds,
178
+ snippet: sliceSnippet(artifact.text, ""),
179
+ });
180
+ }
181
+ } else {
182
+ const raws = files.listRaw(host);
183
+ warnings.push(...files.warnings);
184
+ const sessionSummaries = new Map(files.listSummaries("session").map(item => [item.id, item]));
185
+ warnings.push(...files.warnings);
186
+ for (const raw of raws) {
187
+ if (sessionId && raw.sessionId !== sessionId) continue;
188
+ const summary = sessionSummaries.get(raw.id);
189
+ const brief = sessionBrief(raw, summary?.text);
190
+ if (!inTimeRange(brief.from, brief.to, after, before)) continue;
191
+ matches.push({
192
+ ...brief,
193
+ parents: [],
194
+ snippet: summary ? sliceSnippet(summary.text, "") : brief.preview,
195
+ });
196
+ }
197
+ }
198
+ } else {
199
+ // Keyword query: pre-filter candidate files via rg/fallback, then parse and match exact fields.
200
+ const searchRaw = !dimension || dimension === "raw";
201
+ const summaryDimensions = dimension === "raw"
202
+ ? []
203
+ : dimension
204
+ ? [dimension]
205
+ : files.listDimensions();
206
+
207
+ if (searchRaw) {
208
+ const candidateRaws = files.searchCandidateRaw(needle);
209
+ warnings.push(...files.warnings);
210
+ for (const raw of candidateRaws) {
211
+ if (host && raw.host !== host) continue;
212
+ if (sessionId && raw.sessionId !== sessionId) continue;
213
+ const ordered = orderedRawExchanges(raw);
214
+ const title = rawSessionTitle(raw);
215
+ for (const item of ordered) {
216
+ if (!item.text.toLowerCase().includes(needle)) continue;
217
+ if (!inTimeRange(item.from, item.to, after, before)) continue;
218
+ matches.push({
219
+ ...exchangeBrief(raw, item, title),
220
+ parents: [raw.id],
221
+ snippet: sliceSnippet(item.text, needle),
222
+ });
223
+ }
224
+ }
225
+ }
226
+
227
+ for (const dim of summaryDimensions) {
228
+ const candidateSummaries = files.searchCandidateSummaries(dim, needle);
229
+ warnings.push(...files.warnings);
230
+ for (const artifact of candidateSummaries) {
231
+ if (host && artifact.host !== host) continue;
232
+ if (sessionId && artifact.sessionId !== sessionId) continue;
233
+ const searchable = `${artifact.title}\n${artifact.text}`;
234
+ if (!searchable.toLowerCase().includes(needle)) continue;
235
+ if (!inTimeRange(artifact.from, artifact.to, after, before)) continue;
236
+ matches.push({
237
+ ...summaryBrief(artifact),
238
+ parents: artifact.dimension === "monthly" ? [] : artifact.source.rawIds,
239
+ snippet: sliceSnippet(artifact.text, needle),
240
+ });
241
+ }
242
+ }
243
+ }
244
+
245
+ matches.sort((a, b) => b.to.localeCompare(a.to) || a.id.localeCompare(b.id));
246
+ const paged = page(matches, offset, limit);
247
+ return {
248
+ matches: paged.values,
249
+ total: matches.length,
250
+ nextOffset: paged.nextOffset,
251
+ warnings: [...new Set(warnings)],
252
+ };
253
+ }
254
+
255
+ function sliceText(text: string, offset: number, limit: number) {
256
+ requireThat(offset <= text.length, "读取位置超出正文。");
257
+ let start = offset;
258
+ if (start && /[\uDC00-\uDFFF]/.test(text[start] ?? "")) start--;
259
+ let end = Math.min(text.length, start + limit);
260
+ if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1] ?? "")) end += end - start === 1 ? 1 : -1;
261
+ return {
262
+ text: text.slice(start, end),
263
+ totalLength: text.length,
264
+ nextOffset: end < text.length ? end : null,
265
+ };
266
+ }
267
+
268
+ function findMonthlyParent(files: HistoryFiles, bucket: string, rawId: string): HistoryNodeBrief | undefined {
269
+ if (files.layout !== "monthly" || bucket === unknownHistoryBucket) return undefined;
270
+ const monthly = files.readSummary("monthly", bucket.replace("/", "-"));
271
+ if (!monthly || !monthly.source.rawIds.includes(rawId)) return undefined;
272
+ return summaryBrief(monthly);
273
+ }
274
+
275
+ /** O(1) read of a session root, summary artifact, or individual raw exchange. */
276
+ export function readWorkspaceHistory(
277
+ root: string,
278
+ id: string,
279
+ offset = 0,
280
+ limit = 12000,
281
+ childrenOffset = 0,
282
+ host?: HistoryHost,
283
+ ): HistoryReadNode {
284
+ const layout = readWorkspaceHistoryLayoutSync(root);
285
+ const files = new HistoryFiles(join(root, ".pbot/history"), "pi", layout);
286
+ const baseWarnings: string[] = [];
287
+ if (layout === "monthly") {
288
+ const flatNotice = files.detectFlatFiles().message;
289
+ if (flatNotice) baseWarnings.push(flatNotice);
290
+ }
291
+
292
+ // 1. Summary artifact: summary:<dimension>:<artifactId>
293
+ const parsedSummary = parseSummaryNodeId(id);
294
+ if (parsedSummary) {
295
+ const artifact = files.readSummary(parsedSummary.dimension, parsedSummary.artifactId);
296
+ requireThat(artifact && (!host || artifact.host === host), "历史节点不存在,请重新搜索。");
297
+ const parents: HistoryNodeBrief[] = [];
298
+ const children: HistoryNodeBrief[] = [];
299
+
300
+ if (artifact.dimension === "monthly") {
301
+ // Monthly summary drills down to per-session summaries (falling back to raw session roots).
302
+ for (const rawId of artifact.source.rawIds) {
303
+ const sessionSummary = files.readSummary("session", rawId);
304
+ if (sessionSummary) {
305
+ children.push(summaryBrief(sessionSummary));
306
+ continue;
307
+ }
308
+ const raw = files.readRaw(rawId);
309
+ if (raw) children.push(sessionBrief(raw));
310
+ }
311
+ } else {
312
+ const wantedExchanges = new Set(artifact.source.exchangeIds);
313
+ for (const rawId of artifact.source.rawIds) {
314
+ const raw = files.readRaw(rawId);
315
+ if (!raw) continue;
316
+ parents.push(sessionBrief(raw, artifact.dimension === "session" ? artifact.text : undefined));
317
+ const ordered = orderedRawExchanges(raw);
318
+ const title = rawSessionTitle(raw);
319
+ for (const item of ordered) {
320
+ if (!wantedExchanges.size || wantedExchanges.has(item.id)) {
321
+ children.push(exchangeBrief(raw, item, title));
322
+ }
323
+ }
324
+ }
325
+ if (artifact.dimension === "session") {
326
+ const bucket = historyBucketFromTimestamp(artifact.from || artifact.to);
327
+ const monthlyParent = findMonthlyParent(files, bucket, artifact.id);
328
+ if (monthlyParent) parents.push(monthlyParent);
329
+ }
330
+ }
331
+
332
+ const pagedChildren = page(children, childrenOffset, 20);
333
+ const sliced = sliceText(artifact.text, offset, limit);
334
+ return {
335
+ ...summaryBrief(artifact),
336
+ ...sliced,
337
+ parents,
338
+ children: pagedChildren.values,
339
+ nextChildrenOffset: pagedChildren.nextOffset,
340
+ source: {
341
+ host: artifact.host ?? "workspace",
342
+ sessionId: artifact.sessionId ?? artifact.id,
343
+ entryIds: artifact.source.exchangeIds,
344
+ dimension: artifact.dimension,
345
+ },
346
+ warnings: [...new Set([...baseWarnings, ...files.warnings])],
347
+ };
348
+ }
349
+
350
+ // 2. Raw exchange: <rawId>:0:<end>
351
+ const parsedExchange = parseExchangeNodeId(id);
352
+ if (parsedExchange) {
353
+ const raw = files.readRaw(parsedExchange.rawId);
354
+ requireThat(raw && (!host || raw.host === host), "历史节点不存在,请重新搜索。");
355
+ const exchange = raw.exchanges.find(item => item.id === id);
356
+ requireThat(exchange, "历史节点不存在,请重新搜索。");
357
+ const title = rawSessionTitle(raw);
358
+ const parents: HistoryNodeBrief[] = [sessionBrief(raw)];
359
+ for (const dim of files.listDimensions()) {
360
+ if (dim === "monthly") continue;
361
+ const artifact = files.readSummary(dim, raw.id);
362
+ if (artifact) parents.push(summaryBrief(artifact));
363
+ }
364
+ const sliced = sliceText(exchange.text, offset, limit);
365
+ return {
366
+ ...exchangeBrief(raw, exchange, title),
367
+ ...sliced,
368
+ parents,
369
+ children: [],
370
+ nextChildrenOffset: null,
371
+ source: {
372
+ host: raw.host,
373
+ sessionId: raw.sessionId,
374
+ entryIds: exchange.entryIds,
375
+ },
376
+ warnings: [...new Set([...baseWarnings, ...files.warnings])],
377
+ };
378
+ }
379
+
380
+ // 3. Session root: <rawId>
381
+ const raw = files.readRaw(id);
382
+ requireThat(raw && (!host || raw.host === host), "历史节点不存在,请重新搜索。");
383
+ const ordered = orderedRawExchanges(raw);
384
+ const title = rawSessionTitle(raw);
385
+ const summaryChildren: HistoryNodeBrief[] = [];
386
+ let sessionSummaryText: string | undefined;
387
+ for (const dim of files.listDimensions()) {
388
+ if (dim === "monthly") continue;
389
+ const artifact = files.readSummary(dim, raw.id);
390
+ if (!artifact) continue;
391
+ if (dim === "session") sessionSummaryText = artifact.text;
392
+ summaryChildren.push(summaryBrief(artifact));
393
+ }
394
+ const monthlyParent = findMonthlyParent(files, rawHistoryBucket(raw), raw.id);
395
+ const allChildren: HistoryNodeBrief[] = [
396
+ ...summaryChildren,
397
+ ...ordered.map(item => exchangeBrief(raw, item, title)),
398
+ ];
399
+ const pagedChildren = page(allChildren, childrenOffset, 20);
400
+ const body = sessionSummaryText ? (title ? `${title}\n\n${sessionSummaryText}` : sessionSummaryText) : title;
401
+ const sliced = sliceText(body, offset, limit);
402
+ return {
403
+ ...sessionBrief(raw, sessionSummaryText),
404
+ ...sliced,
405
+ parents: monthlyParent ? [monthlyParent] : [],
406
+ children: pagedChildren.values,
407
+ nextChildrenOffset: pagedChildren.nextOffset,
408
+ source: {
409
+ host: raw.host,
410
+ sessionId: raw.sessionId,
411
+ entryIds: ordered.flatMap(item => item.entryIds),
412
+ },
413
+ warnings: [...new Set([...baseWarnings, ...files.warnings])],
414
+ };
415
+ }
@@ -0,0 +1,69 @@
1
+ import { object } from "../../common/json.js";
2
+ import { requireThat } from "../../common/validation.js";
3
+
4
+ export type ParsedHistoryCommand =
5
+ | { kind: "status" }
6
+ | { kind: "list" }
7
+ | { kind: "migrate"; dryRun: boolean }
8
+ | { kind: "summary"; dimensions?: string[]; force: boolean; backend?: string; model?: string; thinking?: string }
9
+ | { kind: "query"; input: Record<string, unknown> };
10
+
11
+ export const historyCommandUsage =
12
+ '用法:/pbot history summary [维度...] [--force] [--backend <acp>] [--model <model>] [--thinking <level>] | migrate [--dry-run] | status | list | {"action":"search"|"read",...}';
13
+
14
+ export function parseHistoryCommand(raw: string): ParsedHistoryCommand {
15
+ const trimmed = raw.trim();
16
+ if (!trimmed || trimmed === "status") return { kind: "status" };
17
+ if (trimmed === "list") return { kind: "list" };
18
+ if (trimmed.startsWith("{")) {
19
+ const parsed: unknown = JSON.parse(trimmed);
20
+ requireThat(object(parsed), "历史查询参数必须是 JSON 对象。");
21
+ return { kind: "query", input: parsed };
22
+ }
23
+ const tokens = trimmed.split(/\s+/);
24
+ const sub = tokens[0];
25
+ if (sub === "migrate") {
26
+ let dryRun = false;
27
+ for (const token of tokens.slice(1)) {
28
+ if (token === "--dry-run") dryRun = true;
29
+ else throw new Error(`未知参数:${token}\n${historyCommandUsage}`);
30
+ }
31
+ return { kind: "migrate", dryRun };
32
+ }
33
+ if (sub === "summary") {
34
+ let force = false;
35
+ let backend: string | undefined;
36
+ let model: string | undefined;
37
+ let thinking: string | undefined;
38
+ const dimensions: string[] = [];
39
+ const rest = tokens.slice(1);
40
+ for (let i = 0; i < rest.length; i++) {
41
+ const token = rest[i]!;
42
+ if (token === "--force" || token === "-f") {
43
+ force = true;
44
+ } else if (token === "--backend") {
45
+ backend = rest[++i];
46
+ requireThat(backend && !backend.startsWith("-"), "--backend 需要指定 ACP 后端名称(如 pi、dsh、claude)。");
47
+ } else if (token === "--model") {
48
+ model = rest[++i];
49
+ requireThat(model && !model.startsWith("-"), "--model 需要指定模型标识。");
50
+ } else if (token === "--thinking") {
51
+ thinking = rest[++i];
52
+ requireThat(thinking && !thinking.startsWith("-"), "--thinking 需要指定思考深度。");
53
+ } else if (token.startsWith("-")) {
54
+ throw new Error(`未知参数:${token}\n${historyCommandUsage}`);
55
+ } else {
56
+ dimensions.push(token);
57
+ }
58
+ }
59
+ return {
60
+ kind: "summary",
61
+ ...(dimensions.length ? { dimensions } : {}),
62
+ force,
63
+ ...(backend ? { backend } : {}),
64
+ ...(model ? { model } : {}),
65
+ ...(thinking ? { thinking } : {}),
66
+ };
67
+ }
68
+ throw new Error(historyCommandUsage);
69
+ }