@cobia/pi-onward 0.4.0 → 0.5.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.
@@ -0,0 +1,70 @@
1
+ /** Pi message and command adapters, registered through the same interface as external actions. */
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import type { ActionDefinition } from "./protocol.ts";
4
+
5
+ export const CUSTOM_TYPE = "pi-onward";
6
+ const modes = ["tui", "rpc", "json", "print"] as const;
7
+ export function piActions(pi: Pick<ExtensionAPI, "getCommands" | "sendUserMessage">): ActionDefinition[] {
8
+ return [
9
+ {
10
+ name: "pi.message",
11
+ description: "发送一条消息续跑",
12
+ phase: "boundary",
13
+ modes,
14
+ parameters: {
15
+ type: "object",
16
+ properties: { prompt: { type: "string", pattern: "\\S", maxLength: 4000, default: "继续" } },
17
+ additionalProperties: false,
18
+ },
19
+ execute(params, context) {
20
+ const prompt = String(params.prompt ?? "继续");
21
+ if (prompt.includes("{taskPrompt}") && !context.taskPrompt?.trim())
22
+ return { kind: "failed", message: "No task prompt is available to expand {taskPrompt}" };
23
+ const vars: Record<string, string> = {
24
+ failures: String(context.failures),
25
+ rule: context.rule,
26
+ error: context.failure.text || "空回复",
27
+ taskPrompt: context.taskPrompt ?? "",
28
+ };
29
+ const content = prompt.replace(/\{(failures|rule|error|taskPrompt)\}/g, (_, key: string) => vars[key]!);
30
+ return {
31
+ kind: "continue",
32
+ entries: [
33
+ {
34
+ type: "custom_message",
35
+ customType: CUSTOM_TYPE,
36
+ content,
37
+ display: true,
38
+ details: { rule: context.rule, failures: context.failures, invocationId: context.invocationId },
39
+ },
40
+ ],
41
+ };
42
+ },
43
+ },
44
+ {
45
+ name: "pi.command",
46
+ description: "分派已加载的扩展命令;业务结果未知",
47
+ phase: "settled",
48
+ modes,
49
+ parameters: {
50
+ type: "object",
51
+ required: ["name"],
52
+ additionalProperties: false,
53
+ properties: { name: { type: "string", pattern: "^[^/\\s]+$" }, args: { type: "string" } },
54
+ },
55
+ execute(params, context) {
56
+ if (context.signal.aborted) return { kind: "cancelled", message: "命令分派已取消" };
57
+ const name = String(params.name);
58
+ if (name === "onward" || name.startsWith("onward:"))
59
+ return { kind: "failed", message: "Cannot automatically invoke onward's own control commands" };
60
+ if (!pi.getCommands().some((command) => command.source === "extension" && command.name === name))
61
+ return {
62
+ kind: "failed",
63
+ message: `Extension command /${name} is not loaded; no text was sent to the model`,
64
+ };
65
+ pi.sendUserMessage(`/${name}${params.args ? ` ${params.args}` : ""}`, { expandPromptTemplates: true });
66
+ return { kind: "dispatched", message: `已分派 /${name};完成情况由目标插件报告` };
67
+ },
68
+ },
69
+ ];
70
+ }
@@ -40,7 +40,7 @@ interface Execution {
40
40
  failures: number;
41
41
  minFailures: number;
42
42
  failure: Readonly<FailureSnapshot>;
43
- /** Task input text, kept stable across automatically generated continuation messages. */
43
+ /** Accepted task text, rebuilt from persisted input origins and stable across automatic continuations. */
44
44
  taskPrompt?: string;
45
45
  chain: Readonly<RecoveryChain>;
46
46
  signal: AbortSignal;
@@ -1,4 +1,4 @@
1
- /** 修改默认写全局,查询默认看合并结果;set 先全部校验,--help 不执行修改。 */
1
+ /** 严格解析结构后校验字段;帮助和补全共用校验,配置修改默认写全局。 */
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";
@@ -14,7 +14,6 @@ import {
14
14
  layerNotice,
15
15
  menuTitle,
16
16
  type Notice,
17
- reloadNotice,
18
17
  rulesNotice,
19
18
  SCOPE,
20
19
  say,
@@ -27,7 +26,7 @@ import {
27
26
 
28
27
  export type Command =
29
28
  | { kind: "choose"; scope?: Scope }
30
- | { kind: "status" | "reload" | "actions" }
29
+ | { kind: "status" | "actions" }
31
30
  | { kind: "reset"; scope: Scope }
32
31
  | { kind: "help"; topic?: string }
33
32
  | { kind: "show"; rules: boolean; scope?: Scope }
@@ -46,7 +45,12 @@ const QUIET_HELP: [string, string] = [
46
45
  ].join("\n"),
47
46
  ];
48
47
 
49
- const SCOPE_HELP = `${SCOPE} 写在动作前:不写或 global 改全局设置,project 改 Pi 已信任的当前项目设置;两份在哪见 /${COMMAND} show`;
48
+ const SCOPE_HELP = `${SCOPE} 只接受空格分隔的 global 或 project,最多一次且写在动作前;不写时修改全局,project 只改 Pi 已信任的当前项目;文件位置见 /${COMMAND} show`;
49
+ const PARSING_HELP = [
50
+ "命令只占一行,以空格或 Tab 分隔;不支持引号、转义、缩写或大小写转换",
51
+ `${HELP} 最多一次且必须放在最后;只免除 set/unset 完全未填参数,已填内容仍须合法`,
52
+ "结构错误从左到右报告第一个;结构通过后汇总字段和值错误;帮助和报错不修改配置或恢复状态",
53
+ ];
50
54
  const SCOPE_FALLBACK = "去掉之后继承下一层:项目级的退回全局,全局的退回内置默认值";
51
55
 
52
56
  interface ActionSpec {
@@ -89,7 +93,7 @@ const ACTIONS: readonly ActionSpec[] = [
89
93
  details: [
90
94
  "在设置文件里写 enabled: true",
91
95
  "成功后只确认启用结果和配置范围;当前仍不能续跑时补充原因",
92
- `设置文件有问题时打开了也不续跑:先改好,再 /${COMMAND} reload`,
96
+ "设置文件有问题时打开了也不续跑:先改好,再用 Pi 的 /reload",
93
97
  "启用开关会取消当前恢复并清零,不立即发起恢复",
94
98
  "保存失败时明确提示;本次运行保留配置修改,重新加载或重启后以原文件为准",
95
99
  ],
@@ -117,7 +121,7 @@ const ACTIONS: readonly ActionSpec[] = [
117
121
  "show rules 只显示规则;按顺序列出,第一条命中的生效,停用的标出来",
118
122
  "配置无效时只列具体问题和文件位置,不展示部分参数或规则",
119
123
  `写了 ${SCOPE} 时只看本层显式配置,不合并、不填默认值;未写 rules 与显式空列表不同`,
120
- `手改文件后 /${COMMAND} reload;show 本身不重载、不写配置`,
124
+ "手改文件后使用 Pi 的 /reload;show 本身不重载、不写配置",
121
125
  ],
122
126
  scoped: "read",
123
127
  examples: [`/${COMMAND} show rules`, `/${COMMAND} ${SCOPE} project show`],
@@ -127,12 +131,13 @@ const ACTIONS: readonly ActionSpec[] = [
127
131
  args: "字段=值 …",
128
132
  description: "修改配置参数",
129
133
  details: [
130
- "可以一次写几个:先全部检查,有一项不合法就一项都不改,问题一起说",
134
+ "可以一次写几个字段;结构通过后汇总字段和值错误,有一项不合法就一项都不改",
135
+ "每个参数必须为完整的 字段=值,恰好一个等号、两侧非空;不允许等号两侧加空格或重复字段",
131
136
  "成功后只回显本次修改值和目标范围;项目级覆盖与当前不可用原因另行说明",
132
137
  "修改恢复过程的上限、动作执行时限和全局 quietStartup",
133
138
  "写入失败时本次运行保留配置修改,重新加载或重启后以原文件为准",
134
139
  "修改配置会取消当前恢复过程",
135
- `rules 只能在设置文件里手写,改完 /${COMMAND} reload;开关用 /${COMMAND} on、off`,
140
+ `rules 只能在设置文件里手写,改完使用 Pi 的 /reload;开关用 /${COMMAND} on、off`,
136
141
  ],
137
142
  fields: true,
138
143
  scoped: "write",
@@ -157,16 +162,6 @@ const ACTIONS: readonly ActionSpec[] = [
157
162
  scoped: "write",
158
163
  examples: [`/${COMMAND} unset maxFailures actionTimeout`, `/${COMMAND} ${SCOPE} project unset enabled`],
159
164
  },
160
- {
161
- name: "reload",
162
- args: "",
163
- description: "重新加载配置",
164
- details: [
165
- "丢弃未保存修改,重读配置;项目级仅在绑定且受信任时读取,会话开始前只读全局",
166
- `成功时确认读取范围;配置无效时说明原因摘要,详情见 /${COMMAND} show`,
167
- "重载会取消等待、待执行动作和本轮计数,不主动发起恢复",
168
- ],
169
- },
170
165
  {
171
166
  name: "reset",
172
167
  args: "",
@@ -268,10 +263,6 @@ function execute(
268
263
  case "show":
269
264
  if (command.scope) return layerNotice(settings, command.scope, command.rules);
270
265
  return command.rules ? rulesNotice(settings) : showNotice(settings);
271
- case "reload":
272
- settings.reload();
273
- onward.stop(ctx);
274
- return reloadNotice(settings, status());
275
266
  case "reset": {
276
267
  const saved = settings.reset(command.scope);
277
268
  onward.stop(ctx);
@@ -292,125 +283,135 @@ function execute(
292
283
  }
293
284
 
294
285
  export function parseCommand(text: string): Command {
295
- const tokens = tokenize(text);
296
- if (typeof tokens === "string") return { kind: "error", message: tokens };
297
- const { words, at, value, count } = splitScope(tokens);
298
- if (tokens.includes(HELP)) {
299
- const [first] = words;
300
- if (first === undefined) return { kind: "help" };
301
- const spec = actionNamed(first);
302
- return spec ? { kind: "help", topic: spec.name } : unknownAction(first);
286
+ const parsed = parseStructure(scan(text).words);
287
+ if (parsed.kind === "error") return parsed;
288
+ if (parsed.kind === "scope") return syntaxError(`${SCOPE} requires ${SCOPES.join(" or ")} as its value`);
289
+ return resolveCommand(parsed);
290
+ }
291
+
292
+ type CommandError = Extract<Command, { kind: "error" }>;
293
+ interface CommandInput {
294
+ kind: "input";
295
+ scope?: Scope;
296
+ spec?: ActionSpec;
297
+ args: string[];
298
+ help: boolean;
299
+ }
300
+
301
+ /** 从左到右检查结构;scope 是补全时允许停留的缺值状态。字段语义在结构通过后检查。 */
302
+ function parseStructure(tokens: readonly string[]): CommandInput | { kind: "scope" } | CommandError {
303
+ const input: CommandInput = { kind: "input", args: [], help: false };
304
+ for (let index = 0; index < tokens.length; index++) {
305
+ const token = tokens[index]!;
306
+ const topic = input.spec?.name;
307
+ const problem = tokenProblem(token);
308
+ if (problem) return syntaxError(problem, topic);
309
+ if (token === HELP) {
310
+ if (input.scope && !input.spec) return syntaxError(`${SCOPE} requires an action before ${HELP}`);
311
+ 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
+ );
316
+ input.help = true;
317
+ continue;
318
+ }
319
+ 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);
322
+ const value = tokens[++index];
323
+ if (value === undefined) return { kind: "scope" };
324
+ const invalid = tokenProblem(value);
325
+ if (invalid) return syntaxError(invalid);
326
+ if (value.startsWith("-")) return syntaxError(`${SCOPE} requires ${SCOPES.join(" or ")} as its value`);
327
+ const scope = scopeNamed(value);
328
+ if (!scope) return syntaxError(`${SCOPE} must be ${SCOPES.join(" or ")}`);
329
+ input.scope = scope;
330
+ continue;
331
+ }
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);
335
+ if (!input.spec) {
336
+ const spec = actionNamed(token);
337
+ if (!spec) return unknownAction(token);
338
+ if (input.scope && !spec.scoped)
339
+ return syntaxError(`${SCOPE} is only supported by ${scopedActions()}`, spec.name);
340
+ input.spec = spec;
341
+ continue;
342
+ }
343
+ const shape = argumentProblem(input.spec.name, token, input.args.length);
344
+ if (shape) return syntaxError(shape, topic);
345
+ input.args.push(token);
303
346
  }
304
- const [first, ...rest] = words;
305
- const spec = first === undefined ? undefined : actionNamed(first);
306
- const topic = spec && { topic: spec.name };
307
- if (count > 1) return { kind: "error", message: `${SCOPE} may only be specified once`, ...topic };
308
- const scope = count ? scopeNamed(value) : "global";
309
- // 先看 --scope 的值:`--scope set …` 是漏写了值,不是动作写错了。
310
- if (scope === undefined)
311
- return {
312
- kind: "error",
313
- message: `${SCOPE} ${value === undefined ? "requires" : "must be"} ${SCOPES.join(" or ")}`,
314
- ...topic,
315
- };
316
- if (first !== undefined && !spec) return unknownAction(first);
317
- if (count && spec && !spec.scoped) return { kind: "error", message: scopedOnly(), topic: spec.name };
318
- if (count && at !== 0)
319
- return {
320
- kind: "error",
321
- message: `${SCOPE} must precede the action: /${COMMAND} ${[SCOPE, scope, ...words.map(quoted)].join(" ")}`,
322
- ...topic,
323
- };
324
- if (!spec) return count ? { kind: "choose", scope } : { kind: "choose" };
325
- const action = spec.name;
347
+ return input;
348
+ }
349
+
350
+ function argumentProblem(action: string, token: string, position: number): string | undefined {
326
351
  switch (action) {
327
- case "status":
328
- case "reload":
329
- case "actions":
330
- return none(action, rest) ?? { kind: action };
331
- case "reset":
332
- return none(action, rest) ?? { kind: "reset", scope };
333
- case "on":
334
- case "off":
335
- return none(action, rest) ?? { kind: "update", scope, change: { enabled: action === "on" } };
336
- case "show": {
337
- const only = count ? { scope } : {};
338
- if (!rest.length) return { kind: "show", rules: false, ...only };
339
- if (rest.length === 1 && rest[0] === "rules") return { kind: "show", rules: true, ...only };
340
- return { kind: "error", message: "show only accepts the optional argument 'rules'", topic: "show" };
352
+ case "show":
353
+ return position === 0 && token === "rules" ? undefined : "show only accepts the optional argument 'rules'";
354
+ case "set": {
355
+ const equals = token.indexOf("=");
356
+ return equals > 0 && equals < token.length - 1 && equals === token.lastIndexOf("=")
357
+ ? undefined
358
+ : `'${token}' must be one field=value with exactly one '=' and a non-empty field and value`;
341
359
  }
342
- case "set":
343
- return parseSet(rest, scope);
344
360
  case "unset":
345
- return parseUnset(rest, scope);
361
+ return token.includes("=") ? "unset requires field names without '='" : undefined;
346
362
  default:
347
- return unknownAction(first!);
363
+ return `${action} does not accept arguments`;
348
364
  }
349
365
  }
350
366
 
351
- /** at 是首个 --scope 前的其他词数;只有 0 合法。支持 --scope=x 与 --scope x。 */
352
- function splitScope(tokens: readonly string[]): { words: string[]; at: number; value?: string; count: number } {
353
- const words: string[] = [];
354
- let at = -1;
355
- let value: string | undefined;
356
- let count = 0;
357
- for (let i = 0; i < tokens.length; i++) {
358
- const token = tokens[i]!;
359
- if (token === HELP) continue;
360
- const option = scopeOption(token);
361
- if (!option) {
362
- words.push(token);
363
- continue;
364
- }
365
- count++;
366
- let own = option.value;
367
- const next = tokens[i + 1];
368
- if (!option.inline && next !== undefined && !next.startsWith("-")) {
369
- own = next;
370
- i++;
371
- }
372
- if (count === 1) {
373
- at = words.length;
374
- value = own || undefined;
375
- }
367
+ /** 帮助仅免除空参数列表;已提供字段和值与执行使用同一校验。 */
368
+ function resolveCommand(input: CommandInput): Command {
369
+ const { spec, args, help } = input;
370
+ if (!spec) return help ? { kind: "help" } : { kind: "choose", ...(input.scope && { scope: input.scope }) };
371
+ const scope = input.scope ?? "global";
372
+ let command: Command;
373
+ switch (spec.name) {
374
+ case "set":
375
+ case "unset":
376
+ if (help && !args.length) return { kind: "help", topic: spec.name };
377
+ command = spec.name === "set" ? parseSet(args, scope) : parseUnset(args, scope);
378
+ break;
379
+ case "show":
380
+ command = { kind: "show", rules: args.length > 0, ...(input.scope && { scope: input.scope }) };
381
+ break;
382
+ case "status":
383
+ case "actions":
384
+ command = { kind: spec.name };
385
+ break;
386
+ case "reset":
387
+ command = { kind: "reset", scope };
388
+ break;
389
+ case "on":
390
+ case "off":
391
+ command = { kind: "update", scope, change: { enabled: spec.name === "on" } };
392
+ break;
393
+ default:
394
+ return unknownAction(spec.name);
376
395
  }
377
- return { words, at, ...(value !== undefined && { value }), count };
396
+ return help && command.kind !== "error" ? { kind: "help", topic: spec.name } : command;
378
397
  }
379
398
 
380
- /** inline 区分 --scope 与 --scope=(包括空值)。 */
381
- function scopeOption(token: string): { inline: boolean; value?: string } | undefined {
382
- const match = /^--scope(?:=(.*))?$/.exec(token);
383
- if (!match) return undefined;
384
- return match[1] === undefined ? { inline: false } : { inline: true, value: match[1] };
399
+ function syntaxError(message: string, topic?: string): CommandError {
400
+ return { kind: "error", message, ...(topic && { topic }) };
385
401
  }
386
402
 
387
403
  function scopeNamed(value: string | undefined): Scope | undefined {
388
404
  return SCOPES.find((scope) => scope === value);
389
405
  }
390
406
 
391
- function quoted(word: string): string {
392
- if (!/\s/.test(word)) return word;
393
- const equals = word.indexOf("=");
394
- return equals > 0 ? `${word.slice(0, equals + 1)}"${word.slice(equals + 1)}"` : `"${word}"`;
395
- }
396
-
397
- function scopedOnly(): string {
398
- return `${SCOPE} is only supported by ${scopedActions()}`;
399
- }
400
-
401
407
  function scopedActions(only?: "write"): string {
402
408
  return ACTIONS.filter((item) => (only ? item.scoped === only : item.scoped))
403
409
  .map((item) => item.name)
404
410
  .join(", ");
405
411
  }
406
412
 
407
- function unknownAction(word: string): Command {
408
- return { kind: "error", message: `Unknown action '${word}'; available actions: ${actionList()}` };
409
- }
410
-
411
- /** 拒绝无参动作后多写的参数。 */
412
- function none(action: string, rest: string[]): Command | undefined {
413
- return rest.length ? { kind: "error", message: `${action} does not accept arguments`, topic: action } : undefined;
413
+ function unknownAction(word: string): CommandError {
414
+ return syntaxError(`Unknown action '${word}'; available actions: ${actionList()}`);
414
415
  }
415
416
 
416
417
  function parseSet(tokens: string[], scope: Scope): Command {
@@ -421,19 +422,14 @@ function parseSet(tokens: string[], scope: Scope): Command {
421
422
  topic: "set",
422
423
  };
423
424
  const problems: string[] = [];
425
+ const seen = new Set<string>();
424
426
  const values: Record<string, unknown> = {};
425
427
  for (const token of tokens) {
426
428
  const equals = token.indexOf("=");
427
- if (equals <= 0) {
428
- problems.push(`'${token}' must use field=value`);
429
- continue;
430
- }
431
429
  const key = token.slice(0, equals);
432
430
  const text = token.slice(equals + 1);
433
- if (Object.hasOwn(values, key)) {
434
- problems.push(`${key} may only be specified once`);
435
- continue;
436
- }
431
+ if (seen.has(key)) problems.push(`${key} may only be specified once`);
432
+ seen.add(key);
437
433
  const parsed = key === QUIET ? quietValue(text, scope) : paramValue(key, text, scope);
438
434
  if ("problem" in parsed) problems.push(parsed.problem);
439
435
  else values[parsed.name] = parsed.value;
@@ -471,11 +467,13 @@ function parseUnset(tokens: string[], scope: Scope): Command {
471
467
  topic: "unset",
472
468
  };
473
469
  const problems: string[] = [];
470
+ const seen = new Set<string>();
474
471
  const unset: string[] = [];
475
472
  for (const token of tokens) {
473
+ if (seen.has(token)) problems.push(`${token} may only be specified once`);
474
+ seen.add(token);
476
475
  const key = unsetKey(token, scope);
477
476
  if ("problem" in key) problems.push(key.problem);
478
- else if (unset.includes(key.name)) problems.push(`${key.name} may only be specified once`);
479
477
  else unset.push(key.name);
480
478
  }
481
479
  return problems.length ? rejected(problems, "unset") : { kind: "update", scope, change: { unset } };
@@ -489,7 +487,7 @@ function unsetKey(token: string, scope: Scope): { name: string } | { problem: st
489
487
  }
490
488
 
491
489
  function paramField(key: string, scope: Scope, names: readonly string[] = FIELD_NAMES): Field | string {
492
- if (key === "rules") return `rules must be edited in the settings file; then run /${COMMAND} reload`;
490
+ if (key === "rules") return "rules must be edited in the settings file; then run Pi's /reload";
493
491
  if (key === "enabled")
494
492
  return `use /${COMMAND} ${scope === "project" ? `${SCOPE} project ` : ""}on or off to change enabled`;
495
493
  return fieldNamed(key) ?? `Unknown field '${key}'; available fields: ${names.join(", ")}`;
@@ -517,12 +515,21 @@ export function helpText(topic?: string): string {
517
515
  function overallHelp(): string {
518
516
  return [
519
517
  `${COMMAND} — ${DESCRIPTION}`,
520
- `用法:/${COMMAND} [${SCOPE} <${SCOPES.join("|")}>] [动作] [参数] [${HELP}]`,
518
+ `用法:/${COMMAND}`,
519
+ ` /${COMMAND} ${HELP}`,
520
+ ` /${COMMAND} ${SCOPE} <${SCOPES.join("|")}>`,
521
+ ` /${COMMAND} [${SCOPE} <${SCOPES.join("|")}>] <动作> [参数] [${HELP}]`,
521
522
  ...section("动作", table(ACTIONS.map((item) => [item.name, item.description]))),
522
523
  "",
523
524
  ` 不写动作时弹出菜单,标题区分当前状态和修改目标;菜单里的 ${SCOPE} <层> … 进到只看、只改那一份的菜单`,
524
525
  ` ${scopedActions("write")} 改哪一份设置由 ${SCOPE} 定,写在动作前:不写或 global 是全局,project 是当前目录的项目级`,
525
526
  ` show 不写 ${SCOPE} 时看合并后的结果,写了只看那一份`,
527
+ ` status/actions 不支持 ${SCOPE};${SCOPE} <层> ${HELP} 缺少动作,不能用于查看帮助`,
528
+ " 命令修改配置后立即生效;手改文件后使用 Pi 的 /reload",
529
+ ...section(
530
+ "解析规则",
531
+ PARSING_HELP.map((line) => ` ${line}`),
532
+ ),
526
533
  ` 每个动作的用法:/${COMMAND} <动作> ${HELP}(只显示帮助,不执行)`,
527
534
  ` 字段和默认值:/${COMMAND} set ${HELP}`,
528
535
  ].join("\n");
@@ -534,7 +541,11 @@ function actionHelp(spec: ActionSpec): string {
534
541
  `用法:/${COMMAND} ${usage(spec)}`,
535
542
  ...section(
536
543
  "说明",
537
- [...spec.details, ...(spec.scoped === "write" ? [SCOPE_HELP] : [])].map((line) => ` ${line}`),
544
+ [
545
+ ...spec.details,
546
+ ...PARSING_HELP,
547
+ ...(spec.scoped === "write" ? ["配置修改立即在当前运行中生效,无需 /reload", SCOPE_HELP] : []),
548
+ ].map((line) => ` ${line}`),
538
549
  ),
539
550
  ...(spec.fields
540
551
  ? section(
@@ -554,7 +565,7 @@ function actionHelp(spec: ActionSpec): string {
554
565
  }
555
566
 
556
567
  function usage(spec: ActionSpec): string {
557
- const words = [spec.scoped ? `[${SCOPE} <${SCOPES.join("|")}>]` : "", spec.name, spec.args];
568
+ const words = [spec.scoped ? `[${SCOPE} <${SCOPES.join("|")}>]` : "", spec.name, spec.args, `[${HELP}]`];
558
569
  return words.filter(Boolean).join(" ");
559
570
  }
560
571
 
@@ -564,36 +575,20 @@ function fieldHelp(item: Field): string {
564
575
 
565
576
  // ── 分词 ──
566
577
 
567
- /** 与补全共用分词,未闭合引号只在执行时拒绝。 */
568
- function tokenize(text: string): string[] | string {
569
- const { words, quoted } = scan(text);
570
- return quoted ? "Unmatched double quote" : words;
571
- }
572
-
573
- /** start 为当前词的起点;quoted 表示引号未闭合,补全时允许这种中间状态。 */
574
- function scan(text: string): { words: string[]; start: number; quoted: boolean } {
575
- const words: string[] = [];
576
- let word = "";
577
- let started = false;
578
- let quoted = false;
579
- let start = 0;
580
- for (let i = 0; i < text.length; i++) {
581
- const char = text[i];
582
- if (char === '"') {
583
- quoted = !quoted;
584
- started = true;
585
- } else if (!quoted && /\s/.test(char)) {
586
- if (started) words.push(word);
587
- word = "";
588
- started = false;
589
- start = i + 1;
590
- } else {
591
- word += char;
592
- started = true;
593
- }
594
- }
595
- if (started) words.push(word);
596
- return { words, start, quoted };
578
+ /** 只按空格和 Tab 分词;保留非法字符,由结构解析按 token 顺序报告。 */
579
+ function scan(text: string): { words: string[]; start: number } {
580
+ return {
581
+ words: text.split(/[ \t]+/).filter(Boolean),
582
+ start: Math.max(text.lastIndexOf(" "), text.lastIndexOf("\t")) + 1,
583
+ };
584
+ }
585
+
586
+ function tokenProblem(token: string): string | undefined {
587
+ const invalid = /['"\s\u0085]/u.exec(token)?.[0];
588
+ 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";
597
592
  }
598
593
 
599
594
  // ── 补全 ──
@@ -607,7 +602,7 @@ interface Candidate {
607
602
  export function completeArguments(prefix: string): { value: string; label: string }[] | null {
608
603
  const { words, start } = scan(prefix);
609
604
  const current = prefix.slice(start);
610
- if (current.includes('"')) return null;
605
+ if (tokenProblem(current)) return null;
611
606
  const head = prefix.slice(0, start);
612
607
  const done = current ? words.slice(0, -1) : words;
613
608
  const all = candidates(done, current);
@@ -626,48 +621,33 @@ export function completeArguments(prefix: string): { value: string; label: strin
626
621
  }
627
622
 
628
623
  function candidates(typed: string[], current: string): Candidate[] {
629
- if (typed.includes(HELP)) return [];
630
- const words = typed.flatMap((word) => {
631
- const option = scopeOption(word);
632
- return option ? [SCOPE, ...(option.inline ? [option.value ?? ""] : [])] : [word];
633
- });
634
- const at = words.indexOf(SCOPE);
635
- if (at > 0) return [];
636
- if (at === 0 && words.length === 1)
624
+ const parsed = parseStructure(typed);
625
+ if (parsed.kind === "error") return [];
626
+ if (parsed.kind === "scope")
637
627
  return [
638
628
  { value: "global", description: "全局设置;改设置时不写 --scope 就是它" },
639
629
  { value: "project", description: "当前目录的项目级设置" },
640
630
  ];
641
- const scoped = at === 0;
642
- if (scoped && scopeNamed(words[1]) === undefined) return [];
643
- const [first, ...rest] = scoped ? words.slice(2) : words;
644
- if (first === undefined)
631
+ if (parsed.help) return [];
632
+ const { spec, scope, args } = parsed;
633
+ if (!spec)
645
634
  return [
646
- ...(scoped ? [] : [{ value: SCOPE, description: "指定查看或修改的配置范围" }]),
647
- ...ACTIONS.filter((item) => !scoped || item.scoped).map((item) => ({
635
+ ...(scope ? [] : [{ value: SCOPE, description: "指定查看或修改的配置范围" }]),
636
+ ...ACTIONS.filter((item) => !scope || item.scoped).map((item) => ({
648
637
  value: item.name,
649
638
  description: item.description,
650
639
  })),
651
- { value: HELP, description: "显示帮助" },
640
+ ...(scope ? [] : [{ value: HELP, description: "显示帮助" }]),
652
641
  ];
653
- const spec = actionNamed(first);
654
- if (!spec || (scoped && !spec.scoped)) return [];
655
- const args = argumentCandidates(spec.name, rest, current, scoped ? scopeNamed(words[1])! : "global");
656
- return args ? [...args, { value: HELP, description: `显示 ${spec.name} 的帮助,不执行` }] : [];
657
- }
658
-
659
- /** undefined 表示输入已无效,不再补全 --help。 */
660
- function argumentCandidates(action: string, rest: string[], current: string, scope: Scope): Candidate[] | undefined {
661
- switch (action) {
662
- case "show":
663
- if (!rest.length) return [{ value: "rules", description: "只看规则" }];
664
- return rest.length === 1 && rest[0] === "rules" ? [] : undefined;
665
- case "set":
666
- case "unset":
667
- return fieldCandidates(action, rest, current, scope);
668
- default:
669
- return rest.length ? undefined : [];
670
- }
642
+ // 只豁免尚未填写参数;所有已经结束的 token 都经过实际执行使用的字段校验。
643
+ if (resolveCommand({ ...parsed, help: true }).kind === "error") return [];
644
+ const values =
645
+ spec.name === "set" || spec.name === "unset"
646
+ ? fieldCandidates(spec.name, args, current, scope ?? "global")
647
+ : spec.name === "show" && !args.length
648
+ ? [{ value: "rules", description: "只看规则" }]
649
+ : [];
650
+ return [...values, { value: HELP, description: `显示 ${spec.name} 的帮助,不执行` }];
671
651
  }
672
652
 
673
653
  const QUIET_CHOICES: readonly Candidate[] = [
@@ -675,17 +655,9 @@ const QUIET_CHOICES: readonly Candidate[] = [
675
655
  { value: "false", description: "照常显示,不管 pi 的 quietStartup" },
676
656
  ];
677
657
 
678
- function fieldCandidates(action: string, rest: string[], current: string, scope: Scope): Candidate[] | undefined {
658
+ function fieldCandidates(action: string, rest: string[], current: string, scope: Scope): Candidate[] {
679
659
  // 项目层不提示 quietStartup,但允许手写 unset 来修复误配置。
680
660
  const offered = scope === "global";
681
- const named = (name: string) =>
682
- fieldNamed(name) !== undefined || (name === QUIET && (offered || action === "unset"));
683
- const valid = (word: string) => {
684
- if (action === "unset") return word === "enabled" || named(word);
685
- const equals = word.indexOf("=");
686
- return equals > 0 && equals < word.length - 1 && named(word.slice(0, equals));
687
- };
688
- if (!rest.every(valid)) return undefined;
689
661
  const written = new Set(rest.map((word) => word.split("=")[0]));
690
662
  const unwritten = FIELDS.filter((item) => !written.has(item.name));
691
663
  const quiet = offered && !written.has(QUIET);
@@ -704,8 +676,7 @@ function fieldCandidates(action: string, rest: string[], current: string, scope:
704
676
  ...(quiet ? [{ value: `${QUIET}=`, description: "true 或 false:启动时的提示显示不显示" }] : []),
705
677
  ];
706
678
  const name = current.slice(0, equals);
707
- if (written.has(name)) return undefined;
708
- if (name === QUIET)
709
- return quiet ? QUIET_CHOICES.map((choice) => ({ ...choice, value: `${QUIET}=${choice.value}` })) : undefined;
710
- return fieldNamed(name) ? [] : undefined;
679
+ if (name === QUIET && quiet)
680
+ return QUIET_CHOICES.map((choice) => ({ ...choice, value: `${QUIET}=${choice.value}` }));
681
+ return [];
711
682
  }