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
@@ -0,0 +1,159 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { AgentFiles, descriptor, launch, status } from "../storage/agent-files.js";
4
+ import { acpModelState, acpReference } from "../storage/acp-files.js";
5
+ import { AcpAgentRun } from "../services/agents/acp-run.js";
6
+ import { openAcp } from "../integrations/acp/connection.js";
7
+ import { acpExecutable } from "../integrations/acp/launch.js";
8
+ import { claudeOptions } from "../integrations/acp/claude.js";
9
+ import { acpContent } from "../integrations/acp/input.js";
10
+ import { agentText } from "../integrations/agent-resources.js";
11
+ import { activatePython } from "../integrations/python-activation.js";
12
+ import { PythonEnvironmentService } from "../services/workspace/python-environment-service.js";
13
+ import { resourceRoot } from "../common/paths.js";
14
+ import { requireThat } from "../common/validation.js";
15
+ import { packageVersion, releaseLine } from "../common/version.js";
16
+ const args = process.argv.slice(2);
17
+ const option = (name) => args[args.indexOf(name) + 1];
18
+ const directory = option("--directory"), id = option("--pbot-acp-agent"), generation = option("--generation");
19
+ requireThat(directory && id && generation, "缺少 ACP worker 启动信息。");
20
+ const files = new AgentFiles(dirname(directory), option("--host"));
21
+ requireThat(files.directory(id) === directory, "ACP worker 目录不匹配。");
22
+ const d = files.read(id, "descriptor.json", descriptor), reference = files.read(id, "acp-session.json", acpReference);
23
+ requireThat(d.agentId === id && releaseLine(d.release) === releaseLine(packageVersion), "ACP worker 身份或版本不匹配。");
24
+ const validating = args.includes("--validate"), lifetime = new AbortController();
25
+ let execution, restorePython;
26
+ const python = new PythonEnvironmentService(d.workspace);
27
+ const stop = () => { void execution?.stop().catch(error => lifetime.abort(error)); if (!execution)
28
+ lifetime.abort(); };
29
+ process.on("SIGTERM", stop);
30
+ process.on("SIGINT", stop);
31
+ async function main() {
32
+ requireThat(files.read(id, "launch.json", launch).generation === generation, "ACP worker 启动代次已失效。");
33
+ if (!validating) {
34
+ try {
35
+ const prepared = await python.setup(lifetime.signal);
36
+ restorePython = activatePython(prepared.directory);
37
+ }
38
+ catch {
39
+ lifetime.signal.throwIfAborted();
40
+ }
41
+ }
42
+ const env = { ...process.env, PBOT_ACP_PYTHON_STATE: validating ? "unavailable" : python.status.state, PBOT_SUBAGENT_RUN_ID: id, PBOT_SUBAGENT_DIR: directory, PBOT_SUBAGENT_GENERATION: generation,
43
+ ...(validating ? { PBOT_ACP_VALIDATE: "1" } : {}) };
44
+ const command = { ...reference, args: [...reference.args] };
45
+ const packageRoot = resolve(resourceRoot, "..");
46
+ if (reference.backend === "pi") {
47
+ Object.assign(env, { PBOT_ACP_PI_COMMAND: process.env.PI_ACP_PI_COMMAND ?? acpExecutable("pi", "pi"),
48
+ PI_ACP_PI_COMMAND: join(packageRoot, "bin/pbot-pi-acp.mjs") });
49
+ }
50
+ if (reference.backend === "dsh") {
51
+ const patch = join(directory, "acp-dsh-patch.json");
52
+ await writeFile(patch, JSON.stringify([{ insert: [{ id: "pbot-acp-member", name: join(packageRoot, "lib/extension/dsh/acp-member.js") }] }]) + "\n", { mode: 0o600 });
53
+ command.args.push("--patch", patch);
54
+ }
55
+ let prompt;
56
+ if (reference.backend === "claude") {
57
+ prompt = [await readFile(join(resourceRoot, "prompts/workspace.md"), "utf8"), await agentText("general-purpose", d.workspace),
58
+ JSON.stringify({ workspaceRoot: d.workspace, resourceRoot, python: python.status.state === "ready"
59
+ ? { state: "ready", directory: process.env.VIRTUAL_ENV } : { state: python.status.state } })].join("\n\n");
60
+ }
61
+ const saveSelection = (selection) => {
62
+ if (validating)
63
+ return;
64
+ const run = files.read(id, "launch.json", launch);
65
+ if (run.generation === generation && !run.stop)
66
+ files.write(id, "acp-model.json", { generation, ...selection }, acpModelState);
67
+ };
68
+ const claude = reference.backend === "claude" ? await claudeOptions(reference, d.cwd, d.options.thinking) : undefined;
69
+ const connection = await openAcp(command, d.cwd, env, {
70
+ selection: saveSelection,
71
+ update(update) {
72
+ if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text")
73
+ execution?.update({ kind: "text", text: update.content.text,
74
+ ...(update.messageId ? { messageId: update.messageId } : {}) });
75
+ else if (update.sessionUpdate === "agent_thought_chunk")
76
+ execution?.update({ kind: "thought" });
77
+ else if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update")
78
+ execution?.update({ kind: update.sessionUpdate === "tool_call" ? "tool" : "activity", activity: update.name ?? update.title ?? "工具" });
79
+ },
80
+ async permission(request, signal) {
81
+ if (!execution)
82
+ return { outcome: { outcome: "cancelled" } };
83
+ const selected = await execution.permission(JSON.stringify(request.toolCall, null, 2), request.options, signal);
84
+ return { outcome: selected === null ? { outcome: "cancelled" } : { outcome: "selected", optionId: selected } };
85
+ },
86
+ }, lifetime.signal, prompt, claude);
87
+ try {
88
+ requireThat(!prompt || reference.backend !== "claude" || connection.systemPrompt, "Claude ACP 后端需要支持 systemPrompt,以加载专家职责与工作区资料。");
89
+ if (validating) {
90
+ if (process.connected)
91
+ process.send?.({ type: "validated" });
92
+ return;
93
+ }
94
+ if (reference.sessionId === null)
95
+ await connection.configure(d.options);
96
+ requireThat(files.read(id, "launch.json", launch).generation === generation && !files.read(id, "launch.json", launch).stop, "ACP 启动已取消。");
97
+ files.write(id, "acp-session.json", { ...reference, sessionId: reference.backend === "dsh" || reference.sessionId !== null ? connection.sessionId : null, capabilities: connection.capabilities }, acpReference);
98
+ saveSelection(connection.selection());
99
+ execution = new AcpAgentRun(files, d, generation, {
100
+ signal: connection.signal,
101
+ async prompt(request) {
102
+ const content = await acpContent(request, connection.images, connection.signal);
103
+ const run = files.read(id, "launch.json", launch);
104
+ requireThat(run.generation === generation && !run.stop, "ACP 输入已取消或启动代次变化。");
105
+ connection.signal.throwIfAborted();
106
+ const saved = files.read(id, "acp-session.json", acpReference);
107
+ if (saved.sessionId === null)
108
+ files.write(id, "acp-session.json", { ...saved, sessionId: connection.sessionId }, acpReference);
109
+ return connection.prompt(content);
110
+ },
111
+ cancel: () => connection.cancel(),
112
+ }, reference.backend !== "claude");
113
+ await execution.run();
114
+ }
115
+ finally {
116
+ try {
117
+ await connection.close();
118
+ }
119
+ finally {
120
+ await execution?.settled();
121
+ }
122
+ }
123
+ }
124
+ try {
125
+ await main();
126
+ if (!validating && files.read(id, "launch.json", launch).generation === generation) {
127
+ if (execution)
128
+ execution.execution.save({ state: "stopped", activity: "已停止" });
129
+ else
130
+ files.write(id, "status.json", { generation, state: "stopped", activity: "已停止", updatedAt: Date.now() }, status);
131
+ }
132
+ }
133
+ catch (error) {
134
+ if (validating) {
135
+ if (process.connected)
136
+ process.send?.({ type: "error", error: String(error) });
137
+ }
138
+ else if (files.read(id, "launch.json", launch).generation === generation) {
139
+ const stopped = files.read(id, "launch.json", launch).stop;
140
+ const patch = { state: stopped ? "stopped" : "error", activity: stopped ? "已停止" : "ACP 执行失败", ...(stopped ? {} : { error: String(error) }) };
141
+ if (execution)
142
+ execution.execution.save(patch);
143
+ else
144
+ files.write(id, "status.json", { generation, ...patch, updatedAt: Date.now() }, status);
145
+ }
146
+ process.exitCode = 1;
147
+ }
148
+ finally {
149
+ lifetime.abort();
150
+ try {
151
+ await python.close();
152
+ }
153
+ finally {
154
+ restorePython?.();
155
+ }
156
+ if (process.connected)
157
+ process.disconnect();
158
+ // Keep child processes in this worker's process group so forced release covers descendants.
159
+ }
@@ -0,0 +1,15 @@
1
+ export declare function claudeWorkspaceRoot(cwd: string, projectDirectory?: string | undefined): Promise<string>;
2
+ export declare function claudeCommand(args: readonly string[], cwd: string): Promise<{
3
+ version: string;
4
+ workspaceRoot: string;
5
+ resourceRoot: string;
6
+ configuration: import("../model/workspace-config.js").WorkspaceConfiguration;
7
+ python: {
8
+ executable?: string;
9
+ state: "unprepared" | "preparing" | "ready" | "error";
10
+ directory?: string;
11
+ error?: string;
12
+ };
13
+ }>;
14
+ /** Standard command hooks consume documented stdin fields; native sessions remain entirely host-owned. */
15
+ export declare function claudeHook(value: unknown): Promise<Record<string, unknown>>;
@@ -0,0 +1,104 @@
1
+ import { readFile, realpath, stat } from "node:fs/promises";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { object } from "../common/json.js";
4
+ import { resourceRoot } from "../common/paths.js";
5
+ import { packageVersion } from "../common/version.js";
6
+ import { requireThat } from "../common/validation.js";
7
+ import { agentText } from "../integrations/agent-resources.js";
8
+ import { PythonEnvironmentService } from "../services/workspace/python-environment-service.js";
9
+ import { readWorkspaceConfig } from "../services/workspace/workspace-config.js";
10
+ import { initializeWorkspace } from "../services/workspace/workspace-preparation.js";
11
+ export async function claudeWorkspaceRoot(cwd, projectDirectory = process.env.CLAUDE_PROJECT_DIR) {
12
+ const directory = projectDirectory || cwd;
13
+ requireThat(isAbsolute(directory), "Claude 工作区需要绝对路径。");
14
+ const root = await realpath(directory);
15
+ requireThat((await stat(root)).isDirectory(), "Claude 工作区需要目录。");
16
+ return root;
17
+ }
18
+ async function pythonStatus(root, prepare, force = false) {
19
+ const python = new PythonEnvironmentService(root);
20
+ try {
21
+ if (force)
22
+ await python.setup();
23
+ else {
24
+ const current = await python.inspect();
25
+ if (prepare && current.state === "unprepared")
26
+ await python.setup();
27
+ }
28
+ }
29
+ catch { /* The service retains the preparation or inspection error for status. */ }
30
+ finally {
31
+ await python.close();
32
+ }
33
+ const status = python.status;
34
+ return { ...status, ...(status.state === "ready" ? { executable: join(status.directory, "bin/python") } : {}) };
35
+ }
36
+ function disabled(configuration) {
37
+ return configuration.error ?? "Personal Bot 未在此工作区启用。运行 /personal-bot:pbot init;配置文件:" + configuration.path;
38
+ }
39
+ export async function claudeCommand(args, cwd) {
40
+ const root = await claudeWorkspaceRoot(cwd);
41
+ const action = args.join(" ");
42
+ requireThat(["init", "status", "python setup"].includes(action), "用法:node <插件目录>/lib/claude.js init|status|python setup");
43
+ if (action === "init")
44
+ await initializeWorkspace(root);
45
+ const configuration = await readWorkspaceConfig(root);
46
+ if (action === "python setup")
47
+ requireThat(configuration.enabled, disabled(configuration));
48
+ return { version: packageVersion, workspaceRoot: root, resourceRoot, configuration,
49
+ python: configuration.enabled ? await pythonStatus(root, action !== "status", action === "python setup") : { state: "unprepared" } };
50
+ }
51
+ /** Standard command hooks consume documented stdin fields; native sessions remain entirely host-owned. */
52
+ export async function claudeHook(value) {
53
+ requireThat(object(value) && typeof value.hook_event_name === "string", "Claude hook 输入无效。");
54
+ if (process.env.PBOT_SUBAGENT_RUN_ID)
55
+ return {};
56
+ const event = value.hook_event_name;
57
+ requireThat(["SessionStart", "UserPromptSubmit", "SubagentStart", "PreToolUse", "UserPromptExpansion"].includes(event), "Claude hook 事件未支持。");
58
+ const skillCheck = event === "PreToolUse" || event === "UserPromptExpansion";
59
+ if (skillCheck) {
60
+ const skill = event === "UserPromptExpansion"
61
+ ? value.expansion_type === "slash_command" ? value.command_name : undefined
62
+ : value.tool_name === "Skill" && object(value.tool_input) ? value.tool_input.skill : undefined;
63
+ if (typeof skill !== "string" || !skill.startsWith("personal-bot:") || skill === "personal-bot:pbot")
64
+ return {};
65
+ }
66
+ requireThat(typeof value.cwd === "string", "Claude hook 缺少工作目录。");
67
+ const root = await claudeWorkspaceRoot(value.cwd);
68
+ const configuration = await readWorkspaceConfig(root);
69
+ if (skillCheck) {
70
+ if (configuration.enabled)
71
+ return {};
72
+ return event === "UserPromptExpansion" ? { decision: "block", reason: disabled(configuration) } : { hookSpecificOutput: {
73
+ hookEventName: event, permissionDecision: "deny", permissionDecisionReason: disabled(configuration),
74
+ } };
75
+ }
76
+ if (!configuration.enabled)
77
+ return event === "SubagentStart" ? {} : {
78
+ hookSpecificOutput: { hookEventName: event, additionalContext: disabled(configuration) },
79
+ };
80
+ if (event === "SubagentStart" && value.agent_type !== "personal-bot:general-purpose")
81
+ return {};
82
+ const python = await pythonStatus(root, event === "SessionStart" || event === "UserPromptSubmit");
83
+ if (event === "SessionStart")
84
+ return python.state === "error" ? { systemMessage: python.error } : {};
85
+ const member = event === "SubagentStart" || typeof value.agent_id === "string";
86
+ const role = event === "SubagentStart" ? readFile(join(root, "agents/general-purpose.md"), "utf8").catch(error => {
87
+ if (error.code === "ENOENT")
88
+ return "";
89
+ throw error;
90
+ }) : agentText(member ? "general-purpose" : "coordinator", root, "claude");
91
+ const [workspace, duties, agents] = await Promise.all([
92
+ readFile(join(resourceRoot, "prompts/workspace.md"), "utf8"),
93
+ role,
94
+ readFile(join(root, "AGENTS.md"), "utf8").catch(error => {
95
+ if (error.code === "ENOENT")
96
+ return "";
97
+ throw error;
98
+ }),
99
+ ]);
100
+ return { ...(python.state === "error" ? { systemMessage: python.error } : {}),
101
+ hookSpecificOutput: { hookEventName: event, additionalContext: [
102
+ workspace, duties, agents, JSON.stringify({ workspaceRoot: root, resourceRoot, python }),
103
+ ].filter(Boolean).join("\n\n") } };
104
+ }
@@ -0,0 +1,4 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ export declare const name = "pbot-acp-member";
3
+ export declare const inject: string[];
4
+ export declare function apply(ctx: Context): Promise<void>;
@@ -0,0 +1,48 @@
1
+ import { acpMember } from "../acp-member.js";
2
+ import { dshResources, dshExpertTools } from "../../integrations/dsh/resources.js";
3
+ import { registerDshSkills } from "../../integrations/dsh/skills.js";
4
+ import { finalDshAnswer } from "../../integrations/dsh/messages.js";
5
+ import { registerDshFileEvents } from "./files.js";
6
+ import { requireThat } from "../../common/validation.js";
7
+ export const name = "pbot-acp-member";
8
+ export const inject = ["agents", "sessions", "llm", "tools", "systemPrompt", "skills", "fs", "workingDirectory", "approval"];
9
+ export async function apply(ctx) {
10
+ const member = await acpMember();
11
+ ctx.on("agent/pre-step", async (_event, next) => {
12
+ if (process.env.PBOT_ACP_VALIDATE === "1")
13
+ return { kind: "reject" };
14
+ member.input();
15
+ return next();
16
+ });
17
+ ctx.on("agent/created", async ({ agent, source }) => {
18
+ if (!ctx.agents.roots().includes(agent))
19
+ return;
20
+ if (source === "resume")
21
+ agent.inbox.clear();
22
+ const reference = member.files.reference(member.id);
23
+ requireThat(reference.host === "acp" && reference.backend === "dsh" && agent.session.header.cwd === member.d.cwd &&
24
+ (reference.sessionId === null || reference.sessionId === agent.id), "dsh ACP 会话身份或工作目录不匹配。");
25
+ await agent.ctx.plugin({ name: "pbot-acp-expert", inject, apply: async (scope) => {
26
+ registerDshSkills(scope, agent);
27
+ dshExpertTools(scope, agent, member.d.options);
28
+ await dshResources(scope, agent, member.d.workspace, "general-purpose", () => process.env.PBOT_ACP_PYTHON_STATE === "ready" && process.env.VIRTUAL_ENV
29
+ ? { state: "ready", directory: process.env.VIRTUAL_ENV } : { state: process.env.PBOT_ACP_PYTHON_STATE ?? "unavailable" }, member.check);
30
+ registerDshFileEvents(scope, agent, member.d.workspace, true, member.check);
31
+ let input, answer = "";
32
+ scope.on("session/event", (session, event) => {
33
+ if (session !== agent.session)
34
+ return;
35
+ if (event.type === "turn/start") {
36
+ input = member.input();
37
+ answer = "";
38
+ }
39
+ if (event.type === "assistant/message")
40
+ answer = finalDshAnswer(event);
41
+ if (event.type === "turn/end" && input) {
42
+ const reason = event.data.reason;
43
+ member.answer(input, reason.kind === "completed" && answer.trim() ? "completed" : reason.kind === "aborted" ? "cancelled" : "failed", answer, reason.kind === "error" ? reason.error.message : reason.kind === "completed" ? undefined : reason.kind);
44
+ }
45
+ });
46
+ } });
47
+ });
48
+ }
@@ -11,6 +11,9 @@ const chatSchema = Type.Object({ agentId: Type.String({ minLength: 1 }), text: T
11
11
  delivery: Type.Optional(Type.Union([Type.Literal("steer"), Type.Literal("followUp")])),
12
12
  files: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { maxItems: 32 })) }, { additionalProperties: false });
13
13
  const validChat = schema(chatSchema);
14
+ const approvalSchema = Type.Object({ agentId: Type.String({ minLength: 1 }), requestId: Type.String({ minLength: 1 }),
15
+ optionId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]) }, { additionalProperties: false });
16
+ const validApproval = schema(approvalSchema);
14
17
  const usage = '用法:/pbot status | init | python setup | agent {"action":…} | chat {"agentId":…,"text":…} | team {"action":…} | post {"teamId":…,"text":…} | history {"action":…} | records {"agentId":…}';
15
18
  export function registerDshCommand(ctx, workspaces, management) {
16
19
  ctx.commands.register({ name: "pbot", description: "Personal Bot 工作区与协作管理", recordInput: false,
@@ -58,7 +61,14 @@ export function registerDshCommand(ctx, workspaces, management) {
58
61
  case "chat": {
59
62
  requireThat(validChat(input), "人工对话参数无效。");
60
63
  const args = input;
61
- result = await workspace.expert(args.agentId).interact(args.text ?? "", args.delivery, args.files, attachments, signal);
64
+ result = await workspace.interact(args.agentId, args.text ?? "", args.delivery, args.files, attachments, signal);
65
+ break;
66
+ }
67
+ case "approval": {
68
+ requireThat(validApproval(input), "ACP 确认答复参数无效。");
69
+ const args = input;
70
+ workspace.agents.answerPermission(args.agentId, args.requestId, args.optionId, workspace.owner);
71
+ result = { answered: true };
62
72
  break;
63
73
  }
64
74
  case "team": {
@@ -17,7 +17,7 @@ export class DshHistoryWork {
17
17
  constructor(ctx, root) {
18
18
  this.ctx = ctx;
19
19
  const agents = new AgentFiles(dshHomePath("pbot", "subagents"), "dsh");
20
- this.service = new HistoryService(root, new HistoryFiles(join(root, ".pbot/history"), "dsh"), new DshHistory(ctx, root, () => agents.list().filter(value => value.workspace === root).map(value => value.agentId)), new HistoryFiles(join(root, ".pbot/history")));
20
+ this.service = new HistoryService(root, new HistoryFiles(join(root, ".pbot/history"), "dsh"), new DshHistory(ctx, root, () => agents.list().filter(value => value.workspace === root).map(value => value.agentId)), [new HistoryFiles(join(root, ".pbot/history"), "pi"), new HistoryFiles(join(root, ".pbot/history"), "claude")]);
21
21
  }
22
22
  attach(agent) { this.#parents.add(agent); return () => { this.#parents.delete(agent); }; }
23
23
  cancel() { this.#controller?.abort(); }
@@ -109,7 +109,7 @@ export function dshStatus(workspaces, workspace) {
109
109
  return json({ host: "dsh", release: packageVersion, enabled: true, state: "running", workspaceRoot: workspace.root, sessionId: workspace.agent.id,
110
110
  model: workspace.agent.model.current() ?? null, python: workspaces.python.status,
111
111
  controlError: workspace.controlError ?? null, history: workspace.history.status,
112
- agents, teams: workspace.teams.list(workspace.owner, agents) });
112
+ agents, permissions: workspace.agents.pendingPermissions(workspace.owner), teams: workspace.teams.list(workspace.owner, agents) });
113
113
  }
114
114
  /** Status remains available when this workspace has not opted in. */
115
115
  export async function dshWorkspaceStatus(workspaces, agent) {
@@ -175,6 +175,8 @@ let PbotManagement = (() => {
175
175
  requireThat(validExpert(input), "专家记录查询参数无效。");
176
176
  const args = input;
177
177
  const view = workspace.agents.status(args.agentId, workspace.owner);
178
+ if (view.transport === "acp")
179
+ return json(await workspace.agents.recordPage(args.agentId, workspace.owner, args));
178
180
  const observation = __addDisposableResource(env_1, await this.ctx.sessionQuery.observeSession(SessionId(view.agentId), { projectionMode: "none", signal: current.signal }), false);
179
181
  workspace.check();
180
182
  current.signal.throwIfAborted();
@@ -1,5 +1,7 @@
1
1
  import type { Agent } from "@deepseek-ai/dsh-agent";
2
2
  import type { Context } from "@deepseek-ai/cordis";
3
+ import type { FileBlock, ImageBlock } from "@deepseek-ai/dsh-llm";
4
+ import type { AcpCommands } from "../../model/acp.js";
3
5
  import type { AgentOwner } from "../../model/agent.js";
4
6
  import { DshAgents } from "../../integrations/dsh/dsh-agents.js";
5
7
  import { AgentService } from "../../services/agents/agent-service.js";
@@ -25,10 +27,42 @@ export declare class DshWorkspace {
25
27
  readonly teams: TeamService;
26
28
  readonly history: HistoryService;
27
29
  readonly owner: AgentOwner;
28
- constructor(ctx: Context, root: string, agent: Agent, python: PythonEnvironmentService, component: AbortSignal, historyWork: DshHistoryWork, releaseHistory: () => Promise<void>);
30
+ constructor(ctx: Context, root: string, agent: Agent, python: PythonEnvironmentService, component: AbortSignal, historyWork: DshHistoryWork, releaseHistory: () => Promise<void>, acp?: AcpCommands);
29
31
  check: () => void;
30
32
  get controlError(): string | undefined;
31
33
  open(): Promise<void>;
34
+ interact(id: string, text: string, delivery: "steer" | "followUp" | undefined, files: readonly string[] | undefined, attachments: readonly (ImageBlock | FileBlock)[] | undefined, signal: AbortSignal): Promise<{
35
+ requestId: string;
36
+ messageStatus: "queued";
37
+ name: string;
38
+ generation: string;
39
+ state: import("../../model/agent.js").AgentStatus["state"];
40
+ activity: string;
41
+ backend?: import("../../model/acp.js").AcpBackend;
42
+ transport?: "native" | "acp";
43
+ selection?: import("../../model/acp.js").AcpModelSelection;
44
+ capabilities?: {
45
+ steer: boolean;
46
+ resume: boolean;
47
+ team: boolean;
48
+ transcript: boolean;
49
+ };
50
+ cycle?: import("../../model/agent.js").AgentCycle;
51
+ error?: string;
52
+ owned: boolean;
53
+ agentId: string;
54
+ release: string;
55
+ workspace: string;
56
+ cwd: string;
57
+ parentSessionId: string;
58
+ parentLeaf: string | null;
59
+ createdAt: number;
60
+ options: import("../../model/agent.js").AgentOptions;
61
+ alive: boolean;
62
+ } | {
63
+ status: "queued";
64
+ messageId: import("@deepseek-ai/dsh-llm").MessageId;
65
+ }>;
32
66
  expert(id: string): DshAgentRuntime;
33
67
  close(): Promise<void>;
34
68
  }
@@ -1,5 +1,6 @@
1
1
  import { realpath } from "node:fs/promises";
2
2
  import { dshHomePath } from "@deepseek-ai/dsh-home-paths";
3
+ import { AgentBackends } from "../../integrations/acp/agents.js";
3
4
  import { DshAgents } from "../../integrations/dsh/dsh-agents.js";
4
5
  import { dshResources, dshExpertTools } from "../../integrations/dsh/resources.js";
5
6
  import { AgentService } from "../../services/agents/agent-service.js";
@@ -36,7 +37,7 @@ export class DshWorkspace {
36
37
  #scope;
37
38
  #events;
38
39
  #closing;
39
- constructor(ctx, root, agent, python, component, historyWork, releaseHistory) {
40
+ constructor(ctx, root, agent, python, component, historyWork, releaseHistory, acp) {
40
41
  this.ctx = ctx;
41
42
  this.root = root;
42
43
  this.agent = agent;
@@ -73,7 +74,8 @@ export class DshWorkspace {
73
74
  stopping: async (child, generation) => { const runtime = this.#experts.get(child.id); if (runtime?.generation === generation)
74
75
  await runtime.stop(); },
75
76
  }, this.lifetime.signal);
76
- this.agents = new AgentService(root, dshHomePath("pbot", "subagents"), this.host);
77
+ const directory = dshHomePath("pbot", "subagents");
78
+ this.agents = new AgentService(root, directory, new AgentBackends(this.host, directory, acp));
77
79
  this.teams = new TeamService(root, this.agents.files, this.agents.teamFiles);
78
80
  }
79
81
  check = () => { this.component.throwIfAborted(); this.lifetime.signal.throwIfAborted(); };
@@ -94,6 +96,22 @@ export class DshWorkspace {
94
96
  } });
95
97
  this.check();
96
98
  }
99
+ async interact(id, text, delivery, files = [], attachments = [], signal) {
100
+ const view = this.agents.status(id, this.owner);
101
+ if (view.transport !== "acp")
102
+ return this.expert(id).interact(text, delivery, files, attachments, signal);
103
+ this.check();
104
+ signal.throwIfAborted();
105
+ requireThat(text.length <= 24000 && files.length + attachments.length <= 32 && (!files.length || !attachments.length), "人工消息或附件参数无效。");
106
+ const paths = [...files, ...attachments.map(attachment => {
107
+ const path = attachment.type === "image" ? this.ctx.attachments.imageHostPath(attachment.attachment) : this.ctx.attachments.fileHostPath(attachment.attachment);
108
+ requireThat(path, "该原生附件存储不提供 ACP 子进程可读取的文件路径。");
109
+ return path;
110
+ })];
111
+ requireThat(text.trim() || paths.length, "请输入消息或附加文件。");
112
+ this.teams.pauseMember(id, "成员由人工接管");
113
+ return this.agents.send(id, text || "请处理所附文件。", delivery ?? "followUp", this.owner, paths);
114
+ }
97
115
  expert(id) {
98
116
  this.check();
99
117
  const view = this.agents.status(id, this.owner), runtime = this.#experts.get(id);
@@ -226,7 +244,7 @@ export class DshWorkspaces {
226
244
  const history = await this.history(root);
227
245
  let workspace;
228
246
  try {
229
- workspace = new DshWorkspace(this.ctx, root, agent, this.python, this.#lifetime.signal, history.work, history.release);
247
+ workspace = new DshWorkspace(this.ctx, root, agent, this.python, this.#lifetime.signal, history.work, history.release, configuration.acp);
230
248
  const owned = workspace;
231
249
  const dispose = agent.ctx.effect(() => async () => {
232
250
  this.#parents.delete(agent);
@@ -0,0 +1,24 @@
1
+ import type { AgentHost } from "../../services/agents/agent-service.js";
2
+ import type { AgentDescriptor, AgentOptions, AgentSessionReference } from "../../model/agent.js";
3
+ import type { AcpBackend, AcpCommands } from "../../model/acp.js";
4
+ import { AgentFiles } from "../../storage/agent-files.js";
5
+ /** Select the native strategy or one of the three explicit ACP targets per member. */
6
+ export declare class AgentBackends implements AgentHost {
7
+ readonly native: AgentHost;
8
+ readonly commands: AcpCommands;
9
+ readonly kind: import("../../model/agent.js").NativeAgentHost;
10
+ readonly files: AgentFiles;
11
+ readonly worker: string;
12
+ constructor(native: AgentHost, directory: string, commands?: AcpCommands);
13
+ available(backend?: AcpBackend): void;
14
+ prepare(backend: AcpBackend, options: AgentOptions): import("../../model/acp.js").AcpSessionReference;
15
+ validateOptions(options: AgentOptions, backend?: AcpBackend): void;
16
+ private isAcp;
17
+ private process;
18
+ alive(id: string): boolean;
19
+ validateSession(d: AgentDescriptor, reference: AgentSessionReference): Promise<void>;
20
+ private spawn;
21
+ launch(d: AgentDescriptor, directory: string, generation: string, reference: AgentSessionReference, resume: boolean, signal: AbortSignal): Promise<void>;
22
+ release(id: string, generation: string): Promise<void>;
23
+ report(d: AgentDescriptor, reference: AgentSessionReference, leaf: string): string | Promise<string>;
24
+ }