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
@@ -59,8 +59,8 @@ const text = (content) => content.flatMap(block => block.type === "text" ? [bloc
59
59
  block.type === "file" ? ["[附件 " + (block.attachment.name ?? block.attachment.attachmentId) + "]"] : []).join("\n");
60
60
  /** Archive questions and the final/partial answer; raw tool records stay in the native log. */
61
61
  export function projectDshHistory(header, events, name = "") {
62
- const exchanges = [];
63
- let users = [], answer;
62
+ const exchanges = [], supersededEntryIds = [];
63
+ let users = [], answer, observed = [];
64
64
  const finish = (completed = false) => {
65
65
  if (users.length) {
66
66
  const entries = [...users, ...(answer ? [answer] : [])];
@@ -71,22 +71,30 @@ export function projectDshHistory(header, events, name = "") {
71
71
  text: users.map(event => (event.data.source.kind === "user" ? "用户:\n" : "协调者要求:\n") + text(event.data.content)).join("\n\n") +
72
72
  (body ? "\n\n助手:\n" + body : "") });
73
73
  }
74
+ const last = (answer ?? users.at(-1))?.seq;
75
+ supersededEntryIds.push(...observed.filter(id => id !== "dsh:" + last));
74
76
  users = [];
75
77
  answer = undefined;
78
+ observed = [];
76
79
  };
77
80
  for (const event of events) {
78
81
  if (event.type === "turn/start")
79
82
  finish();
80
- else if (event.type === "user/message" && ["user", "pbot-input"].includes(event.data.source.kind))
83
+ else if (event.type === "user/message" && ["user", "pbot-input"].includes(event.data.source.kind)) {
84
+ if (!answer)
85
+ observed.push("dsh:" + event.seq);
81
86
  users.push(event);
82
- else if (event.type === "assistant/message" && users.length)
87
+ }
88
+ else if (event.type === "assistant/message" && users.length) {
83
89
  answer = event;
90
+ observed.push("dsh:" + event.seq);
91
+ }
84
92
  else if (event.type === "turn/end")
85
93
  finish(event.data.reason.kind === "completed");
86
94
  }
87
95
  finish();
88
96
  return { sessionId: header.id, name: name || exchanges[0]?.text.replace(/\s+/g, " ").slice(0, 80) || "",
89
- branches: exchanges.length ? [exchanges] : [] };
97
+ branches: exchanges.length ? [exchanges] : [], supersededEntryIds };
90
98
  }
91
99
  export class DshHistory {
92
100
  ctx;
@@ -1,2 +1,4 @@
1
1
  import type { HistorySummarizer } from "../model/history.js";
2
+ /** Split Pi/dsh summary inputs within the model's character budget. */
3
+ export declare function splitHistorySummary(text: string, budget: number): string[];
2
4
  export declare function reduceHistorySummary(budget: number, ask: HistorySummarizer): HistorySummarizer;
@@ -1,21 +1,32 @@
1
- import { requireThat } from "../common/validation.js";
1
+ /** Split Pi/dsh summary inputs within the model's character budget. */
2
+ export function splitHistorySummary(text, budget) {
3
+ if (!Number.isInteger(budget) || budget < 2)
4
+ throw new Error("历史摘要分段预算无效。");
5
+ const parts = [];
6
+ for (let offset = 0; offset < text.length;) {
7
+ let end = Math.min(text.length, offset + budget);
8
+ if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]))
9
+ end--;
10
+ parts.push(text.slice(offset, end));
11
+ offset = end;
12
+ }
13
+ return parts;
14
+ }
2
15
  export function reduceHistorySummary(budget, ask) {
3
- return async (text, signal) => {
16
+ return async (request, signal) => {
17
+ let text = request.prompt;
4
18
  while (text.length > budget) {
5
19
  const parts = [];
6
- for (let offset = 0; offset < text.length;) {
20
+ for (const prompt of splitHistorySummary(text, budget)) {
7
21
  signal.throwIfAborted();
8
- let end = Math.min(text.length, offset + budget);
9
- if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]))
10
- end--;
11
- parts.push(await ask(text.slice(offset, end), signal));
12
- 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)
26
+ throw new Error("历史摘要未缩短,稍后重试。");
16
27
  text = smaller;
17
28
  }
18
29
  signal.throwIfAborted();
19
- return ask(text, signal);
30
+ return ask({ ...request, prompt: text }, signal);
20
31
  };
21
32
  }
@@ -36,8 +36,8 @@ export interface AgentDescriptor {
36
36
  export interface AgentSessionRef {
37
37
  file: string | null;
38
38
  }
39
- /** Native references are interpreted only by their owning host adapter. */
40
39
  export type NativeAgentHost = "pi" | "dsh";
40
+ /** Native references are interpreted only by their owning host adapter. */
41
41
  export type AgentSessionReference = {
42
42
  host: "pi";
43
43
  file: string | null;
@@ -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,9 +27,9 @@ export interface HistoryRecord {
25
27
  name: string;
26
28
  nodes: HistoryNode[];
27
29
  }
28
- export type HistoryHost = "pi" | "dsh";
30
+ export type HistoryHost = "pi" | "dsh" | "claude";
29
31
  export type HistoryLocation = {
30
- host?: "pi";
32
+ host: "pi";
31
33
  directory: string;
32
34
  file?: string;
33
35
  } | {
@@ -35,10 +37,15 @@ export type HistoryLocation = {
35
37
  sessionId?: string;
36
38
  };
37
39
  export interface HistorySource {
38
- readonly host: HistoryHost;
40
+ readonly host: HistoryLocation["host"];
39
41
  scan(location: HistoryLocation, signal?: AbortSignal): Promise<{
40
42
  sessions: HistorySession[];
41
43
  warnings: string[];
42
44
  }>;
43
45
  }
44
- export type HistorySummarizer = (text: string, signal: AbortSignal) => Promise<string>;
46
+ export interface HistorySummaryRequest {
47
+ system: string;
48
+ prompt: string;
49
+ maxTokens: number;
50
+ }
51
+ export type HistorySummarizer = (request: HistorySummaryRequest, signal: AbortSignal) => Promise<string>;
@@ -1,6 +1,6 @@
1
1
  import type { HistoryHost, HistoryLocation, HistoryNode, HistoryRecord, HistorySession, HistorySource, HistorySummarizer } from "../../model/history.js";
2
2
  import type { HistoryFiles } from "../../storage/history-files.js";
3
- /** Shared prefixes reuse nodes; only consecutive exchanges on one native branch can merge. */
3
+ /** Shared prefixes reuse nodes; a partial scan updates observed nodes and retains archived branches. */
4
4
  export declare function indexHistory(session: HistorySession, previous?: HistoryRecord, host?: HistoryHost): HistoryRecord;
5
5
  export interface HistoryQuery {
6
6
  host?: HistoryHost;
@@ -11,15 +11,16 @@ export interface HistoryQuery {
11
11
  offset?: number;
12
12
  limit?: number;
13
13
  }
14
- /** Validate the exact inputs again under the source lock; another writer's ready summary wins. */
15
- export declare function completeHistorySummary(record: HistoryRecord, id: string, children: HistoryNode[], text: string): boolean;
14
+ type HistoryReader = Pick<HistoryFiles, "host" | "list" | "warnings">;
15
+ /** Validate the exact target and ordered inputs again; another writer's ready summary wins. */
16
+ export declare function completeHistorySummary(record: HistoryRecord, expected: HistoryNode, children: readonly HistoryNode[], text: string): boolean;
16
17
  export declare class HistoryService {
17
18
  #private;
18
19
  readonly root: string;
19
20
  private readonly files;
20
21
  private readonly source;
21
- private readonly otherFiles?;
22
- constructor(root: string, files: HistoryFiles, source: HistorySource, otherFiles?: HistoryFiles | undefined);
22
+ private readonly otherFiles;
23
+ constructor(root: string, files: HistoryFiles, source: HistorySource, otherFiles?: readonly HistoryReader[]);
23
24
  check(): void;
24
25
  get warnings(): string[];
25
26
  get status(): {
@@ -96,7 +97,8 @@ export declare class HistoryService {
96
97
  ready: boolean;
97
98
  completed: boolean;
98
99
  };
99
- /** Only this source is organized. Model calls run outside the write lock. */
100
+ /** Retain exact inputs only for this call; model work never holds the source write lock. */
100
101
  organize(summarize: HistorySummarizer, signal: AbortSignal): Promise<void>;
101
102
  close(): Promise<void>;
102
103
  }
104
+ export {};
@@ -1,28 +1,55 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { resourceRoot } from "../../common/paths.js";
2
5
  import { requireThat } from "../../common/validation.js";
3
- /** Shared prefixes reuse nodes; only consecutive exchanges on one native branch can merge. */
6
+ const exchangeSource = (value) => [value.entryIds, value.text, value.from, value.to, value.completed];
7
+ /** Shared prefixes reuse nodes; a partial scan updates observed nodes and retains archived branches. */
4
8
  export function indexHistory(session, previous, host = previous?.host ?? "pi") {
5
- const id = previous?.id ?? (host === "dsh" ? "dsh-" : "") + randomUUID(), nodes = new Map();
6
- const old = new Map(previous?.nodes.map(node => [node.id, node])), changed = new Set();
9
+ requireThat(!previous || previous.host === host && previous.sessionId === session.sessionId, "历史会话与归档来源不匹配。");
10
+ const id = previous?.id ?? (host === "pi" ? "" : host + "-") + randomUUID();
11
+ const old = new Map(previous?.nodes.map(node => [node.id, node]));
12
+ const nodes = new Map(previous?.nodes.filter(node => node.kind !== "session").map(node => [node.id, {
13
+ ...node, entryIds: [...node.entryIds], children: [...node.children], parents: [],
14
+ }]));
15
+ const exchanges = session.branches.flat(), observedEnds = new Set(exchanges.map(value => value.entryIds.at(-1)));
16
+ const replaced = new Set(session.supersededEntryIds);
17
+ const superseded = new Set([...nodes.values()].filter(node => node.kind === "exchange" && !node.completed &&
18
+ !observedEnds.has(node.entryIds.at(-1)) && replaced.has(node.entryIds.at(-1)) &&
19
+ exchanges.some(exchange => node.entryIds.slice(0, -1).every(entry => exchange.entryIds.includes(entry)))).map(node => node.id));
20
+ // Native adapters identify replaced observations along the same branch/turn. Preserve
21
+ // terminal forks and interrupted exchanges, then rebuild summaries that used old partials.
22
+ for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
23
+ if (node.children.some(id => superseded.has(id)))
24
+ superseded.add(node.id);
25
+ }
26
+ for (const key of superseded)
27
+ nodes.delete(key);
28
+ const observed = new Set(), changed = new Set();
7
29
  const add = (value, level, children = []) => {
8
- const key = `${id}:${level}:${value.entryIds.at(-1)}`, found = nodes.get(key);
9
- if (found)
10
- return found;
11
- const before = old.get(key), same = before && JSON.stringify(before.children) === JSON.stringify(children) &&
12
- (level ? children.every(child => !changed.has(child)) : before.text === value.text && before.completed === value.completed);
13
- const node = { ...value, id: key, kind: level ? "summary" : "exchange", level, children, parents: [],
30
+ const key = `${id}:${level}:${value.entryIds.at(-1)}`;
31
+ if (observed.has(key))
32
+ return nodes.get(key);
33
+ const before = old.get(key);
34
+ if (!level && before && value.entryIds.length < before.entryIds.length &&
35
+ value.entryIds.every((entry, index) => entry === before.entryIds[before.entryIds.length - value.entryIds.length + index])) {
36
+ observed.add(key);
37
+ return nodes.get(key);
38
+ }
39
+ const same = before && JSON.stringify(before.children) === JSON.stringify(children) &&
40
+ JSON.stringify(exchangeSource({ ...before, text: level ? "" : before.text })) === JSON.stringify(exchangeSource(value));
41
+ const node = { ...value, entryIds: [...value.entryIds], id: key, kind: level ? "summary" : "exchange", level, children, parents: [],
14
42
  text: level ? same ? before.text : "" : value.text, ready: level ? Boolean(same && before.ready) : true };
15
43
  if (!same)
16
44
  changed.add(key);
45
+ observed.add(key);
17
46
  nodes.set(key, node);
18
47
  return node;
19
48
  };
20
- const roots = new Set();
21
49
  for (const branch of session.branches) {
22
50
  let layer = branch.map(exchange => add(exchange, 0)), level = 1;
23
51
  while (layer.length >= 4) {
24
52
  const count = Math.floor(layer.length / 4) * 4, next = [];
25
- layer.slice(count).forEach(node => roots.add(node.id));
26
53
  for (let i = 0; i < count; i += 4) {
27
54
  const children = layer.slice(i, i + 4), first = children[0], last = children.at(-1);
28
55
  next.push(add({ entryIds: [first.entryIds[0], last.entryIds.at(-1)], text: "", from: first.from, to: last.to,
@@ -31,12 +58,24 @@ export function indexHistory(session, previous, host = previous?.host ?? "pi") {
31
58
  layer = next;
32
59
  level++;
33
60
  }
34
- layer.forEach(node => roots.add(node.id));
61
+ }
62
+ // Retained summaries can also depend on an observed prefix. Invalidate all affected ancestors.
63
+ for (const node of [...nodes.values()].filter(node => node.kind === "summary").sort((a, b) => a.level - b.level)) {
64
+ const children = node.children.map(id => nodes.get(id)), first = children[0], last = children.at(-1);
65
+ const value = { entryIds: [first.entryIds[0], last.entryIds.at(-1)], from: first.from, to: last.to,
66
+ completed: children.every(child => child.completed) };
67
+ if (children.some(child => changed.has(child.id))) {
68
+ node.text = "";
69
+ node.ready = false;
70
+ changed.add(node.id);
71
+ }
72
+ Object.assign(node, value);
35
73
  }
36
74
  const dates = [...nodes.values()].flatMap(node => [node.from, node.to]).sort();
75
+ const nested = new Set([...nodes.values()].flatMap(node => node.children));
37
76
  nodes.set(id, { id, kind: "session", level: -1, entryIds: [], text: session.name, ready: true, completed: [...nodes.values()].every(node => node.completed),
38
77
  from: dates[0] ?? "", to: dates.at(-1) ?? "", parents: [],
39
- children: [...roots].sort((a, b) => nodes.get(a).from.localeCompare(nodes.get(b).from)) });
78
+ children: [...nodes.keys()].filter(key => !nested.has(key)).sort((a, b) => nodes.get(a).from.localeCompare(nodes.get(b).from)) });
40
79
  for (const node of nodes.values())
41
80
  for (const child of node.children)
42
81
  nodes.get(child).parents.push(node.id);
@@ -47,15 +86,17 @@ const page = (values, offset, limit) => ({ values: values.slice(offset, offset +
47
86
  const brief = ({ host, record }, node) => ({ host, id: node.id, kind: node.kind, sessionId: record.sessionId,
48
87
  name: record.name, preview: node.text.replace(/\s+/g, " ").slice(0, 100), from: node.from, to: node.to, ready: node.ready, completed: node.completed });
49
88
  const rawSource = (record) => record && JSON.stringify({ name: record.name,
50
- exchanges: record.nodes.filter(node => node.kind === "exchange").map(node => [node.id, node.entryIds, node.text, node.from, node.to, node.completed]) });
51
- const summarySource = (node) => [node.id, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
52
- /** Validate the exact inputs again under the source lock; another writer's ready summary wins. */
53
- export function completeHistorySummary(record, id, children, text) {
54
- const node = record.nodes.find(value => value.id === id);
55
- if (!node || node.kind !== "summary" || node.ready || JSON.stringify(node.children) !== JSON.stringify(children.map(child => child.id)))
89
+ nodes: record.nodes.map(node => [node.id, node.kind, node.level, node.entryIds, node.children,
90
+ node.kind === "summary" ? "" : node.text, node.from, node.to, node.completed]) });
91
+ const summarySource = (node) => [node.id, node.kind, node.level, node.entryIds, node.children, node.text, node.from, node.to, node.completed, node.ready];
92
+ /** Validate the exact target and ordered inputs again; another writer's ready summary wins. */
93
+ export function completeHistorySummary(record, expected, children, text) {
94
+ const node = record.nodes.find(value => value.id === expected.id);
95
+ if (!node || node.kind !== "summary" || node.ready || JSON.stringify(summarySource(node)) !== JSON.stringify(summarySource(expected)) ||
96
+ JSON.stringify(node.children) !== JSON.stringify(children.map(child => child.id)))
56
97
  return false;
57
98
  const current = node.children.map(id => record.nodes.find(value => value.id === id));
58
- if (current.some(value => !value) || JSON.stringify(current.map(value => summarySource(value))) !== JSON.stringify(children.map(summarySource)))
99
+ if (current.some(value => !value || !value.ready) || JSON.stringify(current.map(value => summarySource(value))) !== JSON.stringify(children.map(summarySource)))
59
100
  return false;
60
101
  requireThat(text.trim(), "历史摘要为空。");
61
102
  node.text = text.trim();
@@ -72,18 +113,20 @@ export class HistoryService {
72
113
  #loaded = false;
73
114
  #refresh;
74
115
  #work;
116
+ #controller = new AbortController();
75
117
  #sourceWarnings = [];
76
118
  #summaryError;
77
- constructor(root, files, source, otherFiles) {
119
+ constructor(root, files, source, otherFiles = []) {
78
120
  this.root = root;
79
121
  this.files = files;
80
122
  this.source = source;
81
123
  this.otherFiles = otherFiles;
82
- requireThat(source.host === files.host && (!otherFiles || otherFiles.host !== files.host), "历史来源与归档目录不匹配。");
124
+ requireThat((source.host === "pi" || source.host === "dsh") && source.host === files.host &&
125
+ new Set([files.host, ...otherFiles.map(value => value.host)]).size === otherFiles.length + 1, "历史来源与归档目录不匹配。");
83
126
  }
84
127
  check() { requireThat(!this.#closed, "历史服务已关闭。"); }
85
128
  get warnings() {
86
- return [...new Set([...this.#sourceWarnings, ...this.files.warnings, ...(this.otherFiles?.warnings ?? []),
129
+ return [...new Set([...this.#sourceWarnings, ...this.files.warnings, ...this.otherFiles.flatMap(value => value.warnings),
87
130
  ...(this.#summaryError ? [this.files.host + " 摘要:" + this.#summaryError] : [])])];
88
131
  }
89
132
  get status() {
@@ -92,6 +135,7 @@ export class HistoryService {
92
135
  }
93
136
  refresh(location, signal) {
94
137
  this.check();
138
+ requireThat(location.host === this.source.host, "历史位置与来源不匹配。");
95
139
  // Each caller keeps its own cancellation. A closed page cannot cancel a server-owned refresh.
96
140
  const work = (this.#refresh ?? Promise.resolve()).catch(() => { }).then(() => this.load(location, signal));
97
141
  this.#refresh = work;
@@ -151,18 +195,12 @@ export class HistoryService {
151
195
  warning(this.files.host, error);
152
196
  }
153
197
  records.push(...known.map(record => ({ host: record.host, record })));
154
- if (this.otherFiles) {
155
- try {
156
- this.otherFiles.migrate(this.root);
157
- }
158
- catch (error) {
159
- warning(this.otherFiles.host, error);
160
- }
198
+ for (const files of this.otherFiles) {
161
199
  try {
162
- records.push(...this.otherFiles.list().map(record => ({ host: record.host, record })));
200
+ records.push(...files.list(this.root).map(record => ({ host: record.host, record })));
163
201
  }
164
202
  catch (error) {
165
- warning(this.otherFiles.host, error);
203
+ warning(files.host, error);
166
204
  }
167
205
  }
168
206
  this.check();
@@ -207,33 +245,31 @@ export class HistoryService {
207
245
  parents: node.parents.map(id => brief(value, lookup.get(id))), children: children.values.map(id => brief(value, lookup.get(id))),
208
246
  nextChildrenOffset: children.nextOffset, source: { host: value.host, sessionId: value.record.sessionId, entryIds: node.entryIds }, warnings: this.warnings };
209
247
  }
210
- /** Only this source is organized. Model calls run outside the write lock. */
248
+ /** Retain exact inputs only for this call; model work never holds the source write lock. */
211
249
  organize(summarize, signal) {
212
250
  this.check();
251
+ const active = AbortSignal.any([signal, this.#controller.signal]);
213
252
  const run = async () => {
214
253
  for (;;) {
215
254
  this.check();
216
- signal.throwIfAborted();
217
- let pending;
218
- for (const record of this.files.list()) {
255
+ active.throwIfAborted();
256
+ const pending = this.files.list().flatMap(record => {
219
257
  const lookup = new Map(record.nodes.map(node => [node.id, node]));
220
258
  const node = [...record.nodes].sort((a, b) => a.level - b.level).find(node => node.kind === "summary" && !node.ready && node.children.every(id => lookup.get(id).ready));
221
- if (node) {
222
- pending = { record, node, children: node.children.map(id => lookup.get(id)) };
223
- break;
224
- }
225
- }
259
+ return node ? [{ record, node, children: node.children.map(id => lookup.get(id)) }] : [];
260
+ })[0];
226
261
  if (!pending)
227
262
  return;
228
263
  const { record, node, children } = pending;
229
- const text = await summarize(children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n"), signal);
264
+ const text = await summarize({ system: readFileSync(join(resourceRoot, "prompts/history-summary.md"), "utf8"), maxTokens: 2048,
265
+ prompt: children.map(child => `[${child.from} — ${child.to}${child.completed ? "" : ";未完成"}]\n${child.text}`).join("\n\n") }, active);
230
266
  this.check();
231
- signal.throwIfAborted();
267
+ active.throwIfAborted();
232
268
  const committed = this.files.control(() => {
233
269
  this.check();
234
- signal.throwIfAborted();
235
- const current = this.files.list().find(value => value.id === record.id);
236
- if (!current || !completeHistorySummary(current, node.id, children, text))
270
+ active.throwIfAborted();
271
+ const current = this.files.list().find(value => value.id === record.id && value.sessionId === record.sessionId);
272
+ if (!current || !completeHistorySummary(current, node, children, text))
237
273
  return;
238
274
  this.files.save(current);
239
275
  return current;
@@ -244,7 +280,7 @@ export class HistoryService {
244
280
  }
245
281
  };
246
282
  const work = (this.#work ?? Promise.resolve()).catch(() => { }).then(run).then(() => { this.#summaryError = undefined; }).catch(error => {
247
- if (!signal.aborted && !this.#closed)
283
+ if (!active.aborted && !this.#closed)
248
284
  this.#summaryError = String(error);
249
285
  throw error;
250
286
  });
@@ -252,5 +288,11 @@ export class HistoryService {
252
288
  return work.finally(() => { if (this.#work === work)
253
289
  this.#work = undefined; });
254
290
  }
255
- async close() { this.#closed = true; await Promise.allSettled([this.#work, this.#refresh]); this.#records = []; this.#loaded = false; }
291
+ async close() {
292
+ this.#closed = true;
293
+ this.#controller.abort();
294
+ await Promise.allSettled([this.#work, this.#refresh]);
295
+ this.#records = [];
296
+ this.#loaded = false;
297
+ }
256
298
  }
@@ -7,6 +7,12 @@ export declare class PythonEnvironmentService {
7
7
  directory?: string;
8
8
  error?: string;
9
9
  };
10
+ private run;
11
+ inspect(signal?: AbortSignal): Promise<{
12
+ state: "unprepared" | "preparing" | "ready" | "error";
13
+ directory?: string;
14
+ error?: string;
15
+ }>;
10
16
  setup(signal?: AbortSignal): Promise<{
11
17
  directory: string;
12
18
  python: string;
@@ -12,6 +12,29 @@ export class PythonEnvironmentService {
12
12
  this.root = root;
13
13
  }
14
14
  get status() { return { ...this.#status }; }
15
+ async run(checkOnly, signal) {
16
+ const environment = {};
17
+ for (const [key, value] of Object.entries(process.env))
18
+ if (value !== undefined)
19
+ environment[key] = value;
20
+ const result = await runCommand("/bin/sh", ["-c", 'exec "$(command -v python3 || command -v python)" "$@"',
21
+ "pbot-python", "-I", "-B", join(resourceRoot, "../scripts/setup-python.py"), ...(checkOnly ? ["--check"] : [])], undefined, this.root, environment, signal, { timeoutMs: 15 * 60_000 });
22
+ signal.throwIfAborted();
23
+ requireThat(result.success && object(result.data) && typeof result.data.directory === "string" && typeof result.data.python === "string", "共享 Python 环境未就绪;修复后执行 Python 准备入口。\n" + JSON.stringify(result.data).slice(-6000));
24
+ return { directory: result.data.directory, python: result.data.python, action: result.data.action };
25
+ }
26
+ async inspect(signal) {
27
+ const cancel = signal ? AbortSignal.any([this.#shutdown.signal, signal]) : this.#shutdown.signal;
28
+ try {
29
+ const result = await this.run(true, cancel);
30
+ this.#status = result.action === "verify" ? { state: "ready", directory: result.directory } : { state: "unprepared" };
31
+ return this.status;
32
+ }
33
+ catch (error) {
34
+ this.#status = { state: "error", error: error instanceof Error ? error.message : String(error) };
35
+ throw error;
36
+ }
37
+ }
15
38
  setup(signal) {
16
39
  const cancel = signal ? AbortSignal.any([this.#shutdown.signal, signal]) : this.#shutdown.signal;
17
40
  if (cancel.aborted)
@@ -21,15 +44,8 @@ export class PythonEnvironmentService {
21
44
  this.#status = { state: "preparing" };
22
45
  this.#pending = (async () => {
23
46
  try {
24
- const environment = {};
25
- for (const [key, value] of Object.entries(process.env))
26
- if (value !== undefined)
27
- environment[key] = value;
28
- const result = await runCommand("/bin/sh", ["-c", 'exec "$(command -v python3 || command -v python)" "$@"',
29
- "pbot-python", "-I", "-B", join(resourceRoot, "../scripts/setup-python.py")], undefined, this.root, environment, cancel, { timeoutMs: 15 * 60_000 });
30
- cancel.throwIfAborted();
31
- requireThat(result.success && object(result.data) && typeof result.data.directory === "string" && typeof result.data.python === "string", "共享 Python 环境未就绪;修复后执行 /pbot python setup。\n" + JSON.stringify(result.data).slice(-6000));
32
- const ready = { directory: result.data.directory, python: result.data.python };
47
+ const result = await this.run(false, cancel);
48
+ const ready = { directory: result.directory, python: result.python };
33
49
  this.#status = { state: "ready", directory: ready.directory };
34
50
  return ready;
35
51
  }
@@ -53,6 +53,7 @@ export class AgentFiles {
53
53
  constructor(root, host = "pi") {
54
54
  this.root = root;
55
55
  this.host = host;
56
+ requireThat(host === "pi" || host === "dsh", "子会话所属宿主无效。");
56
57
  }
57
58
  check() { if (this.#failure)
58
59
  throw this.#failure; }
@@ -84,6 +85,8 @@ export class AgentFiles {
84
85
  }
85
86
  create(value, run, acp) {
86
87
  this.check();
88
+ if (acp)
89
+ acpReference(acp);
87
90
  mkdirSync(this.root, { recursive: true, mode: 0o700 });
88
91
  mkdirSync(this.directory(value.agentId), { mode: 0o700 });
89
92
  for (const dir of ["inbox", "completions"])
@@ -5,7 +5,8 @@ export declare class HistoryFiles {
5
5
  readonly host: HistoryHost;
6
6
  constructor(directory: string, host?: HistoryHost);
7
7
  get warnings(): readonly string[];
8
- list(): HistoryRecord[];
8
+ /** A peer can include its legacy directory without migrating or modifying either source. */
9
+ list(legacyRoot?: string): HistoryRecord[];
9
10
  /** Publish each legacy archive with its directory's host before removing the old copy. */
10
11
  migrate(root: string): void;
11
12
  /** The callback is synchronous: no SDK reads or model work can hold this source's write lock. */
@@ -6,7 +6,7 @@ import { internalPath, readJsonFile, syncDirectory, writeJsonFile } from "./atom
6
6
  import { fileId } from "./file-access.js";
7
7
  const strings = (value) => Array.isArray(value) && value.every(item => typeof item === "string");
8
8
  function record(value) {
9
- requireThat(object(value) && (value.host === "pi" || value.host === "dsh") &&
9
+ requireThat(object(value) && (value.host === "pi" || value.host === "dsh" || value.host === "claude") &&
10
10
  typeof value.id === "string" && typeof value.sessionId === "string" &&
11
11
  typeof value.name === "string" && Array.isArray(value.nodes), "历史索引无效。");
12
12
  for (const node of value.nodes)
@@ -28,26 +28,37 @@ export class HistoryFiles {
28
28
  this.host = host;
29
29
  }
30
30
  get warnings() { return this.#warnings; }
31
- list() {
31
+ /** A peer can include its legacy directory without migrating or modifying either source. */
32
+ list(legacyRoot) {
32
33
  this.#warnings = [];
33
- if (!existsSync(this.directory))
34
- return [];
35
- const records = [];
36
- for (const name of readdirSync(this.directory).filter(name => name.endsWith(".json"))) {
37
- try {
38
- const value = readJsonFile(this.directory, name, record);
39
- requireThat(name === fileId(value.id) + ".json", "历史文件名与根 ID 不匹配。");
40
- if (value.host === this.host)
41
- records.push(value);
42
- }
43
- catch (error) {
44
- this.#warnings.push(join(this.directory, name) + ": " + String(error));
34
+ const records = new Map();
35
+ const directories = [this.directory, ...(legacyRoot && this.host !== "claude" ? [join(legacyRoot, "." + this.host, "pbot/history")] : [])];
36
+ for (const directory of directories) {
37
+ if (!existsSync(directory))
38
+ continue;
39
+ for (const name of readdirSync(directory).filter(name => name.endsWith(".json"))) {
40
+ try {
41
+ const value = readJsonFile(directory, name, value => {
42
+ if (directory === this.directory)
43
+ return record(value);
44
+ requireThat(object(value) && (value.host === undefined || value.host === this.host), "旧历史归档与来源目录不匹配。");
45
+ return record({ ...value, host: this.host });
46
+ });
47
+ requireThat(name === fileId(value.id) + ".json", "历史文件名与根 ID 不匹配。");
48
+ if (value.host === this.host && !records.has(value.id))
49
+ records.set(value.id, value);
50
+ }
51
+ catch (error) {
52
+ this.#warnings.push(join(directory, name) + ": " + String(error));
53
+ }
45
54
  }
46
55
  }
47
- return records;
56
+ return [...records.values()];
48
57
  }
49
58
  /** Publish each legacy archive with its directory's host before removing the old copy. */
50
59
  migrate(root) {
60
+ if (this.host !== "pi" && this.host !== "dsh")
61
+ return;
51
62
  const directory = join(root, "." + this.host, "pbot/history");
52
63
  if (!existsSync(directory))
53
64
  return;
@@ -1,6 +1,7 @@
1
1
  import { dshParameters, dshOutputSchema } from "../../integrations/dsh/schema.js";
2
2
  import { object, json } from "../../common/json.js";
3
- import { requireThat, schema } from "../../common/validation.js";
3
+ import { requireThat } from "../../common/validation.js";
4
+ import { schema } from "../../common/schema.js";
4
5
  import { markdownFields } from "../../common/markdown.js";
5
6
  import { executeAgent } from "./actions.js";
6
7
  import { agentDescription, agentResultSchema } from "./contract.js";