@hit-sudomaker/ccw 0.4.1 → 0.5.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.
@@ -0,0 +1,155 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { step } from './work.js';
3
+ import { cancelled, commandReceipt } from './model.js';
4
+ import { errorCode } from './machine.js';
5
+ import { npmVersion, verifyNpmScope } from './program-channels.js';
6
+ import { npmInstallArgs, npmUninstallArgs } from './npm-registry.js';
7
+ /**
8
+ * 准备移除摘要匹配的程序文件
9
+ *
10
+ * @param target - 路径与树摘要,null 表示原本不存在
11
+ * @param changes - 预览说明,可为空数组
12
+ * @returns 目标缺失即完成,摘要变化则以 program-changed 阻止移除
13
+ */
14
+ export function removeProgramFile(ctx, target, changes) {
15
+ const { file, before } = target;
16
+ return step(changes, async (fact) => {
17
+ const current = await ctx.machine.treeStamp(file);
18
+ if (current === null)
19
+ return {
20
+ state: 'complete',
21
+ effects: fact.dispatched ? [{ state: 'done', code: 'program-removed', detail: file }] : [],
22
+ };
23
+ if (fact.confirmed || current !== before)
24
+ return { state: 'blocked', problem: 'program-changed' };
25
+ return { state: 'ready' };
26
+ }, before === null
27
+ ? undefined
28
+ : async () => {
29
+ await ctx.effects.removeTree(file, before);
30
+ return { receipt: { kind: 'returned', failure: null } };
31
+ });
32
+ }
33
+ /**
34
+ * 准备按摘要替换程序文件
35
+ *
36
+ * @param target - 路径、原指纹、目标 SHA-256 和字节;bytes 为 null 时仅复用匹配的原件
37
+ * @param changes - 预览说明,可为空数组
38
+ * @returns 按最终摘要确认的替换步骤;拒绝覆盖准备后变化的目标
39
+ * @remarks 写入前复核候选字节的摘要
40
+ */
41
+ export function deployProgram(ctx, target, changes) {
42
+ return step(changes, async (fact) => {
43
+ const current = await ctx.machine.fingerprint(target.binary);
44
+ if (current === target.digest && (target.bytes === null || fact.dispatched))
45
+ return {
46
+ state: 'complete',
47
+ effects: [
48
+ {
49
+ state: target.bytes === null ? 'kept' : 'done',
50
+ code: target.bytes === null ? 'program-kept' : 'program-file-ready',
51
+ },
52
+ ],
53
+ };
54
+ if (fact.dispatched || current !== target.before)
55
+ return { state: 'blocked', problem: fact.receipt?.failure ?? 'program-changed' };
56
+ return { state: 'ready' };
57
+ }, async () => {
58
+ if (!target.bytes || createHash('sha256').update(target.bytes).digest('hex') !== target.digest)
59
+ throw new Error('release-checksum-mismatch');
60
+ await ctx.effects.replaceFile(target.binary, target.bytes, target.before, true);
61
+ return { receipt: { kind: 'returned', failure: null } };
62
+ });
63
+ }
64
+ /**
65
+ * 准备将程序目录加入用户 PATH
66
+ *
67
+ * @param directory - 非根绝对目录,不得包含换行或空字符
68
+ * @returns 已包含时直接完成,否则写入后核验
69
+ */
70
+ export function programPath(ctx, directory, changes) {
71
+ return step(changes, async () => (await ctx.machine.userPathContains(directory))
72
+ ? { state: 'complete', effects: [{ state: 'done', code: 'program-user-path' }] }
73
+ : { state: 'ready' }, async () => {
74
+ await ctx.effects.ensureUserPath(directory);
75
+ return { receipt: { kind: 'returned', failure: null } };
76
+ });
77
+ }
78
+ /**
79
+ * 准备绑定 npm 身份、范围和来源的程序变更
80
+ *
81
+ * @param target - version 为 null 表示卸载;readBinary 重读安装入口,assertReady 检查工具前置条件
82
+ * @returns 延迟步骤及当前入口读取器
83
+ * @remarks 每次检查和写入前复核 npm 身份与范围,写入前还复核原版本与指纹
84
+ * 安装使用冻结来源与精确版本;已有目标版本和入口时保留
85
+ * 派发后按版本及捕获指纹确认结果;回执丢失仍捕获,捕获失败不算完成
86
+ */
87
+ export function npmProgram(ctx, target, changes) {
88
+ let installedBinary = target.binary;
89
+ let captured;
90
+ const operation = step(changes, async (fact) => {
91
+ await verifyNpmScope(ctx, target.scope);
92
+ await target.assertReady?.();
93
+ const version = await npmVersion(ctx, target.name, target.scope.npmRoot);
94
+ if (fact.dispatched && target.readBinary && version !== null)
95
+ installedBinary = await target.readBinary();
96
+ const stamp = await ctx.machine.fingerprint(installedBinary);
97
+ if (fact.dispatched) {
98
+ if (captured === undefined)
99
+ return { state: 'blocked', problem: fact.receipt?.failure ?? 'program-installation-unconfirmed' };
100
+ if (version === target.version &&
101
+ (target.version === null ? stamp === null : stamp !== null && stamp === captured))
102
+ return {
103
+ state: 'complete',
104
+ effects: [{ state: 'done', code: target.version === null ? 'program-removed' : 'program-ready' }],
105
+ };
106
+ return {
107
+ state: 'blocked',
108
+ problem: fact.receipt?.failure ??
109
+ (stamp !== captured
110
+ ? 'program-changed'
111
+ : target.version === null
112
+ ? 'program-removal-unconfirmed'
113
+ : 'program-not-ready'),
114
+ };
115
+ }
116
+ if (version !== target.beforeVersion || stamp !== target.beforeStamp)
117
+ return { state: 'blocked', problem: 'program-changed' };
118
+ if (target.version !== null && version === target.version && stamp !== null)
119
+ return {
120
+ state: 'complete',
121
+ effects: [{ state: 'kept', code: 'program-kept' }],
122
+ };
123
+ return { state: 'ready' };
124
+ }, async (signal, verify) => {
125
+ cancelled(signal);
126
+ await verifyNpmScope(ctx, target.scope);
127
+ await target.assertReady?.();
128
+ if ((await npmVersion(ctx, target.name, target.scope.npmRoot)) !== target.beforeVersion ||
129
+ (await ctx.machine.fingerprint(target.binary)) !== target.beforeStamp)
130
+ throw new Error('program-changed');
131
+ let receipt;
132
+ try {
133
+ const result = await ctx.effects.npm(target.version === null
134
+ ? npmUninstallArgs(['uninstall', '-g', ...target.scope.args, '--ignore-scripts', target.name])
135
+ : npmInstallArgs(['install', '-g', ...target.scope.args, ...target.args, target.name + '@' + target.version], target.registry));
136
+ receipt = commandReceipt(result, target.version === null ? 'npm-uninstall-failed' : 'npm-install-failed');
137
+ }
138
+ catch (error) {
139
+ receipt = { kind: 'unknown', failure: errorCode(error) };
140
+ }
141
+ try {
142
+ await verify(async () => {
143
+ if (target.readBinary && target.version !== null)
144
+ installedBinary = await target.readBinary();
145
+ captured = await ctx.machine.fingerprint(installedBinary);
146
+ });
147
+ }
148
+ catch {
149
+ // 捕获失败保留未知状态,不能用空指纹伪装已确认的卸载结果
150
+ captured = undefined;
151
+ }
152
+ return { receipt };
153
+ });
154
+ return { ...operation, binary: () => installedBinary };
155
+ }
@@ -1,11 +1,31 @@
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
- /** 统一只读阶段的时限、取消和进度;共享读取仅限单次检查,准备与执行不用缓存。
4
- * 未覆写的 Machine 方法原样透传,不获本层的时限与取消 */
3
+ import { SKILLS_CLI } from './management-catalog.js';
4
+ /**
5
+ * 限定观察命令,管理读取预算、取消和准备进度
6
+ *
7
+ * @param current - 当前作用域,deadlineMs 以 performance.now() 为基准
8
+ * @param options - shouldShareReads 按原始参数缓存 read、entries、realpath、locate 的 Promise
9
+ * @returns 读取包装;缓存值克隆返回,失败也缓存,每次检查须新建实例
10
+ * @throws 取消为 cancelled,非观察命令为 read-command-not-allowed;底层及进度异常原样传播
11
+ * @remarks 作用域预算仅限制命令和远端读取;耗尽使用 timeoutCode,默认 inspection-timeout
12
+ * 所有读取前后均检查取消,缓存命中也不例外
13
+ */
5
14
  export function createReadMachine(machine, current, options = {}) {
15
+ const read = async (work, cancellation) => {
16
+ const scope = current();
17
+ const signal = cancellation && scope?.signal ? AbortSignal.any([cancellation, scope.signal]) : (cancellation ?? scope?.signal);
18
+ cancelled(signal);
19
+ try {
20
+ return await work(signal);
21
+ }
22
+ finally {
23
+ cancelled(signal);
24
+ }
25
+ };
6
26
  const shared = (load) => {
7
27
  const values = new Map();
8
- return async (key) => {
28
+ return (key) => read(async () => {
9
29
  if (!options.shouldShareReads)
10
30
  return load(key);
11
31
  let value = values.get(key);
@@ -14,57 +34,93 @@ export function createReadMachine(machine, current, options = {}) {
14
34
  values.set(key, value);
15
35
  }
16
36
  return structuredClone(await value);
17
- };
18
- };
19
- const read = async (work) => {
20
- const scope = current();
21
- cancelled(scope?.signal);
22
- try {
23
- return await work(scope?.signal);
24
- }
25
- finally {
26
- cancelled(scope?.signal);
27
- }
37
+ });
28
38
  };
29
39
  const command = async (stage, timeoutMs, options, work) => {
30
40
  const scope = current();
31
41
  if (!scope)
32
42
  return work(options ?? {});
33
- cancelled(scope.signal);
34
- scope.report?.(stage);
35
- const remainingMs = scope.deadlineMs === undefined ? Infinity : scope.deadlineMs - performance.now();
36
- if (remainingMs <= 0)
37
- throw new Error('inspection-timeout');
38
- const signal = options?.signal && scope.signal
39
- ? AbortSignal.any([options.signal, scope.signal])
40
- : (options?.signal ?? scope.signal);
41
- try {
43
+ if (stage === 'inspect')
44
+ timeoutMs = scope.commandTimeoutMs ?? timeoutMs;
45
+ return read(async (signal) => {
46
+ scope.report?.(stage);
47
+ const remainingMs = scope.deadlineMs === undefined ? Infinity : scope.deadlineMs - performance.now();
48
+ if (remainingMs <= 0)
49
+ throw new Error(scope.timeoutCode ?? 'inspection-timeout');
42
50
  const result = await work({
43
51
  ...options,
44
52
  timeoutMs: Math.max(1, Math.ceil(Math.min(options?.timeoutMs ?? timeoutMs, timeoutMs, remainingMs))),
45
53
  ...(signal ? { signal } : {}),
46
54
  });
47
55
  if (scope.deadlineMs !== undefined && performance.now() >= scope.deadlineMs)
48
- throw new Error('inspection-timeout');
56
+ throw new Error(scope.timeoutCode ?? 'inspection-timeout');
49
57
  return result;
50
- }
51
- finally {
52
- cancelled(signal);
53
- }
58
+ }, options?.signal);
54
59
  };
55
60
  return {
56
- ...machine,
57
- read: shared(file => read(() => machine.read(file))),
58
- entries: shared(directory => read(() => machine.entries(directory))),
59
- realpath: shared(file => read(() => machine.realpath(file))),
60
- locate: shared(name => read(() => machine.locate(name))),
61
- fingerprint: (file, signal) => read(active => machine.fingerprint(file, active ?? signal)),
62
- treeStamp: (file, signal) => read(active => machine.treeStamp(file, active ?? signal)),
63
- processes: signal => read(active => machine.processes(active ?? signal)),
64
- npm: (args, options) => command(args[0] === 'view' ? 'metadata' : 'inspect', READ_COMMAND_TIMEOUT_MS, options, bounded => machine.npm(args, bounded)),
65
- execute: (file, args, options) => command(file === 'git' ? 'metadata' : 'inspect', file === 'git' ? GIT_COMMAND_TIMEOUT_MS : READ_COMMAND_TIMEOUT_MS, options, bounded => machine.execute(file, args, bounded)),
61
+ npmIdentity: () => read(() => machine.npmIdentity()),
62
+ userPathContains: (directory, options) => command('inspect', READ_COMMAND_TIMEOUT_MS, options, bounded => machine.userPathContains(directory, bounded)),
63
+ read: shared(file => machine.read(file)),
64
+ entries: shared(directory => machine.entries(directory)),
65
+ realpath: shared(file => machine.realpath(file)),
66
+ locate: shared(name => machine.locate(name)),
67
+ fingerprint: (file, signal) => read(active => machine.fingerprint(file, active), signal),
68
+ treeStamp: (file, signal) => read(active => machine.treeStamp(file, active), signal),
69
+ processes: options => command('inspect', READ_COMMAND_TIMEOUT_MS, options, bounded => machine.processes(bounded)),
70
+ npm: async (args, options) => {
71
+ if (!isNpmObservation(args))
72
+ throw new Error('read-command-not-allowed');
73
+ return command(args[0] === 'exec' ? 'source' : args[0] === 'view' ? 'metadata' : 'inspect', args[0] === 'exec' ? SOURCE_TIMEOUT_MS : READ_COMMAND_TIMEOUT_MS, options, bounded => machine.npm(args, bounded));
74
+ },
75
+ execute: async (file, args, options) => {
76
+ if (!isObservationCommand(file, args))
77
+ throw new Error('read-command-not-allowed');
78
+ return command(file === 'git' ? 'metadata' : 'inspect', file === 'git' ? GIT_COMMAND_TIMEOUT_MS : READ_COMMAND_TIMEOUT_MS, options, bounded => machine.execute(file, args, bounded));
79
+ },
66
80
  fetchText: (url, options) => command('metadata', FETCH_TEXT_TIMEOUT_MS, options, bounded => machine.fetchText(url, bounded)),
67
81
  fetchBytes: (url, options) => command('download', FETCH_BYTES_TIMEOUT_MS, options, bounded => machine.fetchBytes(url, bounded)),
68
82
  source: (repository, revision, folder, options) => command('source', SOURCE_TIMEOUT_MS, options, bounded => machine.source(repository, revision, folder, bounded)),
69
83
  };
70
84
  }
85
+ /** 只允许固定观察命令;其他外部命令须通过执行能力派发 */
86
+ function isObservationCommand(file, args) {
87
+ const name = file
88
+ .split(/[\\/]/)
89
+ .at(-1)
90
+ ?.toLowerCase()
91
+ .replace(/\.exe$/, '');
92
+ const nodeEntry = name === 'node' &&
93
+ args[0]?.endsWith('.js') &&
94
+ args[0].replaceAll('\\', '/').toLowerCase().includes('/@anthropic-ai/claude-code/');
95
+ const actual = nodeEntry ? args.slice(1) : args;
96
+ const knownProgram = nodeEntry || ['claude', 'officecli', 'ccline', 'git'].some(program => program === name);
97
+ if (knownProgram && actual.length === 1 && (actual[0] === '--version' || actual[0] === '--help'))
98
+ return true;
99
+ if ((name === 'claude' || nodeEntry) &&
100
+ actual.length === 3 &&
101
+ actual[0] === 'auth' &&
102
+ actual[1] === 'status' &&
103
+ actual[2] === '--json')
104
+ return true;
105
+ if (name === 'git')
106
+ return (args.length === 3 && args[0] === 'ls-remote' && /^https:\/\/[^\s]+$/.test(args[1] ?? '') && args[2] === 'HEAD');
107
+ return false;
108
+ }
109
+ function isNpmObservation(args) {
110
+ if (args[0] === 'exec') {
111
+ const [action, source, option, ...extra] = args.slice(SKILLS_CLI.length);
112
+ return (SKILLS_CLI.every((part, index) => args[index] === part) &&
113
+ action === 'a' &&
114
+ source !== undefined &&
115
+ source !== '' &&
116
+ !source.startsWith('-') &&
117
+ option === '--list' &&
118
+ extra.length === 0);
119
+ }
120
+ if (args[0] === 'config')
121
+ return (args.length === 3 &&
122
+ args[1] === 'get' &&
123
+ (args[2] === 'registry' || /^@[a-z0-9._-]+:registry$/i.test(args[2] ?? '')));
124
+ return ((args[0] === 'view' || args[0] === 'ls' || args[0] === 'root') &&
125
+ !args.some(arg => arg === '--' || /^--(?:globalconfig|userconfig|script-shell|cache|logfile)(?:=|$)/.test(arg)));
126
+ }