@online-tools/work-agent-runner 0.0.0-stage → 0.0.1-alpha-5

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/jobs.mjs ADDED
@@ -0,0 +1,505 @@
1
+ // Running website jobs on this machine.
2
+ //
3
+ // A job carries data only (task text, model, credentials, timeout, Skill
4
+ // version); the command line, environment, tool allowlist and sandbox
5
+ // settings are built here. Per job:
6
+ // validate → accept → sync Skills → run directory → claude (own process
7
+ // group, sandboxed) → stream output (ordered batches, retried) → exit →
8
+ // delete the run directory.
9
+ // Logs name the run, feature, duration and exit code — never the API key,
10
+ // GITCODE_CRED, the machine token or proxy credentials.
11
+
12
+ import { spawn } from 'node:child_process';
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { StringDecoder } from 'node:string_decoder';
16
+
17
+ import { claudeArgs, claudeEnv } from './claude-cli.mjs';
18
+ import { ApiError } from './http.mjs';
19
+ import {
20
+ caPaths,
21
+ createRunLayout,
22
+ homeReadAllow,
23
+ newRunDir,
24
+ passThroughEnv,
25
+ socketPathProblem,
26
+ writeSandboxSettings,
27
+ } from './sandbox.mjs';
28
+
29
+ export const FEATURE_LABELS = {
30
+ 'pr-desc-issue-gen': 'PR 描述 / Issue',
31
+ 'ascend-code-review': '代码检视(全量)',
32
+ 'code-review-flash': '代码检视(快速)',
33
+ };
34
+
35
+ const RUN_ID = /^(skill|review)_\d+_[0-9a-f]{8}$/;
36
+ const TASK_MAX_BYTES = 64 * 1024;
37
+ const KILL_GRACE_MS = 5000;
38
+ const CLOSE_WAIT_MS = 2000;
39
+
40
+ const BATCH_DELAY_MS = 200;
41
+ const BATCH_BYTES = 64 * 1024;
42
+ const REQUEST_MAX_BYTES = 1024 * 1024;
43
+ const RETRY_MIN_MS = 1000;
44
+ const RETRY_MAX_MS = 10_000;
45
+ const UNDELIVERED_LIMIT_MS = 60_000;
46
+ const BACKLOG_LIMIT_BYTES = 32 * 1024 * 1024;
47
+
48
+ /** '' when the job is acceptable, else the name of the first bad field (design 5.4). */
49
+ export function invalidJobField(job) {
50
+ if (!job || typeof job !== 'object') return 'job';
51
+ if (job.protocol !== 1) return 'protocol';
52
+ if (typeof job.runId !== 'string' || !RUN_ID.test(job.runId)) return 'runId';
53
+ if (!Object.hasOwn(FEATURE_LABELS, job.feature)) return 'feature';
54
+ if (typeof job.task !== 'string' || !job.task || Buffer.byteLength(job.task) > TASK_MAX_BYTES) return 'task';
55
+ if (typeof job.model !== 'string' || job.model.length < 1 || job.model.length > 120 || /[\s/]/.test(job.model)) return 'model';
56
+ try {
57
+ const url = new URL(job.baseUrl);
58
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) return 'baseUrl';
59
+ } catch {
60
+ return 'baseUrl';
61
+ }
62
+ if (typeof job.apiKey !== 'string' || job.apiKey.length < 1 || job.apiKey.length > 512 || /[\r\n]/.test(job.apiKey)) return 'apiKey';
63
+ const env = job.env;
64
+ if (!env || typeof env !== 'object' || Array.isArray(env)) return 'env';
65
+ const keys = Object.keys(env);
66
+ if (keys.length !== 1 || keys[0] !== 'GITCODE_CRED' || typeof env.GITCODE_CRED !== 'string' || env.GITCODE_CRED.length > 512) return 'env';
67
+ if (!Number.isInteger(job.timeoutMs) || job.timeoutMs < 60_000 || job.timeoutMs > 14_400_000) return 'timeoutMs';
68
+ if (job.interactive !== false) return 'interactive';
69
+ if (typeof job.skillsHash !== 'string' || !/^[0-9a-f]{64}$/.test(job.skillsHash)) return 'skillsHash';
70
+ return '';
71
+ }
72
+
73
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
74
+
75
+ function backoff(attempt) {
76
+ return Math.min(RETRY_MAX_MS, RETRY_MIN_MS * 2 ** attempt);
77
+ }
78
+
79
+ /** Cuts `text` to at most `bytes` UTF-8 bytes without splitting a character. */
80
+ function sliceBytes(text, bytes) {
81
+ if (Buffer.byteLength(text) <= bytes) return [text, ''];
82
+ let end = Math.min(text.length, bytes);
83
+ while (end > 0 && Buffer.byteLength(text.slice(0, end)) > bytes) end = Math.floor(end * 0.9);
84
+ // Never split a surrogate pair.
85
+ if (end > 0 && /[\uD800-\uDBFF]/.test(text[end - 1])) end -= 1;
86
+ return [text.slice(0, end), text.slice(end)];
87
+ }
88
+
89
+ /**
90
+ * Sends a job's output in order: one request at a time, numbered from 1, a
91
+ * batch every 200 ms or 64 KB (at most 1 MB). Failures retry the same batch
92
+ * (1–10 s apart). Gives up — and calls onFailure(reason) — when nothing got
93
+ * through for 60 s or 32 MB are waiting; onGone() when the website no longer
94
+ * knows the job (404).
95
+ */
96
+ export class OutputUploader {
97
+ constructor({ client, runId, onGone, onFailure, onFatal }) {
98
+ this.client = client;
99
+ this.url = `/jobs/${encodeURIComponent(runId)}/output`;
100
+ this.onGone = onGone;
101
+ this.onFailure = onFailure;
102
+ this.onFatal = onFatal;
103
+ this.pending = []; // [{ stream, data }]
104
+ this.pendingBytes = 0;
105
+ this.pendingSince = 0;
106
+ this.lastSeq = 0; // last seq acknowledged
107
+ this.dead = false;
108
+ this.pump = null;
109
+ this.timer = null;
110
+ this.idle = [];
111
+ }
112
+
113
+ push(stream, data) {
114
+ if (this.dead || !data) return;
115
+ const last = this.pending.at(-1);
116
+ if (last && last.stream === stream) last.data += data;
117
+ else this.pending.push({ stream, data });
118
+ this.pendingBytes += Buffer.byteLength(data);
119
+ if (!this.pendingSince) this.pendingSince = Date.now();
120
+ if (this.pendingBytes > BACKLOG_LIMIT_BYTES) {
121
+ this.fail('输出积压过多');
122
+ return;
123
+ }
124
+ this.schedule();
125
+ }
126
+
127
+ schedule() {
128
+ if (this.pump || this.dead) return;
129
+ const wait = this.pendingBytes >= BATCH_BYTES ? 0 : Math.max(0, BATCH_DELAY_MS - (Date.now() - this.pendingSince));
130
+ clearTimeout(this.timer);
131
+ this.timer = setTimeout(() => this.start(), wait);
132
+ }
133
+
134
+ start() {
135
+ if (this.pump || this.dead || !this.pending.length) {
136
+ this.settleIdle();
137
+ return;
138
+ }
139
+ this.pump = this.send().finally(() => {
140
+ this.pump = null;
141
+ if (this.pending.length && !this.dead) this.schedule();
142
+ else this.settleIdle();
143
+ });
144
+ }
145
+
146
+ takeBatch() {
147
+ const chunks = [];
148
+ let budget = REQUEST_MAX_BYTES;
149
+ while (this.pending.length && budget > 0) {
150
+ const head = this.pending[0];
151
+ const [part, rest] = sliceBytes(head.data, budget);
152
+ if (!part) break;
153
+ chunks.push({ stream: head.stream, data: part });
154
+ budget -= Buffer.byteLength(part);
155
+ if (rest) head.data = rest;
156
+ else this.pending.shift();
157
+ }
158
+ const bytes = chunks.reduce((sum, chunk) => sum + Buffer.byteLength(chunk.data), 0);
159
+ this.pendingBytes -= bytes;
160
+ this.pendingSince = this.pending.length ? Date.now() : 0;
161
+ return chunks;
162
+ }
163
+
164
+ async send() {
165
+ const seq = this.lastSeq + 1;
166
+ const chunks = this.takeBatch();
167
+ const firstTry = Date.now();
168
+ for (let attempt = 0; !this.dead; attempt += 1) {
169
+ try {
170
+ const reply = await this.client.request('POST', this.url, { seq, chunks });
171
+ this.lastSeq = Math.max(seq, Number(reply?.ackSeq) || seq);
172
+ return;
173
+ } catch (error) {
174
+ if (error instanceof ApiError) {
175
+ if (error.status === 404) {
176
+ this.dead = true;
177
+ this.onGone();
178
+ return;
179
+ }
180
+ if (error.status === 401 || (error.status === 403 && error.code === 'machine_blocked')) {
181
+ this.dead = true;
182
+ this.onFatal(error);
183
+ return;
184
+ }
185
+ if (error.status === 409 && error.code === 'seq_gap') {
186
+ // The website already has this batch (a reply got lost): carry on.
187
+ if (Number(error.body?.expected) === seq + 1) {
188
+ this.lastSeq = seq;
189
+ return;
190
+ }
191
+ this.fail('输出序号与网站不一致');
192
+ return;
193
+ }
194
+ if (error.status === 409 && error.code === 'machine_unknown') {
195
+ this.dead = true;
196
+ this.onGone();
197
+ return;
198
+ }
199
+ }
200
+ if (Date.now() - firstTry > UNDELIVERED_LIMIT_MS) {
201
+ this.fail('输出 60 秒无法送达');
202
+ return;
203
+ }
204
+ await sleep(error?.retryAfterMs || backoff(attempt));
205
+ }
206
+ }
207
+ }
208
+
209
+ fail(reason) {
210
+ if (this.dead) return;
211
+ this.dead = true;
212
+ this.pending = [];
213
+ this.pendingBytes = 0;
214
+ clearTimeout(this.timer);
215
+ this.onFailure(reason);
216
+ this.settleIdle();
217
+ }
218
+
219
+ settleIdle() {
220
+ if (this.pump || (this.pending.length && !this.dead)) return;
221
+ for (const resolve of this.idle.splice(0)) resolve();
222
+ }
223
+
224
+ /** Resolves once everything pushed so far was acknowledged (or the uploader gave up). */
225
+ drain() {
226
+ clearTimeout(this.timer);
227
+ if (!this.pump && this.pending.length && !this.dead) this.start();
228
+ return new Promise((resolve) => {
229
+ this.idle.push(resolve);
230
+ this.settleIdle();
231
+ });
232
+ }
233
+ }
234
+
235
+ function killGroup(pid, signal) {
236
+ if (!pid) return;
237
+ try {
238
+ process.kill(-pid, signal);
239
+ } catch {
240
+ // Gone already.
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Holds the jobs running on this machine. `client`: http.mjs client;
246
+ * `skills`: SkillCache; `onFatal(error)`: the token or machine is no longer
247
+ * accepted (stop everything).
248
+ */
249
+ export class JobManager {
250
+ constructor({ client, skills, workRoot, claudePath, realHome, env = process.env, platform = process.platform, log, onFatal = () => {} }) {
251
+ this.client = client;
252
+ this.skills = skills;
253
+ this.runsDir = path.join(workRoot, 'runs');
254
+ this.claudePath = claudePath;
255
+ this.realHome = realHome;
256
+ this.env = env;
257
+ this.platform = platform;
258
+ this.log = log;
259
+ this.onFatal = onFatal;
260
+ this.jobs = new Map(); // runId → entry
261
+ this.closed = false;
262
+ fs.mkdirSync(this.runsDir, { recursive: true, mode: 0o700 });
263
+ }
264
+
265
+ runningIds() {
266
+ return [...this.jobs.keys()];
267
+ }
268
+
269
+ /** A `job` event from the control channel. Repeats of a running job are ignored. */
270
+ handle(job) {
271
+ if (this.closed) return;
272
+ const runId = typeof job?.runId === 'string' && job.runId.length <= 100 ? job.runId : '';
273
+ if (!runId || this.jobs.has(runId)) return;
274
+ const entry = { runId, job, child: null, cancelled: false, timedOut: false, failure: '', gone: false, done: null };
275
+ this.jobs.set(runId, entry);
276
+ entry.done = this.run(entry)
277
+ .catch((error) => this.log.error(`任务 ${runId} 异常:${error?.message || error}`))
278
+ .finally(() => this.jobs.delete(runId));
279
+ }
280
+
281
+ /** Stops a job (website cancel, heartbeat reconciliation). */
282
+ cancel(runId) {
283
+ const entry = this.jobs.get(runId);
284
+ if (!entry || entry.cancelled) return;
285
+ entry.cancelled = true;
286
+ this.log.info(`任务 ${runId} 被取消`);
287
+ this.terminate(entry);
288
+ }
289
+
290
+ terminate(entry) {
291
+ const pid = entry.child?.pid;
292
+ if (!pid || entry.killing) return;
293
+ entry.killing = true;
294
+ killGroup(pid, 'SIGTERM');
295
+ setTimeout(() => killGroup(pid, 'SIGKILL'), KILL_GRACE_MS).unref();
296
+ }
297
+
298
+ /** Stops every job and waits (≤ timeoutMs) for their exits to be reported. */
299
+ async stopAll(timeoutMs = 5000) {
300
+ this.closed = true;
301
+ const entries = [...this.jobs.values()];
302
+ for (const entry of entries) {
303
+ entry.cancelled = true;
304
+ this.terminate(entry);
305
+ }
306
+ await Promise.race([
307
+ Promise.allSettled(entries.map((entry) => entry.done)),
308
+ sleep(timeoutMs),
309
+ ]);
310
+ }
311
+
312
+ async accept(entry) {
313
+ const url = `/jobs/${encodeURIComponent(entry.runId)}/accept`;
314
+ for (let attempt = 0; attempt < 4; attempt += 1) {
315
+ try {
316
+ await this.client.request('POST', url, {});
317
+ return true;
318
+ } catch (error) {
319
+ if (error instanceof ApiError && error.status === 404) return false;
320
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
321
+ this.onFatal(error);
322
+ return false;
323
+ }
324
+ await sleep(1000 * (attempt + 1));
325
+ }
326
+ }
327
+ return false; // the website gives up after 10 s anyway
328
+ }
329
+
330
+ async reportExit(entry, { seq = 0, code = null, signal = null, timedOut = false, error = '' }) {
331
+ const url = `/jobs/${encodeURIComponent(entry.runId)}/exit`;
332
+ const body = { seq, code, signal, timedOut, error: String(error || '').slice(0, 500) };
333
+ for (let attempt = 0; attempt < 6; attempt += 1) {
334
+ try {
335
+ await this.client.request('POST', url, body);
336
+ return;
337
+ } catch (failure) {
338
+ if (failure instanceof ApiError) {
339
+ if (failure.status === 404) return;
340
+ if (failure.status === 401 || failure.status === 403) return;
341
+ if (failure.status === 409 && failure.code === 'seq_gap') {
342
+ this.log.warn(`任务 ${entry.runId} 的输出与网站不一致,无法补齐`);
343
+ return;
344
+ }
345
+ }
346
+ await sleep(failure?.retryAfterMs || backoff(attempt));
347
+ }
348
+ }
349
+ }
350
+
351
+ async run(entry) {
352
+ const { runId, job } = entry;
353
+ const started = Date.now();
354
+ const invalid = invalidJobField(job);
355
+ // Acknowledge first so the website does not wait for the accept timeout.
356
+ if (!(await this.accept(entry))) {
357
+ this.log.warn(`任务 ${runId} 已在网站上失效,未执行`);
358
+ return;
359
+ }
360
+ if (invalid) {
361
+ this.log.warn(`任务 ${runId} 参数不合法(${invalid}),未执行`);
362
+ await this.reportExit(entry, { error: `任务参数不合法:${invalid}` });
363
+ return;
364
+ }
365
+ const label = FEATURE_LABELS[job.feature];
366
+ this.log.info(`开始任务 ${runId}(${label})`);
367
+
368
+ let files;
369
+ try {
370
+ files = await this.skills.ensure(job.skillsHash);
371
+ } catch (error) {
372
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) this.onFatal(error);
373
+ await this.reportExit(entry, { error: `同步 Skill 失败:${error?.message || error}` });
374
+ return;
375
+ }
376
+ if (entry.cancelled) {
377
+ await this.reportExit(entry, { signal: 'SIGTERM' });
378
+ return;
379
+ }
380
+
381
+ // A short directory name, not the run id: see socketPathProblem().
382
+ let runDir = '';
383
+ let layout;
384
+ try {
385
+ runDir = newRunDir(this.runsDir, 'r');
386
+ layout = createRunLayout(runDir);
387
+ const tooLong = socketPathProblem(layout.tmpDir, this.platform);
388
+ if (tooLong) throw new Error(tooLong);
389
+ this.skills.copyInto(job.skillsHash, files, layout.skillsDir, layout.workAgentDir);
390
+ writeSandboxSettings(layout.settingsFile, {
391
+ workDir: fs.realpathSync(layout.workDir),
392
+ realHome: this.realHome,
393
+ readAllow: homeReadAllow({ realHome: this.realHome, pathEnv: this.env.PATH || '', caPaths: caPaths(this.env) }),
394
+ });
395
+ } catch (error) {
396
+ if (runDir) fs.rmSync(runDir, { recursive: true, force: true });
397
+ await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
398
+ return;
399
+ }
400
+
401
+ try {
402
+ const result = await this.spawnClaude(entry, layout);
403
+ if (!entry.gone) {
404
+ await this.reportExit(entry, {
405
+ seq: entry.uploader.lastSeq,
406
+ code: result.code,
407
+ signal: result.signal,
408
+ timedOut: entry.timedOut,
409
+ error: result.error || entry.failure,
410
+ });
411
+ }
412
+ const seconds = Math.round((Date.now() - started) / 1000);
413
+ const outcome = entry.timedOut ? '超时' : entry.cancelled ? '已取消' : result.error ? result.error : `退出码 ${result.code ?? result.signal}`;
414
+ this.log.info(`任务 ${runId} 结束(${label}):${outcome},用时 ${seconds} 秒`);
415
+ } finally {
416
+ fs.rmSync(runDir, { recursive: true, force: true });
417
+ }
418
+ }
419
+
420
+ spawnClaude(entry, layout) {
421
+ const { job } = entry;
422
+ return new Promise((resolve) => {
423
+ if (!this.claudePath) {
424
+ entry.uploader = { lastSeq: 0 };
425
+ resolve({ code: null, signal: null, error: '无法启动 claude:未安装' });
426
+ return;
427
+ }
428
+ let child;
429
+ try {
430
+ child = spawn(this.claudePath, claudeArgs({ settingsFile: layout.settingsFile }), {
431
+ cwd: layout.workDir,
432
+ detached: true,
433
+ stdio: ['pipe', 'pipe', 'pipe'],
434
+ env: claudeEnv({
435
+ path: this.env.PATH,
436
+ runDir: layout.runDir,
437
+ homeDir: layout.homeDir,
438
+ configDir: layout.configDir,
439
+ tmpDir: layout.tmpDir,
440
+ baseUrl: job.baseUrl,
441
+ apiKey: job.apiKey,
442
+ model: job.model,
443
+ extra: { ...passThroughEnv(this.env, this.platform), GITCODE_CRED: job.env.GITCODE_CRED },
444
+ }),
445
+ });
446
+ } catch (error) {
447
+ entry.uploader = { lastSeq: 0 };
448
+ resolve({ code: null, signal: null, error: `无法启动 claude:${error.code || error.message}` });
449
+ return;
450
+ }
451
+ entry.child = child;
452
+ const uploader = new OutputUploader({
453
+ client: this.client,
454
+ runId: entry.runId,
455
+ onGone: () => {
456
+ entry.gone = true;
457
+ this.terminate(entry);
458
+ },
459
+ onFailure: (reason) => {
460
+ entry.failure = reason;
461
+ this.terminate(entry);
462
+ },
463
+ onFatal: (error) => {
464
+ this.terminate(entry);
465
+ this.onFatal(error);
466
+ },
467
+ });
468
+ entry.uploader = uploader;
469
+ for (const name of ['stdout', 'stderr']) {
470
+ const decoder = new StringDecoder('utf8');
471
+ child[name].on('data', (chunk) => uploader.push(name, decoder.write(chunk)));
472
+ child[name].on('end', () => uploader.push(name, decoder.end()));
473
+ }
474
+ const timeout = setTimeout(() => {
475
+ entry.timedOut = true;
476
+ this.terminate(entry);
477
+ }, job.timeoutMs);
478
+ timeout.unref();
479
+ if (entry.cancelled) this.terminate(entry);
480
+ let closeWait = null;
481
+ let finished = false;
482
+ const finish = async (result) => {
483
+ if (finished) return;
484
+ finished = true;
485
+ clearTimeout(timeout);
486
+ clearTimeout(closeWait);
487
+ killGroup(child.pid, 'SIGKILL'); // whatever the job left behind
488
+ await uploader.drain();
489
+ resolve(result);
490
+ };
491
+ child.once('exit', () => {
492
+ // Background descendants may keep the pipes open: end them shortly after.
493
+ closeWait = setTimeout(() => killGroup(child.pid, 'SIGKILL'), CLOSE_WAIT_MS);
494
+ closeWait.unref();
495
+ });
496
+ // Spawn failures (ENOENT, EACCES) have no pid; 'close' may or may not follow.
497
+ child.once('error', (error) => {
498
+ if (!child.pid) finish({ code: null, signal: null, error: `无法启动 claude:${error.code || error.message}` });
499
+ });
500
+ child.once('close', (code, signal) => finish({ code, signal, error: '' }));
501
+ child.stdin.on('error', () => {});
502
+ child.stdin.end(job.task);
503
+ });
504
+ }
505
+ }
package/lib/lock.mjs ADDED
@@ -0,0 +1,70 @@
1
+ // One running instance per user: run.lock holds the owner's pid. A lock
2
+ // whose pid is gone (or now belongs to some other program) is taken over.
3
+
4
+ import { spawnSync } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+
7
+ export class LockedError extends Error {
8
+ constructor(pid) {
9
+ super(`已有实例在运行(pid ${pid},可能是后台服务,见 work-agent-runner service status)`);
10
+ this.pid = pid;
11
+ }
12
+ }
13
+
14
+ /**
15
+ * True when `pid` is a live process whose command line names `program` — this
16
+ * program, or LEGACY_NAME for the old one (unknown commands count as live).
17
+ */
18
+ export function isRunnerAlive(pid, program = 'work-agent-runner') {
19
+ if (!Number.isInteger(pid) || pid <= 0) return false;
20
+ try {
21
+ process.kill(pid, 0);
22
+ } catch (error) {
23
+ if (error.code !== 'EPERM') return false;
24
+ }
25
+ let command = '';
26
+ if (process.platform === 'linux') {
27
+ try {
28
+ command = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
29
+ } catch {
30
+ return true;
31
+ }
32
+ } else {
33
+ const result = spawnSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', timeout: 5000 });
34
+ if (result.status !== 0) return true;
35
+ command = result.stdout;
36
+ }
37
+ // A reused pid that runs something else is not our instance.
38
+ return command.includes(program);
39
+ }
40
+
41
+ /** The pid written in a lock file (NaN when there is none). */
42
+ export function lockHolder(file) {
43
+ try {
44
+ return Number(fs.readFileSync(file, 'utf8').trim());
45
+ } catch {
46
+ return Number.NaN;
47
+ }
48
+ }
49
+
50
+ /** Takes the lock or throws LockedError. Returns { release() }. */
51
+ export function acquireLock(file, { pid = process.pid, isAlive = isRunnerAlive } = {}) {
52
+ const release = () => {
53
+ if (lockHolder(file) === pid) fs.rmSync(file, { force: true });
54
+ };
55
+ for (let attempt = 0; attempt < 5; attempt += 1) {
56
+ try {
57
+ const fd = fs.openSync(file, 'wx', 0o600);
58
+ fs.writeSync(fd, String(pid));
59
+ fs.closeSync(fd);
60
+ return { release };
61
+ } catch (error) {
62
+ if (error.code !== 'EEXIST') throw error;
63
+ }
64
+ const holder = lockHolder(file);
65
+ if (holder === pid) return { release };
66
+ if (Number.isInteger(holder) && holder > 0 && isAlive(holder)) throw new LockedError(holder);
67
+ fs.rmSync(file, { force: true }); // left behind by a dead instance
68
+ }
69
+ throw new Error(`无法获取运行锁 ${file}`);
70
+ }
package/lib/log.mjs ADDED
@@ -0,0 +1,22 @@
1
+ // Timestamped Chinese log lines on stdout / stderr (systemd puts them in the
2
+ // journal, launchd in ~/Library/Logs). Never log a token, an API key,
3
+ // GITCODE_CRED or a proxy password: use redactUrl() for anything URL-like.
4
+
5
+ function stamp(date = new Date()) {
6
+ const pad = (value) => String(value).padStart(2, '0');
7
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
8
+ }
9
+
10
+ export function createLogger({ out = process.stdout, err = process.stderr } = {}) {
11
+ const write = (stream, prefix, message) => stream.write(`${stamp()} ${prefix}${message}\n`);
12
+ return {
13
+ info: (message) => write(out, '', message),
14
+ warn: (message) => write(err, '警告:', message),
15
+ error: (message) => write(err, '错误:', message),
16
+ };
17
+ }
18
+
19
+ /** Masks the account part of URLs (proxy addresses may carry user:password). */
20
+ export function redactUrl(value) {
21
+ return String(value ?? '').replace(/(\/\/)[^/@\s]*@/g, '$1***@');
22
+ }