@hit-sudomaker/ccw 0.5.0 → 0.5.2

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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # CCW 0.5.0
1
+ # CCW 0.5.2
2
2
 
3
3
  CCW 是一个管理 Claude Code 及其常用扩展的终端工具。安装、更新和移除前,CCW 会先展示变更预览,确认后再执行。
4
4
 
@@ -18,12 +18,12 @@ ccw
18
18
  | 菜单 | 用途 |
19
19
  | -------- | -------------------------------------- |
20
20
  | 安装配置 | 安装或更新所选项目,编辑模型和偏好设置 |
21
- | 检查状态 | 查看安装状态和配置路径 |
21
+ | 检查状态 | 查看安装状态、模型字段和配置路径 |
22
22
  | 移除程序 | 移除受管程序或解除所选接入 |
23
23
  | 清理数据 | 按类别清理 Claude 数据 |
24
24
  | 退出程序 | 关闭 CCW |
25
25
 
26
- 在“安装配置”中勾选已安装的项目,即可更新。已有的有效模型连接、语言和输出风格会直接复用;需要修改时,可以在列表中进入对应的设置项。检查状态是只读操作。
26
+ 在“安装配置”中勾选已安装的项目,即可更新。已有的有效模型连接、语言和输出风格会直接复用;需要修改时,可以在列表中进入对应的设置项。检查状态是只读操作,会显示默认模型、Fable、Opus、Sonnet 和 Haiku,未设置的字段标为“未配置”。
27
27
 
28
28
  方向键移动,空格勾选,`A` 全选或取消全选,`Enter` 确认,`Esc` 返回。长页面可用 `PgUp` 和 `PgDn` 翻页。执行过程中按 `Ctrl+C` 会停止后续操作,已经发生的变更不会回滚。
29
29
 
@@ -72,15 +72,15 @@ npm start
72
72
  ```powershell
73
73
  New-Item -ItemType Directory -Force .scratch | Out-Null
74
74
  npm pack ./packages/ccw --pack-destination .scratch
75
- pnpm add --global --force ./.scratch/hit-sudomaker-ccw-0.5.0.tgz
75
+ pnpm add --global --force ./.scratch/hit-sudomaker-ccw-0.5.2.tgz
76
76
  ```
77
77
 
78
78
  重新打包后再安装,关闭旧的 CCW 窗口并运行 `ccw`,即可使用新版本。如果原来使用 npm 全局安装,可将最后一行换成 `npm install -g`,并指定同一个安装包。打包和本地安装不会发布版本。
79
79
 
80
80
  开发检查使用 `npm run check`;独立运行包可用 `npm run package:runtime` 构建,并用 `npm run test:runtime` 验证。Windows 终端交互使用 ConPTY 测试;macOS 和 Linux 目前主要通过平台模拟覆盖。
81
81
 
82
- 开发资料:[接入说明](https://github.com/HIT-SudoMaker/claude-code-workpack/blob/main/docs/integrations.md) · [产品与执行合同](https://github.com/HIT-SudoMaker/claude-code-workpack/blob/main/docs/specs/operation-state-machine.md) · [CSU 编码规范](https://github.com/HIT-SudoMaker/claude-code-workpack/blob/main/docs/standards/typescript-csu.md)
82
+ 开发资料:[接入说明](https://github.com/HIT-SudoMaker/ccw/blob/main/docs/integrations.md) · [产品与执行合同](https://github.com/HIT-SudoMaker/ccw/blob/main/docs/specs/operation-state-machine.md) · [CSU 编码规范](https://github.com/HIT-SudoMaker/ccw/blob/main/docs/standards/typescript-csu.md)
83
83
 
84
84
  交互设计参考了 [ZCF](https://github.com/UfoMiao/zcf)。本项目集成的工具与扩展归各自作者所有。
85
85
 
86
- [MIT](https://github.com/HIT-SudoMaker/claude-code-workpack/blob/main/LICENSE) © HIT-SudoMaker
86
+ [MIT](https://github.com/HIT-SudoMaker/ccw/blob/main/LICENSE) © HIT-SudoMaker
package/dist/claude.js CHANGED
@@ -1,46 +1,26 @@
1
- import { inspectSettings, prepareSettings } from './settings.js';
1
+ import { prepareDefaultSettings } from './settings.js';
2
2
  import { knownTitle } from './management-catalog.js';
3
3
  import path from 'node:path';
4
- import { errorCode, isObject } from './machine.js';
4
+ import { isObject } from './machine.js';
5
5
  import { claudeRunning } from './claude-program.js';
6
6
  import { isExactVersion, NPM_OFFICIAL, resolveNpmView } from './npm-registry.js';
7
7
  import { CLAUDE_PACKAGE, CLAUDE_NPM_ARGS, claudeNpmBinary, bindClaudeCommand, claudePrograms, } from './claude-program.js';
8
8
  import { freezeNpmScope } from './program-channels.js';
9
9
  import { npmProgram } from './program-operations.js';
10
10
  import { step, sequence } from './work.js';
11
- import { prepareDataCleanup } from './cleanup.js';
11
+ import { kindOf } from './model.js';
12
12
  const STABLE_METADATA_TIMEOUT_MS = 5_000;
13
13
  /**
14
- * 管理 Claude 程序、默认设置、模型配置和官方登录
14
+ * 管理 Claude Code 程序
15
15
  *
16
- * @remarks 仅管理 npm 渠道,安装与更新使用当次 stable 并补齐默认设置
17
- * 卸载要求 Claude 已停止;外部安装只展示
16
+ * @remarks 通过 npm 安装或更新当次 stable 版本,并补齐默认设置
17
+ * 显示外部安装状态,卸载受管程序前须确认 Claude 已停止
18
18
  */
19
19
  export function createClaudeDomain(ctx) {
20
20
  return {
21
- async inspect() {
22
- const checks = [
23
- ['claude', () => inspectClaudePrograms(ctx)],
24
- ['settings', async () => ({ items: [await inspectSettings(ctx)], problems: [] })],
25
- ];
26
- const results = await Promise.all(checks.map(async ([name, read]) => {
27
- try {
28
- return await read();
29
- }
30
- catch (error) {
31
- return { items: [], problems: [{ code: errorCode(error), detail: name }] };
32
- }
33
- }));
34
- return { items: results.flatMap(result => result.items), problems: results.flatMap(result => result.problems) };
35
- },
36
- async prepare(selection, claude) {
37
- if (selection.id.startsWith('data:'))
38
- return prepareDataCleanup(ctx, selection);
39
- if (selection.id === 'settings') {
40
- const login = selection.action === 'configure' && selection.fields?.mode === 'official' && selection.fields.login === 'yes';
41
- return prepareSettings(ctx, selection, login ? await claude?.() : undefined);
42
- }
43
- if (selection.id.split(':')[0] !== 'claude')
21
+ inspect: () => inspectClaudePrograms(ctx),
22
+ async prepare(selection) {
23
+ if (kindOf(selection.id) !== 'claude')
44
24
  throw new Error('unknown-selection');
45
25
  return prepareClaudeProgram(ctx, selection);
46
26
  },
@@ -83,9 +63,9 @@ async function prepareClaudeProgram(ctx, selection) {
83
63
  const operation = await prepareClaudeInstallation(ctx, action, program);
84
64
  if (action !== 'install')
85
65
  return operation;
86
- const defaults = await prepareSettings(ctx, { id: 'settings', action: 'configure' });
66
+ const defaultSettings = await prepareDefaultSettings(ctx);
87
67
  return {
88
- ...sequence([operation, defaults]),
68
+ ...sequence([operation, defaultSettings]),
89
69
  action: operation.action ?? 'install',
90
70
  ...(operation.claude ? { claude: operation.claude } : {}),
91
71
  };
@@ -150,7 +130,7 @@ async function stableClaudeVersion(ctx) {
150
130
  const release = await resolveNpmView(ctx.machine, `${CLAUDE_PACKAGE}@stable`, 'version', exactVersion);
151
131
  if (release !== null)
152
132
  return release;
153
- // npm 查询未得到有效版本时才读取官方稳定版元数据,返回值仍绑定官方来源
133
+ // 改查官方 stable 元数据时,将安装来源也固定为官方 registry
154
134
  try {
155
135
  const metadata = JSON.parse(await ctx.machine.fetchText(`${NPM_OFFICIAL}/@anthropic-ai%2Fclaude-code/stable`, {
156
136
  timeoutMs: STABLE_METADATA_TIMEOUT_MS,
@@ -169,7 +149,7 @@ async function stableClaudeVersion(ctx) {
169
149
  function exactVersion(value) {
170
150
  return isExactVersion(value) ? value : null;
171
151
  }
172
- /** 卸载前后核对 Claude 进程,通用 npm 执行器不识别具体包名 */
152
+ /** 确认 Claude 进程已停止,供卸载前后核验 */
173
153
  async function assertClaudeStopped(ctx) {
174
154
  const running = await claudeRunning(ctx.machine);
175
155
  if (running !== false)
package/dist/cleanup.js CHANGED
@@ -2,11 +2,11 @@ import path from 'node:path';
2
2
  import { knownTitle } from './management-catalog.js';
3
3
  import { claudeRunning } from './claude-program.js';
4
4
  import { errorCode } from './machine.js';
5
- import { normalizePath, restOf, unchanged } from './model.js';
5
+ import { normalizePath, unchanged } from './model.js';
6
6
  import { step } from './work.js';
7
7
  const CATEGORIES = ['cache', 'history', 'memory', 'backups', 'runtime'];
8
- const SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
9
- const BINARY_UNIT_BASE = 1024;
8
+ const SIZE_UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
9
+ const BINARY_UNIT_BASE = 1024n;
10
10
  const DIRECTORIES = {
11
11
  cache: ['cache', 'debug', 'image-cache', 'logs', 'paste-cache', 'statsig', 'usage-data'],
12
12
  history: ['file-history', 'shell-snapshots', 'sessions', 'projects'],
@@ -21,43 +21,54 @@ const FILES = {
21
21
  backups: [],
22
22
  runtime: ['daemon.lock', 'daemon.status.json'],
23
23
  };
24
- function size(bytes) {
25
- let value = Number(bytes), unit = 0;
26
- while (value >= BINARY_UNIT_BASE && unit < SIZE_UNITS.length - 1) {
27
- value /= BINARY_UNIT_BASE;
28
- unit++;
24
+ /** 格式化字节数,使用整数运算将二进制单位舍入到一位小数 */
25
+ function formatSizeBytes(sizeBytes) {
26
+ let unitIndex = 0;
27
+ let bytesPerUnit = 1n;
28
+ while (sizeBytes >= bytesPerUnit * BINARY_UNIT_BASE && unitIndex < SIZE_UNITS.length - 1) {
29
+ bytesPerUnit *= BINARY_UNIT_BASE;
30
+ unitIndex++;
29
31
  }
30
- return `${unit ? value.toFixed(1) : value} ${SIZE_UNITS[unit]}`;
32
+ if (unitIndex === 0)
33
+ return `${sizeBytes} B`;
34
+ const sizeTenths = (sizeBytes * 10n + bytesPerUnit / 2n) / bytesPerUnit;
35
+ return `${sizeTenths / 10n}.${sizeTenths % 10n} ${SIZE_UNITS[unitIndex]}`;
31
36
  }
32
- async function inventory(ctx, category) {
37
+ /** 清点所选类别,按子目录优先的顺序记录可移除目录 */
38
+ async function collectCleanupInventory(ctx, category) {
33
39
  const files = [];
34
40
  const directories = [];
35
41
  const links = [];
36
- const real = await ctx.machine.realpath(ctx.claudeRoot);
37
- if (real !== null && normalizePath(ctx.platform, real) !== normalizePath(ctx.platform, ctx.claudeRoot))
42
+ let totalSizeBytes = 0n;
43
+ const canonicalRoot = await ctx.machine.realpath(ctx.claudeRoot);
44
+ if (canonicalRoot !== null &&
45
+ normalizePath(ctx.platform, canonicalRoot) !== normalizePath(ctx.platform, ctx.claudeRoot))
38
46
  throw new Error('linked-parent');
39
- const belongs = (file) => {
47
+ const belongsToCategory = (file) => {
40
48
  const parts = path.relative(ctx.claudeRoot, file).split(path.sep);
41
49
  return parts[0] !== 'projects' || (parts[2] === 'memory') === (category === 'memory');
42
50
  };
43
- const visit = async (file, kind, bytes) => {
51
+ const visitEntry = async (file, kind, sizeBytes) => {
52
+ const isInCategory = belongsToCategory(file);
44
53
  if (kind === 'link') {
45
- if (belongs(file))
54
+ if (isInCategory)
46
55
  links.push(file);
47
56
  return false;
48
57
  }
49
58
  if (kind === 'file') {
50
- if (belongs(file))
51
- files.push({ file, size: bytes });
52
- return belongs(file);
59
+ if (isInCategory) {
60
+ files.push(file);
61
+ totalSizeBytes += sizeBytes;
62
+ }
63
+ return isInCategory;
53
64
  }
54
- let removable = belongs(file);
65
+ let canRemoveDirectory = isInCategory;
55
66
  for (const entry of await ctx.machine.entries(file))
56
- if (!(await visit(path.join(file, entry.name), entry.kind, entry.sizeBytes)))
57
- removable = false;
58
- if (removable)
67
+ if (!(await visitEntry(path.join(file, entry.name), entry.kind, entry.sizeBytes)))
68
+ canRemoveDirectory = false;
69
+ if (canRemoveDirectory)
59
70
  directories.push(file);
60
- return removable;
71
+ return canRemoveDirectory;
61
72
  };
62
73
  for (const [kind, names] of [
63
74
  ['directory', DIRECTORIES[category]],
@@ -65,8 +76,8 @@ async function inventory(ctx, category) {
65
76
  ])
66
77
  for (const name of names) {
67
78
  const file = path.join(ctx.claudeRoot, name);
68
- const canonical = await ctx.machine.realpath(file);
69
- if (canonical !== null && normalizePath(ctx.platform, canonical) !== normalizePath(ctx.platform, file)) {
79
+ const canonicalPath = await ctx.machine.realpath(file);
80
+ if (canonicalPath !== null && normalizePath(ctx.platform, canonicalPath) !== normalizePath(ctx.platform, file)) {
70
81
  links.push(file);
71
82
  continue;
72
83
  }
@@ -75,16 +86,19 @@ async function inventory(ctx, category) {
75
86
  continue;
76
87
  if (entry.kind !== 'link' && entry.kind !== kind)
77
88
  throw new Error('cleanup-type-changed');
78
- await visit(file, entry.kind, entry.sizeBytes);
89
+ await visitEntry(file, entry.kind, entry.sizeBytes);
79
90
  }
80
- return {
81
- files,
82
- directories,
83
- links,
84
- detail: `${files.length} 个文件 · ${directories.length} 个目录 · ${size(files.reduce((sum, file) => sum + file.size, 0n))}`,
85
- };
91
+ return { files, directories, links, totalSizeBytes };
86
92
  }
87
- /** 清点白名单数据,保留配置、凭据、插件和 Skills */
93
+ /** 格式化检查与预览共用的清理明细 */
94
+ function formatCleanupSummary({ files, directories, totalSizeBytes }) {
95
+ return `${files.length} 个文件 · ${directories.length} 个目录 · ${formatSizeBytes(totalSizeBytes)}`;
96
+ }
97
+ /**
98
+ * 检查 Claude 可清理数据
99
+ *
100
+ * @returns 各类别的清理资格与清点明细,读取失败记在相应类别
101
+ */
88
102
  export async function inspectClaudeData(ctx) {
89
103
  const items = await Promise.all(CATEGORIES.map(async (category) => {
90
104
  const item = {
@@ -94,13 +108,13 @@ export async function inspectClaudeData(ctx) {
94
108
  location: ctx.claudeRoot,
95
109
  };
96
110
  try {
97
- const found = await inventory(ctx, category);
111
+ const inventory = await collectCleanupInventory(ctx, category);
98
112
  return {
99
113
  ...item,
100
- canClean: found.files.length > 0 || found.directories.length > 0,
114
+ canClean: inventory.files.length > 0 || inventory.directories.length > 0,
101
115
  facts: [
102
- { code: 'data-size', detail: found.detail },
103
- ...(found.links.length ? [{ code: 'data-links-kept', detail: String(found.links.length) }] : []),
116
+ { code: 'data-size', detail: formatCleanupSummary(inventory) },
117
+ ...(inventory.links.length ? [{ code: 'data-links-kept', detail: String(inventory.links.length) }] : []),
104
118
  ],
105
119
  };
106
120
  }
@@ -110,64 +124,71 @@ export async function inspectClaudeData(ctx) {
110
124
  }));
111
125
  return { items, problems: [] };
112
126
  }
113
- async function requireStopped(ctx) {
114
- const running = await claudeRunning(ctx.machine);
115
- if (running !== false)
116
- throw new Error(running ? 'claude-running' : 'process-state-unconfirmed');
127
+ /** 确认 Claude 已停止,进程状态不明时也阻止清理 */
128
+ async function requireClaudeStopped(ctx) {
129
+ const isRunning = await claudeRunning(ctx.machine);
130
+ if (isRunning !== false)
131
+ throw new Error(isRunning ? 'claude-running' : 'process-state-unconfirmed');
117
132
  }
118
- /** 删除已确认的类别快照,保留 Claude 配置根目录 */
133
+ /**
134
+ * 准备类别清理计划
135
+ *
136
+ * @returns 待确认的工作项,内部保留文件摘要
137
+ * @throws Error - 类别无效、目标已变化、读取失败或无法确认 Claude 已停止时 Promise 拒绝
138
+ * @remarks 准备时只读取目标,执行时仅移除清单内文件和空目录
139
+ * 取消后由执行核心复核已发生的效果
140
+ */
119
141
  export async function prepareDataCleanup(ctx, selection) {
120
- const category = CATEGORIES.find(value => value === restOf(selection.id));
142
+ const category = CATEGORIES.find(value => selection.id === `data:${value}`);
121
143
  if (!category || selection.action !== 'clean')
122
144
  throw new Error('unknown-selection');
123
- const found = await inventory(ctx, category);
124
- await requireStopped(ctx);
125
- const files = await Promise.all(found.files.map(async (file) => ({ ...file, stamp: await ctx.machine.fingerprint(file.file) })));
126
- const before = async () => {
127
- await requireStopped(ctx);
128
- await inventory(ctx, category);
129
- for (const file of files)
130
- unchanged(await ctx.machine.fingerprint(file.file), file.stamp);
145
+ const inventory = await collectCleanupInventory(ctx, category);
146
+ await requireClaudeStopped(ctx);
147
+ const fileSnapshots = await Promise.all(inventory.files.map(async (file) => {
148
+ const fingerprint = await ctx.machine.fingerprint(file);
149
+ if (fingerprint === null)
150
+ throw new Error('target-changed');
151
+ return { file, fingerprint };
152
+ }));
153
+ const checkCleanupTargets = async () => {
154
+ await requireClaudeStopped(ctx);
155
+ await collectCleanupInventory(ctx, category);
156
+ for (const { file, fingerprint } of fileSnapshots)
157
+ unchanged(await ctx.machine.fingerprint(file), fingerprint);
131
158
  };
132
159
  return {
133
160
  ...step([
134
- { code: 'data-delete', detail: found.detail },
161
+ { code: 'data-delete', detail: formatCleanupSummary(inventory) },
135
162
  { code: 'data-root', detail: ctx.claudeRoot },
136
163
  { code: 'data-permanent' },
137
164
  { code: 'data-keep-configuration' },
138
- ...(found.links.length ? [{ code: 'data-links-kept', detail: String(found.links.length) }] : []),
139
- ], async (fact) => {
140
- if (!fact.dispatched) {
141
- await before();
165
+ ...(inventory.links.length ? [{ code: 'data-links-kept', detail: String(inventory.links.length) }] : []),
166
+ ], async (attempt) => {
167
+ if (!attempt.dispatched) {
168
+ await checkCleanupTargets();
142
169
  return { state: 'ready' };
143
170
  }
144
- const current = await inventory(ctx, category);
145
- if (current.files.length || current.directories.length)
146
- return { state: 'blocked', problem: fact.receipt?.failure ?? 'cleanup-incomplete' };
171
+ const remainingInventory = await collectCleanupInventory(ctx, category);
172
+ if (remainingInventory.files.length || remainingInventory.directories.length)
173
+ return { state: 'blocked', problem: attempt.receipt?.failure ?? 'cleanup-incomplete' };
147
174
  return { state: 'complete' };
148
175
  }, async () => {
149
176
  const effects = [];
150
177
  try {
151
- await before();
152
- for (const file of files) {
153
- await requireStopped(ctx);
154
- if (file.stamp !== null)
155
- await ctx.effects.removeTree(file.file, file.stamp);
156
- effects.push({ state: 'done', code: 'data-file-removed', detail: file.file });
178
+ await checkCleanupTargets();
179
+ for (const { file, fingerprint } of fileSnapshots) {
180
+ await requireClaudeStopped(ctx);
181
+ await ctx.effects.removeFile(file, fingerprint);
182
+ effects.push({ state: 'done', code: 'data-file-removed', detail: file });
157
183
  }
158
- for (const directory of found.directories) {
159
- if ((await ctx.machine.entries(directory)).length)
160
- continue;
161
- const stamp = await ctx.machine.treeStamp(directory);
162
- if (stamp !== null) {
163
- await requireStopped(ctx);
164
- await ctx.effects.removeTree(directory, stamp);
165
- }
184
+ for (const directory of inventory.directories) {
185
+ await requireClaudeStopped(ctx);
186
+ await ctx.effects.removeEmptyDirectory(directory);
166
187
  }
167
188
  if (!effects.length)
168
189
  effects.push({ state: 'done', code: 'data-cleared' });
169
- if (found.links.length)
170
- effects.push({ state: 'kept', code: 'data-links-kept', detail: String(found.links.length) });
190
+ if (inventory.links.length)
191
+ effects.push({ state: 'kept', code: 'data-links-kept', detail: String(inventory.links.length) });
171
192
  return { receipt: { kind: 'returned', failure: null }, effects };
172
193
  }
173
194
  catch (error) {
@@ -1,9 +1,8 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  /**
3
- * 隔离异步调用链的写入资格
3
+ * 创建写入作用域
4
4
  *
5
- * @returns 受保护的写入能力,以及授予当前调用链资格的 run 方法
6
- * @remarks 每次派发检查资格和取消,不中断或撤销已派发操作
5
+ * @returns 受保护的写入能力和授予当前异步调用链资格的 run 方法
7
6
  */
8
7
  export function createEffectScope(machine) {
9
8
  const execution = new AsyncLocalStorage();
@@ -17,12 +16,12 @@ export function createEffectScope(machine) {
17
16
  return true;
18
17
  }),
19
18
  /**
20
- * 授予 work 调用链写入资格,结束后撤销
19
+ * 授予当前调用链写入资格
21
20
  *
22
- * @param work - Promise 须覆盖全部写入
23
- * @param cancellation - 已取消时,后续能力派发同步抛出 cancelled
24
- * @throws 已有调用运行时拒绝为 operation-in-progress;work 异常原样传播
25
- * @remarks 取消只阻止后续派发,不跳过 work 或强制其失败
21
+ * @param work - 返回的 Promise 须覆盖全部写入,结算时撤销资格
22
+ * @param cancellation - 取消后调用写入能力时同步抛出 cancelled
23
+ * @throws 已有作用域运行时以 operation-in-progress 拒绝 Promise,work 异常原样传播
24
+ * @remarks 取消阻止后续派发,已派发的操作和 work 自身继续结算
26
25
  */
27
26
  run(work, cancellation) {
28
27
  if (active !== undefined)
@@ -40,11 +39,11 @@ export function createEffectScope(machine) {
40
39
  };
41
40
  }
42
41
  /**
43
- * 每次调用写入能力前检查资格
42
+ * 包装受资格检查的写入能力
44
43
  *
45
- * @param allowed - 同步资格检查,可抛出取消等错误,结果不缓存
46
- * @throws 无资格时同步抛出 effect-not-authorized;检查异常原样传播
47
- * @remarks 不复核完成时的资格,也不中断已派发操作
44
+ * @param allowed - 每次派发前执行的同步资格检查
45
+ * @returns 写入方法在无资格时同步抛出 effect-not-authorized,检查异常原样传播
46
+ * @remarks 已派发的操作继续执行,完成时不重新检查资格
48
47
  */
49
48
  export function createEffectMachine(machine, allowed) {
50
49
  const guarded = (work) => (...args) => {
@@ -56,6 +55,8 @@ export function createEffectMachine(machine, allowed) {
56
55
  initialize: guarded((file, text) => machine.initialize(file, text)),
57
56
  editJson: guarded((file, edit) => machine.editJson(file, edit)),
58
57
  npm: guarded((args, options) => machine.npm(args, options)),
58
+ removeFile: guarded((file, expectedFingerprint) => machine.removeFile(file, expectedFingerprint)),
59
+ removeEmptyDirectory: guarded(directory => machine.removeEmptyDirectory(directory)),
59
60
  removeTree: guarded((file, expected, preserveAt) => machine.removeTree(file, expected, preserveAt)),
60
61
  replaceTree: guarded((directory, files, expected, preserveAt) => machine.replaceTree(directory, files, expected, preserveAt)),
61
62
  execute: guarded((file, args, options) => machine.execute(file, args, options)),
package/dist/machine.js CHANGED
@@ -62,6 +62,8 @@ export function createMachine(environment = process.env, cwd = process.cwd(), ha
62
62
  editJson,
63
63
  entries,
64
64
  treeStamp,
65
+ removeFile,
66
+ removeEmptyDirectory,
65
67
  removeTree,
66
68
  replaceFile,
67
69
  async realpath(file) {
@@ -437,6 +439,30 @@ async function treeStamp(file, signal) {
437
439
  throw error;
438
440
  }
439
441
  }
442
+ async function removeFile(file, expectedFingerprint) {
443
+ await checkParentLinks(file);
444
+ if ((await fingerprint(file)) !== expectedFingerprint)
445
+ throw new Error('target-changed');
446
+ await fs.unlink(file);
447
+ }
448
+ async function removeEmptyDirectory(directory) {
449
+ if (path.resolve(directory) === path.parse(path.resolve(directory)).root)
450
+ throw new Error('invalid-target');
451
+ await checkParentLinks(directory);
452
+ try {
453
+ if (!(await fs.lstat(directory)).isDirectory())
454
+ throw new Error('target-changed');
455
+ await fs.rmdir(directory);
456
+ }
457
+ catch (error) {
458
+ const code = errorCode(error);
459
+ if (code === 'ENOENT')
460
+ return;
461
+ if (code === 'ENOTEMPTY' || code === 'EEXIST' || code === 'ENOTDIR')
462
+ throw new Error('target-changed', { cause: error });
463
+ throw error;
464
+ }
465
+ }
440
466
  async function removeTree(file, expected, preserveAt) {
441
467
  if (path.resolve(file) === path.parse(path.resolve(file)).root)
442
468
  throw new Error('invalid-target');
@@ -716,7 +742,11 @@ function relativeFile(root, relative) {
716
742
  return result;
717
743
  }
718
744
  async function prepareParent(file) {
719
- // 拒绝通过已有链接目录写到其他根;不追随链接部署或删除资产
745
+ await checkParentLinks(file);
746
+ await fs.mkdir(path.dirname(file), { recursive: true });
747
+ }
748
+ /** 检查父路径,阻止通过符号链接修改目标 */
749
+ async function checkParentLinks(file) {
720
750
  let directory = path.dirname(file);
721
751
  while (directory !== path.dirname(directory)) {
722
752
  try {
@@ -729,7 +759,6 @@ async function prepareParent(file) {
729
759
  }
730
760
  directory = path.dirname(directory);
731
761
  }
732
- await fs.mkdir(path.dirname(file), { recursive: true });
733
762
  }
734
763
  async function fileStat(file) {
735
764
  try {
package/dist/planning.js CHANGED
@@ -3,29 +3,33 @@ import { freezeClaudeCommand } from './claude-program.js';
3
3
  import { knownTitle } from './management-catalog.js';
4
4
  import { createCcline } from './ccline.js';
5
5
  import { createClaudeDomain } from './claude.js';
6
+ import { prepareDataCleanup } from './cleanup.js';
6
7
  import { createPluginsDomain } from './plugins.js';
8
+ import { createSettingsDomain } from './settings.js';
7
9
  import { createSkillsDomain, overlappingSkillSelections } from './skills.js';
8
10
  import { createOfficecli } from './officecli.js';
9
11
  import { errorCode } from './machine.js';
10
12
  import { cancelled, kindOf, restOf } from './model.js';
11
13
  const PREPARATION_CONCURRENCY = 2;
12
- /** 业务入口:Claude、Plugins、Skills,以及各自负责的额外工具 */
14
+ /** 程序和接入的域注册表,顺序与检查结果一致 */
13
15
  export const CONTENT_DOMAINS = [
14
- [['claude', 'settings', 'data'], 'claude', createClaudeDomain],
16
+ [['claude'], 'claude', createClaudeDomain],
17
+ [['settings'], 'settings', createSettingsDomain],
15
18
  [['plugin'], 'plugins', createPluginsDomain],
16
19
  [['skill', 'skill-set'], 'skills', createSkillsDomain],
17
20
  [['officecli'], 'officecli', createOfficecli],
18
21
  [['ccline'], 'ccline', createCcline],
19
22
  ];
20
23
  /**
21
- * 生成资源已准备、尚未执行的计划
24
+ * 创建计划准备器
22
25
  *
23
26
  * @param readScope - 为并行准备隔离取消和进度归属的读取作用域
24
- * @returns 接收请求、取消信号和进度回调的准备函数
25
- * @remarks 单项问题进入预览,无效请求和取消使准备拒绝;调用方隔离回调异常并消费计划
27
+ * @returns 准备资源并返回待确认计划的函数
28
+ * @remarks 准备函数将单项问题写入预览,无效请求或取消时拒绝 Promise
29
+ * 调用方负责隔离进度回调异常和消费计划
26
30
  */
27
31
  export function createPlanner(ctx, readScope) {
28
- // 准备域复用同一上下文;检查域另行装配以使用当次读取预算
32
+ // 复用准备域,检查时另行装配以使用当次读取预算
29
33
  const prepareDomains = new Map();
30
34
  for (const [keys, , factory] of CONTENT_DOMAINS) {
31
35
  const domain = factory(ctx);
@@ -82,10 +86,14 @@ export function createPlanner(ctx, readScope) {
82
86
  let operation;
83
87
  let problem = null;
84
88
  try {
85
- const domain = prepareDomains.get(kindOf(selection.id));
86
- if (!domain)
87
- throw new Error('unknown-selection');
88
- operation = await domain.prepare(selection, commandFor);
89
+ if (snapshot.task === 'clean')
90
+ operation = await prepareDataCleanup(ctx, selection);
91
+ else {
92
+ const domain = prepareDomains.get(kindOf(selection.id));
93
+ if (!domain)
94
+ throw new Error('unknown-selection');
95
+ operation = await domain.prepare(selection, commandFor);
96
+ }
89
97
  work.set(selection.id, operation);
90
98
  }
91
99
  catch (error) {
@@ -129,7 +137,7 @@ export function createPlanner(ctx, readScope) {
129
137
  return { plan, work };
130
138
  };
131
139
  }
132
- /** 根据对象标识生成计划标题,不以显示名称代替身份验证 */
140
+ /** 根据对象标识生成计划标题 */
133
141
  function planDisplayTitle(id) {
134
142
  const kind = kindOf(id);
135
143
  const key = restOf(id) ?? '';
package/dist/render.js CHANGED
@@ -2,6 +2,7 @@ import { createRequire } from 'node:module';
2
2
  import stringWidth from 'string-width';
3
3
  import { MESSAGES } from './messages.js';
4
4
  import { isObject } from './machine.js';
5
+ import { MODEL_FIELDS } from './settings.js';
5
6
  const FIRST_PRINTABLE_ASCII_CODE = 0x20;
6
7
  const ASCII_DELETE_CODE = 0x7f;
7
8
  const manifest = createRequire(import.meta.url)('../package.json');
@@ -34,16 +35,9 @@ const ACTION_NAMES = {
34
35
  uninstall: '移除程序',
35
36
  clean: '清理',
36
37
  };
37
- /** 模型配置表单的字段键与显示顺序 */
38
- export const MODEL_FIELDS = [
39
- { key: 'model', label: '默认模型' },
40
- { key: 'opus', label: 'Opus' },
41
- { key: 'sonnet', label: 'Sonnet' },
42
- { key: 'haiku', label: 'Haiku' },
43
- ];
44
38
  /** 配置表单在缺少已有值时采用的偏好 */
45
39
  export const DEFAULT_PREFERENCES = { language: 'Simplified Chinese', outputStyle: 'Explanatory' };
46
- /** 模型连接、语言和风格分别编辑,计划阶段仍合并为同一配置对象 */
40
+ /** 模型连接、语言和输出风格的独立编辑项 */
47
41
  export const SETTINGS_EDITORS = ['connection', 'language', 'outputStyle'];
48
42
  /** 语言和风格选择的显示标签与实际配置值 */
49
43
  export const SETTINGS_LANGUAGES = [
@@ -75,7 +69,7 @@ const GROUPS = {
75
69
  ccline: '附加工具',
76
70
  data: '清理数据',
77
71
  };
78
- /** 按终端菜单的类别顺序返回新数组,不修改输入 */
72
+ /** 按终端菜单的类别顺序排列条目,返回新数组 */
79
73
  export function contentOrder(items) {
80
74
  const order = ['claude', 'settings', 'plugin', 'skill', 'officecli', 'ccline', 'data'];
81
75
  return [...items].sort((left, right) => order.indexOf(left.kind) - order.indexOf(right.kind));
@@ -84,7 +78,7 @@ export function contentOrder(items) {
84
78
  export function contentRow(item) {
85
79
  return { label: contentName(item), detail: shortStatus(item), group: GROUPS[item.kind] };
86
80
  }
87
- /** 按当前值和本次草稿显示独立设置入口,不读取或写入配置 */
81
+ /** 根据当前值和表单草稿生成设置菜单行 */
88
82
  export function settingsRow(item, editor, fields) {
89
83
  const values = { ...item.values, ...fields };
90
84
  if (editor === 'connection')
@@ -108,9 +102,10 @@ export function settingsRow(item, editor, fields) {
108
102
  };
109
103
  }
110
104
  /**
111
- * 汇总检查条目和检查问题的显示文本
105
+ * 生成检查报告文本
112
106
  *
113
- * @param details - 为 true 时附带事实诊断代码;输入详情必须已脱敏
107
+ * @param details - 为 true 时附带事实诊断码
108
+ * @remarks 调用方须先对输入详情脱敏
114
109
  */
115
110
  export function describeInspection(view, details = false) {
116
111
  const lines = [];
@@ -143,7 +138,7 @@ export function describeInspection(view, details = false) {
143
138
  lines.push('\n── 检查未完成', ...view.problems.map(change => describeChange(change, details)));
144
139
  return lines.join('\n');
145
140
  }
146
- /** 优先采用表单中的显式连接模式,否则从已有配置事实推断初始选项 */
141
+ /** 解析表单连接模式,显式选项优先于已有配置 */
147
142
  export function effectiveConnection(values, facts) {
148
143
  return values.mode === 'api' || (values.mode !== 'official' && facts.some(fact => fact.code === 'api-configured'))
149
144
  ? 'api'
@@ -153,7 +148,7 @@ export function effectiveConnection(values, facts) {
153
148
  export function describePreparation(event) {
154
149
  return '准备:' + contentName(event);
155
150
  }
156
- /** 按产品类别展示计划,详细模式展开执行步骤 */
151
+ /** 按产品类别生成计划预览,详细模式展开执行步骤 */
157
152
  export function describePlan(plan, details = false) {
158
153
  const counts = new Map();
159
154
  for (const item of plan.items) {
@@ -233,11 +228,11 @@ export function describePlan(plan, details = false) {
233
228
  return lines.join('\n');
234
229
  }
235
230
  /**
236
- * 将计划、进度事件和最终结果转换为执行视图
231
+ * 创建执行视图生成器
237
232
  *
238
233
  * @param task - 整批失败时的任务名称,省略时显示通用失败文案
239
- * @param details - 显示原因码,不改变执行状态
240
- * @returns 仅更新内存的视图生成器,保留计划中的条目标题
234
+ * @param details - 是否显示原因码
235
+ * @returns 接收进度和最终结果的视图生成器,保留计划中的条目标题
241
236
  */
242
237
  export function createRunPresentation(plan, task, details = false) {
243
238
  const execution = new Map(plan.items.map(item => [
@@ -256,7 +251,7 @@ export function createRunPresentation(plan, task, details = false) {
256
251
  }
257
252
  };
258
253
  return {
259
- /** 记录已知条目的事件并返回当前视图;省略事件只读取视图 */
254
+ /** 更新已知条目的进度,省略事件时仅返回当前视图 */
260
255
  progress(event) {
261
256
  if (event) {
262
257
  const previous = execution.get(event.id);
@@ -270,14 +265,14 @@ export function createRunPresentation(plan, task, details = false) {
270
265
  }
271
266
  return progressView(items(), details);
272
267
  },
273
- /** 合入最终条目结果并返回结果视图 */
268
+ /** 合并最终条目结果,返回结果视图 */
274
269
  result(result) {
275
270
  recordResult(result);
276
271
  return resultView(result, items(), details, task);
277
272
  },
278
273
  };
279
274
  }
280
- /** 将执行视图转换为标题、汇总和状态行组成的多行文本 */
275
+ /** 生成包含标题、汇总和状态行的执行文本 */
281
276
  export function describeRun(view) {
282
277
  return [view.title, view.summary, ...view.rows.map(statusLine)].filter(Boolean).join('\n');
283
278
  }
@@ -293,8 +288,7 @@ function describeItem(item, nameWidth, details, commonPath) {
293
288
  information.push(['状态栏', facts.some(fact => fact.code === 'connected') ? '已配置' : '未配置']);
294
289
  if (item.kind === 'settings' && !item.problem) {
295
290
  for (const { key, label } of MODEL_FIELDS)
296
- if (values[key])
297
- information.push([label, values[key]]);
291
+ information.push([label, values[key]?.trim() || '未配置']);
298
292
  if (values.language)
299
293
  information.push(['默认语言', values.language]);
300
294
  if (values.outputStyle)
package/dist/settings.js CHANGED
@@ -3,7 +3,7 @@ import { knownTitle } from './management-catalog.js';
3
3
  import { isObject } from './machine.js';
4
4
  import { commandReceipt, json, object, success } from './model.js';
5
5
  import { applyFrozenJson, assessFrozenJson, jsonField, jsonFingerprint as digest } from './frozen-json.js';
6
- // 保留字段只定位已有键;偏好默认值由编辑器提交,不在安装初始化时补齐
6
+ // 保留字段只参与排序,偏好默认值由编辑表单提交
7
7
  const ROOT_FIELDS = {
8
8
  $schema: { placement: 'prefix', role: 'preserve' },
9
9
  defaultShell: { placement: 'prefix', role: 'preserve' },
@@ -35,42 +35,67 @@ const ENV_FIELDS = {
35
35
  ANTHROPIC_CUSTOM_HEADERS: { placement: 'suffix', role: 'preserve' },
36
36
  ANTHROPIC_API_KEY: { placement: 'suffix', role: 'key' },
37
37
  ANTHROPIC_AUTH_TOKEN: { placement: 'suffix', role: 'token' },
38
- ANTHROPIC_MODEL: { placement: 'suffix', role: 'model', editor: 'model' },
38
+ ANTHROPIC_MODEL: { placement: 'suffix', role: 'model', modelField: { key: 'model', label: '默认模型' } },
39
39
  ANTHROPIC_DEFAULT_MODEL: { placement: 'suffix', role: 'preserve' },
40
- ANTHROPIC_DEFAULT_FABLE_MODEL: { placement: 'suffix', role: 'model', editor: 'fable' },
41
- ANTHROPIC_DEFAULT_OPUS_MODEL: { placement: 'suffix', role: 'model', editor: 'opus' },
42
- ANTHROPIC_DEFAULT_SONNET_MODEL: { placement: 'suffix', role: 'model', editor: 'sonnet' },
43
- ANTHROPIC_DEFAULT_HAIKU_MODEL: { placement: 'suffix', role: 'model', editor: 'haiku' },
40
+ ANTHROPIC_DEFAULT_FABLE_MODEL: { placement: 'suffix', role: 'model', modelField: { key: 'fable', label: 'Fable' } },
41
+ ANTHROPIC_DEFAULT_OPUS_MODEL: { placement: 'suffix', role: 'model', modelField: { key: 'opus', label: 'Opus' } },
42
+ ANTHROPIC_DEFAULT_SONNET_MODEL: {
43
+ placement: 'suffix',
44
+ role: 'model',
45
+ modelField: { key: 'sonnet', label: 'Sonnet' },
46
+ },
47
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: { placement: 'suffix', role: 'model', modelField: { key: 'haiku', label: 'Haiku' } },
44
48
  };
45
49
  const rootFields = Object.entries(ROOT_FIELDS);
46
50
  const envFields = Object.entries(ENV_FIELDS);
51
+ /** 模型字段和显示名称的只读清单,沿用配置顺序 */
52
+ export const MODEL_FIELDS = Object.freeze(envFields.flatMap(([, field]) => (field.role === 'model' ? [Object.freeze({ ...field.modelField })] : [])));
47
53
  const connectionKeys = envFields
48
54
  .filter(([, field]) => ['base', 'key', 'token', 'model'].includes(field.role))
49
55
  .map(([key]) => key);
50
56
  const helperKeys = rootFields.filter(([, field]) => field.role === 'helper').map(([key]) => key);
51
57
  /**
52
- * 准备模型连接、偏好和默认设置变更
58
+ * 创建用户设置域
53
59
  *
54
- * @param selection - configure 可留空凭据以沿用所选认证类型;detach 只移除连接字段和凭据助手
55
- * @param claude - 官方登录所需的绑定命令
56
- * @returns 预览不含凭据的延迟流程,执行时复核字段并保留无关设置
57
- * @throws Error - 读取、动作、连接字段、登录依赖无效,无连接可解除或继承环境变量冲突时拒绝
58
- * @remarks 登录失败或取消不回滚已保存设置
60
+ * @returns 管理模型连接和偏好的设置域,检查时仅返回公开字段和凭据存在标记
61
+ * @remarks 仅在显式请求官方登录时获取计划绑定的 Claude 命令
59
62
  */
60
- export async function prepareSettings(ctx, selection, claude) {
63
+ export function createSettingsDomain(ctx) {
64
+ return {
65
+ inspect: async () => ({ items: [await inspectSettings(ctx)], problems: [] }),
66
+ async prepare(selection, getClaudeCommand) {
67
+ if (selection.id !== 'settings')
68
+ throw new Error('unknown-selection');
69
+ return prepareSettings(ctx, selection, getClaudeCommand);
70
+ },
71
+ };
72
+ }
73
+ /**
74
+ * 准备安装后的默认设置
75
+ *
76
+ * @returns 供安装核验后执行的工作项
77
+ * @throws Error - 设置文件读取失败或内容不是有效的 JSON 对象时拒绝 Promise
78
+ * @remarks 准备时只读取用户设置,执行时将自动更新通道设为 stable 并补齐其余缺失的默认项
79
+ */
80
+ export function prepareDefaultSettings(ctx) {
81
+ return prepareSettings(ctx, { action: 'configure' });
82
+ }
83
+ /** 准备用户设置变更,官方登录失败或取消时保留已保存的设置 */
84
+ async function prepareSettings(ctx, selection, getClaudeCommand) {
61
85
  if (!['configure', 'detach'].includes(selection.action))
62
86
  throw new Error('action-unavailable');
87
+ const fields = selection.action === 'detach' ? {} : (selection.fields ?? {});
88
+ const shouldLogIn = fields.mode === 'official' && fields.login === 'yes';
89
+ const loginCommand = shouldLogIn ? await getClaudeCommand?.() : undefined;
63
90
  const settings = await json(ctx.machine, ctx.settingsFile);
64
91
  const env = object(settings.env);
65
92
  if (selection.action === 'detach' &&
66
93
  !connectionKeys.some(key => env[key] !== undefined) &&
67
94
  !helperKeys.some(key => settings[key] !== undefined))
68
95
  throw new Error('no-connection');
69
- const fields = selection.action === 'detach' ? {} : (selection.fields ?? {});
70
96
  const changes = {};
71
97
  const preferences = {};
72
- const shouldLogin = fields.mode === 'official' && fields.login === 'yes';
73
- if (shouldLogin && !claude)
98
+ if (shouldLogIn && !loginCommand)
74
99
  throw new Error('claude-not-installed');
75
100
  const shouldControlHelper = selection.action === 'detach' || fields.mode === 'official' || fields.mode === 'api';
76
101
  if (selection.action === 'detach' || fields.mode === 'official') {
@@ -104,8 +129,8 @@ export async function prepareSettings(ctx, selection, claude) {
104
129
  for (const key of helperKeys)
105
130
  preferences[key] = undefined;
106
131
  for (const [key, field] of envFields)
107
- if (field.role === 'model' && fields[field.editor] !== undefined)
108
- changes[key] = fields[field.editor]?.trim() || undefined;
132
+ if (field.role === 'model' && fields[field.modelField.key] !== undefined)
133
+ changes[key] = fields[field.modelField.key]?.trim() || undefined;
109
134
  for (const [key, field] of rootFields)
110
135
  if (field.role === 'preference' && fields[key] !== undefined)
111
136
  preferences[key] = fields[key] || undefined;
@@ -148,26 +173,26 @@ export async function prepareSettings(ctx, selection, claude) {
148
173
  const write = writeSettings(ctx, patches, fields.secret?.trim() || undefined, [
149
174
  { code: selection.action === 'detach' ? 'settings-disconnect' : 'settings-edit', detail: ctx.settingsFile },
150
175
  ]);
151
- return shouldLogin && claude
176
+ return loginCommand
152
177
  ? sequence([
153
178
  step([], async () => {
154
- await claude.verify();
179
+ await loginCommand.verify();
155
180
  return { state: 'complete' };
156
181
  }),
157
182
  write,
158
- loginWork(claude),
183
+ loginWork(loginCommand),
159
184
  ])
160
185
  : write;
161
186
  }
162
- /** 供 Claude 管理域检查模型设置;只返回公开字段和凭据存在标记 */
163
- export async function inspectSettings(ctx) {
187
+ /** 读取模型与偏好设置,隐去凭据内容 */
188
+ async function inspectSettings(ctx) {
164
189
  const settings = await json(ctx.machine, ctx.settingsFile);
165
190
  const env = object(settings.env);
166
191
  const hasApiConfiguration = envFields.some(([key, field]) => ['base', 'key', 'token'].includes(field.role) && typeof env[key] === 'string');
167
192
  const values = {};
168
193
  if (hasApiConfiguration || Object.keys(settings).length > 0)
169
194
  values.mode = hasApiConfiguration ? 'api' : 'official';
170
- // 仅提示本文件的编辑选择,不代表已解析当前会话的认证来源
195
+ // 仅从用户设置推断表单的认证选项,实际会话由 Claude 解析
171
196
  values.auth = envFields.some(([key, field]) => field.role === 'token' && typeof env[key] === 'string' && env[key].trim() !== '')
172
197
  ? 'token'
173
198
  : 'key';
@@ -177,7 +202,7 @@ export async function inspectSettings(ctx) {
177
202
  if (field.role === 'base')
178
203
  values.baseUrl = value;
179
204
  if (field.role === 'model')
180
- values[field.editor] = value;
205
+ values[field.modelField.key] = value;
181
206
  }
182
207
  }
183
208
  for (const [key, field] of rootFields)
@@ -205,6 +230,7 @@ export async function inspectSettings(ctx) {
205
230
  canUninstall: connectionKeys.some(key => env[key] !== undefined) || helperKeys.some(key => settings[key] !== undefined),
206
231
  };
207
232
  }
233
+ /** 准备字段级写入,执行时复核目标字段并保留无关设置 */
208
234
  function writeSettings(ctx, patches, secret, changes) {
209
235
  let frozenDefaults;
210
236
  return step(changes, async (fact) => {
@@ -273,6 +299,7 @@ function writeSettings(ctx, patches, secret, changes) {
273
299
  return { receipt: { kind: 'returned', failure: null }, effects: [{ state: 'done', code: 'settings-saved' }] };
274
300
  });
275
301
  }
302
+ /** 准备交互登录,通过 Claude 认证状态核验结果 */
276
303
  function loginWork(claude) {
277
304
  const login = step([{ code: 'login-browser' }], async (fact) => {
278
305
  await claude.verify();
@@ -288,7 +315,7 @@ function loginWork(claude) {
288
315
  });
289
316
  return login;
290
317
  }
291
- /** 补齐安装默认值;保留显式值和继承变量声明 */
318
+ /** 固定自动更新通道,跳过已有值和继承变量以补齐其余默认项 */
292
319
  function initializeDefaults(settings, ctx) {
293
320
  const env = object(settings.env);
294
321
  const hasCustomBase = envFields.some(([key, field]) => {
@@ -315,7 +342,6 @@ function initializeDefaults(settings, ctx) {
315
342
  settings[key] = { ...field.value };
316
343
  root[key] = settings[key];
317
344
  }
318
- // 始终使用 stable 通道;首次危险模式确认使用官方设置
319
345
  if (settings.autoUpdatesChannel !== 'stable') {
320
346
  settings.autoUpdatesChannel = 'stable';
321
347
  root.autoUpdatesChannel = 'stable';
@@ -324,7 +350,7 @@ function initializeDefaults(settings, ctx) {
324
350
  settings.skipDangerousModePermissionPrompt = true;
325
351
  root.skipDangerousModePermissionPrompt = true;
326
352
  }
327
- // 权限默认模式只在缺失时补齐;已有选择(含更保守模式)不覆盖,allow/ask/deny 原样保留
353
+ // 仅在缺少默认模式时补齐,保留已有权限规则
328
354
  const permissions = object(settings.permissions);
329
355
  if (permissions.defaultMode === undefined) {
330
356
  permissions.defaultMode = 'bypassPermissions';
@@ -333,7 +359,7 @@ function initializeDefaults(settings, ctx) {
333
359
  }
334
360
  return { env: added, root };
335
361
  }
336
- /** 只重排 root/env 自身属性;未知键保持相对顺序,嵌套值保持原样 */
362
+ /** 重排配置对象的自身属性,保留未知键的相对顺序与嵌套值 */
337
363
  function orderFields(value, fields) {
338
364
  const known = new Set(fields.map(([key]) => key));
339
365
  const ordered = Object.fromEntries([
@@ -343,7 +369,7 @@ function orderFields(value, fields) {
343
369
  ].map(([key]) => [key, value[key]]));
344
370
  for (const key of Object.keys(value))
345
371
  delete value[key];
346
- // JSON 可包含 __proto__;以自身属性重建,不触发原型 setter
372
+ // 重建自身属性,避免 __proto__ 触发原型 setter
347
373
  Object.defineProperties(value, Object.getOwnPropertyDescriptors(ordered));
348
374
  }
349
375
  function jsonValue(value) {
@@ -359,11 +385,12 @@ function jsonValue(value) {
359
385
  throw new Error('invalid-settings');
360
386
  }
361
387
  /**
362
- * 校验 API 地址和凭据存在性,不连接远端服务
388
+ * 校验 API 地址与凭据是否齐备
363
389
  *
364
390
  * @param baseUrl - 可带首尾空白的 HTTP 或 HTTPS 地址
365
- * @param hasCredential - 调用方已确认是否存在有效凭据
366
- * @returns 缺少字段或地址格式的问题码;校验通过时为 null
391
+ * @param hasCredential - 是否有可提交或可保留的凭据
392
+ * @returns 校验通过时为 null,缺少字段或地址无效时返回问题码
393
+ * @remarks 仅校验本地输入
367
394
  */
368
395
  export function apiConfigurationProblem(baseUrl, hasCredential) {
369
396
  if (!baseUrl?.trim())
@@ -283,6 +283,7 @@ function InlineForm({ title, fields, validate, interrupt, done, }) {
283
283
  };
284
284
  const [problem, setProblem] = useState(null);
285
285
  const size = useWindowSize();
286
+ const labelWidth = Math.max(0, ...fields.map(field => stringWidth(field.label)));
286
287
  const append = (text) => {
287
288
  const field = fields[activeRef.current];
288
289
  if (field) {
@@ -355,14 +356,14 @@ function InlineForm({ title, fields, validate, interrupt, done, }) {
355
356
  : (values[field.key] ?? '');
356
357
  const characters = Array.from(text);
357
358
  const caret = index === active ? cursor : characters.length;
358
- const available = Math.max(1, size.columns - stringWidth(field.label) - LAYOUT.formDecorationColumns);
359
+ const available = Math.max(1, size.columns - labelWidth - LAYOUT.formDecorationColumns);
359
360
  let from = caret;
360
361
  while (from > 0 && stringWidth(characters.slice(from - 1, caret).join('')) < available)
361
362
  from--;
362
363
  let to = caret;
363
364
  while (to < characters.length && stringWidth(characters.slice(from, to + 1).join('')) < available)
364
365
  to++;
365
- return (_jsxs(Text, { wrap: "truncate-end", ...(index === active ? { color: ACCENT } : {}), children: [index === active ? '› ' : ' ', field.label, "\uFF1A", safeText(characters.slice(from, caret).join('')), index === active && _jsx(Text, { inverse: true, children: characters[caret] ?? ' ' }), safeText(characters.slice(caret + (index === active ? 1 : 0), to).join('')), !values[field.key] && field.placeholder ? ' ' + field.placeholder : ''] }, field.key));
366
+ return (_jsxs(Text, { wrap: "truncate-end", ...(index === active ? { color: ACCENT } : {}), children: [index === active ? '› ' : ' ', field.label, ' '.repeat(labelWidth - stringWidth(field.label)), "\uFF1A", safeText(characters.slice(from, caret).join('')), index === active && _jsx(Text, { inverse: true, children: characters[caret] ?? ' ' }), safeText(characters.slice(caret + (index === active ? 1 : 0), to).join('')), !values[field.key] && field.placeholder ? ' ' + field.placeholder : ''] }, field.key));
366
367
  }), _jsxs(Text, { ...(active === fields.length ? { color: ACCENT } : {}), children: [active === fields.length ? '› ' : ' ', "\u4FDD\u5B58"] }), _jsxs(Text, { ...(active === fields.length + 1 ? { color: ACCENT } : {}), children: [active === fields.length + 1 ? '› ' : ' ', "\u8FD4\u56DE"] }), problem && _jsx(Text, { color: "red", children: problem.message })] }));
367
368
  } }));
368
369
  }
package/dist/terminal.js CHANGED
@@ -1,6 +1,6 @@
1
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';
2
+ import { apiConfigurationProblem, MODEL_FIELDS } from './settings.js';
3
+ import { HOME_TITLE, BACK_TO_HOME, contentRow, contentOrder, describeInspection, describeChange, describePreparation, describeRun, describePlan, DEFAULT_PREFERENCES, effectiveConnection, SETTINGS_EDITORS, SETTINGS_LANGUAGES, SETTINGS_STYLES, settingsRow, reason, createRunPresentation, } from './render.js';
4
4
  const HOME_ACTIONS = [
5
5
  { label: '安装配置', id: 'install' },
6
6
  { label: '检查状态', id: 'inspect' },
@@ -22,11 +22,12 @@ const TASK_TEXT = {
22
22
  },
23
23
  };
24
24
  /**
25
- * 驱动主菜单、配置草稿、变更预览和确认后的执行
25
+ * 运行终端工作流
26
26
  *
27
27
  * @param signal - 传递给检查、计划准备与执行;取消不会唤醒正在等待输入的菜单或表单
28
28
  * @param details - 在检查、预览、执行结果和操作失败说明中附带原因码
29
- * @remarks 只有用户确认预览后才调用 apply;取消不回滚已执行变更,终端由调用方关闭
29
+ * @remarks 仅在用户确认预览后执行变更,取消不回滚已执行变更
30
+ * 调用方负责关闭终端
30
31
  * @throws Error - 未在操作页处理的终端或检查失败会拒绝 Promise
31
32
  */
32
33
  export async function runTerminal(ccw, terminal, signal, details = false) {
@@ -182,7 +183,7 @@ async function configure(item, editor, terminal, prior) {
182
183
  login: 'yes',
183
184
  },
184
185
  };
185
- const kept = item.hasCredential === true;
186
+ const hasSavedCredential = item.hasCredential === true;
186
187
  const fields = await terminal.form('第三方 API', [
187
188
  { key: 'baseUrl', label: 'Base URL', value: values.baseUrl ?? '' },
188
189
  {
@@ -190,16 +191,16 @@ async function configure(item, editor, terminal, prior) {
190
191
  label: 'API Key',
191
192
  value: prior?.fields?.secret ?? '',
192
193
  secret: true,
193
- placeholder: kept ? '留空保留现有凭据' : '必填',
194
+ placeholder: hasSavedCredential ? '留空保留现有凭据' : '必填',
194
195
  },
195
- ...MODEL_FIELDS.map(field => ({
196
- key: field.key,
197
- label: field.label,
198
- value: values[field.key] ?? '',
196
+ ...MODEL_FIELDS.map(({ key, label }) => ({
197
+ key,
198
+ label,
199
+ value: values[key] ?? '',
199
200
  placeholder: '选填',
200
201
  })),
201
202
  ], value => {
202
- const problem = apiConfigurationProblem(value.baseUrl, !!value.secret?.trim() || kept);
203
+ const problem = apiConfigurationProblem(value.baseUrl, Boolean(value.secret?.trim()) || hasSavedCredential);
203
204
  return problem
204
205
  ? { message: reason(problem), field: problem === 'credential-required' ? 'secret' : 'baseUrl' }
205
206
  : null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hit-sudomaker/ccw",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Claude Code lifecycle management terminal",
5
5
  "license": "MIT",
6
6
  "type": "module",