@hit-sudomaker/ccw 0.4.0 → 0.4.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/dist/programs.js CHANGED
@@ -1,18 +1,17 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import path from 'node:path';
3
3
  import { knownTitle } from './titles.js';
4
- import { officeIntegration } from './management-catalog.js';
4
+ import { OFFICECLI_REPO_SLUG, officeIntegration } from './management-catalog.js';
5
5
  import { errorCode, isObject, succeeded } from './machine.js';
6
- import { cancelled, claudeEnvironment, claudeRunning, success } from './model.js';
7
- import { npmInstallArgs, npmUninstallArgs, NPM_OFFICIAL, resolveNpmView } from './npm-registry.js';
8
- import { channelCanPinVersion, containsPath, freezeNpmScope, freezeProgramScope, identifyProgramChannel, maintainProgramChannel, npmBinary, npmGlobalRoot, npmScopeArgs, npmVersion, officeBinary, PROGRAM_PACKAGES, programPackageAbsent, removeProgramChannel, samePath, } from './program-channels.js';
6
+ import { cancelled, claudeEnvironment, claudeRunning, success, userBinary } from './model.js';
7
+ import { isExactVersion, npmInstallArgs, npmUninstallArgs, NPM_OFFICIAL, resolveNpmView } from './npm-registry.js';
8
+ import { channelCanPinVersion, containsPath, freezeNpmScope, freezeProgramScope, identifyProgramChannel, maintainProgramChannel, npmBinary, npmGlobalRoot, npmScriptFlags, npmScopeArgs, npmVersion, officeBinary, PROGRAM_PACKAGES, programPackageAbsent, removeProgramChannel, samePath, } from './program-channels.js';
9
+ import { installScratch } from './storage.js';
9
10
  export async function programs(ctx, kind) {
10
11
  const values = new Map();
11
12
  const problems = [];
12
13
  const canonicalPaths = [];
13
- const native = kind === 'claude'
14
- ? path.join(ctx.home, '.local/bin', ctx.platform === 'win32' ? 'claude.exe' : 'claude')
15
- : officeBinary(ctx);
14
+ const native = kind === 'claude' ? userBinary(ctx, 'claude') : officeBinary(ctx);
16
15
  const add = (value) => values.set(`${kind}:${value.channel}:${value.binary}`, value);
17
16
  try {
18
17
  const version = await npmVersion(ctx, PROGRAM_PACKAGES[kind]);
@@ -240,7 +239,7 @@ async function claudeVersion(ctx, binary) {
240
239
  return !output.failed && output.code === 0 ? (version ?? null) : null;
241
240
  }
242
241
  function exactVersion(value) {
243
- return typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value) ? value : null;
242
+ return isExactVersion(value) ? value : null;
244
243
  }
245
244
  async function stableClaudeVersion(ctx) {
246
245
  const release = await resolveNpmView(ctx.machine, `${PROGRAM_PACKAGES.claude}@stable`, 'version', exactVersion);
@@ -286,7 +285,7 @@ async function prepareClaudeInstall(ctx) {
286
285
  let cmdStamp;
287
286
  let isCmdFailed = false;
288
287
  let installerCleanup;
289
- const native = path.join(ctx.home, '.local/bin', ctx.platform === 'win32' ? 'claude.exe' : 'claude');
288
+ const native = userBinary(ctx, 'claude');
290
289
  try {
291
290
  npmScope = await freezeNpmScope(ctx);
292
291
  }
@@ -324,6 +323,143 @@ async function prepareClaudeInstall(ctx) {
324
323
  stamp = await ctx.machine.treeStamp(binary);
325
324
  isComplete = true;
326
325
  };
326
+ // 五段顺次落差推进;段守卫兼作续办重入点
327
+ /** npm 首装段:复核空机与 npm 槽位后落包,留存清单与二进制指纹供后续段核对 */
328
+ const installViaNpm = async (report) => {
329
+ if (stage !== 'npm')
330
+ return;
331
+ const before = await programs(ctx, 'claude');
332
+ if (before.values.size)
333
+ throw new Error('program-changed');
334
+ if (before.problems.length)
335
+ throw new Error('installation-state-unconfirmed');
336
+ await npmScope?.verify();
337
+ stage = 'npm-confirm';
338
+ report({ state: 'kept', code: 'npm-install-started' });
339
+ if (npmRoot === undefined)
340
+ return;
341
+ try {
342
+ const args = npmInstallArgs([
343
+ 'install',
344
+ '-g',
345
+ ...npmScopeArgs(ctx, npmRoot),
346
+ ...npmScriptFlags('claude'),
347
+ `${PROGRAM_PACKAGES.claude}@${targetVersion}`,
348
+ ], targetRegistry);
349
+ success(await ctx.machine.npm(args), 'npm-install-failed');
350
+ report({ state: 'done', code: 'package-command-completed' });
351
+ }
352
+ catch (error) {
353
+ if (errorCode(error) === 'npm-changed')
354
+ throw error;
355
+ npmFailure = errorCode(error);
356
+ }
357
+ const manifest = path.join(npmRoot, PROGRAM_PACKAGES.claude, 'package.json');
358
+ try {
359
+ const manifestStamp = await ctx.machine.treeStamp(manifest);
360
+ if (manifestStamp === null)
361
+ npmSnapshot = { manifestStamp };
362
+ else {
363
+ const file = await npmBinary(ctx, 'claude', npmRoot);
364
+ npmSnapshot = { manifestStamp, binary: { file, stamp: await ctx.machine.treeStamp(file) } };
365
+ }
366
+ }
367
+ catch (error) {
368
+ throw new Error('program-installation-unconfirmed', { cause: error });
369
+ }
370
+ };
371
+ /** npm 确认段:核对指纹并验收;非 Windows 无备选渠道,失败即终局 */
372
+ const confirmNpmInstallation = async (report, signal) => {
373
+ if (stage !== 'npm-confirm')
374
+ return;
375
+ await npmScope?.verify();
376
+ await verifyNpmSnapshot();
377
+ const installed = await installedClaude(ctx, 'npm', targetVersion);
378
+ if (installed !== undefined) {
379
+ await confirm(installed);
380
+ report({ state: 'done', code: 'program-ready', detail: `npm · ${targetVersion}` });
381
+ cancelled(signal);
382
+ return;
383
+ }
384
+ cancelled(signal);
385
+ npmFailure ??= 'program-not-ready';
386
+ report({ state: 'kept', code: npmFailure });
387
+ if (ctx.platform !== 'win32')
388
+ throw new Error(npmFailure);
389
+ stage = 'cleanup';
390
+ };
391
+ /** 失败清理段:仅清本次目标版本的 npm 残留,清毕转入 CMD 备选 */
392
+ const cleanupFailedNpmInstall = async (report) => {
393
+ if (stage !== 'cleanup')
394
+ return;
395
+ await npmScope?.verify();
396
+ if (!isCleanupCompleted)
397
+ await verifyNpmSnapshot();
398
+ const remainder = await npmVersion(ctx, PROGRAM_PACKAGES.claude, npmRoot);
399
+ if (remainder !== null) {
400
+ if (remainder !== targetVersion || isCleanupCompleted)
401
+ throw new Error('program-changed');
402
+ success(await ctx.machine.npm(npmUninstallArgs(['uninstall', '-g', ...npmScopeArgs(ctx, npmRoot), PROGRAM_PACKAGES.claude])), 'failed-install-cleanup-failed');
403
+ isCleanupCompleted = true;
404
+ if ((await npmVersion(ctx, PROGRAM_PACKAGES.claude, npmRoot)) !== null)
405
+ throw new Error('failed-install-cleanup-failed');
406
+ report({ state: 'kept', code: 'failed-install-cleaned' });
407
+ }
408
+ stage = 'cmd';
409
+ };
410
+ /** CMD 备选段:拉取官方安装脚本到一次性目录执行,目录即用即清 */
411
+ const installViaCmd = async (report, signal) => {
412
+ if (stage !== 'cmd')
413
+ return;
414
+ const current = await programs(ctx, 'claude');
415
+ if (current.values.size)
416
+ throw new Error('program-changed');
417
+ if (current.problems.length)
418
+ throw new Error('installation-state-unconfirmed');
419
+ cancelled(signal);
420
+ report({ state: 'kept', code: 'cmd-install-started' });
421
+ const script = await ctx.machine.fetchText('https://claude.ai/install.cmd');
422
+ if (/^\s*</.test(script) || !script.trim())
423
+ throw new Error('installer-unavailable');
424
+ const directory = installScratch(ctx, `claude-${randomUUID()}`);
425
+ const file = path.join(directory, 'install.cmd');
426
+ if (!(await ctx.machine.initialize(file, script)))
427
+ throw new Error('installer-conflict');
428
+ installerCleanup = { directory };
429
+ try {
430
+ cancelled(signal);
431
+ stage = 'cmd-confirm';
432
+ const result = await ctx.machine.execute('cmd.exe', ['/d', '/v:off', '/s', '/c', '.\\install.cmd', targetVersion], { env: claudeEnvironment(ctx), cwd: directory });
433
+ isCmdFailed = !succeeded(result);
434
+ if (!isCmdFailed)
435
+ report({ state: 'done', code: 'package-command-completed' });
436
+ try {
437
+ cmdStamp = await ctx.machine.treeStamp(native);
438
+ }
439
+ catch (error) {
440
+ throw new Error('program-installation-unconfirmed', { cause: error });
441
+ }
442
+ }
443
+ finally {
444
+ await cleanInstaller();
445
+ }
446
+ };
447
+ /** CMD 确认段:核对原生位指纹并验收 */
448
+ const confirmCmdInstallation = async (report, signal) => {
449
+ if (stage !== 'cmd-confirm')
450
+ return;
451
+ await cleanInstaller();
452
+ if (cmdStamp === undefined)
453
+ throw new Error('program-installation-unconfirmed');
454
+ if ((await ctx.machine.treeStamp(native)) !== cmdStamp)
455
+ throw new Error('program-changed');
456
+ const installed = await installedClaude(ctx, 'native', targetVersion);
457
+ if (installed === undefined)
458
+ throw new Error(isCmdFailed ? 'cmd-install-failed' : 'program-not-ready');
459
+ await confirm(installed);
460
+ report({ state: 'done', code: 'program-ready', detail: `CMD · ${targetVersion}` });
461
+ cancelled(signal);
462
+ };
327
463
  const operation = {
328
464
  targetVersion,
329
465
  targetRegistry,
@@ -342,129 +478,11 @@ async function prepareClaudeInstall(ctx) {
342
478
  },
343
479
  async run(report, signal) {
344
480
  cancelled(signal);
345
- if (stage === 'npm') {
346
- const before = await programs(ctx, 'claude');
347
- if (before.values.size)
348
- throw new Error('program-changed');
349
- if (before.problems.length)
350
- throw new Error('installation-state-unconfirmed');
351
- await npmScope?.verify();
352
- stage = 'npm-confirm';
353
- report({ state: 'kept', code: 'npm-install-started' });
354
- if (npmRoot !== undefined) {
355
- try {
356
- const args = npmInstallArgs([
357
- 'install',
358
- '-g',
359
- ...npmScopeArgs(ctx, npmRoot),
360
- '--ignore-scripts=false',
361
- `--allow-scripts=${PROGRAM_PACKAGES.claude}`,
362
- '--include=optional',
363
- `${PROGRAM_PACKAGES.claude}@${targetVersion}`,
364
- ], targetRegistry);
365
- success(await ctx.machine.npm(args), 'npm-install-failed');
366
- report({ state: 'done', code: 'package-command-completed' });
367
- }
368
- catch (error) {
369
- if (errorCode(error) === 'npm-changed')
370
- throw error;
371
- npmFailure = errorCode(error);
372
- }
373
- const manifest = path.join(npmRoot, PROGRAM_PACKAGES.claude, 'package.json');
374
- try {
375
- const manifestStamp = await ctx.machine.treeStamp(manifest);
376
- if (manifestStamp === null)
377
- npmSnapshot = { manifestStamp };
378
- else {
379
- const file = await npmBinary(ctx, 'claude', npmRoot);
380
- npmSnapshot = { manifestStamp, binary: { file, stamp: await ctx.machine.treeStamp(file) } };
381
- }
382
- }
383
- catch (error) {
384
- throw new Error('program-installation-unconfirmed', { cause: error });
385
- }
386
- }
387
- }
388
- if (stage === 'npm-confirm') {
389
- await npmScope?.verify();
390
- await verifyNpmSnapshot();
391
- const installed = await installedClaude(ctx, 'npm', targetVersion);
392
- if (installed !== undefined) {
393
- await confirm(installed);
394
- report({ state: 'done', code: 'program-ready', detail: `npm · ${targetVersion}` });
395
- cancelled(signal);
396
- return;
397
- }
398
- cancelled(signal);
399
- npmFailure ??= 'program-not-ready';
400
- report({ state: 'kept', code: npmFailure });
401
- if (ctx.platform !== 'win32')
402
- throw new Error(npmFailure);
403
- stage = 'cleanup';
404
- }
405
- if (stage === 'cleanup') {
406
- await npmScope?.verify();
407
- if (!isCleanupCompleted)
408
- await verifyNpmSnapshot();
409
- const remainder = await npmVersion(ctx, PROGRAM_PACKAGES.claude, npmRoot);
410
- if (remainder !== null) {
411
- if (remainder !== targetVersion || isCleanupCompleted)
412
- throw new Error('program-changed');
413
- success(await ctx.machine.npm(npmUninstallArgs(['uninstall', '-g', ...npmScopeArgs(ctx, npmRoot), PROGRAM_PACKAGES.claude])), 'failed-install-cleanup-failed');
414
- isCleanupCompleted = true;
415
- if ((await npmVersion(ctx, PROGRAM_PACKAGES.claude, npmRoot)) !== null)
416
- throw new Error('failed-install-cleanup-failed');
417
- report({ state: 'kept', code: 'failed-install-cleaned' });
418
- }
419
- stage = 'cmd';
420
- }
421
- if (stage === 'cmd') {
422
- const current = await programs(ctx, 'claude');
423
- if (current.values.size)
424
- throw new Error('program-changed');
425
- if (current.problems.length)
426
- throw new Error('installation-state-unconfirmed');
427
- cancelled(signal);
428
- report({ state: 'kept', code: 'cmd-install-started' });
429
- const script = await ctx.machine.fetchText('https://claude.ai/install.cmd');
430
- if (/^\s*</.test(script) || !script.trim())
431
- throw new Error('installer-unavailable');
432
- const directory = path.join(ctx.storage, `install-claude-${randomUUID()}`);
433
- const file = path.join(directory, 'install.cmd');
434
- if (!(await ctx.machine.initialize(file, script)))
435
- throw new Error('installer-conflict');
436
- installerCleanup = { directory };
437
- try {
438
- cancelled(signal);
439
- stage = 'cmd-confirm';
440
- const result = await ctx.machine.execute('cmd.exe', ['/d', '/v:off', '/s', '/c', '.\\install.cmd', targetVersion], { env: claudeEnvironment(ctx), cwd: directory });
441
- isCmdFailed = !succeeded(result);
442
- if (!isCmdFailed)
443
- report({ state: 'done', code: 'package-command-completed' });
444
- try {
445
- cmdStamp = await ctx.machine.treeStamp(native);
446
- }
447
- catch (error) {
448
- throw new Error('program-installation-unconfirmed', { cause: error });
449
- }
450
- }
451
- finally {
452
- await cleanInstaller();
453
- }
454
- }
455
- if (stage === 'cmd-confirm') {
456
- await cleanInstaller();
457
- if (cmdStamp === undefined)
458
- throw new Error('program-installation-unconfirmed');
459
- if ((await ctx.machine.treeStamp(native)) !== cmdStamp)
460
- throw new Error('program-changed');
461
- const installed = await installedClaude(ctx, 'native', targetVersion);
462
- if (installed === undefined)
463
- throw new Error(isCmdFailed ? 'cmd-install-failed' : 'program-not-ready');
464
- await confirm(installed);
465
- report({ state: 'done', code: 'program-ready', detail: `CMD · ${targetVersion}` });
466
- cancelled(signal);
467
- }
481
+ await installViaNpm(report);
482
+ await confirmNpmInstallation(report, signal);
483
+ await cleanupFailedNpmInstall(report);
484
+ await installViaCmd(report, signal);
485
+ await confirmCmdInstallation(report, signal);
468
486
  },
469
487
  remaining: () => (isComplete ? undefined : operation),
470
488
  async verify() {
@@ -526,7 +544,7 @@ async function prepareOfficeNative(ctx, selection, program) {
526
544
  throw new Error('program-changed');
527
545
  const updates = await officeUpdates(ctx, binary);
528
546
  const assetName = officeAsset(ctx);
529
- const release = JSON.parse(await ctx.machine.fetchText('https://api.github.com/repos/iOfficeAI/OfficeCLI/releases/latest'));
547
+ const release = JSON.parse(await ctx.machine.fetchText(`https://api.github.com/repos/${OFFICECLI_REPO_SLUG}/releases/latest`));
530
548
  if (!isObject(release) ||
531
549
  release.draft !== false ||
532
550
  release.prerelease !== false ||
@@ -535,7 +553,7 @@ async function prepareOfficeNative(ctx, selection, program) {
535
553
  !Array.isArray(release.assets))
536
554
  throw new Error('invalid-release');
537
555
  const targetVersion = release.tag_name.slice(1);
538
- const baseUrl = `https://github.com/iOfficeAI/OfficeCLI/releases/download/${release.tag_name}/`;
556
+ const baseUrl = `https://github.com/${OFFICECLI_REPO_SLUG}/releases/download/${release.tag_name}/`;
539
557
  const assets = release.assets.filter(isObject);
540
558
  const asset = assets.find(value => value.name === assetName);
541
559
  const manifest = assets.find(value => value.name === 'SHA256SUMS');
@@ -627,16 +645,19 @@ async function prepareOfficeNative(ctx, selection, program) {
627
645
  };
628
646
  return operation;
629
647
  }
648
+ /** Claude 变更前的进程复核:枚举失败保留未知,不臆断未运行 */
649
+ async function ensureClaudeNotRunning(ctx) {
650
+ const isClaudeActive = await claudeRunning(ctx.machine);
651
+ if (isClaudeActive !== false)
652
+ throw new Error(isClaudeActive ? 'claude-running' : 'process-state-unconfirmed');
653
+ }
630
654
  async function prepareProgramRemoval(ctx, kind, program, shouldPreserveData = true) {
631
655
  if (!program)
632
656
  throw new Error('program-not-installed');
633
657
  if (program.channel === 'manual')
634
658
  throw new Error('channel-not-supported');
635
- if (kind === 'claude') {
636
- const isClaudeActive = await claudeRunning(ctx.machine);
637
- if (isClaudeActive !== false)
638
- throw new Error(isClaudeActive ? 'claude-running' : 'process-state-unconfirmed');
639
- }
659
+ if (kind === 'claude')
660
+ await ensureClaudeNotRunning(ctx);
640
661
  const before = await ctx.machine.treeStamp(program.binary);
641
662
  const scope = await freezeProgramScope(ctx, program);
642
663
  if (kind === 'officecli' &&
@@ -687,11 +708,8 @@ async function prepareProgramRemoval(ctx, kind, program, shouldPreserveData = tr
687
708
  },
688
709
  async run(report, signal) {
689
710
  cancelled(signal);
690
- if (kind === 'claude') {
691
- const isClaudeActive = await claudeRunning(ctx.machine);
692
- if (isClaudeActive !== false)
693
- throw new Error(isClaudeActive ? 'claude-running' : 'process-state-unconfirmed');
694
- }
711
+ if (kind === 'claude')
712
+ await ensureClaudeNotRunning(ctx);
695
713
  if (removals.length) {
696
714
  for (const target of removals) {
697
715
  if (target.isDone) {
@@ -766,7 +784,8 @@ async function prepareProgramRemoval(ctx, kind, program, shouldPreserveData = tr
766
784
  };
767
785
  return operation;
768
786
  }
769
- function compareVersions(left, right) {
787
+ /** 三段语义化版本比较:正值为左更新;ccline 的降级门共用 */
788
+ export function compareVersions(left, right) {
770
789
  const a = left.split('.').map(Number);
771
790
  const b = right.split('.').map(Number);
772
791
  for (let index = 0; index < 3; index++) {
@@ -1,6 +1,7 @@
1
1
  import { FETCH_BYTES_TIMEOUT_MS, FETCH_TEXT_TIMEOUT_MS, GIT_COMMAND_TIMEOUT_MS, READ_COMMAND_TIMEOUT_MS, SOURCE_TIMEOUT_MS, } from './machine.js';
2
2
  import { cancelled } from './model.js';
3
- /** 统一只读阶段的时限、取消和进度;共享读取仅限单次检查,准备与执行不用缓存 */
3
+ /** 统一只读阶段的时限、取消和进度;共享读取仅限单次检查,准备与执行不用缓存。
4
+ * 未覆写的 Machine 方法原样透传,不获本层的时限与取消 */
4
5
  export function createReadMachine(machine, current, options = {}) {
5
6
  const shared = (load) => {
6
7
  const values = new Map();
@@ -19,13 +20,10 @@ export function createReadMachine(machine, current, options = {}) {
19
20
  const scope = current();
20
21
  cancelled(scope?.signal);
21
22
  try {
22
- const result = await work(scope?.signal);
23
- cancelled(scope?.signal);
24
- return result;
23
+ return await work(scope?.signal);
25
24
  }
26
- catch (error) {
25
+ finally {
27
26
  cancelled(scope?.signal);
28
- throw error;
29
27
  }
30
28
  };
31
29
  const command = async (stage, timeoutMs, options, work) => {
@@ -46,17 +44,14 @@ export function createReadMachine(machine, current, options = {}) {
46
44
  timeoutMs: Math.max(1, Math.ceil(Math.min(options?.timeoutMs ?? timeoutMs, timeoutMs, remainingMs))),
47
45
  ...(signal ? { signal } : {}),
48
46
  });
49
- cancelled(signal);
50
47
  if (scope.deadlineMs !== undefined && performance.now() >= scope.deadlineMs)
51
48
  throw new Error('inspection-timeout');
52
49
  return result;
53
50
  }
54
- catch (error) {
51
+ finally {
55
52
  cancelled(signal);
56
- throw error;
57
53
  }
58
54
  };
59
- // 整体复用原 machine 的方法,只覆写需统一时限、取消或共享的读取面;新增 Machine 方法无需在此补转发
60
55
  return {
61
56
  ...machine,
62
57
  read: shared(file => read(() => machine.read(file))),