@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/main.js CHANGED
@@ -2,27 +2,32 @@
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { createCcw } from './ccw.js';
5
+ import { collectLogs } from './collect.js';
5
6
  import { createMachine, errorCode, isObject } from './machine.js';
6
7
  import { BRAND, describeInspection, HELP_TEXT, startupFailure } from './render.js';
7
8
  import { runTerminal } from './terminal.js';
8
9
  import { createTerminal } from './terminal-view.js';
10
+ /** CLI 模式清单单一出处:新增模式仍需人工同步 errors.ts 与 HELP_TEXT 的散文枚举 */
11
+ const CLI_MODES = ['--help', '--version', '--inspect', '--collect-logs'];
12
+ const CLI_MODE_VALUES = CLI_MODES;
13
+ const isMode = (value) => CLI_MODE_VALUES.includes(value);
9
14
  function parseArguments(args) {
10
15
  let mode;
11
16
  let hasDetails = false;
12
17
  for (const argument of args) {
13
18
  if (argument === '--details' && !hasDetails)
14
19
  hasDetails = true;
15
- else if ((argument === '--help' || argument === '--version' || argument === '--inspect') && mode === undefined)
20
+ else if (isMode(argument) && mode === undefined)
16
21
  mode = argument;
17
22
  else
18
23
  throw new Error('unknown-argument');
19
24
  }
20
- return mode;
25
+ return { mode, hasDetails };
21
26
  }
22
27
  async function main() {
23
- const argument = parseArguments(process.argv.slice(2));
28
+ const { mode: argument, hasDetails } = parseArguments(process.argv.slice(2));
24
29
  if (argument === '--version') {
25
- process.stdout.write(`${BRAND.version.slice(1)}\n`);
30
+ process.stdout.write(`${BRAND.versionNumber}\n`);
26
31
  return;
27
32
  }
28
33
  if (argument === '--help') {
@@ -46,7 +51,7 @@ async function main() {
46
51
  abort.abort();
47
52
  };
48
53
  const terminal = argument === undefined ? createTerminal(stop) : undefined;
49
- const ccw = createCcw({
54
+ const options = {
50
55
  machine: createMachine(process.env, process.cwd(), terminal ? work => terminal.handoff(work) : undefined),
51
56
  home,
52
57
  claudeRoot,
@@ -58,14 +63,20 @@ async function main() {
58
63
  arch: /arm64|aarch64/i.test(machineArch) ? 'arm64' : /x86_64|amd64|x64/i.test(machineArch) ? 'x64' : process.arch,
59
64
  ...(process.platform === 'linux' ? { libc } : {}),
60
65
  platform: process.platform,
61
- });
66
+ };
67
+ const ccw = createCcw(options);
62
68
  if (argument === '--inspect') {
63
69
  const view = await ccw.inspect();
64
- process.stdout.write(`${describeInspection(view)}\n`);
70
+ process.stdout.write(`${describeInspection(view, hasDetails)}\n`);
65
71
  if (view.problems.length || view.items.some(item => item.problem))
66
72
  process.exitCode = 1;
67
73
  return;
68
74
  }
75
+ if (argument === '--collect-logs') {
76
+ const collected = await collectLogs(ccw, options);
77
+ process.stdout.write(`${collected.summary}\n`);
78
+ return;
79
+ }
69
80
  if (!terminal)
70
81
  return;
71
82
  process.on('SIGINT', stop);
@@ -42,6 +42,10 @@ export const pluginSpecs = {
42
42
  exposure: 'discovered',
43
43
  },
44
44
  };
45
+ /** 技能套件目录。隐含不变量:repository 在目录内全局唯一(不与其他套件共享仓库)——
46
+ * 已装成员的套件归属与更新资格均以 repository 单字段匹配(skills.ts suiteOfRecord/memberSuite) */
47
+ /** 技能入口文件名:载荷校验、套件成员发现与随包技能读取共用 */
48
+ export const SKILL_ENTRY = 'SKILL.md';
45
49
  export const skillSuites = {
46
50
  mattpocock: {
47
51
  title: 'Matt Pocock/Skills',
@@ -85,9 +89,11 @@ export const mcpSpecs = {
85
89
  };
86
90
  /** 抑制 OfficeCLI 自更新/自动安装的固定旗标:MCP 注册模板与版本探测共用同一份事实 */
87
91
  const officeSuppressSelfUpdate = { OFFICECLI_NO_AUTO_INSTALL: '1', OFFICECLI_SKIP_UPDATE: '1' };
92
+ /** OfficeCLI 上游仓库标识:目录登记、发布/标签 API 与下载 URL 派生共用 */
93
+ export const OFFICECLI_REPO_SLUG = 'iOfficeAI/OfficeCLI';
88
94
  export const officeIntegration = {
89
95
  suppressSelfUpdate: officeSuppressSelfUpdate,
90
- skill: { repository: 'https://github.com/iOfficeAI/OfficeCLI', folder: 'skills/officecli' },
96
+ skill: { repository: `https://github.com/${OFFICECLI_REPO_SLUG}`, folder: 'skills/officecli' },
91
97
  mcp: {
92
98
  args: ['mcp'],
93
99
  env: officeSuppressSelfUpdate,
package/dist/mcp.js CHANGED
@@ -3,8 +3,10 @@ import { randomUUID } from 'node:crypto';
3
3
  import { knownTitle } from './titles.js';
4
4
  import { mcpSpecs } from './management-catalog.js';
5
5
  import { errorCode, isObject } from './machine.js';
6
- import { cancelled, editFields, json, object, removeFields, restOf, success, unchanged } from './model.js';
6
+ import { cancelled, editFields, MCP_SERVERS_KEY, readMcpServers, removeFields, restOf, success, unchanged, userBinDirectory, userBinary, } from './model.js';
7
+ import { isExactVersion } from './npm-registry.js';
7
8
  import { hasLegacyAmircPermissions, prepareLegacyAmircDetach } from './legacy-amirc.js';
9
+ import { installScratch } from './storage.js';
8
10
  const MCP_PROTOCOLS = {
9
11
  http: ['http:', 'https:'],
10
12
  'streamable-http': ['http:', 'https:'],
@@ -28,6 +30,8 @@ function validRegistration(value) {
28
30
  return false;
29
31
  }
30
32
  }
33
+ /** Serena 命令形状判定:注册身份确认与更新渠道守卫共用同一谓词 */
34
+ const isSerenaCommand = (command) => /(?:^|[\\/])serena(?:\.exe)?$/.test(command);
31
35
  /** 以本地形状证据判定注册身份:与 CCW 写入模板一致才算确认,证据不足保留原始键名;
32
36
  * 不联网、不启动程序 */
33
37
  function confirmedMcpTitle(name, registration) {
@@ -43,7 +47,7 @@ function confirmedMcpTitle(name, registration) {
43
47
  if (name === 'serena')
44
48
  return (registration.type === undefined || registration.type === 'stdio') &&
45
49
  typeof registration.command === 'string' &&
46
- /(?:^|[\\/])serena(?:\.exe)?$/.test(registration.command) &&
50
+ isSerenaCommand(registration.command) &&
47
51
  Array.isArray(registration.args) &&
48
52
  registration.args[0] === mcpSpecs.serena.registration.args[0]
49
53
  ? knownTitle('mcp:serena')
@@ -82,7 +86,7 @@ async function inspectMcp(ctx) {
82
86
  let registrations = {};
83
87
  let readProblem;
84
88
  try {
85
- registrations = object((await json(ctx.machine, ctx.stateFile)).mcpServers);
89
+ registrations = await readMcpServers(ctx);
86
90
  }
87
91
  catch (error) {
88
92
  readProblem = errorCode(error);
@@ -136,7 +140,8 @@ export async function prepareMcp(ctx, name, selection, options = {}) {
136
140
  return prepareLegacyAmircDetach(ctx);
137
141
  if (name === 'amirc')
138
142
  throw new Error('action-unavailable');
139
- const before = object((await json(ctx.machine, ctx.stateFile)).mcpServers);
143
+ const registrationsNow = () => readMcpServers(ctx);
144
+ const before = await registrationsNow();
140
145
  describe?.(confirmedMcpTitle(name, before[name]));
141
146
  const action = selection.action;
142
147
  if (!['install', 'connect', 'update', 'reinstall', 'detach'].includes(action) ||
@@ -145,7 +150,7 @@ export async function prepareMcp(ctx, name, selection, options = {}) {
145
150
  if (action === 'detach' && before[name] === undefined)
146
151
  throw new Error('no-connection');
147
152
  if (action === 'detach')
148
- return removeFields(ctx, ctx.stateFile, { [name]: before[name] }, [{ code: 'mcp-remove-registration', detail: name }, { code: 'mcp-keep-runtime' }, { code: 'mcp-auth-unchanged' }], { state: 'done', code: 'registration-removed', detail: name }, 'mcpServers');
153
+ return removeFields(ctx, ctx.stateFile, { [name]: before[name] }, [{ code: 'mcp-remove-registration', detail: name }, { code: 'mcp-keep-runtime' }, { code: 'mcp-auth-unchanged' }], { state: 'done', code: 'registration-removed', detail: name }, MCP_SERVERS_KEY);
149
154
  if (!/^[\w.:-]+$/.test(name))
150
155
  throw new Error('invalid-mcp-name');
151
156
  if (!Object.hasOwn(mcpSpecs, name) && customRegistration === undefined)
@@ -155,11 +160,11 @@ export async function prepareMcp(ctx, name, selection, options = {}) {
155
160
  return {
156
161
  changes: [{ code: 'registration-kept', detail: name }],
157
162
  async run(report) {
158
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers)[name], value);
163
+ unchanged((await registrationsNow())[name], value);
159
164
  report({ state: 'kept', code: 'registration-kept', detail: name });
160
165
  },
161
166
  async verify() {
162
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers)[name], value);
167
+ unchanged((await registrationsNow())[name], value);
163
168
  },
164
169
  };
165
170
  }
@@ -167,39 +172,122 @@ export async function prepareMcp(ctx, name, selection, options = {}) {
167
172
  before[name] = undefined;
168
173
  if (name === 'serena' &&
169
174
  action === 'update' &&
170
- (typeof value.command !== 'string' || !/(^|[\\/])serena(?:\.exe)?$/.test(value.command)))
175
+ (typeof value.command !== 'string' || !isSerenaCommand(value.command)))
171
176
  throw new Error('channel-change-required');
172
- let registration;
173
- let targetVersion;
174
- if (name === 'context7')
175
- registration = {
176
- ...mcpSpecs.context7.registration,
177
- ...(selection.fields?.secret
178
- ? { headers: { Authorization: `Bearer ${selection.fields.secret}` } }
179
- : value.headers !== undefined
180
- ? { headers: value.headers }
181
- : {}),
182
- };
183
- else if (customRegistration !== undefined)
184
- registration = customRegistration();
185
- else {
177
+ /** 注册目标解析:context7 合并既有凭据,外部产品由所属域提供,其余拉取 Serena 发布元数据 */
178
+ const resolveTarget = async () => {
179
+ if (name === 'context7')
180
+ return {
181
+ registration: {
182
+ ...mcpSpecs.context7.registration,
183
+ ...(selection.fields?.secret
184
+ ? { headers: { Authorization: `Bearer ${selection.fields.secret}` } }
185
+ : value.headers !== undefined
186
+ ? { headers: value.headers }
187
+ : {}),
188
+ },
189
+ };
190
+ if (customRegistration !== undefined)
191
+ return { registration: customRegistration() };
186
192
  const release = JSON.parse(await ctx.machine.fetchText(mcpSpecs.serena.release.metadataUrl));
187
- if (!isObject(release) ||
188
- !isObject(release.info) ||
189
- typeof release.info.version !== 'string' ||
190
- !/^\d+\.\d+\.\d+$/.test(release.info.version))
193
+ if (!isObject(release) || !isObject(release.info) || !isExactVersion(release.info.version))
191
194
  throw new Error('invalid-release');
192
- targetVersion = release.info.version;
193
- registration = {
194
- command: 'serena',
195
- args: [...mcpSpecs.serena.registration.args],
195
+ return {
196
+ registration: { command: 'serena', args: [...mcpSpecs.serena.registration.args] },
197
+ targetVersion: release.info.version,
196
198
  };
197
- }
199
+ };
200
+ const resolved = await resolveTarget();
201
+ const registration = resolved.registration;
202
+ const targetVersion = resolved.targetVersion;
198
203
  let isRemoved = false;
199
204
  let isToolReady = false;
200
205
  let isInitialized = false;
201
206
  let isRegistrationSaved = false;
202
207
  let toolStamp = null;
208
+ /** 定位 uv;缺失时经官方脚本装入用户目录,脚本即用即清 */
209
+ const ensureUv = async (report) => {
210
+ let uv = (await ctx.machine.locate('uv'))[0];
211
+ const localUv = userBinary(ctx, 'uv');
212
+ if (uv === undefined && (await ctx.machine.treeStamp(localUv)) !== null)
213
+ uv = localUv;
214
+ if (uv !== undefined)
215
+ return uv;
216
+ const file = installScratch(ctx, `uv-${randomUUID()}.${ctx.platform === 'win32' ? 'ps1' : 'sh'}`);
217
+ await ctx.machine.initialize(file, await ctx.machine.fetchText(`https://astral.sh/uv/install.${ctx.platform === 'win32' ? 'ps1' : 'sh'}`));
218
+ try {
219
+ success(await ctx.machine.execute(ctx.platform === 'win32' ? 'powershell.exe' : 'sh', ctx.platform === 'win32' ? ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', file] : [file], { env: { UV_NO_MODIFY_PATH: '1', UV_INSTALL_DIR: userBinDirectory(ctx) } }));
220
+ }
221
+ finally {
222
+ const stamp = await ctx.machine.treeStamp(file);
223
+ if (stamp !== null)
224
+ await ctx.machine.removeTree(file, stamp);
225
+ }
226
+ report({ state: 'done', code: 'uv-installed' });
227
+ return localUv;
228
+ };
229
+ /** Serena 运行时链:uv 供给 → 固定版本安装 → 注册命令解析 → 首装初始化 */
230
+ const ensureSerenaRuntime = async (report, signal) => {
231
+ if (name !== 'serena')
232
+ return;
233
+ if (isToolReady && (await ctx.machine.treeStamp(String(registration.command))) !== toolStamp)
234
+ throw new Error('program-changed');
235
+ if (!isToolReady) {
236
+ const uv = await ensureUv(report);
237
+ cancelled(signal);
238
+ const serenaIn = (text) => text
239
+ .split('\n')
240
+ .some(line => line.trim().split(/\s+/).slice(0, 2).join(' ') === `${mcpSpecs.serena.release.package} v${targetVersion}`);
241
+ const currentTools = await ctx.machine.execute(uv, ['tool', 'list']);
242
+ const isAlreadyInstalled = !currentTools.failed && currentTools.code === 0 && serenaIn(currentTools.stdout);
243
+ if (!isAlreadyInstalled || action === 'reinstall')
244
+ success(await ctx.machine.execute(uv, [
245
+ 'tool',
246
+ 'install',
247
+ '--python',
248
+ mcpSpecs.serena.release.python,
249
+ '--upgrade',
250
+ ...(action === 'reinstall' ? ['--reinstall'] : []),
251
+ `${mcpSpecs.serena.release.package}==${targetVersion}`,
252
+ ]), 'serena-install-failed');
253
+ const installed = success(await ctx.machine.execute(uv, ['tool', 'list']));
254
+ if (!serenaIn(installed))
255
+ throw new Error('binary-version-mismatch');
256
+ const bin = success(await ctx.machine.execute(uv, ['tool', 'dir', '--bin'])).trim();
257
+ if (!path.isAbsolute(bin) || /[\r\n]/.test(bin))
258
+ throw new Error('invalid-tool-directory');
259
+ registration.command = path.join(bin, ctx.platform === 'win32' ? 'serena.exe' : 'serena');
260
+ if ((await ctx.machine.treeStamp(String(registration.command))) === null)
261
+ throw new Error('program-not-ready');
262
+ toolStamp = await ctx.machine.treeStamp(String(registration.command));
263
+ isToolReady = true;
264
+ report({ state: 'done', code: 'serena-installed' });
265
+ }
266
+ cancelled(signal);
267
+ if (action !== 'update' && !isInitialized) {
268
+ success(await ctx.machine.execute(String(registration.command), ['init']), 'serena-initialization-failed');
269
+ isInitialized = true;
270
+ report({ state: 'done', code: 'serena-initialized' });
271
+ }
272
+ };
273
+ const removeExistingRegistration = async (report) => {
274
+ await editFields(ctx, ctx.stateFile, before, { [name]: undefined }, MCP_SERVERS_KEY, () => {
275
+ before[name] = undefined;
276
+ isRemoved = true;
277
+ report({ state: 'done', code: 'registration-removed' });
278
+ });
279
+ };
280
+ const saveRegistration = async (report) => {
281
+ if (isRegistrationSaved) {
282
+ unchanged((await registrationsNow())[name], registration);
283
+ return;
284
+ }
285
+ await editFields(ctx, ctx.stateFile, before, { [name]: registration }, MCP_SERVERS_KEY, () => {
286
+ isRegistrationSaved = true;
287
+ before[name] = registration;
288
+ report({ state: 'done', code: 'registration-saved', detail: name });
289
+ });
290
+ };
203
291
  return {
204
292
  get changes() {
205
293
  if (isRegistrationSaved)
@@ -216,84 +304,14 @@ export async function prepareMcp(ctx, name, selection, options = {}) {
216
304
  ];
217
305
  },
218
306
  async run(report, signal) {
219
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers)[name], before[name]);
307
+ unchanged((await registrationsNow())[name], before[name]);
220
308
  cancelled(signal);
221
309
  if (action === 'reinstall' && !isRemoved)
222
- await editFields(ctx, ctx.stateFile, before, { [name]: undefined }, 'mcpServers', () => {
223
- before[name] = undefined;
224
- isRemoved = true;
225
- report({ state: 'done', code: 'registration-removed' });
226
- });
227
- if (name === 'serena') {
228
- if (isToolReady && (await ctx.machine.treeStamp(String(registration.command))) !== toolStamp)
229
- throw new Error('program-changed');
230
- if (!isToolReady) {
231
- let uv = (await ctx.machine.locate('uv'))[0];
232
- const localUv = path.join(ctx.home, '.local/bin', ctx.platform === 'win32' ? 'uv.exe' : 'uv');
233
- if (uv === undefined && (await ctx.machine.treeStamp(localUv)) !== null)
234
- uv = localUv;
235
- if (uv === undefined) {
236
- const file = path.join(ctx.storage, `install-uv-${randomUUID()}.${ctx.platform === 'win32' ? 'ps1' : 'sh'}`);
237
- await ctx.machine.initialize(file, await ctx.machine.fetchText(`https://astral.sh/uv/install.${ctx.platform === 'win32' ? 'ps1' : 'sh'}`));
238
- try {
239
- success(await ctx.machine.execute(ctx.platform === 'win32' ? 'powershell.exe' : 'sh', ctx.platform === 'win32' ? ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', file] : [file], { env: { UV_NO_MODIFY_PATH: '1', UV_INSTALL_DIR: path.join(ctx.home, '.local/bin') } }));
240
- }
241
- finally {
242
- const stamp = await ctx.machine.treeStamp(file);
243
- if (stamp !== null)
244
- await ctx.machine.removeTree(file, stamp);
245
- }
246
- uv = localUv;
247
- report({ state: 'done', code: 'uv-installed' });
248
- }
249
- cancelled(signal);
250
- const serenaIn = (text) => text
251
- .split('\n')
252
- .some(line => line.trim().split(/\s+/).slice(0, 2).join(' ') ===
253
- `${mcpSpecs.serena.release.package} v${targetVersion}`);
254
- const currentTools = await ctx.machine.execute(uv, ['tool', 'list']);
255
- const isAlreadyInstalled = !currentTools.failed && currentTools.code === 0 && serenaIn(currentTools.stdout);
256
- if (!isAlreadyInstalled || action === 'reinstall')
257
- success(await ctx.machine.execute(uv, [
258
- 'tool',
259
- 'install',
260
- '--python',
261
- mcpSpecs.serena.release.python,
262
- '--upgrade',
263
- ...(action === 'reinstall' ? ['--reinstall'] : []),
264
- `${mcpSpecs.serena.release.package}==${targetVersion}`,
265
- ]), 'serena-install-failed');
266
- const installed = success(await ctx.machine.execute(uv, ['tool', 'list']));
267
- if (!serenaIn(installed))
268
- throw new Error('binary-version-mismatch');
269
- const bin = success(await ctx.machine.execute(uv, ['tool', 'dir', '--bin'])).trim();
270
- if (!path.isAbsolute(bin) || /[\r\n]/.test(bin))
271
- throw new Error('invalid-tool-directory');
272
- registration.command = path.join(bin, ctx.platform === 'win32' ? 'serena.exe' : 'serena');
273
- if ((await ctx.machine.treeStamp(String(registration.command))) === null)
274
- throw new Error('program-not-ready');
275
- toolStamp = await ctx.machine.treeStamp(String(registration.command));
276
- isToolReady = true;
277
- report({ state: 'done', code: 'serena-installed' });
278
- }
279
- cancelled(signal);
280
- if (action !== 'update' && !isInitialized) {
281
- success(await ctx.machine.execute(String(registration.command), ['init']), 'serena-initialization-failed');
282
- isInitialized = true;
283
- report({ state: 'done', code: 'serena-initialized' });
284
- }
285
- }
310
+ await removeExistingRegistration(report);
311
+ await ensureSerenaRuntime(report, signal);
286
312
  cancelled(signal);
287
- if (action !== 'update') {
288
- if (!isRegistrationSaved)
289
- await editFields(ctx, ctx.stateFile, before, { [name]: registration }, 'mcpServers', () => {
290
- isRegistrationSaved = true;
291
- before[name] = registration;
292
- report({ state: 'done', code: 'registration-saved', detail: name });
293
- });
294
- else
295
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers)[name], registration);
296
- }
313
+ if (action !== 'update')
314
+ await saveRegistration(report);
297
315
  },
298
316
  };
299
317
  }
package/dist/model.js CHANGED
@@ -60,6 +60,13 @@ export function context(options) {
60
60
  export function claudeEnvironment(ctx) {
61
61
  return { CLAUDE_CONFIG_DIR: ctx.stateFile === path.join(ctx.home, '.claude.json') ? undefined : ctx.claudeRoot };
62
62
  }
63
+ /** POSIX 用户级可执行目录:Claude 原生安装、uv 与非 Windows OfficeCLI 的共同落点 */
64
+ export const userBinDirectory = (ctx) => path.join(ctx.home, '.local/bin');
65
+ /** 用户级可执行目录内的平台二进制名(win32 补 .exe 后缀) */
66
+ export const userBinary = (ctx, name) => path.join(userBinDirectory(ctx), ctx.platform === 'win32' ? `${name}.exe` : name);
67
+ /** 状态文件内 MCP 注册表的键名与读取面:mcp、officecli 与退役迁移共用 */
68
+ export const MCP_SERVERS_KEY = 'mcpServers';
69
+ export const readMcpServers = async (ctx) => object((await json(ctx.machine, ctx.stateFile))[MCP_SERVERS_KEY]);
63
70
  export function claudeProcessActive(name, command) {
64
71
  return (/(?:^|[\\/])(?:claude|Claude Code)(?:\.exe)?$/i.test(name) ||
65
72
  (/(?:^|[\\/])node(?:js)?(?:\.exe)?$/i.test(name) &&
@@ -81,6 +88,12 @@ export function restOf(id) {
81
88
  const index = id.indexOf(':');
82
89
  return index === -1 ? undefined : id.slice(index + 1);
83
90
  }
91
+ /** Claude 用户数据清理项的固定 id:编排、路由、渲染与标题表共用 */
92
+ export const CLAUDE_DATA_ID = 'data:claude';
93
+ /** 「备份并替换」表单同意值:终端产生,技能与 OfficeCLI 域消费 */
94
+ export const REPLACE_CONSENT = 'yes';
95
+ /** 普通安装任务的默认动作:settings 项进入配置而非重装 */
96
+ export const defaultInstallAction = (id) => (id === 'settings' ? 'configure' : 'install');
84
97
  /** 归一路径用于等价比较:win32 大小写不敏感 */
85
98
  export function normalizePath(platform, file) {
86
99
  return platform === 'win32' ? path.resolve(file).toLowerCase() : path.resolve(file);
@@ -3,8 +3,12 @@ const NPM_MIRROR = 'https://registry.npmmirror.com';
3
3
  export const NPM_OFFICIAL = 'https://registry.npmjs.org';
4
4
  export const NPM_READ_TIMEOUT_MS = 5_000;
5
5
  const NPM_AUDIT_FREE = ['--no-audit', '--no-fund'];
6
+ /** 需要安装期脚本的包(claude、ccline)以此启用脚本执行;字面量不得散布 */
7
+ export const NPM_ENABLE_SCRIPTS = ['--ignore-scripts=false'];
6
8
  const queryFlags = ['--fetch-retries=0', '--fetch-timeout=4000'];
7
9
  const installFlags = ['--fetch-retries=1', '--fetch-timeout=30000'];
10
+ /** 精确三段版本号(无前后缀) */
11
+ export const isExactVersion = (value) => typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value);
8
12
  function registryFlags(registry, packageSpec) {
9
13
  const scope = /^(@[a-z0-9._-]+)\/[a-z0-9._-]+(?:@[^\s]+)?$/i.exec(packageSpec)?.[1];
10
14
  if (scope === undefined)
package/dist/officecli.js CHANGED
@@ -1,18 +1,23 @@
1
1
  import path from 'node:path';
2
2
  import { knownTitle } from './titles.js';
3
- import { officeIntegration } from './management-catalog.js';
3
+ import { OFFICECLI_REPO_SLUG, officeIntegration, SKILL_ENTRY } from './management-catalog.js';
4
4
  import { currentSkill, prepareSkillFiles, skillFilesStamp } from './skill-files.js';
5
5
  import { prepareSkill } from './skills.js';
6
6
  import { prepareMcp } from './mcp.js';
7
- import { errorCode, isObject } from './machine.js';
8
- import { cancelled, json, object, sequence, unchanged } from './model.js';
9
- import { resolveNpmView } from './npm-registry.js';
7
+ import { errorCode, isGitRevision, isObject } from './machine.js';
8
+ import { cancelled, json, readMcpServers, REPLACE_CONSENT, sequence, unchanged } from './model.js';
9
+ import { isExactVersion, resolveNpmView } from './npm-registry.js';
10
10
  import { officeBinary, samePath } from './program-channels.js';
11
11
  import { officeVersion, prepareProgram, programs } from './programs.js';
12
+ import { sourcesFile } from './storage.js';
13
+ /** OfficeCLI 接入入口的 id 集合:域内入口类型与计划层的重叠门判共用 */
14
+ export const OFFICECLI_ENTRY_IDS = ['skill:officecli', 'mcp:officecli'];
12
15
  const OFFICECLI_SKILL = 'officecli';
16
+ /** 随包技能的读取落点:检查与准备共用 */
17
+ const officeSkillDirectory = (ctx) => path.join(ctx.claudeRoot, 'skills', OFFICECLI_SKILL);
13
18
  /** 管理 OfficeCLI 程序与所选 Claude 入口,计划及剩余工作由 CCW 消费 */
14
19
  export function createOfficecli(ctx) {
15
- const directory = path.join(ctx.claudeRoot, 'skills', OFFICECLI_SKILL);
20
+ const directory = officeSkillDirectory(ctx);
16
21
  async function commandOwner(command, found) {
17
22
  const candidates = path.isAbsolute(command)
18
23
  ? [command]
@@ -53,14 +58,14 @@ export function createOfficecli(ctx) {
53
58
  let registration;
54
59
  let metadata = {};
55
60
  try {
56
- metadata = await json(ctx.machine, path.join(ctx.storage, 'sources.json'));
61
+ metadata = await json(ctx.machine, sourcesFile(ctx));
57
62
  }
58
63
  catch {
59
64
  problems.push({ code: 'source-metadata-unavailable', detail: 'officecli' });
60
65
  }
61
66
  try {
62
67
  skillStamp = await ctx.machine.treeStamp(directory);
63
- const text = skillStamp !== null ? await ctx.machine.read(path.join(directory, 'SKILL.md')) : null;
68
+ const text = skillStamp !== null ? await ctx.machine.read(path.join(directory, SKILL_ENTRY)) : null;
64
69
  skillEvidence = officeSkillEvidence(text, metadata[directory], skillStamp);
65
70
  }
66
71
  catch (error) {
@@ -68,7 +73,7 @@ export function createOfficecli(ctx) {
68
73
  problems.push({ code: errorCode(error), detail: directory });
69
74
  }
70
75
  try {
71
- registration = object((await json(ctx.machine, ctx.stateFile)).mcpServers).officecli;
76
+ registration = (await readMcpServers(ctx)).officecli;
72
77
  mcpCommand = officeMcpCommand(registration);
73
78
  }
74
79
  catch (error) {
@@ -117,7 +122,7 @@ export function createOfficecli(ctx) {
117
122
  if (entry.id === 'skill:officecli')
118
123
  unchanged(await ctx.machine.treeStamp(directory), null);
119
124
  else
120
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers).officecli, undefined);
125
+ unchanged((await readMcpServers(ctx)).officecli, undefined);
121
126
  };
122
127
  const step = {
123
128
  ...(operation.writes ? { writes: operation.writes } : {}),
@@ -350,25 +355,25 @@ async function officeRevision(ctx, target) {
350
355
  if (version === null)
351
356
  throw new Error('source-version-unavailable');
352
357
  if (target.source === 'npm') {
353
- const resolved = await resolveNpmView(ctx.machine, '@officecli/officecli@' + version, 'gitHead', value => (typeof value === 'string' && /^[a-f0-9]{40}$/.test(value) ? value : null), target.registry ?? null);
358
+ const resolved = await resolveNpmView(ctx.machine, '@officecli/officecli@' + version, 'gitHead', value => (typeof value === 'string' && isGitRevision(value) ? value : null), target.registry ?? null);
354
359
  if (resolved === null)
355
360
  throw new Error('source-version-unavailable');
356
361
  return resolved.value;
357
362
  }
358
- if (!/^\d+\.\d+\.\d+$/.test(version))
363
+ if (!isExactVersion(version))
359
364
  throw new Error('source-version-unavailable');
360
- const reference = JSON.parse(await ctx.machine.fetchText('https://api.github.com/repos/iOfficeAI/OfficeCLI/git/ref/tags/v' + version));
365
+ const reference = JSON.parse(await ctx.machine.fetchText(`https://api.github.com/repos/${OFFICECLI_REPO_SLUG}/git/ref/tags/v${version}`));
361
366
  if (!isObject(reference) || reference.ref !== 'refs/tags/v' + version || !isObject(reference.object))
362
367
  throw new Error('source-version-unavailable');
363
368
  let object = reference.object;
364
369
  for (let depth = 0; depth < 4; depth++) {
365
- if (typeof object.sha !== 'string' || !/^[a-f0-9]{40}$/.test(object.sha))
370
+ if (typeof object.sha !== 'string' || !isGitRevision(object.sha))
366
371
  throw new Error('source-version-unavailable');
367
372
  if (object.type === 'commit')
368
373
  return object.sha;
369
374
  if (object.type !== 'tag')
370
375
  throw new Error('source-version-unavailable');
371
- const tag = JSON.parse(await ctx.machine.fetchText('https://api.github.com/repos/iOfficeAI/OfficeCLI/git/tags/' + object.sha));
376
+ const tag = JSON.parse(await ctx.machine.fetchText(`https://api.github.com/repos/${OFFICECLI_REPO_SLUG}/git/tags/${object.sha}`));
372
377
  if (!isObject(tag) || tag.sha !== object.sha || !isObject(tag.object))
373
378
  throw new Error('source-version-unavailable');
374
379
  object = tag.object;
@@ -376,7 +381,7 @@ async function officeRevision(ctx, target) {
376
381
  throw new Error('source-version-unavailable');
377
382
  }
378
383
  async function prepareOfficeConnection(ctx, selection, observed, target) {
379
- const directory = path.join(ctx.claudeRoot, 'skills', OFFICECLI_SKILL);
384
+ const directory = officeSkillDirectory(ctx);
380
385
  const { skillStamp: before, sourceRecord: record, mcpCommand: command } = observed;
381
386
  const hasMcp = command !== undefined && (!path.isAbsolute(command) || samePath(ctx, command, target.binary));
382
387
  const integration = selection.fields?.connection;
@@ -419,7 +424,9 @@ async function prepareOfficeConnection(ctx, selection, observed, target) {
419
424
  ((hasMcp && integration !== 'mcp') || (observed.skillEvidence !== 'none' && integration === 'mcp')));
420
425
  if (integration === 'mcp' && !shouldConnectBoth)
421
426
  return mcp('connect', isReinstall);
422
- if (before !== null && selection.fields?.replace !== 'yes' && (!isObject(record) || record.stamp !== before))
427
+ if (before !== null &&
428
+ selection.fields?.replace !== REPLACE_CONSENT &&
429
+ (!isObject(record) || record.stamp !== before))
423
430
  throw new Error('local-edits-preserved');
424
431
  if (isReinstall && before !== null && observed.skillEvidence === 'none')
425
432
  throw new Error('integration-source-conflict');