@cobia/pi-onward 0.3.1 → 0.4.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,81 +1,25 @@
1
- /**
2
- * 给用户看的通知、状态栏和设置说明;命令的用法在 command.ts,和命令的写法放在一起。
3
- *
4
- * pi 把 info 通知画成暗色、warning 画成黄色并加上「Warning:」,所以颜色只分轻重;状态靠开头的图标看:
5
- * ⏩ 在管(开着、有规则,或正在续跑),💤 不会续跑(关了、没有规则),🛑 停了或要先修。三个图标都占两格,
6
- * 后面的字始终在同一列。
7
- *
8
- * 续跑和停手时状态栏写状态(图标、第几次、哪条规则);会话里的提示只补状态栏没有的:续跑说接下来做什么,
9
- * 停手说为什么、怎么办,不重复图标、次数和规则名。错误本身 pi 已经在上面用红字显示,提示里也不再摘。
10
- */
1
+ /** UI-only descriptions. Model-visible text is produced solely by action implementations. */
11
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
- import { type Config, configWarnings, type Hit } from "../policy/config.ts";
13
- import { formatDelay, retryDelay, totalDelay } from "../policy/delay.ts";
14
- import { EMPTY_REPLY, errorSignature, type Failure } from "../policy/failure.ts";
15
- import { DEFAULT_POLICY, FIELDS, type Field, type Policy, type PolicyPatch, resolvePolicy } from "../policy/policy.ts";
3
+ import type { ActionDefinition } from "../actions/protocol.ts";
4
+ import { type Config, configWarnings } from "../policy/config.ts";
5
+ import { delayText } from "../policy/delay.ts";
6
+ import { FIELDS, fieldNamed, type LimitsPatch, resolveLimits } from "../policy/policy.ts";
16
7
  import type { Rule } from "../policy/rules.ts";
17
- import type { GiveUp, Progress, Retry } from "../policy/tracker.ts";
18
- import { isRecord } from "../util.ts";
19
- import type { Continue } from "./onward.ts";
8
+ import type { OnwardStatus, RunState } from "../runtime/recovery.ts";
20
9
  import type { Saved, Scope, Settings, SettingsFile } from "./settings.ts";
21
10
 
22
11
  export const COMMAND = "onward";
23
- /** 改设置的命令改哪一份:写在动作前,`--scope project <动作>`;不写就是全局。 */
24
12
  export const SCOPE = "--scope";
25
-
26
13
  export interface Notice {
27
14
  message: string;
28
15
  level: "info" | "warning";
29
16
  }
30
-
31
- /** 没有界面时(`pi -p`)不提示;RPC 下 pi 把它发给客户端,显不显示由客户端定。 */
32
- export function say(ctx: Pick<ExtensionContext, "hasUI" | "ui">, notice: Notice): void {
33
- if (ctx.hasUI) ctx.ui.notify(notice.message, notice.level);
34
- }
35
-
36
17
  export const info = (message: string): Notice => ({ message, level: "info" });
37
18
  const warning = (message: string): Notice => ({ message, level: "warning" });
38
-
39
- const RUNNING = "⏩";
40
- const IDLE = "💤";
41
- const STOPPED = "🛑";
42
-
43
- const UNTIL_FIXED = "修好之前不会自动续跑";
44
- const addRules = () => `在设置文件的 rules 里写规则(常见规则见 README),再 /${COMMAND} reload`;
45
- const SEE_SHOW = `/${COMMAND} show 查看`;
46
-
47
- /** 两份设置文件给人看的名字:表格、来源和问题前面都用它。 */
48
- const SCOPE_NAMES: Readonly<Record<Scope, string>> = { global: "全局", project: "项目级" };
49
-
50
- // ── 排版 ──
51
-
52
- /** 帮助和状态里的表:行首空两格,名字一列、内容一列,按终端里的宽度对齐;内容的后几行对齐在第一行下面。 */
53
- export function table(rows: [name: string, text: string][]): string[] {
54
- const width = Math.max(0, ...rows.map(([name]) => cells(name)));
55
- return rows.flatMap(([name, text]) => {
56
- const [first, ...more] = text.split("\n");
57
- return [
58
- ` ${name}${" ".repeat(width - cells(name))} ${first}`,
59
- ...more.map((line) => ` ${" ".repeat(width)} ${line}`),
60
- ];
61
- });
62
- }
63
-
64
- /**
65
- * 菜单和补全的每一项:名字一列、说明一列,按终端里的宽度对齐。说明里的换行换成空格,所以一项正好一行,
66
- * 返回的第几行就是第几项,调用方按下标取回。
67
- */
68
- export function columns(rows: [name: string, text: string][]): string[] {
69
- const width = Math.max(0, ...rows.map(([name]) => cells(name)));
70
- return rows.map(([name, text]) => `${name}${" ".repeat(width - cells(name))} ${text.replace(/\s*\n\s*/g, " ")}`);
71
- }
72
-
73
- /** 有内容才出这一节,前面空一行。 */
74
- export function section(title: string, lines: string[]): string[] {
75
- return lines.length ? ["", title, ...lines] : [];
19
+ const NAMES = { global: "全局", project: "项目级" } as const;
20
+ export function say(ctx: Pick<ExtensionContext, "hasUI" | "ui">, notice: Notice): void {
21
+ if (ctx.hasUI) ctx.ui.notify(notice.message, notice.level);
76
22
  }
77
-
78
- /** 终端里占几格:中文和全角字符占两格。 */
79
23
  export function cells(text: string): number {
80
24
  return [...text].reduce(
81
25
  (sum, char) =>
@@ -83,408 +27,335 @@ export function cells(text: string): number {
83
27
  0,
84
28
  );
85
29
  }
86
-
87
- // ── /onward ──
88
-
89
- /** `topic`:出错的动作,用法指到它自己的帮助。 */
90
- export function commandErrorNotice(message: string, topic?: string): Notice {
91
- return warning(`onward:${message};用法见 /${COMMAND}${topic ? ` ${topic}` : ""} --help`);
92
- }
93
-
94
- /** 菜单标题区分运行状态与修改目标;默认菜单只说修改默认写全局,不把查看合并结果也标成全局。 */
95
- export function menuTitle(settings: Settings, scope?: Scope): string {
96
- const target = scope ? `${SCOPE_NAMES[scope]}设置` : `修改默认写入:${SCOPE_NAMES.global}设置`;
97
- return `${statusHeadline(settings)} · ${target}`;
30
+ export function table(rows: [string, string][]): string[] {
31
+ const width = Math.max(0, ...rows.map(([key]) => cells(key)));
32
+ return rows.flatMap(([key, value]) => {
33
+ const [first, ...rest] = value.split("\n");
34
+ return [
35
+ ` ${key}${" ".repeat(width - cells(key))} ${first}`,
36
+ ...rest.map((line) => ` ${" ".repeat(width)} ${line}`),
37
+ ];
38
+ });
98
39
  }
99
-
100
- /** `/onward` 菜单里进到这一份的菜单的那一项的说明。 */
101
- export function layerMenuText(scope: Scope): string {
102
- return `只看、只改${SCOPE_NAMES[scope]}设置`;
40
+ export function columns(rows: [string, string][]): string[] {
41
+ const width = Math.max(0, ...rows.map(([key]) => cells(key)));
42
+ return rows.map(([key, value]) => `${key}${" ".repeat(width - cells(key))} ${value.replace(/\s*\n\s*/g, " ")}`);
103
43
  }
104
-
105
- /** 一行说清现在会不会续跑:`/onward status` 的第一行,也是 `/onward` 菜单标题里的状态部分。 */
106
- export function statusHeadline(settings: Settings): string {
107
- const { config } = settings;
108
- if (brokenFiles(settings).length) return `${STOPPED} onward:设置文件读不了,${UNTIL_FIXED}`;
109
- const problems = config.problems.length;
110
- if (problems && !config.enabled) return `${STOPPED} onward:关;设置文件有 ${problems} 处问题,打开前要先修好`;
111
- if (problems) return `${STOPPED} onward:开,但设置文件有 ${problems} 处问题,${UNTIL_FIXED}`;
112
- if (!config.enabled) return `${IDLE} onward:关,出错时不会自动续跑`;
113
- const usable = usableRules(config);
114
- return usable
115
- ? `${RUNNING} onward:开,${usable} 条规则生效`
116
- : `${IDLE} onward:开,但没有可用的规则,出错时不会自动续跑`;
44
+ export function section(title: string, lines: string[]): string[] {
45
+ return lines.length ? ["", title, ...lines] : [];
117
46
  }
118
-
119
- export function statusNotice(settings: Settings, progress: Progress, note?: string): Notice {
120
- return settingsNotice(settings, statusText(settings, progress, note));
47
+ export function commandErrorNotice(message: string, topic?: string): Notice {
48
+ return warning(`onward: ${message}; see /onward${topic ? ` ${topic}` : ""} --help for usage`);
49
+ }
50
+ export const layerMenuText = (scope: Scope): string => `只看、只改${NAMES[scope]}设置`;
51
+ export function menuTitle(settings: Settings, scope?: Scope, state?: RunState): string {
52
+ return `${statusHeadline(settings, state)} · ${scope ? `${NAMES[scope]}设置` : "修改默认写入:全局设置"}`;
53
+ }
54
+ const PHASES: Record<RunState["phase"], string> = {
55
+ idle: "待命",
56
+ waiting: "等待执行",
57
+ submitted: "提议已提交,等待启动",
58
+ retrying: "续跑中",
59
+ queued: "待执行",
60
+ executing: "执行中",
61
+ stopped: "已停止",
62
+ };
63
+ const RESULTS: Record<string, string> = {
64
+ completed: "已完成",
65
+ dispatched: "已分派,业务结果未知",
66
+ handoff: "已接管",
67
+ stopped: "规则停止",
68
+ failed: "执行失败",
69
+ cancelled: "已取消",
70
+ unknown: "结果未知",
71
+ };
72
+ function usable(config: Config): number {
73
+ return config.rules.filter((rule) => rule.enabled).length;
121
74
  }
122
-
123
- /**
124
- * `/onward status`:标题一行,正在续跑时下一行是进度;再是规则没写的参数和设置文件,最后一行是下一步。
125
- * `note` 是刚做完的事,跟在标题后面。
126
- */
127
- function statusText(settings: Settings, { used, streak }: Progress, note?: string): string {
128
- const { config } = settings;
129
- const lines = [statusHeadline(settings), ...(note ? [note] : [])];
130
- if (used || streak) lines.push(`上次正常返回之后已续跑 ${used} 次,同一个错误连续 ${streak} 次`);
131
- // 读不了的文件也记成一处问题,所以这里不用另外看。
132
- const usable = !config.problems.length;
133
- if (usable) lines.push(...section("规则没写的参数", table(policyRows(resolvePolicy(config.defaults)))));
134
- const reminders = ruleWarningSummary(config);
135
- if (reminders) lines.push("", `${reminders}(${SEE_SHOW})`);
136
- lines.push(...section("设置文件", table(fileRows(settings.files))), "");
137
- if (!usable) lines.push(`改好之后 /${COMMAND} reload;问题见 /${COMMAND} show`);
138
- else if (!config.enabled)
139
- lines.push(`/${COMMAND} ${settings.origin("enabled") === "project" ? `${SCOPE} project ` : ""}on 打开`);
140
- else if (!usableRules(config)) lines.push(addRules());
141
- else lines.push(`规则见 /${COMMAND} show rules`);
142
- return lines.join("\n");
75
+ export function statusHeadline(settings: Settings, state?: RunState): string {
76
+ const config = settings.config;
77
+ if (config.problems.length) return "🛑 onward:配置无效,修好之前不会自动恢复";
78
+ if (!config.enabled) return "💤 onward:关,出错时不会自动恢复";
79
+ if (state && state.phase !== "idle")
80
+ return `${state.phase === "stopped" ? "🛑" : "⏩"} onward:${state.result ? RESULTS[state.result] : PHASES[state.phase]}`;
81
+ return usable(config) ? `⏩ onward:开,${usable(config)} 条规则生效` : "💤 onward:开,但没有可用的规则";
82
+ }
83
+ export function statusNotice(settings: Settings, status: OnwardStatus): Notice {
84
+ const config = settings.config;
85
+ const { state } = status;
86
+ const rows: [string, string][] = [
87
+ ["自动恢复", config.enabled ? "已启用" : "已停用"],
88
+ [
89
+ "当前状态",
90
+ config.problems.length
91
+ ? "配置无效"
92
+ : !config.enabled
93
+ ? "未在恢复"
94
+ : state.phase === "idle" && !usable(config)
95
+ ? "无可用规则"
96
+ : PHASES[state.phase],
97
+ ],
98
+ ];
99
+ if (config.problems.length) rows.push(["配置问题", `${config.problems.length} 处,/onward show 查看详情`]);
100
+ else {
101
+ if (state.phase === "idle") rows.push(["可用规则", `${usable(config)} 条`]);
102
+ if (state.hit)
103
+ rows.push(
104
+ ["命中规则", state.hit.rule.name],
105
+ ["恢复阶段", `从第 ${state.hit.stage.minFailures} 次失败开始`],
106
+ ["动作", state.hit.stage.action.use],
107
+ );
108
+ if (status.failures) rows.push(["连续失败", `${status.failures} 次`]);
109
+ if (status.started) rows.push(["已启动续跑", `${status.started} 次`]);
110
+ if (status.handoffs) rows.push(["跨会话接管", `${status.handoffs} 次`]);
111
+ if (state.result) rows.push(["动作结果", RESULTS[state.result] ?? state.result]);
112
+ if (state.message) rows.push(["说明", state.message]);
113
+ }
114
+ const lines = [COMMAND, ...table(rows)];
115
+ const attention = state.phase === "stopped" && !["completed", "dispatched", "handoff"].includes(state.result ?? "");
116
+ if (state.phase === "stopped") {
117
+ const hint =
118
+ state.result === "dispatched"
119
+ ? "后续执行与结果由目标插件负责;onward 不会自动重放命令。"
120
+ : state.result === "handoff"
121
+ ? "后续恢复由动作提供者负责。"
122
+ : state.result === "completed"
123
+ ? "本次动作已完成;没有自动追加模型请求。"
124
+ : "处理原因后发消息开启新一轮;未自动重放动作。";
125
+ lines.push("", hint);
126
+ }
127
+ return attention || config.problems.length ? warning(lines.join("\n")) : info(lines.join("\n"));
128
+ }
129
+ export function actionsNotice(actions: readonly ActionDefinition[], diagnostics: readonly string[]): Notice {
130
+ const text = [
131
+ "onward 动作",
132
+ ...table(
133
+ actions.map((action) => [
134
+ action.name,
135
+ `${action.description}(${action.phase};${action.modes.join(" / ")})`,
136
+ ]),
137
+ ),
138
+ ...section(
139
+ "动作注册问题",
140
+ diagnostics.map((message) => `- ${message}`),
141
+ ),
142
+ ].join("\n");
143
+ return diagnostics.length ? warning(text) : info(text);
143
144
  }
144
145
 
145
- /** 每份设置文件一行:哪一份、在哪、能不能读。 */
146
146
  function fileRows(files: readonly SettingsFile[]): [string, string][] {
147
- return files.map((file) => [SCOPE_NAMES[file.scope], fileState(file)]);
148
- }
149
-
150
- function fileState({ scope, path, source }: SettingsFile): string {
151
- switch (source.kind) {
152
- case "file":
153
- return path;
154
- case "none":
155
- return `${path}(还没有,${scope === "global" ? "改设置时自动建" : `改设置时写 ${SCOPE} project 自动建`})`;
156
- case "broken":
157
- return `${path}\n读不了:${source.error}`;
158
- }
147
+ const sources = { file: "", none: "(未创建)", broken: "(无法读取)", untrusted: "(未受信任,未读取)" };
148
+ return files.map((file) => [
149
+ NAMES[file.scope],
150
+ `${file.path}${sources[file.source.kind]}${file.unsaved.length ? `(未保存:${file.unsaved.join("、")})` : ""}`,
151
+ ]);
152
+ }
153
+ function showProblems(settings: Settings): Notice {
154
+ return warning(
155
+ [
156
+ "onward 配置无效,修好之前不会自动恢复。",
157
+ ...settings.config.problems.map((problem) => `- ${problem}`),
158
+ ...section("配置文件", table(fileRows(settings.files))),
159
+ "",
160
+ "修复后 /onward reload;加载插件使用 Pi 的 /reload。",
161
+ ].join("\n"),
162
+ );
159
163
  }
160
-
161
- type BrokenFile = SettingsFile & { source: { kind: "broken" } };
162
-
163
- function brokenFiles(settings: Settings): BrokenFile[] {
164
- return settings.files.filter((file): file is BrokenFile => file.source.kind === "broken");
164
+ function effective(settings: Settings, key: string): string {
165
+ const { config } = settings;
166
+ if (key === "quietStartup" && config.quietStartup === undefined) return "跟随 Pi(未配置)";
167
+ const value =
168
+ key === "enabled" || key === "quietStartup" ? String(config[key]) : shown(key, resolveLimits(config.limits));
169
+ const origin = settings.origin(key);
170
+ const source = origin
171
+ ? `${NAMES[origin]}配置${settings.file(origin)!.unsaved.includes(key) ? ",未保存" : ""}`
172
+ : "内置默认值";
173
+ return `${value}(${source})`;
174
+ }
175
+ function shown(key: string, values: LimitsPatch): string {
176
+ const field = fieldNamed(key)!;
177
+ return field.show(values[field.name]!);
165
178
  }
166
-
167
- /** `/onward show`:每个参数的值和它从哪来,再是规则,最后是设置文件。 */
168
179
  export function showNotice(settings: Settings): Notice {
169
- if (brokenFiles(settings).length) return rulesNotice(settings);
170
- const { defaults } = settings.config;
171
- const rows = FIELDS.map((item): [string, string] => {
172
- const from = settings.origin(item.name);
173
- const value = (from ? defaults : DEFAULT_POLICY)[item.name] as never;
174
- const where = from ? `${SCOPE_NAMES[from]}设置` : "内置默认值";
175
- return [item.name, `${(item as Field<typeof item.name>).show(value)}(${where})`];
176
- });
177
- return settingsNotice(
178
- settings,
180
+ if (settings.config.problems.length) return showProblems(settings);
181
+ return info(
179
182
  [
180
- "规则没写的参数",
181
- ...table(rows),
183
+ "onward 配置(合并结果)",
184
+ ...section("开关与启动提示", table(["enabled", "quietStartup"].map((key) => [key, effective(settings, key)]))),
185
+ ...section("恢复上限", table(FIELDS.map((field) => [field.name, effective(settings, field.name)]))),
182
186
  "",
183
187
  rulesText(settings),
184
- ...section("设置文件", table(fileRows(settings.files))),
188
+ ...section("配置文件", table(fileRows(settings.files))),
185
189
  ].join("\n"),
186
190
  );
187
191
  }
188
-
189
- /**
190
- * `/onward --scope <层> show [rules]`:这一份设置文件自己写了什么,不合并、不填默认值;合并后实际用的是 `/onward show`。
191
- * 规则照文件里写的列,参数只列规则自己写了的。
192
- */
193
- export function layerNotice(settings: Settings, scope: Scope, rulesOnly: boolean): Notice {
194
- const file = settings.file(scope);
195
- if (!file) return warning("onward:还不知道当前目录,看不了项目级设置;会话开始之后再看");
196
- const title = `${SCOPE_NAMES[scope]}设置 ${fileState(file)}`;
197
- if (file.source.kind !== "file") return info(title);
198
- const { layer } = file;
199
- if (layer.problems.length)
200
- return info(
201
- [
202
- title,
203
- `有 ${layer.problems.length} 处问题,${UNTIL_FIXED}:`,
204
- ...layer.problems.map((problem) => `- ${problem}`),
205
- ].join("\n"),
206
- );
207
- const inherited = scope === "project" ? "全局设置" : "内置默认值";
208
- const params: [string, string][] = [
209
- ...(layer.enabled === undefined ? [] : [["enabled", String(layer.enabled)] as [string, string]]),
210
- ...FIELDS.filter((item) => Object.hasOwn(layer.defaults, item.name)).map((item): [string, string] => [
211
- item.name,
212
- shown(item, layer.defaults),
213
- ]),
214
- ...(layer.quietStartup === undefined ? [] : [["quietStartup", String(layer.quietStartup)] as [string, string]]),
215
- ];
216
- const rules =
217
- layer.rules === undefined
218
- ? [`没写 rules,${scope === "project" ? "用全局设置的" : "没有规则"}`]
219
- : layerRules(layer.rules, scope);
220
- const head = rulesOnly ? [] : [...(params.length ? table(params) : [` 没写开关和参数,都用${inherited}的`]), ""];
221
- return info([title, ...head, ...rules, "", `合并后实际用的见 /${COMMAND} show`].join("\n"));
222
- }
223
-
224
- /** 一份设置文件里的 rules,照写的列:条件,和规则自己写了的参数。 */
225
- function layerRules(rules: readonly Rule[], scope: Scope): string[] {
226
- if (!rules.length) return [`rules 是空的:${scope === "project" ? "这个项目里没有规则" : "没有规则"}`];
227
- return [
228
- `rules(${rules.length} 条,按顺序,第一条命中的生效)`,
229
- ...rules.map((rule, index) => {
230
- const own = FIELDS.filter((item) => Object.hasOwn(rule.patch, item.name)).map(
231
- (item) => `${item.name}=${shown(item, rule.patch)}`,
232
- );
233
- const state = rule.enabled ? "" : "(已停用)";
234
- return ` ${index + 1}. ${rule.name}${state}:${describeWhen(rule)}${own.length ? `;${own.join(" ")}` : ""}`;
235
- }),
236
- ];
237
- }
238
-
239
- function shown(item: Field, values: PolicyPatch): string {
240
- return (item as Field<typeof item.name>).show(values[item.name] as never);
241
- }
242
-
243
- /** `/onward show rules`。设置文件读不了时说读不了:规则一条也没读到,不是没写。 */
244
192
  export function rulesNotice(settings: Settings): Notice {
245
- const broken = brokenFiles(settings);
246
- if (!broken.length) return settingsNotice(settings, rulesText(settings));
247
- return settingsNotice(
248
- settings,
249
- [`设置文件读不了,${UNTIL_FIXED}`, ...table(fileRows(broken)), "", `改好之后 /${COMMAND} reload`].join("\n"),
250
- );
193
+ return settings.config.problems.length ? showProblems(settings) : info(rulesText(settings));
251
194
  }
252
-
253
- /** 规则的全文。有项目级设置在用时,问题前面标上是哪一份的,规则前面说来自哪一份。 */
254
195
  function rulesText(settings: Settings): string {
255
- const labelled = settings.projectFile !== undefined;
256
- const problems = settings.files.flatMap((file) =>
257
- file.layer.problems.map((problem) => (labelled ? `${SCOPE_NAMES[file.scope]}:${problem}` : problem)),
258
- );
259
- return describeRules({ ...settings.config, problems }, rulesFrom(settings));
260
- }
261
-
262
- /** 有项目级设置在用时,说规则来自哪一份;项目级的 rules 替换了全局的,也说一句。只有一份时不说。 */
263
- function rulesFrom(settings: Settings): string | undefined {
264
196
  const origin = settings.origin("rules");
265
- if (settings.projectFile === undefined || origin === undefined) return undefined;
266
- const replaced = origin === "project" && settings.has("global", "rules");
267
- return `规则来自${SCOPE_NAMES[origin]}设置${replaced ? ",全局的 rules 不生效" : ""}`;
268
- }
269
-
270
- /** 改了 quietStartup 之后:onward 的启动提示现在怎么显示。 */
271
- export function quietLine(quiet: boolean | undefined): string {
272
- if (quiet === undefined) return "onward 的启动提示跟着 pi 的 quietStartup";
273
- return quiet
274
- ? "onward 的启动提示不显示;设置有问题时照样警告"
275
- : "onward 的启动提示照常显示,不管 pi 的 quietStartup";
276
- }
277
-
278
- /** 改了开关或参数之后,总是说清目标层级,和有没有项目级设置无关。 */
279
- export function scopeLine(scope: Scope): string {
280
- return `改的是${SCOPE_NAMES[scope]}设置`;
197
+ return describeRules(
198
+ settings.config,
199
+ `规则(${settings.config.rules.length} 条,${origin ? `来源:${NAMES[origin]}配置` : "未配置"})${origin === "project" && settings.has("global", "rules") ? "\n项目级 rules 整份替换全局 rules。" : ""}`,
200
+ );
281
201
  }
282
-
283
- /**
284
- * 改了全局、项目级又写了同名的:这个项目里还是按项目级的走,给出跟随全局的写法,和 wecom-aibot 一样。`keys` 是这次
285
- * 改到的开关和参数。
286
- */
287
- export function shadowLine(settings: Settings, scope: Scope, keys: readonly string[]): string | undefined {
288
- const shadowed = scope === "global" ? keys.filter((key) => settings.has("project", key)) : [];
289
- return shadowed.length
290
- ? `项目级设置也写了 ${shadowed.join("、")},这个项目里仍按项目级的走;要跟随全局时运行 /${COMMAND} ${SCOPE} project unset ${shadowed.join(" ")}`
291
- : undefined;
202
+ export function describeRules(config: Config, title = `规则(${config.rules.length} 条)`): string {
203
+ if (config.problems.length) return config.problems.join("\n");
204
+ const lines = [title, "按顺序匹配第一条规则;按连续失败次数选择已达到阈值的最后一个阶段。"];
205
+ if (!config.rules.length) lines.push("没有可用的规则;在设置文件的 rules 里写规则,再 /onward reload。");
206
+ for (const [index, rule] of config.rules.entries()) {
207
+ lines.push(`${index + 1}. ${rule.name}${rule.enabled ? "" : "(已停用)"}:${describeWhen(rule)}`);
208
+ for (const stage of rule.stages)
209
+ lines.push(
210
+ ` 从第 ${stage.minFailures} 次失败:${stage.action.use};间隔 ${delayText(stage.delay)}${stage.action.with ? `;参数 ${JSON.stringify(stage.action.with)}` : ""}`,
211
+ );
212
+ }
213
+ lines.push(...section("规则提醒(不影响设置生效)", configWarnings(config)));
214
+ return lines.join("\n");
292
215
  }
293
-
294
- /** reset 只去掉目标层的开关和参数,不能笼统地说「恢复默认」。 */
295
- export function resetLine(scope: Scope, keptRules: boolean): string {
296
- const done = `已去掉${SCOPE_NAMES[scope]}的开关和参数`;
297
- return keptRules ? `${done},手写的 rules 保留` : done;
216
+ function describeWhen({ when }: Rule): string {
217
+ return (
218
+ [
219
+ when.failure && `失败匹配 /${when.failure.source}/i`,
220
+ when.provider && `provider=${when.provider}`,
221
+ when.model && `model=${when.model}`,
222
+ ]
223
+ .filter(Boolean)
224
+ .join(",") || "任何失败"
225
+ );
298
226
  }
299
-
300
- /** 一次修改之后:写好了就是当前状态,`done` 跟在标题后面;否则说明为什么。 */
301
- export function changedNotice(saved: Saved, settings: Settings, progress: Progress, done?: string): Notice {
227
+ export function layerNotice(settings: Settings, scope: Scope, rulesOnly: boolean): Notice {
228
+ const file = settings.file(scope);
229
+ if (!file) return warning("onward:当前目录尚未确定,请在会话开始后重试。");
230
+ const lines = [`onward ${rulesOnly ? "规则" : "配置"}(${NAMES[scope]},仅本层配置)`];
231
+ if (file.source.kind === "untrusted")
232
+ return warning([...lines, "项目未受信任,未读取项目配置。", ...table(fileRows([file]))].join("\n"));
233
+ if (file.layer.problems.length)
234
+ return warning([...lines, ...file.layer.problems, ...section("配置文件", table(fileRows([file])))].join("\n"));
235
+ if (file.unsaved.length) lines.push(`未保存的配置项:${file.unsaved.join("、")};重载后以磁盘为准。`);
236
+ if (file.source.kind === "none") lines.push("配置文件未创建。");
237
+ if (!rulesOnly) {
238
+ const rows: [string, string][] = [];
239
+ if (file.layer.enabled !== undefined) rows.push(["enabled", String(file.layer.enabled)]);
240
+ if (file.layer.quietStartup !== undefined) rows.push(["quietStartup", String(file.layer.quietStartup)]);
241
+ for (const field of FIELDS)
242
+ if (Object.hasOwn(file.layer.limits, field.name))
243
+ rows.push([field.name, shown(field.name, file.layer.limits)]);
244
+ lines.push(...table(rows));
245
+ }
246
+ if (file.layer.rules === undefined)
247
+ lines.push(`未写 rules,${scope === "project" ? "继承全局配置的规则" : "没有规则"}。`);
248
+ else if (!file.layer.rules.length)
249
+ lines.push(`规则(0 条,显式空列表);${scope === "project" ? "不使用全局规则" : "没有规则"}。`);
250
+ else lines.push(describeRules({ enabled: true, limits: file.layer.limits, rules: file.layer.rules, problems: [] }));
251
+ if (!rulesOnly) lines.push(...section("配置文件", table(fileRows([file]))));
252
+ return info(lines.join("\n"));
253
+ }
254
+ function restriction(settings: Settings, state: RunState): string | undefined {
255
+ if (settings.config.problems.length) return "配置无效,暂时无法自动恢复;详情见 /onward show。";
256
+ if (!settings.config.enabled) return "当前自动恢复已停用。";
257
+ if (!usable(settings.config)) return "当前没有可用规则,暂时不会自动恢复。";
258
+ if (state.phase === "stopped") return "本轮恢复已停止,发消息开启新一轮。";
259
+ return undefined;
260
+ }
261
+ function saveBlocker(saved: Saved): string | undefined {
302
262
  switch (saved.kind) {
303
- case "saved":
304
- return statusNotice(settings, progress, done);
305
263
  case "broken":
306
- return warning(`${STOPPED} onward:${saved.path} 读不了(${saved.error}),先修好;未做任何修改`);
264
+ return "配置文件无法读取";
307
265
  case "unbound":
308
- return warning("onward:还不知道当前目录,改不了项目级设置;会话开始之后再改。未做任何修改");
309
- case "unwritten":
310
- return warning(
311
- `onward:设置没能保存(${saved.error}),这次运行仍按改过的设置走\n${statusText(settings, progress)}`,
312
- );
266
+ return "当前目录尚未确定";
267
+ case "untrusted":
268
+ return "项目未受信任";
269
+ default:
270
+ return undefined;
313
271
  }
314
272
  }
315
273
 
316
- // ── 设置说明 ──
317
-
318
- /** 一组参数:怎么续跑、上限、间隔。`stop` 不续跑,只有一行。 */
319
- function policyRows(policy: Policy): [string, string][] {
320
- if (policy.action === "stop") return [["做法", "命中就停,只提醒,不续跑"]];
321
- return [
322
- ["做法", policy.action === "resend" ? "静默重发同一个请求" : `发「${policy.prompt}」`],
323
- ["上限", `最多 ${policy.maxRetries} 次;同一个错误连续 ${policy.maxSameError} 次后也停`],
324
- ["间隔", describeDelay(policy)],
274
+ export function toggleNotice(
275
+ saved: Saved,
276
+ settings: Settings,
277
+ status: OnwardStatus,
278
+ scope: Scope,
279
+ enabled: boolean,
280
+ ): Notice {
281
+ const verb = enabled ? "启用" : "停用";
282
+ const target = `${NAMES[scope]}配置`;
283
+ const blocker = saveBlocker(saved);
284
+ if (blocker) return warning(`onward:未能${verb}自动恢复(${target})\n${blocker},配置未修改。`);
285
+ const lines = [
286
+ saved.kind === "saved"
287
+ ? `onward:已${verb}自动恢复(${target})`
288
+ : `onward:${verb}设置保存失败(${target})\n本次运行保留了配置修改;重新加载或重启后以原文件为准。`,
325
289
  ];
326
- }
327
-
328
- /**
329
- * 间隔表:列到不再变为止,后面的说「之后每次」;太长的中间用 … 省掉。单位都一样时只在最后写一次。
330
- * 例如 `3 → 6 → 9 → 12 → 15 秒,之后每次 15 秒;50 次合计约 12 分`。
331
- */
332
- export function describeDelay(policy: Policy): string {
333
- const count = policy.maxRetries;
334
- const steps = Array.from({ length: count }, (_, i) => retryDelay(i + 1, policy.delay));
335
- // 从这一次起间隔不再变。
336
- let flat = count - 1;
337
- while (flat > 0 && steps[flat - 1] === steps[count - 1]) flat--;
338
- const total = `${count} 次合计约 ${formatDelay(totalDelay(count, policy.delay))}`;
339
- if (count === 1) return formatDelay(steps[0]!);
340
- if (flat === 0) return `每次 ${formatDelay(steps[0]!)};${total}`;
341
- const shown = steps.slice(0, flat + 1);
342
- const head = shown.length > 7 ? [...shown.slice(0, 5), undefined, shown.at(-1)!] : shown;
343
- const tail = flat < count - 1 ? `,之后每次 ${formatDelay(steps[count - 1]!)}` : "";
344
- return `${sequence(head)}${tail};${total}`;
345
- }
346
-
347
- /** `undefined` 是省掉的那段。单位都一样时数字之间不重复单位:`3 → 6 → 9 秒`。 */
348
- function sequence(values: (number | undefined)[]): string {
349
- const texts = values.map((ms) => (ms === undefined ? "…" : formatDelay(ms)));
350
- const unit = (text: string) => /^[\d.]+ (毫秒|秒|分)$/.exec(text)?.[1];
351
- const units = new Set(texts.filter((text) => text !== "…").map(unit));
352
- if (units.size !== 1 || units.has(undefined)) return texts.join(" → ");
353
- const [only] = units;
354
- return `${texts.map((text) => text.replace(` ${only}`, "")).join(" → ")} ${only}`;
355
- }
356
-
357
- /**
358
- * `/onward show rules` 的全文。有问题时只列问题:规则反正不生效,列出来反而像在跑。`from` 说规则来自哪份设置文件,
359
- * 写在最前面。
360
- */
361
- export function describeRules(config: Config, from?: string): string {
362
- if (config.problems.length)
363
- return `设置文件有 ${config.problems.length} 处问题,${UNTIL_FIXED}:\n${config.problems.map((p) => `- ${p}`).join("\n")}\n改完 /${COMMAND} reload`;
364
- const source = from ? [from] : [];
365
- if (!config.rules.length) return [...source, `没有可用的规则,出错时不会自动续跑。${addRules()}`].join("\n");
366
- const blocks = config.rules.map((rule, index) => {
367
- const rows: [string, string][] = [
368
- ["条件", describeWhen(rule)],
369
- ...policyRows(resolvePolicy(config.defaults, rule.patch)),
370
- ];
371
- return [
372
- `${index + 1}. ${rule.name}${rule.enabled ? "" : "(已停用)"}`,
373
- ...table(rows).map((line) => ` ${line}`),
374
- ];
375
- });
376
- return [
377
- ...source,
378
- "规则(按顺序,第一条命中的生效;没命中的错误和空回复不处理)",
379
- ...blocks.flat(),
380
- ...section(
381
- "规则提醒(不影响设置生效)",
382
- configWarnings(config).map((text) => `- ${text}`),
383
- ),
384
- ].join("\n");
385
- }
386
-
387
- function describeWhen({ when }: Rule): string {
388
- const parts = [
389
- when.failure && `失败匹配 /${when.failure.source}/i`,
390
- when.provider && `provider=${when.provider}`,
391
- when.model && `model=${when.model}`,
392
- ].filter(Boolean);
393
- return parts.length ? parts.join(",") : "任何失败";
394
- }
395
-
396
- /** 配置错误和非阻断的规则提醒都用 warning;是否能续跑仍由 config.problems 决定。 */
397
- function settingsNotice(settings: Settings, message: string): Notice {
398
- const attention = settings.config.problems.length > 0 || configWarnings(settings.config).length > 0;
399
- return { message, level: attention ? "warning" : "info" };
400
- }
401
-
402
- function ruleWarningSummary(config: Config): string | undefined {
403
- const count = configWarnings(config).length;
404
- return count ? `规则有 ${count} 处提醒,不影响设置生效` : undefined;
405
- }
406
-
407
- function usableRules(config: Config): number {
408
- return config.rules.filter((rule) => rule.enabled).length;
409
- }
410
-
411
- // ── 运行中的通知 ──
412
-
413
- /**
414
- * 启动时最多一条:配置错误说是哪一份(关着也说,可能就是 enabled 写错了);规则提醒不阻止续跑。
415
- * 两者都不受 quietStartup 影响。用上了项目级设置、没有可用规则这两种平常提示才问 quiet()。
416
- * 不写路径和报错原文,细节用 `/onward show` 查看;pi 只留下连着的提示里的最后一条,分开发会互相顶掉。
417
- */
418
- export function startupNotice(settings: Settings, quiet: () => boolean): Notice | undefined {
419
- const { config } = settings;
420
- const bad = settings.files.flatMap((file) => {
421
- const name = `${SCOPE_NAMES[file.scope]}设置`;
422
- if (file.source.kind === "broken") return [`${name}读不了`];
423
- return file.layer.problems.length ? [`${name}有 ${file.layer.problems.length} 处问题`] : [];
424
- });
425
- if (bad.length) return warning(`${STOPPED} onward:${bad.join(",")},${UNTIL_FIXED}(${SEE_SHOW})`);
426
- const project = settings.file("project")?.source.kind === "file";
427
- const reminders = ruleWarningSummary(config);
428
- if (reminders) return warning(`onward:${project ? "用上了项目级设置;" : ""}${reminders}(${SEE_SHOW})`);
429
- const idle = config.enabled && !usableRules(config);
430
- if (!(project || idle) || quiet()) return undefined;
431
- if (project && idle)
432
- return info(`${IDLE} onward:用上了项目级设置;没有可用的规则,出错时不会自动续跑(${SEE_SHOW})`);
433
- if (project) return info(`onward:用上了项目级设置(${SEE_SHOW})`);
434
- return info(`${IDLE} onward:没有可用的规则,出错时不会自动续跑(${SEE_SHOW})`);
435
- }
436
-
437
- /**
438
- * 状态栏已经写了第几次、哪条规则,这里只说接下来做什么:`onward:3 秒后静默重发`。出错时 pi 已经显示过错误;
439
- * 空回复 pi 什么都不显示,所以先说一句:`onward:空回复,3 秒后发「继续」`。
440
- */
441
- export function retryNotice(step: Retry, draft: Continue, failure: Failure): Notice {
442
- const action = draft.type === "context_edit" ? "静默重发" : `发「${truncate(draft.content, 30)}」`;
443
- const what = failure.stopReason === "stop" ? `${EMPTY_REPLY},` : "";
444
- return info(`onward:${what}${formatDelay(step.delay)}后${action}`);
445
- }
446
-
447
- /** 状态栏已经写了停了、哪条规则,这里只说为什么停、怎么办。 */
448
- export function giveUpNotice(step: GiveUp): Notice {
449
- const again = ";发任意消息重新计数";
450
- switch (step.reason) {
451
- case "stop":
452
- return warning("onward:这条规则只提醒,需要你自己处理");
453
- case "same-error":
454
- return warning(`onward:同一个错误已连续 ${step.streak} 次${again}`);
455
- case "budget":
456
- return warning(`onward:已续跑 ${step.attempt} 次仍未恢复${again}`);
290
+ if (scope === "global" && settings.config.enabled !== enabled && settings.origin("enabled") === "project")
291
+ lines.push(`当前项目仍${settings.config.enabled ? "启用" : "停用"}自动恢复:项目级配置覆盖了全局配置。`);
292
+ else if (enabled) {
293
+ const reason = restriction(settings, status.state);
294
+ if (reason) lines.push(reason);
457
295
  }
458
- }
459
-
460
- /** 状态栏:正在续跑第几次。 */
461
- export function retryStatus(hit: Hit, step: Retry): string {
462
- return `${RUNNING} ${progressText(hit.rule.name, step.attempt, hit.policy.maxRetries)}`;
463
- }
464
-
465
- /** 状态栏:停了,留到恢复或用户发新消息。 */
466
- export function giveUpStatus(hit: Hit, step: GiveUp): string {
467
- return `${STOPPED} ${step.reason === "stop" ? "不续跑" : "续跑已停"} · ${hit.rule.name}`;
468
- }
469
-
470
- /** 续跑消息在会话里的标签。`details` 来自会话记录文件,按 unknown 读:字段齐全才写第几次和规则名。 */
471
- export function continueLabel(details: unknown): string {
472
- if (!isRecord(details)) return `${RUNNING} onward`;
473
- const { rule, attempt, max } = details;
474
- return typeof rule === "string" && Number.isInteger(attempt) && Number.isInteger(max)
475
- ? `${RUNNING} onward · ${progressText(rule, attempt as number, max as number)}`
476
- : `${RUNNING} onward`;
477
- }
478
-
479
- function progressText(rule: string, attempt: number, max: number): string {
480
- return `续跑 ${attempt}/${max} · ${rule}`;
481
- }
482
-
483
- /** 归一化后的错误摘要,不带每次都变的 request id。 */
484
- export function errorExcerpt(failure: Failure, limit = 40): string {
485
- return truncate(errorSignature(failure), limit);
486
- }
487
-
488
- function truncate(text: string, limit: number): string {
489
- return text.length <= limit ? text : `${text.slice(0, limit - 1)}…`;
296
+ return saved.kind === "unwritten" || lines.length > 1 ? warning(lines.join("\n")) : info(lines.join("\n"));
297
+ }
298
+ export function changedNotice(
299
+ saved: Saved,
300
+ settings: Settings,
301
+ status: OnwardStatus,
302
+ change: { action: "set" | "unset" | "reset"; scope: Scope; keys: readonly string[] },
303
+ ): Notice {
304
+ const { action, scope, keys } = change;
305
+ const label = action === "set" ? "修改配置参数" : action === "unset" ? "移除配置项" : "重置配置参数";
306
+ const target = `${NAMES[scope]}配置`;
307
+ const blocker = saveBlocker(saved);
308
+ if (blocker)
309
+ return warning(
310
+ `onward:未能${label}(${target})\n${blocker},配置未修改。${action === "reset" ? "\n本轮恢复状态和计数已重置。" : ""}`,
311
+ );
312
+ const lines = [
313
+ saved.kind === "saved"
314
+ ? `onward:已${label}(${target})`
315
+ : `onward:配置修改保存失败(${target})\n本次运行保留了配置修改;重新加载或重启后以原文件为准。`,
316
+ ];
317
+ if (action === "set") {
318
+ const layer = settings.file(scope)!.layer;
319
+ lines.push(
320
+ ...table(
321
+ keys.map((key) => [key, key === "quietStartup" ? String(layer.quietStartup) : shown(key, layer.limits)]),
322
+ ),
323
+ );
324
+ } else if (action === "unset") {
325
+ if (settings.config.problems.length) lines.push(`配置项:${keys.join("、")}`);
326
+ else lines.push("当前采用", ...table(keys.map((key) => [key, effective(settings, key)])));
327
+ } else lines.push("已移除开关、恢复上限和 quietStartup;rules 及其他手写内容未改动。");
328
+ const covered = scope === "global" ? keys.filter((key) => settings.has("project", key)) : [];
329
+ if (covered.length) lines.push(`当前项目的 ${covered.join("、")} 仍由项目级配置覆盖;详情见 /onward show。`);
330
+ const reason = restriction(settings, status.state);
331
+ if (reason) lines.push(reason);
332
+ return saved.kind === "unwritten" || reason ? warning(lines.join("\n")) : info(lines.join("\n"));
333
+ }
334
+ export function reloadNotice(settings: Settings, status: OnwardStatus): Notice {
335
+ const scopes = settings.files
336
+ .filter((file) => file.source.kind !== "untrusted")
337
+ .map((file) => NAMES[file.scope])
338
+ .join("、");
339
+ if (settings.config.problems.length)
340
+ return warning(`onward:重新加载后配置无效(${scopes})\n修好之前不会自动恢复,详情见 /onward show。`);
341
+ const reason = restriction(settings, status.state);
342
+ const ignored = settings.file("project")?.source.kind === "untrusted" ? "\n项目未受信任,未读取项目配置。" : "";
343
+ return info(`onward:已重新加载配置(${scopes})${ignored}${reason ? `\n${reason}` : ""}`);
344
+ }
345
+ export function startupNotice(settings: Settings, quiet: () => boolean, actionProblems: number): Notice | undefined {
346
+ if (settings.config.problems.length)
347
+ return warning(
348
+ `🛑 onward:配置有 ${settings.config.problems.length} 处问题,修好之前不会自动恢复(/onward show 查看)`,
349
+ );
350
+ const notices: string[] = [];
351
+ const warnings = configWarnings(settings.config);
352
+ if (warnings.length) notices.push(`规则有 ${warnings.length} 处提醒(/onward show 查看)`);
353
+ if (actionProblems) notices.push(`动作注册有 ${actionProblems} 处问题(/onward actions 查看)`);
354
+ if (notices.length) return warning(`onward:${notices.join(";")};不影响当前配置生效。`);
355
+ const project = settings.file("project")?.source.kind === "file";
356
+ const idle = settings.config.enabled && !usable(settings.config);
357
+ if ((!project && !idle) || quiet()) return;
358
+ return info(
359
+ `${idle ? "💤 " : ""}onward:${project ? "用上了项目级设置;" : ""}${idle ? "没有可用的规则,出错时不会自动恢复" : "配置已加载"}(/onward show 查看)`,
360
+ );
490
361
  }