personal-bot 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +18 -0
  2. package/.claude-plugin/plugin.json +15 -0
  3. package/CONTEXT.md +11 -5
  4. package/README.md +45 -14
  5. package/README.zh-CN.md +45 -14
  6. package/bin/pbot-pi-acp.mjs +20 -0
  7. package/docs/README.md +6 -4
  8. package/docs/adr/0001-claude-skill-discovery.md +3 -0
  9. package/docs/adr/0002-claude-native-collaboration.md +3 -0
  10. package/docs/agent-collaboration.md +54 -6
  11. package/docs/architecture-guidelines.md +1 -1
  12. package/docs/capability-design.md +15 -3
  13. package/docs/claude-code-design.md +45 -0
  14. package/docs/claude-code.md +64 -0
  15. package/docs/dsh.md +12 -11
  16. package/docs/file-storage.md +26 -9
  17. package/docs/history.md +17 -9
  18. package/docs/interaction-design.md +11 -3
  19. package/docs/model-context.md +43 -12
  20. package/docs/model-instruction-guidelines.md +3 -3
  21. package/docs/release.md +13 -5
  22. package/docs/technical-design.md +59 -19
  23. package/docs/workspace-configuration.md +50 -23
  24. package/hooks/hooks.json +19 -0
  25. package/lib/claude.d.ts +1 -0
  26. package/lib/claude.js +20 -0
  27. package/lib/client.js +41 -8
  28. package/lib/dsh.js +2 -0
  29. package/lib/extension/acp-member.d.ts +16 -0
  30. package/lib/extension/acp-member.js +45 -0
  31. package/lib/extension/acp-worker.d.ts +1 -0
  32. package/lib/extension/acp-worker.js +159 -0
  33. package/lib/extension/claude-hooks.d.ts +15 -0
  34. package/lib/extension/claude-hooks.js +104 -0
  35. package/lib/extension/dsh/acp-member.d.ts +4 -0
  36. package/lib/extension/dsh/acp-member.js +48 -0
  37. package/lib/extension/dsh/command.js +11 -1
  38. package/lib/extension/dsh/history.js +1 -1
  39. package/lib/extension/dsh/management.js +3 -1
  40. package/lib/extension/dsh/workspace.d.ts +35 -1
  41. package/lib/extension/dsh/workspace.js +21 -3
  42. package/lib/integrations/acp/agents.d.ts +24 -0
  43. package/lib/integrations/acp/agents.js +168 -0
  44. package/lib/integrations/acp/claude.d.ts +18 -0
  45. package/lib/integrations/acp/claude.js +33 -0
  46. package/lib/integrations/acp/connection.d.ts +27 -0
  47. package/lib/integrations/acp/connection.js +167 -0
  48. package/lib/integrations/acp/input.d.ts +4 -0
  49. package/lib/integrations/acp/input.js +45 -0
  50. package/lib/integrations/acp/launch.d.ts +4 -0
  51. package/lib/integrations/acp/launch.js +52 -0
  52. package/lib/integrations/acp/model-selection.d.ts +12 -0
  53. package/lib/integrations/acp/model-selection.js +65 -0
  54. package/lib/integrations/agent-resources.d.ts +1 -1
  55. package/lib/integrations/agent-resources.js +3 -1
  56. package/lib/integrations/dsh/dsh-agents.d.ts +2 -1
  57. package/lib/integrations/dsh/dsh-agents.js +4 -0
  58. package/lib/integrations/dsh/history-summary.js +5 -9
  59. package/lib/integrations/dsh/history.js +13 -5
  60. package/lib/integrations/history-summary.d.ts +2 -0
  61. package/lib/integrations/history-summary.js +21 -10
  62. package/lib/model/acp.d.ts +59 -0
  63. package/lib/model/acp.js +1 -0
  64. package/lib/model/agent.d.ts +15 -1
  65. package/lib/model/history.d.ts +11 -4
  66. package/lib/model/workspace-config.d.ts +3 -0
  67. package/lib/services/agents/acp-run.d.ts +42 -0
  68. package/lib/services/agents/acp-run.js +149 -0
  69. package/lib/services/agents/agent-service.d.ts +114 -6
  70. package/lib/services/agents/agent-service.js +81 -10
  71. package/lib/services/agents/team-service.js +4 -2
  72. package/lib/services/history/history-service.d.ts +8 -6
  73. package/lib/services/history/history-service.js +90 -48
  74. package/lib/services/workspace/python-environment-service.d.ts +6 -0
  75. package/lib/services/workspace/python-environment-service.js +25 -9
  76. package/lib/services/workspace/workspace-config.js +12 -1
  77. package/lib/storage/acp-files.d.ts +9 -0
  78. package/lib/storage/acp-files.js +50 -0
  79. package/lib/storage/agent-files.d.ts +5 -4
  80. package/lib/storage/agent-files.js +14 -2
  81. package/lib/storage/history-files.d.ts +2 -1
  82. package/lib/storage/history-files.js +26 -15
  83. package/lib/tools/agents/actions.d.ts +16 -2
  84. package/lib/tools/agents/actions.js +3 -1
  85. package/lib/tools/agents/contract.d.ts +48 -3
  86. package/lib/tools/agents/contract.js +15 -9
  87. package/lib/tools/agents/dsh-contract.d.ts +8 -15
  88. package/lib/tools/agents/dsh-contract.js +12 -8
  89. package/lib/tools/history/contract.d.ts +7 -7
  90. package/lib/tools/history/contract.js +2 -2
  91. package/lib/ui/dsh/management.js +37 -9
  92. package/npm-shrinkwrap.json +975 -51
  93. package/package.json +40 -29
  94. package/python/README.md +17 -14
  95. package/resources/agents/coordinator.md +1 -1
  96. package/resources/claude/agents/general-purpose.md +12 -0
  97. package/resources/claude/skills/pbot/SKILL.md +17 -0
  98. package/resources/prompts/claude-coordinator.md +1 -0
  99. package/resources/prompts/native-coordinator.md +1 -0
  100. package/resources/prompts/workspace.md +2 -2
  101. package/resources/references/compute.md +2 -2
  102. package/resources/references/task-conductor.md +3 -2
  103. package/resources/skills/.claude-plugin/plugin.json +4 -0
  104. package/resources/skills/provider-connections/SKILL.md +17 -1
  105. package/scripts/README.md +29 -5
  106. package/src/claude.ts +19 -0
  107. package/src/dsh.ts +1 -0
  108. package/src/extension/acp-member.ts +44 -0
  109. package/src/extension/acp-worker.ts +124 -0
  110. package/src/extension/agent-events.ts +28 -3
  111. package/src/extension/agents-command.ts +33 -5
  112. package/src/extension/claude-hooks.ts +94 -0
  113. package/src/extension/dsh/acp-member.ts +44 -0
  114. package/src/extension/dsh/command.ts +10 -1
  115. package/src/extension/dsh/history.ts +1 -1
  116. package/src/extension/dsh/management.ts +2 -1
  117. package/src/extension/dsh/workspace.ts +21 -3
  118. package/src/extension/lifecycle.ts +2 -2
  119. package/src/extension/pi-acp-member.ts +64 -0
  120. package/src/integrations/acp/agents.ts +118 -0
  121. package/src/integrations/acp/claude.ts +40 -0
  122. package/src/integrations/acp/connection.ts +152 -0
  123. package/src/integrations/acp/input.ts +39 -0
  124. package/src/integrations/acp/launch.ts +50 -0
  125. package/src/integrations/acp/model-selection.ts +66 -0
  126. package/src/integrations/agent-resources.ts +2 -1
  127. package/src/integrations/dsh/dsh-agents.ts +4 -1
  128. package/src/integrations/dsh/history-summary.ts +5 -9
  129. package/src/integrations/dsh/history.ts +12 -6
  130. package/src/integrations/history-summary.ts +18 -8
  131. package/src/integrations/pi/history.ts +16 -15
  132. package/src/integrations/pi/pi-agents.ts +4 -1
  133. package/src/model/acp.ts +26 -0
  134. package/src/model/agent.ts +7 -1
  135. package/src/model/history.ts +12 -4
  136. package/src/model/workspace-config.ts +4 -0
  137. package/src/pbot.ts +5 -4
  138. package/src/services/agents/acp-run.ts +123 -0
  139. package/src/services/agents/agent-service.ts +85 -12
  140. package/src/services/agents/team-service.ts +3 -2
  141. package/src/services/history/history-service.ts +82 -41
  142. package/src/services/workspace/python-environment-service.ts +26 -9
  143. package/src/services/workspace/workspace-config.ts +10 -1
  144. package/src/storage/acp-files.ts +50 -0
  145. package/src/storage/agent-files.ts +15 -4
  146. package/src/storage/history-files.ts +20 -11
  147. package/src/tools/agents/actions.ts +4 -2
  148. package/src/tools/agents/contract.ts +16 -9
  149. package/src/tools/agents/dsh-contract.ts +12 -8
  150. package/src/tools/history/contract.ts +2 -2
  151. package/src/ui/dsh/management.ts +32 -9
@@ -0,0 +1,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
+ }>;
@@ -0,0 +1,167 @@
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 { requireThat } from "../../common/validation.js";
6
+ import { packageVersion } from "../../common/version.js";
7
+ import { acpModelSelection, acpModelValue, acpThinkingValue } from "./model-selection.js";
8
+ import { object } from "../../common/json.js";
9
+ export function acpFailure(error) {
10
+ return error instanceof acp.RequestError && error.data !== undefined
11
+ ? new Error(error.message + ":" + JSON.stringify(error.data), { cause: error }) : error;
12
+ }
13
+ /** One ACP v1 connection. The worker owns its process group and business state. */
14
+ export async function openAcp(reference, cwd, env, callbacks, signal, systemPrompt, claude) {
15
+ signal.throwIfAborted();
16
+ const child = spawn(reference.command, reference.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] });
17
+ const lifetime = new AbortController();
18
+ const cancel = AbortSignal.any([signal, lifetime.signal]);
19
+ const exited = new Promise(resolve => child.once("close", () => resolve()));
20
+ child.once("error", error => lifetime.abort(error));
21
+ child.once("exit", (code, termination) => lifetime.abort(new Error("ACP 进程退出:" + (termination ?? code))));
22
+ child.stderr.resume();
23
+ child.stdin.on("error", () => { });
24
+ let sessionId;
25
+ let options = [];
26
+ let resolvedModel;
27
+ const selection = () => ({ ...acpModelSelection(reference.backend, options, claude?.thinking),
28
+ ...(resolvedModel ? { resolvedModel } : {}) });
29
+ let updating = Promise.resolve();
30
+ const app = acp.client({ name: "personal-bot" })
31
+ .onRequest(acp.methods.client.session.requestPermission, async (ctx) => {
32
+ if (cancel.aborted || ctx.params.sessionId !== sessionId)
33
+ return { outcome: { outcome: "cancelled" } };
34
+ return callbacks.permission(ctx.params, cancel);
35
+ })
36
+ .onNotification(acp.methods.client.session.update, ctx => {
37
+ // Load may replay before its response. Output from replay never becomes a new report.
38
+ if (ctx.params.sessionId !== sessionId || cancel.aborted)
39
+ return;
40
+ updating = updating.then(async () => {
41
+ if (ctx.params.update.sessionUpdate === "config_option_update") {
42
+ const before = acpModelSelection(reference.backend, options);
43
+ options = ctx.params.update.configOptions;
44
+ if (acpModelSelection(reference.backend, options).model !== before.model)
45
+ resolvedModel = undefined;
46
+ callbacks.selection?.(selection());
47
+ }
48
+ await callbacks.update(ctx.params.update);
49
+ });
50
+ void updating.catch(error => lifetime.abort(error));
51
+ return updating;
52
+ })
53
+ .onNotification("_claude/sdkMessage", (value) => value, ctx => {
54
+ if (reference.backend !== "claude" || !object(ctx.params) || ctx.params.sessionId !== sessionId || cancel.aborted)
55
+ return;
56
+ const message = ctx.params.message;
57
+ if (!object(message) || message.type !== "system" || message.subtype !== "init" || typeof message.model !== "string" || !message.model)
58
+ return;
59
+ const model = message.model;
60
+ updating = updating.then(() => { resolvedModel = model; callbacks.selection?.(selection()); });
61
+ void updating.catch(error => lifetime.abort(error));
62
+ return updating;
63
+ });
64
+ const connection = await app.connect(acp.ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout), { maxMessageBytes: 8 * 1024 * 1024 }));
65
+ const abort = () => connection.close(cancel.reason);
66
+ cancel.addEventListener("abort", abort, { once: true });
67
+ if (cancel.aborted)
68
+ abort();
69
+ const connected = AbortSignal.any([cancel, connection.signal]);
70
+ let closing;
71
+ const close = () => closing ??= (async () => {
72
+ try {
73
+ if (sessionId && initialized?.agentCapabilities?.sessionCapabilities?.close && !connection.signal.aborted) {
74
+ await connection.agent.request(acp.methods.agent.session.close, { sessionId }, { cancellationSignal: AbortSignal.timeout(5000), stopWaitingOnCancel: true });
75
+ }
76
+ }
77
+ finally {
78
+ cancel.removeEventListener("abort", abort);
79
+ connection.close();
80
+ child.stdin.end();
81
+ if (child.exitCode === null)
82
+ child.kill("SIGTERM");
83
+ const grace = new AbortController();
84
+ try {
85
+ await Promise.race([exited, delay(1500, undefined, { signal: grace.signal })]);
86
+ }
87
+ finally {
88
+ grace.abort();
89
+ }
90
+ if (child.exitCode === null && child.signalCode === null)
91
+ child.kill("SIGKILL");
92
+ child.stdout.destroy();
93
+ child.stderr.destroy();
94
+ await exited;
95
+ }
96
+ })();
97
+ let initialized;
98
+ try {
99
+ initialized = await connection.agent.request(acp.methods.agent.initialize, {
100
+ protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "personal-bot", version: packageVersion },
101
+ }, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true });
102
+ requireThat(initialized.protocolVersion === 1, "目标宿主没有协商 ACP v1。");
103
+ const advertised = initialized.agentCapabilities;
104
+ const capabilities = { resume: Boolean(advertised?.sessionCapabilities?.resume), load: advertised?.loadSession === true,
105
+ close: Boolean(advertised?.sessionCapabilities?.close) };
106
+ const setup = { cwd, mcpServers: [],
107
+ ...(reference.backend === "claude" ? { _meta: { claudeCode: { options: { ...claude?.options, disallowedTools: ["Agent", "Task"] },
108
+ emitRawSDKMessages: [{ type: "system", subtype: "init" }] } } } : {}), ...(systemPrompt && advertised?.sessionCapabilities?.systemPrompt ? {
109
+ systemPrompt: { mode: "append", content: [{ type: "text", text: systemPrompt }] },
110
+ } : {}) };
111
+ if (reference.sessionId === null) {
112
+ const created = await connection.agent.request(acp.methods.agent.session.new, setup, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true });
113
+ sessionId = created.sessionId;
114
+ options = created.configOptions ?? [];
115
+ }
116
+ else {
117
+ requireThat(capabilities.resume || capabilities.load, "目标 ACP 后端不支持恢复已有会话。");
118
+ const restored = capabilities.resume
119
+ ? await connection.agent.request(acp.methods.agent.session.resume, { ...setup, sessionId: reference.sessionId }, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true })
120
+ : await connection.agent.request(acp.methods.agent.session.load, { ...setup, sessionId: reference.sessionId }, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true });
121
+ sessionId = reference.sessionId;
122
+ options = restored.configOptions ?? [];
123
+ }
124
+ requireThat(sessionId, "ACP 后端没有返回会话 ID。");
125
+ const activeId = sessionId;
126
+ return {
127
+ sessionId: activeId, capabilities, signal: connected, close, images: advertised?.promptCapabilities?.image === true,
128
+ systemPrompt: Boolean(advertised?.sessionCapabilities?.systemPrompt),
129
+ selection,
130
+ async configure(requested) {
131
+ requireThat(!requested.provider || requested.model, "provider 需要同时指定目标 model。");
132
+ for (const kind of ["model", "thinking"]) {
133
+ const supplied = requested[kind];
134
+ if (supplied === undefined)
135
+ continue;
136
+ const chosen = kind === "model" ? acpModelValue(reference.backend, options, supplied, requested.provider) : acpThinkingValue(options, supplied);
137
+ const changed = await connection.agent.request(acp.methods.agent.session.setConfigOption, { sessionId: activeId, ...chosen }, { cancellationSignal: AbortSignal.any([cancel, AbortSignal.timeout(30_000)]), stopWaitingOnCancel: true });
138
+ await updating;
139
+ options = changed.configOptions;
140
+ if (kind === "model")
141
+ resolvedModel = undefined;
142
+ callbacks.selection?.(selection());
143
+ }
144
+ return selection();
145
+ },
146
+ async prompt(content) {
147
+ try {
148
+ const response = await connection.agent.request(acp.methods.agent.session.prompt, { sessionId: activeId, prompt: content });
149
+ await updating;
150
+ cancel.throwIfAborted();
151
+ return response;
152
+ }
153
+ catch (error) {
154
+ throw acpFailure(error);
155
+ }
156
+ },
157
+ async cancel() {
158
+ if (!connection.signal.aborted)
159
+ await connection.agent.notify(acp.methods.agent.session.cancel, { sessionId: activeId });
160
+ },
161
+ };
162
+ }
163
+ catch (error) {
164
+ await close().catch(() => { });
165
+ throw acpFailure(error);
166
+ }
167
+ }
@@ -0,0 +1,4 @@
1
+ import type { ContentBlock } from "@agentclientprotocol/sdk";
2
+ import type { AgentMessage } from "../../model/agent.js";
3
+ /** Local ACP agents can continue reading each absolute source with their native tools. */
4
+ export declare function acpContent(request: AgentMessage, images: boolean, signal: AbortSignal): Promise<ContentBlock[]>;
@@ -0,0 +1,45 @@
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 { requireThat } from "../../common/validation.js";
6
+ /** Local ACP agents can continue reading each absolute source with their native tools. */
7
+ export async function acpContent(request, images, signal) {
8
+ const content = [{ type: "text", text: request.message }];
9
+ for (const file of request.files) {
10
+ signal.throwIfAborted();
11
+ const handle = await open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
12
+ try {
13
+ const info = await handle.stat();
14
+ requireThat(info.isFile(), "附件必须是普通文件:" + file);
15
+ const prefix = Buffer.alloc(Math.min(info.size, 60000)), read = await handle.read(prefix, 0, prefix.length, 0);
16
+ const bytes = prefix.subarray(0, read.bytesRead);
17
+ const mimeType = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? "image/png"
18
+ : bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 ? "image/jpeg"
19
+ : /^GIF8[79]a$/.test(bytes.toString("ascii", 0, 6)) ? "image/gif"
20
+ : bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP" ? "image/webp" : undefined;
21
+ if (mimeType) {
22
+ requireThat(images, "目标 ACP 会话不支持图片附件。");
23
+ const data = await handle.readFile();
24
+ signal.throwIfAborted();
25
+ content.push({ type: "text", text: "附件来源:" + file }, { type: "image", data: data.toString("base64"), mimeType });
26
+ continue;
27
+ }
28
+ let text;
29
+ try {
30
+ if (!bytes.includes(0))
31
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes, { stream: info.size > bytes.length });
32
+ }
33
+ catch { /* Native tools handle non-text attachments through their source link. */ }
34
+ if (text === undefined)
35
+ content.push({ type: "resource_link", uri: pathToFileURL(file).href, name: basename(file) });
36
+ else
37
+ content.push({ type: "text", text: "附件来源:" + file + "\n\n" + text.slice(0, 20000) +
38
+ (info.size > bytes.length || text.length > 20000 ? "\n\n附件已截断,请沿上述路径续读。" : "") });
39
+ }
40
+ finally {
41
+ await handle.close();
42
+ }
43
+ }
44
+ return content;
45
+ }
@@ -0,0 +1,4 @@
1
+ import type { AcpBackend, AcpCommands, AcpSessionReference } from "../../model/acp.js";
2
+ import type { AgentOptions } from "../../model/agent.js";
3
+ export declare function acpExecutable(command: string, backend: AcpBackend): string;
4
+ export declare function acpLaunch(backend: AcpBackend, commands: AcpCommands, options: AgentOptions): AcpSessionReference;
@@ -0,0 +1,52 @@
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
+ const targets = {
5
+ pi: { command: "pi-acp", args: [], install: "npm install -g pi-acp",
6
+ configure: "Pi 也需已安装;运行 pi 完成登录和默认模型配置。" },
7
+ dsh: { command: "dsh", args: ["--profile", "acp"], install: "npm install -g @deepseek-ai/dsh@latest",
8
+ configure: "按 dsh 原生方式配置目标 profile 的模型与认证。" },
9
+ claude: { command: "claude-agent-acp", args: [], install: "npm install -g @agentclientprotocol/claude-agent-acp",
10
+ configure: "在 Claude Code 中完成登录或 API 配置,并设置默认模型。" },
11
+ };
12
+ export function acpExecutable(command, backend) {
13
+ const candidates = isAbsolute(command) ? [command] : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map(directory => resolve(directory, command));
14
+ for (const candidate of candidates) {
15
+ try {
16
+ accessSync(candidate, constants.X_OK);
17
+ if (statSync(candidate).isFile())
18
+ return realpathSync(candidate);
19
+ }
20
+ catch (error) {
21
+ if (!["ENOENT", "ENOTDIR", "EACCES"].includes(error.code ?? ""))
22
+ throw error;
23
+ }
24
+ }
25
+ const target = targets[backend], nativePi = backend === "pi" && command === "pi";
26
+ const install = nativePi ? "npm install -g @earendil-works/pi-coding-agent" : target.install;
27
+ const configured = JSON.stringify({ command: "/absolute/path/to/" + target.command, args: target.args });
28
+ const path = nativePi ? "Pi 已安装但 PATH 不可见时,启动主宿主前将 PI_ACP_PI_COMMAND 设置为 pi 的绝对路径。"
29
+ : "已安装但 PATH 不可见时,在 .pbot/config.json 设置 acp." + backend + ":" + configured + ",command 使用实际绝对路径。";
30
+ throw new Error([
31
+ "未找到子代理程序:" + command + "。",
32
+ "在运行 Pi/dsh 的机器上安装:" + install,
33
+ target.configure,
34
+ "检查安装路径:command -v " + (nativePi ? "pi" : target.command) + (!nativePi && backend === "pi" ? ";另用 command -v pi 检查 Pi。" : "。"),
35
+ path,
36
+ "安装后重试原 start 请求;PATH 变化时重启主宿主。配置修改后,Pi 执行 /reload,dsh 重启宿主。",
37
+ ].join("\n"));
38
+ }
39
+ export function acpLaunch(backend, commands, options) {
40
+ requireThat(["pi", "dsh", "claude"].includes(backend), "未知子代理程序。");
41
+ requireThat(!options.provider || options.model, "provider 需要同时指定目标 model。");
42
+ if (backend !== "pi")
43
+ for (const key of ["noExtensions", "noPromptTemplates", "noContextFiles"]) {
44
+ requireThat(options[key] === undefined, backend + " 子代理不支持启动选项:" + key);
45
+ }
46
+ if (backend === "claude") {
47
+ requireThat(options.noSkills === undefined && options.tools === undefined, "Claude 子代理的技能和工具通过 Claude 原生配置选择。");
48
+ requireThat(options.provider === undefined, "Claude 子代理使用原生提供方配置;请仅指定目标 model。");
49
+ }
50
+ const selected = commands[backend] ?? targets[backend];
51
+ return { host: "acp", backend, command: acpExecutable(selected.command, backend), args: [...selected.args], sessionId: null };
52
+ }
@@ -0,0 +1,12 @@
1
+ import type { SessionConfigOption } from "@agentclientprotocol/sdk";
2
+ import type { AcpBackend, AcpModelSelection } from "../../model/acp.js";
3
+ /** Resolve a native model ID against the peer's advertised values. */
4
+ export declare function acpModelValue(backend: AcpBackend, options: SessionConfigOption[], model: string, provider?: string): {
5
+ configId: string;
6
+ value: string;
7
+ };
8
+ export declare function acpThinkingValue(options: SessionConfigOption[], thinking: string): {
9
+ configId: string;
10
+ value: string;
11
+ };
12
+ export declare function acpModelSelection(backend: AcpBackend, options: SessionConfigOption[], effectiveThinking?: string): AcpModelSelection;
@@ -0,0 +1,65 @@
1
+ import { requireThat } from "../../common/validation.js";
2
+ function optionFor(options, category) {
3
+ const ids = category === "model" ? ["model"] : ["thought_level", "thinking", "reasoning_effort", "effort"];
4
+ return options.find((option) => option.type === "select" && ids.includes(option.id)) ??
5
+ options.find((option) => option.type === "select" && option.category === category);
6
+ }
7
+ function values(option) {
8
+ return [...new Map(option.options.flatMap(item => "options" in item ? item.options : [item]).map(item => [item.value, item])).values()];
9
+ }
10
+ function modelIdentity(backend, value) {
11
+ if (backend === "dsh") {
12
+ try {
13
+ const parts = JSON.parse(value);
14
+ if (Array.isArray(parts) && parts.length === 2 && parts.every(part => typeof part === "string" && part.length > 0)) {
15
+ return { provider: parts[0], model: parts[1] };
16
+ }
17
+ }
18
+ catch { /* Unencoded identifiers remain usable as exact ACP option values. */ }
19
+ }
20
+ if (backend === "pi") {
21
+ const separator = value.indexOf("/");
22
+ if (separator > 0)
23
+ return { provider: value.slice(0, separator), model: value.slice(separator + 1) };
24
+ }
25
+ return { model: value };
26
+ }
27
+ /** Resolve a native model ID against the peer's advertised values. */
28
+ export function acpModelValue(backend, options, model, provider) {
29
+ const option = optionFor(options, "model");
30
+ requireThat(option, "ACP 后端未提供可选择的模型。");
31
+ const choices = values(option);
32
+ if (backend === "pi" && provider) {
33
+ const qualified = choices.find(item => item.value === provider + "/" + model);
34
+ if (qualified)
35
+ return { configId: option.id, value: qualified.value };
36
+ }
37
+ const available = choices.map(item => ({ ...modelIdentity(backend, item.value), value: item.value }));
38
+ let matches = available.filter(item => (item.value === model || item.model === model) && (!provider || item.provider === provider));
39
+ const exact = matches.filter(item => item.value === model);
40
+ if (exact.length)
41
+ matches = exact;
42
+ if (matches.length > 1 && !provider) {
43
+ const current = modelIdentity(backend, option.currentValue);
44
+ const sameProvider = matches.filter(item => item.provider === current.provider);
45
+ if (sameProvider.length === 1)
46
+ matches = sameProvider;
47
+ }
48
+ requireThat(matches.length, "ACP 模型不可用:" + [provider, model].filter(Boolean).join("/") + ";可用值:" + available.map(item => item.value).join(", "));
49
+ requireThat(matches.length === 1, "多个 ACP 提供方包含该模型,请指定 provider 或完整模型值:" + matches.map(item => item.value).join(", "));
50
+ return { configId: option.id, value: matches[0].value };
51
+ }
52
+ export function acpThinkingValue(options, thinking) {
53
+ const option = optionFor(options, "thought_level");
54
+ requireThat(option, "目标模型未提供可选择的思考等级。");
55
+ const available = values(option);
56
+ const chosen = available.find(item => item.value === thinking);
57
+ requireThat(chosen, "ACP 思考等级不可用:" + thinking + ";可用值:" + available.map(item => item.value).join(", "));
58
+ return { configId: option.id, value: chosen.value };
59
+ }
60
+ export function acpModelSelection(backend, options, effectiveThinking) {
61
+ const model = optionFor(options, "model"), thinking = optionFor(options, "thought_level");
62
+ const selectedThinking = effectiveThinking === "unset" ? effectiveThinking
63
+ : thinking && effectiveThinking && values(thinking).some(item => item.value === effectiveThinking) ? effectiveThinking : thinking?.currentValue;
64
+ return { ...(model ? modelIdentity(backend, model.currentValue) : {}), ...(selectedThinking ? { thinking: selectedThinking } : {}) };
65
+ }
@@ -1 +1 @@
1
- export declare function agentText(agent: "coordinator" | "general-purpose", root: string): Promise<string>;
1
+ export declare function agentText(agent: "coordinator" | "general-purpose", root: string, host?: "pi" | "dsh" | "claude"): Promise<string>;
@@ -2,9 +2,11 @@ import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { resourceRoot } from "../common/paths.js";
4
4
  import { requireThat } from "../common/validation.js";
5
- export async function agentText(agent, root) {
5
+ export async function agentText(agent, root, host = "pi") {
6
6
  requireThat(agent === "coordinator" || agent === "general-purpose", "未知职责。");
7
7
  let text = await readFile(join(resourceRoot, "agents", agent + ".md"), "utf8");
8
+ if (agent === "coordinator")
9
+ text += "\n\n" + await readFile(join(resourceRoot, "prompts", host === "claude" ? "claude-coordinator.md" : "native-coordinator.md"), "utf8");
8
10
  try {
9
11
  const local = await readFile(join(root, "agents", agent + ".md"), "utf8");
10
12
  text += "\n\n工作区职责补充:\n" + local;
@@ -1,6 +1,6 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { Agent, AgentSetup } from "@deepseek-ai/dsh-agent";
3
- import type { AgentDescriptor, AgentSessionReference } from "../../model/agent.js";
3
+ import type { AgentDescriptor, AgentOptions, AgentSessionReference } from "../../model/agent.js";
4
4
  import type { AgentHost } from "../../services/agents/agent-service.js";
5
5
  /** Native handles belong to the execution component, independently of browser observers. */
6
6
  export declare class DshAgents implements AgentHost {
@@ -19,6 +19,7 @@ export declare class DshAgents implements AgentHost {
19
19
  ready(agent: Agent, generation: string): void;
20
20
  stopping(agent: Agent, generation: string): Promise<void>;
21
21
  }, lifetime: AbortSignal);
22
+ validateOptions(options: AgentOptions): void;
22
23
  available(): void;
23
24
  alive(id: string): boolean;
24
25
  private reference;