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
@@ -16,6 +16,10 @@ export class DshAgents {
16
16
  this.composition = composition;
17
17
  this.lifetime = lifetime;
18
18
  }
19
+ validateOptions(options) {
20
+ for (const key of ["noExtensions", "noPromptTemplates", "noContextFiles"])
21
+ requireThat(options[key] === undefined, "dsh 不支持宿主选项:" + key);
22
+ }
19
23
  available() {
20
24
  this.lifetime.throwIfAborted();
21
25
  requireThat(!this.#closed && this.ctx.agents.get(this.parent.id) === this.parent, "dsh 父会话或执行组件已关闭。");
@@ -1,26 +1,22 @@
1
- import { readFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
1
  import { BlockAssembler } from "@deepseek-ai/dsh-llm";
4
- import { resourceRoot } from "../../common/paths.js";
5
2
  import { requireThat } from "../../common/validation.js";
6
3
  import { reduceHistorySummary } from "../history-summary.js";
7
4
  /** Independent text calls through the host's routing and authentication; no Agent or Session messages. */
8
5
  export function dshHistorySummarizer(ctx, selection, sessionId) {
9
- return async (text, signal) => {
6
+ return async (request, signal) => {
10
7
  requireThat(selection, "请先选择 dsh 模型。");
11
8
  signal.throwIfAborted();
12
- const system = await readFile(join(resourceRoot, "prompts/history-summary.md"), { encoding: "utf8", signal });
13
- const prepare = () => ctx.llm.prepareCall({ provider: selection.provider, model: selection.model, maxTokens: 2048 }, signal, (controls, model) => ({ ...controls, ...(model.reasoning?.efforts[0] ? { reasoningEffort: model.reasoning.efforts[0].id } : {}) }));
9
+ const prepare = () => ctx.llm.prepareCall({ provider: selection.provider, model: selection.model, maxTokens: request.maxTokens }, signal, (controls, model) => ({ ...controls, ...(model.reasoning?.efforts[0] ? { reasoningEffort: model.reasoning.efforts[0].id } : {}) }));
14
10
  let first = await prepare();
15
11
  const budget = Math.max(2000, Math.min(24000, Math.floor((first.context?.contextWindow ?? 12000) / 2)));
16
- const ask = async (content, signal) => {
12
+ const ask = async ({ system, prompt }, signal) => {
17
13
  signal.throwIfAborted();
18
14
  const prepared = first ?? await prepare();
19
15
  first = undefined;
20
16
  const assembler = new BlockAssembler();
21
17
  let finished = false;
22
18
  for await (const chunk of prepared.stream({ ...prepared.config, system, sessionId, purpose: "pbot-history", signal, tools: [],
23
- messages: [{ role: "user", content: [{ type: "text", text: content }] }] })) {
19
+ messages: [{ role: "user", content: [{ type: "text", text: prompt }] }] })) {
24
20
  signal.throwIfAborted();
25
21
  assembler.push(chunk);
26
22
  if (chunk.type === "finish")
@@ -35,6 +31,6 @@ export function dshHistorySummarizer(ctx, selection, sessionId) {
35
31
  requireThat(answer, "历史摘要为空。");
36
32
  return answer;
37
33
  };
38
- return reduceHistorySummary(budget, ask)(text, signal);
34
+ return reduceHistorySummary(budget, ask)(request, signal);
39
35
  };
40
36
  }
@@ -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
  }
@@ -0,0 +1,59 @@
1
+ export type AcpBackend = "pi" | "dsh" | "claude";
2
+ export interface AcpCommand {
3
+ command: string;
4
+ args: string[];
5
+ }
6
+ export type AcpCommands = Partial<Record<AcpBackend, AcpCommand>>;
7
+ export interface AcpSessionReference extends AcpCommand {
8
+ host: "acp";
9
+ backend: AcpBackend;
10
+ sessionId: string | null;
11
+ capabilities?: {
12
+ resume: boolean;
13
+ load: boolean;
14
+ close: boolean;
15
+ };
16
+ }
17
+ export interface AcpModelSelection {
18
+ provider?: string;
19
+ model?: string;
20
+ resolvedModel?: string;
21
+ thinking?: string;
22
+ }
23
+ export interface AcpModelState extends AcpModelSelection {
24
+ generation: string;
25
+ }
26
+ export interface AcpProcess {
27
+ generation: string;
28
+ pid: number;
29
+ startedAt: number;
30
+ }
31
+ export interface AcpInput {
32
+ generation: string;
33
+ requestId: string;
34
+ }
35
+ export interface AcpAnswer extends AcpInput {
36
+ answer: string;
37
+ state: "completed" | "failed" | "cancelled";
38
+ error?: string;
39
+ }
40
+ export interface AcpReport {
41
+ generation: string;
42
+ cycleId: string;
43
+ text: string;
44
+ }
45
+ export interface AcpPermission {
46
+ generation: string;
47
+ requestId: string;
48
+ description: string;
49
+ options: {
50
+ optionId: string;
51
+ name: string;
52
+ kind: string;
53
+ }[];
54
+ }
55
+ export interface AcpPermissionReply {
56
+ generation: string;
57
+ requestId: string;
58
+ optionId: string | null;
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,3 +1,7 @@
1
+ import type { AcpBackend, AcpModelSelection, AcpSessionReference } from "./acp.js";
2
+ export interface AgentStartOptions extends AgentOptions {
3
+ backend?: AcpBackend;
4
+ }
1
5
  export interface AgentOptions {
2
6
  name?: string;
3
7
  message?: string;
@@ -32,6 +36,7 @@ export interface AgentDescriptor {
32
36
  export interface AgentSessionRef {
33
37
  file: string | null;
34
38
  }
39
+ export type NativeAgentHost = "pi" | "dsh";
35
40
  /** Native references are interpreted only by their owning host adapter. */
36
41
  export type AgentSessionReference = {
37
42
  host: "pi";
@@ -39,7 +44,7 @@ export type AgentSessionReference = {
39
44
  } | {
40
45
  host: "dsh";
41
46
  sessionId: string;
42
- };
47
+ } | AcpSessionReference;
43
48
  export interface AgentLaunch {
44
49
  generation: string;
45
50
  name: string;
@@ -80,6 +85,15 @@ export interface AgentView extends AgentDescriptor {
80
85
  generation: string;
81
86
  state: AgentStatus["state"];
82
87
  activity: string;
88
+ backend?: AcpBackend;
89
+ transport?: "native" | "acp";
90
+ selection?: AcpModelSelection;
91
+ capabilities?: {
92
+ steer: boolean;
93
+ resume: boolean;
94
+ team: boolean;
95
+ transcript: boolean;
96
+ };
83
97
  cycle?: AgentCycle;
84
98
  error?: string;
85
99
  owned: boolean;
@@ -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,9 +1,12 @@
1
+ import type { AcpCommands } from "./acp.js";
1
2
  export interface WorkspaceConfig {
2
3
  enabled?: boolean;
4
+ acp?: AcpCommands;
3
5
  }
4
6
  export interface WorkspaceConfiguration {
5
7
  path: string;
6
8
  present: boolean;
7
9
  enabled: boolean;
8
10
  error?: string;
11
+ acp?: AcpCommands;
9
12
  }
@@ -0,0 +1,42 @@
1
+ import type { AgentDescriptor, AgentMessage } from "../../model/agent.js";
2
+ import type { AcpPermission } from "../../model/acp.js";
3
+ import { AgentFiles } from "../../storage/agent-files.js";
4
+ import { AgentRun } from "./agent-run.js";
5
+ export interface AcpProgress {
6
+ kind: "text" | "thought" | "tool" | "activity";
7
+ text?: string;
8
+ messageId?: string;
9
+ activity?: string;
10
+ }
11
+ export declare class AcpAnswerBuffer {
12
+ #private;
13
+ get text(): string;
14
+ reset(): void;
15
+ update(value: AcpProgress): void;
16
+ }
17
+ export interface AcpWork {
18
+ readonly signal: AbortSignal;
19
+ prompt(request: AgentMessage): Promise<{
20
+ stopReason: string;
21
+ }>;
22
+ cancel(): Promise<void>;
23
+ }
24
+ /** ACP prompt completion is the receipt boundary; final reports publish before completions. */
25
+ export declare class AcpAgentRun {
26
+ #private;
27
+ readonly files: AgentFiles;
28
+ readonly descriptor: AgentDescriptor;
29
+ readonly generation: string;
30
+ readonly work: AcpWork;
31
+ readonly exactAnswer: boolean;
32
+ readonly execution: AgentRun;
33
+ constructor(files: AgentFiles, descriptor: AgentDescriptor, generation: string, work: AcpWork, exactAnswer: boolean);
34
+ private get id();
35
+ private current;
36
+ update(value: AcpProgress): void;
37
+ permission(description: string, options: AcpPermission["options"], signal: AbortSignal): Promise<string | null>;
38
+ run(): Promise<void>;
39
+ private perform;
40
+ settled(): Promise<void> | undefined;
41
+ stop(): Promise<void>;
42
+ }
@@ -0,0 +1,149 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { AgentFiles, launch } from "../../storage/agent-files.js";
4
+ import { acpAnswer, acpInput, acpPermission, acpPermissionReply, acpReport } from "../../storage/acp-files.js";
5
+ import { AgentRun } from "./agent-run.js";
6
+ export class AcpAnswerBuffer {
7
+ #text = "";
8
+ #messageId;
9
+ get text() { return this.#text; }
10
+ reset() { this.#text = ""; this.#messageId = undefined; }
11
+ update(value) {
12
+ if (value.kind === "tool")
13
+ this.reset();
14
+ if (value.kind !== "text")
15
+ return;
16
+ if (value.messageId && value.messageId !== this.#messageId)
17
+ this.#text = "";
18
+ this.#messageId = value.messageId;
19
+ this.#text += value.text ?? "";
20
+ }
21
+ }
22
+ /** ACP prompt completion is the receipt boundary; final reports publish before completions. */
23
+ export class AcpAgentRun {
24
+ files;
25
+ descriptor;
26
+ generation;
27
+ work;
28
+ exactAnswer;
29
+ execution;
30
+ #answer = new AcpAnswerBuffer();
31
+ #lastActivity = 0;
32
+ #stopping = false;
33
+ #work;
34
+ #stop;
35
+ #failure;
36
+ constructor(files, descriptor, generation, work, exactAnswer) {
37
+ this.files = files;
38
+ this.descriptor = descriptor;
39
+ this.generation = generation;
40
+ this.work = work;
41
+ this.exactAnswer = exactAnswer;
42
+ this.execution = new AgentRun(files, descriptor.agentId, generation);
43
+ }
44
+ get id() { return this.descriptor.agentId; }
45
+ current() { return this.files.read(this.id, "launch.json", launch).generation === this.generation; }
46
+ update(value) {
47
+ if (!this.execution.current || !this.current())
48
+ return;
49
+ this.#answer.update(value);
50
+ if (Date.now() - this.#lastActivity >= 500) {
51
+ this.#lastActivity = Date.now();
52
+ this.execution.save({ state: this.#stopping ? "stopping" : "busy", activity: value.activity ?? (value.kind === "text" ? "回答" : "思考") });
53
+ }
54
+ }
55
+ async permission(description, options, signal) {
56
+ const requestId = randomUUID(), request = { generation: this.generation, requestId, description, options };
57
+ this.files.write(this.id, "permissions/" + requestId + ".json", request, acpPermission, true);
58
+ this.execution.save({ state: "busy", activity: "等待确认" });
59
+ while (!signal.aborted && !this.#stopping && this.current() && !this.files.read(this.id, "launch.json", launch).stop) {
60
+ const reply = this.files.optional(this.id, "permissions/" + requestId + "-reply.json", acpPermissionReply);
61
+ if (reply?.generation === this.generation)
62
+ return reply.optionId;
63
+ await delay(100);
64
+ }
65
+ return null;
66
+ }
67
+ async run() {
68
+ this.execution.recover();
69
+ this.execution.save({ state: "idle", activity: "空闲" });
70
+ while (!this.#stopping && this.current() && !this.work.signal.aborted) {
71
+ this.files.check();
72
+ if (this.#failure)
73
+ throw this.#failure;
74
+ if (this.files.read(this.id, "launch.json", launch).stop) {
75
+ await this.stop();
76
+ break;
77
+ }
78
+ if (!this.#work) {
79
+ const request = this.files.messages(this.id).find(message => message.generation === this.generation && !this.execution.accepted(message.requestId));
80
+ if (request) {
81
+ const pending = this.perform(request).finally(() => { if (this.#work === pending)
82
+ this.#work = undefined; });
83
+ this.#work = pending;
84
+ void pending.catch(error => { this.#failure = error; });
85
+ }
86
+ }
87
+ await delay(100);
88
+ }
89
+ if (!this.current() && !this.#stopping)
90
+ await this.stop();
91
+ if (!this.#stopping)
92
+ await this.#work;
93
+ if (this.work.signal.aborted && !this.#stopping)
94
+ throw this.work.signal.reason;
95
+ }
96
+ async perform(request) {
97
+ this.#answer.reset();
98
+ this.execution.claim(request.requestId);
99
+ this.execution.enter(request.requestId);
100
+ this.execution.begin();
101
+ this.files.write(this.id, "acp-input.json", { generation: this.generation, requestId: request.requestId }, acpInput);
102
+ let result;
103
+ try {
104
+ const end = await this.work.prompt(request);
105
+ let snapshot;
106
+ if (this.exactAnswer) {
107
+ snapshot = this.files.optional(this.id, "acp-answer.json", acpAnswer);
108
+ if (snapshot?.generation !== this.generation || snapshot.requestId !== request.requestId)
109
+ snapshot = undefined;
110
+ }
111
+ const answer = this.exactAnswer ? snapshot?.answer ?? "" : this.#answer.text;
112
+ const state = end.stopReason === "cancelled" || this.#stopping ? "cancelled" : end.stopReason === "end_turn" &&
113
+ (!this.exactAnswer || snapshot?.state === "completed") && answer.trim() ? "completed" : "failed";
114
+ if (state === "completed")
115
+ this.execution.consume(request.requestId);
116
+ result = { generation: this.generation, requestId: request.requestId, state, answer,
117
+ ...(state === "failed" ? { error: snapshot?.error ?? "ACP 工作未产生有效最终回答:" + end.stopReason } : {}) };
118
+ }
119
+ catch (error) {
120
+ result = { generation: this.generation, requestId: request.requestId, answer: this.#answer.text,
121
+ state: this.#stopping || this.files.read(this.id, "launch.json", launch).stop ? "cancelled" : "failed", error: String(error) };
122
+ }
123
+ if (!this.current())
124
+ return;
125
+ const cycleId = this.execution.current.cycleId;
126
+ this.files.write(this.id, "reports/" + cycleId + ".json", { generation: this.generation, cycleId, text: result.answer }, acpReport, true);
127
+ this.execution.finish({ state: this.work.signal.aborted && !this.#stopping ? "interrupted" : result.state,
128
+ position: "acp:" + cycleId, answer: result.answer, ...(result.error ? { error: result.error } : {}) });
129
+ }
130
+ settled() { return this.#work; }
131
+ stop() {
132
+ return this.#stop ??= (async () => {
133
+ this.#stopping = true;
134
+ if (this.current())
135
+ this.execution.save({ state: "stopping", activity: "停止" });
136
+ const pending = this.#work;
137
+ if (!pending)
138
+ return;
139
+ const grace = new AbortController();
140
+ try {
141
+ const cancelAndSettle = this.work.cancel().catch(() => { }).then(() => pending);
142
+ await Promise.race([cancelAndSettle, delay(4000, undefined, { signal: grace.signal })]);
143
+ }
144
+ finally {
145
+ grace.abort();
146
+ }
147
+ })();
148
+ }
149
+ }