@online-tools/work-agent-runner 0.1.0-alpha-1 → 0.1.0-alpha-2

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.
@@ -0,0 +1,119 @@
1
+ // `setup` as resumable steps (docs/remediation-and-install-plan.md 4.3, design
2
+ // 10.2): what each step came to, kept in state/setup.json, so a second run
3
+ // skips what is done or was declined and starts again where something failed;
4
+ // and the setup log (logs/setup-<time>.log, every line redacted).
5
+ //
6
+ // Only node: built-ins and files in this directory.
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ import { readJsonFile, writeJsonAtomic } from './fs-safe.mjs';
12
+ import { redact } from './log.mjs';
13
+ import { displayWidth } from './views.mjs';
14
+
15
+ export const SETUP_SCHEMA = 1;
16
+ export const SETUP_STEPS = [
17
+ ['precheck', '预检'],
18
+ ['token', '接入令牌与机器名称'],
19
+ ['deps', '系统依赖'],
20
+ ['claude', 'Claude Code'],
21
+ ['prereq', '沙箱前提'],
22
+ ['repo', 'work-agent 仓库'],
23
+ ['sandbox', '沙箱实测'],
24
+ ['pool', '知识仓(可选)'],
25
+ ['service', '后台服务(可选)'],
26
+ ];
27
+ const STATUSES = new Set(['pending', 'done', 'skipped', 'failed']);
28
+ const LOGS_KEPT = 10;
29
+
30
+ /** state/setup.json: { schema, version, updatedAt, steps: { [id]: { status, at, detail, error } } }. */
31
+ export class SetupState {
32
+ constructor(file, { version = '', now = () => Date.now() } = {}) {
33
+ this.file = file;
34
+ this.version = version;
35
+ this.now = now;
36
+ const saved = readJsonFile(file);
37
+ this.steps = {};
38
+ if (saved?.schema === SETUP_SCHEMA && saved.steps && typeof saved.steps === 'object') {
39
+ for (const [id] of SETUP_STEPS) {
40
+ const step = saved.steps[id];
41
+ if (step && STATUSES.has(step.status)) this.steps[id] = { status: step.status, at: String(step.at || ''), detail: String(step.detail || ''), error: step.error || null };
42
+ }
43
+ }
44
+ }
45
+
46
+ status(id) {
47
+ return this.steps[id]?.status || 'pending';
48
+ }
49
+
50
+ /** Records a step's outcome at once (a Ctrl+C later keeps what was done). */
51
+ set(id, status, { detail = '', error = null } = {}) {
52
+ this.steps[id] = { status, at: new Date(this.now()).toISOString(), detail: String(detail || ''), error };
53
+ this.save();
54
+ }
55
+
56
+ reset() {
57
+ this.steps = {};
58
+ this.save();
59
+ }
60
+
61
+ /** Every step done or declined: the first run is over. */
62
+ complete() {
63
+ return SETUP_STEPS.every(([id]) => ['done', 'skipped'].includes(this.status(id)));
64
+ }
65
+
66
+ save() {
67
+ try {
68
+ fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
69
+ writeJsonAtomic(this.file, { schema: SETUP_SCHEMA, version: this.version, updatedAt: new Date(this.now()).toISOString(), steps: this.steps });
70
+ } catch {
71
+ // A record only: never a reason to stop the setup.
72
+ }
73
+ }
74
+
75
+ toJSON() {
76
+ return Object.fromEntries(SETUP_STEPS.map(([id]) => [id, this.steps[id] || { status: 'pending' }]));
77
+ }
78
+ }
79
+
80
+ /** "[3/9] 系统依赖 .............. ✓ 完成(41 秒)": the step's title dotted out to a fixed column. */
81
+ export function stepLine(index, title, result = '') {
82
+ const head = `[${index + 1}/${SETUP_STEPS.length}] ${title} `;
83
+ const dots = '.'.repeat(Math.max(3, 34 - displayWidth(head)));
84
+ return `${head}${dots} ${result}`.trimEnd();
85
+ }
86
+
87
+ /**
88
+ * A new setup log, logs/setup-<yyyymmdd-hhmmss>.log (0600); the oldest beyond
89
+ * the last ten are deleted. Returns { file, write(line) } — every line is
90
+ * redacted (a token pasted at a prompt never reaches it).
91
+ */
92
+ export function openSetupLog(logsDir, { now = new Date() } = {}) {
93
+ const pad = (value) => String(value).padStart(2, '0');
94
+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
95
+ let file = '';
96
+ try {
97
+ fs.mkdirSync(logsDir, { recursive: true, mode: 0o700 });
98
+ file = path.join(logsDir, `setup-${stamp}.log`);
99
+ fs.writeFileSync(file, '', { mode: 0o600, flag: 'a' });
100
+ const logs = fs
101
+ .readdirSync(logsDir)
102
+ .filter((name) => /^setup-\d{8}-\d{6}\.log$/.test(name))
103
+ .sort();
104
+ for (const name of logs.slice(0, Math.max(0, logs.length - LOGS_KEPT))) fs.rmSync(path.join(logsDir, name), { force: true });
105
+ } catch {
106
+ file = '';
107
+ }
108
+ return {
109
+ file,
110
+ write(line) {
111
+ if (!file) return;
112
+ try {
113
+ fs.appendFileSync(file, `${redact(line)}\n`);
114
+ } catch {
115
+ // The log must never stop the setup.
116
+ }
117
+ },
118
+ };
119
+ }
package/lib/setup.mjs CHANGED
@@ -42,6 +42,8 @@ export function npmPrefixWritable(prefix) {
42
42
  * manager 'apt' | … | 'brew' | ''
43
43
  * isRoot, sudo absolute path of sudo or ''
44
44
  * npm, npmWritable absolute path of npm, and whether its global dir is writable
45
+ * managedClaude claude is installed by this program (lib/claude-install.mjs),
46
+ * not with npm: it is left out of this plan
45
47
  * Returns { commands: [[file, ...args]], manual: [[...]], missing: [names], ignored: [names], notes: [text] }.
46
48
  */
47
49
  export function planSetup({
@@ -56,6 +58,7 @@ export function planSetup({
56
58
  sudo = '',
57
59
  npm = '',
58
60
  npmWritable = false,
61
+ managedClaude = false,
59
62
  }) {
60
63
  const ignored = requiredTools.filter((name) => !SKILL_TOOLS.includes(name));
61
64
  const wanted = SKILL_TOOLS.filter((name) => requiredTools.includes(name) || extraTools.includes(name));
@@ -92,7 +95,7 @@ export function planSetup({
92
95
  }
93
96
  }
94
97
 
95
- const needsClaude = !claudeVersion || (minClaudeVersion && compareVersions(claudeVersion, minClaudeVersion) < 0);
98
+ const needsClaude = !managedClaude && (!claudeVersion || (minClaudeVersion && compareVersions(claudeVersion, minClaudeVersion) < 0));
96
99
  if (needsClaude) {
97
100
  if (!npm) {
98
101
  notes.push('没有找到 npm,无法安装 claude');
@@ -0,0 +1,122 @@
1
+ // `work-agent-runner uninstall` (design 3.21): what goes and what stays.
2
+ // Only what is this program's own goes — the work root's runs/ archive/
3
+ // trash/ and marker (the directory itself only when the program made it and
4
+ // it is empty), a marked clone, the program home (all of it with --purge,
5
+ // else all but config.json); work-agent's home and the knowledge pool are
6
+ // the user's and stay, with where they are and how big.
7
+ //
8
+ // Only node: built-ins and files in this directory.
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ import { WORK_ROOT_MARKER, isInside } from './config.mjs';
14
+ import { readJsonFile, removeTree } from './fs-safe.mjs';
15
+ import { CLONE_MARKER } from './work-agent.mjs';
16
+
17
+ function exists(target) {
18
+ try {
19
+ fs.lstatSync(target);
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ /** Bytes under `dir` (regular files, symlinks not followed); 0 when it is not there. */
27
+ export function treeSize(dir) {
28
+ let total = 0;
29
+ const walk = (target) => {
30
+ let stat;
31
+ try {
32
+ stat = fs.lstatSync(target);
33
+ } catch {
34
+ return;
35
+ }
36
+ if (stat.isFile()) total += stat.size;
37
+ else if (stat.isDirectory()) {
38
+ let names = [];
39
+ try {
40
+ names = fs.readdirSync(target);
41
+ } catch {
42
+ return;
43
+ }
44
+ for (const name of names) walk(path.join(target, name));
45
+ }
46
+ };
47
+ walk(dir);
48
+ return total;
49
+ }
50
+
51
+ /**
52
+ * { remove: [{ path, what }], removeIfEmpty: [{ path, what }], keep: [{ path, what }] }.
53
+ * `paths` (configPaths + withRepoPaths), `workRoot` (the one in use), `purge`.
54
+ */
55
+ export function uninstallPlan({ paths, workRoot, purge = false }) {
56
+ const remove = [];
57
+ const removeIfEmpty = [];
58
+ const keep = [];
59
+ const home = path.resolve(paths.baseDir);
60
+ const root = path.resolve(workRoot || home);
61
+ if (root !== home && !isInside(root, home)) {
62
+ for (const name of ['runs', 'archive', 'trash', WORK_ROOT_MARKER]) {
63
+ const target = path.join(root, name);
64
+ if (exists(target)) remove.push({ path: target, what: name === WORK_ROOT_MARKER ? '工作目录的标记' : `任务目录 ${name}/` });
65
+ }
66
+ const marker = readJsonFile(path.join(root, WORK_ROOT_MARKER));
67
+ if (marker?.createdByProgram === true) removeIfEmpty.push({ path: root, what: '工作目录(程序建的,空了就删除)' });
68
+ else keep.push({ path: root, what: '工作目录(原来就有,只删除了程序放进去的东西)' });
69
+ }
70
+ const clone = path.resolve(paths.repoDir);
71
+ if (!isInside(clone, home) && exists(clone)) {
72
+ if (exists(path.join(clone, '.git', CLONE_MARKER))) remove.push({ path: clone, what: 'work-agent 仓库的克隆' });
73
+ else keep.push({ path: clone, what: 'work-agent 仓库(不是本程序创建的,不动)' });
74
+ }
75
+ if (purge) remove.push({ path: home, what: '程序目录(全部,含 config.json)' });
76
+ else {
77
+ let names = [];
78
+ try {
79
+ names = fs.readdirSync(home);
80
+ } catch {
81
+ names = [];
82
+ }
83
+ for (const name of names) {
84
+ if (name === 'config.json') continue;
85
+ remove.push({ path: path.join(home, name), what: `程序目录里的 ${name}` });
86
+ }
87
+ if (exists(paths.configFile)) keep.push({ path: paths.configFile, what: '配置(接入令牌和机器标识;重装后沿用同一台机器,不想要了就删除它)' });
88
+ }
89
+ for (const [target, what] of [
90
+ [paths.workAgentHome, 'work-agent 的家(你手工使用 work-agent 时也用它)'],
91
+ [paths.poolDir, '知识仓'],
92
+ ]) {
93
+ if (exists(target) && !isInside(path.resolve(target), home)) keep.push({ path: target, what, size: treeSize(target) });
94
+ }
95
+ return { remove, removeIfEmpty, keep };
96
+ }
97
+
98
+ /** Deletes what the plan says (removeTree: no symlink is followed); { removed, failed }. */
99
+ export function performUninstall(plan) {
100
+ const removed = [];
101
+ const failed = [];
102
+ for (const item of plan.remove) {
103
+ const outcome = removeTree(item.path);
104
+ (outcome.removed ? removed : failed).push(item);
105
+ }
106
+ for (const item of plan.removeIfEmpty) {
107
+ let names = null;
108
+ try {
109
+ names = fs.readdirSync(item.path);
110
+ } catch {
111
+ continue;
112
+ }
113
+ if (names.length) continue;
114
+ try {
115
+ fs.rmdirSync(item.path);
116
+ removed.push(item);
117
+ } catch {
118
+ failed.push(item);
119
+ }
120
+ }
121
+ return { removed, failed };
122
+ }
package/lib/views.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
  //
5
5
  // Only node: built-ins and files in this directory.
6
6
 
7
+ import { ALL_FEATURES, FEATURE_NAMES } from './check.mjs';
7
8
  import { FEATURE_LABELS } from './jobs.mjs';
8
9
 
9
10
  const GB = 1024 ** 3;
@@ -34,6 +35,7 @@ const REASON_LABELS = {
34
35
  disk_low: '工作目录磁盘空间不足',
35
36
  unconfirmed: '网页上还没有确认这台机器',
36
37
  outdated: '程序版本过低',
38
+ upgrade: '正在升级程序',
37
39
  };
38
40
 
39
41
  // Characters a terminal draws two columns wide (CJK, fullwidth forms): columns
@@ -224,6 +226,30 @@ export function jobDetailLines(record, { now = Date.now() } = {}) {
224
226
  return lines;
225
227
  }
226
228
 
229
+ const CHECK_MARKS = { ok: '✓', warn: '⚠', fail: '✗', info: '·', skip: '-' };
230
+
231
+ /** `check`: the report of lib/check.mjs, group by group, then the verdict. */
232
+ export function checkLines(report) {
233
+ const lines = [];
234
+ const width = Math.max(0, ...report.groups.flatMap((group) => group.items.map((entry) => displayWidth(entry.title)))) + 2;
235
+ const indent = ' '.repeat(4 + width);
236
+ for (const group of report.groups) {
237
+ lines.push(group.title);
238
+ for (const entry of group.items) {
239
+ lines.push(` ${CHECK_MARKS[entry.status] || '·'} ${padDisplay(entry.title, width)}${entry.detail}${entry.code ? `(${entry.code})` : ''}`);
240
+ for (const note of entry.notes || []) lines.push(`${indent}${note}`);
241
+ if (entry.status === 'fail' && entry.affects?.length) {
242
+ const all = ALL_FEATURES.every((feature) => entry.affects.includes(feature));
243
+ lines.push(`${indent}影响:${all ? '所有功能' : entry.affects.map((feature) => FEATURE_NAMES[feature] || feature).join('、')}`);
244
+ }
245
+ if (entry.status !== 'ok' && entry.fix) lines.push(`${indent}处理:${entry.fix}`);
246
+ if (entry.status !== 'ok' && entry.docs) lines.push(`${indent}说明:${entry.docs}`);
247
+ }
248
+ }
249
+ lines.push('', `结论:${report.summary}`);
250
+ return lines;
251
+ }
252
+
227
253
  /** `paths`: [{ label, path, note, free, check }] → aligned lines. */
228
254
  export function pathsLines(rows) {
229
255
  const width = Math.max(...rows.map((row) => displayWidth(row.label))) + 2;
@@ -116,8 +116,10 @@ function gitEnv(env) {
116
116
  // repos into the Skill tree (work-agent has submodules inside .claude/skills).
117
117
  const GIT_CONFIG = ['-c', 'credential.helper=', '-c', 'submodule.recurse=false'];
118
118
 
119
+ /** Why git failed, from its stderr: the first fatal: / error: line (git's last line is often advice). */
119
120
  function lastLine(text) {
120
- return String(text || '').trim().split('\n').filter(Boolean).pop() || '';
121
+ const lines = String(text || '').trim().split('\n').map((line) => line.trim()).filter(Boolean);
122
+ return (lines.find((line) => /^(fatal|error):/i.test(line)) || lines.pop() || '').replace(/^(fatal|error):\s*/i, '');
121
123
  }
122
124
 
123
125
  /** Quick local queries (rev-parse, log, status): synchronous. */
@@ -288,14 +290,17 @@ export class WorkAgent {
288
290
  * Runs `fn` alone among clone operations: after anything queued here, and
289
291
  * holding work-agent.lock, for which it waits up to `waitMs`.
290
292
  */
291
- withClone(fn, { waitMs = this.lockWaitMs } = {}) {
293
+ withClone(fn, { waitMs = this.lockWaitMs, onWait = null } = {}) {
292
294
  const next = this.cloneQueue.then(async () => {
293
295
  fs.mkdirSync(path.dirname(this.paths.repoLockFile), { recursive: true, mode: 0o700 });
294
296
  let lock;
295
297
  try {
296
298
  lock = await acquireLockWaiting(this.paths.repoLockFile, {
297
299
  timeoutMs: waitMs,
298
- onWait: (pid) => this.note('info', `work-agent 仓库正被另一个进程使用(pid ${pid}),等待它结束……`),
300
+ onWait: (pid) => {
301
+ this.note('info', `work-agent 仓库正被另一个进程使用(pid ${pid}),等待它结束……`);
302
+ onWait?.(pid);
303
+ },
299
304
  });
300
305
  } catch (error) {
301
306
  if (error instanceof LockedError) {
@@ -650,7 +655,7 @@ export class WorkAgent {
650
655
  * for reading and running, not for pushing; so is any symlink that leads out
651
656
  * of the repository. Returns the commit that was copied.
652
657
  */
653
- copyRepoInto(targetDir, targets) {
658
+ copyRepoInto(targetDir, targets, { onWait = null } = {}) {
654
659
  return this.withClone(() => {
655
660
  const state = this.state();
656
661
  if (!state.ok) throw new Error(state.reason);
@@ -660,7 +665,7 @@ export class WorkAgent {
660
665
  });
661
666
  rewriteSkillPaths(path.join(targetDir, SKILLS_SUBDIR), targets);
662
667
  return { commit: state.commit };
663
- });
668
+ }, { onWait });
664
669
  }
665
670
 
666
671
  /** `python3 -I <clone>/scripts/work-agent.py <args>` with the workspace it manages. */
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@online-tools/work-agent-runner",
3
- "version": "0.1.0-alpha-1",
3
+ "version": "0.1.0-alpha-2",
4
4
  "description": "GitCode 在线工具的 Agent 执行机器:在自己的机器上运行 work-agent 的 Skill(PR 描述、代码检视)",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": { "work-agent-runner": "bin/work-agent-runner.cjs" },
8
- "files": ["bin/", "lib/", "README.md", "LICENSE"],
8
+ "files": ["bin/", "lib/", "README.md", "CHANGELOG.md", "LICENSE"],
9
9
  "engines": { "node": ">=10.12.0" },
10
10
  "os": ["linux", "darwin"],
11
11
  "publishConfig": { "access": "public" }