@botlearn-course/daemon 0.0.29-beta.3 → 0.0.29-beta.5

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 (54) hide show
  1. package/README.md +29 -89
  2. package/dist/auth-store.d.ts +1 -11
  3. package/dist/auth-store.js +2 -83
  4. package/dist/cli.d.ts +0 -15
  5. package/dist/cli.js +12 -204
  6. package/dist/index.d.ts +0 -3
  7. package/dist/index.js +0 -3
  8. package/dist/run-dispatcher.d.ts +1 -5
  9. package/dist/run-dispatcher.js +41 -116
  10. package/dist/runtime-capabilities.js +3 -11
  11. package/dist/runtimes/engine.js +15 -52
  12. package/dist/runtimes/index.d.ts +1 -7
  13. package/dist/runtimes/index.js +1 -45
  14. package/dist/runtimes/pi-agent.js +38 -7
  15. package/dist/runtimes/pi-managed-launch.d.ts +5 -0
  16. package/dist/runtimes/pi-managed-launch.js +41 -0
  17. package/dist/runtimes/pi-managed-subagent-extension.d.ts +127 -0
  18. package/dist/runtimes/pi-managed-subagent-extension.js +300 -0
  19. package/dist/runtimes/pi-managed.d.ts +16 -2
  20. package/dist/runtimes/pi-managed.js +38 -16
  21. package/dist/runtimes/probe.d.ts +0 -5
  22. package/dist/runtimes/probe.js +0 -16
  23. package/dist/types.d.ts +10 -73
  24. package/dist/workspace.d.ts +0 -2
  25. package/dist/workspace.js +0 -10
  26. package/package.json +2 -2
  27. package/dist/course-client.d.ts +0 -46
  28. package/dist/course-client.js +0 -158
  29. package/dist/doctor.d.ts +0 -15
  30. package/dist/doctor.js +0 -85
  31. package/dist/runtime-profile.d.ts +0 -8
  32. package/dist/runtime-profile.js +0 -236
  33. package/dist/runtimes/acp-stream.d.ts +0 -96
  34. package/dist/runtimes/acp-stream.js +0 -490
  35. package/dist/runtimes/claude-code.d.ts +0 -41
  36. package/dist/runtimes/claude-code.js +0 -364
  37. package/dist/runtimes/codex.d.ts +0 -44
  38. package/dist/runtimes/codex.js +0 -348
  39. package/dist/runtimes/gemini.d.ts +0 -39
  40. package/dist/runtimes/gemini.js +0 -264
  41. package/dist/runtimes/hermes-agent.d.ts +0 -61
  42. package/dist/runtimes/hermes-agent.js +0 -191
  43. package/dist/runtimes/kimi.d.ts +0 -35
  44. package/dist/runtimes/kimi.js +0 -343
  45. package/dist/runtimes/native-tool-blocks.d.ts +0 -3
  46. package/dist/runtimes/native-tool-blocks.js +0 -98
  47. package/dist/runtimes/ndjson-stream.d.ts +0 -48
  48. package/dist/runtimes/ndjson-stream.js +0 -210
  49. package/dist/runtimes/openclaw-acp.d.ts +0 -52
  50. package/dist/runtimes/openclaw-acp.js +0 -893
  51. package/dist/runtimes/runtime-errors.d.ts +0 -20
  52. package/dist/runtimes/runtime-errors.js +0 -95
  53. package/dist/runtimes/text-cap.d.ts +0 -7
  54. package/dist/runtimes/text-cap.js +0 -25
package/README.md CHANGED
@@ -1,50 +1,23 @@
1
1
  # @botlearn-course/daemon
2
2
 
3
- BotLearn Course 的轻量本机 daemon:把课程任务(run)分发到你自己机器上的 agent runtime 执行
4
- (BYOA,Bring Your Own Agent)。daemon 用 install code 绑定你的 BotLearn 账号,然后轮询
5
- Course API 领取分配给本机的 run,在隔离工作区内调用本机已登录的 CLI runtime(Codex、
6
- Claude Code、Gemini 等)完成任务,并把过程事件与产出文件候选回传给课程服务。
3
+ BotLearn Course 托管沙盒的内部 daemon 包。它只在 Agent Service 托管 sandbox 内运行:
4
+ `botlearn-sandbox-supervisor` 以固定 argv 启动 `botlearn-course-daemon agent-service session`,
5
+ daemon 通过 WebSocket 与 Agent Service 保持 session,接收 `turn.start` 后在隔离 workspace 内调用
6
+ 托管 runtime,并把过程事件与产出文件候选经 Agent Service 回传课程服务。本包不提供学员本机安装、
7
+ 登录或轮询入口。
7
8
 
8
9
  - 零 production 依赖,只用 Node 内建模块(Node >= 20)。
9
- - 凭据只存本机,不经过第三方;runtime 复用你本机已有的登录状态。
10
+ - 每轮只接受服务端组装的 `runtime_prompt`;缺失或校验失败时本轮显式失败。
10
11
 
11
- ## 安装与使用
12
+ ## 托管启动
12
13
 
13
- 无需安装,直接用 `npx`:
14
-
15
- ```bash
16
- # 1. 环境自检:探测各 runtime 的安装 / 版本 / 登录状态
17
- npx --yes --package @botlearn-course/daemon@latest botlearn-course-daemon course doctor
18
-
19
- # 2. 登录:用前端「我的 Daemon」页面生成的 install code 绑定本机
20
- npx --yes --package @botlearn-course/daemon@latest botlearn-course-daemon course login --api-url <course-api-url> --code <blic_xxx> [--label <名称>]
21
-
22
- # 3. 启动:前台轮询并执行分配给本机的 run(Ctrl+C 优雅退出)
23
- npx --yes --package @botlearn-course/daemon@latest botlearn-course-daemon course start [--once] [--poll-interval-ms <ms>]
24
-
25
- # 4. 登出:删除本机凭据文件
26
- npx --yes --package @botlearn-course/daemon@latest botlearn-course-daemon course logout
27
- ```
28
-
29
- 命令说明:
30
-
31
- | 命令 | 说明 |
32
- | --- | --- |
33
- | `course login` | 用 install code 换取 daemon 凭据并写入本机 `auth.json`。`--api-url` 缺省时读 `BOTLEARN_COURSE_API_URL`;`--label` 缺省为本机 hostname。成功后打印 daemon id。 |
34
- | `course start` | 读取 `auth.json`,轮询 Course API 领取 run 并执行。`--once` 只领取一次(有 run 则等它执行完再退出);`--poll-interval-ms` 调整空轮询间隔。凭据过期/被吊销时提示重新 login 并退出。 |
35
- | `course logout` | 删除本机 `auth.json`。服务端吊销请在前端 daemon 列表操作。 |
36
- | `course doctor` | 打印 Auth 状态(不含 token)与 runtime 探测表(安装路径 / 版本 / 登录状态 / 安装提示)。 |
37
- | `--help` / `--version` | 帮助与版本。 |
38
-
39
- 包内还包含供 BotLearn 托管 sandbox 使用的内部命令
40
- `botlearn-sandbox-supervisor agent-service session`。它不是 BYOA 用户入口:生产环境只允许由
41
- Agent Service 以固定 argv 启动,通过 stdin 接收一次性 bootstrap。sandbox 中 daemon/runtime 分别
42
- 降权到 `botlearn-control`/`user` UID;继承 `NoNewPrivs=1`、无法使用 sudo 的平台保留 root control
43
- daemon,由 root-owned 固定 launcher 清空附加组后直接降权为 `user`。两条路径都为 DeepSeek
44
- 设置 `no_new_privs`,runtime 用户本身没有 sudo 权限。托管启动链只执行
14
+ 生产环境只允许由 Agent Service 以固定 argv 启动 `botlearn-sandbox-supervisor`,通过 stdin 接收一次性
15
+ bootstrap。sandbox 中 daemon/runtime 分别降权到 `botlearn-control`/`user` UID;继承 `NoNewPrivs=1`、
16
+ 无法使用 sudo 的平台保留 root control daemon,由 root-owned 固定 launcher 清空附加组后直接降权为
17
+ `user`。两条路径都为 DeepSeek 设置 `no_new_privs`,runtime 用户本身没有 sudo 权限。托管启动链只执行
45
18
  `/opt` 下的固定 Node、supervisor、daemon、launcher 与 DeepSeek 文件,不信任 provider 会开放给 runtime
46
19
  写入的 `/usr/local/bin`。
47
- `agent-service session --bootstrap-stdin` 同样属于受 supervisor 保护的内部协议,不应直接暴露给
20
+ `agent-service session --bootstrap-stdin` 属于受 supervisor 保护的内部协议,不应直接暴露给
48
21
  课程任务或 workspace shell。
49
22
 
50
23
  veFaaS Origin 的托管 workspace 使用用户级 NAS backing image。root bootstrap 完成 NFS、marker、
@@ -56,30 +29,17 @@ writer,再通过 root launcher 执行 ext4 sync、`fuse2fs` unmount、backing
56
29
 
57
30
  ## 支持的 runtime
58
31
 
59
- run 的 `runtime.id` 决定用哪个 adapter 执行;未指定时默认 `codex`。runtime 不可用时 run 会
60
- 直接失败(不做静默回退),请先用 `course doctor` 确认目标 runtime 可用。
61
-
62
- | runtime id | 名称 | 依赖的本机命令 | 二进制覆盖变量 | 说明 |
63
- | --- | --- | --- | --- | --- |
64
- | `codex` | Codex CLI | `codex` | `BOTLEARN_CODEX_BIN` | 默认 runtime |
65
- | `claude-code` | Claude Code | `claude` | `BOTLEARN_CLAUDE_BIN` | doctor 会额外探测登录状态 |
66
- | `gemini` | Gemini CLI | `gemini` | `BOTLEARN_GEMINI_BIN` | |
67
- | `kimi-cli` | Kimi CLI | `kimi` | `BOTLEARN_KIMI_CLI_BIN` | |
68
- | `deepseek-tui` | DeepSeek TUI | `deepseek` | `BOTLEARN_DEEPSEEK_TUI_BIN` | Linux/macOS 本地 server 会保留现有 MCP 配置并注入零依赖 `report_progress`;`botlearn` 是保留 server key。Windows 因固定 runtime 无法保证 MCP clean-env,首版 fail closed、不注入 progress |
69
- | `hermes-agent` | Hermes Agent | `hermes-acp` | `BOTLEARN_HERMES_AGENT_BIN` | ACP stdio 协议 |
70
- | `pi-agent` | Pi Agent | `pi` | `BOTLEARN_PI_AGENT_BIN` | 固定 `@earendil-works/pi-coding-agent@0.85.1`,要求 Node.js >=22.19.0;每轮使用独立 RPC(远程过程调用)进程 |
71
- | `openclaw-acp` | OpenClaw (ACP) | `openclaw` | `BOTLEARN_OPENCLAW_BIN` | 还需配置 `BOTLEARN_OPENCLAW_URL`(可选 `BOTLEARN_OPENCLAW_TOKEN` / `BOTLEARN_OPENCLAW_AGENT`),二进制或 URL 缺失时 doctor 标记不可用 |
72
- | `fake` | 假 runtime | 无 | — | 仅测试/演示用:产出确定性文本与一个 `draft.md`。默认隐藏,只有 `BOTLEARN_DAEMON_ENABLE_FAKE_RUNTIME=1` 时才注册并上报 |
32
+ run 的 `runtime.id` 决定用哪个 adapter 执行,没有默认回退。runtime 不可用时 run 直接失败。
73
33
 
74
- 各 runtime 的登录(API key / OAuth)沿用你本机已有的配置 —— daemon 不保存、不代管任何
75
- runtime 凭据。
34
+ | runtime id | 名称 | 说明 |
35
+ | --- | --- | --- |
36
+ | `deepseek-tui` | DeepSeek TUI / Codewhale | 托管镜像内固定版本;注入零依赖 `report_progress` MCP,`botlearn` 是保留 server key |
37
+ | `pi-agent` | Pi Agent | 固定 `@earendil-works/pi-coding-agent@0.85.1`,要求 Node.js >=22.19.0;每轮使用独立 RPC(远程过程调用)进程 |
38
+ | `fake` | 假 runtime | 仅测试/演示用:产出确定性文本与一个 `draft.md`。只有 `BOTLEARN_DAEMON_ENABLE_FAKE_RUNTIME=1` 时才注册 |
76
39
 
77
- ### Pi Agent 接入与协议验证
40
+ 模型凭据由 Agent Service 按 activation 签发短期代理授权,daemon 不保存长期 provider key。
78
41
 
79
- 本机安装 `npm install -g @earendil-works/pi-coding-agent@0.85.1`,使用 Pi 自身的配置管理模型
80
- 和凭据。模型参数可使用 `provider/model`。`BOTLEARN_PI_AGENT_BIN` 可覆盖本机执行路径,
81
- 未设置时查找 PATH 上的 `pi`;启动前检查精确版本,版本不匹配显式失败。
82
- 配置在下一轮启动时生效,删除覆盖即恢复 PATH 查找。
42
+ ### Pi Agent 会话与协议验证
83
43
 
84
44
  每轮使用独立 RPC 进程,原生会话保存在当前工作区的 `.botlearn-pi-runtime` 隐藏目录。
85
45
  daemon 持久化原生会话文件名,用显式 `--session` 续接;启动后先用 `get_state` 校验,再发送
@@ -87,7 +47,7 @@ daemon 持久化原生会话文件名,用显式 `--session` 续接;启动后
87
47
  持久对话。空文件、损坏记录、权限错误和协议失败明确报错,不自动重跑任务。
88
48
  系统提示、模型选择和授权技能随每轮进程刷新,继续禁用隐式发现;托管临时 HOME 清理不影响会话文件。
89
49
  托管执行沿用固定启动器、短期模型代理授权及显式课程技能目录;需部署匹配的镜像和 Daemon,
90
- 并通过 `AGENT_SERVICE_RUNTIMES` 开放。本机路径覆盖不会启用托管能力。
50
+ 并通过 `AGENT_SERVICE_RUNTIMES` 开放。
91
51
 
92
52
  真实程序协议测试使用本地模型替身,不读取 `.env` 或调用付费模型:
93
53
 
@@ -104,39 +64,21 @@ pnpm exec vitest run src/runtimes/__tests__/runtime-binaries.test.ts
104
64
 
105
65
  ## 环境变量
106
66
 
67
+ 托管 sandbox 的变量由 supervisor 与 Agent Service 设置,不应手工配置。
68
+
107
69
  | 变量 | 说明 |
108
70
  | --- | --- |
109
- | `BOTLEARN_COURSE_API_URL` | `course login --api-url` 缺省值 |
110
- | `BOTLEARN_DAEMON_HOME` | 覆盖本地状态根目录(默认 `~/.botlearn-course/daemon`;测试/多实例用) |
71
+ | `BOTLEARN_AGENT_SERVICE_WS_URL` / `BOTLEARN_AGENT_SERVICE_SANDBOX_ID` / `BOTLEARN_AGENT_SERVICE_SANDBOX_TOKEN` | 未使用 `--bootstrap-stdin` 时的 session 连接参数 |
72
+ | `BOTLEARN_DAEMON_HOME` | 状态根目录;托管时由 supervisor 设为 control home,未设置时为 `~/.botlearn-course/daemon` |
111
73
  | `BOTLEARN_DAEMON_DEBUG` | 非空时输出 debug 级日志 |
112
- | `BOTLEARN_<X>_BIN` | 覆盖某个 runtime 的二进制路径,各 runtime 的变量名见上表(如 `BOTLEARN_CLAUDE_BIN`),以 `course doctor` 输出为准 |
113
- | `BOTLEARN_OPENCLAW_URL` | OpenClaw gateway 地址(`openclaw-acp` 必需) |
114
- | `BOTLEARN_OPENCLAW_TOKEN` | OpenClaw gateway token(可选) |
115
- | `BOTLEARN_OPENCLAW_AGENT` | OpenClaw agent 名称(可选) |
116
74
  | `BOTLEARN_DAEMON_ENABLE_FAKE_RUNTIME` | 设为 `1` 时启用测试用 `fake` runtime |
117
75
 
118
- ## 本地文件布局与权限
119
-
120
- 所有状态位于 `~/.botlearn-course/daemon`(可用 `BOTLEARN_DAEMON_HOME` 覆盖):
121
-
122
- ```text
123
- ~/.botlearn-course/daemon/ # 0700
124
- auth.json # 0600,daemon 凭据(access/refresh token、courseApiUrl)
125
- machine-id # 0600,首次运行生成的机器指纹
126
- logs/ # 0700
127
- daemon.log # 0600,按 10MiB 轮转,保留 20 个历史文件
128
- workspaces/<agent_run_id>/ # 每个 run 一个隔离目录,0700
129
- work/ # runtime 的工作目录(cwd),产出文件候选从这里扫描
130
- transcript.jsonl # 本地执行记录(脱敏后写入)
131
- ```
132
-
133
76
  ## 安全说明
134
77
 
135
- - `auth.json` 是敏感凭据文件(0600),token 只存本机、只发给你 login 时指定的 Course API;
136
- 日志、transcript、doctor 输出、错误信息在写出前都会经过脱敏(token / api key / 密码等
137
- 字段与常见 token 形态一律替换为 `[REDACTED]`)。
78
+ - 日志、transcript、错误信息在写出前都会经过脱敏(token / api key / 密码等字段与常见
79
+ token 形态一律替换为 `[REDACTED]`)。
138
80
  - 文件扫描只访问 workspace 内路径;包含 `..`、绝对路径或反斜杠的路径会被拒绝。daemon
139
- 只上报相对路径、大小、sha256 和有界脱敏 preview,文件正文始终留在本地或托管 sandbox
81
+ 只上报相对路径、大小、sha256 和有界脱敏 preview,文件正文始终留在托管 sandbox
140
82
  的持久 workspace,不上传 Course Service 或对象存储。扫描或 metadata 上报失败不影响 run 终态。
141
83
  - 托管 Practice Agent 的学员输入附件由 Course Service 为当前 activation 签发单对象、短时效的
142
84
  存储源站 URL;daemon 直接下载并复核 grant 集合、大小、SHA-256、MIME 与图片签名。URL 只留在
@@ -148,8 +90,6 @@ pnpm exec vitest run src/runtimes/__tests__/runtime-binaries.test.ts
148
90
  - 浏览器执行流使用 `agent-stream/0.1`。推理文本经过凭据过滤和长度限制;工具在服务端投影为
149
91
  学员可见的安全动作。教师审计分别使用有界 `run.trace` 和 `run.observation`,权限由 Course
150
92
  Service 控制。原始工具参数、结果和供应商事件包不会直接进入浏览器。
151
- - `course logout` 只删除本机凭据;要让服务端立即吊销该 daemon,请在前端 daemon 列表执行
152
- revoke。
153
93
  - 本包 production 依赖为零,发布 tarball 只包含 `dist/`、`README.md`、`package.json`、
154
94
  `LICENSE`(CI 发布前强制校验)。
155
95
  - 托管 session 的 control token/reconnect state 位于 runtime UID 不可访问的 `0700` control home;
@@ -161,7 +101,7 @@ pnpm exec vitest run src/runtimes/__tests__/runtime-binaries.test.ts
161
101
  runtime workspace 独立可写。activation-scoped Skill Provider binding 只留在 daemon control
162
102
  process 内存;DeepSeek 只通过 clean-env `course_skills` Unix Socket relay 按需读取当前授权
163
103
  `SKILL.md`/reference,endpoint/token 不进入 runtime env、MCP config、state、workspace 或日志。
164
- Prompt Pack 仍通过受信 system context 应用。长期模型 provider key 留在 Agent Service,runtime
104
+ 系统提示词只使用服务端下发的 `runtime_prompt`。长期模型 provider key 留在 Agent Service,runtime
165
105
  只拿 generation-scoped proxy grant。
166
106
 
167
107
  ## 流式缓冲约束
@@ -1,16 +1,6 @@
1
- import type { DaemonAuth } from "./types.js";
2
1
  /**
3
- * 本地身份与状态目录(spec §5)。
2
+ * 本地状态目录(spec §5)。
4
3
  * 可用 BOTLEARN_DAEMON_HOME 覆盖根目录(测试 / 多实例)。
5
4
  */
6
5
  export declare function daemonHome(): string;
7
6
  export declare function ensureDaemonHome(): string;
8
- export declare function authFilePath(): string;
9
- export declare function writeAuth(auth: DaemonAuth): void;
10
- export declare function readAuth(): DaemonAuth | null;
11
- export declare function clearAuth(): boolean;
12
- /**
13
- * 稳定的本机指纹:首次生成 randomUUID 并持久化到 <home>/machine-id(0600),
14
- * 之后跨进程 / 跨重启保持不变,供 login 上报。
15
- */
16
- export declare function machineFingerprint(): string;
@@ -1,9 +1,8 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
2
- import { randomBytes, randomUUID } from "node:crypto";
1
+ import { chmodSync, mkdirSync } from "node:fs";
3
2
  import { homedir } from "node:os";
4
3
  import path from "node:path";
5
4
  /**
6
- * 本地身份与状态目录(spec §5)。
5
+ * 本地状态目录(spec §5)。
7
6
  * 可用 BOTLEARN_DAEMON_HOME 覆盖根目录(测试 / 多实例)。
8
7
  */
9
8
  export function daemonHome() {
@@ -24,83 +23,3 @@ export function ensureDaemonHome() {
24
23
  }
25
24
  return home;
26
25
  }
27
- export function authFilePath() {
28
- return path.join(daemonHome(), "auth.json");
29
- }
30
- // 原子写:先写同目录 tmp 文件(0600)再 rename,读方永远看不到半写状态。
31
- function writeFileAtomic(file, content) {
32
- const tmp = `${file}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
33
- try {
34
- writeFileSync(tmp, content, { encoding: "utf8", mode: 0o600 });
35
- renameSync(tmp, file);
36
- }
37
- catch (err) {
38
- try {
39
- unlinkSync(tmp);
40
- }
41
- catch {
42
- // tmp 可能尚未创建。
43
- }
44
- throw err;
45
- }
46
- // writeFileSync 的 mode 受 umask 影响之外还可能被目标文件旧权限覆盖(rename 保留 tmp 权限,
47
- // 但 Windows 无 chmod),这里再收紧一次。
48
- try {
49
- chmodSync(file, 0o600);
50
- }
51
- catch {
52
- // Windows 等不支持 chmod 时忽略。
53
- }
54
- }
55
- export function writeAuth(auth) {
56
- ensureDaemonHome();
57
- writeFileAtomic(authFilePath(), JSON.stringify(auth, null, 2));
58
- }
59
- export function readAuth() {
60
- const file = authFilePath();
61
- if (!existsSync(file))
62
- return null;
63
- try {
64
- const parsed = JSON.parse(readFileSync(file, "utf8"));
65
- if (!parsed || typeof parsed !== "object")
66
- return null;
67
- return parsed;
68
- }
69
- catch {
70
- // 损坏的 auth.json 视同未登录,由 CLI 引导重新 login。
71
- return null;
72
- }
73
- }
74
- export function clearAuth() {
75
- const file = authFilePath();
76
- if (!existsSync(file))
77
- return false;
78
- try {
79
- unlinkSync(file);
80
- return true;
81
- }
82
- catch {
83
- return false;
84
- }
85
- }
86
- /**
87
- * 稳定的本机指纹:首次生成 randomUUID 并持久化到 <home>/machine-id(0600),
88
- * 之后跨进程 / 跨重启保持不变,供 login 上报。
89
- */
90
- export function machineFingerprint() {
91
- ensureDaemonHome();
92
- const file = path.join(daemonHome(), "machine-id");
93
- if (existsSync(file)) {
94
- try {
95
- const value = readFileSync(file, "utf8").trim();
96
- if (value)
97
- return value;
98
- }
99
- catch {
100
- // 读失败则重新生成。
101
- }
102
- }
103
- const id = randomUUID();
104
- writeFileAtomic(file, `${id}\n`);
105
- return id;
106
- }
package/dist/cli.d.ts CHANGED
@@ -1,24 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { type Logger } from "./log.js";
3
- import type { RunStartPayload } from "./types.js";
4
2
  export { clearAgentServiceControlEnv } from "./runtime-env.js";
5
3
  export interface CliArgs {
6
4
  positional: string[];
7
5
  flags: Record<string, string | boolean>;
8
6
  }
9
7
  export declare function parseCliArgs(argv: string[]): CliArgs;
10
- export type PollLoopExit = "stopped" | "once" | "auth_failure";
11
- export interface PollLoopDeps {
12
- claimNextRun(): Promise<RunStartPayload | null>;
13
- /** dispatch 的 Promise 由调用方保证不 reject(RunDispatcher 语义)。 */
14
- dispatch(payload: RunStartPayload): Promise<void>;
15
- isStopping(): boolean;
16
- pollIntervalMs: number;
17
- once?: boolean;
18
- maxBackoffMs?: number;
19
- sleep?: (ms: number) => Promise<void>;
20
- log?: Logger;
21
- }
22
- export declare function runPollLoop(deps: PollLoopDeps): Promise<PollLoopExit>;
23
8
  export declare function assertManagedCourseDaemonVersion(actualVersion: string, selectedVersion: string | undefined): void;
24
9
  export declare function runCli(argv: string[]): Promise<number>;
package/dist/cli.js CHANGED
@@ -1,53 +1,36 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync } from "node:fs";
3
3
  import { createRequire } from "node:module";
4
- import { hostname } from "node:os";
5
4
  import { fileURLToPath } from "node:url";
6
- import { authFilePath, clearAuth, machineFingerprint, readAuth, writeAuth } from "./auth-store.js";
7
5
  import { AgentServiceSandboxClient } from "./agent-service-sandbox.js";
8
- import { CourseClient, isAuthFailure, loginCourseDaemon } from "./course-client.js";
9
- import { runCourseDoctor } from "./doctor.js";
10
- import { log } from "./log.js";
11
6
  import { augmentProcessPath } from "./path-env.js";
12
7
  import { redactSecretString } from "./redaction.js";
13
- import { RunDispatcher } from "./run-dispatcher.js";
14
8
  import { clearAgentServiceControlEnv } from "./runtime-env.js";
15
- import { RUNTIME_MODULES, detectAvailableRuntimeIds, fakeRuntimeEnabled, } from "./runtimes/index.js";
9
+ import { RUNTIME_MODULES, fakeRuntimeEnabled } from "./runtimes/index.js";
16
10
  const pkg = createRequire(import.meta.url)("../package.json");
17
11
  const SESSION_BOOTSTRAP_MAX_BYTES = 64 * 1024;
18
- const HELP = `botlearn-course-daemon ${pkg.version} — run BotLearn Course tasks on your own machine (BYOA)
12
+ const HELP = `botlearn-course-daemon ${pkg.version} — BotLearn Course daemon for Agent Service managed sandboxes
19
13
 
20
14
  Usage:
21
- botlearn-course-daemon course login --api-url <url> --code <blic_xxx> [--label <name>]
22
- botlearn-course-daemon course start [--once] [--poll-interval-ms <ms>]
23
- botlearn-course-daemon course logout
24
- botlearn-course-daemon course doctor
25
- botlearn-course-daemon agent-service session
15
+ botlearn-course-daemon agent-service session [--bootstrap-stdin]
26
16
  botlearn-course-daemon --help | --version
27
17
 
28
18
  Commands:
29
- course login Bind this machine to BotLearn Course using a one-time
30
- install code. Writes <daemon-home>/auth.json (0600).
31
- course start Poll Course Service, execute assigned runs with local
32
- agent runtimes, report run events back.
33
- course logout Delete the local daemon credential (auth.json).
34
- course doctor Probe installed runtimes and local auth state.
19
+ agent-service session Connect to Agent Service over WebSocket and execute
20
+ managed runtime turns inside this sandbox.
35
21
 
36
- Environment:
37
- BOTLEARN_COURSE_API_URL default --api-url for course login
38
- BOTLEARN_DAEMON_HOME state dir (default ~/.botlearn-course/daemon)
39
- BOTLEARN_DAEMON_DEBUG enable debug logging
40
- BOTLEARN_<ID>_BIN override a runtime binary path (e.g. BOTLEARN_CODEX_BIN)
41
-
42
- Agent Service sandbox environment:
43
- BOTLEARN_COURSE_API_URL
22
+ Agent Service sandbox environment (when --bootstrap-stdin is not used):
44
23
  BOTLEARN_AGENT_SERVICE_WS_URL
45
24
  BOTLEARN_AGENT_SERVICE_SANDBOX_ID
46
- BOTLEARN_AGENT_SERVICE_SANDBOX_TOKEN`;
25
+ BOTLEARN_AGENT_SERVICE_SANDBOX_TOKEN
26
+
27
+ Other environment:
28
+ BOTLEARN_DAEMON_HOME state dir (default ~/.botlearn-course/daemon)
29
+ BOTLEARN_DAEMON_DEBUG enable debug logging`;
47
30
  // ---------------------------------------------------------------
48
31
  // flag parser(极简:--k v / --k=v / 布尔开关)
49
32
  // ---------------------------------------------------------------
50
- const BOOLEAN_FLAGS = new Set(["once", "help", "version", "bootstrap-stdin"]);
33
+ const BOOLEAN_FLAGS = new Set(["help", "version", "bootstrap-stdin"]);
51
34
  export { clearAgentServiceControlEnv } from "./runtime-env.js";
52
35
  export function parseCliArgs(argv) {
53
36
  const positional = [];
@@ -87,166 +70,6 @@ export function parseCliArgs(argv) {
87
70
  }
88
71
  return { positional, flags };
89
72
  }
90
- function stringFlag(args, name) {
91
- const value = args.flags[name];
92
- return typeof value === "string" && value.length > 0 ? value : undefined;
93
- }
94
- function numberFlag(args, name, fallback) {
95
- const raw = stringFlag(args, name);
96
- if (raw === undefined)
97
- return fallback;
98
- const n = Number(raw);
99
- return Number.isFinite(n) && n > 0 ? n : fallback;
100
- }
101
- // 默认 sleep 切成小片轮询 isStopping,让 SIGINT 不用等完整个退避窗口。
102
- async function interruptibleSleep(ms, isStopping) {
103
- const deadline = Date.now() + ms;
104
- while (!isStopping()) {
105
- const remaining = deadline - Date.now();
106
- if (remaining <= 0)
107
- return;
108
- await new Promise((r) => setTimeout(r, Math.min(remaining, 200)));
109
- }
110
- }
111
- export async function runPollLoop(deps) {
112
- const logger = deps.log ?? log;
113
- const maxBackoffMs = deps.maxBackoffMs ?? 60_000;
114
- const sleep = deps.sleep ?? ((ms) => interruptibleSleep(ms, deps.isStopping));
115
- let failures = 0;
116
- while (!deps.isStopping()) {
117
- let payload;
118
- try {
119
- payload = await deps.claimNextRun();
120
- }
121
- catch (err) {
122
- if (isAuthFailure(err))
123
- return "auth_failure";
124
- const backoffMs = Math.min(deps.pollIntervalMs * 2 ** failures, maxBackoffMs);
125
- failures += 1;
126
- logger.warn("course run claim failed; backing off", {
127
- error: err instanceof Error ? redactSecretString(err.message) : String(err),
128
- backoffMs,
129
- });
130
- await sleep(backoffMs);
131
- continue;
132
- }
133
- failures = 0;
134
- if (payload) {
135
- const runId = payload.agent_run_id;
136
- const task = deps.dispatch(payload).catch((err) => {
137
- logger.error("course run dispatch failed", {
138
- agentRunId: runId,
139
- error: err instanceof Error ? err.message : String(err),
140
- });
141
- });
142
- if (deps.once) {
143
- await task;
144
- return "once";
145
- }
146
- // 有任务:立即继续 claim,run 在后台并发执行。
147
- continue;
148
- }
149
- if (deps.once)
150
- return "once";
151
- await sleep(deps.pollIntervalMs);
152
- }
153
- return "stopped";
154
- }
155
- // ---------------------------------------------------------------
156
- // 子命令
157
- // ---------------------------------------------------------------
158
- function defaultLoginLabel() {
159
- const name = hostname().replace(/\.local$/, "").trim();
160
- return name || "daemon";
161
- }
162
- async function cmdLogin(args) {
163
- const courseApiUrl = stringFlag(args, "api-url") ?? process.env.BOTLEARN_COURSE_API_URL;
164
- const code = stringFlag(args, "code");
165
- if (!courseApiUrl || !code) {
166
- console.error("usage: botlearn-course-daemon course login --api-url <url> --code <blic_xxx> [--label <name>]");
167
- return 1;
168
- }
169
- augmentProcessPath();
170
- const auth = await loginCourseDaemon({
171
- courseApiUrl,
172
- code,
173
- label: stringFlag(args, "label") ?? defaultLoginLabel(),
174
- machineFingerprint: machineFingerprint(),
175
- capabilities: { poll: true, runtimes: await detectAvailableRuntimeIds() },
176
- });
177
- writeAuth(auth);
178
- console.log(`BotLearn Course daemon linked as ${auth.daemonId}`);
179
- return 0;
180
- }
181
- async function cmdStart(args) {
182
- const auth = readAuth();
183
- if (!auth) {
184
- console.error("not linked to BotLearn Course");
185
- console.error("run: botlearn-course-daemon course login --api-url <url> --code <blic_xxx>");
186
- return 1;
187
- }
188
- augmentProcessPath();
189
- const pollIntervalMs = numberFlag(args, "poll-interval-ms", 2_000);
190
- const once = args.flags.once === true;
191
- const client = CourseClient.fromAuth(auth, { onAuthRefreshed: writeAuth });
192
- const runtimes = new Map();
193
- for (const mod of RUNTIME_MODULES) {
194
- if (mod.hidden && !fakeRuntimeEnabled())
195
- continue;
196
- runtimes.set(mod.id, mod.create());
197
- }
198
- const dispatcher = new RunDispatcher(client, runtimes);
199
- let stopping = false;
200
- let signalCount = 0;
201
- const onSignal = (sig) => {
202
- signalCount += 1;
203
- if (signalCount > 1) {
204
- // 二次信号:不再等待 drain,取消所有 run 立即退出。
205
- dispatcher.cancelAll();
206
- process.exit(130);
207
- }
208
- stopping = true;
209
- log.info("course daemon signal received; draining", { sig });
210
- };
211
- process.on("SIGINT", () => onSignal("SIGINT"));
212
- process.on("SIGTERM", () => onSignal("SIGTERM"));
213
- console.log(`BotLearn Course daemon polling ${auth.courseApiUrl}`);
214
- const exit = await runPollLoop({
215
- claimNextRun: () => client.claimNextRun(),
216
- dispatch: (payload) => dispatcher.dispatch(payload),
217
- isStopping: () => stopping,
218
- pollIntervalMs,
219
- once,
220
- log,
221
- });
222
- if (exit === "auth_failure") {
223
- clearAuth();
224
- console.error("daemon credentials expired or revoked — run `botlearn-course-daemon course login` again");
225
- return 1;
226
- }
227
- // 停止 claim 后先等 inflight 排空;超时强制取消再给 5s 收尾。
228
- if (!(await dispatcher.drain(10_000))) {
229
- log.warn("drain timed out; cancelling in-flight runs", { active: dispatcher.activeCount });
230
- dispatcher.cancelAll();
231
- await dispatcher.drain(5_000);
232
- }
233
- return 0;
234
- }
235
- function cmdLogout() {
236
- const removed = clearAuth();
237
- console.log(removed
238
- ? `removed local daemon credentials (${authFilePath()})`
239
- : "no local daemon credentials found");
240
- console.log("note: to revoke this daemon server-side, use the daemon list in the frontend");
241
- return 0;
242
- }
243
- async function cmdDoctor() {
244
- augmentProcessPath();
245
- const result = await runCourseDoctor({ includeHidden: fakeRuntimeEnabled() });
246
- console.log(result.text);
247
- // doctor 是诊断不是校验:即使 0 个 runtime 可用也 exit 0。
248
- return 0;
249
- }
250
73
  async function readSandboxBootstrapFromStdin() {
251
74
  const chunks = [];
252
75
  let size = 0;
@@ -360,21 +183,6 @@ export async function runCli(argv) {
360
183
  return 0;
361
184
  }
362
185
  const [command, sub] = args.positional;
363
- if (command === "course") {
364
- switch (sub) {
365
- case "login":
366
- return cmdLogin(args);
367
- case "start":
368
- return cmdStart(args);
369
- case "logout":
370
- return cmdLogout();
371
- case "doctor":
372
- return cmdDoctor();
373
- default:
374
- console.error(HELP);
375
- return 1;
376
- }
377
- }
378
186
  if (command === "agent-service" && sub === "session") {
379
187
  return cmdAgentServiceSession(args);
380
188
  }
package/dist/index.d.ts CHANGED
@@ -4,7 +4,6 @@
4
4
  */
5
5
  export * from "./types.js";
6
6
  export * from "./auth-store.js";
7
- export * from "./course-client.js";
8
7
  export * from "./agent-service-sandbox.js";
9
8
  export * from "./agent-service-ws-protocol.js";
10
9
  export * from "./run-dispatcher.js";
@@ -12,10 +11,8 @@ export * from "./run-queue.js";
12
11
  export * from "./workspace.js";
13
12
  export * from "./transcript.js";
14
13
  export * from "./file-candidates.js";
15
- export * from "./doctor.js";
16
14
  export * from "./log.js";
17
15
  export * from "./redaction.js";
18
- export * from "./runtime-profile.js";
19
16
  export * from "./runtime-env.js";
20
17
  export * from "./runtime-skills.js";
21
18
  export * from "./mcp/report-progress.js";
package/dist/index.js CHANGED
@@ -4,7 +4,6 @@
4
4
  */
5
5
  export * from "./types.js";
6
6
  export * from "./auth-store.js";
7
- export * from "./course-client.js";
8
7
  export * from "./agent-service-sandbox.js";
9
8
  export * from "./agent-service-ws-protocol.js";
10
9
  export * from "./run-dispatcher.js";
@@ -12,10 +11,8 @@ export * from "./run-queue.js";
12
11
  export * from "./workspace.js";
13
12
  export * from "./transcript.js";
14
13
  export * from "./file-candidates.js";
15
- export * from "./doctor.js";
16
14
  export * from "./log.js";
17
15
  export * from "./redaction.js";
18
- export * from "./runtime-profile.js";
19
16
  export * from "./runtime-env.js";
20
17
  export * from "./runtime-skills.js";
21
18
  export * from "./mcp/report-progress.js";
@@ -2,9 +2,8 @@ import { type ScanLimits, type WorkspaceScanMeasurement } from "./file-candidate
2
2
  import { type InputAttachmentGrant } from "./input-attachments.js";
3
3
  import { type Logger } from "./log.js";
4
4
  import type { PreparedRuntimeSkillProvider } from "./runtime-skills.js";
5
- import { type CourseRuntimeProfile, type CourseRuntime, type RunEvent, type RunEventReceipt, type RunStartPayload } from "./types.js";
5
+ import { type CourseRuntime, type RunEvent, type RunEventReceipt, type RunStartPayload } from "./types.js";
6
6
  export interface RunDispatcherOptions {
7
- defaultRuntimeId?: string;
8
7
  log?: Logger;
9
8
  scanLimits?: ScanLimits;
10
9
  now?: () => number;
@@ -29,7 +28,6 @@ export interface RunReportingClient {
29
28
  postEvent(agentRunId: string, event: RunEvent): Promise<void | RunEventReceipt>;
30
29
  postFiles(agentRunId: string, files: import("./types.js").RunFileCandidate[], truncated?: boolean, signal?: AbortSignal): Promise<unknown>;
31
30
  recordWorkspaceScanMeasurement?(agentRunId: string, measurement: WorkspaceScanMeasurement): Promise<void> | void;
32
- getRunRuntimeProfile?(agentRunId: string): Promise<CourseRuntimeProfile>;
33
31
  }
34
32
  /**
35
33
  * Run dispatcher:把 Course Service 下发的 run.start 交给 runtime,
@@ -37,7 +35,6 @@ export interface RunReportingClient {
37
35
  *
38
36
  * - 串行:同一 agent_instance 经 RunQueue 排队。
39
37
  * - 取消:AbortController;runtime 抛错归一化为 run.failed。
40
- * - 服务端 409(run 已终态)→ abort 并静默停止后续上报。
41
38
  * - daemon 不推进进度,只汇报事实。
42
39
  */
43
40
  export declare class RunDispatcher {
@@ -47,7 +44,6 @@ export declare class RunDispatcher {
47
44
  private readonly inflight;
48
45
  private readonly scheduledRunIds;
49
46
  private readonly pendingCancellations;
50
- private readonly defaultRuntimeId;
51
47
  private readonly log;
52
48
  private readonly scanLimits?;
53
49
  private readonly now;