personal-bot 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) 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 +45 -14
  5. package/README.zh-CN.md +45 -14
  6. package/bin/pbot-pi-acp.mjs +20 -0
  7. package/docs/README.md +6 -4
  8. package/docs/adr/0001-claude-skill-discovery.md +3 -0
  9. package/docs/adr/0002-claude-native-collaboration.md +3 -0
  10. package/docs/agent-collaboration.md +54 -6
  11. package/docs/architecture-guidelines.md +1 -1
  12. package/docs/capability-design.md +15 -3
  13. package/docs/claude-code-design.md +45 -0
  14. package/docs/claude-code.md +64 -0
  15. package/docs/dsh.md +12 -11
  16. package/docs/file-storage.md +26 -9
  17. package/docs/history.md +17 -9
  18. package/docs/interaction-design.md +11 -3
  19. package/docs/model-context.md +43 -12
  20. package/docs/model-instruction-guidelines.md +3 -3
  21. package/docs/release.md +13 -5
  22. package/docs/technical-design.md +59 -19
  23. package/docs/workspace-configuration.md +50 -23
  24. package/hooks/hooks.json +19 -0
  25. package/lib/claude.d.ts +1 -0
  26. package/lib/claude.js +20 -0
  27. package/lib/client.js +41 -8
  28. package/lib/dsh.js +2 -0
  29. package/lib/extension/acp-member.d.ts +16 -0
  30. package/lib/extension/acp-member.js +45 -0
  31. package/lib/extension/acp-worker.d.ts +1 -0
  32. package/lib/extension/acp-worker.js +159 -0
  33. package/lib/extension/claude-hooks.d.ts +15 -0
  34. package/lib/extension/claude-hooks.js +104 -0
  35. package/lib/extension/dsh/acp-member.d.ts +4 -0
  36. package/lib/extension/dsh/acp-member.js +48 -0
  37. package/lib/extension/dsh/command.js +11 -1
  38. package/lib/extension/dsh/history.js +1 -1
  39. package/lib/extension/dsh/management.js +3 -1
  40. package/lib/extension/dsh/workspace.d.ts +35 -1
  41. package/lib/extension/dsh/workspace.js +21 -3
  42. package/lib/integrations/acp/agents.d.ts +24 -0
  43. package/lib/integrations/acp/agents.js +168 -0
  44. package/lib/integrations/acp/claude.d.ts +18 -0
  45. package/lib/integrations/acp/claude.js +33 -0
  46. package/lib/integrations/acp/connection.d.ts +27 -0
  47. package/lib/integrations/acp/connection.js +167 -0
  48. package/lib/integrations/acp/input.d.ts +4 -0
  49. package/lib/integrations/acp/input.js +45 -0
  50. package/lib/integrations/acp/launch.d.ts +4 -0
  51. package/lib/integrations/acp/launch.js +52 -0
  52. package/lib/integrations/acp/model-selection.d.ts +12 -0
  53. package/lib/integrations/acp/model-selection.js +65 -0
  54. package/lib/integrations/agent-resources.d.ts +1 -1
  55. package/lib/integrations/agent-resources.js +3 -1
  56. package/lib/integrations/dsh/dsh-agents.d.ts +2 -1
  57. package/lib/integrations/dsh/dsh-agents.js +4 -0
  58. package/lib/integrations/dsh/history-summary.js +5 -9
  59. package/lib/integrations/dsh/history.js +13 -5
  60. package/lib/integrations/history-summary.d.ts +2 -0
  61. package/lib/integrations/history-summary.js +21 -10
  62. package/lib/model/acp.d.ts +59 -0
  63. package/lib/model/acp.js +1 -0
  64. package/lib/model/agent.d.ts +15 -1
  65. package/lib/model/history.d.ts +11 -4
  66. package/lib/model/workspace-config.d.ts +3 -0
  67. package/lib/services/agents/acp-run.d.ts +42 -0
  68. package/lib/services/agents/acp-run.js +149 -0
  69. package/lib/services/agents/agent-service.d.ts +114 -6
  70. package/lib/services/agents/agent-service.js +81 -10
  71. package/lib/services/agents/team-service.js +4 -2
  72. package/lib/services/history/history-service.d.ts +8 -6
  73. package/lib/services/history/history-service.js +90 -48
  74. package/lib/services/workspace/python-environment-service.d.ts +6 -0
  75. package/lib/services/workspace/python-environment-service.js +25 -9
  76. package/lib/services/workspace/workspace-config.js +12 -1
  77. package/lib/storage/acp-files.d.ts +9 -0
  78. package/lib/storage/acp-files.js +50 -0
  79. package/lib/storage/agent-files.d.ts +5 -4
  80. package/lib/storage/agent-files.js +14 -2
  81. package/lib/storage/history-files.d.ts +2 -1
  82. package/lib/storage/history-files.js +26 -15
  83. package/lib/tools/agents/actions.d.ts +16 -2
  84. package/lib/tools/agents/actions.js +3 -1
  85. package/lib/tools/agents/contract.d.ts +48 -3
  86. package/lib/tools/agents/contract.js +15 -9
  87. package/lib/tools/agents/dsh-contract.d.ts +8 -15
  88. package/lib/tools/agents/dsh-contract.js +12 -8
  89. package/lib/tools/history/contract.d.ts +7 -7
  90. package/lib/tools/history/contract.js +2 -2
  91. package/lib/ui/dsh/management.js +37 -9
  92. package/npm-shrinkwrap.json +975 -51
  93. package/package.json +40 -29
  94. package/python/README.md +17 -14
  95. package/resources/agents/coordinator.md +1 -1
  96. package/resources/claude/agents/general-purpose.md +12 -0
  97. package/resources/claude/skills/pbot/SKILL.md +17 -0
  98. package/resources/prompts/claude-coordinator.md +1 -0
  99. package/resources/prompts/native-coordinator.md +1 -0
  100. package/resources/prompts/workspace.md +2 -2
  101. package/resources/references/compute.md +2 -2
  102. package/resources/references/task-conductor.md +3 -2
  103. package/resources/skills/.claude-plugin/plugin.json +4 -0
  104. package/resources/skills/provider-connections/SKILL.md +17 -1
  105. package/scripts/README.md +29 -5
  106. package/src/claude.ts +19 -0
  107. package/src/dsh.ts +1 -0
  108. package/src/extension/acp-member.ts +44 -0
  109. package/src/extension/acp-worker.ts +124 -0
  110. package/src/extension/agent-events.ts +28 -3
  111. package/src/extension/agents-command.ts +33 -5
  112. package/src/extension/claude-hooks.ts +94 -0
  113. package/src/extension/dsh/acp-member.ts +44 -0
  114. package/src/extension/dsh/command.ts +10 -1
  115. package/src/extension/dsh/history.ts +1 -1
  116. package/src/extension/dsh/management.ts +2 -1
  117. package/src/extension/dsh/workspace.ts +21 -3
  118. package/src/extension/lifecycle.ts +2 -2
  119. package/src/extension/pi-acp-member.ts +64 -0
  120. package/src/integrations/acp/agents.ts +118 -0
  121. package/src/integrations/acp/claude.ts +40 -0
  122. package/src/integrations/acp/connection.ts +152 -0
  123. package/src/integrations/acp/input.ts +39 -0
  124. package/src/integrations/acp/launch.ts +50 -0
  125. package/src/integrations/acp/model-selection.ts +66 -0
  126. package/src/integrations/agent-resources.ts +2 -1
  127. package/src/integrations/dsh/dsh-agents.ts +4 -1
  128. package/src/integrations/dsh/history-summary.ts +5 -9
  129. package/src/integrations/dsh/history.ts +12 -6
  130. package/src/integrations/history-summary.ts +18 -8
  131. package/src/integrations/pi/history.ts +16 -15
  132. package/src/integrations/pi/pi-agents.ts +4 -1
  133. package/src/model/acp.ts +26 -0
  134. package/src/model/agent.ts +7 -1
  135. package/src/model/history.ts +12 -4
  136. package/src/model/workspace-config.ts +4 -0
  137. package/src/pbot.ts +5 -4
  138. package/src/services/agents/acp-run.ts +123 -0
  139. package/src/services/agents/agent-service.ts +85 -12
  140. package/src/services/agents/team-service.ts +3 -2
  141. package/src/services/history/history-service.ts +82 -41
  142. package/src/services/workspace/python-environment-service.ts +26 -9
  143. package/src/services/workspace/workspace-config.ts +10 -1
  144. package/src/storage/acp-files.ts +50 -0
  145. package/src/storage/agent-files.ts +15 -4
  146. package/src/storage/history-files.ts +20 -11
  147. package/src/tools/agents/actions.ts +4 -2
  148. package/src/tools/agents/contract.ts +16 -9
  149. package/src/tools/agents/dsh-contract.ts +12 -8
  150. package/src/tools/history/contract.ts +2 -2
  151. package/src/ui/dsh/management.ts +32 -9
@@ -1,10 +1,13 @@
1
1
  import { AgentFiles } from "../../storage/agent-files.js";
2
2
  import { TeamFiles } from "../../storage/team-files.js";
3
3
  import type { TeamAgent, TeamInput } from "../../model/team.js";
4
- import type { AgentOwner, AgentOptions, AgentDescriptor, AgentCycle, AgentCompletion, AgentSessionReference } from "../../model/agent.js";
4
+ import type { AgentOwner, AgentOptions, AgentStartOptions, AgentDescriptor, AgentCycle, AgentCompletion, AgentSessionReference, NativeAgentHost } from "../../model/agent.js";
5
+ import type { AcpBackend, AcpSessionReference } from "../../model/acp.js";
5
6
  export interface AgentHost {
6
- readonly kind: AgentSessionReference["host"];
7
- available(): void;
7
+ readonly kind: NativeAgentHost;
8
+ available(backend?: AcpBackend): void;
9
+ prepare?(backend: AcpBackend, options: AgentOptions): AcpSessionReference;
10
+ validateOptions?(options: AgentOptions, backend?: AcpBackend): void;
8
11
  alive(id: string): boolean;
9
12
  validateSession(value: AgentDescriptor, reference: AgentSessionReference): void | Promise<void>;
10
13
  launch(value: AgentDescriptor, directory: string, generation: string, reference: AgentSessionReference, resume: boolean, signal: AbortSignal): void | Promise<void>;
@@ -25,13 +28,22 @@ export declare class AgentService {
25
28
  private records;
26
29
  list(owner: AgentOwner): TeamAgent[];
27
30
  private view;
28
- start(options: AgentOptions, owner: AgentOwner): Promise<{
31
+ start(input: AgentStartOptions, owner: AgentOwner): Promise<{
29
32
  requestId?: string;
30
33
  messageStatus?: "queued";
31
34
  name: string;
32
35
  generation: string;
33
36
  state: import("../../model/agent.js").AgentStatus["state"];
34
37
  activity: string;
38
+ backend?: AcpBackend;
39
+ transport?: "native" | "acp";
40
+ selection?: import("../../model/acp.js").AcpModelSelection;
41
+ capabilities?: {
42
+ steer: boolean;
43
+ resume: boolean;
44
+ team: boolean;
45
+ transcript: boolean;
46
+ };
35
47
  cycle?: AgentCycle;
36
48
  error?: string;
37
49
  owned: boolean;
@@ -46,13 +58,22 @@ export declare class AgentService {
46
58
  alive: boolean;
47
59
  }>;
48
60
  private launch;
49
- send(id: string, text: string, delivery: "steer" | "followUp", owner: AgentOwner): {
61
+ send(id: string, text: string, delivery: "steer" | "followUp", owner: AgentOwner, attachments?: readonly string[]): {
50
62
  requestId: string;
51
63
  messageStatus: "queued";
52
64
  name: string;
53
65
  generation: string;
54
66
  state: import("../../model/agent.js").AgentStatus["state"];
55
67
  activity: string;
68
+ backend?: AcpBackend;
69
+ transport?: "native" | "acp";
70
+ selection?: import("../../model/acp.js").AcpModelSelection;
71
+ capabilities?: {
72
+ steer: boolean;
73
+ resume: boolean;
74
+ team: boolean;
75
+ transcript: boolean;
76
+ };
56
77
  cycle?: AgentCycle;
57
78
  error?: string;
58
79
  owned: boolean;
@@ -74,6 +95,15 @@ export declare class AgentService {
74
95
  generation: string;
75
96
  state: import("../../model/agent.js").AgentStatus["state"];
76
97
  activity: string;
98
+ backend?: AcpBackend;
99
+ transport?: "native" | "acp";
100
+ selection?: import("../../model/acp.js").AcpModelSelection;
101
+ capabilities?: {
102
+ steer: boolean;
103
+ resume: boolean;
104
+ team: boolean;
105
+ transcript: boolean;
106
+ };
77
107
  cycle?: AgentCycle;
78
108
  error?: string;
79
109
  owned: boolean;
@@ -98,6 +128,15 @@ export declare class AgentService {
98
128
  generation: string;
99
129
  state: import("../../model/agent.js").AgentStatus["state"];
100
130
  activity: string;
131
+ backend?: AcpBackend;
132
+ transport?: "native" | "acp";
133
+ selection?: import("../../model/acp.js").AcpModelSelection;
134
+ capabilities?: {
135
+ steer: boolean;
136
+ resume: boolean;
137
+ team: boolean;
138
+ transcript: boolean;
139
+ };
101
140
  cycle?: AgentCycle;
102
141
  error?: string;
103
142
  owned: boolean;
@@ -119,6 +158,15 @@ export declare class AgentService {
119
158
  generation: string;
120
159
  state: import("../../model/agent.js").AgentStatus["state"];
121
160
  activity: string;
161
+ backend?: AcpBackend;
162
+ transport?: "native" | "acp";
163
+ selection?: import("../../model/acp.js").AcpModelSelection;
164
+ capabilities?: {
165
+ steer: boolean;
166
+ resume: boolean;
167
+ team: boolean;
168
+ transcript: boolean;
169
+ };
122
170
  error?: string;
123
171
  owned: boolean;
124
172
  agentId: string;
@@ -134,7 +182,7 @@ export declare class AgentService {
134
182
  read(id: string, owner: AgentOwner, cycleId?: string, offset?: number, limit?: number): Promise<{
135
183
  cycles: {
136
184
  cycleId: string;
137
- state: "running" | "completed" | "failed" | "cancelled" | "interrupted";
185
+ state: "completed" | "failed" | "cancelled" | "running" | "interrupted";
138
186
  }[];
139
187
  report: string;
140
188
  totalLength: number;
@@ -144,6 +192,15 @@ export declare class AgentService {
144
192
  generation: string;
145
193
  state: import("../../model/agent.js").AgentStatus["state"];
146
194
  activity: string;
195
+ backend?: AcpBackend;
196
+ transport?: "native" | "acp";
197
+ selection?: import("../../model/acp.js").AcpModelSelection;
198
+ capabilities?: {
199
+ steer: boolean;
200
+ resume: boolean;
201
+ team: boolean;
202
+ transcript: boolean;
203
+ };
147
204
  error?: string;
148
205
  owned: boolean;
149
206
  agentId: string;
@@ -158,6 +215,57 @@ export declare class AgentService {
158
215
  }>;
159
216
  completions(owner: AgentOwner): Promise<AgentCompletion[]>;
160
217
  private report;
218
+ recordPage(id: string, owner: AgentOwner, options?: {
219
+ seq?: number;
220
+ offset?: number;
221
+ limit?: number;
222
+ textOffset?: number;
223
+ textLimit?: number;
224
+ format?: string;
225
+ }): Promise<{
226
+ kind: string;
227
+ agent: TeamAgent;
228
+ cursor: string;
229
+ seq: number;
230
+ offset: number;
231
+ text: string;
232
+ totalLength: number;
233
+ nextOffset: number | null;
234
+ total?: never;
235
+ records?: never;
236
+ } | {
237
+ kind: string;
238
+ agent: TeamAgent;
239
+ cursor: string;
240
+ total: number;
241
+ offset: number;
242
+ nextOffset: number | null;
243
+ records: {
244
+ preview: string;
245
+ seq: number;
246
+ type: string;
247
+ time: number;
248
+ requestId?: string;
249
+ cycleId?: string;
250
+ state: string;
251
+ }[];
252
+ seq?: never;
253
+ text?: never;
254
+ totalLength?: never;
255
+ }>;
256
+ pendingPermissions(owner: AgentOwner): {
257
+ agentId: string;
258
+ name: string;
259
+ generation: string;
260
+ requestId: string;
261
+ description: string;
262
+ options: {
263
+ optionId: string;
264
+ name: string;
265
+ kind: string;
266
+ }[];
267
+ }[];
268
+ answerPermission(id: string, requestId: string, optionId: string | null, owner: AgentOwner): void;
161
269
  private release;
162
270
  /** Called by the parent scanner; stop remains nonblocking to the model. */
163
271
  refresh(owner: AgentOwner): Promise<void>;
@@ -1,10 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { realpathSync } from "node:fs";
2
+ import { realpathSync, readdirSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
4
  import { packageVersion, releaseLine } from "../../common/version.js";
5
5
  import { requireThat } from "../../common/validation.js";
6
6
  import { AgentFiles, descriptor, launch, status, cycle } from "../../storage/agent-files.js";
7
7
  import { TeamFiles } from "../../storage/team-files.js";
8
+ import { acpModelState, acpPermission, acpPermissionReply, acpReference } from "../../storage/acp-files.js";
8
9
  export class AgentService {
9
10
  root;
10
11
  host;
@@ -46,16 +47,28 @@ export class AgentService {
46
47
  const current = saved?.generation === run.generation ? saved : undefined;
47
48
  const alive = this.alive(d.agentId), pending = this.#starting.get(d.agentId);
48
49
  const starting = pending && !pending.controller.signal.aborted;
50
+ const reference = this.files.optional(d.agentId, "acp-session.json", acpReference);
51
+ const model = reference ? this.files.optional(d.agentId, "acp-model.json", acpModelState) : undefined;
52
+ const selection = model?.generation === run.generation ? { ...(model.provider ? { provider: model.provider } : {}),
53
+ ...(model.model ? { model: model.model } : {}), ...(model.resolvedModel ? { resolvedModel: model.resolvedModel } : {}),
54
+ ...(model.thinking ? { thinking: model.thinking } : {}) } : undefined;
49
55
  return { ...d, name: run.name, generation: run.generation, owned: this.owned(d, owner), alive,
56
+ ...(reference?.host === "acp" ? { backend: reference.backend, transport: "acp",
57
+ capabilities: { steer: false, resume: Boolean(reference.capabilities?.resume || reference.capabilities?.load), team: false, transcript: false },
58
+ ...(selection ? { selection } : {}) } : {}),
50
59
  state: alive ? starting ? "starting" : run.stop || pending?.controller.signal.aborted ? "stopping" : current?.state ?? "starting" : current?.state === "error" ? "error" : "stopped",
51
60
  activity: starting ? "启动" : alive ? current?.activity ?? "启动" : current?.error ?? "已停止",
52
61
  ...(current?.cycle ? { cycle: current.cycle } : {}), ...(current?.error ? { error: current.error } : {}) };
53
62
  }
54
- async start(options, owner) {
63
+ async start(input, owner) {
55
64
  this.check();
56
- this.host.available();
57
- options = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== undefined));
58
- requireThat(options.provider && options.model, "请选择可在专家会话使用的模型。");
65
+ const { backend, ...supplied } = input;
66
+ this.host.available(backend);
67
+ const options = Object.fromEntries(Object.entries(supplied).filter(([, v]) => v !== undefined));
68
+ this.host.validateOptions?.(options, backend);
69
+ requireThat(backend || options.provider && options.model, "请选择可在专家会话使用的模型。");
70
+ const reference = backend ? this.host.prepare?.(backend, options) : undefined;
71
+ requireThat(!backend || reference, "当前执行接入不支持 ACP 后端。");
59
72
  const prepared = this.files.control(() => {
60
73
  requireThat(this.list(owner).filter(v => v.alive).length < 50, "最多 50 个存活或启动中子会话;请先停止一个空闲会话。");
61
74
  const agentId = randomUUID();
@@ -64,7 +77,7 @@ export class AgentService {
64
77
  const d = { agentId, release: packageVersion, workspace: this.root, cwd,
65
78
  parentSessionId: owner.sessionId, parentLeaf: owner.leaf, createdAt: Date.now(), options: { ...options, files, cwd } };
66
79
  const run = { generation: randomUUID(), name: options.name ?? agentId.slice(0, 8), sequence: 0, stop: false, startedAt: Date.now() };
67
- this.files.create(d, run);
80
+ this.files.create(d, run, reference);
68
81
  const initial = [options.message, ...(options.prompts ?? [])].filter(Boolean).join("\n\n");
69
82
  const request = initial || files.length ? this.files.enqueue(agentId, initial, "steer", files) : undefined;
70
83
  this.#starting.set(agentId, { generation: run.generation, controller: new AbortController(), stage: "launch" });
@@ -107,12 +120,15 @@ export class AgentService {
107
120
  this.#launches.delete(operation);
108
121
  }
109
122
  }
110
- send(id, text, delivery, owner) {
123
+ send(id, text, delivery, owner, attachments = []) {
111
124
  const d = this.get(id, owner);
112
125
  return this.files.control(() => {
113
126
  requireThat(this.alive(id) && this.#starting.get(id)?.stage !== "validate" && !this.files.read(id, "launch.json", launch).stop, "子会话已停止或仍在恢复校验,请等待显式恢复完成。");
114
127
  this.assertPrivate(id);
115
- const request = this.files.enqueue(id, text, delivery);
128
+ const view = this.view(d, owner);
129
+ requireThat(!(view.transport === "acp" && delivery === "steer" && view.state !== "idle"), "该子代理运行中不支持 steer;请用 delivery: followUp 排队。");
130
+ const files = attachments.map(path => realpathSync(resolve(this.root, path)));
131
+ const request = this.files.enqueue(id, text, delivery, files);
116
132
  return { ...this.view(d, owner), requestId: request.requestId, messageStatus: "queued" };
117
133
  });
118
134
  }
@@ -171,8 +187,8 @@ export class AgentService {
171
187
  return this.restart(id, owner, text);
172
188
  }
173
189
  async restart(id, owner, text) {
174
- const d = this.get(id, owner);
175
- this.host.available();
190
+ const d = this.get(id, owner), reference = this.files.reference(id);
191
+ this.host.available(reference.host === "acp" ? reference.backend : undefined);
176
192
  const reserved = this.files.control(() => {
177
193
  requireThat(!this.alive(id), "子会话仍在运行。");
178
194
  this.assertPrivate(id);
@@ -260,6 +276,61 @@ export class AgentService {
260
276
  return "";
261
277
  return this.host.report(d, this.files.reference(d.agentId), c.leaf);
262
278
  }
279
+ async recordPage(id, owner, options = {}) {
280
+ const d = this.get(id, owner), view = this.view(d, owner);
281
+ requireThat(view.transport === "acp", "该记录入口用于 ACP 成员。");
282
+ const messages = this.files.messages(id), cycles = this.cycles(id, owner).sort((a, b) => a.startedAt - b.startedAt);
283
+ const records = [];
284
+ const included = new Set();
285
+ for (const c of cycles) {
286
+ for (const requestId of c.requestIds) {
287
+ const request = messages.find(message => message.requestId === requestId);
288
+ if (!request || included.has(requestId))
289
+ continue;
290
+ included.add(requestId);
291
+ records.push({ seq: records.length, type: "acp/input", time: c.startedAt, requestId, state: c.state,
292
+ text: [request.message, ...request.files.map(file => "附件:" + file)].filter(Boolean).join("\n\n") });
293
+ }
294
+ const report = await this.report(d, c);
295
+ this.check();
296
+ records.push({ seq: records.length, type: "acp/report", time: c.finishedAt ?? c.startedAt, cycleId: c.cycleId, state: c.state,
297
+ text: [c.error, report].filter(Boolean).join("\n\n") });
298
+ }
299
+ const run = this.files.read(id, "launch.json", launch);
300
+ for (const request of messages.filter(message => message.generation === run.generation && !included.has(message.requestId))) {
301
+ records.push({ seq: records.length, type: "acp/input", time: run.startedAt, requestId: request.requestId, state: "queued",
302
+ text: [request.message, ...request.files.map(file => "附件:" + file)].filter(Boolean).join("\n\n") });
303
+ }
304
+ const cursor = run.generation + ":" + records.length + ":" + cycles.at(-1)?.state;
305
+ if (options.seq !== undefined) {
306
+ const record = records[options.seq];
307
+ requireThat(record, "ACP 记录位置不存在。");
308
+ const text = options.format === "json" ? JSON.stringify(record, null, 2) : record.text;
309
+ const offset = options.textOffset ?? 0, end = offset + (options.textLimit ?? 12000);
310
+ requireThat(offset <= text.length, "ACP 记录分页位置超出范围。");
311
+ return { kind: "acp", agent: view, cursor, seq: record.seq, offset, text: text.slice(offset, end), totalLength: text.length, nextOffset: end < text.length ? end : null };
312
+ }
313
+ const limit = options.limit ?? 30, offset = options.offset ?? Math.max(0, records.length - limit);
314
+ requireThat(offset <= records.length, "ACP 记录分页位置超出范围。");
315
+ return { kind: "acp", agent: view, cursor, total: records.length, offset, nextOffset: offset + limit < records.length ? offset + limit : null,
316
+ records: records.slice(offset, offset + limit).map(record => { const { text, ...fields } = record; return { ...fields, preview: text.slice(0, 800) }; }) };
317
+ }
318
+ pendingPermissions(owner) {
319
+ return this.list(owner).filter(view => view.owned && view.alive && view.transport === "acp").flatMap(view => readdirSync(resolve(this.files.directory(view.agentId), "permissions")).filter(name => name.endsWith(".json") && !name.endsWith("-reply.json")).flatMap(name => {
320
+ const request = this.files.read(view.agentId, "permissions/" + name, acpPermission);
321
+ if (request.generation !== view.generation || this.files.optional(view.agentId, "permissions/" + request.requestId + "-reply.json", acpPermissionReply))
322
+ return [];
323
+ return [{ ...request, agentId: view.agentId, name: view.name }];
324
+ })).slice(0, 32);
325
+ }
326
+ answerPermission(id, requestId, optionId, owner) {
327
+ this.get(id, owner);
328
+ const request = this.files.read(id, "permissions/" + requestId + ".json", acpPermission);
329
+ const run = this.files.read(id, "launch.json", launch);
330
+ requireThat(run.generation === request.generation && !run.stop && this.alive(id), "ACP 确认请求已失效。");
331
+ requireThat(optionId === null || request.options.some(option => option.optionId === optionId), "ACP 确认选项无效。");
332
+ this.files.write(id, "permissions/" + requestId + "-reply.json", { generation: run.generation, requestId, optionId }, acpPermissionReply, true);
333
+ }
263
334
  release(id) {
264
335
  let pending = this.#releasing.get(id);
265
336
  if (!pending) {
@@ -129,7 +129,8 @@ export class TeamService {
129
129
  this.files.save(team);
130
130
  }
131
131
  pauseAll(owner, reason) {
132
- this.check();
132
+ if (!this.records(owner.sessionId).length)
133
+ return;
133
134
  this.agents.control(() => { for (const team of this.records(owner.sessionId))
134
135
  this.pauseRecord(team, reason); });
135
136
  }
@@ -244,7 +245,8 @@ export class TeamService {
244
245
  });
245
246
  }
246
247
  advance(owner, views, completions) {
247
- this.check();
248
+ if (!this.records(owner.sessionId).length)
249
+ return [];
248
250
  return this.agents.control(() => {
249
251
  const inputs = [], records = this.records(owner.sessionId), links = this.files.links(records);
250
252
  for (const team of records) {
@@ -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
  }