personal-bot 0.2.10 → 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 +21 -3
- 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/python/README.md +3 -3
- package/resources/skills/.claude-plugin/plugin.json +4 -0
- package/scripts/README.md +6 -0
- package/scripts/setup-python.py +33 -7
- 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
|
@@ -2,6 +2,9 @@ import { realpath } from "node:fs/promises";
|
|
|
2
2
|
import { dshHomePath } from "@deepseek-ai/dsh-home-paths";
|
|
3
3
|
import type { Agent } from "@deepseek-ai/dsh-agent";
|
|
4
4
|
import type { Context } from "@deepseek-ai/cordis";
|
|
5
|
+
import type { FileBlock, ImageBlock } from "@deepseek-ai/dsh-llm";
|
|
6
|
+
import { AgentBackends } from "../../integrations/acp/agents.js";
|
|
7
|
+
import type { AcpCommands } from "../../model/acp.js";
|
|
5
8
|
import type { AgentOwner } from "../../model/agent.js";
|
|
6
9
|
import { DshAgents } from "../../integrations/dsh/dsh-agents.js";
|
|
7
10
|
import { dshResources, dshExpertTools } from "../../integrations/dsh/resources.js";
|
|
@@ -38,7 +41,7 @@ export class DshWorkspace {
|
|
|
38
41
|
#closing: Promise<void> | undefined;
|
|
39
42
|
constructor(readonly ctx: Context, readonly root: string, readonly agent: Agent,
|
|
40
43
|
readonly python: PythonEnvironmentService, readonly component: AbortSignal,
|
|
41
|
-
private readonly historyWork: DshHistoryWork, private readonly releaseHistory: () => Promise<void
|
|
44
|
+
private readonly historyWork: DshHistoryWork, private readonly releaseHistory: () => Promise<void>, acp?: AcpCommands) {
|
|
42
45
|
this.history = historyWork.service;
|
|
43
46
|
this.owner = { sessionId: agent.id, leaf: null, branch: [] };
|
|
44
47
|
this.host = new DshAgents(ctx, agent, {
|
|
@@ -64,7 +67,8 @@ export class DshWorkspace {
|
|
|
64
67
|
},
|
|
65
68
|
stopping: async (child, generation) => { const runtime = this.#experts.get(child.id); if (runtime?.generation === generation) await runtime.stop(); },
|
|
66
69
|
}, this.lifetime.signal);
|
|
67
|
-
|
|
70
|
+
const directory = dshHomePath("pbot", "subagents");
|
|
71
|
+
this.agents = new AgentService(root, directory, new AgentBackends(this.host, directory, acp));
|
|
68
72
|
this.teams = new TeamService(root, this.agents.files, this.agents.teamFiles);
|
|
69
73
|
}
|
|
70
74
|
check = () => { this.component.throwIfAborted(); this.lifetime.signal.throwIfAborted(); };
|
|
@@ -85,6 +89,20 @@ export class DshWorkspace {
|
|
|
85
89
|
} });
|
|
86
90
|
this.check();
|
|
87
91
|
}
|
|
92
|
+
async interact(id: string, text: string, delivery: "steer" | "followUp" | undefined, files: readonly string[] = [],
|
|
93
|
+
attachments: readonly (ImageBlock | FileBlock)[] = [], signal: AbortSignal) {
|
|
94
|
+
const view = this.agents.status(id, this.owner);
|
|
95
|
+
if (view.transport !== "acp") return this.expert(id).interact(text, delivery, files, attachments, signal);
|
|
96
|
+
this.check(); signal.throwIfAborted();
|
|
97
|
+
requireThat(text.length <= 24000 && files.length + attachments.length <= 32 && (!files.length || !attachments.length), "人工消息或附件参数无效。");
|
|
98
|
+
const paths = [...files, ...attachments.map(attachment => {
|
|
99
|
+
const path = attachment.type === "image" ? this.ctx.attachments.imageHostPath(attachment.attachment) : this.ctx.attachments.fileHostPath(attachment.attachment);
|
|
100
|
+
requireThat(path, "该原生附件存储不提供 ACP 子进程可读取的文件路径。"); return path;
|
|
101
|
+
})];
|
|
102
|
+
requireThat(text.trim() || paths.length, "请输入消息或附加文件。");
|
|
103
|
+
this.teams.pauseMember(id, "成员由人工接管");
|
|
104
|
+
return this.agents.send(id, text || "请处理所附文件。", delivery ?? "followUp", this.owner, paths);
|
|
105
|
+
}
|
|
88
106
|
expert(id: string) {
|
|
89
107
|
this.check(); const view = this.agents.status(id, this.owner), runtime = this.#experts.get(id);
|
|
90
108
|
requireThat(view.owned, "专家不属于当前父会话。");
|
|
@@ -166,7 +184,7 @@ export class DshWorkspaces {
|
|
|
166
184
|
const history = await this.history(root);
|
|
167
185
|
let workspace: DshWorkspace | undefined;
|
|
168
186
|
try {
|
|
169
|
-
workspace = new DshWorkspace(this.ctx, root, agent, this.python, this.#lifetime.signal, history.work, history.release);
|
|
187
|
+
workspace = new DshWorkspace(this.ctx, root, agent, this.python, this.#lifetime.signal, history.work, history.release, configuration.acp);
|
|
170
188
|
const owned = workspace;
|
|
171
189
|
const dispose = agent.ctx.effect(() => async () => {
|
|
172
190
|
this.#parents.delete(agent); this.#configurations.delete(agent); this.#parentEffects.delete(agent); await owned.close();
|
|
@@ -66,7 +66,7 @@ export class Lifecycle {
|
|
|
66
66
|
#active: WorkspaceInstance | undefined;
|
|
67
67
|
configuration: WorkspaceConfiguration | undefined;
|
|
68
68
|
root: string | undefined;
|
|
69
|
-
constructor(private readonly create: (root: string) => WorkspaceInstance,
|
|
69
|
+
constructor(private readonly create: (root: string, configuration: WorkspaceConfiguration) => WorkspaceInstance,
|
|
70
70
|
private readonly register: (instance: WorkspaceInstance) => void, private readonly hide: () => void) {}
|
|
71
71
|
get active() { return this.#active; }
|
|
72
72
|
get() {
|
|
@@ -78,7 +78,7 @@ export class Lifecycle {
|
|
|
78
78
|
this.root = await realpath(root);
|
|
79
79
|
this.configuration = await readWorkspaceConfig(this.root);
|
|
80
80
|
if (!this.configuration.enabled) return;
|
|
81
|
-
const instance = this.create(this.root);
|
|
81
|
+
const instance = this.create(this.root, this.configuration);
|
|
82
82
|
this.#active = instance;
|
|
83
83
|
try { this.register(instance); }
|
|
84
84
|
catch (error) { await this.close(); throw error; }
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import type { AcpInput } from "../model/acp.js";
|
|
6
|
+
import { acpMember } from "./acp-member.js";
|
|
7
|
+
import { agentFileTools } from "../integrations/pi/agent-tools.js";
|
|
8
|
+
import { authorizeMutation } from "../services/workspace/workspace-files.js";
|
|
9
|
+
import { resourceRoot } from "../common/paths.js";
|
|
10
|
+
import { launch } from "../storage/agent-files.js";
|
|
11
|
+
import { requireThat } from "../common/validation.js";
|
|
12
|
+
|
|
13
|
+
/** Member resources and authoritative final answers; ACP owns input delivery. */
|
|
14
|
+
export default async function piAcpMember(pi: ExtensionAPI) {
|
|
15
|
+
const member = await acpMember(), lifetime = new AbortController();
|
|
16
|
+
let input: AcpInput | undefined, startLeaf: string | null = null;
|
|
17
|
+
const checkSession = (ctx: ExtensionContext) => {
|
|
18
|
+
const reference = member.files.reference(member.id);
|
|
19
|
+
requireThat(reference.host === "acp" && reference.backend === "pi" && realpathSync(ctx.cwd) === member.d.cwd &&
|
|
20
|
+
(reference.sessionId === null || reference.sessionId === ctx.sessionManager.getSessionId()), "Pi ACP 会话身份或工作目录不匹配。");
|
|
21
|
+
};
|
|
22
|
+
pi.on("resources_discover", async () => {
|
|
23
|
+
if (member.d.options.noSkills) return {};
|
|
24
|
+
const skillPaths = [join(resourceRoot, "skills")], workspaceSkills = join(member.d.workspace, ".agents/skills");
|
|
25
|
+
try { if ((await stat(workspaceSkills)).isDirectory()) skillPaths.push(workspaceSkills); }
|
|
26
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
27
|
+
return { skillPaths };
|
|
28
|
+
});
|
|
29
|
+
pi.on("session_start", (_event, ctx) => {
|
|
30
|
+
checkSession(ctx);
|
|
31
|
+
const active = pi.getActiveTools();
|
|
32
|
+
for (const tool of agentFileTools(member.d.cwd, lifetime.signal, async (path, change, signal) => {
|
|
33
|
+
member.check(); await authorizeMutation(member.d.workspace, path, change, async () => false, signal); member.check();
|
|
34
|
+
})) pi.registerTool(tool);
|
|
35
|
+
pi.setActiveTools(active.filter(name => !["pbot_agent", "pbot_team", "pbot_history"].includes(name)));
|
|
36
|
+
pi.setSessionName(member.files.read(member.id, "launch.json", launch).name);
|
|
37
|
+
startLeaf = ctx.sessionManager.getLeafId();
|
|
38
|
+
});
|
|
39
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
40
|
+
try {
|
|
41
|
+
checkSession(ctx);
|
|
42
|
+
const current = member.input();
|
|
43
|
+
if (current.requestId !== input?.requestId) { input = current; startLeaf = ctx.sessionManager.getLeafId(); }
|
|
44
|
+
const context = await member.context(); member.check();
|
|
45
|
+
Object.assign(event.systemPromptOptions.sections, { pbot_workspace: context.workspace, pbot_child: context.role, pbot_environment: context.environment });
|
|
46
|
+
} catch (error) { ctx.abort(); throw error; }
|
|
47
|
+
});
|
|
48
|
+
pi.on("tool_call", event => {
|
|
49
|
+
member.check();
|
|
50
|
+
if (["pbot_agent", "pbot_team", "pbot_history"].includes(event.toolName)) return { block: true, reason: "专家不提供协调管理工具。" };
|
|
51
|
+
return;
|
|
52
|
+
});
|
|
53
|
+
pi.on("agent_settled", (event, ctx) => {
|
|
54
|
+
if (!input) return;
|
|
55
|
+
const branch = ctx.sessionManager.getBranch(), at = startLeaf === null ? -1 : branch.findIndex(entry => entry.id === startLeaf);
|
|
56
|
+
const last = branch.slice(at + 1).findLast(entry => entry.type === "message" && entry.message.role === "assistant");
|
|
57
|
+
const assistant = last?.type === "message" && last.message.role === "assistant" ? last.message : undefined;
|
|
58
|
+
const answer = assistant?.content.filter(block => block.type === "text").map(block => block.text).join("\n") ?? "";
|
|
59
|
+
member.answer(input, event.aborted ? "cancelled" : assistant?.stopReason === "stop" ? "completed" : "failed", answer, assistant?.errorMessage);
|
|
60
|
+
});
|
|
61
|
+
pi.on("session_before_switch", () => ({ cancel: true }));
|
|
62
|
+
pi.on("session_before_fork", () => ({ cancel: true }));
|
|
63
|
+
pi.on("session_shutdown", () => { lifetime.abort(); });
|
|
64
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
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 type { AgentHost } from "../../services/agents/agent-service.js";
|
|
6
|
+
import type { AgentDescriptor, AgentOptions, AgentSessionReference } from "../../model/agent.js";
|
|
7
|
+
import type { AcpBackend, AcpCommands } from "../../model/acp.js";
|
|
8
|
+
import { AgentFiles, launch } from "../../storage/agent-files.js";
|
|
9
|
+
import { acpInput, acpProcess, acpReference, acpReport } from "../../storage/acp-files.js";
|
|
10
|
+
import { fileId } from "../../storage/file-access.js";
|
|
11
|
+
import { requireThat } from "../../common/validation.js";
|
|
12
|
+
import { resourceRoot } from "../../common/paths.js";
|
|
13
|
+
import { acpLaunch } from "./launch.js";
|
|
14
|
+
|
|
15
|
+
/** Select the native strategy or one of the three explicit ACP targets per member. */
|
|
16
|
+
export class AgentBackends implements AgentHost {
|
|
17
|
+
readonly kind;
|
|
18
|
+
readonly files: AgentFiles;
|
|
19
|
+
readonly worker = resolve(resourceRoot, "../lib/extension/acp-worker.js");
|
|
20
|
+
constructor(readonly native: AgentHost, directory: string, readonly commands: AcpCommands = {}) {
|
|
21
|
+
this.kind = native.kind; this.files = new AgentFiles(directory, native.kind);
|
|
22
|
+
}
|
|
23
|
+
available(backend?: AcpBackend) {
|
|
24
|
+
if (!backend) return this.native.available();
|
|
25
|
+
requireThat(process.platform === "linux" || process.platform === "darwin", "ACP worker 当前支持 Linux 和 macOS。");
|
|
26
|
+
requireThat(existsSync(this.worker), "缺少 ACP worker 构建产物;请先运行 npm run build。");
|
|
27
|
+
}
|
|
28
|
+
prepare(backend: AcpBackend, options: AgentOptions) { return acpLaunch(backend, this.commands, options); }
|
|
29
|
+
validateOptions(options: AgentOptions, backend?: AcpBackend) {
|
|
30
|
+
if (backend) this.prepare(backend, options); else this.native.validateOptions?.(options);
|
|
31
|
+
}
|
|
32
|
+
private isAcp(id: string) { return Boolean(this.files.optional(id, "acp-session.json", acpReference)); }
|
|
33
|
+
private process(id: string) {
|
|
34
|
+
const record = this.files.optional(id, "acp-process.json", acpProcess);
|
|
35
|
+
if (!record || this.files.read(id, "launch.json", launch).generation !== record.generation) return;
|
|
36
|
+
let denied = false;
|
|
37
|
+
try { process.kill(-record.pid, 0); }
|
|
38
|
+
catch (error) {
|
|
39
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
40
|
+
if (code === "ESRCH") return;
|
|
41
|
+
if (code !== "EPERM") throw error;
|
|
42
|
+
denied = true;
|
|
43
|
+
}
|
|
44
|
+
const leader = spawnSync("ps", ["-p", String(record.pid), "-o", "args="], { encoding: "utf8" });
|
|
45
|
+
// A dead leader can leave its group alive. A reused leader must match our exact launch identity.
|
|
46
|
+
if (leader.status === 0 && !leader.stdout.includes("--pbot-acp-agent " + id + " --generation " + record.generation) || denied && leader.status !== 0) return;
|
|
47
|
+
return record;
|
|
48
|
+
}
|
|
49
|
+
alive(id: string) { return this.isAcp(id) ? Boolean(this.process(id)) : this.native.alive(id); }
|
|
50
|
+
async validateSession(d: AgentDescriptor, reference: AgentSessionReference) {
|
|
51
|
+
if (reference.host !== "acp") return this.native.validateSession(d, reference);
|
|
52
|
+
requireThat(!this.alive(d.agentId), "ACP 成员仍在运行,不能恢复。");
|
|
53
|
+
if (reference.sessionId === null) {
|
|
54
|
+
requireThat(!this.files.optional(d.agentId, "acp-input.json", acpInput), "ACP 输入交付状态不明;请核对原请求后新建成员。");
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const generation = this.files.read(d.agentId, "launch.json", launch).generation;
|
|
58
|
+
await new Promise<void>((resolveResult, reject) => {
|
|
59
|
+
const child = this.spawn(d, generation, true);
|
|
60
|
+
let validated = false, failure: Error | undefined;
|
|
61
|
+
const timer = setTimeout(() => {
|
|
62
|
+
failure = new Error("ACP 恢复校验超时。");
|
|
63
|
+
if (child.pid) { try { process.kill(-child.pid, "SIGKILL"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") reject(error); } }
|
|
64
|
+
}, 45_000);
|
|
65
|
+
child.on("message", (message: { type?: string; error?: string }) => {
|
|
66
|
+
if (message.type === "validated") validated = true;
|
|
67
|
+
if (message.type === "error") failure = new Error(message.error ?? "ACP 恢复校验失败。");
|
|
68
|
+
});
|
|
69
|
+
child.once("error", error => { failure = error; });
|
|
70
|
+
child.once("close", code => { clearTimeout(timer); if (validated && code === 0 && !failure) resolveResult(); else reject(failure ?? new Error("ACP 恢复校验失败;原代次和队列已保留。")); });
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
private spawn(d: AgentDescriptor, generation: string, validate = false) {
|
|
74
|
+
const child = fork(this.worker, ["--pbot-acp-agent", d.agentId, "--generation", generation, "--directory", this.files.directory(d.agentId),
|
|
75
|
+
"--host", this.kind, ...(validate ? ["--validate"] : [])], {
|
|
76
|
+
cwd: d.cwd, env: { ...process.env }, detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"], execArgv: [],
|
|
77
|
+
});
|
|
78
|
+
return child;
|
|
79
|
+
}
|
|
80
|
+
async launch(d: AgentDescriptor, directory: string, generation: string, reference: AgentSessionReference, resume: boolean, signal: AbortSignal) {
|
|
81
|
+
if (reference.host !== "acp") return this.native.launch(d, directory, generation, reference, resume, signal);
|
|
82
|
+
signal.throwIfAborted();
|
|
83
|
+
const child = this.spawn(d, generation);
|
|
84
|
+
await new Promise<void>((resolveResult, reject) => { child.once("spawn", resolveResult); child.once("error", reject); });
|
|
85
|
+
requireThat(child.pid, "ACP worker 没有进程身份。");
|
|
86
|
+
try { this.files.write(d.agentId, "acp-process.json", { generation, pid: child.pid, startedAt: Date.now() }, acpProcess); }
|
|
87
|
+
catch (error) {
|
|
88
|
+
try { process.kill(-child.pid, "SIGKILL"); } catch (failure) { if ((failure as NodeJS.ErrnoException).code !== "ESRCH") throw new AggregateError([error, failure], "ACP 启动与清理失败。"); }
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
if (child.connected) child.disconnect(); child.unref();
|
|
92
|
+
if (signal.aborted) { await this.release(d.agentId, generation); signal.throwIfAborted(); }
|
|
93
|
+
}
|
|
94
|
+
async release(id: string, generation: string) {
|
|
95
|
+
if (!this.isAcp(id)) return this.native.release(id, generation);
|
|
96
|
+
const record = this.process(id);
|
|
97
|
+
if (!record || record.generation !== generation) return;
|
|
98
|
+
const terminate = (signal: NodeJS.Signals) => {
|
|
99
|
+
try { process.kill(-record.pid, signal); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
|
|
100
|
+
};
|
|
101
|
+
terminate("SIGTERM");
|
|
102
|
+
const deadline = Date.now() + 4500;
|
|
103
|
+
while (Date.now() < deadline) {
|
|
104
|
+
const current = this.process(id);
|
|
105
|
+
if (!current || current.generation !== generation || current.pid !== record.pid) return;
|
|
106
|
+
await delay(100);
|
|
107
|
+
}
|
|
108
|
+
const current = this.process(id);
|
|
109
|
+
if (current?.generation === generation && current.pid === record.pid) terminate("SIGKILL");
|
|
110
|
+
}
|
|
111
|
+
report(d: AgentDescriptor, reference: AgentSessionReference, leaf: string) {
|
|
112
|
+
if (reference.host !== "acp") return this.native.report(d, reference, leaf);
|
|
113
|
+
requireThat(leaf.startsWith("acp:"), "ACP 报告引用无效。");
|
|
114
|
+
const cycleId = fileId(leaf.slice(4)), report = this.files.read(d.agentId, join("reports", cycleId + ".json"), acpReport);
|
|
115
|
+
requireThat(report.cycleId === cycleId, "ACP 报告周期不匹配。");
|
|
116
|
+
return report.text;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { basename, join, resolve } from "node:path";
|
|
4
|
+
import type { AcpCommand } from "../../model/acp.js";
|
|
5
|
+
import { object } from "../../common/json.js";
|
|
6
|
+
import { requireThat } from "../../common/validation.js";
|
|
7
|
+
import { resourceRoot } from "../../common/paths.js";
|
|
8
|
+
|
|
9
|
+
const levels = ["low", "medium", "high", "xhigh", "max"];
|
|
10
|
+
export interface ClaudeConfiguration {
|
|
11
|
+
thinking?: string;
|
|
12
|
+
options: { plugins: { type: "local"; path: string }[]; effort?: string; settings?: { env: { CLAUDE_CODE_EFFORT_LEVEL: string } } };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Read the target installation's native settings without creating a model session. */
|
|
16
|
+
export async function claudeOptions(command: AcpCommand, cwd: string, requested?: string): Promise<ClaudeConfiguration> {
|
|
17
|
+
const script = command.args[0];
|
|
18
|
+
const anchor = ["node", "node.exe"].includes(basename(command.command)) && script && !script.startsWith("-") ? resolve(cwd, script) : command.command;
|
|
19
|
+
const require = createRequire(pathToFileURL(anchor));
|
|
20
|
+
const sdk: unknown = await import(pathToFileURL(require.resolve("@anthropic-ai/claude-agent-sdk")).href);
|
|
21
|
+
requireThat(object(sdk) && typeof sdk.resolveSettings === "function", "Claude ACP 需要提供 resolveSettings 的原生 SDK。");
|
|
22
|
+
const resolved: unknown = await sdk.resolveSettings({ cwd });
|
|
23
|
+
requireThat(object(resolved) && object(resolved.effective), "Claude 原生设置解析失败。");
|
|
24
|
+
const environment = object(resolved.effective.env) ? resolved.effective.env : {};
|
|
25
|
+
const configured = environment.CLAUDE_CODE_EFFORT_LEVEL ?? process.env.CLAUDE_CODE_EFFORT_LEVEL;
|
|
26
|
+
const explicit = requested !== undefined && requested !== "default";
|
|
27
|
+
requireThat(!explicit || levels.includes(requested), "Claude 思考等级不可用:" + requested);
|
|
28
|
+
const effort = explicit ? requested : typeof configured === "string" && levels.includes(configured) ? configured : undefined;
|
|
29
|
+
const thinking = effort ?? (configured === "unset" ? "unset" : undefined);
|
|
30
|
+
return {
|
|
31
|
+
...(thinking ? { thinking } : {}),
|
|
32
|
+
options: {
|
|
33
|
+
plugins: [{ type: "local", path: join(resourceRoot, "skills") }],
|
|
34
|
+
...(effort ? { effort } : {}),
|
|
35
|
+
// SDK effort alone loses to CLAUDE_CODE_EFFORT_LEVEL. A flag-tier env entry
|
|
36
|
+
// applies the explicit choice to this invocation and preserves other settings.
|
|
37
|
+
...(explicit ? { settings: { env: { CLAUDE_CODE_EFFORT_LEVEL: requested } } } : {}),
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { Readable, Writable } from "node:stream";
|
|
3
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
+
import * as acp from "@agentclientprotocol/sdk";
|
|
5
|
+
import type { AcpModelSelection, AcpSessionReference } from "../../model/acp.js";
|
|
6
|
+
import type { AgentOptions } from "../../model/agent.js";
|
|
7
|
+
import { requireThat } from "../../common/validation.js";
|
|
8
|
+
import { packageVersion } from "../../common/version.js";
|
|
9
|
+
import { acpModelSelection, acpModelValue, acpThinkingValue } from "./model-selection.js";
|
|
10
|
+
import type { ClaudeConfiguration } from "./claude.js";
|
|
11
|
+
import { object } from "../../common/json.js";
|
|
12
|
+
|
|
13
|
+
export function acpFailure(error: unknown): unknown {
|
|
14
|
+
return error instanceof acp.RequestError && error.data !== undefined
|
|
15
|
+
? new Error(error.message + ":" + JSON.stringify(error.data), { cause: error }) : error;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface AcpCallbacks {
|
|
19
|
+
update(update: acp.SessionUpdate): void | Promise<void>;
|
|
20
|
+
selection?(selection: AcpModelSelection): void;
|
|
21
|
+
permission(request: acp.RequestPermissionRequest, signal: AbortSignal): Promise<acp.RequestPermissionResponse>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** One ACP v1 connection. The worker owns its process group and business state. */
|
|
25
|
+
export async function openAcp(reference: AcpSessionReference, cwd: string, env: NodeJS.ProcessEnv,
|
|
26
|
+
callbacks: AcpCallbacks, signal: AbortSignal, systemPrompt?: string, claude?: ClaudeConfiguration) {
|
|
27
|
+
signal.throwIfAborted();
|
|
28
|
+
const child = spawn(reference.command, reference.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] });
|
|
29
|
+
const lifetime = new AbortController();
|
|
30
|
+
const cancel = AbortSignal.any([signal, lifetime.signal]);
|
|
31
|
+
const exited = new Promise<void>(resolve => child.once("close", () => resolve()));
|
|
32
|
+
child.once("error", error => lifetime.abort(error));
|
|
33
|
+
child.once("exit", (code, termination) => lifetime.abort(new Error("ACP 进程退出:" + (termination ?? code))));
|
|
34
|
+
child.stderr.resume();
|
|
35
|
+
child.stdin.on("error", () => {});
|
|
36
|
+
let sessionId: string | undefined;
|
|
37
|
+
let options: acp.SessionConfigOption[] = [];
|
|
38
|
+
let resolvedModel: string | undefined;
|
|
39
|
+
const selection = (): AcpModelSelection => ({ ...acpModelSelection(reference.backend, options, claude?.thinking),
|
|
40
|
+
...(resolvedModel ? { resolvedModel } : {}) });
|
|
41
|
+
let updating = Promise.resolve();
|
|
42
|
+
const app = acp.client({ name: "personal-bot" })
|
|
43
|
+
.onRequest(acp.methods.client.session.requestPermission, async ctx => {
|
|
44
|
+
if (cancel.aborted || ctx.params.sessionId !== sessionId) return { outcome: { outcome: "cancelled" as const } };
|
|
45
|
+
return callbacks.permission(ctx.params, cancel);
|
|
46
|
+
})
|
|
47
|
+
.onNotification(acp.methods.client.session.update, ctx => {
|
|
48
|
+
// Load may replay before its response. Output from replay never becomes a new report.
|
|
49
|
+
if (ctx.params.sessionId !== sessionId || cancel.aborted) return;
|
|
50
|
+
updating = updating.then(async () => {
|
|
51
|
+
if (ctx.params.update.sessionUpdate === "config_option_update") {
|
|
52
|
+
const before = acpModelSelection(reference.backend, options);
|
|
53
|
+
options = ctx.params.update.configOptions;
|
|
54
|
+
if (acpModelSelection(reference.backend, options).model !== before.model) resolvedModel = undefined;
|
|
55
|
+
callbacks.selection?.(selection());
|
|
56
|
+
}
|
|
57
|
+
await callbacks.update(ctx.params.update);
|
|
58
|
+
});
|
|
59
|
+
void updating.catch(error => lifetime.abort(error));
|
|
60
|
+
return updating;
|
|
61
|
+
})
|
|
62
|
+
.onNotification("_claude/sdkMessage", (value: unknown) => value, ctx => {
|
|
63
|
+
if (reference.backend !== "claude" || !object(ctx.params) || ctx.params.sessionId !== sessionId || cancel.aborted) return;
|
|
64
|
+
const message = ctx.params.message;
|
|
65
|
+
if (!object(message) || message.type !== "system" || message.subtype !== "init" || typeof message.model !== "string" || !message.model) return;
|
|
66
|
+
const model = message.model;
|
|
67
|
+
updating = updating.then(() => { resolvedModel = model; callbacks.selection?.(selection()); });
|
|
68
|
+
void updating.catch(error => lifetime.abort(error));
|
|
69
|
+
return updating;
|
|
70
|
+
});
|
|
71
|
+
const connection = await app.connect(acp.ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>, { maxMessageBytes: 8 * 1024 * 1024 }));
|
|
72
|
+
const abort = () => connection.close(cancel.reason);
|
|
73
|
+
cancel.addEventListener("abort", abort, { once: true });
|
|
74
|
+
if (cancel.aborted) abort();
|
|
75
|
+
const connected = AbortSignal.any([cancel, connection.signal]);
|
|
76
|
+
let closing: Promise<void> | undefined;
|
|
77
|
+
const close = (): Promise<void> => closing ??= (async () => {
|
|
78
|
+
try {
|
|
79
|
+
if (sessionId && initialized?.agentCapabilities?.sessionCapabilities?.close && !connection.signal.aborted) {
|
|
80
|
+
await connection.agent.request(acp.methods.agent.session.close, { sessionId }, { cancellationSignal: AbortSignal.timeout(5000), stopWaitingOnCancel: true });
|
|
81
|
+
}
|
|
82
|
+
} finally {
|
|
83
|
+
cancel.removeEventListener("abort", abort);
|
|
84
|
+
connection.close(); child.stdin.end();
|
|
85
|
+
if (child.exitCode === null) child.kill("SIGTERM");
|
|
86
|
+
const grace = new AbortController();
|
|
87
|
+
try { await Promise.race([exited, delay(1500, undefined, { signal: grace.signal })]); }
|
|
88
|
+
finally { grace.abort(); }
|
|
89
|
+
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
|
90
|
+
child.stdout.destroy(); child.stderr.destroy();
|
|
91
|
+
await exited;
|
|
92
|
+
}
|
|
93
|
+
})();
|
|
94
|
+
let initialized: acp.InitializeResponse | undefined;
|
|
95
|
+
try {
|
|
96
|
+
initialized = await connection.agent.request(acp.methods.agent.initialize, {
|
|
97
|
+
protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "personal-bot", version: packageVersion },
|
|
98
|
+
}, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true });
|
|
99
|
+
requireThat(initialized.protocolVersion === 1, "目标宿主没有协商 ACP v1。");
|
|
100
|
+
const advertised = initialized.agentCapabilities;
|
|
101
|
+
const capabilities = { resume: Boolean(advertised?.sessionCapabilities?.resume), load: advertised?.loadSession === true,
|
|
102
|
+
close: Boolean(advertised?.sessionCapabilities?.close) };
|
|
103
|
+
const setup = { cwd, mcpServers: [],
|
|
104
|
+
...(reference.backend === "claude" ? { _meta: { claudeCode: { options: { ...claude?.options, disallowedTools: ["Agent", "Task"] },
|
|
105
|
+
emitRawSDKMessages: [{ type: "system", subtype: "init" }] } } } : {}), ...(systemPrompt && advertised?.sessionCapabilities?.systemPrompt ? {
|
|
106
|
+
systemPrompt: { mode: "append" as const, content: [{ type: "text" as const, text: systemPrompt }] },
|
|
107
|
+
} : {}) };
|
|
108
|
+
if (reference.sessionId === null) {
|
|
109
|
+
const created = await connection.agent.request<acp.NewSessionResponse>(acp.methods.agent.session.new, setup, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true });
|
|
110
|
+
sessionId = created.sessionId; options = created.configOptions ?? [];
|
|
111
|
+
} else {
|
|
112
|
+
requireThat(capabilities.resume || capabilities.load, "目标 ACP 后端不支持恢复已有会话。");
|
|
113
|
+
const restored = capabilities.resume
|
|
114
|
+
? await connection.agent.request<acp.ResumeSessionResponse>(acp.methods.agent.session.resume, { ...setup, sessionId: reference.sessionId }, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true })
|
|
115
|
+
: await connection.agent.request<acp.LoadSessionResponse>(acp.methods.agent.session.load, { ...setup, sessionId: reference.sessionId }, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true });
|
|
116
|
+
sessionId = reference.sessionId; options = restored.configOptions ?? [];
|
|
117
|
+
}
|
|
118
|
+
requireThat(sessionId, "ACP 后端没有返回会话 ID。");
|
|
119
|
+
const activeId = sessionId;
|
|
120
|
+
return {
|
|
121
|
+
sessionId: activeId, capabilities, signal: connected, close, images: advertised?.promptCapabilities?.image === true,
|
|
122
|
+
systemPrompt: Boolean(advertised?.sessionCapabilities?.systemPrompt),
|
|
123
|
+
selection,
|
|
124
|
+
async configure(requested: AgentOptions) {
|
|
125
|
+
requireThat(!requested.provider || requested.model, "provider 需要同时指定目标 model。");
|
|
126
|
+
for (const kind of ["model", "thinking"] as const) {
|
|
127
|
+
const supplied = requested[kind];
|
|
128
|
+
if (supplied === undefined) continue;
|
|
129
|
+
const chosen = kind === "model" ? acpModelValue(reference.backend, options, supplied, requested.provider) : acpThinkingValue(options, supplied);
|
|
130
|
+
const changed = await connection.agent.request(acp.methods.agent.session.setConfigOption, { sessionId: activeId, ...chosen },
|
|
131
|
+
{ cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true });
|
|
132
|
+
await updating;
|
|
133
|
+
options = changed.configOptions;
|
|
134
|
+
if (kind === "model") resolvedModel = undefined;
|
|
135
|
+
callbacks.selection?.(selection());
|
|
136
|
+
}
|
|
137
|
+
return selection();
|
|
138
|
+
},
|
|
139
|
+
async prompt(content: acp.ContentBlock[]) {
|
|
140
|
+
try {
|
|
141
|
+
const response = await connection.agent.request(acp.methods.agent.session.prompt, { sessionId: activeId, prompt: content });
|
|
142
|
+
await updating; cancel.throwIfAborted(); return response;
|
|
143
|
+
} catch (error) { throw acpFailure(error); }
|
|
144
|
+
},
|
|
145
|
+
async cancel() {
|
|
146
|
+
if (!connection.signal.aborted) await connection.agent.notify(acp.methods.agent.session.cancel, { sessionId: activeId });
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
} catch (error) {
|
|
150
|
+
await close().catch(() => {}); throw acpFailure(error);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { open } from "node:fs/promises";
|
|
3
|
+
import { basename } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import type { ContentBlock } from "@agentclientprotocol/sdk";
|
|
6
|
+
import type { AgentMessage } from "../../model/agent.js";
|
|
7
|
+
import { requireThat } from "../../common/validation.js";
|
|
8
|
+
|
|
9
|
+
/** Local ACP agents can continue reading each absolute source with their native tools. */
|
|
10
|
+
export async function acpContent(request: AgentMessage, images: boolean, signal: AbortSignal): Promise<ContentBlock[]> {
|
|
11
|
+
const content: ContentBlock[] = [{ type: "text", text: request.message }];
|
|
12
|
+
for (const file of request.files) {
|
|
13
|
+
signal.throwIfAborted();
|
|
14
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
15
|
+
try {
|
|
16
|
+
const info = await handle.stat(); requireThat(info.isFile(), "附件必须是普通文件:" + file);
|
|
17
|
+
const prefix = Buffer.alloc(Math.min(info.size, 60000)), read = await handle.read(prefix, 0, prefix.length, 0);
|
|
18
|
+
const bytes = prefix.subarray(0, read.bytesRead);
|
|
19
|
+
const mimeType = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? "image/png"
|
|
20
|
+
: bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 ? "image/jpeg"
|
|
21
|
+
: /^GIF8[79]a$/.test(bytes.toString("ascii", 0, 6)) ? "image/gif"
|
|
22
|
+
: bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP" ? "image/webp" : undefined;
|
|
23
|
+
if (mimeType) {
|
|
24
|
+
requireThat(images, "目标 ACP 会话不支持图片附件。");
|
|
25
|
+
const data = await handle.readFile();
|
|
26
|
+
signal.throwIfAborted();
|
|
27
|
+
content.push({ type: "text", text: "附件来源:" + file }, { type: "image", data: data.toString("base64"), mimeType });
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
let text: string | undefined;
|
|
31
|
+
try { if (!bytes.includes(0)) text = new TextDecoder("utf-8", { fatal: true }).decode(bytes, { stream: info.size > bytes.length }); }
|
|
32
|
+
catch { /* Native tools handle non-text attachments through their source link. */ }
|
|
33
|
+
if (text === undefined) content.push({ type: "resource_link", uri: pathToFileURL(file).href, name: basename(file) });
|
|
34
|
+
else content.push({ type: "text", text: "附件来源:" + file + "\n\n" + text.slice(0, 20000) +
|
|
35
|
+
(info.size > bytes.length || text.length > 20000 ? "\n\n附件已截断,请沿上述路径续读。" : "") });
|
|
36
|
+
} finally { await handle.close(); }
|
|
37
|
+
}
|
|
38
|
+
return content;
|
|
39
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { delimiter, isAbsolute, resolve } from "node:path";
|
|
3
|
+
import { requireThat } from "../../common/validation.js";
|
|
4
|
+
import type { AcpBackend, AcpCommands, AcpSessionReference } from "../../model/acp.js";
|
|
5
|
+
import type { AgentOptions } from "../../model/agent.js";
|
|
6
|
+
|
|
7
|
+
const targets = {
|
|
8
|
+
pi: { command: "pi-acp", args: [], install: "npm install -g pi-acp",
|
|
9
|
+
configure: "Pi 也需已安装;运行 pi 完成登录和默认模型配置。" },
|
|
10
|
+
dsh: { command: "dsh", args: ["--profile", "acp"], install: "npm install -g @deepseek-ai/dsh@latest",
|
|
11
|
+
configure: "按 dsh 原生方式配置目标 profile 的模型与认证。" },
|
|
12
|
+
claude: { command: "claude-agent-acp", args: [], install: "npm install -g @agentclientprotocol/claude-agent-acp",
|
|
13
|
+
configure: "在 Claude Code 中完成登录或 API 配置,并设置默认模型。" },
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export function acpExecutable(command: string, backend: AcpBackend): string {
|
|
17
|
+
const candidates = isAbsolute(command) ? [command] : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map(directory => resolve(directory, command));
|
|
18
|
+
for (const candidate of candidates) {
|
|
19
|
+
try {
|
|
20
|
+
accessSync(candidate, constants.X_OK);
|
|
21
|
+
if (statSync(candidate).isFile()) return realpathSync(candidate);
|
|
22
|
+
} catch (error) { if (!["ENOENT", "ENOTDIR", "EACCES"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; }
|
|
23
|
+
}
|
|
24
|
+
const target = targets[backend], nativePi = backend === "pi" && command === "pi";
|
|
25
|
+
const install = nativePi ? "npm install -g @earendil-works/pi-coding-agent" : target.install;
|
|
26
|
+
const configured = JSON.stringify({ command: "/absolute/path/to/" + target.command, args: target.args });
|
|
27
|
+
const path = nativePi ? "Pi 已安装但 PATH 不可见时,启动主宿主前将 PI_ACP_PI_COMMAND 设置为 pi 的绝对路径。"
|
|
28
|
+
: "已安装但 PATH 不可见时,在 .pbot/config.json 设置 acp." + backend + ":" + configured + ",command 使用实际绝对路径。";
|
|
29
|
+
throw new Error([
|
|
30
|
+
"未找到子代理程序:" + command + "。",
|
|
31
|
+
"在运行 Pi/dsh 的机器上安装:" + install,
|
|
32
|
+
target.configure,
|
|
33
|
+
"检查安装路径:command -v " + (nativePi ? "pi" : target.command) + (!nativePi && backend === "pi" ? ";另用 command -v pi 检查 Pi。" : "。"),
|
|
34
|
+
path,
|
|
35
|
+
"安装后重试原 start 请求;PATH 变化时重启主宿主。配置修改后,Pi 执行 /reload,dsh 重启宿主。",
|
|
36
|
+
].join("\n"));
|
|
37
|
+
}
|
|
38
|
+
export function acpLaunch(backend: AcpBackend, commands: AcpCommands, options: AgentOptions): AcpSessionReference {
|
|
39
|
+
requireThat(["pi", "dsh", "claude"].includes(backend), "未知子代理程序。");
|
|
40
|
+
requireThat(!options.provider || options.model, "provider 需要同时指定目标 model。");
|
|
41
|
+
if (backend !== "pi") for (const key of ["noExtensions", "noPromptTemplates", "noContextFiles"] as const) {
|
|
42
|
+
requireThat(options[key] === undefined, backend + " 子代理不支持启动选项:" + key);
|
|
43
|
+
}
|
|
44
|
+
if (backend === "claude") {
|
|
45
|
+
requireThat(options.noSkills === undefined && options.tools === undefined, "Claude 子代理的技能和工具通过 Claude 原生配置选择。");
|
|
46
|
+
requireThat(options.provider === undefined, "Claude 子代理使用原生提供方配置;请仅指定目标 model。");
|
|
47
|
+
}
|
|
48
|
+
const selected = commands[backend] ?? targets[backend];
|
|
49
|
+
return { host: "acp", backend, command: acpExecutable(selected.command, backend), args: [...selected.args], sessionId: null };
|
|
50
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
|
|
2
|
+
import type { AcpBackend, AcpModelSelection } from "../../model/acp.js";
|
|
3
|
+
import { requireThat } from "../../common/validation.js";
|
|
4
|
+
|
|
5
|
+
type SelectOption = Extract<SessionConfigOption, { type: "select" }>;
|
|
6
|
+
|
|
7
|
+
function optionFor(options: SessionConfigOption[], category: "model" | "thought_level"): SelectOption | undefined {
|
|
8
|
+
const ids = category === "model" ? ["model"] : ["thought_level", "thinking", "reasoning_effort", "effort"];
|
|
9
|
+
return options.find((option): option is SelectOption => option.type === "select" && ids.includes(option.id)) ??
|
|
10
|
+
options.find((option): option is SelectOption => option.type === "select" && option.category === category);
|
|
11
|
+
}
|
|
12
|
+
function values(option: SelectOption) {
|
|
13
|
+
return [...new Map(option.options.flatMap(item => "options" in item ? item.options : [item]).map(item => [item.value, item])).values()];
|
|
14
|
+
}
|
|
15
|
+
function modelIdentity(backend: AcpBackend, value: string): { provider?: string; model: string } {
|
|
16
|
+
if (backend === "dsh") {
|
|
17
|
+
try {
|
|
18
|
+
const parts: unknown = JSON.parse(value);
|
|
19
|
+
if (Array.isArray(parts) && parts.length === 2 && parts.every(part => typeof part === "string" && part.length > 0)) {
|
|
20
|
+
return { provider: parts[0], model: parts[1] };
|
|
21
|
+
}
|
|
22
|
+
} catch { /* Unencoded identifiers remain usable as exact ACP option values. */ }
|
|
23
|
+
}
|
|
24
|
+
if (backend === "pi") {
|
|
25
|
+
const separator = value.indexOf("/");
|
|
26
|
+
if (separator > 0) return { provider: value.slice(0, separator), model: value.slice(separator + 1) };
|
|
27
|
+
}
|
|
28
|
+
return { model: value };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Resolve a native model ID against the peer's advertised values. */
|
|
32
|
+
export function acpModelValue(backend: AcpBackend, options: SessionConfigOption[], model: string, provider?: string) {
|
|
33
|
+
const option = optionFor(options, "model");
|
|
34
|
+
requireThat(option, "ACP 后端未提供可选择的模型。");
|
|
35
|
+
const choices = values(option);
|
|
36
|
+
if (backend === "pi" && provider) {
|
|
37
|
+
const qualified = choices.find(item => item.value === provider + "/" + model);
|
|
38
|
+
if (qualified) return { configId: option.id, value: qualified.value };
|
|
39
|
+
}
|
|
40
|
+
const available = choices.map(item => ({ ...modelIdentity(backend, item.value), value: item.value }));
|
|
41
|
+
let matches = available.filter(item => (item.value === model || item.model === model) && (!provider || item.provider === provider));
|
|
42
|
+
const exact = matches.filter(item => item.value === model);
|
|
43
|
+
if (exact.length) matches = exact;
|
|
44
|
+
if (matches.length > 1 && !provider) {
|
|
45
|
+
const current = modelIdentity(backend, option.currentValue);
|
|
46
|
+
const sameProvider = matches.filter(item => item.provider === current.provider);
|
|
47
|
+
if (sameProvider.length === 1) matches = sameProvider;
|
|
48
|
+
}
|
|
49
|
+
requireThat(matches.length, "ACP 模型不可用:" + [provider, model].filter(Boolean).join("/") + ";可用值:" + available.map(item => item.value).join(", "));
|
|
50
|
+
requireThat(matches.length === 1, "多个 ACP 提供方包含该模型,请指定 provider 或完整模型值:" + matches.map(item => item.value).join(", "));
|
|
51
|
+
return { configId: option.id, value: matches[0]!.value };
|
|
52
|
+
}
|
|
53
|
+
export function acpThinkingValue(options: SessionConfigOption[], thinking: string) {
|
|
54
|
+
const option = optionFor(options, "thought_level");
|
|
55
|
+
requireThat(option, "目标模型未提供可选择的思考等级。");
|
|
56
|
+
const available = values(option);
|
|
57
|
+
const chosen = available.find(item => item.value === thinking);
|
|
58
|
+
requireThat(chosen, "ACP 思考等级不可用:" + thinking + ";可用值:" + available.map(item => item.value).join(", "));
|
|
59
|
+
return { configId: option.id, value: chosen.value };
|
|
60
|
+
}
|
|
61
|
+
export function acpModelSelection(backend: AcpBackend, options: SessionConfigOption[], effectiveThinking?: string): AcpModelSelection {
|
|
62
|
+
const model = optionFor(options, "model"), thinking = optionFor(options, "thought_level");
|
|
63
|
+
const selectedThinking = effectiveThinking === "unset" ? effectiveThinking
|
|
64
|
+
: thinking && effectiveThinking && values(thinking).some(item => item.value === effectiveThinking) ? effectiveThinking : thinking?.currentValue;
|
|
65
|
+
return { ...(model ? modelIdentity(backend, model.currentValue) : {}), ...(selectedThinking ? { thinking: selectedThinking } : {}) };
|
|
66
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Context } from "@deepseek-ai/cordis";
|
|
2
2
|
import type { Agent, AgentHandle, AgentSetup } from "@deepseek-ai/dsh-agent";
|
|
3
3
|
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
4
|
-
import type { AgentDescriptor, AgentSessionReference } from "../../model/agent.js";
|
|
4
|
+
import type { AgentDescriptor, AgentOptions, AgentSessionReference } from "../../model/agent.js";
|
|
5
5
|
import type { AgentHost } from "../../services/agents/agent-service.js";
|
|
6
6
|
import { requireThat } from "../../common/validation.js";
|
|
7
7
|
import { openDshAgent, readDshAgentSession, readDshReport } from "./session.js";
|
|
@@ -25,6 +25,9 @@ export class DshAgents implements AgentHost {
|
|
|
25
25
|
ready(agent: Agent, generation: string): void;
|
|
26
26
|
stopping(agent: Agent, generation: string): Promise<void>;
|
|
27
27
|
}, readonly lifetime: AbortSignal) {}
|
|
28
|
+
validateOptions(options: AgentOptions) {
|
|
29
|
+
for (const key of ["noExtensions", "noPromptTemplates", "noContextFiles"] as const) requireThat(options[key] === undefined, "dsh 不支持宿主选项:" + key);
|
|
30
|
+
}
|
|
28
31
|
available() {
|
|
29
32
|
this.lifetime.throwIfAborted();
|
|
30
33
|
requireThat(!this.#closed && this.ctx.agents.get(this.parent.id) === this.parent, "dsh 父会话或执行组件已关闭。");
|