@cobia/pi-onward 0.5.1 → 0.5.3

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.
@@ -2,25 +2,33 @@
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { DEFAULT_LIMITS, FIELD_NAMES, FIELDS, type Field, fieldNamed } from "../policy/policy.ts";
4
4
  import type { Recovery } from "../runtime/recovery.ts";
5
+ import {
6
+ chooseEntry,
7
+ columns,
8
+ type Entry,
9
+ entryLabels,
10
+ HELP_ENTRY,
11
+ type HelpPage,
12
+ type MenuItem,
13
+ noticeWidth,
14
+ type Row,
15
+ helpText as renderHelp,
16
+ } from "./command-display.ts";
5
17
  import { COMMAND_KEYS, SCOPES, type Scope, type Settings, type SettingsChange } from "./settings.ts";
6
18
  import {
7
19
  actionsNotice,
8
20
  COMMAND,
9
21
  changedNotice,
10
- columns,
11
22
  commandErrorNotice,
12
23
  info,
13
- layerMenuText,
14
24
  layerNotice,
15
25
  menuTitle,
16
26
  type Notice,
17
27
  rulesNotice,
18
28
  SCOPE,
19
29
  say,
20
- section,
21
30
  showNotice,
22
31
  statusNotice,
23
- table,
24
32
  toggleNotice,
25
33
  } from "./text.ts";
26
34
 
@@ -31,21 +39,23 @@ export type Command =
31
39
  | { kind: "help"; topic?: string }
32
40
  | { kind: "show"; rules: boolean; scope?: Scope }
33
41
  | { kind: "update"; scope: Scope; change: SettingsChange }
34
- | { kind: "error"; message: string; topic?: string };
42
+ | { kind: "error"; problems: string[]; topic?: string };
35
43
 
36
- const HELP = "--help";
44
+ const HELP = HELP_ENTRY.name;
37
45
  const QUIET = "quietStartup";
38
- const QUIET_HELP: [string, string] = [
46
+ const QUIET_HELP: Row = [
39
47
  QUIET,
40
48
  [
41
- "启动时的提示(用上了项目级设置、没有可用的规则);设置有问题时照样警告。只能写在全局设置",
49
+ "启动时的提示(用上了项目级配置、没有可用的规则);配置有问题时照样警告。只能写在全局配置",
42
50
  "true:不显示",
43
51
  "false:照常显示,不管 pi 的 quietStartup",
44
52
  "不写:跟着 pi 的 quietStartup(默认)",
45
53
  ].join("\n"),
46
54
  ];
47
55
 
48
- const SCOPE_HELP = `${SCOPE} 只接受空格分隔的 global 或 project,最多一次且写在动作前;不写时修改全局,project 只改 Pi 已信任的当前项目;文件位置见 /${COMMAND} show`;
56
+ const SCOPE_SLOT = `${SCOPE} <${SCOPES.join("|")}>`;
57
+ const SCOPE_WRITE_HELP = `写在动作前,最多一次:global 改全局配置(不写时也是),project 只改 Pi 已信任的当前项目;文件位置见 /${COMMAND} show`;
58
+ const SCOPE_READ_HELP = "写在动作前:只看那一层的显式配置,不合并、不填默认值";
49
59
  const PARSING_HELP = [
50
60
  "命令只占一行,以空格或 Tab 分隔;不支持引号、转义、缩写或大小写转换",
51
61
  `${HELP} 最多一次且必须放在最后;只免除 set/unset 完全未填参数,已填内容仍须合法`,
@@ -62,69 +72,89 @@ interface ActionSpec {
62
72
  fields?: boolean;
63
73
  /** 是否允许 --scope;区分读配置与写配置。 */
64
74
  scoped?: "write" | "read";
65
- examples?: readonly string[];
66
- }
67
-
68
- /** 命令、帮助、菜单与补全共用的动作定义。 */
75
+ examples: readonly string[];
76
+ }
77
+
78
+ /** 重置放在动作最后;根菜单把 --scope … 放在它前面,紧跟修改类动作。 */
79
+ const RESET: ActionSpec = {
80
+ name: "reset",
81
+ args: "",
82
+ description: "重置配置参数,保留规则",
83
+ details: [
84
+ "开关、参数和 quietStartup 都去掉;rules 和其他手写的内容留着",
85
+ "反馈确认重置范围和保留内容,不把重置某一层说成整个项目恢复内置默认值",
86
+ "正在等的续跑立刻打断,运行状态和计数清零;即使目标配置无法读取或保存也一样",
87
+ "写入失败时本次运行保留配置修改,重新加载或重启后以原文件为准",
88
+ SCOPE_FALLBACK,
89
+ ],
90
+ scoped: "write",
91
+ examples: [`/${COMMAND} reset`, `/${COMMAND} ${SCOPE} project reset`],
92
+ };
93
+
94
+ /** 命令、帮助、菜单与补全共用的动作定义,按使用顺序排列。 */
69
95
  const ACTIONS: readonly ActionSpec[] = [
70
- {
71
- name: "actions",
72
- args: "",
73
- description: "查看已加载的恢复动作",
74
- details: ["列出动作名称、执行阶段、支持的运行模式和说明", "注册失败的动作另列诊断;未引用的坏动作不阻断当前配置"],
75
- },
76
96
  {
77
97
  name: "status",
78
98
  args: "",
79
99
  description: "查看当前状态",
80
100
  details: [
81
- "显示自动续跑开关和当前运行状态;待命时显示可用规则数,没有续跑记录时不显示零计数",
101
+ "显示自动恢复开关和当前运行状态;待命时显示可用规则数,没有续跑记录时不显示零计数",
82
102
  "显示连续失败次数、已启动续跑次数、当前恢复阶段和动作结果",
83
103
  "从第几次失败进入哪个阶段由 rules[].stages 决定,规则切换不清零",
84
104
  "超过 maxFailures 停止;原生接管受 maxHandoffs 限制",
85
- `默认参数、规则详情和设置文件位置见 /${COMMAND} show`,
105
+ `默认参数、规则详情和配置文件位置见 /${COMMAND} show`,
86
106
  `配置有问题时只显示原因摘要,详情用 /${COMMAND} show;停止时显示原因和处理提示`,
87
107
  ],
108
+ examples: [`/${COMMAND} status`],
109
+ },
110
+ {
111
+ name: "show",
112
+ args: "[rules]",
113
+ description: "查看配置参数、来源和规则",
114
+ details: [
115
+ "查看当前已加载的配置:开关与启动提示、恢复上限、规则及来源、配置文件位置",
116
+ "参数标明来源及未保存的字段;项目级 rules 整份替换全局规则,不拼接",
117
+ "show rules 只显示规则;按顺序列出,第一条命中的生效,停用的标出来",
118
+ "配置无效时只列具体问题和文件位置,不展示部分参数或规则",
119
+ `写了 ${SCOPE} 时只看本层显式配置,不合并、不填默认值;未写 rules 与显式空列表不同`,
120
+ "手改文件后使用 Pi 的 /reload;show 本身不重载、不写配置",
121
+ ],
122
+ scoped: "read",
123
+ examples: [`/${COMMAND} show rules`, `/${COMMAND} ${SCOPE} project show`],
124
+ },
125
+ {
126
+ name: "actions",
127
+ args: "",
128
+ description: "查看已加载的恢复动作",
129
+ details: ["列出动作名称、执行阶段、支持的运行模式和说明", "注册失败的动作另列诊断;未引用的坏动作不阻断当前配置"],
130
+ examples: [`/${COMMAND} actions`],
88
131
  },
89
132
  {
90
133
  name: "on",
91
134
  args: "",
92
- description: "启用自动续跑",
135
+ description: "启用自动恢复",
93
136
  details: [
94
- "在设置文件里写 enabled: true",
95
- "成功后只确认启用结果和配置范围;当前仍不能续跑时补充原因",
96
- "设置文件有问题时打开了也不续跑:先改好,再用 Pi 的 /reload",
137
+ "在配置文件里写 enabled: true",
138
+ "成功后只确认启用结果和配置范围;当前仍不能恢复时补充原因",
139
+ "配置文件有问题时打开了也不恢复:先改好,再用 Pi 的 /reload",
97
140
  "启用开关会取消当前恢复并清零,不立即发起恢复",
98
141
  "保存失败时明确提示;本次运行保留配置修改,重新加载或重启后以原文件为准",
99
142
  ],
100
143
  scoped: "write",
144
+ examples: [`/${COMMAND} on`, `/${COMMAND} ${SCOPE} project on`],
101
145
  },
102
146
  {
103
147
  name: "off",
104
148
  args: "",
105
- description: "停用自动续跑",
149
+ description: "停用自动恢复",
106
150
  details: [
107
- "在设置文件里写 enabled: false",
151
+ "在配置文件里写 enabled: false",
108
152
  "成功后只确认停用结果和配置范围;项目级仍启用时说明覆盖关系",
109
153
  "成功修改配置会取消等待、待执行动作并清零计数",
110
154
  "保存失败时明确提示;本次运行保留配置修改,重新加载或重启后以原文件为准",
111
155
  ],
112
156
  scoped: "write",
113
- },
114
- {
115
- name: "show",
116
- args: "[rules]",
117
- description: "查看配置参数、来源和规则",
118
- details: [
119
- "查看当前已加载的配置:开关与启动提示、恢复上限、规则及来源、配置文件位置",
120
- "参数标明来源及未保存的字段;项目级 rules 整份替换全局规则,不拼接",
121
- "show rules 只显示规则;按顺序列出,第一条命中的生效,停用的标出来",
122
- "配置无效时只列具体问题和文件位置,不展示部分参数或规则",
123
- `写了 ${SCOPE} 时只看本层显式配置,不合并、不填默认值;未写 rules 与显式空列表不同`,
124
- "手改文件后使用 Pi 的 /reload;show 本身不重载、不写配置",
125
- ],
126
- scoped: "read",
127
- examples: [`/${COMMAND} show rules`, `/${COMMAND} ${SCOPE} project show`],
157
+ examples: [`/${COMMAND} off`, `/${COMMAND} ${SCOPE} project off`],
128
158
  },
129
159
  {
130
160
  name: "set",
@@ -137,7 +167,7 @@ const ACTIONS: readonly ActionSpec[] = [
137
167
  "修改恢复过程的上限、动作执行时限和全局 quietStartup",
138
168
  "写入失败时本次运行保留配置修改,重新加载或重启后以原文件为准",
139
169
  "修改配置会取消当前恢复过程",
140
- `rules 只能在设置文件里手写,改完使用 Pi 的 /reload;开关用 /${COMMAND} on、off`,
170
+ `rules 只能在配置文件里手写,改完使用 Pi 的 /reload;开关用 /${COMMAND} on、off`,
141
171
  ],
142
172
  fields: true,
143
173
  scoped: "write",
@@ -162,22 +192,11 @@ const ACTIONS: readonly ActionSpec[] = [
162
192
  scoped: "write",
163
193
  examples: [`/${COMMAND} unset maxFailures actionTimeout`, `/${COMMAND} ${SCOPE} project unset enabled`],
164
194
  },
165
- {
166
- name: "reset",
167
- args: "",
168
- description: "重置配置参数,保留规则",
169
- details: [
170
- "开关、参数和 quietStartup 都去掉;rules 和其他手写的内容留着",
171
- "反馈确认重置范围和保留内容,不把重置某一层说成整个项目恢复内置默认值",
172
- "正在等的续跑立刻打断,运行状态和计数清零;即使目标配置无法读取或保存也一样",
173
- "写入失败时本次运行保留配置修改,重新加载或重启后以原文件为准",
174
- SCOPE_FALLBACK,
175
- ],
176
- scoped: "write",
177
- },
195
+ RESET,
178
196
  ];
179
197
 
180
- const DESCRIPTION = "控制自动续跑,查看状态和配置";
198
+ const SCOPE_ENTRY: Entry = { name: SCOPE, description: "只看、只改某一层配置", opens: "input" };
199
+ const DESCRIPTION = "控制自动恢复,查看状态和配置";
181
200
 
182
201
  export function registerCommand(pi: ExtensionAPI, settings: Settings, onward: Recovery): void {
183
202
  pi.registerCommand(COMMAND, {
@@ -201,7 +220,7 @@ export function registerCommand(pi: ExtensionAPI, settings: Settings, onward: Re
201
220
  });
202
221
  }
203
222
 
204
- /** 必填参数的动作只填入编辑器;其余返回可执行命令。 */
223
+ /** 需要补参数的项只填入编辑器;其余返回可执行命令。 */
205
224
  async function choose(
206
225
  ctx: ExtensionContext,
207
226
  settings: Settings,
@@ -209,38 +228,33 @@ async function choose(
209
228
  scope?: Scope,
210
229
  ): Promise<string | undefined> {
211
230
  if (!ctx.hasUI) return undefined;
212
- const items = menuItems(scope);
213
- const label = await ctx.ui.select(
231
+ const picked = await chooseEntry(
232
+ (heading, options) => ctx.ui.select(heading, options),
214
233
  menuTitle(settings, scope, onward.status().state),
215
- items.map((item) => item.label),
234
+ menuItems(scope),
216
235
  );
217
- const picked = items.find((item) => item.label === label);
218
- if (!picked?.fill) return picked?.input;
219
- ctx.ui.setEditorText(`/${COMMAND} ${picked.input} `);
236
+ if (picked?.opens !== "input") return picked?.value;
237
+ ctx.ui.setEditorText(`/${COMMAND} ${picked.value} `);
220
238
  return undefined;
221
239
  }
222
240
 
223
- export function menuItems(scope?: Scope): { label: string; input: string; fill: boolean }[] {
224
- const actions = scope ? ACTIONS.filter((item) => item.scoped) : ACTIONS;
225
- const layers = scope ? [] : SCOPES;
226
- const labels = columns([
227
- ...actions.map((item): [string, string] => [item.name, item.description]),
228
- ...layers.map((layer): [string, string] => [`${SCOPE} ${layer} …`, layerMenuText(layer)]),
229
- [HELP, "显示帮助"],
230
- ]);
231
- return [
232
- ...actions.map((item, index) => ({
233
- label: labels[index]!,
234
- input: scope ? `${SCOPE} ${scope} ${item.name}` : item.name,
235
- fill: item.args !== "" && !item.args.startsWith("["),
236
- })),
237
- ...layers.map((layer, index) => ({
238
- label: labels[actions.length + index]!,
239
- input: `${SCOPE} ${layer}`,
240
- fill: false,
241
- })),
242
- { label: labels.at(-1)!, input: HELP, fill: false },
243
- ];
241
+ /** 菜单、帮助的动作表和补全共用这份列表;value 是选中后执行或填入的命令。 */
242
+ export function menuItems(scope?: Scope): MenuItem<string>[] {
243
+ const item = (spec: ActionSpec): MenuItem<string> => ({
244
+ name: spec.name,
245
+ description: spec.description,
246
+ ...(needsArguments(spec) ? { opens: "input" as const } : {}),
247
+ value: scope ? `${SCOPE} ${scope} ${spec.name}` : spec.name,
248
+ });
249
+ const help: MenuItem<string> = { ...HELP_ENTRY, value: HELP };
250
+ // 作用域菜单里的 --help 显示总帮助。
251
+ if (scope) return [...ACTIONS.filter((spec) => spec.scoped).map(item), help];
252
+ const others = ACTIONS.filter((spec) => spec !== RESET);
253
+ return [...others.map(item), { ...SCOPE_ENTRY, value: SCOPE }, item(RESET), help];
254
+ }
255
+
256
+ function needsArguments(spec: ActionSpec): boolean {
257
+ return spec.args !== "" && !spec.args.startsWith("[");
244
258
  }
245
259
 
246
260
  function execute(
@@ -251,18 +265,19 @@ function execute(
251
265
  ): Notice {
252
266
  // Read-only queries never change the recovery state.
253
267
  const status = () => onward.status();
268
+ const state = () => status().state;
254
269
  switch (command.kind) {
255
270
  case "actions":
256
- return actionsNotice(onward.registry.list(), onward.registry.diagnostics);
271
+ return actionsNotice(onward.registry.list(), onward.registry.diagnostics, settings, state());
257
272
  case "status":
258
273
  return statusNotice(settings, status());
259
274
  case "help":
260
- return info(helpText(command.topic));
275
+ return info(helpText(command.topic, noticeWidth(ctx.mode)));
261
276
  case "error":
262
- return commandErrorNotice(command.message, command.topic);
277
+ return commandErrorNotice(command.problems, command.topic);
263
278
  case "show":
264
- if (command.scope) return layerNotice(settings, command.scope, command.rules);
265
- return command.rules ? rulesNotice(settings) : showNotice(settings);
279
+ if (command.scope) return layerNotice(settings, command.scope, command.rules, state());
280
+ return command.rules ? rulesNotice(settings, state()) : showNotice(settings, state());
266
281
  case "reset": {
267
282
  const saved = settings.reset(command.scope);
268
283
  onward.stop(ctx);
@@ -285,7 +300,7 @@ function execute(
285
300
  export function parseCommand(text: string): Command {
286
301
  const parsed = parseStructure(scan(text).words);
287
302
  if (parsed.kind === "error") return parsed;
288
- if (parsed.kind === "scope") return syntaxError(`${SCOPE} requires ${SCOPES.join(" or ")} as its value`);
303
+ if (parsed.kind === "scope") return syntaxError(`${SCOPE} 后面要写 ${SCOPES.join(" 或 ")}`);
289
304
  return resolveCommand(parsed);
290
305
  }
291
306
 
@@ -307,36 +322,31 @@ function parseStructure(tokens: readonly string[]): CommandInput | { kind: "scop
307
322
  const problem = tokenProblem(token);
308
323
  if (problem) return syntaxError(problem, topic);
309
324
  if (token === HELP) {
310
- if (input.scope && !input.spec) return syntaxError(`${SCOPE} requires an action before ${HELP}`);
325
+ if (input.scope && !input.spec) return syntaxError(`${SCOPE} 后面要先写动作,才能用 ${HELP}`);
311
326
  if (index < tokens.length - 1)
312
- return syntaxError(
313
- tokens[index + 1] === HELP ? `${HELP} may only be specified once` : `${HELP} must be the last argument`,
314
- topic,
315
- );
327
+ return syntaxError(tokens[index + 1] === HELP ? `${HELP} 只能出现一次` : `${HELP} 必须放在最后`, topic);
316
328
  input.help = true;
317
329
  continue;
318
330
  }
319
331
  if (token === SCOPE) {
320
- if (input.scope) return syntaxError(`${SCOPE} may only be specified once`, topic);
321
- if (input.spec) return syntaxError(`${SCOPE} must precede the action`, topic);
332
+ if (input.scope) return syntaxError(`${SCOPE} 只能出现一次`, topic);
333
+ if (input.spec) return syntaxError(`${SCOPE} 要写在动作前`, topic);
322
334
  const value = tokens[++index];
323
335
  if (value === undefined) return { kind: "scope" };
324
336
  const invalid = tokenProblem(value);
325
337
  if (invalid) return syntaxError(invalid);
326
- if (value.startsWith("-")) return syntaxError(`${SCOPE} requires ${SCOPES.join(" or ")} as its value`);
338
+ if (value.startsWith("-")) return syntaxError(`${SCOPE} 后面要写 ${SCOPES.join(" 或 ")}`);
327
339
  const scope = scopeNamed(value);
328
- if (!scope) return syntaxError(`${SCOPE} must be ${SCOPES.join(" or ")}`);
340
+ if (!scope) return syntaxError(`${SCOPE} 只能是 ${SCOPES.join(" 或 ")}`);
329
341
  input.scope = scope;
330
342
  continue;
331
343
  }
332
- if (token.startsWith(`${SCOPE}=`))
333
- return syntaxError(`${SCOPE} requires a space before its value; '=' is not supported`, topic);
334
- if (token.startsWith("-")) return syntaxError(`Unknown option '${token}'`, topic);
344
+ if (token.startsWith(`${SCOPE}=`)) return syntaxError(`${SCOPE} 和值之间用空格分隔,不支持 =`, topic);
345
+ if (token.startsWith("-")) return syntaxError(`未知选项 ${token}`, topic);
335
346
  if (!input.spec) {
336
347
  const spec = actionNamed(token);
337
348
  if (!spec) return unknownAction(token);
338
- if (input.scope && !spec.scoped)
339
- return syntaxError(`${SCOPE} is only supported by ${scopedActions()}`, spec.name);
349
+ if (input.scope && !spec.scoped) return syntaxError(`只有 ${scopedActions()} 支持 ${SCOPE}`, spec.name);
340
350
  input.spec = spec;
341
351
  continue;
342
352
  }
@@ -350,17 +360,17 @@ function parseStructure(tokens: readonly string[]): CommandInput | { kind: "scop
350
360
  function argumentProblem(action: string, token: string, position: number): string | undefined {
351
361
  switch (action) {
352
362
  case "show":
353
- return position === 0 && token === "rules" ? undefined : "show only accepts the optional argument 'rules'";
363
+ return position === 0 && token === "rules" ? undefined : "show 只接受可选参数 rules";
354
364
  case "set": {
355
365
  const equals = token.indexOf("=");
356
366
  return equals > 0 && equals < token.length - 1 && equals === token.lastIndexOf("=")
357
367
  ? undefined
358
- : `'${token}' must be one field=value with exactly one '=' and a non-empty field and value`;
368
+ : `${token} 必须是完整的 字段=值,恰好一个 =,两侧非空`;
359
369
  }
360
370
  case "unset":
361
- return token.includes("=") ? "unset requires field names without '='" : undefined;
371
+ return token.includes("=") ? "unset 只接受字段名,不带 =" : undefined;
362
372
  default:
363
- return `${action} does not accept arguments`;
373
+ return `${action} 不接受参数`;
364
374
  }
365
375
  }
366
376
 
@@ -396,8 +406,8 @@ function resolveCommand(input: CommandInput): Command {
396
406
  return help && command.kind !== "error" ? { kind: "help", topic: spec.name } : command;
397
407
  }
398
408
 
399
- function syntaxError(message: string, topic?: string): CommandError {
400
- return { kind: "error", message, ...(topic && { topic }) };
409
+ function syntaxError(problem: string, topic?: string): CommandError {
410
+ return { kind: "error", problems: [problem], ...(topic && { topic }) };
401
411
  }
402
412
 
403
413
  function scopeNamed(value: string | undefined): Scope | undefined {
@@ -407,20 +417,15 @@ function scopeNamed(value: string | undefined): Scope | undefined {
407
417
  function scopedActions(only?: "write"): string {
408
418
  return ACTIONS.filter((item) => (only ? item.scoped === only : item.scoped))
409
419
  .map((item) => item.name)
410
- .join(", ");
420
+ .join("、");
411
421
  }
412
422
 
413
423
  function unknownAction(word: string): CommandError {
414
- return syntaxError(`Unknown action '${word}'; available actions: ${actionList()}`);
424
+ return syntaxError(`未知动作 ${word};可用动作:${actionList()}`);
415
425
  }
416
426
 
417
427
  function parseSet(tokens: string[], scope: Scope): Command {
418
- if (!tokens.length)
419
- return {
420
- kind: "error",
421
- message: `set requires field=value; available fields: ${settable(scope).join(", ")}`,
422
- topic: "set",
423
- };
428
+ if (!tokens.length) return syntaxError(`set 至少要写一个 字段=值;可用字段:${settable(scope).join("、")}`, "set");
424
429
  const problems: string[] = [];
425
430
  const seen = new Set<string>();
426
431
  const values: Record<string, unknown> = {};
@@ -428,7 +433,7 @@ function parseSet(tokens: string[], scope: Scope): Command {
428
433
  const equals = token.indexOf("=");
429
434
  const key = token.slice(0, equals);
430
435
  const text = token.slice(equals + 1);
431
- if (seen.has(key)) problems.push(`${key} may only be specified once`);
436
+ if (seen.has(key)) problems.push(`${key} 不能重复`);
432
437
  seen.add(key);
433
438
  const parsed = key === QUIET ? quietValue(text, scope) : paramValue(key, text, scope);
434
439
  if ("problem" in parsed) problems.push(parsed.problem);
@@ -449,9 +454,8 @@ function paramValue(key: string, text: string, scope: Scope): Parsed {
449
454
 
450
455
  /** 项目不能自行隐藏启用项目配置的提示。 */
451
456
  function quietValue(text: string, scope: Scope): Parsed {
452
- if (scope !== "global")
453
- return { problem: `${QUIET} is only allowed in global settings; omit ${SCOPE} to use global scope` };
454
- if (text !== "true" && text !== "false") return { problem: `${QUIET} must be true or false` };
457
+ if (scope !== "global") return { problem: `${QUIET} 只能写在全局配置;去掉 ${SCOPE} 即为全局` };
458
+ if (text !== "true" && text !== "false") return { problem: `${QUIET} 必须是 true 或 false` };
455
459
  return { name: QUIET, value: text === "true" };
456
460
  }
457
461
 
@@ -460,17 +464,12 @@ function settable(scope: Scope): readonly string[] {
460
464
  }
461
465
 
462
466
  function parseUnset(tokens: string[], scope: Scope): Command {
463
- if (!tokens.length)
464
- return {
465
- kind: "error",
466
- message: `unset requires field names; available fields: ${COMMAND_KEYS.join(", ")}`,
467
- topic: "unset",
468
- };
467
+ if (!tokens.length) return syntaxError(`unset 至少要写一个字段名;可用字段:${COMMAND_KEYS.join("、")}`, "unset");
469
468
  const problems: string[] = [];
470
469
  const seen = new Set<string>();
471
470
  const unset: string[] = [];
472
471
  for (const token of tokens) {
473
- if (seen.has(token)) problems.push(`${token} may only be specified once`);
472
+ if (seen.has(token)) problems.push(`${token} 不能重复`);
474
473
  seen.add(token);
475
474
  const key = unsetKey(token, scope);
476
475
  if ("problem" in key) problems.push(key.problem);
@@ -487,18 +486,18 @@ function unsetKey(token: string, scope: Scope): { name: string } | { problem: st
487
486
  }
488
487
 
489
488
  function paramField(key: string, scope: Scope, names: readonly string[] = FIELD_NAMES): Field | string {
490
- if (key === "rules") return "rules must be edited in the settings file; then run Pi's /reload";
489
+ if (key === "rules") return "rules 只能在配置文件里修改,改完使用 Pi 的 /reload";
491
490
  if (key === "enabled")
492
- return `use /${COMMAND} ${scope === "project" ? `${SCOPE} project ` : ""}on or off to change enabled`;
493
- return fieldNamed(key) ?? `Unknown field '${key}'; available fields: ${names.join(", ")}`;
491
+ return `enabled 用 /${COMMAND} ${scope === "project" ? `${SCOPE} project ` : ""}on 或 off 修改`;
492
+ return fieldNamed(key) ?? `未知字段 ${key};可用字段:${names.join("、")}`;
494
493
  }
495
494
 
496
495
  function rejected(problems: string[], topic: string): Command {
497
- return { kind: "error", message: `${problems.join("; ")}. No changes made`, topic };
496
+ return { kind: "error", problems, topic };
498
497
  }
499
498
 
500
499
  function actionList(): string {
501
- return ACTIONS.map((item) => item.name).join(", ");
500
+ return ACTIONS.map((item) => item.name).join("、");
502
501
  }
503
502
 
504
503
  function actionNamed(name: string): ActionSpec | undefined {
@@ -507,65 +506,49 @@ function actionNamed(name: string): ActionSpec | undefined {
507
506
 
508
507
  // ── 帮助 ──
509
508
 
510
- export function helpText(topic?: string): string {
509
+ export function helpText(topic?: string, width?: number): string {
511
510
  const spec = topic === undefined ? undefined : actionNamed(topic);
512
- return spec ? actionHelp(spec) : overallHelp();
513
- }
514
-
515
- function overallHelp(): string {
516
- return [
517
- `${COMMAND} — ${DESCRIPTION}`,
518
- `用法:/${COMMAND}`,
519
- ` /${COMMAND} ${HELP}`,
520
- ` /${COMMAND} ${SCOPE} <${SCOPES.join("|")}>`,
521
- ` /${COMMAND} [${SCOPE} <${SCOPES.join("|")}>] <动作> [参数] [${HELP}]`,
522
- ...section("动作", table(ACTIONS.map((item) => [item.name, item.description]))),
523
- "",
524
- ` 不写动作时弹出菜单,标题区分当前状态和修改目标;菜单里的 ${SCOPE} <层> … 进到只看、只改那一份的菜单`,
525
- ` ${scopedActions("write")} 改哪一份设置由 ${SCOPE} 定,写在动作前:不写或 global 是全局,project 是当前目录的项目级`,
526
- ` show 不写 ${SCOPE} 时看合并后的结果,写了只看那一份`,
527
- ` status/actions 不支持 ${SCOPE};${SCOPE} <层> ${HELP} 缺少动作,不能用于查看帮助`,
528
- " 命令修改配置后立即生效;手改文件后使用 Pi 的 /reload",
529
- ...section(
530
- "解析规则",
531
- PARSING_HELP.map((line) => ` ${line}`),
532
- ),
533
- ` 每个动作的用法:/${COMMAND} <动作> ${HELP}(只显示帮助,不执行)`,
534
- ` 字段和默认值:/${COMMAND} set ${HELP}`,
535
- ].join("\n");
536
- }
537
-
538
- function actionHelp(spec: ActionSpec): string {
539
- return [
540
- `${spec.name} — ${spec.description}`,
541
- `用法:/${COMMAND} ${usage(spec)}`,
542
- ...section(
543
- "说明",
544
- [
545
- ...spec.details,
546
- ...PARSING_HELP,
547
- ...(spec.scoped === "write" ? ["配置修改立即在当前运行中生效,无需 /reload", SCOPE_HELP] : []),
548
- ].map((line) => ` ${line}`),
549
- ),
550
- ...(spec.fields
551
- ? section(
552
- "字段",
553
- table([
554
- ...(spec.name === "unset" ? [["enabled", "自动续跑开关;去掉后继承下一层"] as [string, string]] : []),
555
- ...FIELDS.map((item): [string, string] => [item.name, fieldHelp(item)]),
556
- QUIET_HELP,
557
- ]),
558
- )
559
- : []),
560
- ...section(
561
- "示例",
562
- (spec.examples ?? []).map((line) => ` ${line}`),
563
- ),
564
- ].join("\n");
511
+ return renderHelp(spec ? actionHelp(spec) : overallHelp(), width);
512
+ }
513
+
514
+ function overallHelp(): HelpPage {
515
+ return {
516
+ path: COMMAND,
517
+ description: DESCRIPTION,
518
+ usage: [`/${COMMAND} [${SCOPE_SLOT}] [动作] [参数] [${HELP}]`],
519
+ notes: [
520
+ "不写动作时打开菜单,Esc 取消,不执行任何操作;菜单里的修改默认写入全局配置",
521
+ `${SCOPE} <层> 写在动作前,只看、只改那一层;不写时 ${scopedActions("write")} 修改全局,show 看合并结果`,
522
+ `status、actions 不支持 ${SCOPE};${SCOPE} <层> 后面要写动作才能加 ${HELP}`,
523
+ "命令修改配置后立即生效;手改文件后使用 Pi 的 /reload",
524
+ ],
525
+ actions: menuItems(),
526
+ examples: [`/${COMMAND} status`, `/${COMMAND} set maxFailures=20`, `/${COMMAND} ${SCOPE} project off`],
527
+ more: [`/${COMMAND} set ${HELP}`, `/${COMMAND} show ${HELP}`],
528
+ };
529
+ }
530
+
531
+ function actionHelp(spec: ActionSpec): HelpPage {
532
+ return {
533
+ path: `${COMMAND} ${spec.name}`,
534
+ description: spec.description,
535
+ usage: [`/${COMMAND} ${usage(spec)}`],
536
+ notes: [...spec.details, ...(spec.scoped === "write" ? ["配置修改立即在当前运行中生效,无需 /reload"] : [])],
537
+ fields: spec.fields
538
+ ? [
539
+ ...(spec.name === "unset" ? [["enabled", "自动恢复开关;去掉后继承下一层"] as const] : []),
540
+ ...FIELDS.map((item): Row => [item.name, fieldHelp(item)]),
541
+ QUIET_HELP,
542
+ ]
543
+ : [],
544
+ options: spec.scoped ? [[SCOPE_SLOT, spec.scoped === "write" ? SCOPE_WRITE_HELP : SCOPE_READ_HELP]] : [],
545
+ examples: spec.examples,
546
+ syntax: PARSING_HELP,
547
+ };
565
548
  }
566
549
 
567
550
  function usage(spec: ActionSpec): string {
568
- const words = [spec.scoped ? `[${SCOPE} <${SCOPES.join("|")}>]` : "", spec.name, spec.args, `[${HELP}]`];
551
+ const words = [spec.scoped ? `[${SCOPE_SLOT}]` : "", spec.name, spec.args, `[${HELP}]`];
569
552
  return words.filter(Boolean).join(" ");
570
553
  }
571
554
 
@@ -586,9 +569,9 @@ function scan(text: string): { words: string[]; start: number } {
586
569
  function tokenProblem(token: string): string | undefined {
587
570
  const invalid = /['"\s\u0085]/u.exec(token)?.[0];
588
571
  if (invalid === undefined) return undefined;
589
- if (invalid === "'" || invalid === '"') return "Quotes are not supported";
590
- if (/[\r\n\u0085\u2028\u2029]/u.test(invalid)) return "Commands must be a single line";
591
- return "Only spaces and tabs may separate arguments";
572
+ if (invalid === "'" || invalid === '"') return "命令不支持引号";
573
+ if (/[\r\n\u0085\u2028\u2029]/u.test(invalid)) return "命令只能占一行";
574
+ return "参数之间只能用空格或 Tab 分隔";
592
575
  }
593
576
 
594
577
  // ── 补全 ──
@@ -606,52 +589,53 @@ export function completeArguments(prefix: string): { value: string; label: strin
606
589
  const head = prefix.slice(0, start);
607
590
  const done = current ? words.slice(0, -1) : words;
608
591
  const all = candidates(done, current);
609
- // 说明写进 label,不另给 description:pi 的参数补全把名字列固定留 32 格,说明会隔开一大截。
610
- // 列宽按这一层的全部候选算,不按过滤后的:边打字边过滤时说明不左右跳。
611
- const labels = columns(all.map((item): [string, string] => [item.value, item.description]));
612
- const shown = all.flatMap((item, index) =>
613
- item.value.startsWith(current) ? [{ item, label: labels[index]! }] : [],
614
- );
615
- if (!shown.length || shown.some(({ item }) => item.value === current)) return null;
616
- const spaced = (item: Candidate) => !item.value.endsWith("=") && candidates([...done, item.value], "").length > 0;
617
- return shown.map(({ item, label }) => ({
618
- value: `${head}${item.value}${spaced(item) ? " " : ""}`,
619
- label,
620
- }));
621
- }
622
-
623
- function candidates(typed: string[], current: string): Candidate[] {
592
+ if (!all) return null;
593
+ const shown = all.flatMap((item) => (item.value.startsWith(current) ? [item] : []));
594
+ if (!shown.length || shown.some((item) => item.value === current)) return null;
595
+ const spaced = (value: string) => !value.endsWith("=") && (candidates([...done, value], "")?.length ?? 0) > 0;
596
+ return shown.map((item) => ({ value: `${head}${item.value}${spaced(item.value) ? " " : ""}`, label: item.label }));
597
+ }
598
+
599
+ /**
600
+ * 这一层的全部候选。说明写进 label,不另给 description:pi 的参数补全把名字列固定留 32 格,说明会隔开一大截。
601
+ * 列宽按这一层的全部候选算,不按过滤后的:边打字边过滤时说明不左右跳。动作层与菜单用同一组标签。
602
+ */
603
+ function candidates(typed: string[], current: string): { value: string; label: string }[] | null {
624
604
  const parsed = parseStructure(typed);
625
- if (parsed.kind === "error") return [];
605
+ if (parsed.kind === "error") return null;
626
606
  if (parsed.kind === "scope")
627
- return [
628
- { value: "global", description: "全局设置;改设置时不写 --scope 就是它" },
629
- { value: "project", description: "当前目录的项目级设置" },
630
- ];
631
- if (parsed.help) return [];
607
+ return labelled([
608
+ { value: "global", description: "全局配置;改配置时不写 --scope 就是它" },
609
+ { value: "project", description: "当前目录的项目级配置" },
610
+ ]);
611
+ if (parsed.help) return null;
632
612
  const { spec, scope, args } = parsed;
633
- if (!spec)
634
- return [
635
- ...(scope ? [] : [{ value: SCOPE, description: "指定查看或修改的配置范围" }]),
636
- ...ACTIONS.filter((item) => !scope || item.scoped).map((item) => ({
637
- value: item.name,
638
- description: item.description,
639
- })),
640
- ...(scope ? [] : [{ value: HELP, description: "显示帮助" }]),
641
- ];
613
+ if (!spec) {
614
+ const entries = menuItems(scope);
615
+ const labels = entryLabels(entries);
616
+ // 作用域菜单里的 --help 显示总帮助;输入的 --scope <层> --help 缺少动作,补全不提供。
617
+ return entries.flatMap((entry, index) =>
618
+ scope && entry.name === HELP ? [] : [{ value: entry.name, label: labels[index]! }],
619
+ );
620
+ }
642
621
  // 只豁免尚未填写参数;所有已经结束的 token 都经过实际执行使用的字段校验。
643
- if (resolveCommand({ ...parsed, help: true }).kind === "error") return [];
622
+ if (resolveCommand({ ...parsed, help: true }).kind === "error") return null;
644
623
  const values =
645
624
  spec.name === "set" || spec.name === "unset"
646
625
  ? fieldCandidates(spec.name, args, current, scope ?? "global")
647
626
  : spec.name === "show" && !args.length
648
627
  ? [{ value: "rules", description: "只看规则" }]
649
628
  : [];
650
- return [...values, { value: HELP, description: `显示 ${spec.name} 的帮助,不执行` }];
629
+ return labelled([...values, { value: HELP, description: HELP_ENTRY.description }]);
630
+ }
631
+
632
+ function labelled(items: readonly Candidate[]): { value: string; label: string }[] {
633
+ const labels = columns(items.map((item): Row => [item.value, item.description]));
634
+ return items.map((item, index) => ({ value: item.value, label: labels[index]! }));
651
635
  }
652
636
 
653
637
  const QUIET_CHOICES: readonly Candidate[] = [
654
- { value: "true", description: "启动时不显示 onward 的提示;设置有问题时照样警告" },
638
+ { value: "true", description: "启动时不显示 onward 的提示;配置有问题时照样警告" },
655
639
  { value: "false", description: "照常显示,不管 pi 的 quietStartup" },
656
640
  ];
657
641