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.
Files changed (95) hide show
  1. package/README.md +17 -3
  2. package/README.zh-CN.md +17 -3
  3. package/bin/pbot-pi-acp.mjs +20 -0
  4. package/docs/agent-collaboration.md +38 -2
  5. package/docs/capability-design.md +6 -0
  6. package/docs/dsh.md +9 -8
  7. package/docs/file-storage.md +9 -1
  8. package/docs/interaction-design.md +2 -2
  9. package/docs/model-context.md +10 -2
  10. package/docs/technical-design.md +20 -2
  11. package/docs/workspace-configuration.md +20 -1
  12. package/lib/client.js +40 -7
  13. package/lib/dsh.js +2 -0
  14. package/lib/extension/acp-member.d.ts +16 -0
  15. package/lib/extension/acp-member.js +45 -0
  16. package/lib/extension/acp-worker.d.ts +1 -0
  17. package/lib/extension/acp-worker.js +156 -0
  18. package/lib/extension/dsh/acp-member.d.ts +4 -0
  19. package/lib/extension/dsh/acp-member.js +48 -0
  20. package/lib/extension/dsh/command.js +11 -1
  21. package/lib/extension/dsh/management.js +3 -1
  22. package/lib/extension/dsh/workspace.d.ts +35 -1
  23. package/lib/extension/dsh/workspace.js +21 -3
  24. package/lib/integrations/acp/agents.d.ts +24 -0
  25. package/lib/integrations/acp/agents.js +168 -0
  26. package/lib/integrations/acp/claude.d.ts +18 -0
  27. package/lib/integrations/acp/claude.js +33 -0
  28. package/lib/integrations/acp/connection.d.ts +27 -0
  29. package/lib/integrations/acp/connection.js +167 -0
  30. package/lib/integrations/acp/input.d.ts +4 -0
  31. package/lib/integrations/acp/input.js +45 -0
  32. package/lib/integrations/acp/launch.d.ts +4 -0
  33. package/lib/integrations/acp/launch.js +52 -0
  34. package/lib/integrations/acp/model-selection.d.ts +12 -0
  35. package/lib/integrations/acp/model-selection.js +65 -0
  36. package/lib/integrations/dsh/dsh-agents.d.ts +2 -1
  37. package/lib/integrations/dsh/dsh-agents.js +4 -0
  38. package/lib/model/acp.d.ts +59 -0
  39. package/lib/model/acp.js +1 -0
  40. package/lib/model/agent.d.ts +15 -1
  41. package/lib/model/workspace-config.d.ts +3 -0
  42. package/lib/services/agents/acp-run.d.ts +42 -0
  43. package/lib/services/agents/acp-run.js +149 -0
  44. package/lib/services/agents/agent-service.d.ts +114 -6
  45. package/lib/services/agents/agent-service.js +81 -10
  46. package/lib/services/agents/team-service.js +4 -2
  47. package/lib/services/workspace/workspace-config.js +12 -1
  48. package/lib/storage/acp-files.d.ts +9 -0
  49. package/lib/storage/acp-files.js +50 -0
  50. package/lib/storage/agent-files.d.ts +5 -4
  51. package/lib/storage/agent-files.js +11 -2
  52. package/lib/tools/agents/actions.d.ts +16 -2
  53. package/lib/tools/agents/actions.js +3 -1
  54. package/lib/tools/agents/contract.d.ts +48 -3
  55. package/lib/tools/agents/contract.js +15 -9
  56. package/lib/tools/agents/dsh-contract.d.ts +8 -15
  57. package/lib/tools/agents/dsh-contract.js +12 -8
  58. package/lib/ui/dsh/management.js +36 -8
  59. package/npm-shrinkwrap.json +953 -12
  60. package/package.json +8 -1
  61. package/resources/skills/.claude-plugin/plugin.json +4 -0
  62. package/scripts/README.md +6 -0
  63. package/src/dsh.ts +1 -0
  64. package/src/extension/acp-member.ts +44 -0
  65. package/src/extension/acp-worker.ts +124 -0
  66. package/src/extension/agent-events.ts +28 -3
  67. package/src/extension/agents-command.ts +33 -5
  68. package/src/extension/dsh/acp-member.ts +44 -0
  69. package/src/extension/dsh/command.ts +10 -1
  70. package/src/extension/dsh/management.ts +2 -1
  71. package/src/extension/dsh/workspace.ts +21 -3
  72. package/src/extension/lifecycle.ts +2 -2
  73. package/src/extension/pi-acp-member.ts +64 -0
  74. package/src/integrations/acp/agents.ts +118 -0
  75. package/src/integrations/acp/claude.ts +40 -0
  76. package/src/integrations/acp/connection.ts +152 -0
  77. package/src/integrations/acp/input.ts +39 -0
  78. package/src/integrations/acp/launch.ts +50 -0
  79. package/src/integrations/acp/model-selection.ts +66 -0
  80. package/src/integrations/dsh/dsh-agents.ts +4 -1
  81. package/src/integrations/pi/pi-agents.ts +4 -1
  82. package/src/model/acp.ts +26 -0
  83. package/src/model/agent.ts +7 -1
  84. package/src/model/workspace-config.ts +4 -0
  85. package/src/pbot.ts +3 -2
  86. package/src/services/agents/acp-run.ts +123 -0
  87. package/src/services/agents/agent-service.ts +85 -12
  88. package/src/services/agents/team-service.ts +3 -2
  89. package/src/services/workspace/workspace-config.ts +10 -1
  90. package/src/storage/acp-files.ts +50 -0
  91. package/src/storage/agent-files.ts +12 -4
  92. package/src/tools/agents/actions.ts +4 -2
  93. package/src/tools/agents/contract.ts +16 -9
  94. package/src/tools/agents/dsh-contract.ts +12 -8
  95. package/src/ui/dsh/management.ts +31 -8
@@ -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 父会话或执行组件已关闭。");
@@ -4,7 +4,7 @@ import { existsSync, lstatSync, readFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { CURRENT_SESSION_VERSION, getAgentDir, getPackageDir, parseSessionEntries, SessionManager } from "@earendil-works/pi-coding-agent";
6
6
  import { requireThat } from "../../common/validation.js";
7
- import type { AgentDescriptor, AgentSessionReference } from "../../model/agent.js";
7
+ import type { AgentDescriptor, AgentOptions, AgentSessionReference } from "../../model/agent.js";
8
8
  import type { AgentHost } from "../../services/agents/agent-service.js";
9
9
 
10
10
  export const agentDirectory = () => join(getAgentDir(), "pbot/subagents");
@@ -26,6 +26,9 @@ export class PiAgents implements AgentHost {
26
26
  requireThat(reference.host === "pi", "不能接管其他宿主的会话。");
27
27
  return reference.file;
28
28
  }
29
+ validateOptions(options: AgentOptions) {
30
+ requireThat(options.thinking === undefined || ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(options.thinking), "Pi 思考级别无效。");
31
+ }
29
32
  available() {
30
33
  requireThat(spawnSync("tmux", ["-V"], { encoding: "utf8" }).status === 0, "子会话需要 tmux。");
31
34
  requireThat(existsSync(join(getPackageDir(), "dist/cli.js")), "无法定位 Pi CLI。");
@@ -0,0 +1,26 @@
1
+ export type AcpBackend = "pi" | "dsh" | "claude";
2
+ export interface AcpCommand { command: string; args: string[] }
3
+ export type AcpCommands = Partial<Record<AcpBackend, AcpCommand>>;
4
+ export interface AcpSessionReference extends AcpCommand {
5
+ host: "acp";
6
+ backend: AcpBackend;
7
+ sessionId: string | null;
8
+ capabilities?: { resume: boolean; load: boolean; close: boolean };
9
+ }
10
+ export interface AcpModelSelection { provider?: string; model?: string; resolvedModel?: string; thinking?: string }
11
+ export interface AcpModelState extends AcpModelSelection { generation: string }
12
+ export interface AcpProcess { generation: string; pid: number; startedAt: number }
13
+ export interface AcpInput { generation: string; requestId: string }
14
+ export interface AcpAnswer extends AcpInput {
15
+ answer: string;
16
+ state: "completed" | "failed" | "cancelled";
17
+ error?: string;
18
+ }
19
+ export interface AcpReport { generation: string; cycleId: string; text: string }
20
+ export interface AcpPermission {
21
+ generation: string;
22
+ requestId: string;
23
+ description: string;
24
+ options: { optionId: string; name: string; kind: string }[];
25
+ }
26
+ export interface AcpPermissionReply { generation: string; requestId: string; optionId: string | null }
@@ -1,3 +1,6 @@
1
+ import type { AcpBackend, AcpModelSelection, AcpSessionReference } from "./acp.js";
2
+
3
+ export interface AgentStartOptions extends AgentOptions { backend?: AcpBackend }
1
4
  export interface AgentOptions {
2
5
  name?: string; message?: string; files?: string[]; prompts?: string[];
3
6
  provider?: string; model?: string; thinking?: string; cwd?: string; tools?: string[];
@@ -11,7 +14,8 @@ export interface AgentDescriptor {
11
14
  /** null means no conversation input has been handed to Pi yet. */
12
15
  export interface AgentSessionRef { file: string | null }
13
16
  /** Native references are interpreted only by their owning host adapter. */
14
- export type AgentSessionReference = { host: "pi"; file: string | null } | { host: "dsh"; sessionId: string };
17
+ export type NativeAgentHost = "pi" | "dsh";
18
+ export type AgentSessionReference = { host: "pi"; file: string | null } | { host: "dsh"; sessionId: string } | AcpSessionReference;
15
19
  export interface AgentLaunch { generation: string; name: string; sequence: number; stop: boolean; startedAt: number }
16
20
  export interface AgentMessage { requestId: string; generation: string; sequence: number; message: string; delivery: "steer" | "followUp"; files: string[] }
17
21
  export interface AgentCycle {
@@ -26,6 +30,8 @@ export interface AgentStatus {
26
30
  }
27
31
  export interface AgentView extends AgentDescriptor {
28
32
  name: string; generation: string; state: AgentStatus["state"]; activity: string;
33
+ backend?: AcpBackend; transport?: "native" | "acp"; selection?: AcpModelSelection;
34
+ capabilities?: { steer: boolean; resume: boolean; team: boolean; transcript: boolean };
29
35
  cycle?: AgentCycle; error?: string; owned: boolean;
30
36
  }
31
37
  export interface AgentCompletion { agentId: string; name: string; cycle: AgentCycle; report: string }
@@ -1,5 +1,8 @@
1
+ import type { AcpCommands } from "./acp.js";
2
+
1
3
  export interface WorkspaceConfig {
2
4
  enabled?: boolean;
5
+ acp?: AcpCommands;
3
6
  }
4
7
 
5
8
  export interface WorkspaceConfiguration {
@@ -7,4 +10,5 @@ export interface WorkspaceConfiguration {
7
10
  present: boolean;
8
11
  enabled: boolean;
9
12
  error?: string;
13
+ acp?: AcpCommands;
10
14
  }
package/src/pbot.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { PiAgents, agentDirectory } from "./integrations/pi/pi-agents.js";
3
+ import { AgentBackends } from "./integrations/acp/agents.js";
3
4
  import { PythonEnvironmentService } from "./services/workspace/python-environment-service.js";
4
5
  import { AgentService } from "./services/agents/agent-service.js";
5
6
  import { TeamService } from "./services/agents/team-service.js";
@@ -20,8 +21,8 @@ export default function pbot(pi: ExtensionAPI) {
20
21
  // The explicitly loaded child entry owns the child; normal discovery never grants main privileges.
21
22
  if (process.env.PBOT_SUBAGENT_RUN_ID) return;
22
23
  const confirmations = new Confirmations(), registry = new ToolRegistry(pi);
23
- const lifecycle = new Lifecycle(root => {
24
- const agents = new AgentService(root, agentDirectory(), new PiAgents());
24
+ const lifecycle = new Lifecycle((root, configuration) => {
25
+ const agents = new AgentService(root, agentDirectory(), new AgentBackends(new PiAgents(), agentDirectory(), configuration.acp));
25
26
  const history = new HistoryService(root, new HistoryFiles(join(root, ".pbot/history")), new PiHistory(root, () =>
26
27
  agents.files.list().filter(agent => agent.workspace === root).flatMap(agent => {
27
28
  const file = agents.files.optional(agent.agentId, "session-ref.json", sessionRef)?.file;