@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/terminal.js CHANGED
@@ -1,529 +1,228 @@
1
- import { isDeepStrictEqual } from 'node:util';
2
- import { ACTION_NAMES, BACK_TO_HOME, contentEntries, contentName, contentOrder, contentRows, DEFAULT_PREFERENCES, describeChange, describeDiagnostic, describeItem, describeInspectionProblem, describePreparation, effectiveConnection, entryRows, entrySelected, failureLabel, GROUPS, HOME_TITLE, inspectedItems, MODEL_FIELDS, planVerb, preparationTitle, PROBLEM_MARK, reason, SETTINGS_FIELDS, SETTINGS_LANGUAGES, SETTINGS_STYLES, UNCONFIRMED, USER_SCOPE_SUFFIX, } from './render.js';
3
- import { createRunPresentation } from './run-presentation.js';
4
- import { apiConfigurationProblem, CLAUDE_DATA_ID, defaultInstallAction, kindOf, REPLACE_CONSENT, restOf, } from './model.js';
5
- import { knownTitle } from './titles.js';
6
- async function chooseWithDetails(terminal, title, choices, details, defaultIndex = choices.length - 1) {
7
- let focus = defaultIndex;
8
- while (true) {
9
- const choice = await terminal.choose(title, [...choices, '查看详情'], focus, choices.length - 1);
10
- if (choice !== choices.length)
11
- return choice;
12
- await terminal.choose(details, ['返回']);
13
- focus = choice;
14
- }
15
- }
16
- async function editSettings(item, editor, terminal, prior) {
17
- const values = { ...item.values, ...prior?.fields };
18
- const fields = { ...prior?.fields };
19
- if (editor !== 'connection') {
20
- const choices = editor === 'language' ? SETTINGS_LANGUAGES : SETTINGS_STYLES;
21
- const current = values[editor] ?? DEFAULT_PREFERENCES[editor];
22
- const index = await terminal.choose(editor === 'language' ? '默认输出语言' : '输出风格', [...choices.map(choice => choice.label), '返回'], Math.max(0, choices.findIndex(choice => choice.value === current)));
23
- const choice = choices[index];
24
- if (choice === undefined)
25
- return null;
26
- fields[editor] = choice.value;
27
- return { id: item.id, fields };
28
- }
29
- const mode = await terminal.choose('模型配置', ['官方登录', '第三方 API', '返回'], effectiveConnection(values, item.facts) === 'api' ? 1 : 0);
30
- if (mode === 2)
31
- return null;
32
- for (const field of SETTINGS_FIELDS.connection)
33
- delete fields[field];
34
- if (mode === 0) {
35
- fields.mode = 'official';
36
- fields.login = 'yes';
37
- }
38
- else {
39
- const api = { mode: 'api', auth: values.auth ?? 'key' };
40
- for (const { key } of MODEL_FIELDS)
41
- if (values[key] !== undefined)
42
- api[key] = values[key];
43
- for (const key of ['baseUrl', 'secret'])
44
- if (prior?.fields?.[key] !== undefined)
45
- api[key] = prior.fields[key];
46
- const edited = await terminal.form('第三方 API', [
47
- { key: 'baseUrl', label: 'Base URL', value: api.baseUrl ?? '', placeholder: '必填' },
48
- { key: 'secret', label: 'API Key', value: api.secret ?? '', secret: true, placeholder: '必填' },
49
- ...MODEL_FIELDS.map(model => ({
50
- key: model.key,
51
- label: model.label,
52
- value: api[model.key] ?? '',
53
- placeholder: '选填,可添加 [1m]',
54
- })),
55
- ], form => {
56
- const problem = apiConfigurationProblem(form.baseUrl, Boolean(form.secret?.trim()));
57
- return problem
58
- ? {
59
- message: reason(problem),
60
- field: problem === 'credential-required' ? 'secret' : 'baseUrl',
61
- detail: describeDiagnostic({ code: problem }),
62
- }
63
- : null;
64
- });
65
- if (edited === null)
66
- return null;
67
- for (const [key, value] of Object.entries(edited)) {
68
- const trimmed = value.trim();
69
- if (key === 'secret') {
70
- if (trimmed) {
71
- api.secret = trimmed;
72
- api.auth = 'key';
73
- }
74
- }
75
- else if (trimmed || Object.hasOwn(api, key))
76
- api[key] = trimmed;
77
- }
78
- Object.assign(fields, api);
79
- }
80
- if (values.language === undefined)
81
- fields.language = DEFAULT_PREFERENCES.language;
82
- if (values.outputStyle === undefined)
83
- fields.outputStyle = DEFAULT_PREFERENCES.outputStyle;
84
- return { id: item.id, fields };
85
- }
86
- const TASK_ORDER = ['install', 'inspect', 'uninstall', 'clean'];
87
- /** 草稿标记"仅解除接入":勾选与路由三处共享同一字面量 */
88
- const DETACH_REMOVAL = { removal: 'detach' };
89
- const TASKS = {
90
- install: { name: '安装套件', actions: ['install', 'connect', 'configure'] },
91
- inspect: { name: '检查套件', actions: [] },
92
- uninstall: { name: '卸载套件', actions: ['uninstall', 'detach'] },
93
- clean: { name: '清理数据', actions: ['clean'] },
1
+ import { errorCode } from './machine.js';
2
+ import { apiConfigurationProblem } from './settings.js';
3
+ import { HOME_TITLE, BACK_TO_HOME, contentRow, contentOrder, describeInspection, describeChange, describePreparation, describeRun, describePlan, MODEL_FIELDS, DEFAULT_PREFERENCES, effectiveConnection, SETTINGS_EDITORS, SETTINGS_LANGUAGES, SETTINGS_STYLES, settingsRow, reason, createRunPresentation, } from './render.js';
4
+ const HOME_ACTIONS = [
5
+ { label: '安装配置', id: 'install' },
6
+ { label: '检查状态', id: 'inspect' },
7
+ { label: '移除程序', id: 'uninstall' },
8
+ { label: '清理数据', id: 'clean' },
9
+ { label: '退出程序', id: 'exit' },
10
+ ];
11
+ const TASK_TEXT = {
12
+ install: { title: '安装配置', empty: '没有可配置项目', confirm: '确认安装' },
13
+ uninstall: {
14
+ title: '移除程序\n保留会话记录和个人文件,移除所选接入配置',
15
+ empty: '没有可移除项目',
16
+ confirm: '确认移除',
17
+ },
18
+ clean: {
19
+ title: '清理数据\n删除所选数据,保留程序、配置与凭据',
20
+ empty: '没有可清理数据',
21
+ confirm: '确认清理',
22
+ },
94
23
  };
95
- function availableActions(item, task) {
96
- if (task === 'install' && item.skillSet)
97
- return [];
98
- if (task === 'install')
99
- return item.canInstall ? [defaultInstallAction(item.id)] : item.actions.filter(action => action === 'connect');
100
- return item.actions
101
- .filter(action => TASKS[task].actions.includes(action))
102
- .sort((a, b) => Number(b === 'uninstall') - Number(a === 'uninstall'));
103
- }
104
- export async function runTerminal(ccw, terminal, signal) {
105
- const focus = { install: 0, inspect: 0, uninstall: 0, clean: 0 };
106
- const knownItems = new Map();
107
- const drafts = {
108
- install: new Map(),
109
- inspect: new Map(),
110
- uninstall: new Map(),
111
- clean: new Map(),
112
- };
113
- const problems = new Map();
114
- let task = 'inspect';
115
- let pending;
116
- let removeClaudeData = false;
117
- const selected = () => drafts[task];
118
- const dataPending = () => task === 'uninstall' && pending?.task === task && pending.removeData === true;
119
- const dataVisible = () => task === 'uninstall' &&
120
- ([...selected().keys()].some(id => knownItems.get(id)?.kind === 'claude' || kindOf(id) === 'claude') ||
121
- dataPending());
122
- const hasSelection = () => selected().size > 0 || dataPending();
123
- const reconcile = () => {
124
- if (task === 'uninstall' && !dataVisible())
125
- removeClaudeData = false;
126
- };
127
- const changeSelection = (edit) => {
128
- const before = [...selected()];
129
- const dataBefore = removeClaudeData;
130
- edit();
131
- if (!isDeepStrictEqual(before, [...selected()]) || dataBefore !== removeClaudeData) {
132
- pending = undefined;
133
- problems.delete(CLAUDE_DATA_ID);
134
- }
135
- reconcile();
136
- };
137
- const select = (id, pick) => {
138
- changeSelection(() => {
139
- if (pick)
140
- selected().set(id, pick);
141
- else
142
- selected().delete(id);
143
- problems.delete(id);
144
- });
145
- };
24
+ /**
25
+ * 驱动主菜单、配置草稿、变更预览和确认后的执行
26
+ *
27
+ * @param signal - 传递给检查、计划准备与执行;取消不会唤醒正在等待输入的菜单或表单
28
+ * @param details - 在检查、预览、执行结果和操作失败说明中附带原因码
29
+ * @remarks 只有用户确认预览后才调用 apply;取消不回滚已执行变更,终端由调用方关闭
30
+ * @throws Error - 未在操作页处理的终端或检查失败会拒绝 Promise
31
+ */
32
+ export async function runTerminal(ccw, terminal, signal, details = false) {
146
33
  while (!signal?.aborted) {
147
- const selectedTask = TASK_ORDER[await terminal.choose(HOME_TITLE, [...TASK_ORDER.map(task => TASKS[task].name), '退出'])];
148
- if (selectedTask === undefined || signal?.aborted)
34
+ const choice = await terminal.choose(HOME_TITLE, HOME_ACTIONS.map(action => action.label), 0, {
35
+ home: true,
36
+ });
37
+ const action = HOME_ACTIONS[choice]?.id;
38
+ if (action === undefined || action === 'exit' || signal?.aborted)
149
39
  return;
150
- task = selectedTask;
151
- reconcile();
152
- let returnToMenu = false;
153
- let view = null;
154
- problems.clear();
155
- while (!returnToMenu && !signal?.aborted) {
156
- if (view === null) {
157
- view = await terminal.wait(`${TASKS[task].name} · 检查环境`, reading => ccw.inspect(task === 'clean' ? 'data' : 'contents', reading), signal);
158
- if (view === null || signal?.aborted)
159
- break;
160
- for (const item of view.items)
161
- knownItems.set(item.id, item);
162
- }
163
- const ordered = contentOrder(task === 'inspect' ? inspectedItems(view.items) : view.items);
164
- if (task === 'inspect') {
165
- const choices = [...contentRows(ordered), '刷新检查', BACK_TO_HOME];
166
- const index = await terminal.choose(`检查套件${USER_SCOPE_SUFFIX}${view.problems.length ? `\n${PROBLEM_MARK}${UNCONFIRMED}` : ''}`, view.problems.length ? [...choices, '查看详情'] : choices, focus.inspect, ordered.length + 1);
167
- focus.inspect = index;
168
- if (view.problems.length && index === choices.length) {
169
- await terminal.choose(`检查详情\n${view.problems.map(describeInspectionProblem).join('\n')}`, ['返回']);
170
- continue;
171
- }
172
- if (index === ordered.length) {
173
- view = null;
174
- continue;
175
- }
176
- const item = ordered[index];
177
- if (item === undefined)
178
- break;
179
- const installTarget = item.kind === 'skill' || item.kind === 'command' ? undefined : item;
180
- const routes = [
181
- ...(installTarget && availableActions(installTarget, 'install').length
182
- ? [{ label: '进入安装', task: 'install', item: installTarget, maintenance: undefined }]
183
- : []),
184
- // 识别与操作取并集:识别到 update 动作的对象在此提供更新入口
185
- ...(item.actions.includes('update')
186
- ? [{ label: '进入更新', task: 'install', item, maintenance: 'update' }]
187
- : []),
188
- ...(availableActions(item, 'uninstall').length
189
- ? [{ label: '进入卸载', task: 'uninstall', item, maintenance: undefined }]
190
- : []),
191
- ];
192
- const route = routes[await chooseWithDetails(terminal, describeItem(item), [...routes.map(route => route.label), '返回'], describeItem(item, true), routes.length)];
193
- if (!route)
194
- continue;
195
- task = route.task;
196
- reconcile();
197
- const target = route.item;
198
- const priorFields = selected().get(target.id)?.fields;
199
- const selection = target.kind === 'settings' && task === 'install'
200
- ? await editSettings(target, 'connection', terminal, selected().get(target.id))
201
- : {
202
- id: target.id,
203
- ...(route.maintenance
204
- ? {
205
- maintenance: route.maintenance,
206
- // 保留既有草稿字段(如"备份并替换"的放行同意),不因重进路由而丢失
207
- ...(priorFields ? { fields: priorFields } : {}),
208
- }
209
- : {}),
210
- ...(task === 'uninstall' && !target.actions.includes('uninstall') ? DETACH_REMOVAL : {}),
211
- };
212
- if (selection && (target.kind === 'settings' || route.maintenance !== undefined || !selected().has(target.id)))
213
- select(target.id, selection);
214
- continue;
215
- }
216
- const taskAction = task;
217
- // 已选更新的成员在安装页保留一行:可见、可取消;未选时仍由套件入口代表
218
- const items = ordered.filter(item => availableActions(item, task).length > 0 ||
219
- (task === 'install' && selected().get(item.id)?.maintenance !== undefined));
220
- const remaining = pending?.task === task ? pending : undefined;
221
- const missing = new Set([...selected().keys()].filter(id => !remaining && !items.some(item => item.id === id)));
222
- if (remaining)
223
- for (const id of selected().keys()) {
224
- const item = knownItems.get(id);
225
- if (item && !items.some(value => value.id === id))
226
- items.push(item);
227
- }
228
- for (const id of missing) {
229
- const item = knownItems.get(id);
230
- if (item)
231
- items.push(item);
232
- problems.set(id, 'selected-item-unavailable');
233
- }
234
- const entries = contentEntries(items, task === 'install');
235
- const notices = [];
236
- if (task === 'uninstall') {
237
- notices.push('默认保留用户配置与数据');
238
- if (!items.length && !hasSelection())
239
- notices.push('无可卸载项');
240
- }
241
- if (task === 'clean') {
242
- notices.push('保留程序、配置与凭据');
243
- if (!items.length)
244
- notices.push('无可清理数据');
245
- }
246
- if (problems.size)
247
- notices.push(PROBLEM_MARK + failureLabel(task));
248
- if (view.problems.length)
249
- notices.push(`${PROBLEM_MARK}${UNCONFIRMED}`);
250
- const title = [TASKS[task].name + USER_SCOPE_SUFFIX, ...notices].join('\n');
251
- const page = () => {
252
- const labels = entryRows(entries, selected());
253
- const showData = dataVisible();
254
- const dataProblem = problems.get(CLAUDE_DATA_ID);
255
- const rows = entries.map((entry, index) => {
256
- const problem = problems.get(entry.item.id);
257
- const editable = task === 'install' && entry.editor !== undefined;
258
- const maintenance = task === 'install' ? selected().get(entry.item.id)?.maintenance : undefined;
259
- const removal = task === 'uninstall' && entry.item.actions.includes('uninstall')
260
- ? selected().get(entry.item.id)?.removal === 'detach'
261
- ? '仅解除接入'
262
- : '卸载程序'
263
- : '';
40
+ const inspection = await terminal.wait('检查状态', reading => ccw.inspect(reading, action === 'clean' ? 'data' : 'contents'), signal);
41
+ if (!inspection || signal?.aborted)
42
+ continue;
43
+ if (action === 'inspect') {
44
+ await terminal.choose('检查状态\n' + describeInspection(inspection, details), [BACK_TO_HOME]);
45
+ continue;
46
+ }
47
+ const task = action;
48
+ const text = TASK_TEXT[task];
49
+ const items = contentOrder(inspection.items).filter(item => task === 'install'
50
+ ? item.canInstall === true
51
+ : task === 'clean'
52
+ ? item.canClean === true
53
+ : !item.skillSet && item.canUninstall === true);
54
+ const unavailable = {
55
+ items: inspection.items.filter(item => item.problem && !items.includes(item)),
56
+ problems: inspection.problems,
57
+ };
58
+ const inspectionNotice = unavailable.items.length || unavailable.problems.length
59
+ ? '\n以下项目检查未完成或暂不可操作\n' + describeInspection(unavailable, details)
60
+ : '';
61
+ if (!items.length) {
62
+ await terminal.choose(inspectionNotice || text.empty, [BACK_TO_HOME]);
63
+ continue;
64
+ }
65
+ const entries = items.flatMap(item => task === 'install' && item.kind === 'settings'
66
+ ? SETTINGS_EDITORS.map(editor => ({ item, editor, key: item.id + '/' + editor }))
67
+ : [{ item, key: item.id }]);
68
+ const selected = new Map();
69
+ const drafts = new Map();
70
+ const remember = (key, pick) => {
71
+ drafts.set(key, pick);
72
+ selected.set(key, pick);
73
+ };
74
+ let focus = 0;
75
+ let finished = false;
76
+ while (!finished && !signal?.aborted) {
77
+ const page = () => ({
78
+ title: text.title + inspectionNotice,
79
+ submitLabel: '查看变更 · ' + selected.size + ' 项',
80
+ focus,
81
+ rows: entries.map(entry => {
82
+ const draft = drafts.get(entry.key);
83
+ const row = entry.editor ? settingsRow(entry.item, entry.editor, draft?.fields) : contentRow(entry.item);
264
84
  return {
265
- ...labels[index],
266
- label: labels[index]?.label ?? '',
267
- detail: [
268
- problem ? failureLabel(taskAction) : labels[index]?.detail,
269
- ...(maintenance ? [`已选${ACTION_NAMES[maintenance]}`] : []),
270
- removal,
271
- ]
272
- .filter(Boolean)
273
- .join(' · '),
274
- checked: entrySelected(entry, selected()),
275
- enter: problem
276
- ? 'open'
277
- : editable
278
- ? 'edit'
279
- : task === 'install' || availableActions(entry.item, task).length === 1
280
- ? 'toggle'
281
- : 'open',
85
+ ...row,
86
+ checked: selected.has(entry.key),
87
+ editable: entry.editor !== undefined,
282
88
  };
283
- });
284
- if (showData) {
285
- rows.push({
286
- label: `删除 ${knownTitle(CLAUDE_DATA_ID)}(不可恢复)`,
287
- ...(dataProblem ? { detail: failureLabel(taskAction) } : {}),
288
- group: GROUPS.data,
289
- checked: removeClaudeData,
290
- enter: dataProblem ? 'open' : 'toggle',
291
- });
292
- }
293
- const selectedCount = selected().size + Number(showData && removeClaudeData);
294
- const dataDescription = showData
295
- ? '\n删除范围:配置、登录状态、会话、Skills 和目录内工具\n删除位置:.claude / .claude.json(以预览路径为准)'
296
- : '';
297
- return {
298
- title: title + dataDescription,
299
- submitLabel: task === 'install' ? `开始安装(${selectedCount} 项)` : `预览 ${selectedCount} 项变更`,
300
- rows,
301
- };
302
- };
89
+ }),
90
+ });
303
91
  const response = await terminal.select(page(), event => {
304
- changeSelection(() => {
305
- if (event.kind === 'toggle' && event.index === entries.length && dataVisible()) {
306
- removeClaudeData = !removeClaudeData;
307
- return;
308
- }
309
- const targets = event.kind === 'all'
310
- ? entries.filter(entry => entry.editor === undefined &&
311
- !missing.has(entry.item.id) &&
312
- // 更新勾选是显式意图,全选不得静默降级为普通安装
313
- selected().get(entry.item.id)?.maintenance === undefined)
314
- : entries.filter((_entry, index) => index === event.index);
315
- const shouldSelect = event.kind === 'all' && targets.some(entry => !entrySelected(entry, selected()));
316
- for (const entry of targets) {
317
- const prior = selected().get(entry.item.id);
318
- if (event.kind === 'all' ? !shouldSelect : entrySelected(entry, selected())) {
319
- const fields = { ...prior?.fields };
320
- if (entry.editor)
321
- for (const field of SETTINGS_FIELDS[entry.editor])
322
- delete fields[field];
323
- if (entry.editor && Object.keys(fields).length)
324
- selected().set(entry.item.id, { ...prior, id: entry.item.id, fields });
325
- else
326
- selected().delete(entry.item.id);
327
- }
328
- else if (!prior && entry.editor === undefined && !missing.has(entry.item.id)) {
329
- selected().set(entry.item.id, {
330
- id: entry.item.id,
331
- ...(task === 'uninstall' && !entry.item.actions.includes('uninstall') ? DETACH_REMOVAL : {}),
332
- });
333
- }
334
- if (!missing.has(entry.item.id) || !selected().has(entry.item.id))
335
- problems.delete(entry.item.id);
336
- }
337
- });
92
+ const targets = (event.kind === 'all' ? entries : [entries[event.index]]).filter(entry => entry !== undefined);
93
+ const selectAll = event.kind === 'all' && targets.some(entry => !selected.has(entry.key));
94
+ for (const entry of targets) {
95
+ if (event.kind === 'all' ? selectAll : !selected.has(entry.key))
96
+ selected.set(entry.key, drafts.get(entry.key) ?? { id: entry.item.id });
97
+ else
98
+ selected.delete(entry.key);
99
+ }
338
100
  return page();
339
- }, focus[task]);
340
- focus[task] = response.index;
341
- if (response.kind === 'cancel') {
342
- returnToMenu = true;
101
+ });
102
+ if (response === 'cancel')
103
+ break;
104
+ if (typeof response === 'object') {
105
+ focus = response.index;
106
+ const entry = entries[response.index];
107
+ if (entry?.editor) {
108
+ const pick = await configure(entry.item, entry.editor, terminal, drafts.get(entry.key));
109
+ if (pick)
110
+ remember(entry.key, pick);
111
+ }
343
112
  continue;
344
113
  }
345
- if (response.kind === 'refresh') {
346
- view = null;
347
- problems.clear();
114
+ if (!selected.size)
348
115
  continue;
349
- }
350
- if (response.kind === 'open') {
351
- const entry = entries[response.index];
352
- if (entry === undefined) {
353
- const dataProblem = problems.get(CLAUDE_DATA_ID);
354
- if (response.index === entries.length && dataVisible() && dataProblem) {
355
- const choice = await chooseWithDetails(terminal, `${knownTitle(CLAUDE_DATA_ID)}\n${failureLabel(task)}`, ['取消选择', '返回'], `${knownTitle(CLAUDE_DATA_ID)}\n${describeDiagnostic({ code: dataProblem })}`);
356
- if (choice === 0)
357
- changeSelection(() => {
358
- removeClaudeData = false;
359
- problems.delete(CLAUDE_DATA_ID);
360
- });
116
+ if (task === 'install') {
117
+ let cancelled = false;
118
+ for (const entry of entries.filter(entry => selected.has(entry.key))) {
119
+ const { item, key, editor } = entry;
120
+ if (editor && !selected.get(key)?.fields) {
121
+ const pick = savedSelection(item, editor) ?? (await configure(item, editor, terminal, drafts.get(key)));
122
+ if (!pick) {
123
+ cancelled = true;
124
+ break;
125
+ }
126
+ remember(key, pick);
361
127
  }
362
- continue;
363
- }
364
- const item = entry.item;
365
- const problem = problems.get(item.id);
366
- const brief = problem ? `${contentName(item)}\n${failureLabel(task)}` : describeItem(item);
367
- const details = [
368
- describeItem(item, true),
369
- ...(problem && problem !== item.problem ? [describeDiagnostic({ code: problem })] : []),
370
- ...view.problems.map(describeInspectionProblem),
371
- ].join('\n');
372
- if (task === 'install' && problems.get(item.id) === 'local-edits-preserved') {
373
- const choice = await chooseWithDetails(terminal, brief, ['备份并替换', '取消选择', '返回'], details, 2);
374
- const prior = selected().get(item.id);
375
- if (choice === 0 && prior)
376
- select(item.id, { ...prior, fields: { ...prior.fields, replace: REPLACE_CONSENT } });
377
- if (choice === 1)
378
- select(item.id);
379
- continue;
380
128
  }
381
- if (entry.editor !== undefined) {
382
- if (problem) {
383
- const choice = await chooseWithDetails(terminal, brief, ['编辑配置', '取消选择', '返回'], details);
384
- if (choice === 1)
385
- select(item.id);
386
- if (choice !== 0)
387
- continue;
388
- }
389
- const selection = await editSettings(item, entry.editor, terminal, selected().get(item.id));
390
- if (selection) {
391
- select(item.id, selection);
392
- }
129
+ if (cancelled)
393
130
  continue;
394
- }
395
- const actions = task === 'install' ? [] : availableActions(item, task);
396
- const choice = await chooseWithDetails(terminal, brief, [...actions.map(action => ACTION_NAMES[action]), '取消选择', '返回'], details, actions.length + 1);
397
- if (choice === actions.length) {
398
- select(item.id);
399
- }
400
- const action = actions[choice];
401
- if (action !== undefined) {
402
- select(item.id, {
403
- id: item.id,
404
- ...(action === 'detach' ? DETACH_REMOVAL : {}),
405
- });
406
- }
407
- continue;
408
- }
409
- if (!hasSelection())
410
- continue;
411
- if ([...missing].some(id => selected().has(id))) {
412
- focus[task] = Math.max(0, entries.findIndex(entry => missing.has(entry.item.id) && selected().has(entry.item.id)));
413
- continue;
414
131
  }
415
- const picks = [...selected().values()];
416
- // 套件整装保留已有成员、成员更新改写成员:同计划必然与冻结的目录摘要冲突,提交前阻断
417
- const suiteTargets = new Set(picks.filter(pick => kindOf(pick.id) === 'skill-set').map(pick => restOf(pick.id)));
418
- const overlappingUpdate = suiteTargets.size
419
- ? picks.find(pick => {
420
- if (pick.maintenance === undefined)
421
- return false;
422
- const suite = knownItems.get(pick.id)?.skillSet;
423
- return suite !== undefined && suiteTargets.has(suite);
424
- })
425
- : undefined;
426
- if (overlappingUpdate) {
427
- problems.set(overlappingUpdate.id, 'overlapping-selection');
428
- focus[task] = Math.max(0, entries.findIndex(entry => entry.item.id === overlappingUpdate.id));
429
- continue;
430
- }
431
- const saved = pending?.task === task ? pending : undefined;
432
- const request = saved?.remaining
433
- ? { resume: saved.remaining }
434
- : task === 'uninstall'
435
- ? { task, selected: picks, ...(removeClaudeData ? { removeData: true } : {}) }
436
- : { task, selected: picks };
437
- const preparationTask = task;
438
- const preparation = preparationTitle(task);
439
- let preparing;
440
- const plan = saved?.plan ??
441
- (saved?.remaining
442
- ? await ccw.plan(request, signal)
443
- : await terminal.wait(preparation, (reading, update) => {
444
- preparing = ccw.plan(request, reading, event => update?.(describePreparation(event, preparationTask)));
445
- return preparing;
446
- }, signal, preparation));
447
- if (plan === null) {
448
- await preparing?.catch(() => undefined);
449
- pending = undefined;
450
- continue;
451
- }
452
- if (signal?.aborted)
453
- return;
454
- pending = undefined;
455
- problems.clear();
456
- for (const item of plan.items)
457
- if (item.problem !== null)
458
- problems.set(item.id, item.problem);
459
- if (plan.problem === null && problems.size === 0)
460
- pending = { task, plan, ...(task === 'uninstall' && removeClaudeData ? { removeData: true } : {}) };
461
- if (plan.problem !== null) {
462
- await chooseWithDetails(terminal, failureLabel(task), ['返回'], describeDiagnostic({ code: plan.problem }));
463
- continue;
464
- }
465
- if (problems.size) {
466
- const problemIndex = entries.findIndex(entry => problems.has(entry.item.id));
467
- focus[task] = Math.max(0, problemIndex >= 0 ? problemIndex : removeClaudeData && problems.has(CLAUDE_DATA_ID) ? entries.length : 0);
468
- continue;
469
- }
470
- if (task !== 'install') {
471
- const preview = plan.items
472
- .map(item => `${planVerb(item)} ${contentName(item)}\n${item.problem ? ` ${PROBLEM_MARK}${reason(item.problem)}` : item.changes.map(change => ` · ${describeChange(change)}`).join('\n')}`)
473
- .join('\n');
474
- const confirm = await terminal.choose(`变更预览\n${preview}`, [task === 'clean' ? '确认清理' : '确认卸载', '返回修改'], 1);
475
- if (confirm !== 0)
132
+ try {
133
+ const plan = await terminal.wait('准备变更', (reading, update) => ccw.plan({ task, selected: mergeSelections(selected.values()) }, reading, event => update?.(describePreparation(event))), signal);
134
+ if (!plan)
476
135
  continue;
477
- }
478
- const presentation = createRunPresentation(plan, taskAction);
479
- terminal.show(presentation.progress());
480
- const result = await ccw.apply(plan.id, signal, event => {
481
- terminal.show(presentation.progress(event));
482
- });
483
- view = null;
484
- for (const item of result.items) {
485
- if (item.state !== 'done' && item.isPending !== false)
136
+ const blocked = !!plan.problem || plan.items.every(item => item.problem !== null);
137
+ const confirm = await terminal.choose('变更预览\n' + describePlan(plan, details), blocked ? ['返回修改'] : [text.confirm, '返回修改'], blocked ? 0 : 1);
138
+ if (blocked || confirm !== 0)
486
139
  continue;
487
- if (item.id === CLAUDE_DATA_ID)
488
- removeClaudeData = false;
489
- else
490
- selected().delete(item.id);
140
+ const presentation = createRunPresentation(plan, task, details);
141
+ terminal.show(presentation.progress());
142
+ const result = await ccw.apply(plan.id, signal, event => terminal.show(presentation.progress(event)));
143
+ await terminal.choose(describeRun(presentation.result(result)), [BACK_TO_HOME]);
144
+ finished = true;
491
145
  }
492
- const dataRemaining = removeClaudeData && result.items.some(item => item.id === CLAUDE_DATA_ID && item.isPending === true);
493
- pending = result.remaining
494
- ? { task, remaining: result.remaining, ...(dataRemaining ? { removeData: true } : {}) }
495
- : undefined;
496
- reconcile();
497
- const resultView = presentation.result(result);
498
- let resultFocus = 1;
499
- let detailFocus = 0;
500
- while (!signal?.aborted) {
501
- const next = await terminal.choose(resultView, [hasSelection() && result.remaining ? '重试未完成项' : '返回列表', BACK_TO_HOME, '查看详情'], resultFocus, 1);
502
- if (next !== 2) {
503
- if (next === 1)
504
- returnToMenu = true;
505
- break;
506
- }
507
- resultFocus = next;
508
- let item = result.items[0];
509
- if (result.items.length > 1) {
510
- detailFocus = await terminal.choose('选择结果', [
511
- ...result.items.map(item => {
512
- const row = resultView.rows.find(candidate => candidate.id === item.id);
513
- return {
514
- label: row?.title ?? contentName(item),
515
- detail: row?.status ?? '',
516
- };
517
- }),
518
- '返回',
519
- ], Math.min(detailFocus, result.items.length - 1));
520
- item = result.items[detailFocus];
521
- }
522
- if (item)
523
- await terminal.choose(presentation.details(result, item.id), ['返回']);
524
- else if (!result.items.length)
525
- await terminal.choose('结果详情\n本次没有条目记录', ['返回']);
146
+ catch (error) {
147
+ if (signal?.aborted)
148
+ return;
149
+ await terminal.choose('操作失败:' + describeChange({ code: errorCode(error) }, details), ['返回修改']);
526
150
  }
527
151
  }
528
152
  }
529
153
  }
154
+ function savedSelection(item, editor) {
155
+ const values = item.values ?? {};
156
+ if (item.problem)
157
+ return;
158
+ if (editor !== 'connection')
159
+ return { id: item.id, fields: { [editor]: values[editor] ?? DEFAULT_PREFERENCES[editor] } };
160
+ if (values.mode === 'official' ||
161
+ (effectiveConnection(values, item.facts) === 'api' &&
162
+ apiConfigurationProblem(values.baseUrl, item.hasCredential === true) === null))
163
+ return { id: item.id, fields: {} };
164
+ }
165
+ async function configure(item, editor, terminal, prior) {
166
+ const values = { ...item.values, ...prior?.fields };
167
+ if (editor !== 'connection') {
168
+ const choices = editor === 'language' ? SETTINGS_LANGUAGES : SETTINGS_STYLES;
169
+ const current = values[editor] ?? DEFAULT_PREFERENCES[editor];
170
+ const index = await terminal.choose(editor === 'language' ? '默认语言' : '输出风格', [...choices.map(choice => choice.label), '返回'], Math.max(0, choices.findIndex(choice => choice.value === current)));
171
+ const choice = choices[index];
172
+ return choice ? { id: item.id, fields: { [editor]: choice.value } } : null;
173
+ }
174
+ const mode = await terminal.choose('模型配置', ['官方登录', '第三方 API', '返回'], effectiveConnection(values, item.facts) === 'api' ? 1 : 0);
175
+ if (mode === 2)
176
+ return null;
177
+ if (mode === 0)
178
+ return {
179
+ id: item.id,
180
+ fields: {
181
+ mode: 'official',
182
+ login: 'yes',
183
+ },
184
+ };
185
+ const kept = item.hasCredential === true;
186
+ const fields = await terminal.form('第三方 API', [
187
+ { key: 'baseUrl', label: 'Base URL', value: values.baseUrl ?? '' },
188
+ {
189
+ key: 'secret',
190
+ label: 'API Key',
191
+ value: prior?.fields?.secret ?? '',
192
+ secret: true,
193
+ placeholder: kept ? '留空保留现有凭据' : '必填',
194
+ },
195
+ ...MODEL_FIELDS.map(field => ({
196
+ key: field.key,
197
+ label: field.label,
198
+ value: values[field.key] ?? '',
199
+ placeholder: '选填',
200
+ })),
201
+ ], value => {
202
+ const problem = apiConfigurationProblem(value.baseUrl, !!value.secret?.trim() || kept);
203
+ return problem
204
+ ? { message: reason(problem), field: problem === 'credential-required' ? 'secret' : 'baseUrl' }
205
+ : null;
206
+ });
207
+ return fields
208
+ ? {
209
+ id: item.id,
210
+ fields: {
211
+ ...fields,
212
+ mode: 'api',
213
+ auth: fields.secret?.trim() ? 'key' : (values.auth ?? 'key'),
214
+ },
215
+ }
216
+ : null;
217
+ }
218
+ function mergeSelections(selections) {
219
+ const merged = new Map();
220
+ for (const selection of selections) {
221
+ const prior = merged.get(selection.id);
222
+ merged.set(selection.id, {
223
+ id: selection.id,
224
+ ...(prior?.fields || selection.fields ? { fields: { ...prior?.fields, ...selection.fields } } : {}),
225
+ });
226
+ }
227
+ return [...merged.values()];
228
+ }