personal-bot 0.2.11 → 0.2.12
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.
- package/README.md +17 -3
- package/README.zh-CN.md +17 -3
- package/bin/pbot-pi-acp.mjs +20 -0
- package/docs/agent-collaboration.md +38 -2
- package/docs/capability-design.md +6 -0
- package/docs/dsh.md +9 -8
- package/docs/file-storage.md +9 -1
- package/docs/interaction-design.md +2 -2
- package/docs/model-context.md +10 -2
- package/docs/technical-design.md +20 -2
- package/docs/workspace-configuration.md +20 -1
- package/lib/client.js +40 -7
- package/lib/dsh.js +2 -0
- package/lib/extension/acp-member.d.ts +16 -0
- package/lib/extension/acp-member.js +45 -0
- package/lib/extension/acp-worker.d.ts +1 -0
- package/lib/extension/acp-worker.js +156 -0
- package/lib/extension/dsh/acp-member.d.ts +4 -0
- package/lib/extension/dsh/acp-member.js +48 -0
- package/lib/extension/dsh/command.js +11 -1
- package/lib/extension/dsh/management.js +3 -1
- package/lib/extension/dsh/workspace.d.ts +35 -1
- package/lib/extension/dsh/workspace.js +21 -3
- package/lib/integrations/acp/agents.d.ts +24 -0
- package/lib/integrations/acp/agents.js +168 -0
- package/lib/integrations/acp/claude.d.ts +18 -0
- package/lib/integrations/acp/claude.js +33 -0
- package/lib/integrations/acp/connection.d.ts +27 -0
- package/lib/integrations/acp/connection.js +167 -0
- package/lib/integrations/acp/input.d.ts +4 -0
- package/lib/integrations/acp/input.js +45 -0
- package/lib/integrations/acp/launch.d.ts +4 -0
- package/lib/integrations/acp/launch.js +52 -0
- package/lib/integrations/acp/model-selection.d.ts +12 -0
- package/lib/integrations/acp/model-selection.js +65 -0
- package/lib/integrations/dsh/dsh-agents.d.ts +2 -1
- package/lib/integrations/dsh/dsh-agents.js +4 -0
- package/lib/model/acp.d.ts +59 -0
- package/lib/model/acp.js +1 -0
- package/lib/model/agent.d.ts +15 -1
- package/lib/model/workspace-config.d.ts +3 -0
- package/lib/services/agents/acp-run.d.ts +42 -0
- package/lib/services/agents/acp-run.js +149 -0
- package/lib/services/agents/agent-service.d.ts +114 -6
- package/lib/services/agents/agent-service.js +81 -10
- package/lib/services/agents/team-service.js +4 -2
- package/lib/services/workspace/workspace-config.js +12 -1
- package/lib/storage/acp-files.d.ts +9 -0
- package/lib/storage/acp-files.js +50 -0
- package/lib/storage/agent-files.d.ts +5 -4
- package/lib/storage/agent-files.js +11 -2
- package/lib/tools/agents/actions.d.ts +16 -2
- package/lib/tools/agents/actions.js +3 -1
- package/lib/tools/agents/contract.d.ts +48 -3
- package/lib/tools/agents/contract.js +15 -9
- package/lib/tools/agents/dsh-contract.d.ts +8 -15
- package/lib/tools/agents/dsh-contract.js +12 -8
- package/lib/ui/dsh/management.js +36 -8
- package/npm-shrinkwrap.json +953 -12
- package/package.json +8 -1
- package/resources/skills/.claude-plugin/plugin.json +4 -0
- package/scripts/README.md +6 -0
- package/src/dsh.ts +1 -0
- package/src/extension/acp-member.ts +44 -0
- package/src/extension/acp-worker.ts +124 -0
- package/src/extension/agent-events.ts +28 -3
- package/src/extension/agents-command.ts +33 -5
- package/src/extension/dsh/acp-member.ts +44 -0
- package/src/extension/dsh/command.ts +10 -1
- package/src/extension/dsh/management.ts +2 -1
- package/src/extension/dsh/workspace.ts +21 -3
- package/src/extension/lifecycle.ts +2 -2
- package/src/extension/pi-acp-member.ts +64 -0
- package/src/integrations/acp/agents.ts +118 -0
- package/src/integrations/acp/claude.ts +40 -0
- package/src/integrations/acp/connection.ts +152 -0
- package/src/integrations/acp/input.ts +39 -0
- package/src/integrations/acp/launch.ts +50 -0
- package/src/integrations/acp/model-selection.ts +66 -0
- package/src/integrations/dsh/dsh-agents.ts +4 -1
- package/src/integrations/pi/pi-agents.ts +4 -1
- package/src/model/acp.ts +26 -0
- package/src/model/agent.ts +7 -1
- package/src/model/workspace-config.ts +4 -0
- package/src/pbot.ts +3 -2
- package/src/services/agents/acp-run.ts +123 -0
- package/src/services/agents/agent-service.ts +85 -12
- package/src/services/agents/team-service.ts +3 -2
- package/src/services/workspace/workspace-config.ts +10 -1
- package/src/storage/acp-files.ts +50 -0
- package/src/storage/agent-files.ts +12 -4
- package/src/tools/agents/actions.ts +4 -2
- package/src/tools/agents/contract.ts +16 -9
- package/src/tools/agents/dsh-contract.ts +12 -8
- package/src/ui/dsh/management.ts +31 -8
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,156 @@
|
|
|
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
|
+
process.send?.({ type: "validated" });
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (reference.sessionId === null)
|
|
94
|
+
await connection.configure(d.options);
|
|
95
|
+
requireThat(files.read(id, "launch.json", launch).generation === generation && !files.read(id, "launch.json", launch).stop, "ACP 启动已取消。");
|
|
96
|
+
files.write(id, "acp-session.json", { ...reference, sessionId: reference.backend === "dsh" || reference.sessionId !== null ? connection.sessionId : null, capabilities: connection.capabilities }, acpReference);
|
|
97
|
+
saveSelection(connection.selection());
|
|
98
|
+
execution = new AcpAgentRun(files, d, generation, {
|
|
99
|
+
signal: connection.signal,
|
|
100
|
+
async prompt(request) {
|
|
101
|
+
const content = await acpContent(request, connection.images, connection.signal);
|
|
102
|
+
const run = files.read(id, "launch.json", launch);
|
|
103
|
+
requireThat(run.generation === generation && !run.stop, "ACP 输入已取消或启动代次变化。");
|
|
104
|
+
connection.signal.throwIfAborted();
|
|
105
|
+
const saved = files.read(id, "acp-session.json", acpReference);
|
|
106
|
+
if (saved.sessionId === null)
|
|
107
|
+
files.write(id, "acp-session.json", { ...saved, sessionId: connection.sessionId }, acpReference);
|
|
108
|
+
return connection.prompt(content);
|
|
109
|
+
},
|
|
110
|
+
cancel: () => connection.cancel(),
|
|
111
|
+
}, reference.backend !== "claude");
|
|
112
|
+
await execution.run();
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
try {
|
|
116
|
+
await connection.close();
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
await execution?.settled();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
await main();
|
|
125
|
+
if (!validating && files.read(id, "launch.json", launch).generation === generation) {
|
|
126
|
+
if (execution)
|
|
127
|
+
execution.execution.save({ state: "stopped", activity: "已停止" });
|
|
128
|
+
else
|
|
129
|
+
files.write(id, "status.json", { generation, state: "stopped", activity: "已停止", updatedAt: Date.now() }, status);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
if (validating)
|
|
134
|
+
process.send?.({ type: "error", error: String(error) });
|
|
135
|
+
else if (files.read(id, "launch.json", launch).generation === generation) {
|
|
136
|
+
const stopped = files.read(id, "launch.json", launch).stop;
|
|
137
|
+
const patch = { state: stopped ? "stopped" : "error", activity: stopped ? "已停止" : "ACP 执行失败", ...(stopped ? {} : { error: String(error) }) };
|
|
138
|
+
if (execution)
|
|
139
|
+
execution.execution.save(patch);
|
|
140
|
+
else
|
|
141
|
+
files.write(id, "status.json", { generation, ...patch, updatedAt: Date.now() }, status);
|
|
142
|
+
}
|
|
143
|
+
process.exitCode = 1;
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
lifetime.abort();
|
|
147
|
+
try {
|
|
148
|
+
await python.close();
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
restorePython?.();
|
|
152
|
+
}
|
|
153
|
+
if (process.connected)
|
|
154
|
+
process.disconnect();
|
|
155
|
+
// Keep child processes in this worker's process group so forced release covers descendants.
|
|
156
|
+
}
|
|
@@ -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.
|
|
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": {
|
|
@@ -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
|
-
|
|
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
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { fork, spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
import { AgentFiles, launch } from "../../storage/agent-files.js";
|
|
6
|
+
import { acpInput, acpProcess, acpReference, acpReport } from "../../storage/acp-files.js";
|
|
7
|
+
import { fileId } from "../../storage/file-access.js";
|
|
8
|
+
import { requireThat } from "../../common/validation.js";
|
|
9
|
+
import { resourceRoot } from "../../common/paths.js";
|
|
10
|
+
import { acpLaunch } from "./launch.js";
|
|
11
|
+
/** Select the native strategy or one of the three explicit ACP targets per member. */
|
|
12
|
+
export class AgentBackends {
|
|
13
|
+
native;
|
|
14
|
+
commands;
|
|
15
|
+
kind;
|
|
16
|
+
files;
|
|
17
|
+
worker = resolve(resourceRoot, "../lib/extension/acp-worker.js");
|
|
18
|
+
constructor(native, directory, commands = {}) {
|
|
19
|
+
this.native = native;
|
|
20
|
+
this.commands = commands;
|
|
21
|
+
this.kind = native.kind;
|
|
22
|
+
this.files = new AgentFiles(directory, native.kind);
|
|
23
|
+
}
|
|
24
|
+
available(backend) {
|
|
25
|
+
if (!backend)
|
|
26
|
+
return this.native.available();
|
|
27
|
+
requireThat(process.platform === "linux" || process.platform === "darwin", "ACP worker 当前支持 Linux 和 macOS。");
|
|
28
|
+
requireThat(existsSync(this.worker), "缺少 ACP worker 构建产物;请先运行 npm run build。");
|
|
29
|
+
}
|
|
30
|
+
prepare(backend, options) { return acpLaunch(backend, this.commands, options); }
|
|
31
|
+
validateOptions(options, backend) {
|
|
32
|
+
if (backend)
|
|
33
|
+
this.prepare(backend, options);
|
|
34
|
+
else
|
|
35
|
+
this.native.validateOptions?.(options);
|
|
36
|
+
}
|
|
37
|
+
isAcp(id) { return Boolean(this.files.optional(id, "acp-session.json", acpReference)); }
|
|
38
|
+
process(id) {
|
|
39
|
+
const record = this.files.optional(id, "acp-process.json", acpProcess);
|
|
40
|
+
if (!record || this.files.read(id, "launch.json", launch).generation !== record.generation)
|
|
41
|
+
return;
|
|
42
|
+
let denied = false;
|
|
43
|
+
try {
|
|
44
|
+
process.kill(-record.pid, 0);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
const code = error.code;
|
|
48
|
+
if (code === "ESRCH")
|
|
49
|
+
return;
|
|
50
|
+
if (code !== "EPERM")
|
|
51
|
+
throw error;
|
|
52
|
+
denied = true;
|
|
53
|
+
}
|
|
54
|
+
const leader = spawnSync("ps", ["-p", String(record.pid), "-o", "args="], { encoding: "utf8" });
|
|
55
|
+
// A dead leader can leave its group alive. A reused leader must match our exact launch identity.
|
|
56
|
+
if (leader.status === 0 && !leader.stdout.includes("--pbot-acp-agent " + id + " --generation " + record.generation) || denied && leader.status !== 0)
|
|
57
|
+
return;
|
|
58
|
+
return record;
|
|
59
|
+
}
|
|
60
|
+
alive(id) { return this.isAcp(id) ? Boolean(this.process(id)) : this.native.alive(id); }
|
|
61
|
+
async validateSession(d, reference) {
|
|
62
|
+
if (reference.host !== "acp")
|
|
63
|
+
return this.native.validateSession(d, reference);
|
|
64
|
+
requireThat(!this.alive(d.agentId), "ACP 成员仍在运行,不能恢复。");
|
|
65
|
+
if (reference.sessionId === null) {
|
|
66
|
+
requireThat(!this.files.optional(d.agentId, "acp-input.json", acpInput), "ACP 输入交付状态不明;请核对原请求后新建成员。");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const generation = this.files.read(d.agentId, "launch.json", launch).generation;
|
|
70
|
+
await new Promise((resolveResult, reject) => {
|
|
71
|
+
const child = this.spawn(d, generation, true);
|
|
72
|
+
let validated = false, failure;
|
|
73
|
+
const timer = setTimeout(() => {
|
|
74
|
+
failure = new Error("ACP 恢复校验超时。");
|
|
75
|
+
if (child.pid) {
|
|
76
|
+
try {
|
|
77
|
+
process.kill(-child.pid, "SIGKILL");
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error.code !== "ESRCH")
|
|
81
|
+
reject(error);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}, 45_000);
|
|
85
|
+
child.on("message", (message) => {
|
|
86
|
+
if (message.type === "validated")
|
|
87
|
+
validated = true;
|
|
88
|
+
if (message.type === "error")
|
|
89
|
+
failure = new Error(message.error ?? "ACP 恢复校验失败。");
|
|
90
|
+
});
|
|
91
|
+
child.once("error", error => { failure = error; });
|
|
92
|
+
child.once("close", code => { clearTimeout(timer); if (validated && code === 0 && !failure)
|
|
93
|
+
resolveResult();
|
|
94
|
+
else
|
|
95
|
+
reject(failure ?? new Error("ACP 恢复校验失败;原代次和队列已保留。")); });
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
spawn(d, generation, validate = false) {
|
|
99
|
+
const child = fork(this.worker, ["--pbot-acp-agent", d.agentId, "--generation", generation, "--directory", this.files.directory(d.agentId),
|
|
100
|
+
"--host", this.kind, ...(validate ? ["--validate"] : [])], {
|
|
101
|
+
cwd: d.cwd, env: { ...process.env }, detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"], execArgv: [],
|
|
102
|
+
});
|
|
103
|
+
return child;
|
|
104
|
+
}
|
|
105
|
+
async launch(d, directory, generation, reference, resume, signal) {
|
|
106
|
+
if (reference.host !== "acp")
|
|
107
|
+
return this.native.launch(d, directory, generation, reference, resume, signal);
|
|
108
|
+
signal.throwIfAborted();
|
|
109
|
+
const child = this.spawn(d, generation);
|
|
110
|
+
await new Promise((resolveResult, reject) => { child.once("spawn", resolveResult); child.once("error", reject); });
|
|
111
|
+
requireThat(child.pid, "ACP worker 没有进程身份。");
|
|
112
|
+
try {
|
|
113
|
+
this.files.write(d.agentId, "acp-process.json", { generation, pid: child.pid, startedAt: Date.now() }, acpProcess);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
try {
|
|
117
|
+
process.kill(-child.pid, "SIGKILL");
|
|
118
|
+
}
|
|
119
|
+
catch (failure) {
|
|
120
|
+
if (failure.code !== "ESRCH")
|
|
121
|
+
throw new AggregateError([error, failure], "ACP 启动与清理失败。");
|
|
122
|
+
}
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
if (child.connected)
|
|
126
|
+
child.disconnect();
|
|
127
|
+
child.unref();
|
|
128
|
+
if (signal.aborted) {
|
|
129
|
+
await this.release(d.agentId, generation);
|
|
130
|
+
signal.throwIfAborted();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async release(id, generation) {
|
|
134
|
+
if (!this.isAcp(id))
|
|
135
|
+
return this.native.release(id, generation);
|
|
136
|
+
const record = this.process(id);
|
|
137
|
+
if (!record || record.generation !== generation)
|
|
138
|
+
return;
|
|
139
|
+
const terminate = (signal) => {
|
|
140
|
+
try {
|
|
141
|
+
process.kill(-record.pid, signal);
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (error.code !== "ESRCH")
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
terminate("SIGTERM");
|
|
149
|
+
const deadline = Date.now() + 4500;
|
|
150
|
+
while (Date.now() < deadline) {
|
|
151
|
+
const current = this.process(id);
|
|
152
|
+
if (!current || current.generation !== generation || current.pid !== record.pid)
|
|
153
|
+
return;
|
|
154
|
+
await delay(100);
|
|
155
|
+
}
|
|
156
|
+
const current = this.process(id);
|
|
157
|
+
if (current?.generation === generation && current.pid === record.pid)
|
|
158
|
+
terminate("SIGKILL");
|
|
159
|
+
}
|
|
160
|
+
report(d, reference, leaf) {
|
|
161
|
+
if (reference.host !== "acp")
|
|
162
|
+
return this.native.report(d, reference, leaf);
|
|
163
|
+
requireThat(leaf.startsWith("acp:"), "ACP 报告引用无效。");
|
|
164
|
+
const cycleId = fileId(leaf.slice(4)), report = this.files.read(d.agentId, join("reports", cycleId + ".json"), acpReport);
|
|
165
|
+
requireThat(report.cycleId === cycleId, "ACP 报告周期不匹配。");
|
|
166
|
+
return report.text;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { AcpCommand } from "../../model/acp.js";
|
|
2
|
+
export interface ClaudeConfiguration {
|
|
3
|
+
thinking?: string;
|
|
4
|
+
options: {
|
|
5
|
+
plugins: {
|
|
6
|
+
type: "local";
|
|
7
|
+
path: string;
|
|
8
|
+
}[];
|
|
9
|
+
effort?: string;
|
|
10
|
+
settings?: {
|
|
11
|
+
env: {
|
|
12
|
+
CLAUDE_CODE_EFFORT_LEVEL: string;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** Read the target installation's native settings without creating a model session. */
|
|
18
|
+
export declare function claudeOptions(command: AcpCommand, cwd: string, requested?: string): Promise<ClaudeConfiguration>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { basename, join, resolve } from "node:path";
|
|
4
|
+
import { object } from "../../common/json.js";
|
|
5
|
+
import { requireThat } from "../../common/validation.js";
|
|
6
|
+
import { resourceRoot } from "../../common/paths.js";
|
|
7
|
+
const levels = ["low", "medium", "high", "xhigh", "max"];
|
|
8
|
+
/** Read the target installation's native settings without creating a model session. */
|
|
9
|
+
export async function claudeOptions(command, cwd, requested) {
|
|
10
|
+
const script = command.args[0];
|
|
11
|
+
const anchor = ["node", "node.exe"].includes(basename(command.command)) && script && !script.startsWith("-") ? resolve(cwd, script) : command.command;
|
|
12
|
+
const require = createRequire(pathToFileURL(anchor));
|
|
13
|
+
const sdk = await import(pathToFileURL(require.resolve("@anthropic-ai/claude-agent-sdk")).href);
|
|
14
|
+
requireThat(object(sdk) && typeof sdk.resolveSettings === "function", "Claude ACP 需要提供 resolveSettings 的原生 SDK。");
|
|
15
|
+
const resolved = await sdk.resolveSettings({ cwd });
|
|
16
|
+
requireThat(object(resolved) && object(resolved.effective), "Claude 原生设置解析失败。");
|
|
17
|
+
const environment = object(resolved.effective.env) ? resolved.effective.env : {};
|
|
18
|
+
const configured = environment.CLAUDE_CODE_EFFORT_LEVEL ?? process.env.CLAUDE_CODE_EFFORT_LEVEL;
|
|
19
|
+
const explicit = requested !== undefined && requested !== "default";
|
|
20
|
+
requireThat(!explicit || levels.includes(requested), "Claude 思考等级不可用:" + requested);
|
|
21
|
+
const effort = explicit ? requested : typeof configured === "string" && levels.includes(configured) ? configured : undefined;
|
|
22
|
+
const thinking = effort ?? (configured === "unset" ? "unset" : undefined);
|
|
23
|
+
return {
|
|
24
|
+
...(thinking ? { thinking } : {}),
|
|
25
|
+
options: {
|
|
26
|
+
plugins: [{ type: "local", path: join(resourceRoot, "skills") }],
|
|
27
|
+
...(effort ? { effort } : {}),
|
|
28
|
+
// SDK effort alone loses to CLAUDE_CODE_EFFORT_LEVEL. A flag-tier env entry
|
|
29
|
+
// applies the explicit choice to this invocation and preserves other settings.
|
|
30
|
+
...(explicit ? { settings: { env: { CLAUDE_CODE_EFFORT_LEVEL: requested } } } : {}),
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import * as acp from "@agentclientprotocol/sdk";
|
|
2
|
+
import type { AcpModelSelection, AcpSessionReference } from "../../model/acp.js";
|
|
3
|
+
import type { AgentOptions } from "../../model/agent.js";
|
|
4
|
+
import type { ClaudeConfiguration } from "./claude.js";
|
|
5
|
+
export declare function acpFailure(error: unknown): unknown;
|
|
6
|
+
export interface AcpCallbacks {
|
|
7
|
+
update(update: acp.SessionUpdate): void | Promise<void>;
|
|
8
|
+
selection?(selection: AcpModelSelection): void;
|
|
9
|
+
permission(request: acp.RequestPermissionRequest, signal: AbortSignal): Promise<acp.RequestPermissionResponse>;
|
|
10
|
+
}
|
|
11
|
+
/** One ACP v1 connection. The worker owns its process group and business state. */
|
|
12
|
+
export declare function openAcp(reference: AcpSessionReference, cwd: string, env: NodeJS.ProcessEnv, callbacks: AcpCallbacks, signal: AbortSignal, systemPrompt?: string, claude?: ClaudeConfiguration): Promise<{
|
|
13
|
+
sessionId: string;
|
|
14
|
+
capabilities: {
|
|
15
|
+
resume: boolean;
|
|
16
|
+
load: boolean;
|
|
17
|
+
close: boolean;
|
|
18
|
+
};
|
|
19
|
+
signal: AbortSignal;
|
|
20
|
+
close: () => Promise<void>;
|
|
21
|
+
images: boolean;
|
|
22
|
+
systemPrompt: boolean;
|
|
23
|
+
selection: () => AcpModelSelection;
|
|
24
|
+
configure(requested: AgentOptions): Promise<AcpModelSelection>;
|
|
25
|
+
prompt(content: acp.ContentBlock[]): Promise<acp.PromptResponse>;
|
|
26
|
+
cancel(): Promise<void>;
|
|
27
|
+
}>;
|