@cobia/pi-onward 0.1.1 → 0.2.0

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.
@@ -1,42 +1,63 @@
1
1
  /**
2
- * `/onward <动作> [参数]`:动作在前,参数写成 `字段=值`,字段名和设置文件一样。`set` 全有或全无:任何一项
3
- * 不合法就一项都不写。不写动作时弹出菜单,标题是现在的状态。
2
+ * `/onward <动作> [参数]`:动作在前,参数写成 `字段=值`,字段名和设置文件一样。动作、字段、取值和选项都区分大小写,
3
+ * 和设置文件、pi 自己的命令名一样。`set` 全有或全无:任何一项不合法就一项都不写。不写动作时弹出菜单,标题是现在的状态。
4
4
  *
5
5
  * `--help` 是结束:写在哪都只显示帮助、不执行,跟在动作后面时显示这个动作的帮助。补全在每个动作后面都给它,
6
6
  * 写了它之后什么都不再给,后面有没有空格都一样。
7
+ *
8
+ * 看或改哪一份设置文件由 `--scope <global|project>` 定,和 wecom-aibot 的 `config --scope <层> <动作>` 一样写在动作前:
9
+ * `/onward --scope project set maxRetries=3`,也可以写成 `--scope=project`。改设置的动作(on、off、set、unset、reset)
10
+ * 不写就是全局,和 pi 的 `install`、`config` 不加 `--local` 时一样:同一条命令总是写同一个文件,仓库里的文件要写明才改。
11
+ * show 不写时看合并后的结果,写了只看那一份写了什么。写在动作后不执行,报错给出正确的写法;只写 `--scope` 不写动作时,
12
+ * 弹出这一份的菜单,`/onward` 的菜单里也有进到每一份的项。
7
13
  */
8
14
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
9
15
  import { isActive } from "../policy/config.ts";
10
16
  import { DEFAULT_POLICY, FIELD_NAMES, FIELDS, type Field, fieldNamed } from "../policy/policy.ts";
11
17
  import type { Onward } from "./onward.ts";
12
- import type { Settings, SettingsChange } from "./settings.ts";
18
+ import { COMMAND_KEYS, SCOPES, type Scope, type Settings, type SettingsChange } from "./settings.ts";
13
19
  import {
14
20
  COMMAND,
15
21
  changedNotice,
16
22
  columns,
17
23
  commandErrorNotice,
18
24
  info,
25
+ layerMenuText,
26
+ layerNotice,
27
+ menuTitle,
19
28
  type Notice,
29
+ resetLine,
20
30
  rulesNotice,
31
+ SCOPE,
21
32
  say,
33
+ scopeLine,
22
34
  section,
35
+ shadowLine,
23
36
  showNotice,
24
- statusHeadline,
25
37
  statusNotice,
26
38
  table,
27
39
  } from "./text.ts";
28
40
 
29
- /** `topic`:帮助或出错是关于哪个动作的,没有时是总帮助。`choose`:没写动作,弹菜单。 */
41
+ /**
42
+ * `topic`:帮助或出错是关于哪个动作的,没有时是总帮助。`choose`:没写动作,弹菜单;写了 `--scope` 时只列改这一份的。
43
+ * `scope`:改哪一份设置文件。
44
+ */
30
45
  export type Command =
31
- | { kind: "choose" }
32
- | { kind: "status" | "reload" | "reset" }
46
+ | { kind: "choose"; scope?: Scope }
47
+ | { kind: "status" | "reload" }
48
+ | { kind: "reset"; scope: Scope }
33
49
  | { kind: "help"; topic?: string }
34
- | { kind: "show"; rules: boolean }
35
- | { kind: "update"; change: SettingsChange }
50
+ | { kind: "show"; rules: boolean; scope?: Scope }
51
+ | { kind: "update"; scope: Scope; change: SettingsChange }
36
52
  | { kind: "error"; message: string; topic?: string };
37
53
 
38
54
  const HELP = "--help";
39
55
 
56
+ /** 改设置的动作的帮助里都有这一行。不写路径:设置文件放在哪只由 index.ts 决定,实际的路径在 status 里。 */
57
+ const SCOPE_HELP = `${SCOPE} 写在动作前:不写或 global 改全局设置,project 改当前目录的项目级设置;两份在哪见 /${COMMAND} status`;
58
+ /** 去掉参数的动作:去掉之后按什么走。 */
59
+ const SCOPE_FALLBACK = "去掉之后继承下一层:项目级的退回全局,全局的退回内置默认值";
60
+
40
61
  interface ActionSpec {
41
62
  name: string;
42
63
  /** 动作后面参数的写法;没有参数时为空。 */
@@ -47,6 +68,8 @@ interface ActionSpec {
47
68
  details: readonly string[];
48
69
  /** 帮助里列出字段表:set、unset。 */
49
70
  fields?: boolean;
71
+ /** 前面能写 --scope:`write` 改这一份,`read` 只看这一份。 */
72
+ scoped?: "write" | "read";
50
73
  examples?: readonly string[];
51
74
  }
52
75
 
@@ -58,7 +81,7 @@ const ACTIONS: readonly ActionSpec[] = [
58
81
  description: "现在会不会续跑、规则没写的参数、设置文件",
59
82
  details: [
60
83
  "第一行说现在会不会续跑;正在续跑时下一行是进度",
61
- "下面是规则没写的参数(做法、上限、间隔)和设置文件在哪",
84
+ "下面是规则没写的参数(做法、上限、间隔),以及全局、项目级设置文件在哪",
62
85
  `设置文件有问题时只说有几处,详情用 /${COMMAND} show`,
63
86
  ],
64
87
  },
@@ -67,22 +90,27 @@ const ACTIONS: readonly ActionSpec[] = [
67
90
  args: "",
68
91
  description: "打开",
69
92
  details: ["在设置文件里写 enabled: true", `设置文件有问题时打开了也不续跑:先改好,再 /${COMMAND} reload`],
93
+ scoped: "write",
70
94
  },
71
95
  {
72
96
  name: "off",
73
97
  args: "",
74
98
  description: "关掉",
75
99
  details: ["在设置文件里写 enabled: false", "正在等的续跑立刻打断,计数清零"],
100
+ scoped: "write",
76
101
  },
77
102
  {
78
103
  name: "show",
79
104
  args: "[rules]",
80
105
  description: "各项参数和来源、规则、设置文件里的问题;rules 只看规则",
81
106
  details: [
82
- "每个参数的值,以及它来自设置文件还是内置默认值",
107
+ "每个参数的值,以及它来自全局设置、项目级设置还是内置默认值",
83
108
  "规则按顺序列出,第一条命中的生效;停用的标出来",
84
109
  "设置文件有问题时不列规则,只列问题",
110
+ `写了 ${SCOPE} 时只看那一份设置文件写了什么,不合并、不填默认值`,
85
111
  ],
112
+ scoped: "read",
113
+ examples: [`/${COMMAND} show rules`, `/${COMMAND} ${SCOPE} project show`],
86
114
  },
87
115
  {
88
116
  name: "set",
@@ -94,30 +122,38 @@ const ACTIONS: readonly ActionSpec[] = [
94
122
  `rules 只能在设置文件里手写,改完 /${COMMAND} reload;开关用 /${COMMAND} on、off`,
95
123
  ],
96
124
  fields: true,
125
+ scoped: "write",
97
126
  examples: [
98
127
  `/${COMMAND} set action=resend maxRetries=20 delay=5s,10s,30s`,
99
128
  `/${COMMAND} set prompt="接着做 {error}"`,
129
+ `/${COMMAND} ${SCOPE} project set maxRetries=3`,
100
130
  ],
101
131
  },
102
132
  {
103
133
  name: "unset",
104
134
  args: "字段 …",
105
- description: "去掉参数,退回内置默认值",
106
- details: ["可以一次写几个;有不认识或写了两次的字段就一项都不改", "规则里写的同名字段不受影响"],
135
+ description: "去掉开关或参数,继承下一层",
136
+ details: [
137
+ "可以一次写几个,开关 enabled 也能去掉;有不认识或写了两次的字段就一项都不改",
138
+ "规则里写的同名字段不受影响",
139
+ SCOPE_FALLBACK,
140
+ ],
107
141
  fields: true,
108
- examples: [`/${COMMAND} unset delay maxRetries`],
142
+ scoped: "write",
143
+ examples: [`/${COMMAND} unset delay maxRetries`, `/${COMMAND} ${SCOPE} project unset enabled`],
109
144
  },
110
145
  {
111
146
  name: "reload",
112
147
  args: "",
113
148
  description: "重新读设置文件(手改 rules 之后用)",
114
- details: ["读完显示和 status 一样的状态", "读到关着或有问题的设置时,正在等的续跑立刻打断"],
149
+ details: ["全局、项目级都重读,读完显示和 status 一样的状态", "读到关着或有问题的设置时,正在等的续跑立刻打断"],
115
150
  },
116
151
  {
117
152
  name: "reset",
118
153
  args: "",
119
154
  description: "去掉开关和参数,保留手写的 rules",
120
- details: ["开关回到打开,参数回到内置默认值;rules 和其他手写的内容留着", "正在等的续跑立刻打断,计数清零"],
155
+ details: ["开关和参数都去掉;rules 和其他手写的内容留着", "正在等的续跑立刻打断,计数清零", SCOPE_FALLBACK],
156
+ scoped: "write",
121
157
  },
122
158
  ];
123
159
 
@@ -129,12 +165,12 @@ export function registerCommand(pi: ExtensionAPI, settings: Settings, onward: On
129
165
  getArgumentCompletions: (prefix) => completeArguments(prefix),
130
166
  handler: async (args, ctx) => {
131
167
  let command = parseCommand(args);
132
- if (command.kind === "choose") {
133
- const picked = await choose(ctx, settings);
168
+ // 菜单里选了「--scope <层> …」时接着弹这一份的菜单;这一份的菜单里不再有这种项。
169
+ while (command.kind === "choose") {
170
+ const picked = await choose(ctx, settings, command.scope);
134
171
  if (picked === undefined) return;
135
172
  command = parseCommand(picked);
136
173
  }
137
- if (command.kind === "choose") return;
138
174
  const notice = execute(command, settings, onward, ctx);
139
175
  // 不管是命令关的、还是 reload 读到手改的关或有问题的设置,不生效了就不该还有等着的续跑。
140
176
  if (!isActive(settings.config)) onward.stop(ctx);
@@ -144,14 +180,14 @@ export function registerCommand(pi: ExtensionAPI, settings: Settings, onward: On
144
180
  }
145
181
 
146
182
  /**
147
- * `/onward` 不写动作:弹出菜单,标题是现在的状态。返回选中的动作;要写参数的(set、unset)填进输入框接着写,
148
- * 返回 undefined。没有界面时不弹,什么都不做。
183
+ * `/onward` 不写动作:弹出菜单,标题是现在的状态。返回选中的命令;要写参数的(set、unset)填进输入框接着写,
184
+ * 返回 undefined。写了 `--scope` 时只列改这一份的动作,选中的命令带着它。没有界面时不弹,什么都不做。
149
185
  */
150
- async function choose(ctx: ExtensionContext, settings: Settings): Promise<string | undefined> {
186
+ async function choose(ctx: ExtensionContext, settings: Settings, scope?: Scope): Promise<string | undefined> {
151
187
  if (!ctx.hasUI) return undefined;
152
- const items = menuItems();
188
+ const items = menuItems(scope);
153
189
  const label = await ctx.ui.select(
154
- statusHeadline(settings),
190
+ menuTitle(settings, scope),
155
191
  items.map((item) => item.label),
156
192
  );
157
193
  const picked = items.find((item) => item.label === label);
@@ -160,18 +196,30 @@ async function choose(ctx: ExtensionContext, settings: Settings): Promise<string
160
196
  return undefined;
161
197
  }
162
198
 
163
- /** 每个动作一项,最后是 --help;和帮助里的动作表一样只写名字,参数留给各自动作的帮助。`fill`:参数非写不可。 */
164
- export function menuItems(): { label: string; input: string; fill: boolean }[] {
199
+ /**
200
+ * 每个动作一项,再是进到每一份设置的菜单的 `--scope <层> …`,最后是 --help;和帮助里的动作表一样只写名字,参数留给
201
+ * 各自动作的帮助。`fill`:参数非写不可。写了 `scope` 时是这一份的菜单:只列能写 --scope 的动作,`input` 带上
202
+ * `--scope <scope>`。
203
+ */
204
+ export function menuItems(scope?: Scope): { label: string; input: string; fill: boolean }[] {
205
+ const actions = scope ? ACTIONS.filter((item) => item.scoped) : ACTIONS;
206
+ const layers = scope ? [] : SCOPES;
165
207
  const labels = columns([
166
- ...ACTIONS.map((item): [string, string] => [item.name, item.description]),
208
+ ...actions.map((item): [string, string] => [item.name, item.description]),
209
+ ...layers.map((layer): [string, string] => [`${SCOPE} ${layer} …`, layerMenuText(layer)]),
167
210
  [HELP, "显示帮助"],
168
211
  ]);
169
212
  return [
170
- ...ACTIONS.map((item, index) => ({
213
+ ...actions.map((item, index) => ({
171
214
  label: labels[index]!,
172
- input: item.name,
215
+ input: scope ? `${SCOPE} ${scope} ${item.name}` : item.name,
173
216
  fill: item.args !== "" && !item.args.startsWith("["),
174
217
  })),
218
+ ...layers.map((layer, index) => ({
219
+ label: labels[actions.length + index]!,
220
+ input: `${SCOPE} ${layer}`,
221
+ fill: false,
222
+ })),
175
223
  { label: labels.at(-1)!, input: HELP, fill: false },
176
224
  ];
177
225
  }
@@ -190,57 +238,161 @@ function execute(
190
238
  case "error":
191
239
  return commandErrorNotice(command.message, command.topic);
192
240
  case "show":
241
+ if (command.scope) return layerNotice(settings, command.scope, command.rules);
193
242
  return command.rules ? rulesNotice(settings) : showNotice(settings);
194
243
  case "reload":
195
244
  settings.reload();
196
245
  return statusNotice(settings, onward.progress());
197
246
  case "reset": {
198
247
  onward.stop(ctx);
199
- const saved = settings.reset();
248
+ const saved = settings.reset(command.scope);
200
249
  const kept = saved.kind === "saved" && Array.isArray(saved.value.rules) && saved.value.rules.length > 0;
201
- return changedNotice(
202
- saved,
203
- settings,
204
- onward.progress(),
205
- kept ? "已恢复默认,手写的 rules 保留" : "已恢复默认",
250
+ const done = note(resetLine(settings, command.scope, kept), shadowLine(settings, command.scope, COMMAND_KEYS));
251
+ return changedNotice(saved, settings, onward.progress(), done);
252
+ }
253
+ case "update": {
254
+ const saved = settings.update(command.scope, command.change);
255
+ const done = note(
256
+ scopeLine(settings, command.scope),
257
+ shadowLine(settings, command.scope, changedKeys(command.change)),
206
258
  );
259
+ return changedNotice(saved, settings, onward.progress(), done);
207
260
  }
208
- case "update":
209
- return changedNotice(settings.update(command.change), settings, onward.progress());
210
261
  }
211
262
  }
212
263
 
264
+ /** 跟在标题后面的几行;都没有时是 undefined。 */
265
+ function note(...lines: (string | undefined)[]): string | undefined {
266
+ const kept = lines.filter((line): line is string => line !== undefined);
267
+ return kept.length ? kept.join("\n") : undefined;
268
+ }
269
+
270
+ /** 这次改到的开关和参数。 */
271
+ function changedKeys(change: SettingsChange): string[] {
272
+ return [
273
+ ...(change.enabled === undefined ? [] : ["enabled"]),
274
+ ...Object.keys(change.set ?? {}),
275
+ ...(change.unset ?? []),
276
+ ];
277
+ }
278
+
213
279
  export function parseCommand(text: string): Command {
214
280
  const tokens = tokenize(text);
215
281
  if (typeof tokens === "string") return { kind: "error", message: tokens };
282
+ const { words, at, value, count } = splitScope(tokens);
216
283
  if (tokens.includes(HELP)) {
217
- const [first] = tokens.filter((token) => token !== HELP);
284
+ const [first] = words;
218
285
  if (first === undefined) return { kind: "help" };
219
286
  const spec = actionNamed(first);
220
287
  return spec ? { kind: "help", topic: spec.name } : unknownAction(first);
221
288
  }
222
- const [first, ...rest] = tokens;
223
- if (first === undefined) return { kind: "choose" };
224
- const action = first.toLowerCase();
289
+ const [first, ...rest] = words;
290
+ const spec = first === undefined ? undefined : actionNamed(first);
291
+ const topic = spec && { topic: spec.name };
292
+ if (count > 1) return { kind: "error", message: `${SCOPE} 写了两次`, ...topic };
293
+ const scope = count ? scopeNamed(value) : "global";
294
+ // 先看 --scope 的值:`--scope set …` 是漏写了值,不是动作写错了。
295
+ if (scope === undefined)
296
+ return {
297
+ kind: "error",
298
+ message: `${SCOPE} ${value === undefined ? "后面要写" : "只能是"} ${SCOPES.join(" 或 ")}`,
299
+ ...topic,
300
+ };
301
+ if (first !== undefined && !spec) return unknownAction(first);
302
+ if (count && spec && !spec.scoped) return { kind: "error", message: scopedOnly(), topic: spec.name };
303
+ // --scope 是命令的目标,写在动作前;写在别处不执行,给出正确的写法。
304
+ if (count && at !== 0)
305
+ return {
306
+ kind: "error",
307
+ message: `${SCOPE} 要写在动作前:/${COMMAND} ${[SCOPE, scope, ...words.map(quoted)].join(" ")}`,
308
+ ...topic,
309
+ };
310
+ if (!spec) return count ? { kind: "choose", scope } : { kind: "choose" };
311
+ const action = spec.name;
225
312
  switch (action) {
226
313
  case "status":
227
314
  case "reload":
228
- case "reset":
229
315
  return none(action, rest) ?? { kind: action };
316
+ case "reset":
317
+ return none(action, rest) ?? { kind: "reset", scope };
230
318
  case "on":
231
319
  case "off":
232
- return none(action, rest) ?? { kind: "update", change: { enabled: action === "on" } };
233
- case "show":
234
- if (!rest.length) return { kind: "show", rules: false };
235
- if (rest.length === 1 && rest[0].toLowerCase() === "rules") return { kind: "show", rules: true };
320
+ return none(action, rest) ?? { kind: "update", scope, change: { enabled: action === "on" } };
321
+ case "show": {
322
+ // 不写 --scope 是合并后的结果,不是全局那一份。
323
+ const only = count ? { scope } : {};
324
+ if (!rest.length) return { kind: "show", rules: false, ...only };
325
+ if (rest.length === 1 && rest[0] === "rules") return { kind: "show", rules: true, ...only };
236
326
  return { kind: "error", message: "show 后面只能写 rules", topic: "show" };
327
+ }
237
328
  case "set":
238
- return parseSet(rest);
329
+ return parseSet(rest, scope);
239
330
  case "unset":
240
- return parseUnset(rest);
331
+ return parseUnset(rest, scope);
241
332
  default:
242
- return unknownAction(first);
333
+ return unknownAction(first!);
334
+ }
335
+ }
336
+
337
+ /**
338
+ * 把 `--scope <值>`、`--scope=<值>` 从词里拿出来。`at` 是第一个 `--scope` 前面有几个别的词:
339
+ * 只有 0 是写在动作前;`value` 是它的值,没写时是 undefined;`count` 是写了几次。`-` 开头的词(如 --help)不算它的值。
340
+ */
341
+ function splitScope(tokens: readonly string[]): { words: string[]; at: number; value?: string; count: number } {
342
+ const words: string[] = [];
343
+ let at = -1;
344
+ let value: string | undefined;
345
+ let count = 0;
346
+ for (let i = 0; i < tokens.length; i++) {
347
+ const token = tokens[i]!;
348
+ if (token === HELP) continue;
349
+ const option = scopeOption(token);
350
+ if (!option) {
351
+ words.push(token);
352
+ continue;
353
+ }
354
+ count++;
355
+ let own = option.value;
356
+ const next = tokens[i + 1];
357
+ if (!option.inline && next !== undefined && !next.startsWith("-")) {
358
+ own = next;
359
+ i++;
360
+ }
361
+ if (count === 1) {
362
+ at = words.length;
363
+ value = own || undefined;
364
+ }
243
365
  }
366
+ return { words, at, ...(value !== undefined && { value }), count };
367
+ }
368
+
369
+ /** 这个词是 `--scope` 或 `--scope=<值>` 时:`inline` 是值写在 = 后面(可能是空的)。 */
370
+ function scopeOption(token: string): { inline: boolean; value?: string } | undefined {
371
+ const match = /^--scope(?:=(.*))?$/.exec(token);
372
+ if (!match) return undefined;
373
+ return match[1] === undefined ? { inline: false } : { inline: true, value: match[1] };
374
+ }
375
+
376
+ function scopeNamed(value: string | undefined): Scope | undefined {
377
+ return SCOPES.find((scope) => scope === value);
378
+ }
379
+
380
+ /** 给出正确写法时,含空白的词重新加上引号。 */
381
+ function quoted(word: string): string {
382
+ if (!/\s/.test(word)) return word;
383
+ const equals = word.indexOf("=");
384
+ return equals > 0 ? `${word.slice(0, equals + 1)}"${word.slice(equals + 1)}"` : `"${word}"`;
385
+ }
386
+
387
+ function scopedOnly(): string {
388
+ return `${SCOPE} 只用于 ${scopedActions()}`;
389
+ }
390
+
391
+ /** 能写 --scope 的动作;`write`:只要改设置的。 */
392
+ function scopedActions(only?: "write"): string {
393
+ return ACTIONS.filter((item) => (only ? item.scoped === only : item.scoped))
394
+ .map((item) => item.name)
395
+ .join("、");
244
396
  }
245
397
 
246
398
  function unknownAction(word: string): Command {
@@ -252,7 +404,7 @@ function none(action: string, rest: string[]): Command | undefined {
252
404
  return rest.length ? { kind: "error", message: `${action} 不带参数`, topic: action } : undefined;
253
405
  }
254
406
 
255
- function parseSet(tokens: string[]): Command {
407
+ function parseSet(tokens: string[], scope: Scope): Command {
256
408
  if (!tokens.length)
257
409
  return { kind: "error", message: `set 要写 字段=值;可用 ${FIELD_NAMES.join("、")}`, topic: "set" };
258
410
  const problems: string[] = [];
@@ -265,7 +417,7 @@ function parseSet(tokens: string[]): Command {
265
417
  }
266
418
  const key = token.slice(0, equals);
267
419
  const text = token.slice(equals + 1);
268
- const known = paramField(key);
420
+ const known = paramField(key, scope);
269
421
  if (typeof known === "string") {
270
422
  problems.push(known);
271
423
  continue;
@@ -279,29 +431,39 @@ function parseSet(tokens: string[]): Command {
279
431
  if ("problem" in read) problems.push(`${known.name} ${read.problem}`);
280
432
  else values[known.name] = value;
281
433
  }
282
- return problems.length ? rejected(problems, "set") : { kind: "update", change: { set: values } };
434
+ return problems.length ? rejected(problems, "set") : { kind: "update", scope, change: { set: values } };
283
435
  }
284
436
 
285
- function parseUnset(tokens: string[]): Command {
437
+ /**
438
+ * unset 能去掉的:参数,和开关 enabled。开关有两份设置时也要能去掉:去掉项目级的才继承全局的。
439
+ */
440
+ function parseUnset(tokens: string[], scope: Scope): Command {
286
441
  if (!tokens.length)
287
- return { kind: "error", message: `unset 要写字段名;可用 ${FIELD_NAMES.join("、")}`, topic: "unset" };
442
+ return { kind: "error", message: `unset 要写字段名;可用 ${COMMAND_KEYS.join("、")}`, topic: "unset" };
288
443
  const problems: string[] = [];
289
444
  const unset: string[] = [];
290
445
  for (const token of tokens) {
291
- const known = paramField(token);
292
- if (typeof known === "string") problems.push(known);
293
- else if (unset.includes(known.name)) problems.push(`${known.name} 写了两次`);
294
- else unset.push(known.name);
446
+ const key = unsetKey(token, scope);
447
+ if ("problem" in key) problems.push(key.problem);
448
+ else if (unset.includes(key.name)) problems.push(`${key.name} 写了两次`);
449
+ else unset.push(key.name);
295
450
  }
296
- return problems.length ? rejected(problems, "unset") : { kind: "update", change: { unset } };
451
+ return problems.length ? rejected(problems, "unset") : { kind: "update", scope, change: { unset } };
297
452
  }
298
453
 
299
- /** 参数字段;不是时说明为什么。 */
300
- function paramField(key: string): Field | string {
301
- const lower = key.toLowerCase();
302
- if (lower === "rules") return "rules 要在设置文件里手写,改完 /onward reload";
303
- if (lower === "enabled") return "开关用 /onward on 或 off";
304
- return fieldNamed(key) ?? `不认识的字段 ${key};可用 ${FIELD_NAMES.join("、")}`;
454
+ function unsetKey(token: string, scope: Scope): { name: string } | { problem: string } {
455
+ if (token === "enabled") return { name: "enabled" };
456
+ const known = paramField(token, scope, COMMAND_KEYS);
457
+ return typeof known === "string" ? { problem: known } : { name: known.name };
458
+ }
459
+
460
+ /**
461
+ * 参数字段;不是时说明为什么。开关的提示写同一份的写法。`names` 是这个动作能写的字段,不认识时列出来。
462
+ */
463
+ function paramField(key: string, scope: Scope, names: readonly string[] = FIELD_NAMES): Field | string {
464
+ if (key === "rules") return `rules 要在设置文件里手写,改完 /${COMMAND} reload`;
465
+ if (key === "enabled") return `开关用 /${COMMAND} ${scope === "project" ? `${SCOPE} project ` : ""}on 或 off`;
466
+ return fieldNamed(key) ?? `不认识的字段 ${key};可用 ${names.join("、")}`;
305
467
  }
306
468
 
307
469
  function rejected(problems: string[], topic: string): Command {
@@ -313,8 +475,7 @@ function actionList(): string {
313
475
  }
314
476
 
315
477
  function actionNamed(name: string): ActionSpec | undefined {
316
- const lower = name.toLowerCase();
317
- return ACTIONS.find((item) => item.name === lower);
478
+ return ACTIONS.find((item) => item.name === name);
318
479
  }
319
480
 
320
481
  // ── 帮助 ──
@@ -328,10 +489,12 @@ export function helpText(topic?: string): string {
328
489
  function overallHelp(): string {
329
490
  return [
330
491
  "onward — 出错后按规则自动续跑",
331
- `用法:/${COMMAND} [动作] [参数] [${HELP}]`,
492
+ `用法:/${COMMAND} [${SCOPE} <${SCOPES.join("|")}>] [动作] [参数] [${HELP}]`,
332
493
  ...section("动作", table(ACTIONS.map((item) => [item.name, item.description]))),
333
494
  "",
334
- " 不写动作时弹出菜单,标题是现在的状态",
495
+ ` 不写动作时弹出菜单,标题是现在的状态;菜单里的 ${SCOPE} <层> … 进到只看、只改那一份的菜单`,
496
+ ` ${scopedActions("write")} 改哪一份设置由 ${SCOPE} 定,写在动作前:不写或 global 是全局,project 是当前目录的项目级`,
497
+ ` show 不写 ${SCOPE} 时看合并后的结果,写了只看那一份`,
335
498
  ` 每个动作的用法:/${COMMAND} <动作> ${HELP}(只显示帮助,不执行)`,
336
499
  ` 字段和默认值:/${COMMAND} set ${HELP}`,
337
500
  ].join("\n");
@@ -343,7 +506,7 @@ function actionHelp(spec: ActionSpec): string {
343
506
  `用法:/${COMMAND} ${usage(spec)}`,
344
507
  ...section(
345
508
  "说明",
346
- spec.details.map((line) => ` ${line}`),
509
+ [...spec.details, ...(spec.scoped === "write" ? [SCOPE_HELP] : [])].map((line) => ` ${line}`),
347
510
  ),
348
511
  ...(spec.fields ? section("字段", table(FIELDS.map((item) => [item.name, fieldHelp(item)]))) : []),
349
512
  ...section(
@@ -353,8 +516,10 @@ function actionHelp(spec: ActionSpec): string {
353
516
  ].join("\n");
354
517
  }
355
518
 
519
+ /** 能写 --scope 的动作前面写着 `[--scope <global|project>]`。 */
356
520
  function usage(spec: ActionSpec): string {
357
- return spec.args ? `${spec.name} ${spec.args}` : spec.name;
521
+ const words = [spec.scoped ? `[${SCOPE} <${SCOPES.join("|")}>]` : "", spec.name, spec.args];
522
+ return words.filter(Boolean).join(" ");
358
523
  }
359
524
 
360
525
  /** 作用一行,写法和默认值一行;有固定取值的逐个列出,标出默认的那个。 */
@@ -410,8 +575,8 @@ interface Candidate {
410
575
  }
411
576
 
412
577
  /**
413
- * 补全:动作、show 的 rules、set 和 unset 的字段名、action 的取值,以及每个动作后面的 --help。返回的 value
414
- * 换掉「/onward 」后面的全部文字,正在写的词前面原样保留。
578
+ * 补全:动作前的 --scope 和它的取值、动作、show 的 rules、set 和 unset 的字段名、action 的取值,以及每个动作后面的
579
+ * --help。返回的 value 换掉「/onward 」后面的全部文字,正在写的词前面原样保留。
415
580
  *
416
581
  * 选中的词后面还能接着写时补一个空格,下一下 Tab 补下一层;`字段=` 停在 = 后面写值。写了 --help 就结束了,
417
582
  * 什么都不再给。写完的词不给列表,回车直接执行;写过的字段和引号里的值不补。
@@ -427,9 +592,9 @@ export function completeArguments(prefix: string): { value: string; label: strin
427
592
  // 列宽按这一层的全部候选算,不按过滤后的:边打字边过滤时说明不左右跳。
428
593
  const labels = columns(all.map((item): [string, string] => [item.value, item.description]));
429
594
  const shown = all.flatMap((item, index) =>
430
- item.value.toLowerCase().startsWith(current.toLowerCase()) ? [{ item, label: labels[index]! }] : [],
595
+ item.value.startsWith(current) ? [{ item, label: labels[index]! }] : [],
431
596
  );
432
- if (!shown.length || shown.some(({ item }) => item.value.toLowerCase() === current.toLowerCase())) return null;
597
+ if (!shown.length || shown.some(({ item }) => item.value === current)) return null;
433
598
  const spaced = (item: Candidate) => !item.value.endsWith("=") && candidates([...done, item.value], "").length > 0;
434
599
  return shown.map(({ item, label }) => ({
435
600
  value: `${head}${item.value}${spaced(item) ? " " : ""}`,
@@ -437,17 +602,38 @@ export function completeArguments(prefix: string): { value: string; label: strin
437
602
  }));
438
603
  }
439
604
 
440
- /** `words` 后面能写的词;--help 之后、写错了的地方都是空的。 */
441
- function candidates(words: string[], current: string): Candidate[] {
442
- if (words.includes(HELP)) return [];
443
- const [first, ...rest] = words;
605
+ /**
606
+ * `words` 后面能写的词;--help 之后、写错了的地方都是空的。--scope 只在动作前给:写在别处执行时会被拒绝;写了它之后
607
+ * 只给能写 --scope 的动作。`--scope=<值>` 和 `--scope <值>` 一样看。
608
+ */
609
+ function candidates(typed: string[], current: string): Candidate[] {
610
+ if (typed.includes(HELP)) return [];
611
+ const words = typed.flatMap((word) => {
612
+ const option = scopeOption(word);
613
+ return option ? [SCOPE, ...(option.inline ? [option.value ?? ""] : [])] : [word];
614
+ });
615
+ const at = words.indexOf(SCOPE);
616
+ if (at > 0) return [];
617
+ if (at === 0 && words.length === 1)
618
+ return [
619
+ { value: "global", description: "全局设置;改设置时不写 --scope 就是它" },
620
+ { value: "project", description: "当前目录的项目级设置" },
621
+ ];
622
+ const scoped = at === 0;
623
+ if (scoped && scopeNamed(words[1]) === undefined) return [];
624
+ const [first, ...rest] = scoped ? words.slice(2) : words;
444
625
  if (first === undefined)
445
626
  return [
446
- ...ACTIONS.map((item) => ({ value: item.name, description: item.description })),
627
+ ...(scoped ? [] : [{ value: SCOPE, description: "看或改哪一份设置,写在动作前:global 或 project" }]),
628
+ ...ACTIONS.filter((item) => !scoped || item.scoped).map((item) => ({
629
+ value: item.name,
630
+ description: item.description,
631
+ })),
447
632
  { value: HELP, description: "显示帮助" },
448
633
  ];
449
634
  const spec = actionNamed(first);
450
- const args = spec && argumentCandidates(spec.name, rest, current);
635
+ if (!spec || (scoped && !spec.scoped)) return [];
636
+ const args = argumentCandidates(spec.name, rest, current);
451
637
  return args ? [...args, { value: HELP, description: `显示 ${spec.name} 的帮助,不执行` }] : [];
452
638
  }
453
639
 
@@ -456,7 +642,7 @@ function argumentCandidates(action: string, rest: string[], current: string): Ca
456
642
  switch (action) {
457
643
  case "show":
458
644
  if (!rest.length) return [{ value: "rules", description: "只看规则" }];
459
- return rest.length === 1 && rest[0].toLowerCase() === "rules" ? [] : undefined;
645
+ return rest.length === 1 && rest[0] === "rules" ? [] : undefined;
460
646
  case "set":
461
647
  case "unset":
462
648
  return fieldCandidates(action, rest, current);
@@ -466,10 +652,20 @@ function argumentCandidates(action: string, rest: string[], current: string): Ca
466
652
  }
467
653
 
468
654
  function fieldCandidates(action: string, rest: string[], current: string): Candidate[] | undefined {
655
+ // 前面有执行时会被拒绝的词(不认识的字段、大小写不对的、没写 = 或值的),什么都不给。
656
+ const valid = (word: string) => {
657
+ if (action === "unset") return word === "enabled" || fieldNamed(word) !== undefined;
658
+ const equals = word.indexOf("=");
659
+ return equals > 0 && equals < word.length - 1 && fieldNamed(word.slice(0, equals)) !== undefined;
660
+ };
661
+ if (!rest.every(valid)) return undefined;
469
662
  // 写过的字段不再给:再写一次,执行时会被拒绝。
470
663
  const written = new Set(rest.map((word) => fieldNamed(word.split("=")[0])?.name));
471
664
  const unwritten = FIELDS.filter((item) => !written.has(item.name));
472
- if (action === "unset") return unwritten.map((item) => ({ value: item.name, description: item.description }));
665
+ if (action === "unset") {
666
+ const toggle = rest.includes("enabled") ? [] : [{ value: "enabled", description: "开关:去掉之后继承下一层" }];
667
+ return [...toggle, ...unwritten.map((item) => ({ value: item.name, description: item.description }))];
668
+ }
473
669
  const equals = current.indexOf("=");
474
670
  if (equals < 0)
475
671
  return unwritten.map((item) => ({ value: `${item.name}=`, description: `${item.syntax}:${item.description}` }));