@online-tools/work-agent-runner 0.0.2-alpha-2 → 0.0.3-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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @online-tools/work-agent-runner
2
2
 
3
- GitCode 在线工具的 Agent 执行机器:在你自己的机器上运行「在线 Agent」里的 work-agent Skill——**PR 描述 / Issue**、**代码检视(全量 / 快速)**,不占网站服务器的资源。Skill 由本程序自己从 GitCode 克隆 work-agent 仓库取得,网站只下发任务数据。
3
+ GitCode 在线工具的 Agent 执行机器:在你自己的机器上运行「在线 Agent」里的 work-agent Skill——**PR 描述 / Issue**、**代码检视(全量 / 快速)**、**CANN 知识问答**,不占网站服务器的资源。Skill 由本程序自己从 GitCode 克隆 work-agent 仓库取得,网站只下发任务数据。
4
4
 
5
5
  程序只**主动连出**到网站(HTTPS),适用于没有公网 IP、在 NAT 或公司代理后面的机器;网站从不主动连接你的机器。
6
6
 
@@ -103,7 +103,7 @@ Skill **不来自网站**,而是本程序自己从 GitCode 克隆的 work-agen
103
103
 
104
104
  ### 知识仓(可选)
105
105
 
106
- 「代码检视」要查 CANN / AscendC 的权威文档。下载的是 work-agent 的**必要仓清单** `~/.work-agent/essential-repos.txt`(首次 `init` 时按 work-agent 的内置默认生成,之后**可以自己编辑**再运行 `setup`)。默认是 CANN 组织下这些仓:
106
+ 「代码检视」和「CANN 知识问答」要查 CANN / AscendC 的权威文档(**CANN 知识问答完全靠它作答,没有仓池的机器不能跑这个功能**)。下载的是 work-agent 的**必要仓清单** `~/.work-agent/essential-repos.txt`(首次 `init` 时按 work-agent 的内置默认生成,之后**可以自己编辑**再运行 `setup`)。默认是 CANN 组织下这些仓:
107
107
 
108
108
  ```text
109
109
  asc-devkit cann-samples docs ops-math ops-nn ops-transformer
@@ -125,7 +125,7 @@ work-agent-runner update # 立刻更新(平时程序每小时自己更)
125
125
 
126
126
  ## 任务怎么运行
127
127
 
128
- 网站只下发任务数据:任务文本、模型、你的模型 API Key、GitCode 授权和超时。claude 的命令行、环境变量、工具白名单和沙箱设置都由本程序生成,网站改不了。
128
+ 网站只下发任务数据:任务文本、模型、你的模型 API Key、GitCode 授权、超时和是否交互执行。claude 的命令行、环境变量、工具白名单和沙箱设置都由本程序生成,网站改不了。
129
129
 
130
130
  每个任务:
131
131
 
@@ -134,6 +134,15 @@ work-agent-runner update # 立刻更新(平时程序每小时自己更)
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`),起不来时任务失败,**不会退化为不进沙箱运行**;模型要求「不进沙箱运行命令」一律被忽略
@@ -143,7 +152,7 @@ work-agent-runner update # 立刻更新(平时程序每小时自己更)
143
152
 
144
153
  ## 安全须知
145
154
 
146
- - 选择执行机器运行任务时,你的**模型 API Key 和 GitCode 授权会发送到这台机器**,只注入本次任务的 claude 进程,不写入文件或日志。
155
+ - 选择执行机器运行任务时,你的**模型 API Key 和 GitCode 授权会发送到这台机器**,只注入本次任务的 claude 进程,不写入文件或日志。交互执行的回答也只交给本次任务的 claude,日志里只记「收到网页上的回答」,不记内容。
147
156
  - **建议用一个专用的低权限账号运行本程序**。沙箱之外、主目录之外的可读文件仍然可能被读到;GitCode 本身在网络白名单里。
148
157
  - 程序拒绝以 root 运行(容器里确有需要时加 `--allow-root`)。
149
158
  - 接入令牌只能用来接入机器,不能登录网页。**令牌泄露时在网页上删除它**,用它接入的机器会立即断开;之后新建令牌,在需要的机器上运行 `work-agent-runner login`。网页上的「封禁」只针对单台机器,拿到令牌的人可以换个标识重新接入,所以防泄露要靠删除令牌。
package/bin/main.mjs CHANGED
@@ -69,6 +69,7 @@ const FEATURE_TOOLS = {
69
69
  'pr-desc-issue-gen': ['git', 'curl', 'python3'],
70
70
  'ascend-code-review': ['git', 'python3', 'curl', 'jq', 'sed'],
71
71
  'code-review-flash': ['python3', 'git', 'base64'],
72
+ 'cann-knowledge': ['rg'],
72
73
  };
73
74
 
74
75
  const USAGE = `GitCode Agent 执行机器 ${VERSION}
@@ -477,9 +478,9 @@ async function offerPool(ctx, values) {
477
478
 
478
479
  function neededBy(tool) {
479
480
  if (tool === 'bwrap' || tool === 'socat') return '沙箱需要(所有功能)';
480
- if (tool === 'rg') return '检索 AscendC 知识仓需要';
481
481
  const features = Object.entries(FEATURE_TOOLS).filter(([, tools]) => tools.includes(tool)).map(([feature]) => FEATURE_LABELS[feature]);
482
- return features.length === 3 ? '所有功能需要' : `${features.join('、')}需要`;
482
+ if (!features.length) return '暂时没有功能需要';
483
+ return features.length === Object.keys(FEATURE_TOOLS).length ? '所有功能需要' : `${features.join('、')}需要`;
483
484
  }
484
485
 
485
486
  function printDoctor(result) {
@@ -1,7 +1,6 @@
1
- // Claude Code command line and environment, shared by the website
2
- // (lib/agent-runners.js re-exports these for server runs) and the execution
3
- // machine program (lib/jobs.mjs, lib/doctor.mjs). One copy only: the machine
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.
@@ -11,14 +10,13 @@ export const CLAUDE_TOOLS = 'Bash,Read,Glob,Grep,Edit,Write,Skill,Agent';
11
10
  const DEFAULT_PATH = '/usr/local/bin:/usr/bin:/bin';
12
11
 
13
12
  /**
14
- * `interactive` (交互执行): the task and our answers go over stdin as stream-json,
15
- * and permission prompts come to us (`--permission-prompt-tool stdio`, see
16
- * lib/agent-interaction.js). AskUserQuestion is offered but deliberately not
17
- * pre-allowed, so each call becomes a prompt we forward to the user.
13
+ * `interactive` (交互执行 jobs, lib/interaction.mjs): the task and the answers
14
+ * go over stdin as stream-json, and permission prompts come back
15
+ * (`--permission-prompt-tool stdio`). AskUserQuestion is offered but
16
+ * deliberately not pre-allowed, so each call becomes a prompt.
18
17
  *
19
18
  * `settingsFile` (execution machines): appended as `--settings <file>`, which
20
- * carries the sandbox settings; without it the arguments are exactly the
21
- * server's.
19
+ * carries the sandbox settings.
22
20
  */
23
21
  export function claudeArgs({ addDirs = [], interactive = false, settingsFile = '' } = {}) {
24
22
  const args = [
@@ -1,5 +1,6 @@
1
- // Staying connected: the SSE control channel (jobs, cancels, revocation) and
2
- // heartbeats, independent of each other. The channel reconnects with backoff
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,269 @@
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
+
37
+ // Lines this program adds to an interactive job's stdout, where claude's own
38
+ // control lines were (claude never prints these types). The website turns
39
+ // them into the page's question cards:
40
+ // { type: QUESTION_LINE, requestId, questions: [{ question, header, multiSelect, options }], timeoutMs }
41
+ // { type: QUESTION_CLOSED_LINE, requestId, reason: 'answered' | 'timeout' | 'cancelled' | 'ended' }
42
+ export const QUESTION_LINE = 'machine_question';
43
+ export const QUESTION_CLOSED_LINE = 'machine_question_closed';
44
+ export const CLOSE_REASONS = ['answered', 'timeout', 'cancelled', 'ended'];
45
+
46
+ const MAX_QUESTIONS = 4;
47
+ const MAX_OPTIONS = 6;
48
+ const MAX_ANSWER_LENGTH = 2000;
49
+ const REQUEST_ID_MAX = 100;
50
+
51
+ const clip = (value, max) => String(value ?? '').trim().slice(0, max);
52
+
53
+ /**
54
+ * Validates AskUserQuestion input; returns display-safe questions or null.
55
+ * Each keeps `original`, the exact text the CLI sent (answers are matched by
56
+ * it), which never leaves this program.
57
+ */
58
+ export function normalizeQuestions(input) {
59
+ const list = Array.isArray(input?.questions) ? input.questions : null;
60
+ if (!list || list.length === 0 || list.length > MAX_QUESTIONS) return null;
61
+ const questions = [];
62
+ const seen = new Set();
63
+ for (const item of list) {
64
+ const question = clip(item?.question, 1000);
65
+ if (!question || seen.has(question)) return null;
66
+ seen.add(question);
67
+ const original = typeof item?.question === 'string' ? item.question : question;
68
+ const options = (Array.isArray(item?.options) ? item.options : [])
69
+ .slice(0, MAX_OPTIONS)
70
+ .map((option) => ({ label: clip(option?.label, 200), description: clip(option?.description, 500) }))
71
+ .filter((option) => option.label);
72
+ questions.push({
73
+ question,
74
+ original,
75
+ header: clip(item?.header, 40),
76
+ multiSelect: item?.multiSelect === true,
77
+ options,
78
+ });
79
+ }
80
+ return questions;
81
+ }
82
+
83
+ /** Every question needs a non-empty answer (an option label, several joined, or free text). */
84
+ export function normalizeAnswers(questions, raw) {
85
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
86
+ const answers = {};
87
+ for (const { question } of questions) {
88
+ const value = Object.hasOwn(raw, question) ? raw[question] : undefined;
89
+ if (typeof value !== 'string') return null;
90
+ const text = value.trim();
91
+ if (!text || text.length > MAX_ANSWER_LENGTH) return null;
92
+ answers[question] = text;
93
+ }
94
+ return answers;
95
+ }
96
+
97
+ /**
98
+ * Drives the stdin side of one interactive job.
99
+ * write(obj) writes one JSON line to claude's stdin
100
+ * endInput() closes stdin (claude exits once all its work is done)
101
+ * notify(obj) a QUESTION_LINE / QUESTION_CLOSED_LINE object for the website
102
+ */
103
+ export function createClaudeInteraction({
104
+ write,
105
+ endInput,
106
+ notify,
107
+ questionTimeoutMs = QUESTION_TIMEOUT_MS,
108
+ idleCloseMs = INPUT_IDLE_CLOSE_MS,
109
+ hardIdleCloseMs = INPUT_HARD_IDLE_CLOSE_MS,
110
+ turnIdleCloseMs = INPUT_TURN_IDLE_CLOSE_MS,
111
+ }) {
112
+ const pending = new Map(); // requestId -> { questions, input, timer }
113
+ let closed = false;
114
+ let idleTimer = null;
115
+ let hardIdleTimer = null;
116
+ let runningTasks = 0;
117
+ let followUpTurnDue = false;
118
+ let lastTurnEnded = false;
119
+
120
+ const respond = (requestId, response) => {
121
+ if (closed) return;
122
+ write({ type: 'control_response', response: { subtype: 'success', request_id: requestId, response } });
123
+ };
124
+
125
+ const clearIdle = () => {
126
+ clearTimeout(idleTimer);
127
+ idleTimer = null;
128
+ };
129
+
130
+ const closeInput = () => {
131
+ if (closed) return;
132
+ closed = true;
133
+ clearIdle();
134
+ clearTimeout(hardIdleTimer);
135
+ hardIdleTimer = null;
136
+ endInput();
137
+ };
138
+
139
+ /**
140
+ * Restarted by every stdout event and whenever a question closes: stdin is
141
+ * closed after a long silence even if the turn/task bookkeeping says
142
+ * otherwise. Never runs while a question is open — the user has 5 minutes.
143
+ */
144
+ const armHardIdle = () => {
145
+ clearTimeout(hardIdleTimer);
146
+ hardIdleTimer = null;
147
+ if (closed || pending.size > 0) return;
148
+ hardIdleTimer = setTimeout(closeInput, lastTurnEnded ? hardIdleCloseMs : turnIdleCloseMs);
149
+ hardIdleTimer.unref?.();
150
+ };
151
+
152
+ const maybeScheduleClose = () => {
153
+ clearIdle();
154
+ if (closed || !lastTurnEnded || runningTasks > 0 || followUpTurnDue || pending.size > 0) return;
155
+ idleTimer = setTimeout(() => {
156
+ idleTimer = null;
157
+ closeInput();
158
+ }, idleCloseMs);
159
+ idleTimer.unref?.();
160
+ };
161
+
162
+ const settleQuestion = (requestId, reason) => {
163
+ const item = pending.get(requestId);
164
+ if (!item) return null;
165
+ clearTimeout(item.timer);
166
+ pending.delete(requestId);
167
+ notify({ type: QUESTION_CLOSED_LINE, requestId, reason });
168
+ armHardIdle();
169
+ return item;
170
+ };
171
+
172
+ function askUser(requestId, input) {
173
+ const questions = requestId.length <= REQUEST_ID_MAX ? normalizeQuestions(input) : null;
174
+ if (!questions) {
175
+ respond(requestId, { behavior: 'deny', message: '问题格式不正确:需要 1–4 个不重复的问题。' });
176
+ return;
177
+ }
178
+ const timer = setTimeout(() => {
179
+ if (!settleQuestion(requestId, 'timeout')) return;
180
+ respond(requestId, { behavior: 'deny', message: QUESTION_TIMEOUT_MESSAGE });
181
+ maybeScheduleClose();
182
+ }, questionTimeoutMs);
183
+ timer.unref?.();
184
+ pending.set(requestId, { questions, input, timer });
185
+ notify({
186
+ type: QUESTION_LINE,
187
+ requestId,
188
+ questions: questions.map(({ original: _original, ...shown }) => shown),
189
+ timeoutMs: questionTimeoutMs,
190
+ });
191
+ }
192
+
193
+ /** Feeds one parsed stdout event; returns true when it was a control message (not for the website). */
194
+ function handleEvent(event) {
195
+ clearIdle();
196
+ armHardIdle();
197
+ if (!event || typeof event !== 'object') return false;
198
+ if (event.type === 'control_request') {
199
+ const requestId = typeof event.request_id === 'string' ? event.request_id : '';
200
+ const request = event.request || {};
201
+ if (!requestId) return true;
202
+ if (request.subtype === 'can_use_tool' && request.tool_name === 'AskUserQuestion') {
203
+ askUser(requestId, request.input);
204
+ armHardIdle(); // a pending question suspends it until answered
205
+ } else if (request.subtype === 'can_use_tool') {
206
+ respond(requestId, { behavior: 'deny', message: DENY_TOOL_MESSAGE });
207
+ } else if (!closed) {
208
+ write({ type: 'control_response', response: { subtype: 'error', request_id: requestId, error: 'unsupported' } });
209
+ }
210
+ return true;
211
+ }
212
+ if (event.type === 'control_cancel_request') {
213
+ settleQuestion(String(event.request_id || ''), 'cancelled');
214
+ maybeScheduleClose();
215
+ return true;
216
+ }
217
+ if (event.type === 'control_response') return true;
218
+ if (event.type === 'system') {
219
+ if (event.subtype === 'init') {
220
+ // A new turn (also re-emitted for follow-up turns after subagents finish).
221
+ followUpTurnDue = false;
222
+ lastTurnEnded = false;
223
+ } else if (event.subtype === 'task_notification') {
224
+ // Only a notification that arrives after the turn already ended wakes a
225
+ // follow-up turn. Mid-turn notifications are consumed by the running
226
+ // turn and must not hold stdin open (that used to hang the whole job).
227
+ if (lastTurnEnded) followUpTurnDue = true;
228
+ } else if (event.subtype === 'background_tasks_changed') {
229
+ runningTasks = Array.isArray(event.tasks) ? event.tasks.length : 0;
230
+ }
231
+ } else if (event.type === 'result') {
232
+ lastTurnEnded = true;
233
+ }
234
+ // The safety-net length depends on whether a turn is running.
235
+ armHardIdle();
236
+ maybeScheduleClose();
237
+ return false;
238
+ }
239
+
240
+ /** The user's answer relayed by the website: 'ok' | 'not_found' | 'invalid'. */
241
+ function answer(requestId, rawAnswers) {
242
+ const id = typeof requestId === 'string' ? requestId : '';
243
+ const item = pending.get(id);
244
+ if (!item || closed) return 'not_found';
245
+ const answers = normalizeAnswers(item.questions, rawAnswers);
246
+ if (!answers) return 'invalid';
247
+ settleQuestion(id, 'answered');
248
+ const byOriginal = Object.fromEntries(
249
+ item.questions.map(({ question, original }) => [original, answers[question]]),
250
+ );
251
+ respond(id, { behavior: 'allow', updatedInput: { ...item.input, answers: byOriginal } });
252
+ return 'ok';
253
+ }
254
+
255
+ function start(task) {
256
+ write({ type: 'user', message: { role: 'user', content: task } });
257
+ }
258
+
259
+ /** claude is gone: drop timers, answer nothing more; the website closes any open question card. */
260
+ function dispose() {
261
+ closed = true;
262
+ clearIdle();
263
+ clearTimeout(hardIdleTimer);
264
+ hardIdleTimer = null;
265
+ for (const requestId of [...pending.keys()]) settleQuestion(requestId, 'ended');
266
+ }
267
+
268
+ return { start, handleEvent, answer, dispose, pendingCount: () => pending.size };
269
+ }
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); the
4
- // command line, environment, tool allowlist and sandbox settings are built
5
- // here, and the Skills come from this machine's own work-agent clone
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,
@@ -31,6 +35,7 @@ export const FEATURE_LABELS = {
31
35
  'pr-desc-issue-gen': 'PR 描述 / Issue',
32
36
  'ascend-code-review': '代码检视(全量)',
33
37
  'code-review-flash': '代码检视(快速)',
38
+ 'cann-knowledge': 'CANN 知识问答',
34
39
  };
35
40
 
36
41
  const RUN_ID = /^(skill|review)_\d+_[0-9a-f]{8}$/;
@@ -71,7 +76,8 @@ export function invalidJobField(job) {
71
76
  const keys = Object.keys(env);
72
77
  if (keys.length !== 1 || keys[0] !== 'GITCODE_CRED' || typeof env.GITCODE_CRED !== 'string' || env.GITCODE_CRED.length > 512) return 'env';
73
78
  if (!Number.isInteger(job.timeoutMs) || job.timeoutMs < 60_000 || job.timeoutMs > 14_400_000) return 'timeoutMs';
74
- if (job.interactive !== false) return 'interactive';
79
+ // true: 交互执行 — the website only asks machines that report capabilities.interactive.
80
+ if (typeof job.interactive !== 'boolean') return 'interactive';
75
81
  return '';
76
82
  }
77
83
 
@@ -278,13 +284,28 @@ export class JobManager {
278
284
  if (this.closed) return;
279
285
  const runId = typeof job?.runId === 'string' && job.runId.length <= 100 ? job.runId : '';
280
286
  if (!runId || this.jobs.has(runId)) return;
281
- 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 };
282
288
  this.jobs.set(runId, entry);
283
289
  entry.done = this.run(entry)
284
290
  .catch((error) => this.log.error(`任务 ${runId} 异常:${error?.message || error}`))
285
291
  .finally(() => this.jobs.delete(runId));
286
292
  }
287
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
+
288
309
  /** Stops a job (website cancel, heartbeat reconciliation). */
289
310
  cancel(runId) {
290
311
  const entry = this.jobs.get(runId);
@@ -396,6 +417,10 @@ export class JobManager {
396
417
  try {
397
418
  const { commit } = await this.workAgent.copyRepoInto(layout.workDir, this.paths.workAgentHome);
398
419
  const pool = this.workAgent.mountablePool();
420
+ // Claude Code limits its file tools to the working directory and whatever
421
+ // --add-dir names; the pool is outside it (the sandbox still decides what
422
+ // may be written).
423
+ entry.addDirs = pool ? [this.paths.workAgentHome] : [];
399
424
  writeSandboxSettings(layout.settingsFile, {
400
425
  workDir: fs.realpathSync(layout.workDir),
401
426
  realHome: this.realHome,
@@ -441,9 +466,10 @@ export class JobManager {
441
466
  resolve({ code: null, signal: null, error: '无法启动 claude:未安装' });
442
467
  return;
443
468
  }
469
+ const interactive = job.interactive === true;
444
470
  let child;
445
471
  try {
446
- child = spawn(this.claudePath, claudeArgs({ settingsFile: layout.settingsFile }), {
472
+ child = spawn(this.claudePath, claudeArgs({ settingsFile: layout.settingsFile, addDirs: entry.addDirs || [], interactive }), {
447
473
  cwd: layout.workDir,
448
474
  detached: true,
449
475
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -488,8 +514,34 @@ export class JobManager {
488
514
  },
489
515
  });
490
516
  entry.uploader = uploader;
517
+ if (interactive) {
518
+ entry.interaction = createClaudeInteraction({
519
+ write: (message) => {
520
+ if (child.stdin.writable) child.stdin.write(`${JSON.stringify(message)}\n`);
521
+ },
522
+ endInput: () => child.stdin.end(),
523
+ // In order with the output around it: where claude's control line was.
524
+ notify: (line) => uploader.push('stdout', `${JSON.stringify(line)}\n`),
525
+ });
526
+ }
491
527
  for (const name of ['stdout', 'stderr']) {
492
528
  const decoder = new StringDecoder('utf8');
529
+ if (name === 'stdout' && entry.interaction) {
530
+ // Line by line: claude's control messages are answered here and
531
+ // never reach the website; everything else goes on unchanged.
532
+ const lines = lineSplitter((line) => {
533
+ let event = null;
534
+ try {
535
+ event = JSON.parse(line);
536
+ } catch {
537
+ // Not JSON: plain output.
538
+ }
539
+ if (!entry.interaction.handleEvent(event)) uploader.push('stdout', `${line}\n`);
540
+ });
541
+ child.stdout.on('data', (chunk) => lines.write(decoder.write(chunk)));
542
+ child.stdout.on('end', () => lines.end(decoder.end()));
543
+ continue;
544
+ }
493
545
  child[name].on('data', (chunk) => uploader.push(name, decoder.write(chunk)));
494
546
  child[name].on('end', () => uploader.push(name, decoder.end()));
495
547
  }
@@ -507,6 +559,8 @@ export class JobManager {
507
559
  clearTimeout(timeout);
508
560
  clearTimeout(closeWait);
509
561
  killGroup(child.pid, 'SIGKILL'); // whatever the job left behind
562
+ // Open questions are reported closed before the exit.
563
+ entry.interaction?.dispose();
510
564
  await uploader.drain();
511
565
  resolve(result);
512
566
  };
@@ -521,7 +575,38 @@ export class JobManager {
521
575
  });
522
576
  child.once('close', (code, signal) => finish({ code, signal, error: '' }));
523
577
  child.stdin.on('error', () => {});
524
- child.stdin.end(job.task);
578
+ // Interactive: the task is the first stream-json message and stdin stays
579
+ // open for the answers until the interaction closes it.
580
+ if (entry.interaction) entry.interaction.start(job.task);
581
+ else child.stdin.end(job.task);
525
582
  });
526
583
  }
527
584
  }
585
+
586
+ /**
587
+ * Splits decoded text into lines for `onLine` (without the newline); end()
588
+ * flushes the last line even when it has no newline.
589
+ */
590
+ export function lineSplitter(onLine) {
591
+ let rest = '';
592
+ // Only the new text is searched: a long line arriving in many chunks stays linear.
593
+ const feed = (text) => {
594
+ let start = 0;
595
+ let index;
596
+ while ((index = text.indexOf('\n', start)) >= 0) {
597
+ const line = rest + text.slice(start, index);
598
+ rest = '';
599
+ start = index + 1;
600
+ onLine(line);
601
+ }
602
+ rest += text.slice(start);
603
+ };
604
+ return {
605
+ write: feed,
606
+ end(text = '') {
607
+ feed(text);
608
+ if (rest) onLine(rest);
609
+ rest = '';
610
+ },
611
+ };
612
+ }
@@ -1,5 +1,4 @@
1
- // How Skill text files are rewritten for a run, shared by the website
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
@@ -1,7 +1,5 @@
1
- // Reading a Skill tree and copying it into a run, shared by the website
2
- // (lib/skill-bundle.js, for server runs) and the execution machine program
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 (server run copies, a machine's
23
- * run copies) must see it:
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@online-tools/work-agent-runner",
3
- "version": "0.0.2-alpha-2",
3
+ "version": "0.0.3-alpha-1",
4
4
  "description": "GitCode 在线工具的 Agent 执行机器:在自己的机器上运行 work-agent 的 Skill(PR 描述、代码检视)",
5
5
  "license": "MIT",
6
6
  "type": "module",