@online-tools/work-agent-runner 0.0.5-alpha-1 → 0.1.0-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 +96 -18
- package/bin/main.mjs +898 -271
- package/lib/config.mjs +39 -4
- package/lib/connection.mjs +38 -1
- package/lib/control.mjs +330 -0
- package/lib/errors.mjs +34 -0
- package/lib/jobs.mjs +368 -72
- package/lib/log.mjs +95 -7
- package/lib/maintenance.mjs +394 -0
- package/lib/sandbox.mjs +55 -6
- package/lib/state.mjs +145 -0
- package/lib/views.mjs +234 -0
- package/lib/work-agent.mjs +17 -1
- package/package.json +1 -1
package/lib/state.mjs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// What the running instance knows about itself, kept where a terminal can
|
|
2
|
+
// read it even when the instance does not answer (docs/design.md 9.1, 9.2):
|
|
3
|
+
//
|
|
4
|
+
// state/status.json a snapshot: instance, connection, jobs and their
|
|
5
|
+
// phases, maintenance, resources — rewritten (atomically)
|
|
6
|
+
// at most every 2 s while something changes
|
|
7
|
+
// state/history.jsonl one line per finished job: run id, feature, phase
|
|
8
|
+
// times, result, exit, error code — the last 1000
|
|
9
|
+
// jobs or 30 days
|
|
10
|
+
//
|
|
11
|
+
// Neither ever holds a task's text, a model, an API key, GITCODE_CRED or an
|
|
12
|
+
// answer of 交互执行; the website's 操作记录 has who ran what.
|
|
13
|
+
//
|
|
14
|
+
// Only node: built-ins and files in this directory.
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
|
|
19
|
+
import { readJsonFile, writeJsonAtomic } from './fs-safe.mjs';
|
|
20
|
+
|
|
21
|
+
export const STATUS_SCHEMA = 1;
|
|
22
|
+
export const HISTORY_MAX = 1000;
|
|
23
|
+
export const HISTORY_DAYS = 30;
|
|
24
|
+
const WRITE_DELAY_MS = 2000;
|
|
25
|
+
const TRIM_EVERY = 50;
|
|
26
|
+
|
|
27
|
+
export class StateStore {
|
|
28
|
+
constructor({ statusFile, historyFile, writeDelayMs = WRITE_DELAY_MS, now = () => Date.now() }) {
|
|
29
|
+
this.statusFile = statusFile;
|
|
30
|
+
this.historyFile = historyFile;
|
|
31
|
+
this.writeDelayMs = writeDelayMs;
|
|
32
|
+
this.now = now;
|
|
33
|
+
this.status = { schema: STATUS_SCHEMA };
|
|
34
|
+
this.timer = null;
|
|
35
|
+
this.appends = 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Merges `patch` into the snapshot; written within writeDelayMs. */
|
|
39
|
+
set(patch) {
|
|
40
|
+
Object.assign(this.status, patch);
|
|
41
|
+
if (this.timer) return;
|
|
42
|
+
this.timer = setTimeout(() => {
|
|
43
|
+
this.timer = null;
|
|
44
|
+
this.flush();
|
|
45
|
+
}, this.writeDelayMs);
|
|
46
|
+
this.timer.unref?.();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The snapshot as written, with its time. */
|
|
50
|
+
snapshot() {
|
|
51
|
+
return { ...this.status, updatedAt: new Date(this.now()).toISOString() };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
flush() {
|
|
55
|
+
clearTimeout(this.timer);
|
|
56
|
+
this.timer = null;
|
|
57
|
+
try {
|
|
58
|
+
fs.mkdirSync(path.dirname(this.statusFile), { recursive: true, mode: 0o700 });
|
|
59
|
+
writeJsonAtomic(this.statusFile, this.snapshot());
|
|
60
|
+
} catch {
|
|
61
|
+
// Status is for display: never a reason to stop.
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** One finished job. Trimmed to the last HISTORY_MAX within HISTORY_DAYS now and then. */
|
|
66
|
+
appendHistory(record) {
|
|
67
|
+
try {
|
|
68
|
+
fs.mkdirSync(path.dirname(this.historyFile), { recursive: true, mode: 0o700 });
|
|
69
|
+
fs.appendFileSync(this.historyFile, `${JSON.stringify(record)}\n`, { mode: 0o600 });
|
|
70
|
+
this.appends += 1;
|
|
71
|
+
if (this.appends % TRIM_EVERY === 0) this.trimHistory();
|
|
72
|
+
} catch {
|
|
73
|
+
// Same as above.
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
trimHistory() {
|
|
78
|
+
try {
|
|
79
|
+
const cutoff = this.now() - HISTORY_DAYS * 86_400_000;
|
|
80
|
+
const kept = readLines(this.historyFile)
|
|
81
|
+
.filter((record) => Date.parse(record?.at?.done || '') >= cutoff)
|
|
82
|
+
.slice(-HISTORY_MAX);
|
|
83
|
+
const temp = `${this.historyFile}.${process.pid}.tmp`;
|
|
84
|
+
fs.writeFileSync(temp, kept.map((record) => `${JSON.stringify(record)}\n`).join(''), { mode: 0o600 });
|
|
85
|
+
fs.renameSync(temp, this.historyFile);
|
|
86
|
+
} catch {
|
|
87
|
+
// Next time.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function readLines(file) {
|
|
93
|
+
let text = '';
|
|
94
|
+
try {
|
|
95
|
+
text = fs.readFileSync(file, 'utf8');
|
|
96
|
+
} catch {
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
const records = [];
|
|
100
|
+
for (const line of text.split('\n')) {
|
|
101
|
+
if (!line.trim()) continue;
|
|
102
|
+
try {
|
|
103
|
+
const record = JSON.parse(line);
|
|
104
|
+
if (record && typeof record === 'object' && typeof record.runId === 'string') records.push(record);
|
|
105
|
+
} catch {
|
|
106
|
+
// A line cut by a crash: skipped.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return records;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The last snapshot an instance wrote, or null. */
|
|
113
|
+
export function readStatus(statusFile) {
|
|
114
|
+
return readJsonFile(statusFile);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Whether `wanted` names the run `runId`: the whole id, or any part of it of at least 6 characters. */
|
|
118
|
+
export function matchesRunId(runId, wanted) {
|
|
119
|
+
const id = String(runId || '');
|
|
120
|
+
const part = String(wanted || '');
|
|
121
|
+
return Boolean(part) && (id === part || (part.length >= 6 && id.includes(part)));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Finished jobs, newest first: `since` (ms) by finish time, `failedOnly`
|
|
126
|
+
* (anything but ok), `runId` (see matchesRunId()), at most `limit`.
|
|
127
|
+
*/
|
|
128
|
+
export function readHistory(historyFile, { since = 0, limit = 20, failedOnly = false, runId = '' } = {}) {
|
|
129
|
+
return readLines(historyFile)
|
|
130
|
+
.filter((record) => !since || Date.parse(record?.at?.done || '') >= since)
|
|
131
|
+
.filter((record) => !failedOnly || record.result !== 'ok')
|
|
132
|
+
.filter((record) => !runId || matchesRunId(record.runId, runId))
|
|
133
|
+
.reverse()
|
|
134
|
+
.slice(0, limit);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** { ok, failed, cancelled, timeout } over the records given (e.g. the last 24 hours). */
|
|
138
|
+
export function countResults(records) {
|
|
139
|
+
const counts = { ok: 0, failed: 0, cancelled: 0, timeout: 0 };
|
|
140
|
+
for (const record of records) {
|
|
141
|
+
if (record.result in counts) counts[record.result] += 1;
|
|
142
|
+
else if (record.result !== 'not_accepted') counts.failed += 1;
|
|
143
|
+
}
|
|
144
|
+
return counts;
|
|
145
|
+
}
|
package/lib/views.mjs
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// What `status`, `jobs` and `paths` print (docs/design.md 5.1, 3.22): pure
|
|
2
|
+
// functions from the data the instance (or its state files) reports to lines
|
|
3
|
+
// of text, so the commands stay thin and the wording is tested in one place.
|
|
4
|
+
//
|
|
5
|
+
// Only node: built-ins and files in this directory.
|
|
6
|
+
|
|
7
|
+
import { FEATURE_LABELS } from './jobs.mjs';
|
|
8
|
+
|
|
9
|
+
const GB = 1024 ** 3;
|
|
10
|
+
|
|
11
|
+
const PHASE_LABELS = {
|
|
12
|
+
received: '收到',
|
|
13
|
+
accepted: '已接单',
|
|
14
|
+
waiting: '等待中',
|
|
15
|
+
preparing: '准备中',
|
|
16
|
+
running: '运行中',
|
|
17
|
+
finishing: '收尾中',
|
|
18
|
+
cleaning: '清理中',
|
|
19
|
+
done: '结束',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const RESULT_LABELS = {
|
|
23
|
+
ok: '✓ 成功',
|
|
24
|
+
failed: '✗ 失败',
|
|
25
|
+
cancelled: '· 取消',
|
|
26
|
+
timeout: '✗ 超时',
|
|
27
|
+
not_accepted: '· 未接单',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const REASON_LABELS = {
|
|
31
|
+
starting_checks: '启动检查进行中',
|
|
32
|
+
clone_missing: 'work-agent 仓库不可用',
|
|
33
|
+
pool_update: '正在更新知识仓',
|
|
34
|
+
disk_low: '工作目录磁盘空间不足',
|
|
35
|
+
unconfirmed: '网页上还没有确认这台机器',
|
|
36
|
+
outdated: '程序版本过低',
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// Characters a terminal draws two columns wide (CJK, fullwidth forms): columns
|
|
40
|
+
// line up by what is drawn, not by how many characters there are.
|
|
41
|
+
const WIDE = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/u;
|
|
42
|
+
|
|
43
|
+
/** How many terminal columns `text` takes. */
|
|
44
|
+
export function displayWidth(text) {
|
|
45
|
+
let width = 0;
|
|
46
|
+
for (const char of String(text)) width += WIDE.test(char) ? 2 : 1;
|
|
47
|
+
return width;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `text` and spaces up to `width` columns (none when it is that wide already). */
|
|
51
|
+
export function padDisplay(text, width) {
|
|
52
|
+
return `${text}${' '.repeat(Math.max(0, width - displayWidth(text)))}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// status: labels in a column of this width ("近 24 小时" is the widest).
|
|
56
|
+
const LABEL_WIDTH = 12;
|
|
57
|
+
const INDENT = ' '.repeat(LABEL_WIDTH);
|
|
58
|
+
|
|
59
|
+
export function featureLabel(feature) {
|
|
60
|
+
return FEATURE_LABELS[feature] || feature || '(未知)';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** "12 分 31 秒", "3 小时 4 分", "5 秒". */
|
|
64
|
+
export function formatDuration(ms) {
|
|
65
|
+
const seconds = Math.max(0, Math.round(ms / 1000));
|
|
66
|
+
if (seconds < 60) return `${seconds} 秒`;
|
|
67
|
+
const minutes = Math.floor(seconds / 60);
|
|
68
|
+
if (minutes < 60) return `${minutes} 分 ${seconds % 60} 秒`;
|
|
69
|
+
const hours = Math.floor(minutes / 60);
|
|
70
|
+
if (hours < 48) return `${hours} 小时 ${minutes % 60} 分`;
|
|
71
|
+
return `${Math.floor(hours / 24)} 天 ${hours % 24} 小时`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** "12-01 10:12:03" in local time ('' for no time). */
|
|
75
|
+
export function formatTime(value) {
|
|
76
|
+
const time = Date.parse(value || '');
|
|
77
|
+
if (!Number.isFinite(time)) return '';
|
|
78
|
+
const date = new Date(time);
|
|
79
|
+
const pad = (number) => String(number).padStart(2, '0');
|
|
80
|
+
return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** "6 秒前", "3 分钟前", "2 小时前", "3 天前"; "3 小时后" for times ahead. */
|
|
84
|
+
export function relative(value, now = Date.now()) {
|
|
85
|
+
const time = Date.parse(value || '');
|
|
86
|
+
if (!Number.isFinite(time)) return '';
|
|
87
|
+
const diff = now - time;
|
|
88
|
+
const ahead = diff < 0;
|
|
89
|
+
const abs = Math.abs(diff);
|
|
90
|
+
let text;
|
|
91
|
+
if (abs < 60_000) text = `${Math.max(1, Math.round(abs / 1000))} 秒`;
|
|
92
|
+
else if (abs < 3_600_000) text = `${Math.round(abs / 60_000)} 分钟`;
|
|
93
|
+
else if (abs < 86_400_000) text = `${Math.round(abs / 3_600_000)} 小时`;
|
|
94
|
+
else text = `${Math.round(abs / 86_400_000)} 天`;
|
|
95
|
+
return ahead ? `${text}后` : `${text}前`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function gigabytes(bytes) {
|
|
99
|
+
return `${(bytes / GB).toFixed(bytes >= 100 * GB ? 0 : 1)} GB`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A short run id for tables: skill_1764…a3f1. */
|
|
103
|
+
export function shortRunId(runId) {
|
|
104
|
+
const id = String(runId || '');
|
|
105
|
+
return id.length > 20 ? `${id.slice(0, 10)}…${id.slice(-4)}` : id;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The live part of `status`: from the instance's snapshot (status.json shape).
|
|
110
|
+
* `stale`: read from the file, because no instance answered — `silentPid`: one
|
|
111
|
+
* runs but did not answer (`silentReason`), else none runs.
|
|
112
|
+
*/
|
|
113
|
+
export function statusLines(snapshot, { now = Date.now(), stale = false, silentPid = 0, silentReason = '' } = {}) {
|
|
114
|
+
const lines = [];
|
|
115
|
+
const say = (label, text) => lines.push(`${padDisplay(label, LABEL_WIDTH)}${text}`);
|
|
116
|
+
const instance = snapshot.instance || {};
|
|
117
|
+
if (stale && silentPid) {
|
|
118
|
+
lines.push(`程序在运行(pid ${silentPid}),但没有回应管理接口${silentReason ? `(${silentReason})` : ''}。以下是记录里的状态(${relative(snapshot.updatedAt, now)}):`);
|
|
119
|
+
} else if (stale) {
|
|
120
|
+
lines.push(`程序没有在运行。以下是它最后一次记录的状态(${relative(snapshot.updatedAt, now)}):`);
|
|
121
|
+
} else {
|
|
122
|
+
const how = { systemd: '后台服务(systemd)', launchd: '后台服务(launchd)' }[instance.service] || '前台';
|
|
123
|
+
lines.push(`work-agent-runner ${instance.version || ''} · ${how}运行中(pid ${instance.pid},已运行 ${formatDuration(now - Date.parse(instance.startedAt || now))})`);
|
|
124
|
+
}
|
|
125
|
+
const connection = snapshot.connection || {};
|
|
126
|
+
const machine = snapshot.machine || {};
|
|
127
|
+
if (connection.connected) {
|
|
128
|
+
const confirmed = machine.confirmed === false ? ',网页上还没有确认' : '';
|
|
129
|
+
say('连接', `✓ 已连接 ${connection.server || ''} · 最近心跳 ${relative(connection.lastHeartbeatAt, now) || '—'} · 登记为「${machine.name || ''}」${confirmed}${machine.role === 'server' ? ' · 服务器执行机器' : ''}`);
|
|
130
|
+
} else {
|
|
131
|
+
say('连接', `✗ 未连接 ${connection.server || ''}${connection.lastError ? `:${connection.lastError}` : ''}`);
|
|
132
|
+
}
|
|
133
|
+
const state = snapshot.state || {};
|
|
134
|
+
if (state.accepting) say('接单', '✓ 接单中');
|
|
135
|
+
else say('接单', `✗ 暂不接单:${REASON_LABELS[state.reason] || state.reason || '未连接'}`);
|
|
136
|
+
const jobs = Array.isArray(snapshot.jobs) ? snapshot.jobs : [];
|
|
137
|
+
if (!jobs.length) say('任务', '没有运行中的任务');
|
|
138
|
+
else {
|
|
139
|
+
say('任务', `${jobs.length} 个`);
|
|
140
|
+
for (const job of jobs) {
|
|
141
|
+
const timeout = job.timeoutAt ? `,${relative(job.timeoutAt, now)}超时` : '';
|
|
142
|
+
lines.push(`${INDENT}${shortRunId(job.runId)} ${featureLabel(job.feature)} ${PHASE_LABELS[job.phase] || job.phase} ${formatDuration(now - Date.parse(job.phaseSince || now))}${timeout}`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const maintenance = snapshot.maintenance || {};
|
|
146
|
+
const repo = maintenance.repo || {};
|
|
147
|
+
const pool = maintenance.pool || {};
|
|
148
|
+
const repoLast = repo.lastRunAt ? ` · ${relative(repo.lastRunAt, now)}${repo.result === 'ok' ? '刷新成功' : `刷新失败(${repo.error})`}` : '';
|
|
149
|
+
say('维护', `work-agent ${repo.commit ? repo.commit.slice(0, 7) : '不可用'}${repoLast}${repo.nextAt ? ` · 下次 ${formatTime(repo.nextAt)}` : ''}`);
|
|
150
|
+
if (pool.repos) {
|
|
151
|
+
const poolLast = pool.running ? ' · 正在更新' : pool.lastRunAt ? ` · ${relative(pool.lastRunAt, now)}${pool.result === 'ok' ? '更新成功' : `更新失败(${pool.error})`}` : pool.updatedAt ? ` · ${relative(pool.updatedAt, now)}更新` : '';
|
|
152
|
+
lines.push(`${INDENT}知识仓 ${pool.repos} 个仓${poolLast}${pool.requested ? ' · 已请求更新' : ''}${pool.nextAt ? ` · 下次 ${formatTime(pool.nextAt)}` : ''}`);
|
|
153
|
+
} else {
|
|
154
|
+
lines.push(`${INDENT}知识仓未初始化(work-agent-runner setup 可以下载)`);
|
|
155
|
+
}
|
|
156
|
+
const caps = snapshot.capabilities || {};
|
|
157
|
+
const sandbox = caps.sandbox || {};
|
|
158
|
+
const checked = maintenance.checks?.lastRunAt ? `(${relative(maintenance.checks.lastRunAt, now)}检测)` : '';
|
|
159
|
+
say('环境', `Claude Code ${caps.claude || '不可用'} · ${sandbox.ok ? '沙箱可用' : `沙箱不可用:${sandbox.reason || '尚未检测'}`}${checked}`);
|
|
160
|
+
const resources = snapshot.resources || {};
|
|
161
|
+
const parts = [];
|
|
162
|
+
if (resources.workRootFree) parts.push(`工作目录可用 ${gigabytes(resources.workRootFree)}`);
|
|
163
|
+
if (resources.memTotal) parts.push(`内存可用 ${gigabytes(resources.memAvailable || 0)} / ${gigabytes(resources.memTotal)}`);
|
|
164
|
+
if (Array.isArray(resources.loadAvg)) parts.push(`负载 ${resources.loadAvg[0]}`);
|
|
165
|
+
if (parts.length) say('资源', parts.join(' · '));
|
|
166
|
+
const counts = snapshot.last24h;
|
|
167
|
+
if (counts) {
|
|
168
|
+
const total = counts.ok + counts.failed + counts.cancelled + counts.timeout;
|
|
169
|
+
const last = counts.lastError?.code ? ` 最近错误 ${counts.lastError.code}(${relative(counts.lastError.at, now)})` : '';
|
|
170
|
+
say('近 24 小时', `任务 ${total}:成功 ${counts.ok} · 失败 ${counts.failed} · 取消 ${counts.cancelled} · 超时 ${counts.timeout}${last}`);
|
|
171
|
+
}
|
|
172
|
+
for (const problem of snapshot.degraded || []) say('问题', `${problem.code} ${problem.message}`);
|
|
173
|
+
return lines;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** `jobs`: running ones first, then the history (newest first). */
|
|
177
|
+
export function jobsLines({ running = [], history = [] }, { now = Date.now(), failedOnly = false } = {}) {
|
|
178
|
+
const lines = [];
|
|
179
|
+
if (running.length) {
|
|
180
|
+
lines.push(`运行中(${running.length}):`);
|
|
181
|
+
// The whole id: it is what `jobs show` / `jobs cancel` take.
|
|
182
|
+
for (const job of running) {
|
|
183
|
+
lines.push(` ${job.runId} ${featureLabel(job.feature)} ${PHASE_LABELS[job.phase] || job.phase} ${formatDuration(now - Date.parse(job.phaseSince || now))}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (!history.length) {
|
|
187
|
+
lines.push(failedOnly ? '没有失败的任务记录' : '还没有任务记录');
|
|
188
|
+
return lines;
|
|
189
|
+
}
|
|
190
|
+
lines.push(`${failedOnly ? '失败' : '最近'}的任务(${history.length} 条):`);
|
|
191
|
+
for (const record of history) {
|
|
192
|
+
const at = record.at || {};
|
|
193
|
+
const took = at.received && at.done ? formatDuration(Date.parse(at.done) - Date.parse(at.received)) : '';
|
|
194
|
+
const why = record.result !== 'ok' && record.error?.message ? ` ${record.error.code ? `${record.error.code} ` : ''}${record.error.message}` : '';
|
|
195
|
+
lines.push(` ${formatTime(at.done)} ${padDisplay(RESULT_LABELS[record.result] || record.result, 8)} ${padDisplay(took, 12)} ${featureLabel(record.feature)} ${record.runId}${why}`);
|
|
196
|
+
}
|
|
197
|
+
return lines;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** `jobs show <runId>`: one record in full — finished (history), or running (a snapshot entry: no result). */
|
|
201
|
+
export function jobDetailLines(record, { now = Date.now() } = {}) {
|
|
202
|
+
const at = record.at || {};
|
|
203
|
+
const lines = [`任务 ${record.runId}`, ` 功能:${featureLabel(record.feature)}${record.interactive ? '(交互执行)' : ''}`];
|
|
204
|
+
if (!record.result) {
|
|
205
|
+
const timeout = record.timeoutAt ? `,${relative(record.timeoutAt, now)}超时` : '';
|
|
206
|
+
lines.push(` 状态:${PHASE_LABELS[record.phase] || record.phase || '运行中'}(${formatDuration(now - Date.parse(record.phaseSince || now))})${timeout}`);
|
|
207
|
+
} else {
|
|
208
|
+
lines.push(` 结果:${RESULT_LABELS[record.result] || record.result}${record.error?.message ? `:${record.error.code ? `${record.error.code} ` : ''}${record.error.message}` : ''}`);
|
|
209
|
+
}
|
|
210
|
+
if (record.exit) lines.push(` 退出:${record.exit.timedOut ? '超时,' : ''}退出码 ${record.exit.code ?? '—'}${record.exit.signal ? `,信号 ${record.exit.signal}` : ''}`);
|
|
211
|
+
if (record.workAgentCommit) lines.push(` work-agent:${record.workAgentCommit.slice(0, 7)}`);
|
|
212
|
+
if (record.isolation) lines.push(` WORK_AGENT_HOME:${record.isolation === 'per-run' ? '任务独立' : '共享'}`);
|
|
213
|
+
if (record.outputBytes) lines.push(` 输出:${(record.outputBytes / 1024).toFixed(1)} KB`);
|
|
214
|
+
if (record.waitedMs) lines.push(` 开始前等待:${formatDuration(record.waitedMs)}`);
|
|
215
|
+
lines.push(' 过程:');
|
|
216
|
+
const order = ['received', 'accepted', 'waiting', 'preparing', 'running', 'finishing', 'cleaning', 'done'];
|
|
217
|
+
let previous = 0;
|
|
218
|
+
for (const phase of order) {
|
|
219
|
+
if (!at[phase]) continue;
|
|
220
|
+
const time = Date.parse(at[phase]);
|
|
221
|
+
lines.push(` ${formatTime(at[phase])} ${PHASE_LABELS[phase]}${previous ? `(+${formatDuration(time - previous)})` : ''}`);
|
|
222
|
+
previous = time;
|
|
223
|
+
}
|
|
224
|
+
return lines;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** `paths`: [{ label, path, note, free, check }] → aligned lines. */
|
|
228
|
+
export function pathsLines(rows) {
|
|
229
|
+
const width = Math.max(...rows.map((row) => displayWidth(row.label))) + 2;
|
|
230
|
+
return rows.map((row) => {
|
|
231
|
+
const extras = [row.note, row.free ? `可用 ${gigabytes(row.free)}` : '', row.check].filter(Boolean).join(' · ');
|
|
232
|
+
return `${padDisplay(row.label, width)}${row.path || '—'}${extras ? ` (${extras})` : ''}`;
|
|
233
|
+
});
|
|
234
|
+
}
|
package/lib/work-agent.mjs
CHANGED
|
@@ -672,10 +672,12 @@ export class WorkAgent {
|
|
|
672
672
|
reject(new Error('程序正在退出'));
|
|
673
673
|
return;
|
|
674
674
|
}
|
|
675
|
+
// Line by line to `say`: the program's log, and the terminal that asked
|
|
676
|
+
// (directly, or through the control interface).
|
|
675
677
|
const child = spawn('python3', ['-I', script, ...args], {
|
|
676
678
|
cwd: this.paths.repoDir,
|
|
677
679
|
detached: true,
|
|
678
|
-
stdio: ['ignore', 'inherit', 'inherit'],
|
|
680
|
+
stdio: say ? ['ignore', 'pipe', 'pipe'] : ['ignore', 'inherit', 'inherit'],
|
|
679
681
|
env: {
|
|
680
682
|
...gitEnv(this.env),
|
|
681
683
|
WORK_AGENT_HOME: this.paths.workAgentHome,
|
|
@@ -686,6 +688,20 @@ export class WorkAgent {
|
|
|
686
688
|
},
|
|
687
689
|
});
|
|
688
690
|
this.child = child;
|
|
691
|
+
if (say) {
|
|
692
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
693
|
+
let rest = '';
|
|
694
|
+
stream.setEncoding('utf8');
|
|
695
|
+
stream.on('data', (text) => {
|
|
696
|
+
const parts = (rest + text).split(/\r?\n|\r/);
|
|
697
|
+
rest = parts.pop();
|
|
698
|
+
for (const line of parts) if (line.trim()) say(line);
|
|
699
|
+
});
|
|
700
|
+
stream.on('end', () => {
|
|
701
|
+
if (rest.trim()) say(rest);
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
}
|
|
689
705
|
const timer = setTimeout(() => {
|
|
690
706
|
say?.(`已超过 ${Math.round(timeoutMs / 60_000)} 分钟,正在停止`);
|
|
691
707
|
killGroup(child, 'SIGTERM');
|