@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.
package/dist/officecli.js CHANGED
@@ -1,372 +1,212 @@
1
1
  import path from 'node:path';
2
- import { knownTitle } from './titles.js';
3
- import { OFFICECLI_REPO_SLUG, officeIntegration, SKILL_ENTRY } from './management-catalog.js';
4
- import { currentSkill, prepareSkillFiles, skillFilesStamp } from './skill-files.js';
5
- import { prepareSkill } from './skills.js';
6
- import { prepareMcp } from './mcp.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
- import { officeBinary, samePath } from './program-channels.js';
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'];
15
- const OFFICECLI_SKILL = 'officecli';
16
- /** 随包技能的读取落点:检查与准备共用 */
17
- const officeSkillDirectory = (ctx) => path.join(ctx.claudeRoot, 'skills', OFFICECLI_SKILL);
18
- /** 管理 OfficeCLI 程序与所选 Claude 入口,计划及剩余工作由 CCW 消费 */
2
+ import { knownTitle, OFFICECLI_REPO_SLUG, OFFICE_INTEGRATION } from './management-catalog.js';
3
+ import { sourcesFile, currentSkill, prepareSkillFiles, skillFilesStamp, disableSkillEntry, repairSkillSource, ownsSkill, checkSkillSource, } from './skill-files.js';
4
+ import { isGitRevision, isObject, errorCode, succeeded } from './machine.js';
5
+ import { createHash } from 'node:crypto';
6
+ import { json, userBinDirectory } from './model.js';
7
+ import { isExactVersion, compareVersions } from './npm-registry.js';
8
+ import { samePath } from './program-channels.js';
9
+ import { removeProgramFile, deployProgram, programPath } from './program-operations.js';
10
+ import { step, sequence, work } from './work.js';
11
+ const PROGRAM_ACTION_CHANGE = { install: 'program-install', update: 'program-update' };
12
+ const CHECKSUM_DOWNLOAD_TIMEOUT_MS = 10_000;
13
+ const PROGRAM_DOWNLOAD_TIMEOUT_MS = 30_000;
14
+ const VERSION_PROBE_TIMEOUT_MS = 5_000;
15
+ const MAX_TAG_DEREFERENCES = 4;
16
+ /**
17
+ * 管理 OfficeCLI 原生程序和配套技能
18
+ *
19
+ * @remarks 仅管理固定用户目录;按发布摘要及技能提交安装,摘要匹配时复用程序
20
+ * 拒绝降级、来源不明或覆盖本地技能改动
21
+ * 卸载移除程序并保留自有技能副本,不动其他技能和用户数据
22
+ */
19
23
  export function createOfficecli(ctx) {
20
- const directory = officeSkillDirectory(ctx);
21
- async function commandOwner(command, found) {
22
- const candidates = path.isAbsolute(command)
23
- ? [command]
24
- : command === 'officecli' || command === 'officecli.exe'
25
- ? await ctx.machine.locate('officecli')
26
- : [];
27
- const candidate = candidates[0];
28
- if (candidate === undefined)
29
- return undefined;
30
- for (const [id, program] of found.values)
31
- if (samePath(ctx, candidate, program.binary))
32
- return id;
33
- const canonical = await ctx.machine.realpath(candidate);
34
- if (canonical === null)
35
- return undefined;
36
- for (const [id, program] of found.values) {
37
- if (samePath(ctx, candidate, program.binary) || samePath(ctx, canonical, program.binary))
38
- return id;
39
- if (program.channel !== 'npm')
40
- continue;
41
- const packageRoot = path.dirname(path.dirname(program.binary));
42
- const normalized = ctx.platform === 'win32' ? canonical.toLowerCase() : canonical;
43
- const prefix = ctx.platform === 'win32' ? packageRoot.toLowerCase() : packageRoot;
44
- if (normalized.startsWith(`${prefix}${path.sep}`))
45
- return id;
46
- if (program.binary.startsWith(path.join(path.dirname(candidate), 'node_modules', '@officecli', 'officecli') + path.sep))
47
- return id;
48
- }
49
- return undefined;
50
- }
51
- async function observe(found) {
52
- found ??= await programs(ctx, 'officecli');
53
- const problems = found.problems.map(code => ({ code, detail: 'officecli' }));
54
- let isConnectionsUnknown = false;
55
- let skillEvidence = 'none';
56
- let skillStamp = null;
57
- let mcpCommand;
58
- let registration;
59
- let metadata = {};
60
- try {
61
- metadata = await json(ctx.machine, sourcesFile(ctx));
62
- }
63
- catch {
64
- problems.push({ code: 'source-metadata-unavailable', detail: 'officecli' });
65
- }
66
- try {
67
- skillStamp = await ctx.machine.treeStamp(directory);
68
- const text = skillStamp !== null ? await ctx.machine.read(path.join(directory, SKILL_ENTRY)) : null;
69
- skillEvidence = officeSkillEvidence(text, metadata[directory], skillStamp);
70
- }
71
- catch (error) {
72
- isConnectionsUnknown = true;
73
- problems.push({ code: errorCode(error), detail: directory });
74
- }
75
- try {
76
- registration = (await readMcpServers(ctx)).officecli;
77
- mcpCommand = officeMcpCommand(registration);
78
- }
79
- catch (error) {
80
- isConnectionsUnknown = true;
81
- problems.push({ code: errorCode(error), detail: ctx.stateFile });
82
- }
83
- const entries = [];
84
- // 无程序时只认领有来源记录的残留技能入口;仅凭 frontmatter 同名不认领用户自建内容
85
- if (skillEvidence !== 'none' && (found.values.size > 0 || skillEvidence === 'confirmed'))
86
- entries.push({
87
- id: 'skill:officecli',
88
- owner: found.values.size === 0 ? null : await commandOwner('officecli', found),
89
- });
90
- if (mcpCommand !== undefined)
91
- entries.push({
92
- id: 'mcp:officecli',
93
- owner: found.values.size === 0 ? null : await commandOwner(mcpCommand, found),
94
- });
95
- return {
96
- found,
97
- entries,
98
- problems,
99
- skillEvidence,
100
- skillStamp,
101
- sourceRecord: metadata[directory],
102
- mcpCommand,
103
- registration,
104
- isConnectionsUnknown,
105
- };
106
- }
107
- function related(observed, id) {
108
- return observed.entries.filter(entry => entry.owner === id);
109
- }
110
- async function detach(entries, action) {
111
- if (entries.length === 0)
112
- throw new Error('no-connection');
113
- const operations = [];
114
- for (const entry of entries) {
115
- const operation = entry.id === 'skill:officecli'
116
- ? await prepareSkill(ctx, 'officecli', 'skills', { id: entry.id, action: 'detach' })
117
- : await prepareMcp(ctx, 'officecli', { id: entry.id, action: 'detach' });
118
- let isComplete = false;
119
- const verify = async () => {
120
- if (!isComplete || action === 'reinstall')
121
- return;
122
- if (entry.id === 'skill:officecli')
123
- unchanged(await ctx.machine.treeStamp(directory), null);
124
- else
125
- unchanged((await readMcpServers(ctx)).officecli, undefined);
126
- };
127
- const step = {
128
- ...(operation.writes ? { writes: operation.writes } : {}),
129
- changes: operation.changes,
130
- async run(report, signal) {
131
- cancelled(signal);
132
- if (isComplete) {
133
- await verify();
134
- return;
135
- }
136
- await operation.run(report, signal);
137
- isComplete = true;
138
- },
139
- remaining: () => (isComplete ? undefined : step),
140
- verify,
141
- };
142
- operations.push(step);
143
- }
144
- return sequence(operations);
145
- }
24
+ const directory = path.join(ctx.claudeRoot, 'skills', 'officecli');
146
25
  return {
147
26
  async inspect() {
148
- const observed = await observe();
149
- const items = observed.found.items.map(item => {
150
- const entries = related(observed, item.id);
151
- const program = observed.found.values.get(item.id);
152
- const problem = observed.isConnectionsUnknown ? 'installation-state-unconfirmed' : undefined;
153
- return {
154
- ...item,
155
- facts: [
156
- ...item.facts,
157
- ...(program?.channel === 'native' || program?.channel === 'manual'
158
- ? [{ code: 'program-identity-unchecked' }]
159
- : []),
160
- ...connectionFacts(entries),
161
- ],
162
- actions: [...item.actions, ...(entries.length ? ['detach'] : [])],
163
- ...(problem ? { problem } : {}),
164
- };
165
- });
166
- if (items.length === 0) {
167
- const entries = related(observed, null);
168
- items.push({
169
- id: 'officecli',
170
- title: knownTitle('officecli'),
171
- kind: 'officecli',
172
- canInstall: true,
173
- facts: [
174
- { code: observed.found.problems.length ? 'inspection-incomplete' : 'not-installed' },
175
- ...connectionFacts(entries),
176
- ],
177
- actions: ['install', ...(entries.length ? ['detach'] : [])],
178
- ...(observed.isConnectionsUnknown ? { problem: 'installation-state-unconfirmed' } : {}),
179
- });
180
- }
27
+ const found = await officePrograms(ctx);
181
28
  return {
182
- items,
183
- problems: observed.problems,
184
- grouped: observed.isConnectionsUnknown
185
- ? []
186
- : observed.entries.filter(entry => entry.owner !== undefined).map(entry => entry.id),
29
+ items: found.items.length
30
+ ? found.items
31
+ : [
32
+ {
33
+ id: 'officecli',
34
+ title: knownTitle('officecli'),
35
+ kind: 'officecli',
36
+ location: officeBinary(ctx),
37
+ canInstall: true,
38
+ facts: [{ code: 'not-installed' }],
39
+ },
40
+ ],
41
+ problems: [],
187
42
  };
188
43
  },
189
44
  async prepare(selection) {
190
- const observed = await observe();
191
- const program = observed.found.values.get(selection.id) ??
192
- (selection.id === 'officecli' && observed.found.values.size === 1
193
- ? [...observed.found.values.values()][0]
194
- : undefined);
195
- const identity = program ? [...observed.found.values].find(([, value]) => value === program)?.[0] : null;
196
- if (selection.id !== 'officecli' && program === undefined)
197
- throw new Error('program-changed');
198
- if (selection.id === 'officecli' && observed.found.values.size > 1)
199
- throw new Error('program-selection-required');
200
- if (observed.isConnectionsUnknown ||
201
- (selection.action !== 'detach' && observed.found.problems.length > 0 && (!program || program.channel === 'npm')))
202
- throw new Error('installation-state-unconfirmed');
203
- const entries = related(observed, identity ?? null);
204
- if (selection.action === 'detach')
205
- return detach(entries, selection.action);
45
+ if (selection.id !== 'officecli')
46
+ throw new Error('channel-not-supported');
47
+ const found = await officePrograms(ctx);
48
+ const program = found.values.get('officecli');
49
+ if (!program && found.values.size)
50
+ throw new Error('channel-not-supported');
51
+ let metadata;
52
+ try {
53
+ metadata = await json(ctx.machine, sourcesFile(ctx));
54
+ }
55
+ catch {
56
+ throw new Error('source-metadata-unavailable');
57
+ }
58
+ const before = await ctx.machine.treeStamp(directory);
59
+ const record = metadata[directory];
60
+ const owned = ownsSkill(record, OFFICE_INTEGRATION.skill.repository, before);
61
+ if (selection.action !== 'uninstall' && before !== null)
62
+ checkSkillSource(record, OFFICE_INTEGRATION.skill.repository);
206
63
  if (selection.action === 'uninstall') {
207
- if (!program)
208
- return sequence([
209
- await detach(entries, selection.action),
210
- {
211
- changes: [{ code: 'program-not-installed' }],
212
- run(report) {
213
- report({ state: 'kept', code: 'program-not-installed' });
214
- return Promise.resolve();
215
- },
216
- },
217
- ]);
218
- const removal = await prepareProgram(ctx, 'officecli', selection, program);
219
- const belongs = (value, entry) => entry.owner === identity ||
220
- (entry.owner === null && value.found.values.size === 0) ||
221
- (entry.id === 'mcp:officecli' &&
222
- isObject(value.registration) &&
223
- typeof value.registration.command === 'string' &&
224
- path.isAbsolute(value.registration.command) &&
225
- samePath(ctx, value.registration.command, program.binary));
226
- const scope = (value) => value.entries.filter(entry => belongs(value, entry));
227
- const expected = scope(observed);
228
- const unmatched = [
229
- ...(observed.skillStamp !== null &&
230
- (observed.skillEvidence === 'none' ||
231
- observed.entries.some(entry => entry.id === 'skill:officecli' && entry.owner === undefined))
232
- ? [directory]
233
- : []),
234
- ...(observed.registration !== undefined &&
235
- (observed.mcpCommand === undefined ||
236
- observed.entries.some(entry => entry.id === 'mcp:officecli' && entry.owner === undefined))
237
- ? ['officecli']
238
- : []),
239
- ];
240
- const preserved = {
241
- changes: unmatched.map(detail => ({ code: 'unmatched-integration-kept', detail })),
242
- run(report) {
243
- for (const detail of unmatched)
244
- report({ state: 'kept', code: 'unmatched-integration-kept', detail });
245
- return Promise.resolve();
246
- },
247
- };
248
- const guard = (hasDetached) => {
249
- const verify = async () => {
250
- const current = await observe(observed.found);
251
- if (current.isConnectionsUnknown)
252
- throw new Error('installation-state-unconfirmed');
253
- const actual = scope(current);
254
- unchanged(actual.map(entry => entry.id), hasDetached ? [] : expected.map(entry => entry.id));
255
- if (!hasDetached)
256
- for (const entry of expected)
257
- unchanged(entry.id === 'skill:officecli' ? current.skillStamp : current.registration, entry.id === 'skill:officecli' ? observed.skillStamp : observed.registration);
258
- };
259
- return { changes: [], run: verify, ...(hasDetached ? { verify } : {}) };
260
- };
261
- return sequence([
262
- guard(false),
263
- ...(expected.length ? [await detach(expected, selection.action)] : []),
264
- guard(true),
265
- removal,
266
- preserved,
267
- ]);
64
+ const operation = await prepareOfficeRemoval(ctx, program);
65
+ const detach = owned && before !== null ? disableSkillEntry(ctx, directory, before, record) : work([]);
66
+ const kept = step([], () => Promise.resolve({
67
+ state: 'complete',
68
+ effects: before !== null && !owned
69
+ ? [{ state: 'kept', code: 'unmatched-integration-kept', detail: directory }]
70
+ : [],
71
+ }));
72
+ return work([sequence([detach, operation]), kept]);
268
73
  }
269
- if (!['install', 'connect', 'update', 'reinstall'].includes(selection.action))
270
- throw new Error('action-unavailable');
271
- const integration = selection.fields?.connection;
272
- if (observed.skillStamp !== null && observed.skillEvidence === 'none' && integration !== 'mcp')
273
- throw new Error('integration-source-conflict');
274
- if (observed.registration !== undefined &&
275
- observed.mcpCommand === undefined &&
276
- (integration === 'mcp' || integration === 'both'))
277
- throw new Error('integration-source-conflict');
278
- const stamp = program ? await ctx.machine.treeStamp(program.binary) : null;
279
- const shouldKeepProgram = program && !program.isMissing && (selection.action === 'install' || selection.action === 'connect');
280
- // 两次读取之间二进制消失时不允许"保留程序"空转通过
281
- if (shouldKeepProgram && stamp === null)
282
- throw new Error('program-changed');
283
- const version = shouldKeepProgram ? (program.version ?? (await officeVersion(ctx, program.binary))) : null;
284
- if (shouldKeepProgram && version === null)
285
- throw new Error('program-identity-unconfirmed');
286
- if (shouldKeepProgram)
287
- unchanged(await ctx.machine.treeStamp(program.binary), stamp);
288
- const operation = shouldKeepProgram
289
- ? {
290
- targetVersion: version,
291
- targetBinary: program.binary,
292
- ...(program.channel === 'npm' ? { targetRegistry: null } : {}),
293
- changes: [{ code: 'program-kept' }],
294
- async run(report) {
295
- unchanged(await ctx.machine.treeStamp(program.binary), stamp);
296
- if (program.channel === 'native')
297
- await ctx.machine.ensureUserPath(path.dirname(program.binary));
298
- report({ state: 'kept', code: 'program-kept' });
299
- },
300
- async verify() {
301
- unchanged(await ctx.machine.treeStamp(program.binary), stamp);
302
- },
303
- }
304
- : await prepareProgram(ctx, 'officecli', selection, program);
305
- const binary = operation.targetBinary ?? program?.binary ?? officeBinary(ctx);
306
- const connection = await prepareOfficeConnection(ctx, selection, observed, {
307
- version: operation.targetVersion,
308
- binary,
309
- source: program?.channel === 'npm' ? 'npm' : 'native',
310
- ...(operation.targetRegistry !== undefined ? { registry: operation.targetRegistry } : {}),
311
- });
312
- const before = selection.action === 'reinstall' && entries.length ? await detach(entries, selection.action) : undefined;
313
- return sequence([...(before ? [before] : []), operation, connection]);
74
+ const operation = await prepareOfficeNative(ctx, program);
75
+ const revision = await officeRevision(ctx, operation.targetVersion);
76
+ const files = await ctx.machine.source(OFFICE_INTEGRATION.skill.repository, revision, OFFICE_INTEGRATION.skill.folder);
77
+ const source = {
78
+ repository: OFFICE_INTEGRATION.skill.repository,
79
+ revision,
80
+ files,
81
+ stamp: skillFilesStamp(files),
82
+ };
83
+ const target = { name: 'officecli', directory, stamp: before, sourceRecord: record };
84
+ if (before !== null && !owned && before !== source.stamp)
85
+ throw new Error('local-edits-preserved');
86
+ const skill = before === source.stamp
87
+ ? owned
88
+ ? currentSkill(ctx, 'officecli', directory, before)
89
+ : repairSkillSource(ctx, target, source)
90
+ : prepareSkillFiles(ctx, target, source);
91
+ return {
92
+ ...sequence([operation, skill]),
93
+ action: operation.action ?? 'install',
94
+ };
314
95
  },
315
96
  };
316
97
  }
317
- function connectionFacts(entries) {
318
- return [
319
- { code: entries.length ? 'connected' : 'not-connected' },
320
- ...entries.map(entry => ({
321
- code: entry.id === 'skill:officecli' ? 'office-skill-connected' : 'office-mcp-connected',
322
- })),
98
+ async function prepareOfficeRemoval(ctx, program) {
99
+ if (program?.channel === 'manual')
100
+ throw new Error('channel-not-supported');
101
+ if (!program || program.channel !== 'native')
102
+ throw new Error('program-not-installed');
103
+ if ((await officeVersion(ctx, program.binary)) === null)
104
+ throw new Error('program-identity-unconfirmed');
105
+ const targets = [
106
+ { file: program.binary, stamp: await ctx.machine.treeStamp(program.binary) },
107
+ ...(await officeUpdates(ctx, program.binary)),
323
108
  ];
109
+ return work(targets.map(target => removeProgramFile(ctx, { file: target.file, before: target.stamp }, [
110
+ { code: 'program-uninstall', detail: target.file },
111
+ ])));
324
112
  }
325
- function officeSkillEvidence(text, source, stamp) {
326
- if (stamp === null || !text?.trim())
327
- return 'none';
328
- if (isObject(source) && source.repository === officeIntegration.skill.repository && source.stamp === stamp)
329
- return 'confirmed';
330
- const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1];
331
- return frontmatter !== undefined && /(?:^|\n)\s*name:\s*["']?officecli["']?\s*(?:\r?\n|$)/i.test(frontmatter)
332
- ? 'shape'
333
- : 'none';
334
- }
335
- /** 生成 officecli 的 MCP 注册形状:识别与注册同源 */
336
- function officeMcpRegistration(command) {
337
- return { command, args: [...officeIntegration.mcp.args], env: { ...officeIntegration.mcp.env } };
338
- }
339
- function officeMcpCommand(value) {
340
- if (!isObject(value) || typeof value.command !== 'string')
341
- return undefined;
342
- const shape = officeMcpRegistration(value.command);
343
- if (!Array.isArray(value.args) ||
344
- value.args.length !== shape.args.length ||
345
- value.args.some((arg, index) => arg !== shape.args[index]))
346
- return undefined;
347
- const command = value.command;
348
- return /^(?:officecli|officecli\.exe)$/i.test(command) ||
349
- (path.isAbsolute(command) && /(?:^|[\\/])officecli(?:\.exe)?$/i.test(command))
350
- ? command
351
- : undefined;
352
- }
353
- async function officeRevision(ctx, target) {
354
- const version = target.version;
355
- if (version === null)
356
- throw new Error('source-version-unavailable');
357
- if (target.source === 'npm') {
358
- const resolved = await resolveNpmView(ctx.machine, '@officecli/officecli@' + version, 'gitHead', value => (typeof value === 'string' && isGitRevision(value) ? value : null), target.registry ?? null);
359
- if (resolved === null)
360
- throw new Error('source-version-unavailable');
361
- return resolved.value;
113
+ async function prepareOfficeNative(ctx, program) {
114
+ if (program?.channel === 'manual')
115
+ throw new Error('channel-not-supported');
116
+ const action = program ? 'update' : 'install';
117
+ const binary = program?.binary ?? officeBinary(ctx);
118
+ if (!samePath(ctx, binary, officeBinary(ctx)))
119
+ throw new Error('channel-not-supported');
120
+ const before = await ctx.machine.fingerprint(binary);
121
+ if (!program && before !== null)
122
+ throw new Error('program-changed');
123
+ const updates = await officeUpdates(ctx, binary);
124
+ const assetName = officeAsset(ctx);
125
+ const release = JSON.parse(await ctx.machine.fetchText(`https://api.github.com/repos/${OFFICECLI_REPO_SLUG}/releases/latest`));
126
+ if (!isObject(release) ||
127
+ release.draft !== false ||
128
+ release.prerelease !== false ||
129
+ typeof release.tag_name !== 'string' ||
130
+ !/^v\d+\.\d+\.\d+$/.test(release.tag_name) ||
131
+ !Array.isArray(release.assets))
132
+ throw new Error('invalid-release');
133
+ const tag = release.tag_name;
134
+ const targetVersion = tag.slice(1);
135
+ const baseUrl = `https://github.com/${OFFICECLI_REPO_SLUG}/releases/download/${tag}/`;
136
+ const assets = release.assets.filter(isObject);
137
+ const asset = assets.find(value => value.name === assetName);
138
+ const manifest = assets.find(value => value.name === 'SHA256SUMS');
139
+ if (!asset ||
140
+ asset.browser_download_url !== `${baseUrl}${assetName}` ||
141
+ !manifest ||
142
+ manifest.browser_download_url !== `${baseUrl}SHA256SUMS`)
143
+ throw new Error('release-asset-unavailable');
144
+ const fetchReleaseFile = async (name, read, timeoutMs) => {
145
+ try {
146
+ return await read(`${baseUrl}${name}`, { timeoutMs });
147
+ }
148
+ catch (error) {
149
+ if (errorCode(error) === 'cancelled')
150
+ throw error;
151
+ // 上游官方镜像只作为传输备选,标签、文件名与摘要仍由 GitHub 发布约束
152
+ return read(`${OFFICE_INTEGRATION.releaseMirror}/releases/download/${tag}/${name}`);
153
+ }
154
+ };
155
+ const checksums = await fetchReleaseFile('SHA256SUMS', (url, options) => ctx.machine.fetchText(url, options), CHECKSUM_DOWNLOAD_TIMEOUT_MS);
156
+ const matching = checksums
157
+ .split(/\r?\n/)
158
+ .map(line => line.trim().split(/\s+/))
159
+ .filter(parts => parts[1]?.replace(/^\*/, '') === assetName);
160
+ const digest = matching.length === 1 ? matching[0]?.[0]?.toLowerCase() : undefined;
161
+ if (digest === undefined ||
162
+ !/^[a-f0-9]{64}$/.test(digest) ||
163
+ (asset.digest !== undefined && asset.digest !== null && asset.digest !== `sha256:${digest}`))
164
+ throw new Error('release-checksum-unavailable');
165
+ if (before !== null) {
166
+ const currentVersion = await officeVersion(ctx, binary);
167
+ if (currentVersion === null)
168
+ throw new Error('program-version-unconfirmed');
169
+ if (compareVersions(currentVersion, targetVersion) > 0)
170
+ throw new Error('newer-version-preserved');
362
171
  }
172
+ // 完整摘要与发布原件一致才复用,版本号相同但内容不同仍需下载校验
173
+ const shouldKeepBinary = action === 'update' && before === digest;
174
+ const bytes = shouldKeepBinary
175
+ ? null
176
+ : await fetchReleaseFile(assetName, (url, options) => ctx.machine.fetchBytes(url, options), PROGRAM_DOWNLOAD_TIMEOUT_MS);
177
+ if (bytes !== null && createHash('sha256').update(bytes).digest('hex') !== digest)
178
+ throw new Error('release-checksum-mismatch');
179
+ const removals = updates.map(target => removeProgramFile(ctx, { file: target.file, before: target.stamp }, target.stamp === null ? [] : [{ code: 'program-copy-remove', detail: target.file }]));
180
+ const deploy = deployProgram(ctx, { binary, before, digest, bytes }, [
181
+ {
182
+ code: shouldKeepBinary ? 'program-kept' : PROGRAM_ACTION_CHANGE[action],
183
+ detail: 'OfficeCLI · native · ' + targetVersion + ' · ' + binary,
184
+ },
185
+ ]);
186
+ const ready = step([], async () => {
187
+ if ((await ctx.machine.fingerprint(binary)) !== digest || (await officeVersion(ctx, binary)) !== targetVersion)
188
+ throw new Error('program-not-ready');
189
+ return { state: 'complete', effects: [{ state: 'done', code: 'program-ready' }] };
190
+ });
191
+ const userPath = programPath(ctx, path.dirname(binary), [
192
+ { code: 'program-user-path', detail: path.dirname(binary) },
193
+ { code: 'keep-user-data' },
194
+ ]);
195
+ return {
196
+ ...sequence([...(removals.length ? [work(removals)] : []), deploy, ready, userPath]),
197
+ action,
198
+ targetVersion,
199
+ };
200
+ }
201
+ async function officeRevision(ctx, version) {
363
202
  if (!isExactVersion(version))
364
203
  throw new Error('source-version-unavailable');
365
204
  const reference = JSON.parse(await ctx.machine.fetchText(`https://api.github.com/repos/${OFFICECLI_REPO_SLUG}/git/ref/tags/v${version}`));
366
205
  if (!isObject(reference) || reference.ref !== 'refs/tags/v' + version || !isObject(reference.object))
367
206
  throw new Error('source-version-unavailable');
368
207
  let object = reference.object;
369
- for (let depth = 0; depth < 4; depth++) {
208
+ // 技能固定到对应程序版本的提交,最多解引用四层附注标签
209
+ for (let depth = 0; depth < MAX_TAG_DEREFERENCES; depth++) {
370
210
  if (typeof object.sha !== 'string' || !isGitRevision(object.sha))
371
211
  throw new Error('source-version-unavailable');
372
212
  if (object.type === 'commit')
@@ -380,65 +220,88 @@ async function officeRevision(ctx, target) {
380
220
  }
381
221
  throw new Error('source-version-unavailable');
382
222
  }
383
- async function prepareOfficeConnection(ctx, selection, observed, target) {
384
- const directory = officeSkillDirectory(ctx);
385
- const { skillStamp: before, sourceRecord: record, mcpCommand: command } = observed;
386
- const hasMcp = command !== undefined && (!path.isAbsolute(command) || samePath(ctx, command, target.binary));
387
- const integration = selection.fields?.connection;
388
- const mcp = (action, hasDetached = false) => prepareMcp(ctx, 'officecli', { ...selection, action }, {
389
- hasDetached,
390
- registration: () => officeMcpRegistration(target.binary),
391
- });
392
- if (selection.action === 'install') {
393
- if (before !== null && observed.skillEvidence !== 'none') {
394
- const skill = currentSkill(ctx, 'officecli', directory, before);
395
- if (integration === 'both')
396
- return sequence([skill, await mcp('connect')]);
397
- return integration === 'mcp' ? mcp('connect') : skill;
398
- }
399
- }
400
- if (selection.action === 'update') {
401
- if (observed.problems.some(problem => problem.code === 'source-metadata-unavailable'))
402
- throw new Error('source-metadata-unavailable');
403
- if (before === null ||
404
- !isObject(record) ||
405
- record.repository !== officeIntegration.skill.repository ||
406
- record.stamp !== before) {
407
- const code = before === null ? 'office-connection-kept' : 'office-local-skill-kept';
408
- return {
409
- changes: [{ code }],
410
- run(report) {
411
- report({ state: 'kept', code });
412
- return Promise.resolve();
413
- },
414
- };
415
- }
416
- }
417
- const isReinstall = selection.action === 'reinstall';
418
- if ((isReinstall || integration === 'mcp' || integration === 'both') &&
419
- observed.registration !== undefined &&
420
- !hasMcp)
421
- throw new Error('integration-source-conflict');
422
- const shouldConnectBoth = integration === 'both' ||
423
- (isReinstall &&
424
- ((hasMcp && integration !== 'mcp') || (observed.skillEvidence !== 'none' && integration === 'mcp')));
425
- if (integration === 'mcp' && !shouldConnectBoth)
426
- return mcp('connect', isReinstall);
427
- if (before !== null &&
428
- selection.fields?.replace !== REPLACE_CONSENT &&
429
- (!isObject(record) || record.stamp !== before))
430
- throw new Error('local-edits-preserved');
431
- if (isReinstall && before !== null && observed.skillEvidence === 'none')
432
- throw new Error('integration-source-conflict');
433
- const revision = await officeRevision(ctx, target);
434
- let skill;
435
- if (before !== null && isObject(record) && record.stamp === before && record.revision === revision && !isReinstall) {
436
- skill = currentSkill(ctx, 'officecli', directory, before);
437
- }
438
- else {
439
- const repository = officeIntegration.skill.repository;
440
- const files = await ctx.machine.source(repository, revision, officeIntegration.skill.folder);
441
- skill = prepareSkillFiles(ctx, { name: 'officecli', directory, stamp: isReinstall ? null : before, sourceRecord: record }, { repository, revision, files, stamp: skillFilesStamp(files) });
223
+ async function officeUpdates(ctx, binary) {
224
+ const files = ['.update', '.update.partial', '.old'].map(suffix => binary + suffix);
225
+ const entries = await ctx.machine.entries(path.dirname(binary));
226
+ return Promise.all(files.map(async (file) => {
227
+ if (entries.some(entry => entry.name === path.basename(file) && entry.kind === 'directory'))
228
+ throw new Error('program-update-conflict');
229
+ return { file, stamp: await ctx.machine.treeStamp(file) };
230
+ }));
231
+ }
232
+ function officeAsset(ctx) {
233
+ const arch = ctx.arch ?? process.arch;
234
+ if (arch !== 'x64' && arch !== 'arm64')
235
+ throw new Error('unsupported-architecture');
236
+ if (ctx.platform === 'win32')
237
+ return `officecli-win-${arch}.exe`;
238
+ if (ctx.platform === 'darwin')
239
+ return `officecli-mac-${arch}`;
240
+ return `officecli-linux-${ctx.libc === 'musl' ? 'alpine-' : ''}${arch}`;
241
+ }
242
+ /** OfficeCLI 自行发现受管原生安装和只读的外部入口,不参与 npm 发现 */
243
+ async function officePrograms(ctx) {
244
+ const values = new Map();
245
+ const native = officeBinary(ctx);
246
+ if ((await ctx.machine.treeStamp(native)) !== null)
247
+ values.set('officecli', { channel: 'native', binary: native });
248
+ for (const binary of await ctx.machine.locate('officecli')) {
249
+ const canonical = await ctx.machine.realpath(binary);
250
+ if (!canonical ||
251
+ [...values.values()].some(program => samePath(ctx, program.binary, binary) || samePath(ctx, program.binary, canonical)))
252
+ continue;
253
+ values.set('officecli:external:' + binary, { channel: 'manual', binary });
442
254
  }
443
- return shouldConnectBoth ? sequence([skill, await mcp('connect', isReinstall)]) : skill;
255
+ return {
256
+ values,
257
+ items: [...values.entries()].map(([id, program]) => ({
258
+ id,
259
+ title: knownTitle('officecli'),
260
+ kind: 'officecli',
261
+ location: program.binary,
262
+ canInstall: program.channel !== 'manual',
263
+ canUninstall: program.channel !== 'manual',
264
+ facts: [
265
+ { code: 'program-exists', detail: program.channel },
266
+ ...(program.channel === 'manual' ? [{ code: 'external-program-preserved' }] : []),
267
+ ],
268
+ })),
269
+ };
270
+ }
271
+ /**
272
+ * 计算 OfficeCLI 固定入口:Windows 本地应用目录,其他平台用户 bin 目录
273
+ *
274
+ * @throws Error - 目录不是绝对路径或指向文件系统根时抛出 invalid-config-root
275
+ */
276
+ function officeBinary(ctx) {
277
+ const root = ctx.platform === 'win32'
278
+ ? path.join(ctx.localAppData ?? path.join(ctx.home, 'AppData/Local'), 'OfficeCli')
279
+ : userBinDirectory(ctx);
280
+ if (!path.isAbsolute(root) || path.resolve(root) === path.parse(path.resolve(root)).root)
281
+ throw new Error('invalid-config-root');
282
+ return path.join(root, ctx.platform === 'win32' ? 'officecli.exe' : 'officecli');
283
+ }
284
+ /**
285
+ * 禁用自更新后探测 OfficeCLI 身份和版本
286
+ *
287
+ * @returns 经确认的三段版本,无法确认时为 null;命令调用拒绝仍向外传播
288
+ * @remarks 版本与帮助探测共用五秒;版本输出缺少程序名时再查帮助
289
+ */
290
+ async function officeVersion(ctx, binary) {
291
+ const deadlineMs = performance.now() + VERSION_PROBE_TIMEOUT_MS;
292
+ const probe = (argument) => ctx.machine.execute(binary, [argument], {
293
+ env: { ...OFFICE_INTEGRATION.suppressSelfUpdate },
294
+ cwd: ctx.home,
295
+ timeoutMs: Math.max(1, Math.ceil(deadlineMs - performance.now())),
296
+ });
297
+ const output = await probe('--version');
298
+ const version = /\b(\d+\.\d+\.\d+)\b/.exec(output.stdout)?.[1];
299
+ if (!succeeded(output) || version === undefined)
300
+ return null;
301
+ if (/\bofficecli\b/i.test(output.stdout))
302
+ return version;
303
+ if (performance.now() >= deadlineMs)
304
+ return null;
305
+ const help = await probe('--help');
306
+ return succeeded(help) && /\bofficecli\b/i.test(help.stdout) ? version : null;
444
307
  }