@yixinkj/ops 0.0.0-stage → 0.1.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.
Files changed (4) hide show
  1. package/README.md +10 -2
  2. package/index.js +1205 -0
  3. package/package.json +21 -4
  4. package/skills.json +23 -0
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @yixinkj/ops
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 译心运营原生 CLI 启动器。按 skills.json 选择业务二进制,下载对应平台整包,校验后启动。
4
+
5
+ ```sh
6
+ npx -y @yixinkj/ops@latest --help
7
+ ```
8
+
9
+ 当前为开发骨架,尚未发布 npm,业务注册表为空;本地可运行 `node index.js --help`。
10
+
11
+ OSS 使用 releases/yixin-ops/,备用发布仓库为 TimWuc/yixin-ops-releases,缓存使用 ~/.yixin-ops。授权公共层仍沿用现有授权服务及 ~/.yixin 配置。
package/index.js ADDED
@@ -0,0 +1,1205 @@
1
+ #!/usr/bin/env node
2
+
3
+ import https from 'node:https';
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { spawn, spawnSync } from 'node:child_process';
9
+ import { createRequire } from 'node:module';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ const require = createRequire(import.meta.url);
13
+ const packageJson = require('./package.json');
14
+ // skills.json 是新增 Skill 的单一事实源(skill 名 → flag → 二进制名)。
15
+ // launcher 在运行期读它来决定下载哪些二进制、按 flag 启动哪个;发布 workflow 读同一份来打包。
16
+ const registry = require('./skills.json');
17
+
18
+ const VERSION = packageJson.version;
19
+ const NPM_CHANNEL = VERSION.includes('-') ? 'beta' : 'latest';
20
+ const RELEASE_REPO = process.env.YIXIN_OPS_RELEASE_REPO || 'TimWuc/yixin-ops-releases';
21
+ const OSS_RELEASE_BASE_URL =
22
+ 'https://yixin-cli-releases-8488540.oss-cn-hangzhou.aliyuncs.com/releases/yixin-ops';
23
+ const CACHE_ROOT = path.join(os.homedir(), '.yixin-ops');
24
+ const VERSIONS_ROOT = path.join(CACHE_ROOT, 'versions');
25
+ const VERSION_ROOT = path.join(VERSIONS_ROOT, `v${VERSION}`);
26
+ const BIN_DIR = path.join(VERSION_ROOT, 'bin');
27
+ const INSTALL_MARKER = path.join(VERSION_ROOT, 'installed.json');
28
+ const RUNS_DIR = path.join(CACHE_ROOT, 'runs');
29
+ const INSTALL_LOCK_STALE_MS = 10 * 60 * 1000;
30
+ const INSTALL_LOCK_WAIT_MS = 3 * 60 * 1000;
31
+ const INSTALL_LOCK_HEARTBEAT_MS = 10 * 1000;
32
+ const RUN_HEARTBEAT_MS = 10 * 1000;
33
+ const RUNTIME_WAIT_DEFAULT_SECONDS = 45;
34
+ const RUNTIME_WAIT_MAX_SECONDS = 60;
35
+ const RUNTIME_STATUS_POLL_MS = 500;
36
+ const TERMINAL_RUN_STATUSES = new Set([
37
+ 'completed',
38
+ 'completed_partial',
39
+ 'failed',
40
+ 'cancelled',
41
+ 'stalled'
42
+ ]);
43
+
44
+ function fail(message) {
45
+ console.error(`[yixin-ops] ${message}`);
46
+ process.exit(1);
47
+ }
48
+
49
+ function isPermissionError(error) {
50
+ const code = String(error?.code || '').toUpperCase();
51
+ const message = String(error?.message || '');
52
+ return (
53
+ code === 'EPERM' ||
54
+ code === 'EACCES' ||
55
+ /\bEPERM\b|\bEACCES\b|permission denied|operation not permitted/i.test(message)
56
+ );
57
+ }
58
+
59
+ function installPermissionHelp() {
60
+ if (process.platform === 'win32') {
61
+ return (
62
+ `\n\n安装二进制失败:无法写入本地二进制缓存目录。\n` +
63
+ `可能是目录权限异常或安全软件拦截。\n\n` +
64
+ `如重试仍失败,请只删除当前版本缓存,不要删除整个 .yixin-ops 目录:\n\n` +
65
+ ` Remove-Item -Recurse -Force "$env:USERPROFILE\\.yixin-ops\\versions\\v${VERSION}"\n` +
66
+ ` Remove-Item -Force "$env:USERPROFILE\\.yixin-ops\\install-v${VERSION}-*.lock"\n\n` +
67
+ `然后重新运行当前命令。`
68
+ );
69
+ }
70
+ if (process.platform === 'darwin') {
71
+ return (
72
+ `\n\n安装二进制失败:无法写入本地二进制缓存目录。\n` +
73
+ `可能是目录权限异常或安全软件拦截。\n\n` +
74
+ `如重试仍失败,请只删除当前版本缓存,不要删除整个 .yixin-ops 目录:\n\n` +
75
+ ` rm -rf "$HOME/.yixin-ops/versions/v${VERSION}"\n` +
76
+ ` rm -f "$HOME/.yixin-ops/install-v${VERSION}-"*.lock\n\n` +
77
+ `然后重新运行当前命令。`
78
+ );
79
+ }
80
+ return '';
81
+ }
82
+
83
+ function withInstallHelp(error) {
84
+ const message = String(error?.message || error);
85
+ if (!isPermissionError(error)) {
86
+ return error;
87
+ }
88
+ const help = installPermissionHelp();
89
+ if (!help) {
90
+ return error;
91
+ }
92
+ return new Error(`${message}${help}`);
93
+ }
94
+
95
+ function binaryName(base, platform) {
96
+ return `${base}-${platform.id}${platform.exe || ''}`;
97
+ }
98
+
99
+ function localRuntimeDir() {
100
+ const configured = process.env.YIXIN_OPS_LOCAL_RUNTIME_DIR;
101
+ return configured ? path.resolve(configured) : null;
102
+ }
103
+
104
+ function activeBinDir() {
105
+ return localRuntimeDir() || BIN_DIR;
106
+ }
107
+
108
+ function detectTarget() {
109
+ const platformKey = `${process.platform}-${process.arch}`;
110
+ const platform = registry.platforms[platformKey];
111
+ if (!platform) {
112
+ const supported = Object.values(registry.platforms)
113
+ .map((entry) => entry.id)
114
+ .join('、');
115
+ throw new Error(
116
+ `暂不支持当前平台:${process.platform}/${process.arch}。已支持:${supported}。`
117
+ );
118
+ }
119
+ // 整包包含所有 Skill 二进制 + 一份共享浏览器桥接。
120
+ const binaries = registry.skills.map((skill) => binaryName(skill.bin, platform));
121
+ binaries.push(binaryName(registry.bridge, platform));
122
+ return { id: platform.id, archive: platform.archive, exe: platform.exe || '', binaries };
123
+ }
124
+
125
+ function selectSkill(argv) {
126
+ const byFlag = registry.skills.find((skill) => argv.includes(skill.flag));
127
+ if (byFlag) {
128
+ return byFlag;
129
+ }
130
+ // 仅在没有传参时选用唯一 Skill;带参数的调用必须明确指定 Skill,
131
+ // 避免把全局 --help 或其他 Skill 的参数误当成本 Skill 的运行请求。
132
+ if (registry.skills.length === 1 && argv.length === 0) {
133
+ return registry.skills[0];
134
+ }
135
+ return null;
136
+ }
137
+
138
+ function skillBinaryPath(skill, target) {
139
+ return path.join(activeBinDir(), `${skill.bin}-${target.id}${target.exe}`);
140
+ }
141
+
142
+ function browserBridgePath(target) {
143
+ return path.join(activeBinDir(), binaryName(registry.bridge, target));
144
+ }
145
+
146
+ function quotePowerShellLiteral(value) {
147
+ return `'${String(value).replaceAll("'", "''")}'`;
148
+ }
149
+
150
+ function printSkillHelp() {
151
+ const lines = registry.skills.map((skill) => ` ${skill.flag}\t${skill.name}`).join('\n') || ' 暂无已注册业务 Skill';
152
+ console.error(
153
+ `译心运营 CLI v${VERSION}\n\n` +
154
+ `用法:\n npx -y @yixinkj/ops@${NPM_CHANNEL} <skill> [选项]\n\n` +
155
+ `可用 Skill:\n${lines}\n\n` +
156
+ `运行状态:\n npx -y @yixinkj/ops@${NPM_CHANNEL} --runtime-status [run_id|latest]\n\n` +
157
+ `后台启动:\n npx -y @yixinkj/ops@${NPM_CHANNEL} <skill> [选项] --detach\n\n` +
158
+ `等待任务:\n npx -y @yixinkj/ops@${NPM_CHANNEL} --wait-runtime <run_id> --timeout 45\n\n` +
159
+ `示例:\n npx -y @yixinkj/ops@${NPM_CHANNEL} <skill> --help`
160
+ );
161
+ }
162
+
163
+ function validateRunId(value) {
164
+ if (!/^[A-Za-z0-9-]+$/.test(value)) {
165
+ throw new Error('run_id 格式无效');
166
+ }
167
+ return value;
168
+ }
169
+
170
+ function newRunId() {
171
+ return `${new Date().toISOString().replace(/[-:.TZ]/g, '')}-${crypto.randomUUID()}`;
172
+ }
173
+
174
+ function resolveRuntimeStatusPath(requested) {
175
+ if (!fs.existsSync(RUNS_DIR)) {
176
+ throw new Error('当前没有可读取的 CLI 运行状态');
177
+ }
178
+ if (requested === 'latest') {
179
+ const candidates = fs
180
+ .readdirSync(RUNS_DIR)
181
+ .filter((name) => name.endsWith('.status.json'))
182
+ .map((name) => ({ name, mtimeMs: fs.statSync(path.join(RUNS_DIR, name)).mtimeMs }))
183
+ .sort((left, right) => right.mtimeMs - left.mtimeMs);
184
+ if (!candidates.length) throw new Error('当前没有可读取的 CLI 运行状态');
185
+ return path.join(RUNS_DIR, candidates[0].name);
186
+ }
187
+ return path.join(RUNS_DIR, `${validateRunId(requested)}.status.json`);
188
+ }
189
+
190
+ function readRuntimeStatusFile(statusPath) {
191
+ return JSON.parse(fs.readFileSync(statusPath, 'utf8'));
192
+ }
193
+
194
+ function secondsSince(value, now = Date.now()) {
195
+ const timestamp = Date.parse(value || '');
196
+ if (!Number.isFinite(timestamp)) return null;
197
+ return Math.max(0, Math.floor((now - timestamp) / 1000));
198
+ }
199
+
200
+ function observableRuntimeStatus(status, extra = {}) {
201
+ const now = Date.now();
202
+ return {
203
+ ...status,
204
+ heartbeat_age_seconds: secondsSince(status.heartbeat_at, now),
205
+ stage_elapsed_seconds: secondsSince(status.stage_started_at || status.updated_at, now),
206
+ last_progress_age_seconds: secondsSince(status.progress_at || status.updated_at, now),
207
+ ...extra
208
+ };
209
+ }
210
+
211
+ function readRuntimeStatus(argv) {
212
+ const index = argv.indexOf('--runtime-status');
213
+ if (index < 0) return false;
214
+ const requested = argv[index + 1] || 'latest';
215
+ const statusPath = resolveRuntimeStatusPath(requested);
216
+ console.log(JSON.stringify(observableRuntimeStatus(readRuntimeStatusFile(statusPath)), null, 2));
217
+ return true;
218
+ }
219
+
220
+ function runtimeWaitSeconds(argv) {
221
+ const index = argv.indexOf('--timeout');
222
+ if (index < 0) return RUNTIME_WAIT_DEFAULT_SECONDS;
223
+ const value = Number(argv[index + 1]);
224
+ if (!Number.isFinite(value) || value <= 0) {
225
+ throw new Error('--timeout 需要大于 0 的秒数');
226
+ }
227
+ return Math.min(RUNTIME_WAIT_MAX_SECONDS, Math.max(1, Math.floor(value)));
228
+ }
229
+
230
+ async function waitRuntimeStatus(argv) {
231
+ const index = argv.indexOf('--wait-runtime');
232
+ if (index < 0) return false;
233
+ const requested = argv[index + 1];
234
+ if (!requested || requested.startsWith('-')) {
235
+ throw new Error('--wait-runtime 需要 RUN_ID');
236
+ }
237
+ const statusPath = resolveRuntimeStatusPath(validateRunId(requested));
238
+ const waitSeconds = runtimeWaitSeconds(argv);
239
+ const startedAt = Date.now();
240
+ const deadline = startedAt + waitSeconds * 1000;
241
+ let status = readRuntimeStatusFile(statusPath);
242
+
243
+ while (!TERMINAL_RUN_STATUSES.has(status.status) && Date.now() < deadline) {
244
+ await sleep(Math.min(RUNTIME_STATUS_POLL_MS, Math.max(1, deadline - Date.now())));
245
+ status = readRuntimeStatusFile(statusPath);
246
+ }
247
+
248
+ const waitExpired = !TERMINAL_RUN_STATUSES.has(status.status);
249
+ console.log(JSON.stringify(observableRuntimeStatus(status, {
250
+ wait_expired: waitExpired,
251
+ waited_ms: Date.now() - startedAt
252
+ }), null, 2));
253
+ return true;
254
+ }
255
+
256
+ function isInstalled(target) {
257
+ try {
258
+ const marker = JSON.parse(fs.readFileSync(INSTALL_MARKER, 'utf8'));
259
+ if (
260
+ marker.schema !== 'yixin_install_marker_v1' ||
261
+ marker.version !== VERSION ||
262
+ marker.platform !== target.id
263
+ ) {
264
+ return false;
265
+ }
266
+ return target.binaries.every((name) => {
267
+ const expected = marker.files?.[name];
268
+ if (!expected || !Number.isSafeInteger(expected.size) || expected.size <= 0) {
269
+ return false;
270
+ }
271
+ const stat = fs.statSync(path.join(BIN_DIR, name));
272
+ return stat.isFile() && stat.size === expected.size;
273
+ });
274
+ } catch {
275
+ return false;
276
+ }
277
+ }
278
+
279
+ function releaseUrls(target) {
280
+ if (process.env.YIXIN_OPS_RELEASE_BASE_URL) {
281
+ return [`${process.env.YIXIN_OPS_RELEASE_BASE_URL.replace(/\/$/, '')}/${target.archive}`];
282
+ }
283
+ return [
284
+ `${OSS_RELEASE_BASE_URL}/v${VERSION}/${target.archive}`,
285
+ `https://github.com/${RELEASE_REPO}/releases/download/v${VERSION}/${target.archive}`
286
+ ];
287
+ }
288
+
289
+ function downloadFile(url, outputPath, redirectsLeft = 5, signal) {
290
+ return new Promise((resolve, reject) => {
291
+ const requestUrl = new URL(url);
292
+ const headers = {
293
+ 'User-Agent': '@yixinkj/ops',
294
+ Accept: 'application/octet-stream'
295
+ };
296
+
297
+ if (process.env.YIXIN_OPS_GITHUB_TOKEN && requestUrl.hostname.endsWith('github.com')) {
298
+ headers.Authorization = `Bearer ${process.env.YIXIN_OPS_GITHUB_TOKEN}`;
299
+ }
300
+
301
+ const request = https.get(url, { headers, signal }, (response) => {
302
+ if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
303
+ response.resume();
304
+ if (redirectsLeft <= 0) {
305
+ reject(new Error(`下载时重定向次数过多:${url}`));
306
+ return;
307
+ }
308
+ const location = response.headers.location;
309
+ if (!location) {
310
+ reject(new Error(`重定向响应缺少 Location:${url}`));
311
+ return;
312
+ }
313
+ const nextUrl = new URL(location, url).toString();
314
+ downloadFile(nextUrl, outputPath, redirectsLeft - 1, signal).then(resolve, reject);
315
+ return;
316
+ }
317
+
318
+ if (response.statusCode !== 200) {
319
+ response.resume();
320
+ reject(new Error(`下载失败:HTTP ${response.statusCode} ${url}`));
321
+ return;
322
+ }
323
+
324
+ const file = fs.createWriteStream(outputPath);
325
+ response.pipe(file);
326
+ response.on('aborted', () => {
327
+ file.destroy();
328
+ reject(new Error(`下载连接意外中断:${url}`));
329
+ });
330
+ response.on('error', (error) => {
331
+ file.destroy();
332
+ reject(error);
333
+ });
334
+ file.on('finish', () => file.close(resolve));
335
+ file.on('error', reject);
336
+ });
337
+ request.setTimeout(30000, () => {
338
+ request.destroy(new Error(`下载超时:${url}`));
339
+ });
340
+ request.on('error', reject);
341
+ });
342
+ }
343
+
344
+ function sleep(milliseconds, signal) {
345
+ return new Promise((resolve, reject) => {
346
+ if (signal?.aborted) {
347
+ reject(signal.reason || new Error('操作已取消'));
348
+ return;
349
+ }
350
+ const onAbort = () => {
351
+ clearTimeout(timer);
352
+ reject(signal.reason || new Error('操作已取消'));
353
+ };
354
+ const timer = setTimeout(() => {
355
+ signal?.removeEventListener('abort', onAbort);
356
+ resolve();
357
+ }, milliseconds);
358
+ signal?.addEventListener('abort', onAbort, { once: true });
359
+ });
360
+ }
361
+
362
+ function writeJsonAtomic(filePath, value) {
363
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
364
+ const tempPath = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
365
+ try {
366
+ fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
367
+ JSON.parse(fs.readFileSync(tempPath, 'utf8'));
368
+ fs.renameSync(tempPath, filePath);
369
+ } finally {
370
+ fs.rmSync(tempPath, { force: true });
371
+ }
372
+ }
373
+
374
+ function sha256File(filePath) {
375
+ return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
376
+ }
377
+
378
+ function installLockPath(target) {
379
+ return path.join(CACHE_ROOT, `install-v${VERSION}-${target.id}.lock`);
380
+ }
381
+
382
+ function processIsAlive(pid) {
383
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
384
+ try {
385
+ process.kill(pid, 0);
386
+ return true;
387
+ } catch (error) {
388
+ // EPERM 表示进程存在但当前账户无权发信号;只有 ESRCH 才能确认已经退出。
389
+ return error?.code !== 'ESRCH';
390
+ }
391
+ }
392
+
393
+ async function acquireInstallLock(target, signal) {
394
+ fs.mkdirSync(CACHE_ROOT, { recursive: true });
395
+ const lockPath = installLockPath(target);
396
+ const token = crypto.randomUUID();
397
+ const deadline = Date.now() + INSTALL_LOCK_WAIT_MS;
398
+ let announced = false;
399
+
400
+ while (true) {
401
+ if (signal?.aborted) throw signal.reason || new Error('操作已取消');
402
+ try {
403
+ const fd = fs.openSync(lockPath, 'wx', 0o600);
404
+ fs.writeFileSync(
405
+ fd,
406
+ `${JSON.stringify({ token, pid: process.pid, version: VERSION, platform: target.id, created_at: new Date().toISOString() })}\n`
407
+ );
408
+ const heartbeat = setInterval(() => {
409
+ try {
410
+ const now = new Date();
411
+ fs.futimesSync(fd, now, now);
412
+ } catch {
413
+ // 锁仍由打开的 fd 持有;更新时间失败不应打断安装。
414
+ }
415
+ }, INSTALL_LOCK_HEARTBEAT_MS);
416
+ heartbeat.unref();
417
+ let released = false;
418
+ return () => {
419
+ if (released) return;
420
+ released = true;
421
+ clearInterval(heartbeat);
422
+ try {
423
+ fs.closeSync(fd);
424
+ } catch {
425
+ // best effort
426
+ }
427
+ try {
428
+ const current = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
429
+ if (current.token === token) fs.rmSync(lockPath, { force: true });
430
+ } catch {
431
+ // 锁可能已被人工清理。
432
+ }
433
+ };
434
+ } catch (error) {
435
+ if (error?.code !== 'EEXIST') throw error;
436
+
437
+ try {
438
+ const lockStat = fs.statSync(lockPath);
439
+ const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
440
+ const ownerExited = Number.isSafeInteger(lock.pid) && !processIsAlive(lock.pid);
441
+ const expired = Date.now() - lockStat.mtimeMs > INSTALL_LOCK_STALE_MS;
442
+ if (ownerExited || expired) {
443
+ console.error(
444
+ ownerExited
445
+ ? '[yixin-ops] 检测到安装任务已经退出,正在清理遗留锁后重试...'
446
+ : '[yixin-ops] 检测到过期安装锁,正在安全清理后重试...'
447
+ );
448
+ fs.rmSync(lockPath, { force: true });
449
+ continue;
450
+ }
451
+ } catch (statError) {
452
+ if (statError?.code === 'ENOENT') continue;
453
+ }
454
+
455
+ if (Date.now() >= deadline) {
456
+ throw new Error(
457
+ `等待另一条 CLI 完成 v${VERSION} 安装超时。请稍后重试;若确认没有任务运行,可删除 ${lockPath}`
458
+ );
459
+ }
460
+ if (!announced) {
461
+ console.error('[yixin-ops] 另一条 Accio/CLI 任务正在安装同一版本,当前任务将等待并复用其结果...');
462
+ announced = true;
463
+ }
464
+ await sleep(1000, signal);
465
+ }
466
+ }
467
+ }
468
+
469
+ async function downloadFromSources(urls, outputPath, signal) {
470
+ const failures = [];
471
+ for (let index = 0; index < urls.length; index += 1) {
472
+ const url = urls[index];
473
+ try {
474
+ fs.rmSync(outputPath, { force: true });
475
+ console.error(`[yixin-ops] 正在下载 ${url}`);
476
+ await downloadFile(url, outputPath, 5, signal);
477
+ return;
478
+ } catch (error) {
479
+ fs.rmSync(outputPath, { force: true });
480
+ if (signal?.aborted) throw signal.reason || error;
481
+ failures.push(`${url}: ${error.message}`);
482
+ if (index + 1 < urls.length) {
483
+ console.error(`[yixin-ops] 当前下载源失败,正在切换备用源:${error.message}`);
484
+ }
485
+ }
486
+ }
487
+ throw new Error(`所有二进制下载源均失败:\n${failures.join('\n')}`);
488
+ }
489
+
490
+ function runCommand(command, args) {
491
+ const result = spawnSync(command, args, {
492
+ encoding: 'utf8',
493
+ stdio: ['ignore', 'pipe', 'pipe'],
494
+ timeout: 120000,
495
+ windowsHide: true
496
+ });
497
+ if (result.error) {
498
+ throw result.error;
499
+ }
500
+ if (result.status !== 0) {
501
+ const detail = [result.stderr, result.stdout].filter(Boolean).join('\n').trim();
502
+ throw new Error(detail || `${command} 退出码为 ${result.status}`);
503
+ }
504
+ }
505
+
506
+ function extractArchive(archivePath, target, binDir) {
507
+ fs.rmSync(binDir, { recursive: true, force: true });
508
+ fs.mkdirSync(binDir, { recursive: true });
509
+
510
+ if (target.archive.endsWith('.tar.gz')) {
511
+ runCommand('tar', ['-xzf', archivePath, '-C', binDir]);
512
+ return;
513
+ }
514
+
515
+ if (target.archive.endsWith('.zip')) {
516
+ if (process.platform === 'win32') {
517
+ runCommand('powershell.exe', [
518
+ '-NoProfile',
519
+ '-ExecutionPolicy',
520
+ 'Bypass',
521
+ '-Command',
522
+ `Expand-Archive -LiteralPath ${quotePowerShellLiteral(archivePath)} -DestinationPath ${quotePowerShellLiteral(binDir)} -Force`
523
+ ]);
524
+ return;
525
+ }
526
+ runCommand('unzip', ['-q', archivePath, '-d', binDir]);
527
+ return;
528
+ }
529
+
530
+ throw new Error(`暂不支持的压缩包类型:${target.archive}`);
531
+ }
532
+
533
+ function prepareMacBinary(filePath) {
534
+ if (process.platform !== 'darwin' || !fs.existsSync(filePath)) {
535
+ return;
536
+ }
537
+
538
+ spawnSync('xattr', ['-dr', 'com.apple.quarantine', filePath], {
539
+ encoding: 'utf8',
540
+ stdio: 'ignore'
541
+ });
542
+
543
+ const chmod = spawnSync('chmod', ['+x', filePath], {
544
+ encoding: 'utf8',
545
+ stdio: ['ignore', 'pipe', 'pipe']
546
+ });
547
+ if (chmod.error) {
548
+ throw chmod.error;
549
+ }
550
+ if (chmod.status !== 0) {
551
+ throw new Error((chmod.stderr || chmod.stdout || `chmod +x failed: ${filePath}`).trim());
552
+ }
553
+ }
554
+
555
+ function prepareInstalledBinaries(target, binDir = BIN_DIR) {
556
+ if (process.platform !== 'darwin') {
557
+ return;
558
+ }
559
+ for (const name of target.binaries) {
560
+ prepareMacBinary(path.join(binDir, name));
561
+ }
562
+ }
563
+
564
+ function unblockWindowsBinaries(target, binDir = BIN_DIR) {
565
+ if (process.platform !== 'win32') {
566
+ return;
567
+ }
568
+
569
+ const files = target.binaries.map((name) => path.join(binDir, name));
570
+ const script =
571
+ `$files = @(${files.map(quotePowerShellLiteral).join(',')}); ` +
572
+ `foreach ($file in $files) { ` +
573
+ `if (Test-Path -LiteralPath $file) { ` +
574
+ `Unblock-File -LiteralPath $file -ErrorAction SilentlyContinue ` +
575
+ `} ` +
576
+ `}`;
577
+ const result = spawnSync(
578
+ 'powershell.exe',
579
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', script],
580
+ {
581
+ encoding: 'utf8',
582
+ stdio: ['ignore', 'pipe', 'pipe'],
583
+ timeout: 30000,
584
+ windowsHide: true
585
+ }
586
+ );
587
+ if (result.error || result.status !== 0) {
588
+ const detail =
589
+ result.error?.message ||
590
+ (result.stderr || result.stdout || `退出码 ${result.status}`).trim();
591
+ // Unblock-File 是兼容性优化,不应因为旧版 PowerShell 或安全软件策略让整个 CLI 安装失败。
592
+ console.error(`[yixin-ops] Windows 二进制解除下载阻止未完成,将继续启动 skill。(${detail})`);
593
+ }
594
+ }
595
+
596
+ function warmupBrowserBridge(target) {
597
+ const bridge = browserBridgePath(target);
598
+ if (!fs.existsSync(bridge)) {
599
+ return;
600
+ }
601
+ console.error('[yixin-ops] 正在预热浏览器桥接,首次运行可能需要几秒钟...');
602
+ const result = spawnSync(bridge, ['tabs'], {
603
+ encoding: 'utf8',
604
+ stdio: 'ignore',
605
+ timeout: 15000,
606
+ windowsHide: true
607
+ });
608
+ if (result.error || result.status !== 0) {
609
+ const detail = result.error?.message || `退出码 ${result.status}`;
610
+ console.error(
611
+ `[yixin-ops] 浏览器桥接预热未完成,将继续启动 skill。若页面打开后长时间无响应,请重新运行当前命令。(${detail})`
612
+ );
613
+ }
614
+ }
615
+
616
+ function commandNeedsBrowserWarmup(argv) {
617
+ const offlineFlags = new Set([
618
+ '--create-report-patch-template',
619
+ '--apply-report-patch',
620
+ '--render-report',
621
+ '--help',
622
+ '-h',
623
+ '--version',
624
+ '-V',
625
+ '--dry-run',
626
+ '--smoke-auth',
627
+ '--serve',
628
+ '--start',
629
+ '--init-db',
630
+ '--list-tasks',
631
+ '--list-targets',
632
+ '--cycle-status',
633
+ '--analysis-scopes',
634
+ '--analyze'
635
+ ]);
636
+ return !argv.some((arg) => offlineFlags.has(arg));
637
+ }
638
+
639
+ function verifyExtractedBinaries(binDir, target) {
640
+ const manifestPath = path.join(binDir, 'checksums.json');
641
+ let manifest;
642
+ try {
643
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
644
+ } catch (error) {
645
+ throw new Error(`发布包缺少有效的 checksums.json:${error.message}`);
646
+ }
647
+ if (
648
+ manifest.schema !== 'yixin_binary_manifest_v1' ||
649
+ manifest.version !== VERSION ||
650
+ manifest.platform !== target.id
651
+ ) {
652
+ throw new Error(
653
+ `二进制清单不匹配:期望 v${VERSION}/${target.id},实际 ${manifest.version || 'unknown'}/${manifest.platform || 'unknown'}`
654
+ );
655
+ }
656
+
657
+ const verifiedFiles = {};
658
+ for (const name of target.binaries) {
659
+ const expected = manifest.files?.[name];
660
+ if (!expected || typeof expected.sha256 !== 'string' || !Number.isSafeInteger(expected.size)) {
661
+ throw new Error(`二进制清单缺少 ${name}`);
662
+ }
663
+ const filePath = path.join(binDir, name);
664
+ const stat = fs.statSync(filePath);
665
+ if (!stat.isFile() || stat.size !== expected.size || stat.size <= 0) {
666
+ throw new Error(`${name} 文件大小校验失败:期望 ${expected.size},实际 ${stat.size}`);
667
+ }
668
+ const actualHash = sha256File(filePath);
669
+ if (actualHash.toLowerCase() !== expected.sha256.toLowerCase()) {
670
+ throw new Error(`${name} SHA256 校验失败`);
671
+ }
672
+ verifiedFiles[name] = { size: stat.size, sha256: actualHash };
673
+ }
674
+ return verifiedFiles;
675
+ }
676
+
677
+ function commitStagedInstall(stagingRoot) {
678
+ const backupRoot = path.join(
679
+ VERSIONS_ROOT,
680
+ `.backup-v${VERSION}-${process.pid}-${crypto.randomUUID()}`
681
+ );
682
+ let movedOldVersion = false;
683
+ try {
684
+ if (fs.existsSync(VERSION_ROOT)) {
685
+ fs.renameSync(VERSION_ROOT, backupRoot);
686
+ movedOldVersion = true;
687
+ }
688
+ fs.renameSync(stagingRoot, VERSION_ROOT);
689
+ } catch (error) {
690
+ if (movedOldVersion && !fs.existsSync(VERSION_ROOT) && fs.existsSync(backupRoot)) {
691
+ try {
692
+ fs.renameSync(backupRoot, VERSION_ROOT);
693
+ } catch (restoreError) {
694
+ error.message += `;恢复旧版本目录失败:${restoreError.message}`;
695
+ }
696
+ }
697
+ throw error;
698
+ } finally {
699
+ // 只有新目录或已恢复的旧目录确实存在时才清理备份;恢复失败时保留备份供人工救援。
700
+ if (fs.existsSync(VERSION_ROOT)) {
701
+ fs.rmSync(backupRoot, { recursive: true, force: true });
702
+ }
703
+ }
704
+ }
705
+
706
+ function installFromArchive(archivePath, target, shouldWarmup = true) {
707
+ fs.mkdirSync(VERSIONS_ROOT, { recursive: true });
708
+ const stagingPrefix = `.staging-v${VERSION}-${target.id}-`;
709
+ for (const entry of fs.readdirSync(VERSIONS_ROOT)) {
710
+ if (entry.startsWith(stagingPrefix)) {
711
+ fs.rmSync(path.join(VERSIONS_ROOT, entry), { recursive: true, force: true });
712
+ }
713
+ }
714
+ const stagingRoot = fs.mkdtempSync(
715
+ path.join(VERSIONS_ROOT, `${stagingPrefix}${process.pid}-`)
716
+ );
717
+ const stagingBin = path.join(stagingRoot, 'bin');
718
+ try {
719
+ extractArchive(archivePath, target, stagingBin);
720
+ prepareInstalledBinaries(target, stagingBin);
721
+ unblockWindowsBinaries(target, stagingBin);
722
+ const files = verifyExtractedBinaries(stagingBin, target);
723
+ writeJsonAtomic(path.join(stagingRoot, 'installed.json'), {
724
+ schema: 'yixin_install_marker_v1',
725
+ version: VERSION,
726
+ platform: target.id,
727
+ installed_at: new Date().toISOString(),
728
+ files
729
+ });
730
+ commitStagedInstall(stagingRoot);
731
+ } finally {
732
+ fs.rmSync(stagingRoot, { recursive: true, force: true });
733
+ }
734
+ if (shouldWarmup) warmupBrowserBridge(target);
735
+ }
736
+
737
+ async function ensureInstalled(target, signal, skill, shouldWarmup = true) {
738
+ const localDir = localRuntimeDir();
739
+ if (localDir) {
740
+ const localTarget = {
741
+ ...target,
742
+ binaries: [
743
+ path.basename(skillBinaryPath(skill, target)),
744
+ path.basename(browserBridgePath(target))
745
+ ]
746
+ };
747
+ verifyExtractedBinaries(localDir, localTarget);
748
+ prepareInstalledBinaries(localTarget, localDir);
749
+ if (shouldWarmup) warmupBrowserBridge(localTarget);
750
+ return;
751
+ }
752
+ if (isInstalled(target)) {
753
+ prepareInstalledBinaries(target);
754
+ return;
755
+ }
756
+
757
+ const releaseLock = await acquireInstallLock(target, signal);
758
+ try {
759
+ // 另一条等待中的任务可能已经完成安装;拿到锁后必须二次确认。
760
+ if (isInstalled(target)) {
761
+ prepareInstalledBinaries(target);
762
+ return;
763
+ }
764
+
765
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yixin-ops-'));
766
+ const archivePath = path.join(tempDir, target.archive);
767
+ const urls = releaseUrls(target);
768
+
769
+ try {
770
+ console.error(`[yixin-ops] 正在安装 ${target.id} 二进制,版本 ${VERSION}`);
771
+ await downloadFromSources(urls, archivePath, signal);
772
+ installFromArchive(archivePath, target, shouldWarmup);
773
+ } catch (error) {
774
+ throw withInstallHelp(error);
775
+ } finally {
776
+ fs.rmSync(tempDir, { recursive: true, force: true });
777
+ }
778
+ } finally {
779
+ releaseLock();
780
+ }
781
+ }
782
+
783
+ function createRunState(skill, target) {
784
+ const forcedRunId = process.env.YIXIN_FORCED_RUN_ID;
785
+ const runId = forcedRunId ? validateRunId(forcedRunId) : newRunId();
786
+ const statusPath = path.join(RUNS_DIR, `${runId}.status.json`);
787
+ const now = new Date().toISOString();
788
+ let queuedState = null;
789
+ if (forcedRunId) {
790
+ try {
791
+ queuedState = readRuntimeStatusFile(statusPath);
792
+ } catch {
793
+ // detached worker 仍可在排队状态文件缺失时自行恢复。
794
+ }
795
+ }
796
+ let state = {
797
+ ...(queuedState || {}),
798
+ schema: 'yixin_run_status_v1',
799
+ run_id: runId,
800
+ cli_version: VERSION,
801
+ skill: skill.name,
802
+ skill_flag: skill.flag,
803
+ platform: target.id,
804
+ pid: process.pid,
805
+ status: 'starting',
806
+ stage: 'launcher_start',
807
+ retryable: false,
808
+ started_at: queuedState?.started_at || now,
809
+ stage_started_at: now,
810
+ progress_at: now,
811
+ progress_seq: Number(queuedState?.progress_seq || 0) + 1,
812
+ updated_at: now,
813
+ heartbeat_at: now
814
+ };
815
+ let enabled = true;
816
+ let warned = false;
817
+
818
+ const persist = () => {
819
+ if (!enabled) return;
820
+ try {
821
+ writeJsonAtomic(statusPath, state);
822
+ } catch (error) {
823
+ enabled = false;
824
+ if (!warned) {
825
+ warned = true;
826
+ console.error(`[yixin-ops] 运行状态文件写入失败,将继续执行 Skill。(${error.message})`);
827
+ }
828
+ }
829
+ };
830
+ const update = (patch) => {
831
+ const now = new Date().toISOString();
832
+ const stageChanged = typeof patch.stage === 'string' && patch.stage !== state.stage;
833
+ const statusChanged = typeof patch.status === 'string' && patch.status !== state.status;
834
+ const messageChanged = typeof patch.message === 'string' && patch.message !== state.message;
835
+ const artifactsChanged = patch.artifacts && patch.artifacts !== state.artifacts;
836
+ const progressed = stageChanged || statusChanged || messageChanged || artifactsChanged;
837
+ state = {
838
+ ...state,
839
+ ...patch,
840
+ ...(stageChanged ? { stage_started_at: now } : {}),
841
+ ...(progressed
842
+ ? { progress_at: now, progress_seq: Number(state.progress_seq || 0) + 1 }
843
+ : {}),
844
+ updated_at: now,
845
+ heartbeat_at: now
846
+ };
847
+ persist();
848
+ };
849
+
850
+ persist();
851
+ if (enabled) console.error(`[yixin-ops] RUN_ID=${runId} STATUS_FILE=${statusPath}`);
852
+ const heartbeat = setInterval(() => {
853
+ state = {
854
+ ...state,
855
+ heartbeat_at: new Date().toISOString(),
856
+ updated_at: new Date().toISOString()
857
+ };
858
+ persist();
859
+ if (state.status === 'running') {
860
+ console.error(`[yixin-ops] 任务仍在运行:stage=${state.stage} run_id=${runId}`);
861
+ }
862
+ }, RUN_HEARTBEAT_MS);
863
+ heartbeat.unref();
864
+
865
+ return {
866
+ runId,
867
+ statusPath,
868
+ update,
869
+ current() {
870
+ return state;
871
+ },
872
+ finish(patch) {
873
+ clearInterval(heartbeat);
874
+ update(patch);
875
+ }
876
+ };
877
+ }
878
+
879
+ function queuedRunState(runId, skill, target) {
880
+ const now = new Date().toISOString();
881
+ return {
882
+ schema: 'yixin_run_status_v1',
883
+ run_id: runId,
884
+ cli_version: VERSION,
885
+ skill: skill.name,
886
+ skill_flag: skill.flag,
887
+ platform: target.id,
888
+ pid: null,
889
+ status: 'queued',
890
+ stage: 'queued',
891
+ retryable: false,
892
+ started_at: now,
893
+ stage_started_at: now,
894
+ progress_at: now,
895
+ progress_seq: 0,
896
+ updated_at: now,
897
+ heartbeat_at: now,
898
+ message: '任务已进入后台启动队列'
899
+ };
900
+ }
901
+
902
+ function startDetachedRuntime(argv) {
903
+ const detachIndex = argv.indexOf('--detach');
904
+ if (detachIndex < 0) return false;
905
+ if (process.env.YIXIN_DETACHED_WORKER === '1') {
906
+ throw new Error('后台 worker 不允许再次使用 --detach');
907
+ }
908
+
909
+ const workerArgv = argv.filter((_, index) => index !== detachIndex);
910
+ const target = detectTarget();
911
+ const skill = selectSkill(workerArgv);
912
+ if (!skill) {
913
+ throw new Error('--detach 必须与一个有效 Skill 参数一起使用');
914
+ }
915
+
916
+ const runId = newRunId();
917
+ const statusPath = path.join(RUNS_DIR, `${runId}.status.json`);
918
+ writeJsonAtomic(statusPath, queuedRunState(runId, skill, target));
919
+ const launcherPath = fileURLToPath(import.meta.url);
920
+ const child = spawn(process.execPath, [launcherPath, ...workerArgv], {
921
+ cwd: process.cwd(),
922
+ detached: true,
923
+ stdio: 'ignore',
924
+ env: {
925
+ ...process.env,
926
+ YIXIN_FORCED_RUN_ID: runId,
927
+ YIXIN_DETACHED_WORKER: '1'
928
+ },
929
+ windowsHide: true
930
+ });
931
+ child.unref();
932
+
933
+ const localDir = localRuntimeDir();
934
+ const waitCommand = localDir
935
+ ? `YIXIN_OPS_LOCAL_RUNTIME_DIR=${JSON.stringify(localDir)} ${JSON.stringify(process.execPath)} ${JSON.stringify(launcherPath)} --wait-runtime ${runId} --timeout ${RUNTIME_WAIT_DEFAULT_SECONDS}`
936
+ : `npx -y @yixinkj/ops@${NPM_CHANNEL} --wait-runtime ${runId} --timeout ${RUNTIME_WAIT_DEFAULT_SECONDS}`;
937
+
938
+ // Keep the machine-readable JSON on stdout, while also emitting the run id
939
+ // on stderr for hosts that occasionally lose or defer detached stdout.
940
+ console.error(`[yixin-ops] RUN_ID=${runId} STATUS_FILE=${statusPath}`);
941
+ console.log(JSON.stringify({
942
+ status: 'started',
943
+ run_id: runId,
944
+ status_file: statusPath,
945
+ wait_command: waitCommand
946
+ }, null, 2));
947
+ return true;
948
+ }
949
+
950
+ function cancellationError(signalName) {
951
+ const error = new Error(`任务收到 ${signalName},正在取消`);
952
+ error.code = 'YIXIN_CANCELLED';
953
+ error.signalName = signalName;
954
+ return error;
955
+ }
956
+
957
+ function createCancellationController(runState) {
958
+ const abortController = new AbortController();
959
+ let child = null;
960
+ let receivedSignal = null;
961
+ let hardKillTimer = null;
962
+
963
+ const stopChild = (force = false) => {
964
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
965
+ try {
966
+ child.kill(force ? 'SIGKILL' : process.platform === 'win32' ? 'SIGTERM' : receivedSignal);
967
+ } catch {
968
+ // 子进程可能刚好已经退出。
969
+ }
970
+ if (!force && !hardKillTimer) {
971
+ hardKillTimer = setTimeout(() => stopChild(true), 5000);
972
+ hardKillTimer.unref();
973
+ }
974
+ };
975
+ const onSignal = (signalName) => {
976
+ if (receivedSignal) {
977
+ stopChild(true);
978
+ return;
979
+ }
980
+ receivedSignal = signalName;
981
+ runState.update({
982
+ status: 'cancelling',
983
+ stage: 'cancelling',
984
+ retryable: true,
985
+ message: `收到 ${signalName},正在停止当前 Skill`
986
+ });
987
+ abortController.abort(cancellationError(signalName));
988
+ stopChild(false);
989
+ };
990
+ const handlers = new Map();
991
+ for (const signalName of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
992
+ if (process.platform === 'win32' && signalName === 'SIGHUP') continue;
993
+ const handler = () => onSignal(signalName);
994
+ handlers.set(signalName, handler);
995
+ process.on(signalName, handler);
996
+ }
997
+
998
+ return {
999
+ signal: abortController.signal,
1000
+ get receivedSignal() {
1001
+ return receivedSignal;
1002
+ },
1003
+ setChild(value) {
1004
+ child = value;
1005
+ if (abortController.signal.aborted) stopChild(false);
1006
+ },
1007
+ clearChild() {
1008
+ child = null;
1009
+ if (hardKillTimer) clearTimeout(hardKillTimer);
1010
+ hardKillTimer = null;
1011
+ },
1012
+ dispose() {
1013
+ for (const [signalName, handler] of handlers) process.off(signalName, handler);
1014
+ if (hardKillTimer) clearTimeout(hardKillTimer);
1015
+ }
1016
+ };
1017
+ }
1018
+
1019
+ function applyChildStatusLine(line, runState) {
1020
+ const prefix = '[yixin-status] ';
1021
+ if (!line.startsWith(prefix)) return;
1022
+ try {
1023
+ const payload = JSON.parse(line.slice(prefix.length));
1024
+ const patch = {};
1025
+ if (typeof payload.stage === 'string') patch.stage = payload.stage;
1026
+ if (typeof payload.message === 'string') patch.message = payload.message;
1027
+ if (payload.artifacts && typeof payload.artifacts === 'object') {
1028
+ patch.artifacts = payload.artifacts;
1029
+ }
1030
+ runState.update(patch);
1031
+ } catch {
1032
+ // 状态行只是可观测性补充;格式异常不能影响 Skill 本身。
1033
+ }
1034
+ }
1035
+
1036
+ function retryableSkillFailure(stderrTail) {
1037
+ return /LOGIN_REQUIRED|timeout|timed out|超时|bridge|桥接|extension|扩展|network|网络|connection|连接|temporar|offline|页面.*未就绪/i.test(
1038
+ stderrTail
1039
+ );
1040
+ }
1041
+
1042
+ function childFailureMessage(stderrTail, exitCode) {
1043
+ const line = stderrTail
1044
+ .split(/\r?\n/)
1045
+ .map((value) => value.trim())
1046
+ .filter((value) => value && !value.startsWith('[yixin-status]'))
1047
+ .at(-1);
1048
+ return (line || `Skill 退出码 ${exitCode}`).slice(0, 1000);
1049
+ }
1050
+
1051
+ function parseChildJson(stdout) {
1052
+ const text = String(stdout || '').trim();
1053
+ if (!text) return null;
1054
+ try {
1055
+ return JSON.parse(text);
1056
+ } catch {
1057
+ return null;
1058
+ }
1059
+ }
1060
+
1061
+ function runSkill(skill, target, argv, runState, cancellation) {
1062
+ return new Promise((resolve, reject) => {
1063
+ const child = spawn(skillBinaryPath(skill, target), argv, {
1064
+ stdio: ['inherit', 'pipe', 'pipe'],
1065
+ env: {
1066
+ ...process.env,
1067
+ YIXIN_RUN_ID: runState.runId,
1068
+ YIXIN_RUN_STATUS_PATH: runState.statusPath,
1069
+ YIXIN_NODE_EXECUTABLE: process.execPath
1070
+ },
1071
+ windowsHide: true
1072
+ });
1073
+ cancellation.setChild(child);
1074
+ let stdoutBuffer = '';
1075
+ let stderrBuffer = '';
1076
+ let stderrTail = '';
1077
+ child.stdout.on('data', (chunk) => {
1078
+ const text = chunk.toString();
1079
+ process.stdout.write(text);
1080
+ stdoutBuffer = `${stdoutBuffer}${text}`.slice(-2 * 1024 * 1024);
1081
+ });
1082
+ child.stderr.on('data', (chunk) => {
1083
+ const text = chunk.toString();
1084
+ process.stderr.write(text);
1085
+ stderrTail = `${stderrTail}${text}`.slice(-8000);
1086
+ stderrBuffer += text;
1087
+ const lines = stderrBuffer.split(/\r?\n/);
1088
+ stderrBuffer = lines.pop() || '';
1089
+ for (const line of lines) applyChildStatusLine(line, runState);
1090
+ });
1091
+ child.once('error', (error) => {
1092
+ cancellation.clearChild();
1093
+ reject(error);
1094
+ });
1095
+ child.once('exit', (code, signalName) => {
1096
+ if (stderrBuffer) applyChildStatusLine(stderrBuffer, runState);
1097
+ cancellation.clearChild();
1098
+ resolve({ code: code ?? 1, signalName, stderrTail, stdout: stdoutBuffer });
1099
+ });
1100
+ });
1101
+ }
1102
+
1103
+ async function main() {
1104
+ const argv = process.argv.slice(2);
1105
+ if (await waitRuntimeStatus(argv)) return;
1106
+ if (readRuntimeStatus(argv)) return;
1107
+ if (startDetachedRuntime(argv)) return;
1108
+ const skill = selectSkill(argv);
1109
+ if (!skill) {
1110
+ printSkillHelp();
1111
+ process.exit(argv.some((arg) => arg === '--help' || arg === '-h') ? 0 : 1);
1112
+ }
1113
+
1114
+ const target = detectTarget();
1115
+ const runState = createRunState(skill, target);
1116
+ const cancellation = createCancellationController(runState);
1117
+ try {
1118
+ runState.update({ status: 'running', stage: 'install_check', message: '正在检查本地二进制' });
1119
+ await ensureInstalled(
1120
+ target,
1121
+ cancellation.signal,
1122
+ skill,
1123
+ commandNeedsBrowserWarmup(argv)
1124
+ );
1125
+ if (cancellation.signal.aborted) throw cancellation.signal.reason;
1126
+
1127
+ runState.update({ status: 'running', stage: 'skill_start', message: '正在启动 Skill' });
1128
+ const result = await runSkill(skill, target, argv, runState, cancellation);
1129
+ if (cancellation.signal.aborted) throw cancellation.signal.reason;
1130
+ if (result.code === 0) {
1131
+ const childResult = parseChildJson(result.stdout);
1132
+ const artifacts = childResult?.capture_paths || runState.current().artifacts;
1133
+ runState.finish({
1134
+ status: 'completed',
1135
+ stage: 'completed',
1136
+ retryable: false,
1137
+ exit_code: 0,
1138
+ message: 'Skill 已完成',
1139
+ ...(artifacts ? { artifacts } : {}),
1140
+ ...(childResult ? { result: childResult } : {})
1141
+ });
1142
+ process.exitCode = 0;
1143
+ return;
1144
+ }
1145
+ runState.finish({
1146
+ status: 'failed',
1147
+ stage: 'skill_failed',
1148
+ retryable: retryableSkillFailure(result.stderrTail),
1149
+ exit_code: result.code,
1150
+ child_signal: result.signalName,
1151
+ message: childFailureMessage(result.stderrTail, result.code)
1152
+ });
1153
+ process.exitCode = result.code;
1154
+ } catch (error) {
1155
+ const cancelled = error?.code === 'YIXIN_CANCELLED' || cancellation.signal.aborted;
1156
+ runState.finish({
1157
+ status: cancelled ? 'cancelled' : 'failed',
1158
+ stage: cancelled ? 'cancelled' : 'launcher_failed',
1159
+ retryable: cancelled || /timeout|超时|network|网络|download|下载/i.test(error?.message || ''),
1160
+ exit_code: cancelled ? (cancellation.receivedSignal === 'SIGINT' ? 130 : 143) : 1,
1161
+ message: error?.message || String(error)
1162
+ });
1163
+ if (cancelled) {
1164
+ console.error(`[yixin-ops] ${error.message}`);
1165
+ process.exitCode = cancellation.receivedSignal === 'SIGINT' ? 130 : 143;
1166
+ return;
1167
+ }
1168
+ throw error;
1169
+ } finally {
1170
+ cancellation.dispose();
1171
+ }
1172
+ }
1173
+
1174
+ function isDirectExecution() {
1175
+ if (!process.argv[1]) return false;
1176
+ let invoked = path.resolve(process.argv[1]);
1177
+ let current = fileURLToPath(import.meta.url);
1178
+ try {
1179
+ invoked = fs.realpathSync(invoked);
1180
+ current = fs.realpathSync(current);
1181
+ } catch {
1182
+ // 文件系统不支持 realpath 时退回绝对路径比较。
1183
+ }
1184
+ return process.platform === 'win32'
1185
+ ? invoked.toLowerCase() === current.toLowerCase()
1186
+ : invoked === current;
1187
+ }
1188
+
1189
+ if (isDirectExecution()) {
1190
+ main().catch((error) => {
1191
+ fail(error.message);
1192
+ });
1193
+ }
1194
+
1195
+ export {
1196
+ acquireInstallLock,
1197
+ commandNeedsBrowserWarmup,
1198
+ createRunState,
1199
+ detectTarget,
1200
+ installFromArchive,
1201
+ isInstalled,
1202
+ observableRuntimeStatus,
1203
+ runSkill,
1204
+ waitRuntimeStatus
1205
+ };
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@yixinkj/ops",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Yixin operations native CLI launcher.",
5
+ "type": "module",
6
+ "bin": {
7
+ "yixin-ops": "index.js"
8
+ },
9
+ "files": [
10
+ "index.js",
11
+ "skills.json",
12
+ "README.md"
13
+ ],
14
+ "dependencies": {},
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "license": "UNLICENSED",
19
+ "private": false,
20
+ "publishConfig": {
21
+ "access": "public"
22
+ }
23
+ }
package/skills.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "platforms": {
3
+ "darwin-arm64": {
4
+ "id": "mac-arm64",
5
+ "archive": "yixin-ops-mac-arm64.tar.gz",
6
+ "exe": ""
7
+ },
8
+ "darwin-x64": {
9
+ "id": "mac-x64",
10
+ "archive": "yixin-ops-mac-x64.tar.gz",
11
+ "exe": ""
12
+ },
13
+ "win32-x64": {
14
+ "id": "win32-x64",
15
+ "archive": "yixin-ops-win32-x64.zip",
16
+ "exe": ".exe"
17
+ }
18
+ },
19
+ "bridge": "browser-bridge",
20
+ "skills": [
21
+ {"name":"toprank-radar","flag":"--toprank-radar","bin":"toprank-radar"}
22
+ ]
23
+ }