mocode-ai 1.9.6 → 1.9.9
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/dist/agent/index.js +27 -0
- package/dist/agent/model-turn.js +6 -6
- package/dist/agent/request-governor.js +1 -1
- package/dist/context/pipeline.js +8 -3
- package/dist/context/vision-window.js +24 -9
- package/dist/host/protocol.js +4 -1
- package/dist/host/stdio.js +45 -1
- package/dist/index.js +7 -0
- package/dist/jobs/dir-snapshot.js +332 -0
- package/dist/jobs/worktree.js +78 -20
- package/dist/orchestrator/board.js +332 -0
- package/dist/orchestrator/cli.js +628 -0
- package/dist/orchestrator/index.js +4 -0
- package/dist/orchestrator/integrate.js +344 -0
- package/dist/orchestrator/lane-channel.js +146 -0
- package/dist/orchestrator/lane-executor.js +439 -0
- package/dist/orchestrator/lane-repl.js +154 -0
- package/dist/orchestrator/lane-site.js +255 -0
- package/dist/orchestrator/lanes.js +72 -0
- package/dist/orchestrator/lease.js +132 -0
- package/dist/orchestrator/live-log.js +193 -0
- package/dist/orchestrator/repl.js +435 -0
- package/dist/orchestrator/review.js +135 -0
- package/dist/orchestrator/scheduler.js +673 -0
- package/dist/orchestrator/scope.js +88 -0
- package/dist/orchestrator/state.js +533 -0
- package/dist/orchestrator/store.js +221 -0
- package/dist/orchestrator/supervisor-prompt.js +54 -0
- package/dist/orchestrator/supervisor.js +798 -0
- package/dist/orchestrator/tail.js +508 -0
- package/dist/orchestrator/task-prompt.js +93 -0
- package/dist/orchestrator/terminal.js +269 -0
- package/dist/orchestrator/tools.js +392 -0
- package/dist/orchestrator/types.js +1 -0
- package/dist/orchestrator/watch-panel.js +154 -0
- package/dist/orchestrator/worker.js +475 -0
- package/dist/orchestrator/workspaces.js +191 -0
- package/dist/repl/commands/memory.js +1 -1
- package/dist/repl/runtime.js +16 -2
- package/dist/session/compact.js +8 -1
- package/dist/session/store.js +1 -1
- package/dist/tools/builtins/ask-human.js +27 -6
- package/dist/tools/constants.js +10 -0
- package/dist/ui/handoff-block.js +91 -0
- package/dist/ui/layout-internal/statusbar.js +2 -1
- package/dist/ui/prompt-internal/editor.js +49 -0
- package/package.json +2 -2
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
// `mocode supervise tail`:在一个独立终端窗口里看某个 worker 的现场直播。
|
|
2
|
+
//
|
|
3
|
+
// 为什么单独一个进程/面板:supervisor 的对话 TUI 只有一块内容区,把 worker 每一步都写进去
|
|
4
|
+
// 会刷屏,而人真正想看的是「那个 mocode 在工作区里到底在干什么」。所以执行画面进独立窗口,
|
|
5
|
+
// supervisor 只留编排状态;两者通过文件通信(见 ./live-log.ts)。
|
|
6
|
+
//
|
|
7
|
+
// 为什么不复用 src/ui/layout:那是为「对话 + 底栏 + 输入框」服务的单会话布局,有 spinner、
|
|
8
|
+
// 状态栏心跳、DECSTBM 滚动区、markdown 重排等状态。这里是一次性只读视图 + 一行输入,
|
|
9
|
+
// 自己管 alt screen 更简单,也不跟 REPL 的全局单例互相污染(同 watch-panel.ts 的取舍)。
|
|
10
|
+
import { stdin, stdout } from 'node:process';
|
|
11
|
+
import readline from 'node:readline';
|
|
12
|
+
import { renderMarkdown } from '../ui/markdown.js';
|
|
13
|
+
import { ui } from '../ui/theme.js';
|
|
14
|
+
import { displayWidth, fmtElapsed, truncateDisplay, wrapByDisplayWidth } from '../ui/render.js';
|
|
15
|
+
import { appendLiveCommand, readLinesFrom, readLiveLog, } from './live-log.js';
|
|
16
|
+
const ESC = '\x1B[';
|
|
17
|
+
const ALT_ON = `${ESC}?1049h`;
|
|
18
|
+
const ALT_OFF = `${ESC}?1049l`;
|
|
19
|
+
const CURSOR_OFF = `${ESC}?25l`;
|
|
20
|
+
const CURSOR_ON = `${ESC}?25h`;
|
|
21
|
+
const MOUSE_ON = `${ESC}?1000h${ESC}?1006h`;
|
|
22
|
+
const MOUSE_OFF = `${ESC}?1006l${ESC}?1000l`;
|
|
23
|
+
/**
|
|
24
|
+
* 工具参数预览。worker 写的是 `ToolCallRef.arguments`(原始 JSON 字符串),但 live.log 是文本文件:
|
|
25
|
+
* 手写/旧版本/外部工具可能塞进对象、数组或 null。面板绝不能因此崩掉——它存在的意义就是「看一眼」。
|
|
26
|
+
*/
|
|
27
|
+
function formatArgs(args) {
|
|
28
|
+
if (args === undefined || args === null)
|
|
29
|
+
return '';
|
|
30
|
+
let raw;
|
|
31
|
+
if (typeof args === 'string')
|
|
32
|
+
raw = args;
|
|
33
|
+
else {
|
|
34
|
+
try {
|
|
35
|
+
raw = JSON.stringify(args);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return '';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const oneLine = raw.replace(/\s+/g, ' ').trim();
|
|
42
|
+
return oneLine ? truncateDisplay(oneLine, 120) : '';
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* 事件流 → 屏幕行。
|
|
46
|
+
*
|
|
47
|
+
* 渲染拆成「累积块 + 纯渲染」,面板循环只负责键位与定时器:这样排版(换行、缩进、
|
|
48
|
+
* 折叠预览)能单测,也不需要为了看一行内容去 mock 整个终端。
|
|
49
|
+
*/
|
|
50
|
+
export class LiveTranscript {
|
|
51
|
+
blocks = [];
|
|
52
|
+
meta = {};
|
|
53
|
+
activity = { thinkingSince: Date.now() };
|
|
54
|
+
outcome;
|
|
55
|
+
absorb(event) {
|
|
56
|
+
switch (event.kind) {
|
|
57
|
+
case 'header': {
|
|
58
|
+
this.meta = {
|
|
59
|
+
taskId: event.taskId,
|
|
60
|
+
lane: event.lane,
|
|
61
|
+
workspaceRoot: event.workspaceRoot,
|
|
62
|
+
workspacePath: event.workspacePath,
|
|
63
|
+
objective: event.objective,
|
|
64
|
+
};
|
|
65
|
+
this.blocks.push({
|
|
66
|
+
kind: 'lines',
|
|
67
|
+
lines: [
|
|
68
|
+
`${ui.accent}${ui.bold}task ${event.taskId}${ui.reset} ${ui.dim}· lane ${event.lane}${ui.reset}`,
|
|
69
|
+
...wrapByDisplayWidth(event.objective, 200).map((line) => `${ui.bold}${line}${ui.reset}`),
|
|
70
|
+
`${ui.dim}workspace ${event.workspaceRoot}${ui.reset}`,
|
|
71
|
+
`${ui.dim}execute ${event.workspacePath ?? '(pending)'}${ui.reset}`,
|
|
72
|
+
],
|
|
73
|
+
});
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
case 'start':
|
|
77
|
+
this.meta.sessionId = event.sessionId;
|
|
78
|
+
this.activity = { thinkingSince: Date.now(), status: 'starting' };
|
|
79
|
+
if (event.workspacePath)
|
|
80
|
+
this.meta.workspacePath = event.workspacePath;
|
|
81
|
+
return;
|
|
82
|
+
case 'status':
|
|
83
|
+
this.activity.status = event.value;
|
|
84
|
+
if (event.tool)
|
|
85
|
+
this.activity.tool = event.tool;
|
|
86
|
+
if (event.value !== 'running_tool')
|
|
87
|
+
this.activity.toolStartedAt = undefined;
|
|
88
|
+
return;
|
|
89
|
+
case 'tool':
|
|
90
|
+
this.activity.tool = event.name;
|
|
91
|
+
this.activity.toolStartedAt = Date.now();
|
|
92
|
+
this.activity.thinkingSince = Date.now();
|
|
93
|
+
this.blocks.push({
|
|
94
|
+
kind: 'lines',
|
|
95
|
+
lines: [
|
|
96
|
+
`${ui.cyan}▸ ${event.name}${ui.reset}${formatArgs(event.args) ? ` ${ui.dim}${formatArgs(event.args)}${ui.reset}` : ''}`,
|
|
97
|
+
],
|
|
98
|
+
});
|
|
99
|
+
return;
|
|
100
|
+
case 'tool-done':
|
|
101
|
+
this.activity.toolStartedAt = undefined;
|
|
102
|
+
this.blocks.push({
|
|
103
|
+
kind: 'lines',
|
|
104
|
+
lines: [
|
|
105
|
+
`${ui.dim} ✓ ${event.name}${event.preview ? ` · ${truncateDisplay(event.preview, 140)}` : ''}${ui.reset}`,
|
|
106
|
+
],
|
|
107
|
+
});
|
|
108
|
+
return;
|
|
109
|
+
case 'text': {
|
|
110
|
+
const last = this.blocks[this.blocks.length - 1];
|
|
111
|
+
if (last && last.kind === 'text')
|
|
112
|
+
last.text += event.text;
|
|
113
|
+
else
|
|
114
|
+
this.blocks.push({ kind: 'text', text: event.text });
|
|
115
|
+
this.activity.status = 'writing';
|
|
116
|
+
this.activity.tool = undefined;
|
|
117
|
+
this.activity.toolStartedAt = undefined;
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
case 'approval': {
|
|
121
|
+
const options = event.options.length > 0 ? event.options.join(' / ') : 'free text';
|
|
122
|
+
this.blocks.push({
|
|
123
|
+
kind: 'lines',
|
|
124
|
+
lines: [
|
|
125
|
+
'',
|
|
126
|
+
`${ui.yellow}${ui.bold}? ${event.approvalKind === 'ask_human' ? 'question' : 'approval'} ${event.id}${ui.reset}`,
|
|
127
|
+
`${ui.yellow} ${event.title}${ui.reset}`,
|
|
128
|
+
...(event.detail ?? '').split('\n').map((line) => `${ui.dim} ${line}${ui.reset}`),
|
|
129
|
+
`${ui.yellow} [${options}]${ui.reset}`,
|
|
130
|
+
`${ui.dim} 答: /approve ${event.id} <选项或文本> · /deny ${event.id} (在 supervisor 里也能答)${ui.reset}`,
|
|
131
|
+
],
|
|
132
|
+
});
|
|
133
|
+
this.activity.status = 'waiting for you';
|
|
134
|
+
this.activity.tool = undefined;
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
case 'approval-resolved':
|
|
138
|
+
this.blocks.push({
|
|
139
|
+
kind: 'lines',
|
|
140
|
+
lines: [
|
|
141
|
+
`${ui.dim} · approval ${event.id} ${event.action}${event.value ? ` (${event.value})` : ''}${ui.reset}`,
|
|
142
|
+
],
|
|
143
|
+
});
|
|
144
|
+
return;
|
|
145
|
+
case 'note':
|
|
146
|
+
this.blocks.push({ kind: 'lines', lines: [`${ui.dim} ${event.text}${ui.reset}`] });
|
|
147
|
+
return;
|
|
148
|
+
case 'end': {
|
|
149
|
+
this.outcome = { kind: event.outcome, summary: event.summary, error: event.error };
|
|
150
|
+
const good = event.outcome === 'completed';
|
|
151
|
+
const color = good ? ui.green : ui.yellow;
|
|
152
|
+
this.blocks.push({
|
|
153
|
+
kind: 'lines',
|
|
154
|
+
lines: [
|
|
155
|
+
'',
|
|
156
|
+
`${color}${ui.bold}${good ? '✓ completed' : `× ${event.outcome}`}${ui.reset}` +
|
|
157
|
+
(event.summary ? ` ${ui.dim}${truncateDisplay(event.summary, 160)}${ui.reset}` : ''),
|
|
158
|
+
...(event.error ? [`${ui.yellow}${wrapByDisplayWidth(event.error, 200).join('\n')}${ui.reset}`] : []),
|
|
159
|
+
],
|
|
160
|
+
});
|
|
161
|
+
this.activity = { thinkingSince: Date.now() };
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** 展平成所有行;文本块按 cols 渲染 markdown(缓存按 文本长度+cols)。 */
|
|
167
|
+
lines(cols) {
|
|
168
|
+
const out = [];
|
|
169
|
+
const width = Math.max(20, cols);
|
|
170
|
+
for (const block of this.blocks) {
|
|
171
|
+
if (block.kind === 'lines') {
|
|
172
|
+
out.push(...block.lines);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const key = `${width}:${block.text.length}`;
|
|
176
|
+
if (!block.rendered || block.rendered.key !== key) {
|
|
177
|
+
block.rendered = { key, lines: renderMarkdown(block.text, width) };
|
|
178
|
+
}
|
|
179
|
+
out.push(...block.rendered.lines);
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
/** 头部一行状态:`● thinking · read_file 12s`。 */
|
|
184
|
+
activityLine(now = Date.now()) {
|
|
185
|
+
if (this.outcome)
|
|
186
|
+
return `${this.outcome.kind === 'completed' ? ui.green : ui.yellow}■ ${this.outcome.kind}${ui.reset}`;
|
|
187
|
+
const parts = [];
|
|
188
|
+
if (this.activity.tool) {
|
|
189
|
+
const elapsed = this.activity.toolStartedAt ? ` ${fmtElapsed(now - this.activity.toolStartedAt)}` : '';
|
|
190
|
+
parts.push(`${ui.cyan}⚙ ${this.activity.tool}${elapsed}${ui.reset}`);
|
|
191
|
+
}
|
|
192
|
+
const status = this.activity.status;
|
|
193
|
+
if (status)
|
|
194
|
+
parts.push(`${ui.dim}${status}${ui.reset}`);
|
|
195
|
+
if (parts.length === 0)
|
|
196
|
+
parts.push(`${ui.dim}…${ui.reset}`);
|
|
197
|
+
parts.push(`${ui.dim}${fmtElapsed(now - this.activity.thinkingSince)}${ui.reset}`);
|
|
198
|
+
return parts.join(' ');
|
|
199
|
+
}
|
|
200
|
+
empty() {
|
|
201
|
+
return this.blocks.length === 0;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/** 底部输入行的前缀提示。 */
|
|
205
|
+
const INPUT_HINT = `${ui.dim}Enter 发送(tell)· /approve <id> <选择> · /deny <id> · ↑↓ PgUp/PgDn 滚动 · Esc 清空/退出 · Ctrl+C 退出${ui.reset}`;
|
|
206
|
+
function wrapAnsiSafe(line, width) {
|
|
207
|
+
if (displayWidth(line) <= width)
|
|
208
|
+
return [line];
|
|
209
|
+
return wrapByDisplayWidth(line, width);
|
|
210
|
+
}
|
|
211
|
+
/** 一帧的画面行(不含 alt screen 控制码),供面板与测试共用。 */
|
|
212
|
+
export function renderTailFrame(transcript, options) {
|
|
213
|
+
const { cols, rows } = options;
|
|
214
|
+
const headerH = 3;
|
|
215
|
+
const inputH = 2;
|
|
216
|
+
const bodyH = Math.max(3, rows - headerH - inputH);
|
|
217
|
+
const all = transcript.lines(cols);
|
|
218
|
+
const total = all.length;
|
|
219
|
+
const end = Math.max(0, total - options.scroll);
|
|
220
|
+
const start = Math.max(0, end - bodyH);
|
|
221
|
+
const body = all.slice(start, end);
|
|
222
|
+
const header = [
|
|
223
|
+
`${ui.accent}${ui.bold}${truncateDisplay(options.title, Math.max(20, cols - 2))}${ui.reset}`,
|
|
224
|
+
`${transcript.activityLine()} ${ui.dim}${total} lines${ui.reset}`,
|
|
225
|
+
`${ui.dim}${'─'.repeat(Math.max(1, cols))}${ui.reset}`,
|
|
226
|
+
];
|
|
227
|
+
const scrollHint = options.scrolledToBottom
|
|
228
|
+
? ''
|
|
229
|
+
: `${ui.yellow} ↓ 已上滚 ${options.scroll} 行 — End/↓ 回到最新${ui.reset}`;
|
|
230
|
+
const bodyLines = [];
|
|
231
|
+
if (transcript.empty())
|
|
232
|
+
bodyLines.push(`${ui.dim} 等待 worker 输出…${ui.reset}`);
|
|
233
|
+
for (const line of body)
|
|
234
|
+
bodyLines.push(...wrapAnsiSafe(line, cols));
|
|
235
|
+
while (bodyLines.length < bodyH)
|
|
236
|
+
bodyLines.push('');
|
|
237
|
+
bodyLines.splice(bodyH);
|
|
238
|
+
const inputLine = `${ui.accent}>${ui.reset} ${options.input}${ui.reverse} ${ui.reset}`;
|
|
239
|
+
return [
|
|
240
|
+
...header,
|
|
241
|
+
...bodyLines,
|
|
242
|
+
scrollHint || `${ui.dim}${'─'.repeat(Math.max(1, cols))}${ui.reset}`,
|
|
243
|
+
inputLine,
|
|
244
|
+
INPUT_HINT,
|
|
245
|
+
];
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* 进入 tail 面板直到退出。返回进程退出码(0 正常,130 = Ctrl+C)。
|
|
249
|
+
* 非 TTY 不进入面板:一次性把已有的 live.log 打到 stdout,便于管道 / 日志留档。
|
|
250
|
+
*/
|
|
251
|
+
export async function runTailPanel(options) {
|
|
252
|
+
const transcript = new LiveTranscript();
|
|
253
|
+
const send = options.sendCommand ??
|
|
254
|
+
((command) => appendLiveCommand({ log: options.logPath, inbox: options.inboxPath, receipts: options.receiptsPath }, command));
|
|
255
|
+
if (!stdout.isTTY || !stdin.isTTY) {
|
|
256
|
+
const dump = readLiveLog(options.logPath, 0);
|
|
257
|
+
for (const event of dump.events)
|
|
258
|
+
transcript.absorb(event);
|
|
259
|
+
const cols = stdout.columns || 100;
|
|
260
|
+
stdout.write(`${transcript.lines(cols).join('\n')}\n`);
|
|
261
|
+
return 0;
|
|
262
|
+
}
|
|
263
|
+
let logOffset = 0;
|
|
264
|
+
let receiptCursor = 0;
|
|
265
|
+
let input = '';
|
|
266
|
+
let scroll = 0;
|
|
267
|
+
let stopped = false;
|
|
268
|
+
let autoCloseTimer;
|
|
269
|
+
const width = () => stdout.columns || 100;
|
|
270
|
+
const height = () => stdout.rows || 30;
|
|
271
|
+
const paint = () => {
|
|
272
|
+
const frame = renderTailFrame(transcript, {
|
|
273
|
+
cols: width(),
|
|
274
|
+
rows: height(),
|
|
275
|
+
scroll,
|
|
276
|
+
input,
|
|
277
|
+
title: options.title,
|
|
278
|
+
scrolledToBottom: scroll === 0,
|
|
279
|
+
});
|
|
280
|
+
let out = `${ESC}H`;
|
|
281
|
+
for (const line of frame)
|
|
282
|
+
out += `${line}${ESC}K\r\n`;
|
|
283
|
+
stdout.write(`${out}${ESC}0J${CURSOR_ON}`);
|
|
284
|
+
options.onFrame?.({ lines: frame, input, scroll });
|
|
285
|
+
};
|
|
286
|
+
const drain = () => {
|
|
287
|
+
const read = readLiveLog(options.logPath, logOffset);
|
|
288
|
+
logOffset = read.offset;
|
|
289
|
+
let ended = false;
|
|
290
|
+
for (const event of read.events) {
|
|
291
|
+
transcript.absorb(event);
|
|
292
|
+
if (event.kind === 'end')
|
|
293
|
+
ended = true;
|
|
294
|
+
}
|
|
295
|
+
const receipts = readLinesFrom(options.receiptsPath, receiptCursor);
|
|
296
|
+
receiptCursor = receipts.consumed;
|
|
297
|
+
for (const line of receipts.lines) {
|
|
298
|
+
try {
|
|
299
|
+
const receipt = JSON.parse(line);
|
|
300
|
+
transcript.absorb({
|
|
301
|
+
t: receipt.t,
|
|
302
|
+
kind: 'note',
|
|
303
|
+
text: `${receipt.ok ? '✓' : '✗'} ${receipt.text}`,
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
// 坏行跳过
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return ended;
|
|
311
|
+
};
|
|
312
|
+
const cleanup = () => {
|
|
313
|
+
if (stopped)
|
|
314
|
+
return;
|
|
315
|
+
stopped = true;
|
|
316
|
+
if (autoCloseTimer)
|
|
317
|
+
clearTimeout(autoCloseTimer);
|
|
318
|
+
clearInterval(timer);
|
|
319
|
+
process.removeListener('SIGWINCH', onResize);
|
|
320
|
+
stdin.removeListener('keypress', onKey);
|
|
321
|
+
try {
|
|
322
|
+
stdin.setRawMode(false);
|
|
323
|
+
}
|
|
324
|
+
catch {
|
|
325
|
+
// 非 TTY:忽略
|
|
326
|
+
}
|
|
327
|
+
stdin.pause();
|
|
328
|
+
stdout.write(`${MOUSE_OFF}${CURSOR_ON}${ALT_OFF}`);
|
|
329
|
+
};
|
|
330
|
+
const exit = (code) => {
|
|
331
|
+
cleanup();
|
|
332
|
+
resolveExit(code);
|
|
333
|
+
};
|
|
334
|
+
const submit = () => {
|
|
335
|
+
const text = input.trim();
|
|
336
|
+
input = '';
|
|
337
|
+
if (!text)
|
|
338
|
+
return;
|
|
339
|
+
const command = parseTailCommand(text);
|
|
340
|
+
if (!command) {
|
|
341
|
+
transcript.absorb({ t: Date.now(), kind: 'note', text: `不认识这条命令:${text}` });
|
|
342
|
+
paint();
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
send(command);
|
|
347
|
+
transcript.absorb({
|
|
348
|
+
t: Date.now(),
|
|
349
|
+
kind: 'note',
|
|
350
|
+
text: `已投递 ${command.action}${command.text ? `:${command.text}` : ` ${command.approvalId ?? ''}`}(supervisor 收到后生效)`,
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
catch (error) {
|
|
354
|
+
transcript.absorb({
|
|
355
|
+
t: Date.now(),
|
|
356
|
+
kind: 'note',
|
|
357
|
+
text: `投递失败:${error instanceof Error ? error.message : String(error)}`,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
scroll = 0;
|
|
361
|
+
paint();
|
|
362
|
+
};
|
|
363
|
+
function onResize() {
|
|
364
|
+
paint();
|
|
365
|
+
}
|
|
366
|
+
function onKey(str, key) {
|
|
367
|
+
if (key.ctrl && key.name === 'c') {
|
|
368
|
+
exit(130);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
switch (key.name) {
|
|
372
|
+
case 'escape':
|
|
373
|
+
if (input.length > 0) {
|
|
374
|
+
input = '';
|
|
375
|
+
paint();
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
exit(0);
|
|
379
|
+
return;
|
|
380
|
+
case 'return':
|
|
381
|
+
case 'enter':
|
|
382
|
+
submit();
|
|
383
|
+
return;
|
|
384
|
+
case 'backspace':
|
|
385
|
+
if (input.length > 0) {
|
|
386
|
+
input = Array.from(input).slice(0, -1).join('');
|
|
387
|
+
paint();
|
|
388
|
+
}
|
|
389
|
+
return;
|
|
390
|
+
case 'pageup':
|
|
391
|
+
scroll = Math.min(scroll + Math.max(3, height() - 6), Math.max(0, transcript.lines(width()).length));
|
|
392
|
+
paint();
|
|
393
|
+
return;
|
|
394
|
+
case 'pagedown':
|
|
395
|
+
scroll = Math.max(0, scroll - Math.max(3, height() - 6));
|
|
396
|
+
paint();
|
|
397
|
+
return;
|
|
398
|
+
case 'up':
|
|
399
|
+
if (input.length === 0) {
|
|
400
|
+
scroll += 1;
|
|
401
|
+
paint();
|
|
402
|
+
}
|
|
403
|
+
return;
|
|
404
|
+
case 'down':
|
|
405
|
+
if (input.length === 0) {
|
|
406
|
+
scroll = Math.max(0, scroll - 1);
|
|
407
|
+
paint();
|
|
408
|
+
}
|
|
409
|
+
return;
|
|
410
|
+
case 'home':
|
|
411
|
+
if (input.length === 0) {
|
|
412
|
+
scroll = transcript.lines(width()).length;
|
|
413
|
+
paint();
|
|
414
|
+
}
|
|
415
|
+
return;
|
|
416
|
+
case 'end':
|
|
417
|
+
if (input.length === 0) {
|
|
418
|
+
scroll = 0;
|
|
419
|
+
paint();
|
|
420
|
+
}
|
|
421
|
+
return;
|
|
422
|
+
default:
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
425
|
+
// 鼠标滚轮:SGR 机制下 readline 把整段序列作为 str 送进来,这里只认 64/65。
|
|
426
|
+
if (str.startsWith('\x1b[<')) {
|
|
427
|
+
const match = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(str);
|
|
428
|
+
if (match) {
|
|
429
|
+
const button = Number(match[1]);
|
|
430
|
+
if (button === 64)
|
|
431
|
+
scroll = Math.min(scroll + 3, transcript.lines(width()).length);
|
|
432
|
+
else if (button === 65)
|
|
433
|
+
scroll = Math.max(0, scroll - 3);
|
|
434
|
+
paint();
|
|
435
|
+
}
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (key.ctrl || key.meta)
|
|
439
|
+
return;
|
|
440
|
+
if (str && !/^[\x00-\x1f]$/.test(str)) {
|
|
441
|
+
input += str;
|
|
442
|
+
paint();
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
let resolveExit;
|
|
446
|
+
const done = new Promise((resolve) => {
|
|
447
|
+
resolveExit = resolve;
|
|
448
|
+
});
|
|
449
|
+
stdout.write(`${ALT_ON}${MOUSE_ON}${CURSOR_OFF}`);
|
|
450
|
+
readline.emitKeypressEvents(stdin);
|
|
451
|
+
try {
|
|
452
|
+
stdin.setRawMode(true);
|
|
453
|
+
}
|
|
454
|
+
catch {
|
|
455
|
+
// 不支持 raw:按键不会来,画面仍可看;交给定时器/信号退出。
|
|
456
|
+
}
|
|
457
|
+
stdin.resume();
|
|
458
|
+
stdin.on('keypress', onKey);
|
|
459
|
+
process.on('SIGWINCH', onResize);
|
|
460
|
+
// 先把已有内容读一遍再画第一帧:窗口新开时 live.log 里通常已经有几行了。
|
|
461
|
+
drain();
|
|
462
|
+
paint();
|
|
463
|
+
const interval = options.refreshMs ?? 200;
|
|
464
|
+
const timer = setInterval(() => {
|
|
465
|
+
const ended = drain();
|
|
466
|
+
paint();
|
|
467
|
+
if (ended && options.autoClose !== false && !autoCloseTimer) {
|
|
468
|
+
// 收尾后留一小段:让人看清最后那句话(尤其失败原因),再自动关窗。
|
|
469
|
+
autoCloseTimer = setTimeout(() => exit(0), options.autoCloseDelayMs ?? 2500);
|
|
470
|
+
autoCloseTimer.unref?.();
|
|
471
|
+
}
|
|
472
|
+
}, interval);
|
|
473
|
+
timer.unref?.();
|
|
474
|
+
if (options.shouldExit) {
|
|
475
|
+
const poll = setInterval(() => {
|
|
476
|
+
if (options.shouldExit?.())
|
|
477
|
+
exit(0);
|
|
478
|
+
}, 50);
|
|
479
|
+
poll.unref?.();
|
|
480
|
+
}
|
|
481
|
+
return done;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* 把终端里打的一行翻成指令。
|
|
485
|
+
*
|
|
486
|
+
* 语义刻意窄:普通句子 = tell(插话纠偏),`/approve` / `/deny` = 答审批,
|
|
487
|
+
* 其余 `/xxx` 一律 null(不认识就说出来,别猜)。
|
|
488
|
+
*/
|
|
489
|
+
export function parseTailCommand(text) {
|
|
490
|
+
const base = { t: Date.now(), id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}` };
|
|
491
|
+
const approve = /^\/approve\s+(\S+)(?:\s+([\s\S]+))?$/.exec(text);
|
|
492
|
+
if (approve) {
|
|
493
|
+
const value = approve[2]?.trim();
|
|
494
|
+
return {
|
|
495
|
+
...base,
|
|
496
|
+
action: 'approve',
|
|
497
|
+
approvalId: approve[1],
|
|
498
|
+
...(value ? { value, approvalAction: 'submitted' } : { approvalAction: 'submitted' }),
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
const deny = /^\/deny\s+(\S+)$/.exec(text);
|
|
502
|
+
if (deny) {
|
|
503
|
+
return { ...base, action: 'approve', approvalId: deny[1], approvalAction: 'cancelled' };
|
|
504
|
+
}
|
|
505
|
+
if (text.startsWith('/'))
|
|
506
|
+
return null;
|
|
507
|
+
return { ...base, action: 'tell', text };
|
|
508
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// 派给 worker 的任务提示词,以及从回答里回收机器可读交接块。
|
|
2
|
+
//
|
|
3
|
+
// 两个执行器共用这一份,只有一处差异:**能不能问人**。
|
|
4
|
+
// - headless(`HostWorkerExecutor`):没有人在看那根管道,`ask_human` 被禁用,遇事只能报风险;
|
|
5
|
+
// - 可视 lane(`LaneReplExecutor`):那就是一个真 mocode REPL,人就在屏幕前,`ask_human` 正常可用。
|
|
6
|
+
// 这个差异用 `interactive` 一个开关表达,避免两份提示词各自漂移。
|
|
7
|
+
function dependencyContext(request) {
|
|
8
|
+
const items = request.task.dependsOn.flatMap((id) => {
|
|
9
|
+
const dependency = request.run.tasks[id];
|
|
10
|
+
if (!dependency?.output)
|
|
11
|
+
return [];
|
|
12
|
+
return [
|
|
13
|
+
{
|
|
14
|
+
taskId: id,
|
|
15
|
+
summary: dependency.output.summary,
|
|
16
|
+
changedFiles: dependency.output.changedFiles,
|
|
17
|
+
artifacts: dependency.output.artifacts,
|
|
18
|
+
risks: dependency.output.risks,
|
|
19
|
+
},
|
|
20
|
+
];
|
|
21
|
+
});
|
|
22
|
+
return items.length > 0 ? JSON.stringify(items, null, 2) : 'No upstream task handoffs.';
|
|
23
|
+
}
|
|
24
|
+
export function taskPrompt(request, options = {}) {
|
|
25
|
+
const { run, task, attempt, lane } = request;
|
|
26
|
+
const mode = lane?.mode ?? 'worktree';
|
|
27
|
+
const continued = lane?.sessionId
|
|
28
|
+
? `\nYou are continuing an existing session in this lane (task ${task.id}, attempt ${attempt}). Earlier work in this lane is already on disk — inspect it before redoing anything.`
|
|
29
|
+
: '';
|
|
30
|
+
const workspaceNote = mode === 'worktree'
|
|
31
|
+
? 'You are a complete mocode agent in a git worktree (the lane workspace) created from HEAD: uncommitted changes from the main workspace are intentionally absent, so read the code before assuming.'
|
|
32
|
+
: mode === 'copy'
|
|
33
|
+
? 'You are a complete mocode agent in an isolated copy of a non-git workspace (the lane workspace). Your writes land in the copy only; the original directory is untouched and the operator reviews a diff afterwards.'
|
|
34
|
+
: 'You are a complete mocode agent running directly inside the workspace, in place. Every file you write takes effect immediately for the user: prefer additive, reversible edits and never delete or bulk-rewrite files without evidence.';
|
|
35
|
+
const humanNote = options.interactive
|
|
36
|
+
? 'The operator can see this terminal and may type into it at any time; when a decision is genuinely ambiguous or irreversible, use `ask_human` and wait for the answer.'
|
|
37
|
+
: 'You cannot ask the human: `ask_human` is disabled in supervised workers — if a required decision is ambiguous or risky, stop and report it as a risk/open question instead of guessing.';
|
|
38
|
+
return `# Super Agent worker task\n\nRun: ${run.id}\nTask: ${task.id} (${task.title})\nAttempt: ${attempt}\nLane: ${lane?.id ?? task.lane}\nOverall objective: ${run.objective}\n\n## Objective\n${task.contract.objective}\n\n## Upstream handoffs\n${dependencyContext(request)}\n\n## Boundaries\n- Change policy: ${task.contract.changePolicy}\n- Allowed scope: ${task.contract.scope.allow.join(', ')}\n- Denied scope: ${task.contract.scope.deny.join(', ')}\n- Acceptance criteria:\n${task.contract.acceptanceCriteria.map((item) => ` - ${item}`).join('\n') || ' - Complete the objective and report evidence.'}\n- Required checks:\n${task.contract.requiredChecks.map((item) => ` - ${item}`).join('\n') || ' - Choose the smallest relevant validation.'}\n\n${workspaceNote}${continued} Finish only this task. Do not commit or push. ${humanNote} If the task is read_only, do not modify files. End with a concise human-readable handoff, followed by exactly one machine-readable block in this form:\n<mocode_handoff>{"summary":"...","validation":[{"command":"...","status":"passed|failed","detail":"..."}],"risks":["..."]}</mocode_handoff>`;
|
|
39
|
+
}
|
|
40
|
+
/** 解析 worker 回答里的 `<mocode_handoff>` 块;没有块时整段回答就是摘要。 */
|
|
41
|
+
export function parseHandoff(text) {
|
|
42
|
+
const match = /<mocode_handoff>([\s\S]*?)<\/mocode_handoff>/i.exec(text);
|
|
43
|
+
if (!match)
|
|
44
|
+
return { found: false, summary: text.trim() };
|
|
45
|
+
try {
|
|
46
|
+
const value = JSON.parse(match[1]);
|
|
47
|
+
const validation = Array.isArray(value.validation)
|
|
48
|
+
? value.validation.flatMap((entry) => {
|
|
49
|
+
if (!entry || typeof entry !== 'object')
|
|
50
|
+
return [];
|
|
51
|
+
const item = entry;
|
|
52
|
+
if (typeof item.command !== 'string' || (item.status !== 'passed' && item.status !== 'failed'))
|
|
53
|
+
return [];
|
|
54
|
+
return [
|
|
55
|
+
{
|
|
56
|
+
command: item.command,
|
|
57
|
+
status: item.status,
|
|
58
|
+
...(typeof item.detail === 'string' ? { detail: item.detail } : {}),
|
|
59
|
+
},
|
|
60
|
+
];
|
|
61
|
+
})
|
|
62
|
+
: undefined;
|
|
63
|
+
const risks = Array.isArray(value.risks)
|
|
64
|
+
? value.risks.filter((item) => typeof item === 'string')
|
|
65
|
+
: undefined;
|
|
66
|
+
return {
|
|
67
|
+
found: true,
|
|
68
|
+
summary: typeof value.summary === 'string' && value.summary.trim() ? value.summary.trim() : text.trim(),
|
|
69
|
+
validation,
|
|
70
|
+
risks,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return {
|
|
75
|
+
found: false,
|
|
76
|
+
summary: text.trim(),
|
|
77
|
+
risks: ['Worker returned an invalid <mocode_handoff> JSON block.'],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* 完成前的最小校验:报告里写了失败的检查、必需检查没报通过、只读任务动了文件,都算没完成。
|
|
83
|
+
* 返回 undefined 表示可以判 completed。
|
|
84
|
+
*/
|
|
85
|
+
export function handoffViolation(request, parsed) {
|
|
86
|
+
const failedValidation = parsed.validation?.find((item) => item.status === 'failed');
|
|
87
|
+
if (failedValidation)
|
|
88
|
+
return `Worker reported a failed validation: ${failedValidation.command}`;
|
|
89
|
+
const missingChecks = request.task.contract.requiredChecks.filter((command) => !parsed.validation?.some((item) => item.command === command && item.status === 'passed'));
|
|
90
|
+
if (missingChecks.length > 0)
|
|
91
|
+
return `Worker did not report required checks as passed: ${missingChecks.join(', ')}`;
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|