@cobia/pi-onward 0.1.2 → 0.3.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,41 +1,75 @@
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
+ quietLine,
30
+ resetLine,
20
31
  rulesNotice,
32
+ SCOPE,
21
33
  say,
34
+ scopeLine,
22
35
  section,
36
+ shadowLine,
23
37
  showNotice,
24
- statusHeadline,
25
38
  statusNotice,
26
39
  table,
27
40
  } from "./text.ts";
28
41
 
29
- /** `topic`:帮助或出错是关于哪个动作的,没有时是总帮助。`choose`:没写动作,弹菜单。 */
42
+ /**
43
+ * `topic`:帮助或出错是关于哪个动作的,没有时是总帮助。`choose`:没写动作,弹菜单;写了 `--scope` 时只列改这一份的。
44
+ * `scope`:改哪一份设置文件。
45
+ */
30
46
  export type Command =
31
- | { kind: "choose" }
32
- | { kind: "status" | "reload" | "reset" }
47
+ | { kind: "choose"; scope?: Scope }
48
+ | { kind: "status" | "reload" }
49
+ | { kind: "reset"; scope: Scope }
33
50
  | { kind: "help"; topic?: string }
34
- | { kind: "show"; rules: boolean }
35
- | { kind: "update"; change: SettingsChange }
51
+ | { kind: "show"; rules: boolean; scope?: Scope }
52
+ | { kind: "update"; scope: Scope; change: SettingsChange }
36
53
  | { kind: "error"; message: string; topic?: string };
37
54
 
38
55
  const HELP = "--help";
56
+ /** 启动提示的开关:不是规则的参数,只能写在全局设置。 */
57
+ const QUIET = "quietStartup";
58
+ /** 帮助的字段表里 quietStartup 那一行。 */
59
+ const QUIET_HELP: [string, string] = [
60
+ QUIET,
61
+ [
62
+ "启动时的提示(用上了项目级设置、没有可用的规则);设置有问题时照样警告。只能写在全局设置",
63
+ "true:不显示",
64
+ "false:照常显示,不管 pi 的 quietStartup",
65
+ "不写:跟着 pi 的 quietStartup(默认)",
66
+ ].join("\n"),
67
+ ];
68
+
69
+ /** 改设置的动作的帮助里都有这一行。不写路径:设置文件放在哪只由 index.ts 决定,实际的路径在 status 里。 */
70
+ const SCOPE_HELP = `${SCOPE} 写在动作前:不写或 global 改全局设置,project 改当前目录的项目级设置;两份在哪见 /${COMMAND} status`;
71
+ /** 去掉参数的动作:去掉之后按什么走。 */
72
+ const SCOPE_FALLBACK = "去掉之后继承下一层:项目级的退回全局,全局的退回内置默认值";
39
73
 
40
74
  interface ActionSpec {
41
75
  name: string;
@@ -47,6 +81,8 @@ interface ActionSpec {
47
81
  details: readonly string[];
48
82
  /** 帮助里列出字段表:set、unset。 */
49
83
  fields?: boolean;
84
+ /** 前面能写 --scope:`write` 改这一份,`read` 只看这一份。 */
85
+ scoped?: "write" | "read";
50
86
  examples?: readonly string[];
51
87
  }
52
88
 
@@ -58,7 +94,7 @@ const ACTIONS: readonly ActionSpec[] = [
58
94
  description: "现在会不会续跑、规则没写的参数、设置文件",
59
95
  details: [
60
96
  "第一行说现在会不会续跑;正在续跑时下一行是进度",
61
- "下面是规则没写的参数(做法、上限、间隔)和设置文件在哪",
97
+ "下面是规则没写的参数(做法、上限、间隔),以及全局、项目级设置文件在哪",
62
98
  `设置文件有问题时只说有几处,详情用 /${COMMAND} show`,
63
99
  ],
64
100
  },
@@ -67,22 +103,27 @@ const ACTIONS: readonly ActionSpec[] = [
67
103
  args: "",
68
104
  description: "打开",
69
105
  details: ["在设置文件里写 enabled: true", `设置文件有问题时打开了也不续跑:先改好,再 /${COMMAND} reload`],
106
+ scoped: "write",
70
107
  },
71
108
  {
72
109
  name: "off",
73
110
  args: "",
74
111
  description: "关掉",
75
112
  details: ["在设置文件里写 enabled: false", "正在等的续跑立刻打断,计数清零"],
113
+ scoped: "write",
76
114
  },
77
115
  {
78
116
  name: "show",
79
117
  args: "[rules]",
80
118
  description: "各项参数和来源、规则、设置文件里的问题;rules 只看规则",
81
119
  details: [
82
- "每个参数的值,以及它来自设置文件还是内置默认值",
120
+ "每个参数的值,以及它来自全局设置、项目级设置还是内置默认值",
83
121
  "规则按顺序列出,第一条命中的生效;停用的标出来",
84
122
  "设置文件有问题时不列规则,只列问题",
123
+ `写了 ${SCOPE} 时只看那一份设置文件写了什么,不合并、不填默认值`,
85
124
  ],
125
+ scoped: "read",
126
+ examples: [`/${COMMAND} show rules`, `/${COMMAND} ${SCOPE} project show`],
86
127
  },
87
128
  {
88
129
  name: "set",
@@ -94,30 +135,42 @@ const ACTIONS: readonly ActionSpec[] = [
94
135
  `rules 只能在设置文件里手写,改完 /${COMMAND} reload;开关用 /${COMMAND} on、off`,
95
136
  ],
96
137
  fields: true,
138
+ scoped: "write",
97
139
  examples: [
98
140
  `/${COMMAND} set action=resend maxRetries=20 delay=5s,10s,30s`,
99
141
  `/${COMMAND} set prompt="接着做 {error}"`,
142
+ `/${COMMAND} ${SCOPE} project set maxRetries=3`,
100
143
  ],
101
144
  },
102
145
  {
103
146
  name: "unset",
104
147
  args: "字段 …",
105
- description: "去掉参数,退回内置默认值",
106
- details: ["可以一次写几个;有不认识或写了两次的字段就一项都不改", "规则里写的同名字段不受影响"],
148
+ description: "去掉开关或参数,继承下一层",
149
+ details: [
150
+ "可以一次写几个,开关 enabled、启动提示 quietStartup 也能去掉;有不认识或写了两次的字段就一项都不改",
151
+ "规则里写的同名字段不受影响",
152
+ SCOPE_FALLBACK,
153
+ ],
107
154
  fields: true,
108
- examples: [`/${COMMAND} unset delay maxRetries`],
155
+ scoped: "write",
156
+ examples: [`/${COMMAND} unset delay maxRetries`, `/${COMMAND} ${SCOPE} project unset enabled`],
109
157
  },
110
158
  {
111
159
  name: "reload",
112
160
  args: "",
113
161
  description: "重新读设置文件(手改 rules 之后用)",
114
- details: ["读完显示和 status 一样的状态", "读到关着或有问题的设置时,正在等的续跑立刻打断"],
162
+ details: ["全局、项目级都重读,读完显示和 status 一样的状态", "读到关着或有问题的设置时,正在等的续跑立刻打断"],
115
163
  },
116
164
  {
117
165
  name: "reset",
118
166
  args: "",
119
167
  description: "去掉开关和参数,保留手写的 rules",
120
- details: ["开关回到打开,参数回到内置默认值;rules 和其他手写的内容留着", "正在等的续跑立刻打断,计数清零"],
168
+ details: [
169
+ "开关、参数和 quietStartup 都去掉;rules 和其他手写的内容留着",
170
+ "正在等的续跑立刻打断,计数清零",
171
+ SCOPE_FALLBACK,
172
+ ],
173
+ scoped: "write",
121
174
  },
122
175
  ];
123
176
 
@@ -129,12 +182,12 @@ export function registerCommand(pi: ExtensionAPI, settings: Settings, onward: On
129
182
  getArgumentCompletions: (prefix) => completeArguments(prefix),
130
183
  handler: async (args, ctx) => {
131
184
  let command = parseCommand(args);
132
- if (command.kind === "choose") {
133
- const picked = await choose(ctx, settings);
185
+ // 菜单里选了「--scope <层> …」时接着弹这一份的菜单;这一份的菜单里不再有这种项。
186
+ while (command.kind === "choose") {
187
+ const picked = await choose(ctx, settings, command.scope);
134
188
  if (picked === undefined) return;
135
189
  command = parseCommand(picked);
136
190
  }
137
- if (command.kind === "choose") return;
138
191
  const notice = execute(command, settings, onward, ctx);
139
192
  // 不管是命令关的、还是 reload 读到手改的关或有问题的设置,不生效了就不该还有等着的续跑。
140
193
  if (!isActive(settings.config)) onward.stop(ctx);
@@ -144,14 +197,14 @@ export function registerCommand(pi: ExtensionAPI, settings: Settings, onward: On
144
197
  }
145
198
 
146
199
  /**
147
- * `/onward` 不写动作:弹出菜单,标题是现在的状态。返回选中的动作;要写参数的(set、unset)填进输入框接着写,
148
- * 返回 undefined。没有界面时不弹,什么都不做。
200
+ * `/onward` 不写动作:弹出菜单,标题是现在的状态。返回选中的命令;要写参数的(set、unset)填进输入框接着写,
201
+ * 返回 undefined。写了 `--scope` 时只列改这一份的动作,选中的命令带着它。没有界面时不弹,什么都不做。
149
202
  */
150
- async function choose(ctx: ExtensionContext, settings: Settings): Promise<string | undefined> {
203
+ async function choose(ctx: ExtensionContext, settings: Settings, scope?: Scope): Promise<string | undefined> {
151
204
  if (!ctx.hasUI) return undefined;
152
- const items = menuItems();
205
+ const items = menuItems(scope);
153
206
  const label = await ctx.ui.select(
154
- statusHeadline(settings),
207
+ menuTitle(settings, scope),
155
208
  items.map((item) => item.label),
156
209
  );
157
210
  const picked = items.find((item) => item.label === label);
@@ -160,18 +213,30 @@ async function choose(ctx: ExtensionContext, settings: Settings): Promise<string
160
213
  return undefined;
161
214
  }
162
215
 
163
- /** 每个动作一项,最后是 --help;和帮助里的动作表一样只写名字,参数留给各自动作的帮助。`fill`:参数非写不可。 */
164
- export function menuItems(): { label: string; input: string; fill: boolean }[] {
216
+ /**
217
+ * 每个动作一项,再是进到每一份设置的菜单的 `--scope <层> …`,最后是 --help;和帮助里的动作表一样只写名字,参数留给
218
+ * 各自动作的帮助。`fill`:参数非写不可。写了 `scope` 时是这一份的菜单:只列能写 --scope 的动作,`input` 带上
219
+ * `--scope <scope>`。
220
+ */
221
+ export function menuItems(scope?: Scope): { label: string; input: string; fill: boolean }[] {
222
+ const actions = scope ? ACTIONS.filter((item) => item.scoped) : ACTIONS;
223
+ const layers = scope ? [] : SCOPES;
165
224
  const labels = columns([
166
- ...ACTIONS.map((item): [string, string] => [item.name, item.description]),
225
+ ...actions.map((item): [string, string] => [item.name, item.description]),
226
+ ...layers.map((layer): [string, string] => [`${SCOPE} ${layer} …`, layerMenuText(layer)]),
167
227
  [HELP, "显示帮助"],
168
228
  ]);
169
229
  return [
170
- ...ACTIONS.map((item, index) => ({
230
+ ...actions.map((item, index) => ({
171
231
  label: labels[index]!,
172
- input: item.name,
232
+ input: scope ? `${SCOPE} ${scope} ${item.name}` : item.name,
173
233
  fill: item.args !== "" && !item.args.startsWith("["),
174
234
  })),
235
+ ...layers.map((layer, index) => ({
236
+ label: labels[actions.length + index]!,
237
+ input: `${SCOPE} ${layer}`,
238
+ fill: false,
239
+ })),
175
240
  { label: labels.at(-1)!, input: HELP, fill: false },
176
241
  ];
177
242
  }
@@ -190,57 +255,163 @@ function execute(
190
255
  case "error":
191
256
  return commandErrorNotice(command.message, command.topic);
192
257
  case "show":
258
+ if (command.scope) return layerNotice(settings, command.scope, command.rules);
193
259
  return command.rules ? rulesNotice(settings) : showNotice(settings);
194
260
  case "reload":
195
261
  settings.reload();
196
262
  return statusNotice(settings, onward.progress());
197
263
  case "reset": {
198
264
  onward.stop(ctx);
199
- const saved = settings.reset();
265
+ const saved = settings.reset(command.scope);
200
266
  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 保留" : "已恢复默认",
267
+ const done = note(resetLine(settings, command.scope, kept), shadowLine(settings, command.scope, COMMAND_KEYS));
268
+ return changedNotice(saved, settings, onward.progress(), done);
269
+ }
270
+ case "update": {
271
+ const saved = settings.update(command.scope, command.change);
272
+ const keys = changedKeys(command.change);
273
+ const done = note(
274
+ scopeLine(settings, command.scope),
275
+ keys.includes(QUIET) ? quietLine(settings.config.quietStartup) : undefined,
276
+ shadowLine(settings, command.scope, keys),
206
277
  );
278
+ return changedNotice(saved, settings, onward.progress(), done);
207
279
  }
208
- case "update":
209
- return changedNotice(settings.update(command.change), settings, onward.progress());
210
280
  }
211
281
  }
212
282
 
283
+ /** 跟在标题后面的几行;都没有时是 undefined。 */
284
+ function note(...lines: (string | undefined)[]): string | undefined {
285
+ const kept = lines.filter((line): line is string => line !== undefined);
286
+ return kept.length ? kept.join("\n") : undefined;
287
+ }
288
+
289
+ /** 这次改到的开关和参数。 */
290
+ function changedKeys(change: SettingsChange): string[] {
291
+ return [
292
+ ...(change.enabled === undefined ? [] : ["enabled"]),
293
+ ...Object.keys(change.set ?? {}),
294
+ ...(change.unset ?? []),
295
+ ];
296
+ }
297
+
213
298
  export function parseCommand(text: string): Command {
214
299
  const tokens = tokenize(text);
215
300
  if (typeof tokens === "string") return { kind: "error", message: tokens };
301
+ const { words, at, value, count } = splitScope(tokens);
216
302
  if (tokens.includes(HELP)) {
217
- const [first] = tokens.filter((token) => token !== HELP);
303
+ const [first] = words;
218
304
  if (first === undefined) return { kind: "help" };
219
305
  const spec = actionNamed(first);
220
306
  return spec ? { kind: "help", topic: spec.name } : unknownAction(first);
221
307
  }
222
- const [first, ...rest] = tokens;
223
- if (first === undefined) return { kind: "choose" };
224
- const action = first.toLowerCase();
308
+ const [first, ...rest] = words;
309
+ const spec = first === undefined ? undefined : actionNamed(first);
310
+ const topic = spec && { topic: spec.name };
311
+ if (count > 1) return { kind: "error", message: `${SCOPE} 写了两次`, ...topic };
312
+ const scope = count ? scopeNamed(value) : "global";
313
+ // 先看 --scope 的值:`--scope set …` 是漏写了值,不是动作写错了。
314
+ if (scope === undefined)
315
+ return {
316
+ kind: "error",
317
+ message: `${SCOPE} ${value === undefined ? "后面要写" : "只能是"} ${SCOPES.join(" 或 ")}`,
318
+ ...topic,
319
+ };
320
+ if (first !== undefined && !spec) return unknownAction(first);
321
+ if (count && spec && !spec.scoped) return { kind: "error", message: scopedOnly(), topic: spec.name };
322
+ // --scope 是命令的目标,写在动作前;写在别处不执行,给出正确的写法。
323
+ if (count && at !== 0)
324
+ return {
325
+ kind: "error",
326
+ message: `${SCOPE} 要写在动作前:/${COMMAND} ${[SCOPE, scope, ...words.map(quoted)].join(" ")}`,
327
+ ...topic,
328
+ };
329
+ if (!spec) return count ? { kind: "choose", scope } : { kind: "choose" };
330
+ const action = spec.name;
225
331
  switch (action) {
226
332
  case "status":
227
333
  case "reload":
228
- case "reset":
229
334
  return none(action, rest) ?? { kind: action };
335
+ case "reset":
336
+ return none(action, rest) ?? { kind: "reset", scope };
230
337
  case "on":
231
338
  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 };
339
+ return none(action, rest) ?? { kind: "update", scope, change: { enabled: action === "on" } };
340
+ case "show": {
341
+ // 不写 --scope 是合并后的结果,不是全局那一份。
342
+ const only = count ? { scope } : {};
343
+ if (!rest.length) return { kind: "show", rules: false, ...only };
344
+ if (rest.length === 1 && rest[0] === "rules") return { kind: "show", rules: true, ...only };
236
345
  return { kind: "error", message: "show 后面只能写 rules", topic: "show" };
346
+ }
237
347
  case "set":
238
- return parseSet(rest);
348
+ return parseSet(rest, scope);
239
349
  case "unset":
240
- return parseUnset(rest);
350
+ return parseUnset(rest, scope);
241
351
  default:
242
- return unknownAction(first);
352
+ return unknownAction(first!);
353
+ }
354
+ }
355
+
356
+ /**
357
+ * 把 `--scope <值>`、`--scope=<值>` 从词里拿出来。`at` 是第一个 `--scope` 前面有几个别的词:
358
+ * 只有 0 是写在动作前;`value` 是它的值,没写时是 undefined;`count` 是写了几次。`-` 开头的词(如 --help)不算它的值。
359
+ */
360
+ function splitScope(tokens: readonly string[]): { words: string[]; at: number; value?: string; count: number } {
361
+ const words: string[] = [];
362
+ let at = -1;
363
+ let value: string | undefined;
364
+ let count = 0;
365
+ for (let i = 0; i < tokens.length; i++) {
366
+ const token = tokens[i]!;
367
+ if (token === HELP) continue;
368
+ const option = scopeOption(token);
369
+ if (!option) {
370
+ words.push(token);
371
+ continue;
372
+ }
373
+ count++;
374
+ let own = option.value;
375
+ const next = tokens[i + 1];
376
+ if (!option.inline && next !== undefined && !next.startsWith("-")) {
377
+ own = next;
378
+ i++;
379
+ }
380
+ if (count === 1) {
381
+ at = words.length;
382
+ value = own || undefined;
383
+ }
243
384
  }
385
+ return { words, at, ...(value !== undefined && { value }), count };
386
+ }
387
+
388
+ /** 这个词是 `--scope` 或 `--scope=<值>` 时:`inline` 是值写在 = 后面(可能是空的)。 */
389
+ function scopeOption(token: string): { inline: boolean; value?: string } | undefined {
390
+ const match = /^--scope(?:=(.*))?$/.exec(token);
391
+ if (!match) return undefined;
392
+ return match[1] === undefined ? { inline: false } : { inline: true, value: match[1] };
393
+ }
394
+
395
+ function scopeNamed(value: string | undefined): Scope | undefined {
396
+ return SCOPES.find((scope) => scope === value);
397
+ }
398
+
399
+ /** 给出正确写法时,含空白的词重新加上引号。 */
400
+ function quoted(word: string): string {
401
+ if (!/\s/.test(word)) return word;
402
+ const equals = word.indexOf("=");
403
+ return equals > 0 ? `${word.slice(0, equals + 1)}"${word.slice(equals + 1)}"` : `"${word}"`;
404
+ }
405
+
406
+ function scopedOnly(): string {
407
+ return `${SCOPE} 只用于 ${scopedActions()}`;
408
+ }
409
+
410
+ /** 能写 --scope 的动作;`write`:只要改设置的。 */
411
+ function scopedActions(only?: "write"): string {
412
+ return ACTIONS.filter((item) => (only ? item.scoped === only : item.scoped))
413
+ .map((item) => item.name)
414
+ .join("、");
244
415
  }
245
416
 
246
417
  function unknownAction(word: string): Command {
@@ -252,9 +423,9 @@ function none(action: string, rest: string[]): Command | undefined {
252
423
  return rest.length ? { kind: "error", message: `${action} 不带参数`, topic: action } : undefined;
253
424
  }
254
425
 
255
- function parseSet(tokens: string[]): Command {
426
+ function parseSet(tokens: string[], scope: Scope): Command {
256
427
  if (!tokens.length)
257
- return { kind: "error", message: `set 要写 字段=值;可用 ${FIELD_NAMES.join("、")}`, topic: "set" };
428
+ return { kind: "error", message: `set 要写 字段=值;可用 ${settable(scope).join("、")}`, topic: "set" };
258
429
  const problems: string[] = [];
259
430
  const values: Record<string, unknown> = {};
260
431
  for (const token of tokens) {
@@ -265,43 +436,70 @@ function parseSet(tokens: string[]): Command {
265
436
  }
266
437
  const key = token.slice(0, equals);
267
438
  const text = token.slice(equals + 1);
268
- const known = paramField(key);
269
- if (typeof known === "string") {
270
- problems.push(known);
271
- continue;
272
- }
273
- if (known.name in values) {
274
- problems.push(`${known.name} 写了两次`);
439
+ if (Object.hasOwn(values, key)) {
440
+ problems.push(`${key} 写了两次`);
275
441
  continue;
276
442
  }
277
- const value = known.fromText(text);
278
- const read = known.read(value);
279
- if ("problem" in read) problems.push(`${known.name} ${read.problem}`);
280
- else values[known.name] = value;
443
+ const parsed = key === QUIET ? quietValue(text, scope) : paramValue(key, text, scope);
444
+ if ("problem" in parsed) problems.push(parsed.problem);
445
+ else values[parsed.name] = parsed.value;
281
446
  }
282
- return problems.length ? rejected(problems, "set") : { kind: "update", change: { set: values } };
447
+ return problems.length ? rejected(problems, "set") : { kind: "update", scope, change: { set: values } };
283
448
  }
284
449
 
285
- function parseUnset(tokens: string[]): Command {
450
+ type Parsed = { name: string; value: unknown } | { problem: string };
451
+
452
+ function paramValue(key: string, text: string, scope: Scope): Parsed {
453
+ const known = paramField(key, scope, settable(scope));
454
+ if (typeof known === "string") return { problem: known };
455
+ const value = known.fromText(text);
456
+ const read = known.read(value);
457
+ return "problem" in read ? { problem: `${known.name} ${read.problem}` } : { name: known.name, value };
458
+ }
459
+
460
+ /** quietStartup 只认 true、false,只能写在全局:项目级的能关掉「用上了项目级设置」这句提醒。 */
461
+ function quietValue(text: string, scope: Scope): Parsed {
462
+ if (scope !== "global") return { problem: `${QUIET} 只能写在全局设置,不写 ${SCOPE} 就是全局` };
463
+ if (text !== "true" && text !== "false") return { problem: `${QUIET} 需要 true 或 false` };
464
+ return { name: QUIET, value: text === "true" };
465
+ }
466
+
467
+ /** set 能写的字段:参数,全局还有 quietStartup。 */
468
+ function settable(scope: Scope): readonly string[] {
469
+ return scope === "global" ? [...FIELD_NAMES, QUIET] : FIELD_NAMES;
470
+ }
471
+
472
+ /**
473
+ * unset 能去掉的:参数,和开关 enabled。开关有两份设置时也要能去掉:去掉项目级的才继承全局的。
474
+ */
475
+ function parseUnset(tokens: string[], scope: Scope): Command {
286
476
  if (!tokens.length)
287
- return { kind: "error", message: `unset 要写字段名;可用 ${FIELD_NAMES.join("、")}`, topic: "unset" };
477
+ return { kind: "error", message: `unset 要写字段名;可用 ${COMMAND_KEYS.join("、")}`, topic: "unset" };
288
478
  const problems: string[] = [];
289
479
  const unset: string[] = [];
290
480
  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);
481
+ const key = unsetKey(token, scope);
482
+ if ("problem" in key) problems.push(key.problem);
483
+ else if (unset.includes(key.name)) problems.push(`${key.name} 写了两次`);
484
+ else unset.push(key.name);
295
485
  }
296
- return problems.length ? rejected(problems, "unset") : { kind: "update", change: { unset } };
486
+ return problems.length ? rejected(problems, "unset") : { kind: "update", scope, change: { unset } };
487
+ }
488
+
489
+ function unsetKey(token: string, scope: Scope): { name: string } | { problem: string } {
490
+ // quietStartup 在哪一份都能去掉:项目级写了它是一处问题,去掉就好了。
491
+ if (token === "enabled" || token === QUIET) return { name: token };
492
+ const known = paramField(token, scope, COMMAND_KEYS);
493
+ return typeof known === "string" ? { problem: known } : { name: known.name };
297
494
  }
298
495
 
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("、")}`;
496
+ /**
497
+ * 参数字段;不是时说明为什么。开关的提示写同一份的写法。`names` 是这个动作能写的字段,不认识时列出来。
498
+ */
499
+ function paramField(key: string, scope: Scope, names: readonly string[] = FIELD_NAMES): Field | string {
500
+ if (key === "rules") return `rules 要在设置文件里手写,改完 /${COMMAND} reload`;
501
+ if (key === "enabled") return `开关用 /${COMMAND} ${scope === "project" ? `${SCOPE} project ` : ""}on 或 off`;
502
+ return fieldNamed(key) ?? `不认识的字段 ${key};可用 ${names.join("、")}`;
305
503
  }
306
504
 
307
505
  function rejected(problems: string[], topic: string): Command {
@@ -313,8 +511,7 @@ function actionList(): string {
313
511
  }
314
512
 
315
513
  function actionNamed(name: string): ActionSpec | undefined {
316
- const lower = name.toLowerCase();
317
- return ACTIONS.find((item) => item.name === lower);
514
+ return ACTIONS.find((item) => item.name === name);
318
515
  }
319
516
 
320
517
  // ── 帮助 ──
@@ -328,10 +525,12 @@ export function helpText(topic?: string): string {
328
525
  function overallHelp(): string {
329
526
  return [
330
527
  "onward — 出错后按规则自动续跑",
331
- `用法:/${COMMAND} [动作] [参数] [${HELP}]`,
528
+ `用法:/${COMMAND} [${SCOPE} <${SCOPES.join("|")}>] [动作] [参数] [${HELP}]`,
332
529
  ...section("动作", table(ACTIONS.map((item) => [item.name, item.description]))),
333
530
  "",
334
- " 不写动作时弹出菜单,标题是现在的状态",
531
+ ` 不写动作时弹出菜单,标题是现在的状态;菜单里的 ${SCOPE} <层> … 进到只看、只改那一份的菜单`,
532
+ ` ${scopedActions("write")} 改哪一份设置由 ${SCOPE} 定,写在动作前:不写或 global 是全局,project 是当前目录的项目级`,
533
+ ` show 不写 ${SCOPE} 时看合并后的结果,写了只看那一份`,
335
534
  ` 每个动作的用法:/${COMMAND} <动作> ${HELP}(只显示帮助,不执行)`,
336
535
  ` 字段和默认值:/${COMMAND} set ${HELP}`,
337
536
  ].join("\n");
@@ -343,9 +542,11 @@ function actionHelp(spec: ActionSpec): string {
343
542
  `用法:/${COMMAND} ${usage(spec)}`,
344
543
  ...section(
345
544
  "说明",
346
- spec.details.map((line) => ` ${line}`),
545
+ [...spec.details, ...(spec.scoped === "write" ? [SCOPE_HELP] : [])].map((line) => ` ${line}`),
347
546
  ),
348
- ...(spec.fields ? section("字段", table(FIELDS.map((item) => [item.name, fieldHelp(item)]))) : []),
547
+ ...(spec.fields
548
+ ? section("字段", table([...FIELDS.map((item): [string, string] => [item.name, fieldHelp(item)]), QUIET_HELP]))
549
+ : []),
349
550
  ...section(
350
551
  "示例",
351
552
  (spec.examples ?? []).map((line) => ` ${line}`),
@@ -353,8 +554,10 @@ function actionHelp(spec: ActionSpec): string {
353
554
  ].join("\n");
354
555
  }
355
556
 
557
+ /** 能写 --scope 的动作前面写着 `[--scope <global|project>]`。 */
356
558
  function usage(spec: ActionSpec): string {
357
- return spec.args ? `${spec.name} ${spec.args}` : spec.name;
559
+ const words = [spec.scoped ? `[${SCOPE} <${SCOPES.join("|")}>]` : "", spec.name, spec.args];
560
+ return words.filter(Boolean).join(" ");
358
561
  }
359
562
 
360
563
  /** 作用一行,写法和默认值一行;有固定取值的逐个列出,标出默认的那个。 */
@@ -410,8 +613,8 @@ interface Candidate {
410
613
  }
411
614
 
412
615
  /**
413
- * 补全:动作、show 的 rules、set 和 unset 的字段名、action 的取值,以及每个动作后面的 --help。返回的 value
414
- * 换掉「/onward 」后面的全部文字,正在写的词前面原样保留。
616
+ * 补全:动作前的 --scope 和它的取值、动作、show 的 rules、set 和 unset 的字段名、action 的取值,以及每个动作后面的
617
+ * --help。返回的 value 换掉「/onward 」后面的全部文字,正在写的词前面原样保留。
415
618
  *
416
619
  * 选中的词后面还能接着写时补一个空格,下一下 Tab 补下一层;`字段=` 停在 = 后面写值。写了 --help 就结束了,
417
620
  * 什么都不再给。写完的词不给列表,回车直接执行;写过的字段和引号里的值不补。
@@ -427,9 +630,9 @@ export function completeArguments(prefix: string): { value: string; label: strin
427
630
  // 列宽按这一层的全部候选算,不按过滤后的:边打字边过滤时说明不左右跳。
428
631
  const labels = columns(all.map((item): [string, string] => [item.value, item.description]));
429
632
  const shown = all.flatMap((item, index) =>
430
- item.value.toLowerCase().startsWith(current.toLowerCase()) ? [{ item, label: labels[index]! }] : [],
633
+ item.value.startsWith(current) ? [{ item, label: labels[index]! }] : [],
431
634
  );
432
- if (!shown.length || shown.some(({ item }) => item.value.toLowerCase() === current.toLowerCase())) return null;
635
+ if (!shown.length || shown.some(({ item }) => item.value === current)) return null;
433
636
  const spaced = (item: Candidate) => !item.value.endsWith("=") && candidates([...done, item.value], "").length > 0;
434
637
  return shown.map(({ item, label }) => ({
435
638
  value: `${head}${item.value}${spaced(item) ? " " : ""}`,
@@ -437,44 +640,97 @@ export function completeArguments(prefix: string): { value: string; label: strin
437
640
  }));
438
641
  }
439
642
 
440
- /** `words` 后面能写的词;--help 之后、写错了的地方都是空的。 */
441
- function candidates(words: string[], current: string): Candidate[] {
442
- if (words.includes(HELP)) return [];
443
- const [first, ...rest] = words;
643
+ /**
644
+ * `words` 后面能写的词;--help 之后、写错了的地方都是空的。--scope 只在动作前给:写在别处执行时会被拒绝;写了它之后
645
+ * 只给能写 --scope 的动作。`--scope=<值>` 和 `--scope <值>` 一样看。
646
+ */
647
+ function candidates(typed: string[], current: string): Candidate[] {
648
+ if (typed.includes(HELP)) return [];
649
+ const words = typed.flatMap((word) => {
650
+ const option = scopeOption(word);
651
+ return option ? [SCOPE, ...(option.inline ? [option.value ?? ""] : [])] : [word];
652
+ });
653
+ const at = words.indexOf(SCOPE);
654
+ if (at > 0) return [];
655
+ if (at === 0 && words.length === 1)
656
+ return [
657
+ { value: "global", description: "全局设置;改设置时不写 --scope 就是它" },
658
+ { value: "project", description: "当前目录的项目级设置" },
659
+ ];
660
+ const scoped = at === 0;
661
+ if (scoped && scopeNamed(words[1]) === undefined) return [];
662
+ const [first, ...rest] = scoped ? words.slice(2) : words;
444
663
  if (first === undefined)
445
664
  return [
446
- ...ACTIONS.map((item) => ({ value: item.name, description: item.description })),
665
+ ...(scoped ? [] : [{ value: SCOPE, description: "看或改哪一份设置,写在动作前:global 或 project" }]),
666
+ ...ACTIONS.filter((item) => !scoped || item.scoped).map((item) => ({
667
+ value: item.name,
668
+ description: item.description,
669
+ })),
447
670
  { value: HELP, description: "显示帮助" },
448
671
  ];
449
672
  const spec = actionNamed(first);
450
- const args = spec && argumentCandidates(spec.name, rest, current);
673
+ if (!spec || (scoped && !spec.scoped)) return [];
674
+ const args = argumentCandidates(spec.name, rest, current, scoped ? scopeNamed(words[1])! : "global");
451
675
  return args ? [...args, { value: HELP, description: `显示 ${spec.name} 的帮助,不执行` }] : [];
452
676
  }
453
677
 
454
678
  /** 动作后面的参数;`undefined`:这里已经写错了,执行时会被拒绝,--help 也不给。 */
455
- function argumentCandidates(action: string, rest: string[], current: string): Candidate[] | undefined {
679
+ function argumentCandidates(action: string, rest: string[], current: string, scope: Scope): Candidate[] | undefined {
456
680
  switch (action) {
457
681
  case "show":
458
682
  if (!rest.length) return [{ value: "rules", description: "只看规则" }];
459
- return rest.length === 1 && rest[0].toLowerCase() === "rules" ? [] : undefined;
683
+ return rest.length === 1 && rest[0] === "rules" ? [] : undefined;
460
684
  case "set":
461
685
  case "unset":
462
- return fieldCandidates(action, rest, current);
686
+ return fieldCandidates(action, rest, current, scope);
463
687
  default:
464
688
  return rest.length ? undefined : [];
465
689
  }
466
690
  }
467
691
 
468
- function fieldCandidates(action: string, rest: string[], current: string): Candidate[] | undefined {
692
+ /** quietStartup= 后面能写的。 */
693
+ const QUIET_CHOICES: readonly Candidate[] = [
694
+ { value: "true", description: "启动时不显示 onward 的提示;设置有问题时照样警告" },
695
+ { value: "false", description: "照常显示,不管 pi 的 quietStartup" },
696
+ ];
697
+
698
+ function fieldCandidates(action: string, rest: string[], current: string, scope: Scope): Candidate[] | undefined {
699
+ // quietStartup 只能写在全局:项目级的 set 不收它,也不给;unset 哪一份都收,项目级的不给。
700
+ const offered = scope === "global";
701
+ const named = (name: string) =>
702
+ fieldNamed(name) !== undefined || (name === QUIET && (offered || action === "unset"));
703
+ // 前面有执行时会被拒绝的词(不认识的字段、大小写不对的、没写 = 或值的),什么都不给。
704
+ const valid = (word: string) => {
705
+ if (action === "unset") return word === "enabled" || named(word);
706
+ const equals = word.indexOf("=");
707
+ return equals > 0 && equals < word.length - 1 && named(word.slice(0, equals));
708
+ };
709
+ if (!rest.every(valid)) return undefined;
469
710
  // 写过的字段不再给:再写一次,执行时会被拒绝。
470
- const written = new Set(rest.map((word) => fieldNamed(word.split("=")[0])?.name));
711
+ const written = new Set(rest.map((word) => word.split("=")[0]));
471
712
  const unwritten = FIELDS.filter((item) => !written.has(item.name));
472
- if (action === "unset") return unwritten.map((item) => ({ value: item.name, description: item.description }));
713
+ const quiet = offered && !written.has(QUIET);
714
+ if (action === "unset") {
715
+ const toggle = written.has("enabled") ? [] : [{ value: "enabled", description: "开关:去掉之后继承下一层" }];
716
+ return [
717
+ ...toggle,
718
+ ...unwritten.map((item) => ({ value: item.name, description: item.description })),
719
+ ...(quiet ? [{ value: QUIET, description: "启动提示:去掉之后跟着 pi 的 quietStartup" }] : []),
720
+ ];
721
+ }
473
722
  const equals = current.indexOf("=");
474
723
  if (equals < 0)
475
- return unwritten.map((item) => ({ value: `${item.name}=`, description: `${item.syntax}:${item.description}` }));
476
- const known = fieldNamed(current.slice(0, equals));
477
- if (!known || written.has(known.name)) return undefined;
724
+ return [
725
+ ...unwritten.map((item) => ({ value: `${item.name}=`, description: `${item.syntax}:${item.description}` })),
726
+ ...(quiet ? [{ value: `${QUIET}=`, description: "true 或 false:启动时的提示显示不显示" }] : []),
727
+ ];
728
+ const name = current.slice(0, equals);
729
+ if (written.has(name)) return undefined;
730
+ if (name === QUIET)
731
+ return quiet ? QUIET_CHOICES.map((choice) => ({ ...choice, value: `${QUIET}=${choice.value}` })) : undefined;
732
+ const known = fieldNamed(name);
733
+ if (!known) return undefined;
478
734
  return (known.choices ?? []).map((choice) => ({
479
735
  value: `${known.name}=${choice.value}`,
480
736
  description: choice.description,