personal-bot 0.2.10 → 0.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -3
- package/README.zh-CN.md +17 -3
- package/bin/pbot-pi-acp.mjs +20 -0
- package/docs/agent-collaboration.md +38 -2
- package/docs/capability-design.md +6 -0
- package/docs/dsh.md +9 -8
- package/docs/file-storage.md +9 -1
- package/docs/interaction-design.md +2 -2
- package/docs/model-context.md +10 -2
- package/docs/technical-design.md +21 -3
- package/docs/workspace-configuration.md +20 -1
- package/lib/client.js +40 -7
- package/lib/dsh.js +2 -0
- package/lib/extension/acp-member.d.ts +16 -0
- package/lib/extension/acp-member.js +45 -0
- package/lib/extension/acp-worker.d.ts +1 -0
- package/lib/extension/acp-worker.js +156 -0
- package/lib/extension/dsh/acp-member.d.ts +4 -0
- package/lib/extension/dsh/acp-member.js +48 -0
- package/lib/extension/dsh/command.js +11 -1
- package/lib/extension/dsh/management.js +3 -1
- package/lib/extension/dsh/workspace.d.ts +35 -1
- package/lib/extension/dsh/workspace.js +21 -3
- package/lib/integrations/acp/agents.d.ts +24 -0
- package/lib/integrations/acp/agents.js +168 -0
- package/lib/integrations/acp/claude.d.ts +18 -0
- package/lib/integrations/acp/claude.js +33 -0
- package/lib/integrations/acp/connection.d.ts +27 -0
- package/lib/integrations/acp/connection.js +167 -0
- package/lib/integrations/acp/input.d.ts +4 -0
- package/lib/integrations/acp/input.js +45 -0
- package/lib/integrations/acp/launch.d.ts +4 -0
- package/lib/integrations/acp/launch.js +52 -0
- package/lib/integrations/acp/model-selection.d.ts +12 -0
- package/lib/integrations/acp/model-selection.js +65 -0
- package/lib/integrations/dsh/dsh-agents.d.ts +2 -1
- package/lib/integrations/dsh/dsh-agents.js +4 -0
- package/lib/model/acp.d.ts +59 -0
- package/lib/model/acp.js +1 -0
- package/lib/model/agent.d.ts +15 -1
- package/lib/model/workspace-config.d.ts +3 -0
- package/lib/services/agents/acp-run.d.ts +42 -0
- package/lib/services/agents/acp-run.js +149 -0
- package/lib/services/agents/agent-service.d.ts +114 -6
- package/lib/services/agents/agent-service.js +81 -10
- package/lib/services/agents/team-service.js +4 -2
- package/lib/services/workspace/workspace-config.js +12 -1
- package/lib/storage/acp-files.d.ts +9 -0
- package/lib/storage/acp-files.js +50 -0
- package/lib/storage/agent-files.d.ts +5 -4
- package/lib/storage/agent-files.js +11 -2
- package/lib/tools/agents/actions.d.ts +16 -2
- package/lib/tools/agents/actions.js +3 -1
- package/lib/tools/agents/contract.d.ts +48 -3
- package/lib/tools/agents/contract.js +15 -9
- package/lib/tools/agents/dsh-contract.d.ts +8 -15
- package/lib/tools/agents/dsh-contract.js +12 -8
- package/lib/ui/dsh/management.js +36 -8
- package/npm-shrinkwrap.json +953 -12
- package/package.json +8 -1
- package/python/README.md +3 -3
- package/resources/skills/.claude-plugin/plugin.json +4 -0
- package/scripts/README.md +6 -0
- package/scripts/setup-python.py +33 -7
- package/src/dsh.ts +1 -0
- package/src/extension/acp-member.ts +44 -0
- package/src/extension/acp-worker.ts +124 -0
- package/src/extension/agent-events.ts +28 -3
- package/src/extension/agents-command.ts +33 -5
- package/src/extension/dsh/acp-member.ts +44 -0
- package/src/extension/dsh/command.ts +10 -1
- package/src/extension/dsh/management.ts +2 -1
- package/src/extension/dsh/workspace.ts +21 -3
- package/src/extension/lifecycle.ts +2 -2
- package/src/extension/pi-acp-member.ts +64 -0
- package/src/integrations/acp/agents.ts +118 -0
- package/src/integrations/acp/claude.ts +40 -0
- package/src/integrations/acp/connection.ts +152 -0
- package/src/integrations/acp/input.ts +39 -0
- package/src/integrations/acp/launch.ts +50 -0
- package/src/integrations/acp/model-selection.ts +66 -0
- package/src/integrations/dsh/dsh-agents.ts +4 -1
- package/src/integrations/pi/pi-agents.ts +4 -1
- package/src/model/acp.ts +26 -0
- package/src/model/agent.ts +7 -1
- package/src/model/workspace-config.ts +4 -0
- package/src/pbot.ts +3 -2
- package/src/services/agents/acp-run.ts +123 -0
- package/src/services/agents/agent-service.ts +85 -12
- package/src/services/agents/team-service.ts +3 -2
- package/src/services/workspace/workspace-config.ts +10 -1
- package/src/storage/acp-files.ts +50 -0
- package/src/storage/agent-files.ts +12 -4
- package/src/tools/agents/actions.ts +4 -2
- package/src/tools/agents/contract.ts +16 -9
- package/src/tools/agents/dsh-contract.ts +12 -8
- package/src/ui/dsh/management.ts +31 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "personal-bot",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.12",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/realqiyan/personal-bot.git"
|
|
@@ -82,9 +82,11 @@
|
|
|
82
82
|
"test": "npm run build && node --test --test-concurrency=1 tests/*/*.test.mjs",
|
|
83
83
|
"test:smoke": "npm run build && node --test --test-concurrency=1 tests/smoke/*.test.mjs",
|
|
84
84
|
"test:e2e": "npm run build && node --test --test-concurrency=1 tests/e2e/*.test.mjs",
|
|
85
|
+
"test:e2e:acp": "npm run build && node --test --test-concurrency=1 tests/e2e/acp-defaults.e2e.mjs",
|
|
85
86
|
"prepack": "npm run check && npm run build:cli && npm run build:dsh"
|
|
86
87
|
},
|
|
87
88
|
"peerDependencies": {
|
|
89
|
+
"@anthropic-ai/claude-agent-sdk": "*",
|
|
88
90
|
"@deepseek-ai/cordis": "~4.1.0",
|
|
89
91
|
"@deepseek-ai/dsh-agent": "*",
|
|
90
92
|
"@deepseek-ai/dsh-agent-preset-registry": "*",
|
|
@@ -116,6 +118,9 @@
|
|
|
116
118
|
"typebox": "*"
|
|
117
119
|
},
|
|
118
120
|
"peerDependenciesMeta": {
|
|
121
|
+
"@anthropic-ai/claude-agent-sdk": {
|
|
122
|
+
"optional": true
|
|
123
|
+
},
|
|
119
124
|
"@deepseek-ai/cordis": {
|
|
120
125
|
"optional": true
|
|
121
126
|
},
|
|
@@ -205,11 +210,13 @@
|
|
|
205
210
|
}
|
|
206
211
|
},
|
|
207
212
|
"dependencies": {
|
|
213
|
+
"@agentclientprotocol/sdk": "2.6.0",
|
|
208
214
|
"ajv": "8.17.1",
|
|
209
215
|
"ajv-formats": "3.0.1",
|
|
210
216
|
"semver": "7.8.5"
|
|
211
217
|
},
|
|
212
218
|
"devDependencies": {
|
|
219
|
+
"@anthropic-ai/claude-agent-sdk": "0.3.322",
|
|
213
220
|
"@deepseek-ai/cordis": "4.1.0",
|
|
214
221
|
"@deepseek-ai/dsh": "0.2.2-rc.1",
|
|
215
222
|
"@deepseek-ai/dsh-agent": "0.2.2-rc.1",
|
package/python/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
工作区的 `.pbot/config.json` 设置 `enabled: true` 后,Pi 加载或原生 `/reload` 时自动执行 setup;dsh 在首个已启用工作区加载时准备环境。无需另行确认或指定 Python 路径。同一系统用户的两种宿主共用该环境:
|
|
8
8
|
|
|
9
|
-
1. 共享 venv 不存在时创建,不使用系统 site-packages
|
|
9
|
+
1. 共享 venv 不存在时创建,不使用系统 site-packages;解释器无法启动时重新创建。
|
|
10
10
|
2. 按 `requirements.lock` 补齐或对齐依赖,允许升级或降级;已匹配时不重新安装。
|
|
11
11
|
3. 检查依赖关系、全部预装库导入和简单 TA-Lib 计算。
|
|
12
12
|
4. 成功后将 venv 的 `bin` 放到当前宿主进程 PATH 前端,设置 `VIRTUAL_ENV`,移除 `PYTHONHOME`、`PYTHONPATH` 并禁用用户 site-packages。主会话与专家的原生 Bash 继承该环境。
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
| Linux | `${XDG_DATA_HOME:-~/.local/share}/pbot/python/.venv`;仅使用绝对 XDG_DATA_HOME |
|
|
17
17
|
| macOS | `~/Library/Application Support/pbot/python/.venv` |
|
|
18
18
|
|
|
19
|
-
首次准备从当前 PATH 选择 python3,无该命令时使用 python;需要 Python 3.11+ 和 venv/ensurepip。系统 Python 只用于创建独立 venv
|
|
19
|
+
首次准备从当前 PATH 选择 python3,无该命令时使用 python;需要 Python 3.11+ 和 venv/ensurepip。系统 Python 只用于创建独立 venv,不在系统环境中安装依赖。已有 venv 按锁文件对齐,保留额外安装的包。基础解释器被移除或升级、导致共享 venv 的解释器无法启动时,setup 用当前 Python 3.11+ 重建该 venv,原有包随之移除;非 venv 数据、符号链接和其他 Python 环境不会被覆盖或删除。
|
|
20
20
|
|
|
21
21
|
首次安装可能需要数分钟和网络。`/pbot init` 创建共用启用配置并启动环境准备;手工设置 enabled 为 true 后重载也会准备环境。不需要 Personal Bot 的工作区可保留配置缺失或设置 enabled 为 false,再重载或重启宿主;也可通过宿主原生配置取消加载整个插件。`/pbot status` 显示环境状态。所属激活生命周期关闭时恢复本扩展修改的进程环境变量;dsh 按整个 pbot 组件共享激活,不随某个浏览器页面或单个工作区关闭而恢复,不覆盖期间其他代码对变量的新修改。外部终端和 shell 配置不变。
|
|
22
22
|
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
/pbot python setup
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
-
无需路径和额外确认,执行同一准备逻辑,成功后激活。也可重启 pbot。安装限时 15
|
|
33
|
+
无需路径和额外确认,执行同一准备逻辑,成功后激活。也可重启 pbot。安装限时 15 分钟,超时或关闭会取消准备;不会自动回滚或循环重试。失败留下的环境保留,下次 setup 继续按锁文件补齐。共享 venv 解释器无法启动时自动重建;其他损坏不自动删除环境,可自行删除该目录后重试。缺少 pip 时仅尝试该 venv 的 ensurepip。
|
|
34
34
|
|
|
35
35
|
安装只接受 wheel,不编译 C 库、不安装系统软件,不绕过系统 Python 的安装保护。没有匹配 wheel、网络不可用、权限不足或环境损坏时停止。TA-Lib wheel 包含底层库,但并非所有系统和架构都有匹配 wheel。pip 安装配置被忽略,避免包被重定向到其他目标。
|
|
36
36
|
|
package/scripts/README.md
CHANGED
|
@@ -21,6 +21,12 @@
|
|
|
21
21
|
|
|
22
22
|
脚本使用隔离的用户目录、宿主配置与工作目录,完成后清理临时目录。两项检查均不调用模型;Pi 使用预置故障目录跳过 Python 依赖下载,dsh 通过原生 schema 收集导入 Host。
|
|
23
23
|
|
|
24
|
+
## ACP 真实模型 E2E
|
|
25
|
+
|
|
26
|
+
在已配置 Pi、dsh、Claude 原生模型与认证的环境执行 `npm run test:e2e:acp`。该命令在临时工作区调用三个真实后端,省略 model、thinking 和 provider 验证默认值;另测 Claude 显式 low 覆盖原生环境 max。检查文件结果、报告分页、停止耗时,并对照 Claude 原生请求中的模型与思考等级。它单独运行,不进入 `npm test`。
|
|
27
|
+
|
|
28
|
+
入口默认从 PATH 查找。可用 `PBOT_ACP_E2E_PI_COMMAND`、`PBOT_ACP_E2E_DSH_COMMAND`、`PBOT_ACP_E2E_CLAUDE_COMMAND` 指定已有可执行文件路径;dsh 仍使用 acp profile。`PBOT_ACP_E2E_OUTPUT_DIR` 指定输出目录,默认使用临时目录;每个工作区保留 input.json、output.json、report.txt 和 result.json;Claude 用例还保留仅含模型与等级的 native-requests.json。
|
|
29
|
+
|
|
24
30
|
## Python 准备
|
|
25
31
|
|
|
26
32
|
`setup-python.py` 按 `python/requirements.lock` 准备用户共享 venv。Personal Bot 加载时自动调用,也可运行独立脚本或 `/pbot python setup`。路径、依赖与排障见 [Python 说明](../python/README.md)。
|
package/scripts/setup-python.py
CHANGED
|
@@ -6,6 +6,7 @@ import json
|
|
|
6
6
|
import os
|
|
7
7
|
from pathlib import Path
|
|
8
8
|
import re
|
|
9
|
+
import shutil
|
|
9
10
|
import stat
|
|
10
11
|
import subprocess
|
|
11
12
|
import sys
|
|
@@ -54,6 +55,7 @@ def locked_packages():
|
|
|
54
55
|
|
|
55
56
|
|
|
56
57
|
def inspect_environment(target):
|
|
58
|
+
"""Return the shared venv description; None means it must be created or rebuilt."""
|
|
57
59
|
if target.is_symlink():
|
|
58
60
|
raise ValueError("共享环境目录不能是符号链接。")
|
|
59
61
|
if not target.exists():
|
|
@@ -63,7 +65,16 @@ def inspect_environment(target):
|
|
|
63
65
|
raise ValueError("共享环境位置已被非 venv 数据占用;不会覆盖或删除。")
|
|
64
66
|
if re.search(r"include-system-site-packages\s*=\s*true", config.read_text(), re.I):
|
|
65
67
|
raise ValueError("共享 venv 不能继承系统 site-packages。")
|
|
66
|
-
|
|
68
|
+
try:
|
|
69
|
+
probe = subprocess.run([str(target / "bin/python"), "-I", "-B", "-c", INSPECT],
|
|
70
|
+
capture_output=True, text=True)
|
|
71
|
+
except OSError:
|
|
72
|
+
# The base interpreter was removed, so the environment cannot run.
|
|
73
|
+
return None
|
|
74
|
+
if probe.returncode != 0:
|
|
75
|
+
# The base interpreter was upgraded, or the copied executable is damaged.
|
|
76
|
+
return None
|
|
77
|
+
info = json.loads(probe.stdout)
|
|
67
78
|
if Path(info["prefix"]).resolve() != target.resolve() or info["prefix"] == info["basePrefix"]:
|
|
68
79
|
raise ValueError("解释器不属于共享 venv;不会修改其他 Python 环境。")
|
|
69
80
|
if info["version"][:2] < [3, 11]:
|
|
@@ -76,11 +87,15 @@ def plan(target):
|
|
|
76
87
|
required = locked_packages()
|
|
77
88
|
current = inspect_environment(target)
|
|
78
89
|
installed = (current or {}).get("packages", {})
|
|
90
|
+
changes = [{"package": name, "from": installed.get(name), "to": version}
|
|
91
|
+
for name, version in required.items() if installed.get(name) != version]
|
|
92
|
+
if current is None:
|
|
93
|
+
action = "rebuild" if target.exists() else "create"
|
|
94
|
+
else:
|
|
95
|
+
action = "update" if changes else "verify"
|
|
79
96
|
return {
|
|
80
|
-
"directory": str(target), "python": str(target / "bin/python"),
|
|
81
|
-
"current": current, "required": required,
|
|
82
|
-
"changes": [{"package": name, "from": installed.get(name), "to": version}
|
|
83
|
-
for name, version in required.items() if installed.get(name) != version],
|
|
97
|
+
"action": action, "directory": str(target), "python": str(target / "bin/python"),
|
|
98
|
+
"current": current, "required": required, "changes": changes,
|
|
84
99
|
}
|
|
85
100
|
|
|
86
101
|
|
|
@@ -94,7 +109,10 @@ def setup(target):
|
|
|
94
109
|
# Concurrent startups wait, then inspect again rather than apply stale plans.
|
|
95
110
|
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
96
111
|
actual = plan(target)
|
|
97
|
-
if actual["
|
|
112
|
+
if actual["action"] == "rebuild":
|
|
113
|
+
print("共享 venv 的解释器无法运行,重建共享环境。", file=sys.stderr)
|
|
114
|
+
shutil.rmtree(target)
|
|
115
|
+
if actual["action"] in ("create", "rebuild"):
|
|
98
116
|
venv.EnvBuilder(with_pip=True).create(target)
|
|
99
117
|
python = str(target / "bin/python")
|
|
100
118
|
|
|
@@ -126,6 +144,11 @@ def setup(target):
|
|
|
126
144
|
|
|
127
145
|
|
|
128
146
|
def main():
|
|
147
|
+
# venv records the invoking path as its home; resolve first so a symlinked launcher
|
|
148
|
+
# (for example a relocatable CPython managed by another tool) yields a usable base.
|
|
149
|
+
real = os.path.realpath(sys.executable) if sys.executable else ""
|
|
150
|
+
if real and real != sys.executable:
|
|
151
|
+
os.execv(real, [real, "-I", "-B", os.path.abspath(__file__), *sys.argv[1:]])
|
|
129
152
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
130
153
|
parser.add_argument("--check", action="store_true", help="只检查共享环境,不创建或安装")
|
|
131
154
|
args = parser.parse_args()
|
|
@@ -139,6 +162,9 @@ if __name__ == "__main__":
|
|
|
139
162
|
try:
|
|
140
163
|
main()
|
|
141
164
|
except (Exception, KeyboardInterrupt) as error:
|
|
165
|
+
if isinstance(error, subprocess.CalledProcessError) and error.output:
|
|
166
|
+
print(error.output if isinstance(error.output, str) else error.output.decode(errors="replace"),
|
|
167
|
+
file=sys.stderr, end="")
|
|
142
168
|
print(str(error), file=sys.stderr)
|
|
143
|
-
print("共享 Python 环境未就绪。请检查 Python 3.11+、venv/ensurepip、网络、安装权限和 wheel;修复后执行 /pbot python setup
|
|
169
|
+
print("共享 Python 环境未就绪。请检查 Python 3.11+、venv/ensurepip、网络、安装权限和 wheel;修复后执行 /pbot python setup 或重启。不改用系统环境安装或编译 C 库;共享 venv 解释器无法运行时会重建,其他数据不删除。", file=sys.stderr)
|
|
144
170
|
sys.exit(1)
|
package/src/dsh.ts
CHANGED
|
@@ -8,6 +8,7 @@ export const name = "personal-bot";
|
|
|
8
8
|
export const inject = ["commands", "typert", ...dshDependencies];
|
|
9
9
|
|
|
10
10
|
export async function apply(ctx: Context) {
|
|
11
|
+
if (process.env.PBOT_SUBAGENT_RUN_ID) return;
|
|
11
12
|
const [major, minor] = process.versions.node.split(".").map(Number);
|
|
12
13
|
requireThat(major! > 24 || (major === 24 && minor! >= 9), "dsh 接入需要 Node.js 24.9.0 或更新版本。");
|
|
13
14
|
const workspaces = new DshWorkspaces(ctx);
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { dirname, join } from "node:path";
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { AgentFiles, descriptor, launch } from "../storage/agent-files.js";
|
|
5
|
+
import { acpInput, acpAnswer } from "../storage/acp-files.js";
|
|
6
|
+
import type { AcpInput, AcpAnswer } from "../model/acp.js";
|
|
7
|
+
import { requireThat } from "../common/validation.js";
|
|
8
|
+
import { resourceRoot } from "../common/paths.js";
|
|
9
|
+
import { packageVersion, releaseLine } from "../common/version.js";
|
|
10
|
+
import { agentText } from "../integrations/agent-resources.js";
|
|
11
|
+
import { readWorkspaceConfig, workspaceDisabledMessage } from "../services/workspace/workspace-config.js";
|
|
12
|
+
|
|
13
|
+
export async function acpMember() {
|
|
14
|
+
const id = process.env.PBOT_SUBAGENT_RUN_ID, directory = process.env.PBOT_SUBAGENT_DIR, generation = process.env.PBOT_SUBAGENT_GENERATION;
|
|
15
|
+
requireThat(id && directory && generation, "缺少 ACP 成员启动身份。");
|
|
16
|
+
const files = new AgentFiles(dirname(realpathSync(directory)));
|
|
17
|
+
requireThat(files.directory(id) === realpathSync(directory), "ACP 成员目录不匹配。");
|
|
18
|
+
const d = files.read(id, "descriptor.json", descriptor);
|
|
19
|
+
requireThat(d.agentId === id && releaseLine(d.release) === releaseLine(packageVersion), "ACP 成员身份或版本无效。");
|
|
20
|
+
const configuration = await readWorkspaceConfig(d.workspace);
|
|
21
|
+
requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
|
|
22
|
+
const check = () => {
|
|
23
|
+
files.check();
|
|
24
|
+
const run = files.read(id, "launch.json", launch);
|
|
25
|
+
requireThat(run.generation === generation && (!run.stop || process.env.PBOT_ACP_VALIDATE === "1"), "ACP 成员已停止或启动代次变化。");
|
|
26
|
+
};
|
|
27
|
+
const context = async () => {
|
|
28
|
+
const [workspace, role] = await Promise.all([readFile(join(resourceRoot, "prompts/workspace.md"), "utf8"), agentText("general-purpose", d.workspace)]);
|
|
29
|
+
const state = process.env.PBOT_ACP_PYTHON_STATE ?? "unavailable";
|
|
30
|
+
const python = state === "ready" && process.env.VIRTUAL_ENV ? { state, directory: process.env.VIRTUAL_ENV } : { state };
|
|
31
|
+
return { workspace, role, environment: JSON.stringify({ workspaceRoot: d.workspace, resourceRoot, python }) };
|
|
32
|
+
};
|
|
33
|
+
return { files, d, id, generation, check, context,
|
|
34
|
+
input() {
|
|
35
|
+
check(); const input = files.read(id, "acp-input.json", acpInput);
|
|
36
|
+
requireThat(input.generation === generation, "ACP 输入代次无效。"); return input;
|
|
37
|
+
},
|
|
38
|
+
answer(input: AcpInput, state: AcpAnswer["state"], answer: string, error?: string) {
|
|
39
|
+
// A stop can race the native terminal event. The current generation may still seal its result.
|
|
40
|
+
if (files.read(id, "launch.json", launch).generation !== generation) return;
|
|
41
|
+
files.write(id, "acp-answer.json", { ...input, state, answer, ...(error ? { error } : {}) }, acpAnswer);
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { AgentFiles, descriptor, launch, status } from "../storage/agent-files.js";
|
|
4
|
+
import { acpModelState, acpReference } from "../storage/acp-files.js";
|
|
5
|
+
import type { AcpModelSelection } from "../model/acp.js";
|
|
6
|
+
import { AcpAgentRun } from "../services/agents/acp-run.js";
|
|
7
|
+
import { openAcp } from "../integrations/acp/connection.js";
|
|
8
|
+
import { acpExecutable } from "../integrations/acp/launch.js";
|
|
9
|
+
import { claudeOptions } from "../integrations/acp/claude.js";
|
|
10
|
+
import { acpContent } from "../integrations/acp/input.js";
|
|
11
|
+
import { agentText } from "../integrations/agent-resources.js";
|
|
12
|
+
import { activatePython } from "../integrations/python-activation.js";
|
|
13
|
+
import { PythonEnvironmentService } from "../services/workspace/python-environment-service.js";
|
|
14
|
+
import { resourceRoot } from "../common/paths.js";
|
|
15
|
+
import { requireThat } from "../common/validation.js";
|
|
16
|
+
import { packageVersion, releaseLine } from "../common/version.js";
|
|
17
|
+
import type { NativeAgentHost } from "../model/agent.js";
|
|
18
|
+
|
|
19
|
+
const args = process.argv.slice(2);
|
|
20
|
+
const option = (name: string) => args[args.indexOf(name) + 1];
|
|
21
|
+
const directory = option("--directory"), id = option("--pbot-acp-agent"), generation = option("--generation");
|
|
22
|
+
requireThat(directory && id && generation, "缺少 ACP worker 启动信息。");
|
|
23
|
+
const files = new AgentFiles(dirname(directory), option("--host") as NativeAgentHost);
|
|
24
|
+
requireThat(files.directory(id) === directory, "ACP worker 目录不匹配。");
|
|
25
|
+
const d = files.read(id, "descriptor.json", descriptor), reference = files.read(id, "acp-session.json", acpReference);
|
|
26
|
+
requireThat(d.agentId === id && releaseLine(d.release) === releaseLine(packageVersion), "ACP worker 身份或版本不匹配。");
|
|
27
|
+
const validating = args.includes("--validate"), lifetime = new AbortController();
|
|
28
|
+
let execution: AcpAgentRun | undefined, restorePython: (() => void) | undefined;
|
|
29
|
+
const python = new PythonEnvironmentService(d.workspace);
|
|
30
|
+
const stop = () => { void execution?.stop().catch(error => lifetime.abort(error)); if (!execution) lifetime.abort(); };
|
|
31
|
+
process.on("SIGTERM", stop); process.on("SIGINT", stop);
|
|
32
|
+
|
|
33
|
+
async function main() {
|
|
34
|
+
requireThat(files.read(id!, "launch.json", launch).generation === generation, "ACP worker 启动代次已失效。");
|
|
35
|
+
if (!validating) {
|
|
36
|
+
try { const prepared = await python.setup(lifetime.signal); restorePython = activatePython(prepared.directory); }
|
|
37
|
+
catch { lifetime.signal.throwIfAborted(); }
|
|
38
|
+
}
|
|
39
|
+
const env = { ...process.env, PBOT_ACP_PYTHON_STATE: validating ? "unavailable" : python.status.state, PBOT_SUBAGENT_RUN_ID: id!, PBOT_SUBAGENT_DIR: directory!, PBOT_SUBAGENT_GENERATION: generation!,
|
|
40
|
+
...(validating ? { PBOT_ACP_VALIDATE: "1" } : {}) };
|
|
41
|
+
const command = { ...reference, args: [...reference.args] };
|
|
42
|
+
const packageRoot = resolve(resourceRoot, "..");
|
|
43
|
+
if (reference.backend === "pi") {
|
|
44
|
+
Object.assign(env, { PBOT_ACP_PI_COMMAND: process.env.PI_ACP_PI_COMMAND ?? acpExecutable("pi", "pi"),
|
|
45
|
+
PI_ACP_PI_COMMAND: join(packageRoot, "bin/pbot-pi-acp.mjs") });
|
|
46
|
+
}
|
|
47
|
+
if (reference.backend === "dsh") {
|
|
48
|
+
const patch = join(directory!, "acp-dsh-patch.json");
|
|
49
|
+
await writeFile(patch, JSON.stringify([{ insert: [{ id: "pbot-acp-member", name: join(packageRoot, "lib/extension/dsh/acp-member.js") }] }]) + "\n", { mode: 0o600 });
|
|
50
|
+
command.args.push("--patch", patch);
|
|
51
|
+
}
|
|
52
|
+
let prompt: string | undefined;
|
|
53
|
+
if (reference.backend === "claude") {
|
|
54
|
+
prompt = [await readFile(join(resourceRoot, "prompts/workspace.md"), "utf8"), await agentText("general-purpose", d.workspace),
|
|
55
|
+
JSON.stringify({ workspaceRoot: d.workspace, resourceRoot, python: python.status.state === "ready"
|
|
56
|
+
? { state: "ready", directory: process.env.VIRTUAL_ENV } : { state: python.status.state } })].join("\n\n");
|
|
57
|
+
}
|
|
58
|
+
const saveSelection = (selection: AcpModelSelection) => {
|
|
59
|
+
if (validating) return;
|
|
60
|
+
const run = files.read(id!, "launch.json", launch);
|
|
61
|
+
if (run.generation === generation && !run.stop) files.write(id!, "acp-model.json", { generation, ...selection }, acpModelState);
|
|
62
|
+
};
|
|
63
|
+
const claude = reference.backend === "claude" ? await claudeOptions(reference, d.cwd, d.options.thinking) : undefined;
|
|
64
|
+
const connection = await openAcp(command, d.cwd, env, {
|
|
65
|
+
selection: saveSelection,
|
|
66
|
+
update(update) {
|
|
67
|
+
if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") execution?.update({ kind: "text", text: update.content.text,
|
|
68
|
+
...(update.messageId ? { messageId: update.messageId } : {}) });
|
|
69
|
+
else if (update.sessionUpdate === "agent_thought_chunk") execution?.update({ kind: "thought" });
|
|
70
|
+
else if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") execution?.update({ kind: update.sessionUpdate === "tool_call" ? "tool" : "activity", activity: update.name ?? update.title ?? "工具" });
|
|
71
|
+
},
|
|
72
|
+
async permission(request, signal) {
|
|
73
|
+
if (!execution) return { outcome: { outcome: "cancelled" } };
|
|
74
|
+
const selected = await execution.permission(JSON.stringify(request.toolCall, null, 2), request.options, signal);
|
|
75
|
+
return { outcome: selected === null ? { outcome: "cancelled" } : { outcome: "selected", optionId: selected } };
|
|
76
|
+
},
|
|
77
|
+
}, lifetime.signal, prompt, claude);
|
|
78
|
+
try {
|
|
79
|
+
requireThat(!prompt || reference.backend !== "claude" || connection.systemPrompt, "Claude ACP 后端需要支持 systemPrompt,以加载专家职责与工作区资料。");
|
|
80
|
+
if (validating) { process.send?.({ type: "validated" }); return; }
|
|
81
|
+
if (reference.sessionId === null) await connection.configure(d.options);
|
|
82
|
+
requireThat(files.read(id!, "launch.json", launch).generation === generation && !files.read(id!, "launch.json", launch).stop, "ACP 启动已取消。");
|
|
83
|
+
files.write(id!, "acp-session.json", { ...reference, sessionId: reference.backend === "dsh" || reference.sessionId !== null ? connection.sessionId : null, capabilities: connection.capabilities }, acpReference);
|
|
84
|
+
saveSelection(connection.selection());
|
|
85
|
+
execution = new AcpAgentRun(files, d, generation!, {
|
|
86
|
+
signal: connection.signal,
|
|
87
|
+
async prompt(request) {
|
|
88
|
+
const content = await acpContent(request, connection.images, connection.signal);
|
|
89
|
+
const run = files.read(id!, "launch.json", launch);
|
|
90
|
+
requireThat(run.generation === generation && !run.stop, "ACP 输入已取消或启动代次变化。");
|
|
91
|
+
connection.signal.throwIfAborted();
|
|
92
|
+
const saved = files.read(id!, "acp-session.json", acpReference);
|
|
93
|
+
if (saved.sessionId === null) files.write(id!, "acp-session.json", { ...saved, sessionId: connection.sessionId }, acpReference);
|
|
94
|
+
return connection.prompt(content);
|
|
95
|
+
},
|
|
96
|
+
cancel: () => connection.cancel(),
|
|
97
|
+
}, reference.backend !== "claude");
|
|
98
|
+
await execution.run();
|
|
99
|
+
} finally {
|
|
100
|
+
try { await connection.close(); } finally { await execution?.settled(); }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
await main();
|
|
106
|
+
if (!validating && files.read(id, "launch.json", launch).generation === generation) {
|
|
107
|
+
if (execution) execution.execution.save({ state: "stopped", activity: "已停止" });
|
|
108
|
+
else files.write(id, "status.json", { generation, state: "stopped", activity: "已停止", updatedAt: Date.now() }, status);
|
|
109
|
+
}
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (validating) process.send?.({ type: "error", error: String(error) });
|
|
112
|
+
else if (files.read(id, "launch.json", launch).generation === generation) {
|
|
113
|
+
const stopped = files.read(id, "launch.json", launch).stop;
|
|
114
|
+
const patch = { state: stopped ? "stopped" as const : "error" as const, activity: stopped ? "已停止" : "ACP 执行失败", ...(stopped ? {} : { error: String(error) }) };
|
|
115
|
+
if (execution) execution.execution.save(patch);
|
|
116
|
+
else files.write(id, "status.json", { generation, ...patch, updatedAt: Date.now() }, status);
|
|
117
|
+
}
|
|
118
|
+
process.exitCode = 1;
|
|
119
|
+
} finally {
|
|
120
|
+
lifetime.abort();
|
|
121
|
+
try { await python.close(); } finally { restorePython?.(); }
|
|
122
|
+
if (process.connected) process.disconnect();
|
|
123
|
+
// Keep child processes in this worker's process group so forced release covers descendants.
|
|
124
|
+
}
|
|
@@ -34,6 +34,29 @@ export function registerAgentEvents(pi: ExtensionAPI, lifecycle: Lifecycle, conf
|
|
|
34
34
|
// Only a lock-busy, not-yet-published input is retried in this runtime. Reload discards this map.
|
|
35
35
|
const dispatching = new Map<string, TeamInput>();
|
|
36
36
|
let pausePending = false;
|
|
37
|
+
const approving = new Map<string, AbortController>();
|
|
38
|
+
const collectPermissions = () => {
|
|
39
|
+
const instance = lifecycle.active, context = ctx, revision = epoch;
|
|
40
|
+
if (!instance || !context) return;
|
|
41
|
+
const requests = instance.agents.pendingPermissions(agentOwner(context));
|
|
42
|
+
const pending = new Set(requests.map(request => request.agentId + ":" + request.requestId));
|
|
43
|
+
for (const [key, controller] of approving) if (!pending.has(key)) { controller.abort(); approving.delete(key); }
|
|
44
|
+
for (const request of requests) {
|
|
45
|
+
const key = request.agentId + ":" + request.requestId;
|
|
46
|
+
if (approving.has(key)) continue;
|
|
47
|
+
const controller = new AbortController(); approving.set(key, controller);
|
|
48
|
+
void (async () => {
|
|
49
|
+
const allow = request.options.find(option => option.kind === "allow_once");
|
|
50
|
+
const reject = request.options.find(option => option.kind === "reject_once");
|
|
51
|
+
const accepted = context.hasUI && allow ? await confirmations.ask(context, request.name + " 请求确认", request.description,
|
|
52
|
+
AbortSignal.any([controller.signal, instance.signal()])) : false;
|
|
53
|
+
if (controller.signal.aborted || epoch !== revision || lifecycle.active !== instance || !ctx) return;
|
|
54
|
+
instance.agents.answerPermission(request.agentId, request.requestId, accepted ? allow!.optionId : reject?.optionId ?? null, agentOwner(ctx));
|
|
55
|
+
})().catch(error => { if (!controller.signal.aborted && epoch === revision) recordFailure(error); }).finally(() => {
|
|
56
|
+
if (approving.get(key) === controller) approving.delete(key);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
};
|
|
37
60
|
const pauseTeams = () => {
|
|
38
61
|
const instance = lifecycle.active;
|
|
39
62
|
if (!ctx || !instance) return;
|
|
@@ -104,6 +127,7 @@ export function registerAgentEvents(pi: ExtensionAPI, lifecycle: Lifecycle, conf
|
|
|
104
127
|
try {
|
|
105
128
|
instance.agentOwner = agentOwner(ctx);
|
|
106
129
|
await instance.agents.refresh(instance.agentOwner);
|
|
130
|
+
collectPermissions();
|
|
107
131
|
const completed = await instance.agents.completions(instance.agentOwner);
|
|
108
132
|
if (!ctx || lifecycle.active !== instance || revision !== epoch) return;
|
|
109
133
|
const values = instance.agents.list(instance.agentOwner);
|
|
@@ -163,14 +187,15 @@ export function registerAgentEvents(pi: ExtensionAPI, lifecycle: Lifecycle, conf
|
|
|
163
187
|
return;
|
|
164
188
|
};
|
|
165
189
|
pi.on("session_start", (_event, context) => {
|
|
166
|
-
epoch++;
|
|
190
|
+
epoch++; for (const controller of approving.values()) controller.abort(); approving.clear();
|
|
191
|
+
ctx = context; paused = false; pausePending = false; controlBusySince = undefined; failure = undefined; recoveredFailure = undefined; confirmations.resume(); submitting.clear(); dispatching.clear();
|
|
167
192
|
if (timer) clearInterval(timer);
|
|
168
193
|
if (lifecycle.active) { lifecycle.active.agentOwner = agentOwner(ctx); timer = setInterval(() => { void refresh(); }, 1000); timer.unref(); }
|
|
169
194
|
return refresh();
|
|
170
195
|
});
|
|
171
196
|
pi.on("input", (_event, context) => { ctx = context; paused = false; confirmations.resume(); });
|
|
172
197
|
pi.on("before_agent_start", (_event, context) => { ctx = context; });
|
|
173
|
-
pi.on("session_tree", (_event, context) => { epoch++; ctx = context; submitting.clear(); return refresh(); });
|
|
198
|
+
pi.on("session_tree", (_event, context) => { epoch++; for (const controller of approving.values()) controller.abort(); approving.clear(); ctx = context; submitting.clear(); return refresh(); });
|
|
174
199
|
pi.on("turn_end", (event, context) => boundary(event.outcome, event.entries, context));
|
|
175
200
|
pi.on("agent_before_settle", (event, context) => boundary(event.outcome, event.entries, context));
|
|
176
201
|
pi.on("agent_settled", (event, context) => {
|
|
@@ -181,5 +206,5 @@ export function registerAgentEvents(pi: ExtensionAPI, lifecycle: Lifecycle, conf
|
|
|
181
206
|
const keys = (event.details as { agentReadKeys?: string[] } | undefined)?.agentReadKeys;
|
|
182
207
|
if (keys?.length) pi.appendEntry("pbot.agent-read", { keys, toolCallId: event.parentToolCallId ?? event.toolCallId });
|
|
183
208
|
});
|
|
184
|
-
pi.on("session_shutdown", () => { epoch++; if (timer) clearInterval(timer); timer = undefined; submitting.clear(); dispatching.clear(); pausePending = false; ctx = undefined; });
|
|
209
|
+
pi.on("session_shutdown", () => { epoch++; for (const controller of approving.values()) controller.abort(); approving.clear(); if (timer) clearInterval(timer); timer = undefined; submitting.clear(); dispatching.clear(); pausePending = false; ctx = undefined; });
|
|
185
210
|
}
|
|
@@ -23,14 +23,17 @@ export async function showAgents(_pi: ExtensionAPI, instance: WorkspaceInstance,
|
|
|
23
23
|
if (!picked.owned) { ctx.ui.notify("请返回所属分支操作。", "info"); continue; }
|
|
24
24
|
for (;;) {
|
|
25
25
|
instance.check(); const value = instance.agents.status(picked.agentId, owner()), inTmux = Boolean(process.env.TMUX);
|
|
26
|
-
const enterTui = value.alive ? "进入会话" : "打开原会话(待命)";
|
|
27
|
-
const action = await choose(ctx, `${value.name} · ${stateLabel(value.state)}`, [enterTui, "详情", ...(value.alive ? ["补充要求"] : []), "重命名", ...(value.alive ? ["停止"] : [])]);
|
|
26
|
+
const enterTui = value.transport === "acp" ? "查看任务与报告" : value.alive ? "进入会话" : "打开原会话(待命)";
|
|
27
|
+
const action = await choose(ctx, `${value.name} · ${stateLabel(value.state)}`, [enterTui, "详情", ...(value.alive ? ["补充要求"] : value.transport === "acp" ? ["携新要求恢复"] : []), "重命名", ...(value.alive ? ["停止"] : [])]);
|
|
28
28
|
if (!action) break;
|
|
29
29
|
instance.check();
|
|
30
30
|
try {
|
|
31
31
|
if (action === "详情") {
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
const selected = value.selection ?? value.options;
|
|
33
|
+
const model = [selected.provider, selected.model].filter(Boolean).join("/") || "目标宿主配置", resolved = value.selection?.resolvedModel;
|
|
34
|
+
await readPage(ctx, value.name, [`状态 ${stateLabel(value.state)}`, `活动 ${value.activity}`, `模型 ${model}${resolved && resolved !== model ? " → " + resolved : ""}`,
|
|
35
|
+
`思考 ${selected.thinking ?? "宿主默认"}`, `目录 ${value.cwd}`, `ID ${value.agentId}`, ...(value.backend ? [`宿主 ${value.backend}`] : []), ...(value.error ? ["", value.error] : []),
|
|
36
|
+
...(value.transport === "acp" ? [] : ["", `返回主会话:Ctrl+B → ${inTmux ? "l" : "d"}`])].join("\n")); continue;
|
|
34
37
|
}
|
|
35
38
|
if (action === "停止") { instance.agents.stop(value.agentId, owner()); ctx.ui.notify("已请求停止。", "info"); continue; }
|
|
36
39
|
if (action === "重命名") {
|
|
@@ -39,9 +42,34 @@ export async function showAgents(_pi: ExtensionAPI, instance: WorkspaceInstance,
|
|
|
39
42
|
}
|
|
40
43
|
if (action === "补充要求") {
|
|
41
44
|
const message = await ctx.ui.editor("补充要求"); instance.check();
|
|
42
|
-
if (message?.trim()) { instance.agents.send(value.agentId, message, "steer", owner()); ctx.ui.notify("要求已排队。", "info"); } continue;
|
|
45
|
+
if (message?.trim()) { instance.agents.send(value.agentId, message, value.transport === "acp" ? "followUp" : "steer", owner()); ctx.ui.notify("要求已排队。", "info"); } continue;
|
|
46
|
+
}
|
|
47
|
+
if (action === "携新要求恢复") {
|
|
48
|
+
const message = await ctx.ui.editor("新要求"); instance.check();
|
|
49
|
+
if (message?.trim()) await instance.agents.resume(value.agentId, message, owner());
|
|
50
|
+
continue;
|
|
43
51
|
}
|
|
44
52
|
if (action !== enterTui) continue;
|
|
53
|
+
if (value.transport === "acp") {
|
|
54
|
+
const data = await instance.agents.recordPage(value.agentId, owner(), { limit: 100 });
|
|
55
|
+
const records = ("records" in data ? data.records : []) ?? [];
|
|
56
|
+
await readPage(ctx, value.name, records.map(record => [record.type === "acp/input" ? "任务" : "报告",
|
|
57
|
+
record.state, new Date(record.time).toLocaleString(), "", record.preview].join("\n")).join("\n\n") || "还没有任务。");
|
|
58
|
+
const cycles = instance.agents.cycles(value.agentId, owner());
|
|
59
|
+
if (cycles.length) {
|
|
60
|
+
const titles = cycles.map(cycle => cycle.cycleId + " · " + cycle.state);
|
|
61
|
+
const selected = await choose(ctx, "读取周期报告", titles), cycle = cycles[titles.indexOf(selected ?? "")];
|
|
62
|
+
if (cycle) {
|
|
63
|
+
const chunks: string[] = []; let offset = 0;
|
|
64
|
+
for (;;) {
|
|
65
|
+
const page = await instance.agents.read(value.agentId, owner(), cycle.cycleId, offset);
|
|
66
|
+
chunks.push(page.report); if (page.nextOffset === null) break; offset = page.nextOffset;
|
|
67
|
+
}
|
|
68
|
+
await readPage(ctx, value.name, chunks.join(""));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
45
73
|
ctx.ui.notify(`返回主会话:Ctrl+B → ${inTmux ? "l" : "d"}`, "info");
|
|
46
74
|
let tui: TUI | undefined;
|
|
47
75
|
await ctx.ui.custom<void>((terminal, _theme, _keys, done) => { tui = terminal; queueMicrotask(() => done()); return new Text("", 0, 0); });
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
2
|
+
import type { AcpInput } from "../../model/acp.js";
|
|
3
|
+
import { acpMember } from "../acp-member.js";
|
|
4
|
+
import { dshResources, dshExpertTools } from "../../integrations/dsh/resources.js";
|
|
5
|
+
import { registerDshSkills } from "../../integrations/dsh/skills.js";
|
|
6
|
+
import { finalDshAnswer } from "../../integrations/dsh/messages.js";
|
|
7
|
+
import { registerDshFileEvents } from "./files.js";
|
|
8
|
+
import { requireThat } from "../../common/validation.js";
|
|
9
|
+
|
|
10
|
+
export const name = "pbot-acp-member";
|
|
11
|
+
export const inject = ["agents", "sessions", "llm", "tools", "systemPrompt", "skills", "fs", "workingDirectory", "approval"];
|
|
12
|
+
|
|
13
|
+
export async function apply(ctx: Context) {
|
|
14
|
+
const member = await acpMember();
|
|
15
|
+
ctx.on("agent/pre-step", async (_event, next) => {
|
|
16
|
+
if (process.env.PBOT_ACP_VALIDATE === "1") return { kind: "reject" };
|
|
17
|
+
member.input(); return next();
|
|
18
|
+
});
|
|
19
|
+
ctx.on("agent/created", async ({ agent, source }) => {
|
|
20
|
+
if (!ctx.agents.roots().includes(agent)) return;
|
|
21
|
+
if (source === "resume") agent.inbox.clear();
|
|
22
|
+
const reference = member.files.reference(member.id);
|
|
23
|
+
requireThat(reference.host === "acp" && reference.backend === "dsh" && agent.session.header.cwd === member.d.cwd &&
|
|
24
|
+
(reference.sessionId === null || reference.sessionId === agent.id), "dsh ACP 会话身份或工作目录不匹配。");
|
|
25
|
+
await agent.ctx.plugin({ name: "pbot-acp-expert", inject, apply: async scope => {
|
|
26
|
+
registerDshSkills(scope, agent);
|
|
27
|
+
dshExpertTools(scope, agent, member.d.options);
|
|
28
|
+
await dshResources(scope, agent, member.d.workspace, "general-purpose", () => process.env.PBOT_ACP_PYTHON_STATE === "ready" && process.env.VIRTUAL_ENV
|
|
29
|
+
? { state: "ready", directory: process.env.VIRTUAL_ENV } : { state: process.env.PBOT_ACP_PYTHON_STATE ?? "unavailable" }, member.check);
|
|
30
|
+
registerDshFileEvents(scope, agent, member.d.workspace, true, member.check);
|
|
31
|
+
let input: AcpInput | undefined, answer = "";
|
|
32
|
+
scope.on("session/event", (session, event) => {
|
|
33
|
+
if (session !== agent.session) return;
|
|
34
|
+
if (event.type === "turn/start") { input = member.input(); answer = ""; }
|
|
35
|
+
if (event.type === "assistant/message") answer = finalDshAnswer(event);
|
|
36
|
+
if (event.type === "turn/end" && input) {
|
|
37
|
+
const reason = event.data.reason;
|
|
38
|
+
member.answer(input, reason.kind === "completed" && answer.trim() ? "completed" : reason.kind === "aborted" ? "cancelled" : "failed", answer,
|
|
39
|
+
reason.kind === "error" ? reason.error.message : reason.kind === "completed" ? undefined : reason.kind);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
} });
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -15,6 +15,9 @@ const chatSchema = Type.Object({ agentId: Type.String({ minLength: 1 }), text: T
|
|
|
15
15
|
delivery: Type.Optional(Type.Union([Type.Literal("steer"), Type.Literal("followUp")])),
|
|
16
16
|
files: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { maxItems: 32 })) }, { additionalProperties: false });
|
|
17
17
|
const validChat = schema(chatSchema);
|
|
18
|
+
const approvalSchema = Type.Object({ agentId: Type.String({ minLength: 1 }), requestId: Type.String({ minLength: 1 }),
|
|
19
|
+
optionId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]) }, { additionalProperties: false });
|
|
20
|
+
const validApproval = schema(approvalSchema);
|
|
18
21
|
const usage = '用法:/pbot status | init | python setup | agent {"action":…} | chat {"agentId":…,"text":…} | team {"action":…} | post {"teamId":…,"text":…} | history {"action":…} | records {"agentId":…}';
|
|
19
22
|
|
|
20
23
|
export function registerDshCommand(ctx: Context, workspaces: DshWorkspaces, management: PbotManagement) {
|
|
@@ -60,7 +63,13 @@ export function registerDshCommand(ctx: Context, workspaces: DshWorkspaces, mana
|
|
|
60
63
|
case "chat": {
|
|
61
64
|
requireThat(validChat(input), "人工对话参数无效。");
|
|
62
65
|
const args = input as Static<typeof chatSchema>;
|
|
63
|
-
result = await workspace.
|
|
66
|
+
result = await workspace.interact(args.agentId, args.text ?? "", args.delivery, args.files, attachments, signal); break;
|
|
67
|
+
}
|
|
68
|
+
case "approval": {
|
|
69
|
+
requireThat(validApproval(input), "ACP 确认答复参数无效。");
|
|
70
|
+
const args = input as Static<typeof approvalSchema>;
|
|
71
|
+
workspace.agents.answerPermission(args.agentId, args.requestId, args.optionId, workspace.owner);
|
|
72
|
+
result = { answered: true }; break;
|
|
64
73
|
}
|
|
65
74
|
case "team": {
|
|
66
75
|
requireThat(validTeam(input), "团队参数无效。");
|
|
@@ -29,7 +29,7 @@ export function dshStatus(workspaces: DshWorkspaces, workspace: DshWorkspace): J
|
|
|
29
29
|
return json({ host: "dsh", release: packageVersion, enabled: true, state: "running", workspaceRoot: workspace.root, sessionId: workspace.agent.id,
|
|
30
30
|
model: workspace.agent.model.current() ?? null, python: workspaces.python.status,
|
|
31
31
|
controlError: workspace.controlError ?? null, history: workspace.history.status,
|
|
32
|
-
agents, teams: workspace.teams.list(workspace.owner, agents) });
|
|
32
|
+
agents, permissions: workspace.agents.pendingPermissions(workspace.owner), teams: workspace.teams.list(workspace.owner, agents) });
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
/** Status remains available when this workspace has not opted in. */
|
|
@@ -74,6 +74,7 @@ export class PbotManagement extends TypertRemoteService {
|
|
|
74
74
|
requireThat(validExpert(input), "专家记录查询参数无效。");
|
|
75
75
|
const args = input as Static<typeof expertSchema>;
|
|
76
76
|
const view = workspace.agents.status(args.agentId, workspace.owner);
|
|
77
|
+
if (view.transport === "acp") return json(await workspace.agents.recordPage(args.agentId, workspace.owner, args));
|
|
77
78
|
using observation = await this.ctx.sessionQuery.observeSession(SessionId(view.agentId), { projectionMode: "none", signal: current.signal });
|
|
78
79
|
workspace.check(); current.signal.throwIfAborted();
|
|
79
80
|
const header = observation.header;
|