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,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,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;
@@ -16,6 +16,10 @@ export class DshAgents {
16
16
  this.composition = composition;
17
17
  this.lifetime = lifetime;
18
18
  }
19
+ validateOptions(options) {
20
+ for (const key of ["noExtensions", "noPromptTemplates", "noContextFiles"])
21
+ requireThat(options[key] === undefined, "dsh 不支持宿主选项:" + key);
22
+ }
19
23
  available() {
20
24
  this.lifetime.throwIfAborted();
21
25
  requireThat(!this.#closed && this.ctx.agents.get(this.parent.id) === this.parent, "dsh 父会话或执行组件已关闭。");
@@ -0,0 +1,59 @@
1
+ export type AcpBackend = "pi" | "dsh" | "claude";
2
+ export interface AcpCommand {
3
+ command: string;
4
+ args: string[];
5
+ }
6
+ export type AcpCommands = Partial<Record<AcpBackend, AcpCommand>>;
7
+ export interface AcpSessionReference extends AcpCommand {
8
+ host: "acp";
9
+ backend: AcpBackend;
10
+ sessionId: string | null;
11
+ capabilities?: {
12
+ resume: boolean;
13
+ load: boolean;
14
+ close: boolean;
15
+ };
16
+ }
17
+ export interface AcpModelSelection {
18
+ provider?: string;
19
+ model?: string;
20
+ resolvedModel?: string;
21
+ thinking?: string;
22
+ }
23
+ export interface AcpModelState extends AcpModelSelection {
24
+ generation: string;
25
+ }
26
+ export interface AcpProcess {
27
+ generation: string;
28
+ pid: number;
29
+ startedAt: number;
30
+ }
31
+ export interface AcpInput {
32
+ generation: string;
33
+ requestId: string;
34
+ }
35
+ export interface AcpAnswer extends AcpInput {
36
+ answer: string;
37
+ state: "completed" | "failed" | "cancelled";
38
+ error?: string;
39
+ }
40
+ export interface AcpReport {
41
+ generation: string;
42
+ cycleId: string;
43
+ text: string;
44
+ }
45
+ export interface AcpPermission {
46
+ generation: string;
47
+ requestId: string;
48
+ description: string;
49
+ options: {
50
+ optionId: string;
51
+ name: string;
52
+ kind: string;
53
+ }[];
54
+ }
55
+ export interface AcpPermissionReply {
56
+ generation: string;
57
+ requestId: string;
58
+ optionId: string | null;
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,3 +1,7 @@
1
+ import type { AcpBackend, AcpModelSelection, AcpSessionReference } from "./acp.js";
2
+ export interface AgentStartOptions extends AgentOptions {
3
+ backend?: AcpBackend;
4
+ }
1
5
  export interface AgentOptions {
2
6
  name?: string;
3
7
  message?: string;
@@ -33,13 +37,14 @@ export interface AgentSessionRef {
33
37
  file: string | null;
34
38
  }
35
39
  /** Native references are interpreted only by their owning host adapter. */
40
+ export type NativeAgentHost = "pi" | "dsh";
36
41
  export type AgentSessionReference = {
37
42
  host: "pi";
38
43
  file: string | null;
39
44
  } | {
40
45
  host: "dsh";
41
46
  sessionId: string;
42
- };
47
+ } | AcpSessionReference;
43
48
  export interface AgentLaunch {
44
49
  generation: string;
45
50
  name: string;
@@ -80,6 +85,15 @@ export interface AgentView extends AgentDescriptor {
80
85
  generation: string;
81
86
  state: AgentStatus["state"];
82
87
  activity: string;
88
+ backend?: AcpBackend;
89
+ transport?: "native" | "acp";
90
+ selection?: AcpModelSelection;
91
+ capabilities?: {
92
+ steer: boolean;
93
+ resume: boolean;
94
+ team: boolean;
95
+ transcript: boolean;
96
+ };
83
97
  cycle?: AgentCycle;
84
98
  error?: string;
85
99
  owned: boolean;
@@ -1,9 +1,12 @@
1
+ import type { AcpCommands } from "./acp.js";
1
2
  export interface WorkspaceConfig {
2
3
  enabled?: boolean;
4
+ acp?: AcpCommands;
3
5
  }
4
6
  export interface WorkspaceConfiguration {
5
7
  path: string;
6
8
  present: boolean;
7
9
  enabled: boolean;
8
10
  error?: string;
11
+ acp?: AcpCommands;
9
12
  }
@@ -0,0 +1,42 @@
1
+ import type { AgentDescriptor, AgentMessage } from "../../model/agent.js";
2
+ import type { AcpPermission } from "../../model/acp.js";
3
+ import { AgentFiles } from "../../storage/agent-files.js";
4
+ import { AgentRun } from "./agent-run.js";
5
+ export interface AcpProgress {
6
+ kind: "text" | "thought" | "tool" | "activity";
7
+ text?: string;
8
+ messageId?: string;
9
+ activity?: string;
10
+ }
11
+ export declare class AcpAnswerBuffer {
12
+ #private;
13
+ get text(): string;
14
+ reset(): void;
15
+ update(value: AcpProgress): void;
16
+ }
17
+ export interface AcpWork {
18
+ readonly signal: AbortSignal;
19
+ prompt(request: AgentMessage): Promise<{
20
+ stopReason: string;
21
+ }>;
22
+ cancel(): Promise<void>;
23
+ }
24
+ /** ACP prompt completion is the receipt boundary; final reports publish before completions. */
25
+ export declare class AcpAgentRun {
26
+ #private;
27
+ readonly files: AgentFiles;
28
+ readonly descriptor: AgentDescriptor;
29
+ readonly generation: string;
30
+ readonly work: AcpWork;
31
+ readonly exactAnswer: boolean;
32
+ readonly execution: AgentRun;
33
+ constructor(files: AgentFiles, descriptor: AgentDescriptor, generation: string, work: AcpWork, exactAnswer: boolean);
34
+ private get id();
35
+ private current;
36
+ update(value: AcpProgress): void;
37
+ permission(description: string, options: AcpPermission["options"], signal: AbortSignal): Promise<string | null>;
38
+ run(): Promise<void>;
39
+ private perform;
40
+ settled(): Promise<void> | undefined;
41
+ stop(): Promise<void>;
42
+ }