@online-tools/work-agent-runner 0.0.4-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/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
+ }