@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/ccline.js CHANGED
@@ -1,635 +1,167 @@
1
1
  import path from 'node:path';
2
2
  import { fileURLToPath } from 'node:url';
3
- import { isDeepStrictEqual } from 'node:util';
4
- import { parse } from 'smol-toml';
5
- import { knownTitle } from './titles.js';
6
- import { ENABLED_PLUGINS_KEY } from './claude-config.js';
7
- import { errorCode, isObject, READ_COMMAND_TIMEOUT_MS, succeeded } from './machine.js';
8
- import { cancelled, json, removeFields, sequence } from './model.js';
9
- import { isExactVersion, NPM_ENABLE_SCRIPTS, npmInstallArgs, npmUninstallArgs, resolveNpmView, } from './npm-registry.js';
10
- import { compareVersions } from './programs.js';
3
+ import { knownTitle } from './management-catalog.js';
4
+ import { errorCode, isObject, succeeded } from './machine.js';
5
+ import { json, unchanged } from './model.js';
11
6
  import { freezeNpmScope, npmVersion, samePath } from './program-channels.js';
7
+ import { NPM_ENABLE_SCRIPTS, isExactVersion, resolveNpmView, compareVersions } from './npm-registry.js';
8
+ import { npmProgram } from './program-operations.js';
9
+ import { step, sequence } from './work.js';
10
+ import { frozenJsonWork, jsonFingerprint } from './frozen-json.js';
12
11
  const PACKAGE = '@cometix/ccline';
13
12
  const ASSET = fileURLToPath(new URL('../assets/ccline/config.toml', import.meta.url));
14
- const FIELDS = ['statusLine', 'subagentStatusLine'];
15
- const COMPANION_PLUGIN = 'cometix@ccline';
16
- /** ccline --version 输出形状:身份探测允许预发布后缀,执行确认要求精确 2.x.y */
17
- const CCLINE_IDENTITY = /^(?:ccline|ccometixline) \d+\.\d+\.\d+(?:[-+][\w.-]+)?\s*$/i;
18
- const CCLINE_BINARY_VERSION = /^(?:ccline|ccometixline) (2\.\d+\.\d+)\s*$/i;
19
- /** 准备 CCometixLine 变更;计划消费与执行互斥由调用方 CCW 统一管理 */
20
- export function createCcline(options) {
21
- const { machine } = options;
22
- /** ccline 固定落点:不受 CCLINE_HOME 影响 */
23
- const defaultCclineDirectory = path.join(options.home, '.claude', 'ccline');
24
- const binaryFile = path.join(defaultCclineDirectory, options.platform === 'win32' ? 'ccline.exe' : 'ccline');
25
- const settingsFile = options.settingsFile;
26
- // 保留重装中断后的接入模板,供重新准备恢复用户设置
27
- let resumeTemplates;
28
- function cclineDirectory(fields) {
29
- const configured = fields.cclineHome;
30
- const directory = typeof configured === 'string' && configured.trim() !== '' ? configured : options.cclineRoot;
31
- if (!path.isAbsolute(directory))
32
- throw new Error('config-root-relative');
33
- return directory;
34
- }
35
- function isCcline(value) {
36
- if (!isObject(value) || value.type !== 'command' || typeof value.command !== 'string')
37
- return false;
38
- const command = value.command.trim().replaceAll('\\', '/');
39
- return [
40
- 'ccline',
41
- 'ccline.exe',
42
- binaryFile.replaceAll('\\', '/'),
43
- `"${binaryFile.replaceAll('\\', '/')}"`,
44
- '~/.claude/ccline/ccline',
45
- '~/.claude/ccline/ccline.exe',
46
- ].includes(command);
47
- }
48
- const packageVersion = (root) => npmVersion(options, PACKAGE, root, { needsNpm: true });
49
- async function observe(shouldIncludeNpm, shouldIncludeFiles = shouldIncludeNpm) {
50
- const settings = await json(machine, settingsFile);
51
- const fields = {
52
- ...Object.fromEntries(FIELDS.map(field => [field, settings[field]])),
53
- cclineHome: isObject(settings.env) ? settings.env.CCLINE_HOME : undefined,
54
- };
55
- let version = null;
56
- let npmProblem = null;
57
- if (shouldIncludeNpm) {
13
+ /**
14
+ * 管理 CCometixLine 程序、外观和状态栏连接
15
+ *
16
+ * @remarks 仅管理默认目录的 npm 2.x 安装,拒绝降级和覆盖外部状态栏配置
17
+ * 卸载移除自有连接,保留外观、外部程序和其他用户数据
18
+ */
19
+ export function createCcline(ctx) {
20
+ const directory = path.join(ctx.home, '.claude', 'ccline');
21
+ const binary = path.join(directory, ctx.platform === 'win32' ? 'ccline.exe' : 'ccline');
22
+ const config = path.join(directory, 'config.toml');
23
+ const connected = (value) => isObject(value) &&
24
+ value.type === 'command' &&
25
+ typeof value.command === 'string' &&
26
+ ['ccline', 'ccline.exe', binary].includes(value.command);
27
+ const inspect = async () => {
28
+ const settings = await json(ctx.machine, ctx.settingsFile);
29
+ const version = await npmVersion(ctx, PACKAGE);
30
+ const stamp = await ctx.machine.fingerprint(binary);
31
+ return { statusLine: settings.statusLine, version, stamp };
32
+ };
33
+ return {
34
+ async inspect() {
58
35
  try {
59
- version = await packageVersion();
36
+ const state = await inspect();
37
+ return {
38
+ items: [
39
+ {
40
+ id: 'ccline',
41
+ title: knownTitle('ccline'),
42
+ kind: 'ccline',
43
+ location: config,
44
+ canInstall: state.version !== null || state.stamp === null,
45
+ canUninstall: state.version !== null,
46
+ facts: [
47
+ {
48
+ code: state.stamp !== null
49
+ ? 'program-exists'
50
+ : state.version !== null
51
+ ? 'program-missing'
52
+ : 'not-installed',
53
+ },
54
+ ...(state.version ? [{ code: 'program-version', detail: state.version }] : []),
55
+ { code: connected(state.statusLine) ? 'connected' : 'not-connected' },
56
+ ...(state.stamp !== null && state.version === null ? [{ code: 'external-program-preserved' }] : []),
57
+ ],
58
+ },
59
+ ],
60
+ problems: [],
61
+ };
60
62
  }
61
63
  catch (error) {
62
- npmProblem = errorCode(error);
63
- }
64
- }
65
- return {
66
- version,
67
- npmProblem,
68
- binary: shouldIncludeFiles ? await machine.fingerprint(binaryFile) : null,
69
- appearance: shouldIncludeFiles ? await machine.read(path.join(cclineDirectory(fields), 'config.toml')) : null,
70
- fields,
71
- hasCompanionPlugin: isObject(settings[ENABLED_PLUGINS_KEY]) && settings[ENABLED_PLUGINS_KEY][COMPANION_PLUGIN] === true,
72
- };
73
- }
74
- function noDowngrade(version, release) {
75
- if (version === null)
76
- return;
77
- if (compareVersions(version, release) > 0)
78
- throw new Error('newer-version-preserved');
79
- }
80
- function validateAppearance(text) {
81
- let config;
82
- try {
83
- config = parse(text);
84
- }
85
- catch (error) {
86
- throw new Error('invalid-appearance', { cause: error });
87
- }
88
- if (!isObject(config) || config.version !== 2)
89
- throw new Error('appearance-migration-required');
90
- }
91
- function connectionChange(observed, shouldConnect, templates) {
92
- const selected = shouldConnect
93
- ? ['statusLine', ...(isCcline(templates?.subagentStatusLine) ? ['subagentStatusLine'] : [])]
94
- : FIELDS.filter(field => isCcline(observed.fields[field]));
95
- const before = Object.fromEntries(selected.map(field => [field, observed.fields[field]]));
96
- const cclineHome = observed.fields.cclineHome;
97
- const appearanceRoot = shouldConnect ? cclineDirectory(observed.fields) : undefined;
98
- const shouldConfigureHome = appearanceRoot !== undefined && !samePath(options, appearanceRoot, defaultCclineDirectory);
99
- const values = Object.fromEntries(selected.map(field => {
100
- const template = templates?.[field];
101
- const previous = isObject(template) ? template : isObject(before[field]) ? before[field] : {};
102
- return [
103
- field,
104
- shouldConnect
105
- ? {
106
- ...previous,
107
- type: 'command',
108
- command: 'ccline',
109
- padding: typeof previous.padding === 'number' ? previous.padding : 0,
110
- }
111
- : undefined,
112
- ];
113
- }));
114
- let isWritten = false;
115
- const verify = async () => {
116
- if (!selected.length)
117
- return;
118
- const value = await json(machine, settingsFile);
119
- if (selected.some(field => shouldConnect ? !isDeepStrictEqual(value[field], values[field]) : isCcline(value[field])))
120
- throw new Error('connection-not-applied');
121
- if (shouldConnect &&
122
- !isDeepStrictEqual(isObject(value.env) ? value.env.CCLINE_HOME : undefined, shouldConfigureHome ? appearanceRoot : cclineHome))
123
- throw new Error('connection-changed');
124
- };
125
- return {
126
- get isWritten() {
127
- return isWritten;
128
- },
129
- verify,
130
- async run(written) {
131
- if (!isWritten) {
132
- if (selected.length)
133
- await machine.editJson(settingsFile, settings => {
134
- if (shouldConnect) {
135
- const environment = settings.env === undefined ? {} : settings.env;
136
- if (!isObject(environment))
137
- throw new Error('invalid-settings');
138
- if (!isDeepStrictEqual(environment.CCLINE_HOME, cclineHome))
139
- throw new Error('connection-changed');
140
- if (shouldConfigureHome)
141
- settings.env = { ...environment, CCLINE_HOME: appearanceRoot };
142
- }
143
- for (const field of selected) {
144
- if (!isDeepStrictEqual(settings[field], before[field]))
145
- throw new Error('connection-changed');
146
- if (shouldConnect)
147
- settings[field] = values[field];
148
- else
149
- delete settings[field];
150
- }
151
- });
152
- isWritten = true;
153
- written(selected.length > 0);
154
- }
155
- await verify();
156
- },
157
- };
158
- }
159
- async function binaryAtHome() {
160
- const canonical = await machine.realpath(binaryFile);
161
- return canonical !== null && samePath(options, canonical, binaryFile);
162
- }
163
- async function recognizedBinary(stamp) {
164
- if (stamp === null || !(await binaryAtHome()))
165
- return false;
166
- try {
167
- const result = await machine.execute(binaryFile, ['--version'], { timeoutMs: READ_COMMAND_TIMEOUT_MS });
168
- return succeeded(result) && CCLINE_IDENTITY.test(result.stdout.trim());
169
- }
170
- catch {
171
- return false;
172
- }
173
- }
174
- async function prepareUninstall() {
175
- let observed;
176
- let programProblem;
177
- let hasFileObservation = true;
178
- try {
179
- observed = await observe(true);
180
- programProblem = observed.npmProblem;
181
- }
182
- catch (error) {
183
- observed = await observe(false, false);
184
- programProblem = errorCode(error);
185
- hasFileObservation = false;
186
- }
187
- const shouldRemoveBinary = await recognizedBinary(observed.binary);
188
- if (observed.version === null && !shouldRemoveBinary && !FIELDS.some(field => isCcline(observed.fields[field])))
189
- throw new Error(programProblem ?? (observed.binary === null ? 'program-not-installed' : 'manual-program-preserved'));
190
- const npmScope = observed.version === null ? null : await freezeNpmScope(options);
191
- const disconnection = connectionChange(observed, false);
192
- let isDetached = false;
193
- // 尝试证据与删除进度是正交事实:npm 命令可能连带删除二进制,包确认删除后因果证据仍被消费
194
- let hasAttemptedPackageRemoval = false;
195
- let isPackageRemoved = observed.version === null;
196
- let hasAttemptedBinaryRemoval = false;
197
- let isBinaryRemoved = !shouldRemoveBinary;
198
- let isComplete = false;
199
- const changes = () => [
200
- ...(!isDetached && FIELDS.some(field => isCcline(observed.fields[field]))
201
- ? [{ code: 'ccline-disconnect-before-uninstall', detail: settingsFile }]
202
- : []),
203
- ...(!isPackageRemoved ? [{ code: 'program-uninstall', detail: `CCometixLine · npm · ${observed.version}` }] : []),
204
- ...(!isBinaryRemoved
205
- ? [{ code: 'program-uninstall', detail: binaryFile }]
206
- : !shouldRemoveBinary && observed.binary !== null
207
- ? [{ code: 'unrecognized-program-kept', detail: binaryFile }]
208
- : []),
209
- ...(programProblem !== null
210
- ? [
211
- {
212
- code: programProblem === 'npm-not-found' ? 'npm-not-found' : 'program-removal-unconfirmed',
213
- detail: programProblem,
214
- },
215
- ]
216
- : observed.version === null && !shouldRemoveBinary
217
- ? [{ code: 'program-not-installed' }]
218
- : []),
219
- { code: 'keep-user-data' },
220
- { code: 'appearance-kept' },
221
- ...(observed.hasCompanionPlugin ? [{ code: 'ccline-companion-kept', detail: COMPANION_PLUGIN }] : []),
222
- ];
223
- async function verifyPackage(expected) {
224
- await npmScope?.verify();
225
- if ((await packageVersion(npmScope?.npmRoot)) !== expected)
226
- throw new Error('program-changed');
227
- }
228
- async function verifyConnection() {
229
- const current = await observe(false, false);
230
- for (const field of FIELDS) {
231
- if (isDetached
232
- ? isCcline(current.fields[field])
233
- : isCcline(observed.fields[field])
234
- ? !isDeepStrictEqual(current.fields[field], observed.fields[field])
235
- : isCcline(current.fields[field]))
236
- throw new Error('connection-changed');
237
- }
238
- }
239
- async function verifyRemoved() {
240
- await verifyConnection();
241
- if (observed.version !== null)
242
- await verifyPackage(null);
243
- if (shouldRemoveBinary && (await machine.fingerprint(binaryFile)) !== null)
244
- throw new Error('program-changed');
245
- }
246
- const operation = {
247
- get changes() {
248
- return changes();
249
- },
250
- async run(report, signal) {
251
- cancelled(signal);
252
- await verifyConnection();
253
- if (hasAttemptedPackageRemoval && !isPackageRemoved) {
254
- await npmScope?.verify();
255
- const current = await packageVersion(npmScope?.npmRoot);
256
- if (current === null) {
257
- isPackageRemoved = true;
258
- report({ state: 'done', code: 'package-removed', detail: PACKAGE });
259
- }
260
- else if (current !== observed.version)
261
- throw new Error('program-changed');
262
- }
263
- if (!isPackageRemoved)
264
- await verifyPackage(observed.version);
265
- else if (observed.version !== null)
266
- await verifyPackage(null);
267
- if (hasFileObservation) {
268
- const current = await machine.fingerprint(binaryFile);
269
- if ((hasAttemptedPackageRemoval || hasAttemptedBinaryRemoval) &&
270
- shouldRemoveBinary &&
271
- !isBinaryRemoved &&
272
- current === null) {
273
- isBinaryRemoved = true;
274
- report({ state: 'done', code: 'program-removed', detail: binaryFile });
275
- }
276
- else if (current !== (isBinaryRemoved && shouldRemoveBinary ? null : observed.binary))
277
- throw new Error('program-changed');
278
- if (shouldRemoveBinary && !isBinaryRemoved && !(await binaryAtHome()))
279
- throw new Error('program-changed');
280
- }
281
- if (!isDetached) {
282
- await disconnection.run(hasChanged => {
283
- isDetached = true;
284
- resumeTemplates = undefined;
285
- report({ state: hasChanged ? 'done' : 'kept', code: hasChanged ? 'disconnected' : 'no-connection' });
286
- });
287
- }
288
- cancelled(signal);
289
- if (!isPackageRemoved) {
290
- await verifyConnection();
291
- if ((await machine.fingerprint(binaryFile)) !== observed.binary ||
292
- (shouldRemoveBinary && !(await binaryAtHome())))
293
- throw new Error('program-changed');
294
- hasAttemptedPackageRemoval = true;
295
- const result = await machine.npm(npmUninstallArgs(['uninstall', '-g', ...(npmScope?.args ?? []), '--ignore-scripts', PACKAGE]));
296
- let after;
297
- try {
298
- await npmScope?.verify();
299
- after = await packageVersion(npmScope?.npmRoot);
300
- }
301
- catch (error) {
302
- throw new Error('program-removal-unconfirmed', { cause: error });
303
- }
304
- if (after !== null)
305
- throw new Error(succeeded(result) ? 'program-still-installed' : 'npm-uninstall-failed');
306
- isPackageRemoved = true;
307
- report({ state: 'done', code: 'package-removed', detail: PACKAGE });
308
- if (shouldRemoveBinary && (await machine.fingerprint(binaryFile)) === null) {
309
- isBinaryRemoved = true;
310
- report({ state: 'done', code: 'program-removed', detail: binaryFile });
311
- }
312
- }
313
- cancelled(signal);
314
- if (!isBinaryRemoved) {
315
- await verifyConnection();
316
- if (observed.binary === null)
317
- throw new Error('program-changed');
318
- hasAttemptedBinaryRemoval = true;
319
- try {
320
- await machine.remove(binaryFile, observed.binary);
321
- }
322
- catch (error) {
323
- if ((await machine.fingerprint(binaryFile)) !== null)
324
- throw error;
325
- }
326
- if ((await machine.fingerprint(binaryFile)) !== null)
327
- throw new Error('program-removal-unconfirmed');
328
- isBinaryRemoved = true;
329
- report({ state: 'done', code: 'program-removed', detail: binaryFile });
330
- }
331
- cancelled(signal);
332
- await verifyRemoved();
333
- if (programProblem === 'npm-not-found')
334
- report({ state: 'kept', code: 'npm-not-found' });
335
- else if (programProblem === null &&
336
- observed.version === null &&
337
- !shouldRemoveBinary &&
338
- observed.binary === null)
339
- report({ state: 'kept', code: 'program-not-installed' });
340
- if (observed.binary !== null && !shouldRemoveBinary)
341
- report({ state: 'kept', code: 'unrecognized-program-kept', detail: binaryFile });
342
- const copies = [];
343
- for (const file of await machine.locate('ccline'))
344
- if ((await machine.realpath(file)) !== null)
345
- copies.push(file);
346
- if (copies.length)
347
- report({ state: 'kept', code: 'program-other-copies-kept', detail: copies.join('\n') });
348
- report({ state: 'kept', code: 'appearance-kept' });
349
- report({ state: 'kept', code: 'keep-user-data' });
350
- isComplete = true;
351
- if (programProblem !== null && programProblem !== 'npm-not-found') {
352
- report({ state: 'failed', code: 'program-removal-unconfirmed', detail: programProblem });
353
- throw new Error('program-removal-unconfirmed');
354
- }
355
- },
356
- remaining: () => (isComplete ? undefined : operation),
357
- verify: verifyRemoved,
358
- };
359
- return operation;
360
- }
361
- async function inspectItem() {
362
- // 全量探测失败才降级只读探测
363
- let observed = null;
364
- try {
365
- observed = await observe(true);
366
- const isConnected = FIELDS.some(field => isCcline(observed?.fields[field]));
367
- let problem = observed.npmProblem ?? undefined;
368
- if (observed.appearance !== null) {
369
- try {
370
- validateAppearance(observed.appearance);
371
- }
372
- catch (error) {
373
- problem = errorCode(error);
374
- }
64
+ return {
65
+ items: [
66
+ {
67
+ id: 'ccline',
68
+ title: knownTitle('ccline'),
69
+ kind: 'ccline',
70
+ location: config,
71
+ canInstall: true,
72
+ facts: [],
73
+ problem: errorCode(error),
74
+ },
75
+ ],
76
+ problems: [],
77
+ };
375
78
  }
376
- const actions = observed.binary !== null ? ['connect'] : ['install'];
377
- if (observed.binary !== null && observed.npmProblem === null)
378
- actions.push('update', 'reinstall');
379
- if (isConnected)
380
- actions.push('detach');
381
- if (observed.version !== null || (await recognizedBinary(observed.binary)))
382
- actions.push('uninstall');
383
- return {
384
- id: 'ccline',
385
- title: knownTitle('ccline'),
386
- kind: 'ccline',
387
- canInstall: true,
388
- ...(problem ? { problem } : {}),
389
- facts: [
390
- {
391
- code: observed.binary !== null
392
- ? 'program-exists'
393
- : observed.npmProblem !== null
394
- ? 'program-inspection-warning'
395
- : 'not-installed',
396
- ...(observed.version ? { detail: observed.version } : {}),
397
- },
398
- { code: isConnected ? 'connected' : 'not-connected' },
399
- { code: observed.appearance !== null ? 'appearance-kept' : 'appearance-missing' },
400
- { code: observed.hasCompanionPlugin ? 'ccline-companion-present' : 'ccline-companion-missing' },
401
- ],
402
- actions,
403
- };
404
- }
405
- catch (error) {
406
- const fallback = await observe(false, false).catch(() => null);
407
- return {
408
- id: 'ccline',
409
- title: knownTitle('ccline'),
410
- kind: 'ccline',
411
- canInstall: true,
412
- facts: [],
413
- actions: [
414
- 'install',
415
- ...(fallback && FIELDS.some(field => isCcline(fallback.fields[field])) ? ['detach'] : []),
416
- ],
417
- problem: errorCode(error),
418
- };
419
- }
420
- }
421
- return {
422
- async inspect() {
423
- return { items: [await inspectItem()], problems: [] };
424
79
  },
425
80
  async prepare(selection) {
426
81
  if (selection.id !== 'ccline')
427
82
  throw new Error('unknown-selection');
428
- let action = selection.action;
429
- if (action === 'uninstall')
430
- return prepareUninstall();
431
- if (action === 'install' && (await machine.fingerprint(binaryFile)) !== null)
432
- action = 'connect';
433
- if (action !== 'install' &&
434
- action !== 'connect' &&
435
- action !== 'update' &&
436
- action !== 'reinstall' &&
437
- action !== 'detach')
438
- throw new Error('action-unavailable');
439
- let release = '2.0.1';
440
- let releaseRegistry = null;
441
- const observed = await observe(action !== 'detach' && action !== 'connect', action !== 'detach');
442
- if (observed.npmProblem !== null)
443
- throw new Error(observed.npmProblem);
444
- if (action === 'detach' && !FIELDS.some(field => isCcline(observed.fields[field])))
445
- throw new Error('no-connection');
446
- if (action === 'detach') {
447
- resumeTemplates = undefined;
448
- return removeFields(options, settingsFile, Object.fromEntries(FIELDS.filter(field => isCcline(observed.fields[field])).map(field => [field, observed.fields[field]])), [{ code: 'ccline-detach', detail: settingsFile }, { code: 'appearance-kept' }], { state: 'done', code: 'disconnected' });
449
- }
450
- const npmScope = action === 'connect' ? null : await freezeNpmScope(options);
451
- if (npmScope !== null && (await packageVersion(npmScope.npmRoot)) !== observed.version)
452
- throw new Error('program-changed');
453
- if (action !== 'connect') {
454
- const resolved = await resolveNpmView(machine, `${PACKAGE}@latest`, 'version', value => isExactVersion(value) ? value : null);
455
- if (resolved === null)
456
- throw new Error('source-unavailable');
457
- release = resolved.value;
458
- if (!/^2\.\d+\.\d+$/.test(release))
459
- throw new Error('unsupported-ccline-release');
460
- releaseRegistry = resolved.registry;
461
- noDowngrade(observed.version, release);
462
- }
463
- if (observed.appearance !== null)
464
- validateAppearance(observed.appearance);
465
- if (action === 'update' && observed.version === null)
466
- throw new Error('npm-package-missing');
467
- if ((action === 'install' || action === 'reinstall') && observed.binary !== null && observed.version === null)
468
- throw new Error('manual-program-preserved');
469
- if (action === 'connect' && observed.binary === null)
470
- throw new Error('program-not-ready');
471
- const shouldRestoreSubagent = isCcline(resumeTemplates?.subagentStatusLine) ||
472
- (action === 'reinstall' && isCcline(observed.fields.subagentStatusLine));
473
- const connectionTemplates = {
474
- ...resumeTemplates,
475
- ...Object.fromEntries(Object.entries(observed.fields).filter(([, value]) => value !== undefined)),
476
- };
477
- const disconnection = action === 'reinstall' ? connectionChange(observed, false) : undefined;
478
- let isCommandCompleted = false;
479
- let commandStamp;
480
- let programStamp = observed.binary;
481
- const program = {
482
- get changes() {
483
- return [
484
- action === 'connect'
485
- ? { code: 'ccline-program-kept', detail: binaryFile }
486
- : isCommandCompleted
487
- ? { code: 'program-installation-confirm', detail: binaryFile }
488
- : { code: action === 'update' ? 'ccline-program-update' : 'ccline-program-prepare', detail: release },
489
- ...(disconnection && !disconnection.isWritten
490
- ? [{ code: 'ccline-reinstall-connection', detail: settingsFile }]
491
- : []),
492
- ];
493
- },
494
- async run(report, signal) {
495
- cancelled(signal);
496
- await npmScope?.verify();
497
- if (isCommandCompleted) {
498
- if (commandStamp === undefined)
499
- throw new Error('program-installation-unconfirmed');
500
- if ((await machine.fingerprint(binaryFile)) !== commandStamp)
501
- throw new Error('program-changed');
502
- }
503
- else if ((action !== 'connect' && (await packageVersion(npmScope?.npmRoot)) !== observed.version) ||
504
- (await machine.fingerprint(binaryFile)) !== observed.binary)
505
- throw new Error('program-changed');
506
- if (!isCommandCompleted && disconnection)
507
- await disconnection.run(hasChanged => {
508
- resumeTemplates = connectionTemplates;
509
- for (const field of FIELDS)
510
- if (isCcline(observed.fields[field]))
511
- observed.fields[field] = undefined;
512
- report({ state: hasChanged ? 'done' : 'kept', code: hasChanged ? 'disconnected' : 'no-connection' });
513
- });
514
- cancelled(signal);
515
- if (!isCommandCompleted &&
516
- action !== 'connect' &&
517
- (action === 'reinstall' || action === 'update' || observed.version !== release || observed.binary === null)) {
518
- const args = npmInstallArgs([
519
- 'install',
520
- '-g',
521
- ...(npmScope?.args ?? []),
522
- ...(action === 'reinstall' ? ['--force'] : []),
523
- ...NPM_ENABLE_SCRIPTS,
524
- `${PACKAGE}@${release}`,
525
- ], releaseRegistry);
526
- const installed = await machine.npm(args);
527
- if (!succeeded(installed))
528
- throw new Error('npm-install-failed');
529
- isCommandCompleted = true;
530
- report({ state: 'done', code: 'package-command-completed' });
531
- try {
532
- commandStamp = await machine.fingerprint(binaryFile);
533
- }
534
- catch (error) {
535
- throw new Error('program-installation-unconfirmed', { cause: error });
536
- }
537
- }
538
- await npmScope?.verify();
539
- if ((action !== 'connect' && (await packageVersion(npmScope?.npmRoot)) !== release) ||
540
- (await machine.fingerprint(binaryFile)) === null)
541
- throw new Error('program-not-ready');
542
- const versionSignal = signal?.aborted ? undefined : signal;
543
- const version = await machine.execute(binaryFile, ['--version'], {
544
- timeoutMs: READ_COMMAND_TIMEOUT_MS,
545
- ...(versionSignal ? { signal: versionSignal } : {}),
546
- });
547
- if (versionSignal?.aborted)
548
- cancelled(signal);
549
- const binaryVersion = CCLINE_BINARY_VERSION.exec(version.stdout.trim())?.[1];
550
- if (!succeeded(version) || binaryVersion === undefined || (action !== 'connect' && binaryVersion !== release))
551
- throw new Error('binary-version-mismatch');
552
- programStamp = await machine.fingerprint(binaryFile);
553
- report({ state: 'done', code: 'program-ready' });
83
+ if (!samePath(ctx, ctx.cclineRoot, directory))
84
+ throw new Error('external-program-preserved');
85
+ const before = await inspect();
86
+ const uninstall = selection.action === 'uninstall';
87
+ if (before.stamp !== null && before.version === null)
88
+ throw new Error('channel-not-supported');
89
+ if (uninstall && before.version === null)
90
+ throw new Error('program-not-installed');
91
+ const scope = await freezeNpmScope(ctx);
92
+ const release = uninstall
93
+ ? null
94
+ : await resolveNpmView(ctx.machine, PACKAGE + '@latest', 'version', value => isExactVersion(value) ? value : null);
95
+ if (!uninstall && !release)
96
+ throw new Error('source-unavailable');
97
+ if (release && !release.value.startsWith('2.'))
98
+ throw new Error('unsupported-ccline-release');
99
+ if (release && before.version && compareVersions(before.version, release.value) > 0)
100
+ throw new Error('newer-version-preserved');
101
+ const program = npmProgram(ctx, {
102
+ name: PACKAGE,
103
+ binary,
104
+ version: release?.value ?? null,
105
+ beforeVersion: before.version,
106
+ beforeStamp: before.stamp,
107
+ scope,
108
+ registry: release?.registry ?? null,
109
+ args: NPM_ENABLE_SCRIPTS,
110
+ }, [
111
+ {
112
+ code: uninstall ? 'program-uninstall' : before.version ? 'ccline-program-update' : 'ccline-program-prepare',
113
+ detail: PACKAGE,
554
114
  },
555
- async verify() {
556
- await npmScope?.verify();
557
- if ((await machine.fingerprint(binaryFile)) !== programStamp)
558
- throw new Error('program-changed');
559
- },
560
- };
561
- const operations = [program];
562
- if (action === 'update')
563
- operations.push({
564
- changes: [{ code: 'ccline-settings-kept' }],
565
- run: report => Promise.resolve(report({ state: 'kept', code: 'appearance-kept' })),
566
- });
567
- else {
568
- const styleFile = path.join(cclineDirectory(observed.fields), 'config.toml');
569
- let appearanceText = observed.appearance;
570
- let isAppearanceWritten = false;
571
- const verifyAppearance = async () => {
572
- if ((await machine.read(styleFile)) !== appearanceText)
573
- throw new Error('appearance-changed');
574
- };
575
- operations.push({
576
- changes: [
577
- observed.appearance === null ? { code: 'appearance-copy', detail: styleFile } : { code: 'appearance-kept' },
578
- ],
579
- async run(report) {
580
- const existing = await machine.read(styleFile);
581
- if (existing !== (isAppearanceWritten ? appearanceText : observed.appearance))
582
- throw new Error('appearance-changed');
583
- if (existing === null) {
584
- const asset = await machine.read(ASSET);
585
- if (asset === null)
586
- throw new Error('asset-missing');
587
- validateAppearance(asset);
588
- if (!(await machine.initialize(styleFile, asset)))
589
- throw new Error('appearance-changed');
590
- isAppearanceWritten = true;
591
- appearanceText = asset;
592
- report({ state: 'done', code: 'appearance-copied' });
593
- }
594
- else if (!isAppearanceWritten)
595
- report({ state: 'kept', code: 'appearance-kept' });
596
- await verifyAppearance();
597
- },
598
- verify: verifyAppearance,
115
+ { code: 'keep-user-data' },
116
+ ]);
117
+ const original = before.statusLine;
118
+ if (!uninstall && original !== undefined && !connected(original))
119
+ throw new Error('local-edits-preserved');
120
+ const target = uninstall ? undefined : { type: 'command', command: 'ccline', padding: 0 };
121
+ const changes = [{ code: uninstall ? 'ccline-detach' : 'ccline-connect', detail: ctx.settingsFile }];
122
+ const connection = uninstall && !connected(original)
123
+ ? step(changes, () => Promise.resolve({ state: 'complete', effects: [{ state: 'kept', code: 'no-connection' }] }))
124
+ : frozenJsonWork(ctx, {
125
+ file: ctx.settingsFile,
126
+ fields: [{ path: ['statusLine'], before: jsonFingerprint(original), value: target }],
127
+ changes,
128
+ effects: [{ state: 'done', code: uninstall ? 'disconnected' : 'connected' }],
599
129
  });
600
- let connection;
601
- operations.push({
602
- changes: [
603
- ...(shouldRestoreSubagent ? [{ code: 'ccline-subagent-restore', detail: settingsFile }] : []),
604
- {
605
- code: observed.fields.statusLine !== undefined && !isCcline(observed.fields.statusLine)
606
- ? 'ccline-statusline-replace'
607
- : 'ccline-connect',
608
- detail: settingsFile,
609
- },
610
- ...(!samePath(options, cclineDirectory(observed.fields), defaultCclineDirectory)
611
- ? [{ code: 'ccline-root-configure', detail: cclineDirectory(observed.fields) }]
612
- : []),
613
- ],
614
- async run(report) {
615
- connection ??= connectionChange(observed, true, connectionTemplates);
616
- await connection.run(() => report({ state: 'done', code: 'connected' }));
617
- resumeTemplates = undefined;
618
- },
619
- async verify() {
620
- await connection?.verify();
621
- },
622
- });
623
- }
624
- const steps = sequence(operations);
625
- const operation = {
626
- ...steps,
627
- get changes() {
628
- return steps.changes;
629
- },
630
- remaining: () => isCommandCompleted && commandStamp === undefined ? undefined : steps.remaining?.() ? operation : undefined,
631
- };
632
- return operation;
130
+ if (uninstall)
131
+ return { ...sequence([connection, program]), action: 'uninstall' };
132
+ const existing = await ctx.machine.read(config);
133
+ const text = existing ?? (await ctx.machine.read(ASSET));
134
+ if (text === null)
135
+ throw new Error('asset-missing');
136
+ const appearance = step([{ code: existing === null ? 'appearance-copy' : 'appearance-kept' }], async () => {
137
+ const current = await ctx.machine.read(config);
138
+ if (current === text)
139
+ return {
140
+ state: 'complete',
141
+ effects: [
142
+ {
143
+ state: existing === null ? 'done' : 'kept',
144
+ code: existing === null ? 'appearance-copied' : 'appearance-kept',
145
+ },
146
+ ],
147
+ };
148
+ unchanged(current, existing);
149
+ return { state: 'ready' };
150
+ }, async () => {
151
+ if (!(await ctx.effects.initialize(config, text)))
152
+ throw new Error('appearance-changed');
153
+ return { receipt: { kind: 'returned', failure: null } };
154
+ });
155
+ const ready = step([], async () => {
156
+ const version = await ctx.machine.execute(binary, ['--version']);
157
+ const [programName, programVersion] = version.stdout.trim().split(/\s+/);
158
+ if (!succeeded(version) ||
159
+ (programName !== 'ccline' && programName !== 'ccometixline') ||
160
+ programVersion !== release?.value)
161
+ throw new Error('binary-version-mismatch');
162
+ return { state: 'complete', effects: [{ state: 'done', code: 'program-ready' }] };
163
+ });
164
+ return { ...sequence([program, ready, appearance, connection]), action: before.version ? 'update' : 'install' };
633
165
  },
634
166
  };
635
167
  }