@online-tools/work-agent-runner 0.0.2-alpha-3 → 0.0.4-alpha-1
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 +22 -9
- package/lib/claude-cli.mjs +24 -15
- package/lib/connection.mjs +11 -3
- package/lib/doctor.mjs +3 -0
- package/lib/interaction.mjs +271 -0
- package/lib/jobs.mjs +96 -15
- package/lib/sandbox.mjs +69 -24
- package/lib/skill-text.mjs +12 -5
- package/lib/skill-tree.mjs +11 -10
- package/lib/work-agent.mjs +6 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -65,7 +65,7 @@ work-agent-runner service install # 可选:注册为后台服务,开机
|
|
|
65
65
|
└── runs/r7x9k2m/ 一个任务一个,结束即删
|
|
66
66
|
├── work-agent/ ← claude 的工作目录:上面那个克隆的完整副本
|
|
67
67
|
├── .home/ 任务的 HOME(.work-agent 软链到 ~/.work-agent)
|
|
68
|
-
├── .tmp/ TMPDIR
|
|
68
|
+
├── .tmp/ TMPDIR;其中 work-agent/ 是 Skill 的临时目录(被检视仓的克隆等)
|
|
69
69
|
├── claude-home/ CLAUDE_CONFIG_DIR
|
|
70
70
|
└── settings.json 沙箱设置(任务改不了)
|
|
71
71
|
```
|
|
@@ -77,12 +77,12 @@ work-agent 自己的家是独立的真目录,和你手工使用 work-agent 时
|
|
|
77
77
|
├── ascend-repos/ 知识仓(任务只读)
|
|
78
78
|
├── essential-repos.txt 初始化下载哪些仓,可自己编辑
|
|
79
79
|
├── logs/ Skill 日志(任务跑完还在,可以查历史)
|
|
80
|
-
├── tmp/ docs/
|
|
80
|
+
├── tmp/ docs/ 任务也可以写的两个目录(交付件等)
|
|
81
81
|
└── work-agent.py init 建的软链,指向克隆里的脚本
|
|
82
82
|
```
|
|
83
83
|
|
|
84
84
|
- **两个仓库的位置都写在 `config.json` 里**(`workAgentRepoDir`、`ascendReposDir`,首次运行自动填上默认值)。要放到别的盘就直接改这两个值(绝对路径),程序按配置文件去找和更新,不用别的开关;知识仓换盘时 `~/.work-agent/ascend-repos` 会变成指向新位置的软链。
|
|
85
|
-
-
|
|
85
|
+
- **任务只能写** `~/.work-agent/{logs,tmp,docs}` 和本次任务的目录(沙箱里的命令和 claude 自己的文件工具都一样)。`~/.work-agent` 其余部分和知识仓都是只读的 —— 任务删不掉知识仓,也改不了 `essential-repos.txt`。
|
|
86
86
|
- **任务目录**默认在 `~/.work-agent-runner/runs/`,用 `--work-dir <目录>` 可以换到别的盘(代码检视会克隆被检视的仓,可能占几百 MB),其余结构不变。
|
|
87
87
|
- Linux 上程序目录(或 `--work-dir`)的路径不能超过 54 字节:沙箱的通信 socket 建在每个任务的 `.tmp` 里,而 socket 路径最多 107 字节。超了程序会直接报错。
|
|
88
88
|
- 每个任务的工作目录是克隆的**副本**(不含 `.git`):任务在一个 work-agent 仓库里干活,但改不到真仓库,也影响不到下一个任务,结束时整个目录删掉。
|
|
@@ -125,26 +125,37 @@ work-agent-runner update # 立刻更新(平时程序每小时自己更)
|
|
|
125
125
|
|
|
126
126
|
## 任务怎么运行
|
|
127
127
|
|
|
128
|
-
网站只下发任务数据:任务文本、模型、你的模型 API Key、GitCode
|
|
128
|
+
网站只下发任务数据:任务文本、模型、你的模型 API Key、GitCode 授权、超时和是否交互执行。claude 的命令行、环境变量、工具白名单和沙箱设置都由本程序生成,网站改不了。
|
|
129
129
|
|
|
130
130
|
每个任务:
|
|
131
131
|
|
|
132
132
|
1. 在工作目录下建立独立的运行目录
|
|
133
|
-
2. 把本机 work-agent
|
|
133
|
+
2. 把本机 work-agent 仓库复制进去(Skill 里的 `/tmp/work-agent/logs` 改写到 `~/.work-agent/logs`,其余 `/tmp/work-agent` 改写到本次任务自己的临时目录,任务结束一起删掉)
|
|
134
134
|
3. 以独立进程组启动 `claude -p`,带上沙箱设置(`--settings`),超时由本程序执行
|
|
135
135
|
4. 把 claude 的输出按顺序回传网站,结束后删除运行目录
|
|
136
136
|
|
|
137
|
+
### 交互执行
|
|
138
|
+
|
|
139
|
+
网页上勾选了「交互执行」的任务,Agent 需要确认时(例如提交评论前)会在网页上弹出问卷,回答后接着运行:
|
|
140
|
+
|
|
141
|
+
- claude 以 `--input-format stream-json --permission-prompt-tool stdio` 运行:任务和回答从标准输入进去,claude 的每个授权请求都交给本程序。**本程序自己应答所有授权请求**:只有 `AskUserQuestion`(向用户提问)转给网站,其他请求一律拒绝,和静默执行时一样
|
|
142
|
+
- 网站能送进任务的**只有你在网页上对这个问题的回答**,本程序还会按同样的规则再检查一遍(每题都要回答、不超过 2000 字)。网站不能往 claude 的标准输入写别的东西,也不能替你批准任何工具或操作
|
|
143
|
+
- 问题 5 分钟没有回答,按「不同意」告诉 claude(例如不提交);等待期间任务照常计入超时
|
|
144
|
+
- 0.0.3 起,程序在连接网站时上报自己支持交互执行;更早的版本在网页上显示为「不支持交互执行」,更新程序即可
|
|
145
|
+
|
|
137
146
|
沙箱设置:
|
|
138
147
|
|
|
139
148
|
- 沙箱必须可用(`failIfUnavailable`),起不来时任务失败,**不会退化为不进沙箱运行**;模型要求「不进沙箱运行命令」一律被忽略
|
|
140
149
|
- 网络只允许 `gitcode.com`、`*.gitcode.com`(claude 自己访问模型 API 不受影响)
|
|
141
|
-
-
|
|
150
|
+
- 沙箱里的命令只能写本次任务的目录和 `~/.work-agent/{logs,tmp,docs}`,不能改写 Skill 副本和设置
|
|
151
|
+
- claude 自己的文件工具(读、写、搜索文件)只能访问本次任务的目录和 `~/.work-agent`(其中只有 logs、tmp、docs 可写,其余和知识仓只读);你主目录里的其他文件、`/tmp` 等其他位置一律访问不到,任务在自己目录里建的软链接也绕不出去
|
|
152
|
+
- **已知缺口**:沙箱里的命令(Bash)**读取**还没有限制到上面这些目录:除了凭证类目录(`.ssh`、`.gnupg`、`.aws`、`.config` 等)、本程序的令牌和克隆,命令仍能读到你主目录里的其他文件,以及系统里的可读文件。请用专用的低权限账号运行本程序
|
|
142
153
|
- 沙箱里的命令看不到模型 API Key;hooks 一律关闭
|
|
143
154
|
|
|
144
155
|
## 安全须知
|
|
145
156
|
|
|
146
|
-
- 选择执行机器运行任务时,你的**模型 API Key 和 GitCode 授权会发送到这台机器**,只注入本次任务的 claude
|
|
147
|
-
-
|
|
157
|
+
- 选择执行机器运行任务时,你的**模型 API Key 和 GitCode 授权会发送到这台机器**,只注入本次任务的 claude 进程,不写入文件或日志。交互执行的回答也只交给本次任务的 claude,日志里只记「收到网页上的回答」,不记内容。
|
|
158
|
+
- **建议用一个专用的低权限账号运行本程序**:沙箱里的命令仍能读到这个账号能读的文件(凭证类目录除外,见「沙箱设置」);GitCode 本身在网络白名单里。
|
|
148
159
|
- 程序拒绝以 root 运行(容器里确有需要时加 `--allow-root`)。
|
|
149
160
|
- 接入令牌只能用来接入机器,不能登录网页。**令牌泄露时在网页上删除它**,用它接入的机器会立即断开;之后新建令牌,在需要的机器上运行 `work-agent-runner login`。网页上的「封禁」只针对单台机器,拿到令牌的人可以换个标识重新接入,所以防泄露要靠删除令牌。
|
|
150
161
|
- 有新机器接入时网页会提示;不是你的机器请封禁或删除令牌。
|
|
@@ -156,7 +167,7 @@ work-agent-runner update # 立刻更新(平时程序每小时自己更)
|
|
|
156
167
|
|---|---|
|
|
157
168
|
| 更新程序 | `npm i -g @online-tools/work-agent-runner@latest`,然后重启程序或服务(`systemctl --user restart work-agent-runner`)。网页上会提示「有新版本」或「版本过低」 |
|
|
158
169
|
| 更新 Skill / 知识仓 | 程序自己定时更新(Skill 每天 08:00,知识仓每小时);要立刻更新就运行 `work-agent-runner update`(服务正在用仓库时会让你稍后再试) |
|
|
159
|
-
| 查看 Skill 日志 | `~/.work-agent
|
|
170
|
+
| 查看 Skill 日志 | `~/.work-agent/logs/`;启动时会清掉 30 天前的日志和 `~/.work-agent/tmp/` |
|
|
160
171
|
| 令牌泄露 | 在网页上删除该令牌,新建令牌后运行 `work-agent-runner login` |
|
|
161
172
|
| 复制了配置 / 克隆了虚拟机 | 在复制出来的那台上运行 `work-agent-runner login --new-id` |
|
|
162
173
|
| 退出登录后服务停止(Linux) | 让管理员执行一次 `loginctl enable-linger <用户名>` |
|
|
@@ -184,6 +195,8 @@ rm -rf ~/.local/share/gitcode-agent-runner # 旧版自动下载的 Node(如
|
|
|
184
195
|
0.0.2 起 Skill 不再由网站下发,而是本程序自己克隆 work-agent 仓库,所以:
|
|
185
196
|
|
|
186
197
|
- 0.0.1 的机器收不到任务(网页显示「版本过低」),必须升级到 0.0.2 以上。
|
|
198
|
+
|
|
199
|
+
0.0.4 起 claude 自己的文件工具只能访问本次任务的目录(见「沙箱设置」),Skill 的克隆也改放在任务自己的临时目录里。更早的版本没有这层限制,网站不再给它们派任务(网页显示「版本过低」),请运行 `npm i -g @online-tools/work-agent-runner@latest` 后重启程序或服务。
|
|
187
200
|
- 升级后首次运行会把配置搬到 `~/.work-agent-runner/config.json`(令牌和机器标识不变),下载 work-agent 仓库(约 2.5 MB),把自动下载的 Node 一并搬过来,并删掉旧的 `~/.config/work-agent-runner/`、`~/.cache/work-agent-runner/`(网站下发 Skill 时代的缓存)和 `/var/tmp/work-agent-runner-<uid>/`。
|
|
188
201
|
|
|
189
202
|
## 卸载
|
package/lib/claude-cli.mjs
CHANGED
|
@@ -1,26 +1,35 @@
|
|
|
1
|
-
// Claude Code command line and environment
|
|
2
|
-
// (lib/
|
|
3
|
-
//
|
|
4
|
-
// builds the exact command line the server uses, plus its sandbox settings.
|
|
1
|
+
// Claude Code command line and environment of the execution machine program
|
|
2
|
+
// (lib/jobs.mjs, lib/doctor.mjs). The website used them too while it still ran
|
|
3
|
+
// Skills on its own host; now every run is a machine's.
|
|
5
4
|
//
|
|
6
5
|
// Only node: built-ins and files in this directory may be imported here, and
|
|
7
6
|
// importing must have no side effects.
|
|
8
7
|
|
|
8
|
+
// Every tool a job may use.
|
|
9
9
|
export const CLAUDE_TOOLS = 'Bash,Read,Glob,Grep,Edit,Write,Skill,Agent';
|
|
10
|
+
// Pre-allowed: Bash (confined by the operating system sandbox), Skill and
|
|
11
|
+
// Agent. The file tools are deliberately left out: pre-allowing them lets them
|
|
12
|
+
// read and write any path not on the deny list. Without it they reach the
|
|
13
|
+
// working directory and the paths the run's settings allow (sandbox.mjs
|
|
14
|
+
// runAllowances: toolRead / toolWrite); any other path asks, which a silent job
|
|
15
|
+
// refuses and lib/interaction.mjs denies.
|
|
16
|
+
export const CLAUDE_ALLOWED_TOOLS = 'Bash,Skill,Agent';
|
|
10
17
|
|
|
11
18
|
const DEFAULT_PATH = '/usr/local/bin:/usr/bin:/bin';
|
|
12
19
|
|
|
13
20
|
/**
|
|
14
|
-
* `interactive` (交互执行): the task and
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* pre-allowed, so each call becomes a prompt
|
|
21
|
+
* `interactive` (交互执行 jobs, lib/interaction.mjs): the task and the answers
|
|
22
|
+
* go over stdin as stream-json, and permission prompts come back
|
|
23
|
+
* (`--permission-prompt-tool stdio`). AskUserQuestion is offered but
|
|
24
|
+
* deliberately not pre-allowed, so each call becomes a prompt.
|
|
18
25
|
*
|
|
19
26
|
* `settingsFile` (execution machines): appended as `--settings <file>`, which
|
|
20
|
-
* carries the sandbox settings
|
|
21
|
-
*
|
|
27
|
+
* carries the sandbox settings and the file tools' path rules.
|
|
28
|
+
*
|
|
29
|
+
* There is no `--add-dir`: under acceptEdits it makes a whole directory tree
|
|
30
|
+
* writable for the file tools; the settings name exact paths instead.
|
|
22
31
|
*/
|
|
23
|
-
export function claudeArgs({
|
|
32
|
+
export function claudeArgs({ interactive = false, settingsFile = '' } = {}) {
|
|
24
33
|
const args = [
|
|
25
34
|
'-p',
|
|
26
35
|
'--output-format',
|
|
@@ -29,21 +38,21 @@ export function claudeArgs({ addDirs = [], interactive = false, settingsFile = '
|
|
|
29
38
|
...(interactive
|
|
30
39
|
? ['--input-format', 'stream-json', '--permission-prompt-tool', 'stdio']
|
|
31
40
|
: []),
|
|
32
|
-
//
|
|
33
|
-
// allowlist
|
|
41
|
+
// Never bypassPermissions (refused as root anyway): acceptEdits plus the
|
|
42
|
+
// allowlist and the settings' path rules run unattended, and anything else
|
|
43
|
+
// is refused.
|
|
34
44
|
'--permission-mode',
|
|
35
45
|
'acceptEdits',
|
|
36
46
|
'--tools',
|
|
37
47
|
interactive ? `${CLAUDE_TOOLS},AskUserQuestion` : CLAUDE_TOOLS,
|
|
38
48
|
'--allowedTools',
|
|
39
|
-
|
|
49
|
+
CLAUDE_ALLOWED_TOOLS,
|
|
40
50
|
// Only the per-run project (.claude/skills copy); never the host's user settings.
|
|
41
51
|
'--setting-sources',
|
|
42
52
|
'project',
|
|
43
53
|
'--strict-mcp-config',
|
|
44
54
|
'--no-session-persistence',
|
|
45
55
|
];
|
|
46
|
-
for (const dir of addDirs) args.push('--add-dir', dir);
|
|
47
56
|
if (settingsFile) args.push('--settings', settingsFile);
|
|
48
57
|
return args;
|
|
49
58
|
}
|
package/lib/connection.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
// Staying connected: the SSE control channel (jobs, cancels,
|
|
2
|
-
//
|
|
1
|
+
// Staying connected: the SSE control channel (jobs, cancels, answers to the
|
|
2
|
+
// questions of 交互执行 jobs, revocation) and heartbeats, independent of each
|
|
3
|
+
// other. The channel reconnects with backoff
|
|
3
4
|
// (1 s doubling to 60 s, ±20 % jitter, reset after 60 s connected); heartbeats
|
|
4
5
|
// keep going while it is down, so running jobs are not lost.
|
|
5
6
|
//
|
|
@@ -65,7 +66,7 @@ function jitter(ms) {
|
|
|
65
66
|
/**
|
|
66
67
|
* Runs until stopped or fatal.
|
|
67
68
|
* client http.mjs client
|
|
68
|
-
* jobs JobManager (handle / cancel / runningIds)
|
|
69
|
+
* jobs JobManager (handle / cancel / answer / runningIds)
|
|
69
70
|
* connect() POST /connect again (after 409 machine_unknown); returns its reply
|
|
70
71
|
* capabilities { current(): object } — sent when changed and after every hello
|
|
71
72
|
* system { current(): object } — system details, sent with every heartbeat (optional)
|
|
@@ -140,6 +141,10 @@ export async function runConnection({
|
|
|
140
141
|
case 'cancel':
|
|
141
142
|
if (typeof event.runId === 'string') jobs.cancel(event.runId);
|
|
142
143
|
break;
|
|
144
|
+
case 'answer':
|
|
145
|
+
// The user answered a question of a 交互执行 job; jobs.answer() validates it.
|
|
146
|
+
jobs.answer?.(event.runId, event.requestId, event.answers);
|
|
147
|
+
break;
|
|
143
148
|
case 'revoked':
|
|
144
149
|
if (event.reason === 'token_deleted') end(FATAL.tokenDeleted);
|
|
145
150
|
else if (event.reason === 'machine_blocked') end(FATAL.blocked);
|
|
@@ -174,6 +179,9 @@ export async function runConnection({
|
|
|
174
179
|
const reply = await client.request('POST', '/heartbeat', body, { signal: stop });
|
|
175
180
|
if (body.capabilities) state.sentCapabilities = current;
|
|
176
181
|
for (const runId of Array.isArray(reply?.cancel) ? reply.cancel : []) jobs.cancel(runId);
|
|
182
|
+
// Answers the website has not seen arrive yet (the control channel may
|
|
183
|
+
// have been down); repeats of one already given are dropped.
|
|
184
|
+
for (const item of Array.isArray(reply?.answers) ? reply.answers : []) jobs.answer?.(item?.runId, item?.requestId, item?.answers);
|
|
177
185
|
noteConfirmed(reply?.confirmed);
|
|
178
186
|
if (reply?.outdated && !state.warnedOutdated) {
|
|
179
187
|
state.warnedOutdated = true;
|
package/lib/doctor.mjs
CHANGED
|
@@ -303,6 +303,9 @@ export async function runDoctor({
|
|
|
303
303
|
tools: Object.fromEntries(SKILL_TOOLS.map((name) => [name, Boolean(tools[name]?.ok)])),
|
|
304
304
|
sandbox,
|
|
305
305
|
packageManager,
|
|
306
|
+
// This program runs 交互执行 jobs (lib/interaction.mjs, since 0.0.3); the
|
|
307
|
+
// website only sends `interactive: true` to machines that say so.
|
|
308
|
+
interactive: true,
|
|
306
309
|
workAgent: repo
|
|
307
310
|
? { commit: repo.commit, committedAt: repo.committedAt, repos: repo.repos, ascend: repo.ascend }
|
|
308
311
|
: { commit: '', committedAt: '', repos: 0, ascend: false },
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
// 交互执行 (interactive jobs). claude runs with `--input-format stream-json
|
|
2
|
+
// --permission-prompt-tool stdio` (claude-cli.mjs claudeArgs({ interactive })):
|
|
3
|
+
// the task and every permission answer go over its stdin, and every
|
|
4
|
+
// permission prompt comes back on its stdout as a `control_request` /
|
|
5
|
+
// `can_use_tool` line. This program answers all of them itself: AskUserQuestion
|
|
6
|
+
// is reported to the website (which shows it on the user's page) as a
|
|
7
|
+
// question, every other prompt is denied exactly as a silent job denies it.
|
|
8
|
+
// The website can only send back answers to a question this program reported
|
|
9
|
+
// (validated here again); it never writes to claude's stdin and cannot allow
|
|
10
|
+
// anything else.
|
|
11
|
+
//
|
|
12
|
+
// The website imports normalizeQuestions() / normalizeAnswers() and the line
|
|
13
|
+
// types to check questions and answers with the same rules, so only node:
|
|
14
|
+
// built-ins and files in this directory may be imported here, and importing
|
|
15
|
+
// must have no side effects.
|
|
16
|
+
|
|
17
|
+
export const QUESTION_TIMEOUT_MS = 5 * 60 * 1000;
|
|
18
|
+
// After the last turn ends, keep stdin open this long in case a background
|
|
19
|
+
// subagent's completion starts a follow-up turn that may still ask a question.
|
|
20
|
+
export const INPUT_IDLE_CLOSE_MS = 3000;
|
|
21
|
+
// Safety net: the CLI waits for EOF on stdin, so a missing bookkeeping event
|
|
22
|
+
// (a task notification with no follow-up turn, a background task that never
|
|
23
|
+
// reports finishing) would otherwise hang the job until its timeout. A live
|
|
24
|
+
// job keeps emitting stdout — including from background subagents — so this
|
|
25
|
+
// much silence with no open question means there is nothing left to answer.
|
|
26
|
+
export const INPUT_HARD_IDLE_CLOSE_MS = 60 * 1000;
|
|
27
|
+
// While a turn is still running, stream-json prints nothing during a single
|
|
28
|
+
// slow model call (third-party models may take up to API_TIMEOUT_MS = 10 min),
|
|
29
|
+
// so silence there means little; only a much longer gap closes stdin.
|
|
30
|
+
export const INPUT_TURN_IDLE_CLOSE_MS = 11 * 60 * 1000;
|
|
31
|
+
|
|
32
|
+
export const QUESTION_TIMEOUT_MESSAGE =
|
|
33
|
+
'用户未在 5 分钟内回答。如果这个问题是在确认写操作(提交 PR / Issue、发表评论等),视为不同意,不要执行该操作;'
|
|
34
|
+
+ '其他问题按推荐选项继续。不要再次询问同一问题。';
|
|
35
|
+
const DENY_TOOL_MESSAGE =
|
|
36
|
+
'在线执行环境不允许这个操作:文件工具只能读写本次任务的工作目录、$HOME、$TMPDIR 和 $WORK_AGENT_HOME 下的 logs / tmp / docs'
|
|
37
|
+
+ '($WORK_AGENT_HOME 的其余部分只读)。';
|
|
38
|
+
|
|
39
|
+
// Lines this program adds to an interactive job's stdout, where claude's own
|
|
40
|
+
// control lines were (claude never prints these types). The website turns
|
|
41
|
+
// them into the page's question cards:
|
|
42
|
+
// { type: QUESTION_LINE, requestId, questions: [{ question, header, multiSelect, options }], timeoutMs }
|
|
43
|
+
// { type: QUESTION_CLOSED_LINE, requestId, reason: 'answered' | 'timeout' | 'cancelled' | 'ended' }
|
|
44
|
+
export const QUESTION_LINE = 'machine_question';
|
|
45
|
+
export const QUESTION_CLOSED_LINE = 'machine_question_closed';
|
|
46
|
+
export const CLOSE_REASONS = ['answered', 'timeout', 'cancelled', 'ended'];
|
|
47
|
+
|
|
48
|
+
const MAX_QUESTIONS = 4;
|
|
49
|
+
const MAX_OPTIONS = 6;
|
|
50
|
+
const MAX_ANSWER_LENGTH = 2000;
|
|
51
|
+
const REQUEST_ID_MAX = 100;
|
|
52
|
+
|
|
53
|
+
const clip = (value, max) => String(value ?? '').trim().slice(0, max);
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Validates AskUserQuestion input; returns display-safe questions or null.
|
|
57
|
+
* Each keeps `original`, the exact text the CLI sent (answers are matched by
|
|
58
|
+
* it), which never leaves this program.
|
|
59
|
+
*/
|
|
60
|
+
export function normalizeQuestions(input) {
|
|
61
|
+
const list = Array.isArray(input?.questions) ? input.questions : null;
|
|
62
|
+
if (!list || list.length === 0 || list.length > MAX_QUESTIONS) return null;
|
|
63
|
+
const questions = [];
|
|
64
|
+
const seen = new Set();
|
|
65
|
+
for (const item of list) {
|
|
66
|
+
const question = clip(item?.question, 1000);
|
|
67
|
+
if (!question || seen.has(question)) return null;
|
|
68
|
+
seen.add(question);
|
|
69
|
+
const original = typeof item?.question === 'string' ? item.question : question;
|
|
70
|
+
const options = (Array.isArray(item?.options) ? item.options : [])
|
|
71
|
+
.slice(0, MAX_OPTIONS)
|
|
72
|
+
.map((option) => ({ label: clip(option?.label, 200), description: clip(option?.description, 500) }))
|
|
73
|
+
.filter((option) => option.label);
|
|
74
|
+
questions.push({
|
|
75
|
+
question,
|
|
76
|
+
original,
|
|
77
|
+
header: clip(item?.header, 40),
|
|
78
|
+
multiSelect: item?.multiSelect === true,
|
|
79
|
+
options,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
return questions;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Every question needs a non-empty answer (an option label, several joined, or free text). */
|
|
86
|
+
export function normalizeAnswers(questions, raw) {
|
|
87
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
88
|
+
const answers = {};
|
|
89
|
+
for (const { question } of questions) {
|
|
90
|
+
const value = Object.hasOwn(raw, question) ? raw[question] : undefined;
|
|
91
|
+
if (typeof value !== 'string') return null;
|
|
92
|
+
const text = value.trim();
|
|
93
|
+
if (!text || text.length > MAX_ANSWER_LENGTH) return null;
|
|
94
|
+
answers[question] = text;
|
|
95
|
+
}
|
|
96
|
+
return answers;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Drives the stdin side of one interactive job.
|
|
101
|
+
* write(obj) writes one JSON line to claude's stdin
|
|
102
|
+
* endInput() closes stdin (claude exits once all its work is done)
|
|
103
|
+
* notify(obj) a QUESTION_LINE / QUESTION_CLOSED_LINE object for the website
|
|
104
|
+
*/
|
|
105
|
+
export function createClaudeInteraction({
|
|
106
|
+
write,
|
|
107
|
+
endInput,
|
|
108
|
+
notify,
|
|
109
|
+
questionTimeoutMs = QUESTION_TIMEOUT_MS,
|
|
110
|
+
idleCloseMs = INPUT_IDLE_CLOSE_MS,
|
|
111
|
+
hardIdleCloseMs = INPUT_HARD_IDLE_CLOSE_MS,
|
|
112
|
+
turnIdleCloseMs = INPUT_TURN_IDLE_CLOSE_MS,
|
|
113
|
+
}) {
|
|
114
|
+
const pending = new Map(); // requestId -> { questions, input, timer }
|
|
115
|
+
let closed = false;
|
|
116
|
+
let idleTimer = null;
|
|
117
|
+
let hardIdleTimer = null;
|
|
118
|
+
let runningTasks = 0;
|
|
119
|
+
let followUpTurnDue = false;
|
|
120
|
+
let lastTurnEnded = false;
|
|
121
|
+
|
|
122
|
+
const respond = (requestId, response) => {
|
|
123
|
+
if (closed) return;
|
|
124
|
+
write({ type: 'control_response', response: { subtype: 'success', request_id: requestId, response } });
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const clearIdle = () => {
|
|
128
|
+
clearTimeout(idleTimer);
|
|
129
|
+
idleTimer = null;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const closeInput = () => {
|
|
133
|
+
if (closed) return;
|
|
134
|
+
closed = true;
|
|
135
|
+
clearIdle();
|
|
136
|
+
clearTimeout(hardIdleTimer);
|
|
137
|
+
hardIdleTimer = null;
|
|
138
|
+
endInput();
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Restarted by every stdout event and whenever a question closes: stdin is
|
|
143
|
+
* closed after a long silence even if the turn/task bookkeeping says
|
|
144
|
+
* otherwise. Never runs while a question is open — the user has 5 minutes.
|
|
145
|
+
*/
|
|
146
|
+
const armHardIdle = () => {
|
|
147
|
+
clearTimeout(hardIdleTimer);
|
|
148
|
+
hardIdleTimer = null;
|
|
149
|
+
if (closed || pending.size > 0) return;
|
|
150
|
+
hardIdleTimer = setTimeout(closeInput, lastTurnEnded ? hardIdleCloseMs : turnIdleCloseMs);
|
|
151
|
+
hardIdleTimer.unref?.();
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const maybeScheduleClose = () => {
|
|
155
|
+
clearIdle();
|
|
156
|
+
if (closed || !lastTurnEnded || runningTasks > 0 || followUpTurnDue || pending.size > 0) return;
|
|
157
|
+
idleTimer = setTimeout(() => {
|
|
158
|
+
idleTimer = null;
|
|
159
|
+
closeInput();
|
|
160
|
+
}, idleCloseMs);
|
|
161
|
+
idleTimer.unref?.();
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const settleQuestion = (requestId, reason) => {
|
|
165
|
+
const item = pending.get(requestId);
|
|
166
|
+
if (!item) return null;
|
|
167
|
+
clearTimeout(item.timer);
|
|
168
|
+
pending.delete(requestId);
|
|
169
|
+
notify({ type: QUESTION_CLOSED_LINE, requestId, reason });
|
|
170
|
+
armHardIdle();
|
|
171
|
+
return item;
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
function askUser(requestId, input) {
|
|
175
|
+
const questions = requestId.length <= REQUEST_ID_MAX ? normalizeQuestions(input) : null;
|
|
176
|
+
if (!questions) {
|
|
177
|
+
respond(requestId, { behavior: 'deny', message: '问题格式不正确:需要 1–4 个不重复的问题。' });
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const timer = setTimeout(() => {
|
|
181
|
+
if (!settleQuestion(requestId, 'timeout')) return;
|
|
182
|
+
respond(requestId, { behavior: 'deny', message: QUESTION_TIMEOUT_MESSAGE });
|
|
183
|
+
maybeScheduleClose();
|
|
184
|
+
}, questionTimeoutMs);
|
|
185
|
+
timer.unref?.();
|
|
186
|
+
pending.set(requestId, { questions, input, timer });
|
|
187
|
+
notify({
|
|
188
|
+
type: QUESTION_LINE,
|
|
189
|
+
requestId,
|
|
190
|
+
questions: questions.map(({ original: _original, ...shown }) => shown),
|
|
191
|
+
timeoutMs: questionTimeoutMs,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Feeds one parsed stdout event; returns true when it was a control message (not for the website). */
|
|
196
|
+
function handleEvent(event) {
|
|
197
|
+
clearIdle();
|
|
198
|
+
armHardIdle();
|
|
199
|
+
if (!event || typeof event !== 'object') return false;
|
|
200
|
+
if (event.type === 'control_request') {
|
|
201
|
+
const requestId = typeof event.request_id === 'string' ? event.request_id : '';
|
|
202
|
+
const request = event.request || {};
|
|
203
|
+
if (!requestId) return true;
|
|
204
|
+
if (request.subtype === 'can_use_tool' && request.tool_name === 'AskUserQuestion') {
|
|
205
|
+
askUser(requestId, request.input);
|
|
206
|
+
armHardIdle(); // a pending question suspends it until answered
|
|
207
|
+
} else if (request.subtype === 'can_use_tool') {
|
|
208
|
+
respond(requestId, { behavior: 'deny', message: DENY_TOOL_MESSAGE });
|
|
209
|
+
} else if (!closed) {
|
|
210
|
+
write({ type: 'control_response', response: { subtype: 'error', request_id: requestId, error: 'unsupported' } });
|
|
211
|
+
}
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
if (event.type === 'control_cancel_request') {
|
|
215
|
+
settleQuestion(String(event.request_id || ''), 'cancelled');
|
|
216
|
+
maybeScheduleClose();
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
if (event.type === 'control_response') return true;
|
|
220
|
+
if (event.type === 'system') {
|
|
221
|
+
if (event.subtype === 'init') {
|
|
222
|
+
// A new turn (also re-emitted for follow-up turns after subagents finish).
|
|
223
|
+
followUpTurnDue = false;
|
|
224
|
+
lastTurnEnded = false;
|
|
225
|
+
} else if (event.subtype === 'task_notification') {
|
|
226
|
+
// Only a notification that arrives after the turn already ended wakes a
|
|
227
|
+
// follow-up turn. Mid-turn notifications are consumed by the running
|
|
228
|
+
// turn and must not hold stdin open (that used to hang the whole job).
|
|
229
|
+
if (lastTurnEnded) followUpTurnDue = true;
|
|
230
|
+
} else if (event.subtype === 'background_tasks_changed') {
|
|
231
|
+
runningTasks = Array.isArray(event.tasks) ? event.tasks.length : 0;
|
|
232
|
+
}
|
|
233
|
+
} else if (event.type === 'result') {
|
|
234
|
+
lastTurnEnded = true;
|
|
235
|
+
}
|
|
236
|
+
// The safety-net length depends on whether a turn is running.
|
|
237
|
+
armHardIdle();
|
|
238
|
+
maybeScheduleClose();
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** The user's answer relayed by the website: 'ok' | 'not_found' | 'invalid'. */
|
|
243
|
+
function answer(requestId, rawAnswers) {
|
|
244
|
+
const id = typeof requestId === 'string' ? requestId : '';
|
|
245
|
+
const item = pending.get(id);
|
|
246
|
+
if (!item || closed) return 'not_found';
|
|
247
|
+
const answers = normalizeAnswers(item.questions, rawAnswers);
|
|
248
|
+
if (!answers) return 'invalid';
|
|
249
|
+
settleQuestion(id, 'answered');
|
|
250
|
+
const byOriginal = Object.fromEntries(
|
|
251
|
+
item.questions.map(({ question, original }) => [original, answers[question]]),
|
|
252
|
+
);
|
|
253
|
+
respond(id, { behavior: 'allow', updatedInput: { ...item.input, answers: byOriginal } });
|
|
254
|
+
return 'ok';
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function start(task) {
|
|
258
|
+
write({ type: 'user', message: { role: 'user', content: task } });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** claude is gone: drop timers, answer nothing more; the website closes any open question card. */
|
|
262
|
+
function dispose() {
|
|
263
|
+
closed = true;
|
|
264
|
+
clearIdle();
|
|
265
|
+
clearTimeout(hardIdleTimer);
|
|
266
|
+
hardIdleTimer = null;
|
|
267
|
+
for (const requestId of [...pending.keys()]) settleQuestion(requestId, 'ended');
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return { start, handleEvent, answer, dispose, pendingCount: () => pending.size };
|
|
271
|
+
}
|
package/lib/jobs.mjs
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
// Running website jobs on this machine.
|
|
2
2
|
//
|
|
3
|
-
// A job carries data only (task text, model, credentials, timeout
|
|
4
|
-
// command line, environment, tool allowlist and sandbox
|
|
5
|
-
// here, and the Skills come from this machine's own
|
|
6
|
-
// (lib/work-agent.mjs). Per job:
|
|
3
|
+
// A job carries data only (task text, model, credentials, timeout, whether it
|
|
4
|
+
// is interactive); the command line, environment, tool allowlist and sandbox
|
|
5
|
+
// settings are built here, and the Skills come from this machine's own
|
|
6
|
+
// work-agent clone (lib/work-agent.mjs). Per job:
|
|
7
7
|
// validate → accept → run directory → copy Skills → claude (own process
|
|
8
8
|
// group, sandboxed) → stream output (ordered batches, retried) → exit →
|
|
9
9
|
// delete the run directory.
|
|
10
|
+
// 交互执行 jobs keep claude's stdin open: lib/interaction.mjs answers its
|
|
11
|
+
// permission prompts, reports AskUserQuestion to the website in the output and
|
|
12
|
+
// takes the user's answers back (answer()).
|
|
10
13
|
// Logs name the run, feature, duration and exit code — never the API key,
|
|
11
14
|
// GITCODE_CRED, the machine token or proxy credentials.
|
|
12
15
|
|
|
@@ -17,6 +20,7 @@ import { StringDecoder } from 'node:string_decoder';
|
|
|
17
20
|
|
|
18
21
|
import { claudeArgs, claudeEnv } from './claude-cli.mjs';
|
|
19
22
|
import { ApiError } from './http.mjs';
|
|
23
|
+
import { createClaudeInteraction } from './interaction.mjs';
|
|
20
24
|
import {
|
|
21
25
|
caPaths,
|
|
22
26
|
createRunLayout,
|
|
@@ -72,7 +76,8 @@ export function invalidJobField(job) {
|
|
|
72
76
|
const keys = Object.keys(env);
|
|
73
77
|
if (keys.length !== 1 || keys[0] !== 'GITCODE_CRED' || typeof env.GITCODE_CRED !== 'string' || env.GITCODE_CRED.length > 512) return 'env';
|
|
74
78
|
if (!Number.isInteger(job.timeoutMs) || job.timeoutMs < 60_000 || job.timeoutMs > 14_400_000) return 'timeoutMs';
|
|
75
|
-
|
|
79
|
+
// true: 交互执行 — the website only asks machines that report capabilities.interactive.
|
|
80
|
+
if (typeof job.interactive !== 'boolean') return 'interactive';
|
|
76
81
|
return '';
|
|
77
82
|
}
|
|
78
83
|
|
|
@@ -279,13 +284,28 @@ export class JobManager {
|
|
|
279
284
|
if (this.closed) return;
|
|
280
285
|
const runId = typeof job?.runId === 'string' && job.runId.length <= 100 ? job.runId : '';
|
|
281
286
|
if (!runId || this.jobs.has(runId)) return;
|
|
282
|
-
const entry = { runId, job, child: null, cancelled: false, timedOut: false, failure: '', gone: false, done: null };
|
|
287
|
+
const entry = { runId, job, child: null, interaction: null, cancelled: false, timedOut: false, failure: '', gone: false, done: null };
|
|
283
288
|
this.jobs.set(runId, entry);
|
|
284
289
|
entry.done = this.run(entry)
|
|
285
290
|
.catch((error) => this.log.error(`任务 ${runId} 异常:${error?.message || error}`))
|
|
286
291
|
.finally(() => this.jobs.delete(runId));
|
|
287
292
|
}
|
|
288
293
|
|
|
294
|
+
/**
|
|
295
|
+
* The user's answer to a question of a 交互执行 job (an `answer` event, or
|
|
296
|
+
* the heartbeat reply repeating one): 'ok' | 'not_found' | 'invalid'.
|
|
297
|
+
* Repeats of an answer already given find nothing and are dropped. Never
|
|
298
|
+
* logs the answer itself.
|
|
299
|
+
*/
|
|
300
|
+
answer(runId, requestId, answers) {
|
|
301
|
+
const entry = typeof runId === 'string' ? this.jobs.get(runId) : null;
|
|
302
|
+
if (!entry?.interaction) return 'not_found';
|
|
303
|
+
const result = entry.interaction.answer(requestId, answers);
|
|
304
|
+
if (result === 'ok') this.log.info(`任务 ${runId} 收到网页上的回答`);
|
|
305
|
+
else if (result === 'invalid') this.log.warn(`任务 ${runId} 收到的回答不完整或过长,已忽略`);
|
|
306
|
+
return result;
|
|
307
|
+
}
|
|
308
|
+
|
|
289
309
|
/** Stops a job (website cancel, heartbeat reconciliation). */
|
|
290
310
|
cancel(runId) {
|
|
291
311
|
const entry = this.jobs.get(runId);
|
|
@@ -392,15 +412,16 @@ export class JobManager {
|
|
|
392
412
|
return;
|
|
393
413
|
}
|
|
394
414
|
|
|
395
|
-
// A copy of this machine's work-agent clone as the working directory
|
|
396
|
-
//
|
|
415
|
+
// A copy of this machine's work-agent clone as the working directory (the
|
|
416
|
+
// Skills' logs pointed at $WORK_AGENT_HOME/logs, their scratch at the run's
|
|
417
|
+
// own), and the knowledge pool read-only if there is one: the settings name
|
|
418
|
+
// every path the job may reach (sandbox.mjs).
|
|
397
419
|
try {
|
|
398
|
-
const { commit } = await this.workAgent.copyRepoInto(layout.workDir,
|
|
420
|
+
const { commit } = await this.workAgent.copyRepoInto(layout.workDir, {
|
|
421
|
+
logs: path.join(this.paths.workAgentHome, 'logs'),
|
|
422
|
+
scratch: layout.scratchDir,
|
|
423
|
+
});
|
|
399
424
|
const pool = this.workAgent.mountablePool();
|
|
400
|
-
// Claude Code limits its file tools to the working directory and whatever
|
|
401
|
-
// --add-dir names; the pool is outside it (the sandbox still decides what
|
|
402
|
-
// may be written).
|
|
403
|
-
entry.addDirs = pool ? [this.paths.workAgentHome] : [];
|
|
404
425
|
writeSandboxSettings(layout.settingsFile, {
|
|
405
426
|
workDir: fs.realpathSync(layout.workDir),
|
|
406
427
|
realHome: this.realHome,
|
|
@@ -446,9 +467,10 @@ export class JobManager {
|
|
|
446
467
|
resolve({ code: null, signal: null, error: '无法启动 claude:未安装' });
|
|
447
468
|
return;
|
|
448
469
|
}
|
|
470
|
+
const interactive = job.interactive === true;
|
|
449
471
|
let child;
|
|
450
472
|
try {
|
|
451
|
-
child = spawn(this.claudePath, claudeArgs({ settingsFile: layout.settingsFile,
|
|
473
|
+
child = spawn(this.claudePath, claudeArgs({ settingsFile: layout.settingsFile, interactive }), {
|
|
452
474
|
cwd: layout.workDir,
|
|
453
475
|
detached: true,
|
|
454
476
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
@@ -493,8 +515,34 @@ export class JobManager {
|
|
|
493
515
|
},
|
|
494
516
|
});
|
|
495
517
|
entry.uploader = uploader;
|
|
518
|
+
if (interactive) {
|
|
519
|
+
entry.interaction = createClaudeInteraction({
|
|
520
|
+
write: (message) => {
|
|
521
|
+
if (child.stdin.writable) child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
522
|
+
},
|
|
523
|
+
endInput: () => child.stdin.end(),
|
|
524
|
+
// In order with the output around it: where claude's control line was.
|
|
525
|
+
notify: (line) => uploader.push('stdout', `${JSON.stringify(line)}\n`),
|
|
526
|
+
});
|
|
527
|
+
}
|
|
496
528
|
for (const name of ['stdout', 'stderr']) {
|
|
497
529
|
const decoder = new StringDecoder('utf8');
|
|
530
|
+
if (name === 'stdout' && entry.interaction) {
|
|
531
|
+
// Line by line: claude's control messages are answered here and
|
|
532
|
+
// never reach the website; everything else goes on unchanged.
|
|
533
|
+
const lines = lineSplitter((line) => {
|
|
534
|
+
let event = null;
|
|
535
|
+
try {
|
|
536
|
+
event = JSON.parse(line);
|
|
537
|
+
} catch {
|
|
538
|
+
// Not JSON: plain output.
|
|
539
|
+
}
|
|
540
|
+
if (!entry.interaction.handleEvent(event)) uploader.push('stdout', `${line}\n`);
|
|
541
|
+
});
|
|
542
|
+
child.stdout.on('data', (chunk) => lines.write(decoder.write(chunk)));
|
|
543
|
+
child.stdout.on('end', () => lines.end(decoder.end()));
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
498
546
|
child[name].on('data', (chunk) => uploader.push(name, decoder.write(chunk)));
|
|
499
547
|
child[name].on('end', () => uploader.push(name, decoder.end()));
|
|
500
548
|
}
|
|
@@ -512,6 +560,8 @@ export class JobManager {
|
|
|
512
560
|
clearTimeout(timeout);
|
|
513
561
|
clearTimeout(closeWait);
|
|
514
562
|
killGroup(child.pid, 'SIGKILL'); // whatever the job left behind
|
|
563
|
+
// Open questions are reported closed before the exit.
|
|
564
|
+
entry.interaction?.dispose();
|
|
515
565
|
await uploader.drain();
|
|
516
566
|
resolve(result);
|
|
517
567
|
};
|
|
@@ -526,7 +576,38 @@ export class JobManager {
|
|
|
526
576
|
});
|
|
527
577
|
child.once('close', (code, signal) => finish({ code, signal, error: '' }));
|
|
528
578
|
child.stdin.on('error', () => {});
|
|
529
|
-
|
|
579
|
+
// Interactive: the task is the first stream-json message and stdin stays
|
|
580
|
+
// open for the answers until the interaction closes it.
|
|
581
|
+
if (entry.interaction) entry.interaction.start(job.task);
|
|
582
|
+
else child.stdin.end(job.task);
|
|
530
583
|
});
|
|
531
584
|
}
|
|
532
585
|
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Splits decoded text into lines for `onLine` (without the newline); end()
|
|
589
|
+
* flushes the last line even when it has no newline.
|
|
590
|
+
*/
|
|
591
|
+
export function lineSplitter(onLine) {
|
|
592
|
+
let rest = '';
|
|
593
|
+
// Only the new text is searched: a long line arriving in many chunks stays linear.
|
|
594
|
+
const feed = (text) => {
|
|
595
|
+
let start = 0;
|
|
596
|
+
let index;
|
|
597
|
+
while ((index = text.indexOf('\n', start)) >= 0) {
|
|
598
|
+
const line = rest + text.slice(start, index);
|
|
599
|
+
rest = '';
|
|
600
|
+
start = index + 1;
|
|
601
|
+
onLine(line);
|
|
602
|
+
}
|
|
603
|
+
rest += text.slice(start);
|
|
604
|
+
};
|
|
605
|
+
return {
|
|
606
|
+
write: feed,
|
|
607
|
+
end(text = '') {
|
|
608
|
+
feed(text);
|
|
609
|
+
if (rest) onLine(rest);
|
|
610
|
+
rest = '';
|
|
611
|
+
},
|
|
612
|
+
};
|
|
613
|
+
}
|
package/lib/sandbox.mjs
CHANGED
|
@@ -12,14 +12,29 @@
|
|
|
12
12
|
// `~/.work-agent/...` and $WORK_AGENT_HOME are the
|
|
13
13
|
// same directory (linkWorkAgentHome)
|
|
14
14
|
// <runDir>/.tmp/ TMPDIR (the sandbox's bridge sockets live here)
|
|
15
|
+
// <runDir>/.tmp/work-agent the Skills' `/tmp/work-agent` scratch (clones,
|
|
16
|
+
// intermediate files); their logs go to
|
|
17
|
+
// $WORK_AGENT_HOME/logs (skill-text.mjs)
|
|
15
18
|
//
|
|
16
|
-
// Jobs
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
19
|
+
// Jobs run inside the program's home (~/.work-agent-runner). Two layers
|
|
20
|
+
// decide what a job reaches, one per kind of tool:
|
|
21
|
+
// - Bash commands run in the operating system sandbox: writable are exactly
|
|
22
|
+
// the four directories above and $WORK_AGENT_HOME/{logs,tmp,docs}
|
|
23
|
+
// (filesystem.allowWrite). Reading is NOT confined to them:
|
|
24
|
+
// filesystem.allowRead only re-opens paths inside a denyRead region, and
|
|
25
|
+
// none is set — closing the home for reads would also hide toolchains
|
|
26
|
+
// installed there (pyenv, nvm, conda) and has to be tried on real machines
|
|
27
|
+
// first. Bash reads are closed only for the deny list below.
|
|
28
|
+
// - claude's own file tools (Read, Glob, Grep, Edit, Write) run outside that
|
|
29
|
+
// sandbox. They are not pre-allowed (claude-cli.mjs), so they reach the
|
|
30
|
+
// working directory and exactly the paths in permissions.allow (toolRead /
|
|
31
|
+
// toolWrite from runAllowances); any other path is a permission prompt,
|
|
32
|
+
// which a silent job refuses and lib/interaction.mjs denies. claude checks
|
|
33
|
+
// a symlink's target as well as the link (verified with 2.1.322), so a
|
|
34
|
+
// link in a writable directory does not widen this.
|
|
35
|
+
// permissions.deny beats any allow, for both kinds (claude passes Read / Edit
|
|
36
|
+
// denies on to the sandbox): credentials in the home, the token, the real
|
|
37
|
+
// clone, writes to the pool and to this run's Skill copy.
|
|
23
38
|
//
|
|
24
39
|
// Paths are real paths: claude's HOME is the run's, so `~` cannot be used,
|
|
25
40
|
// and on macOS /var is a symlink to /private/var.
|
|
@@ -36,9 +51,8 @@ function fromRoot(absolute) {
|
|
|
36
51
|
}
|
|
37
52
|
|
|
38
53
|
// Directories in the home that a job must never read, whatever else it may
|
|
39
|
-
// reach: credentials, keys and shell history.
|
|
40
|
-
//
|
|
41
|
-
// is the second one, at the tool layer, where deny beats any allow.
|
|
54
|
+
// reach: credentials, keys and shell history. A deny beats any allow, and
|
|
55
|
+
// claude passes these on to the sandbox, so Bash cannot read them either.
|
|
42
56
|
export const SENSITIVE_HOME_PATHS = [
|
|
43
57
|
'.ssh',
|
|
44
58
|
'.gnupg',
|
|
@@ -58,12 +72,12 @@ export const SENSITIVE_HOME_PATHS = [
|
|
|
58
72
|
];
|
|
59
73
|
|
|
60
74
|
/**
|
|
61
|
-
* The settings object. `readAllow` / `writeAllow`
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
* copy of this run.
|
|
75
|
+
* The settings object. `readAllow` / `writeAllow` (the sandbox, for Bash) and
|
|
76
|
+
* `toolRead` / `toolWrite` (the file tools) are real paths, see
|
|
77
|
+
* runAllowances; `deny` keeps both away from credentials, from the program's
|
|
78
|
+
* own files (the token, the real clone) and from the Skill copy of this run.
|
|
65
79
|
*/
|
|
66
|
-
export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow = [], deny = [] }) {
|
|
80
|
+
export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow = [], deny = [], toolRead = [], toolWrite = [] }) {
|
|
67
81
|
return {
|
|
68
82
|
sandbox: {
|
|
69
83
|
enabled: true,
|
|
@@ -76,6 +90,11 @@ export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow
|
|
|
76
90
|
credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
|
|
77
91
|
},
|
|
78
92
|
permissions: {
|
|
93
|
+
// Where the file tools may go besides the working directory: nowhere else.
|
|
94
|
+
allow: [
|
|
95
|
+
...toolRead.map((dir) => `Read(//${fromRoot(dir)}/**)`),
|
|
96
|
+
...toolWrite.map((dir) => `Edit(//${fromRoot(dir)}/**)`),
|
|
97
|
+
],
|
|
79
98
|
deny: [
|
|
80
99
|
...SENSITIVE_HOME_PATHS.flatMap((name) => [
|
|
81
100
|
`Read(//${fromRoot(realHome)}/${name})`,
|
|
@@ -93,11 +112,19 @@ export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow
|
|
|
93
112
|
}
|
|
94
113
|
|
|
95
114
|
/**
|
|
96
|
-
* What one job may read and write
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
115
|
+
* What one job may read and write, all as real paths:
|
|
116
|
+
* writeAllow / readAllow the sandbox (Bash): the four directories of its
|
|
117
|
+
* run, $WORK_AGENT_HOME/{logs,tmp,docs}; read also
|
|
118
|
+
* all of $WORK_AGENT_HOME, the knowledge pool and —
|
|
119
|
+
* inside the home — the PATH entries and CA bundles
|
|
120
|
+
* a command needs (they only matter inside a
|
|
121
|
+
* denyRead region, see the top of this file)
|
|
122
|
+
* toolWrite / toolRead the file tools: the working directory, HOME and
|
|
123
|
+
* TMPDIR of the run (scratch included) and
|
|
124
|
+
* $WORK_AGENT_HOME/{logs,tmp,docs}; read also all of
|
|
125
|
+
* $WORK_AGENT_HOME and the pool. Not claude-home:
|
|
126
|
+
* claude's own state is none of the model's business.
|
|
127
|
+
* deny the program's own files and pool writes.
|
|
101
128
|
*/
|
|
102
129
|
export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], pool = '', paths = null }) {
|
|
103
130
|
const runDirs = [layout.workDir, layout.homeDir, layout.tmpDir, layout.configDir].map((dir) => realpathOr(dir));
|
|
@@ -115,6 +142,15 @@ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], po
|
|
|
115
142
|
...(pool ? [realpathOr(pool)] : []),
|
|
116
143
|
...homeReadAllow({ realHome, pathEnv, caPaths }),
|
|
117
144
|
];
|
|
145
|
+
const toolWrite = [
|
|
146
|
+
...[layout.workDir, layout.homeDir, layout.tmpDir].map((dir) => realpathOr(dir)),
|
|
147
|
+
...(workAgentHome ? ['logs', 'tmp', 'docs'].map((name) => path.join(workAgentHome, name)) : []),
|
|
148
|
+
];
|
|
149
|
+
const toolRead = [
|
|
150
|
+
...toolWrite,
|
|
151
|
+
...(workAgentHome ? [workAgentHome] : []),
|
|
152
|
+
...(pool ? [realpathOr(pool)] : []),
|
|
153
|
+
];
|
|
118
154
|
const deny = [];
|
|
119
155
|
if (paths) {
|
|
120
156
|
// The access token, and the clone every job copies from.
|
|
@@ -125,7 +161,13 @@ export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], po
|
|
|
125
161
|
}
|
|
126
162
|
// The pool is shared with the user's own work-agent: read it, never write it.
|
|
127
163
|
if (pool) deny.push(`Edit(//${fromRoot(realpathOr(pool))}/**)`);
|
|
128
|
-
return {
|
|
164
|
+
return {
|
|
165
|
+
readAllow: [...new Set(readAllow)],
|
|
166
|
+
writeAllow: [...new Set(writeAllow)],
|
|
167
|
+
toolRead: [...new Set(toolRead)],
|
|
168
|
+
toolWrite: [...new Set(toolWrite)],
|
|
169
|
+
deny,
|
|
170
|
+
};
|
|
129
171
|
}
|
|
130
172
|
|
|
131
173
|
function realpathOr(value) {
|
|
@@ -144,8 +186,9 @@ export function writeSandboxSettings(file, input) {
|
|
|
144
186
|
* Directories / files inside HOME that sandboxed commands still need to read:
|
|
145
187
|
* PATH entries (e.g. ~/.local/bin, nvm), CA bundles passed through, and
|
|
146
188
|
* `extra` (the knowledge pool, which lives in ~/.work-agent by default).
|
|
147
|
-
* Returns their real paths
|
|
148
|
-
*
|
|
189
|
+
* Returns their real paths, only those inside HOME: a denyRead on the home
|
|
190
|
+
* (not set yet, see the top of this file) would have to give exactly these
|
|
191
|
+
* back; everything outside it is readable anyway.
|
|
149
192
|
*/
|
|
150
193
|
export function homeReadAllow({ realHome, pathEnv = '', caPaths = [], extra = [] }) {
|
|
151
194
|
const allowed = new Set();
|
|
@@ -207,7 +250,9 @@ export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
|
|
|
207
250
|
workAgentHome,
|
|
208
251
|
};
|
|
209
252
|
layout.skillsDir = path.join(layout.workDir, '.claude', 'skills');
|
|
210
|
-
|
|
253
|
+
// The Skills' `/tmp/work-agent` (clones, intermediate files): deleted with the run.
|
|
254
|
+
layout.scratchDir = path.join(layout.tmpDir, 'work-agent');
|
|
255
|
+
for (const dir of [layout.configDir, layout.workDir, layout.homeDir, layout.tmpDir, layout.scratchDir]) {
|
|
211
256
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
212
257
|
}
|
|
213
258
|
if (workAgentHome) {
|
package/lib/skill-text.mjs
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
// How Skill text files are rewritten for a run,
|
|
2
|
-
// (lib/skill-bundle.js, server runs) and the machine program
|
|
1
|
+
// How Skill text files are rewritten for a run, for the machine program
|
|
3
2
|
// (lib/work-agent.mjs), through lib/skill-tree.mjs.
|
|
4
3
|
//
|
|
5
4
|
// Only node: built-ins and files in this directory may be imported here, and
|
|
@@ -23,7 +22,15 @@ export function renameTokenVariable(text) {
|
|
|
23
22
|
return String(text).split('GITCODE_TOKEN').join('GITCODE_CRED');
|
|
24
23
|
}
|
|
25
24
|
|
|
26
|
-
/**
|
|
27
|
-
|
|
28
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Points the Skills' `/tmp/work-agent` at this machine's directories:
|
|
27
|
+
* `/tmp/work-agent/logs` at `logs` (kept after the job, $WORK_AGENT_HOME/logs)
|
|
28
|
+
* and everything else under it — clones, intermediate files — at `scratch`
|
|
29
|
+
* (the job's own directory, deleted with it). A job may write nowhere else:
|
|
30
|
+
* mapping it to $WORK_AGENT_HOME itself put the clones where the sandbox lets
|
|
31
|
+
* no job write. Paths that merely start with the same letters
|
|
32
|
+
* (`/tmp/work-agent-runner`) are left alone.
|
|
33
|
+
*/
|
|
34
|
+
export function rewriteWorkAgentPath(text, { logs, scratch }) {
|
|
35
|
+
return String(text).replace(/\/tmp\/work-agent(\/logs)?(?![A-Za-z0-9_.-])/g, (_, inLogs) => (inLogs ? logs : scratch));
|
|
29
36
|
}
|
package/lib/skill-tree.mjs
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
// Reading a Skill tree and copying it into a run,
|
|
2
|
-
// (lib/
|
|
3
|
-
// (lib/work-agent.mjs, for jobs). One implementation, so a job's Skill copy is
|
|
4
|
-
// byte for byte what a server run gets from the same source.
|
|
1
|
+
// Reading a Skill tree and copying it into a run, for the execution machine
|
|
2
|
+
// program (lib/work-agent.mjs, for jobs).
|
|
5
3
|
//
|
|
6
4
|
// Only node: built-ins and files in this directory may be imported here, and
|
|
7
5
|
// importing must have no side effects.
|
|
@@ -19,8 +17,8 @@ export const MAX_FILE_BYTES = 100 * 1024 * 1024;
|
|
|
19
17
|
export const MAX_TOTAL_BYTES = 512 * 1024 * 1024;
|
|
20
18
|
|
|
21
19
|
/**
|
|
22
|
-
* Visits a Skill tree the way every consumer (
|
|
23
|
-
*
|
|
20
|
+
* Visits a Skill tree the way every consumer (a machine's run copies, the
|
|
21
|
+
* sandbox check) must see it:
|
|
24
22
|
* - symlinks are followed and reported as what they point to (dangling ones are skipped)
|
|
25
23
|
* - `.git` entries (nested submodule pointers into the source .git) are skipped
|
|
26
24
|
* - sockets / fifos / devices are skipped
|
|
@@ -84,17 +82,20 @@ export function copyTreeDetached(source, target, limits = {}) {
|
|
|
84
82
|
return { files, bytes };
|
|
85
83
|
}
|
|
86
84
|
|
|
87
|
-
/**
|
|
88
|
-
|
|
85
|
+
/**
|
|
86
|
+
* Points `/tmp/work-agent` at `targets` ({ logs, scratch }: skill-text.mjs
|
|
87
|
+
* rewriteWorkAgentPath) and renames GITCODE_TOKEN (AGENTS.md 5.1).
|
|
88
|
+
*/
|
|
89
|
+
export function rewriteSkillPaths(directory, targets) {
|
|
89
90
|
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
90
91
|
const target = path.join(directory, entry.name);
|
|
91
92
|
if (entry.isDirectory()) {
|
|
92
|
-
rewriteSkillPaths(target,
|
|
93
|
+
rewriteSkillPaths(target, targets);
|
|
93
94
|
continue;
|
|
94
95
|
}
|
|
95
96
|
if (!entry.isFile() || !isSkillTextFile(entry.name)) continue;
|
|
96
97
|
const text = fs.readFileSync(target, 'utf8');
|
|
97
98
|
if (!text.includes('/tmp/work-agent') && !text.includes('GITCODE_TOKEN')) continue;
|
|
98
|
-
fs.writeFileSync(target, renameTokenVariable(rewriteWorkAgentPath(text,
|
|
99
|
+
fs.writeFileSync(target, renameTokenVariable(rewriteWorkAgentPath(text, targets)));
|
|
99
100
|
}
|
|
100
101
|
}
|
package/lib/work-agent.mjs
CHANGED
|
@@ -368,16 +368,17 @@ export class WorkAgent {
|
|
|
368
368
|
/**
|
|
369
369
|
* Copies the whole repository into `targetDir` — the job's working directory,
|
|
370
370
|
* so it runs inside a work-agent repository of its own — and points the
|
|
371
|
-
* Skills' `/tmp/work-agent` at `
|
|
372
|
-
*
|
|
373
|
-
*
|
|
371
|
+
* Skills' `/tmp/work-agent` at `targets`: { logs } (the persistent
|
|
372
|
+
* $WORK_AGENT_HOME/logs) and { scratch } (the job's own scratch directory)
|
|
373
|
+
* — lib/skill-text.mjs rewriteWorkAgentPath. `.git` is left out: the copy is
|
|
374
|
+
* for reading and running, not for pushing. Returns the commit that was copied.
|
|
374
375
|
*/
|
|
375
|
-
copyRepoInto(targetDir,
|
|
376
|
+
copyRepoInto(targetDir, targets) {
|
|
376
377
|
return this.run(() => {
|
|
377
378
|
const state = this.state();
|
|
378
379
|
if (!state.ok) throw new Error(state.reason);
|
|
379
380
|
copyTreeDetached(this.paths.repoDir, targetDir);
|
|
380
|
-
rewriteSkillPaths(path.join(targetDir, SKILLS_SUBDIR),
|
|
381
|
+
rewriteSkillPaths(path.join(targetDir, SKILLS_SUBDIR), targets);
|
|
381
382
|
return { commit: state.commit };
|
|
382
383
|
});
|
|
383
384
|
}
|