@cobia/pi-onward 0.0.0-stage → 0.1.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,208 @@
1
+ /**
2
+ * 一轮以错误收尾、命中规则时,在 `agent_before_settle` 边界上等一会儿,再要 pi 接着跑:
3
+ * - message:追加一条看得见的消息(默认「继续」),模型照常读到;
4
+ * - resend:用 `context_edit` 把失败的那条从模型上下文里省略,重发同一个请求。失败的记录仍留在会话里。
5
+ *
6
+ * 等待和续跑都在这一轮之内完成,不靠落定后的定时器,所以 `pi -p`、RPC、subagent 子会话里一样生效。
7
+ */
8
+ import type {
9
+ AgentBeforeSettleEvent,
10
+ AgentBeforeSettleEventResult,
11
+ ExtensionContext,
12
+ MessageEndEvent,
13
+ SessionBoundaryDraft,
14
+ } from "@earendil-works/pi-coding-agent";
15
+ import { type Hit, matchFailure } from "../policy/config.ts";
16
+ import { isSuccess } from "../policy/failure.ts";
17
+ import { renderPrompt } from "../policy/policy.ts";
18
+ import { type Progress, type Retry, Tracker } from "../policy/tracker.ts";
19
+ import type { Settings } from "./settings.ts";
20
+ import { errorExcerpt, giveUpNotice, giveUpStatus, retryNotice, retryStatus, say } from "./text.ts";
21
+
22
+ type Ctx = Pick<ExtensionContext, "sessionManager" | "hasUI" | "ui">;
23
+
24
+ /** 状态栏里本扩展的那一格。 */
25
+ const STATUS_KEY = "pi-onward";
26
+
27
+ /** 续跑消息的类型,render.ts 按它画。 */
28
+ export const CUSTOM_TYPE = "pi-onward";
29
+
30
+ /** 续跑消息带的 details:只给界面画标签,模型只读到 content。 */
31
+ export interface ContinueDetails {
32
+ rule: string;
33
+ attempt: number;
34
+ max: number;
35
+ }
36
+
37
+ /** 怎么接着跑:resend 省略失败的那条重发,message 追加一条文字消息。 */
38
+ export type Continue =
39
+ | Extract<SessionBoundaryDraft, { type: "context_edit" }>
40
+ | (Extract<SessionBoundaryDraft, { type: "custom_message" }> & { content: string; details: ContinueDetails });
41
+
42
+ /**
43
+ * 每个会话由哪个实例负责。同一个会话装了两份(例如 subagent 既按包加载、又按路径加载了一份副本),
44
+ * 两份各自计数:一份到上限停手,另一份照样续跑,互相接力永远停不下来。所以只让先到的那份干活;
45
+ * reload 和子会话销毁前 pi 都会发 session_shutdown,在那里交还。
46
+ */
47
+ const shared = globalThis as typeof globalThis & { __piOnwardOwners?: Map<string, object> };
48
+ shared.__piOnwardOwners ??= new Map();
49
+ const owners = shared.__piOnwardOwners;
50
+
51
+ export class Onward {
52
+ private readonly settings: Settings;
53
+ private readonly tracker = new Tracker();
54
+ /**
55
+ * 接下来的 agent_start 是我们 `continue: true` 出来的。pi 会为它重新发 agent_start,
56
+ * 按新一轮清零的话计数永远到不了上限,会死循环。
57
+ */
58
+ private continuing = false;
59
+ /** 正在等待的那次续跑;关掉、恢复默认、会话结束时打断它。 */
60
+ private waiting: AbortController | undefined;
61
+ /**
62
+ * 状态栏里写着什么:retrying 是第几次续跑,这一轮结束就清掉;gave-up 是停了,留到恢复或用户发新消息。
63
+ * 只有干活的那份会写,所以清的时候不用再问是谁的。
64
+ */
65
+ private statusBar: "retrying" | "gave-up" | undefined;
66
+
67
+ constructor(settings: Settings) {
68
+ this.settings = settings;
69
+ }
70
+
71
+ agentStart(ctx: Ctx): void {
72
+ if (!this.owns(ctx)) return;
73
+ if (!this.continuing) this.reset(ctx);
74
+ this.continuing = false;
75
+ }
76
+
77
+ messageEnd(event: MessageEndEvent, ctx: Ctx): void {
78
+ // 续跑之后只要正常返回过一次就算恢复了:后面再出错是新的一串,次数从头算。
79
+ if (this.owns(ctx) && isSuccess(event.message)) this.reset(ctx);
80
+ }
81
+
82
+ /** 等待期间这一轮仍算忙:按 Esc 打断等待;用户输入的消息优先,我们让路。 */
83
+ async beforeSettle(
84
+ event: AgentBeforeSettleEvent,
85
+ ctx: ExtensionContext,
86
+ ): Promise<AgentBeforeSettleEventResult | undefined> {
87
+ this.continuing = false;
88
+ if (!this.owns(ctx)) return undefined;
89
+ // 别的扩展已经要求继续:再插一条会改掉它要重发的内容。
90
+ if (event.outcome === "aborted" || event.continue || ctx.hasPendingMessages()) return undefined;
91
+ const entry = event.context.contextEntries.at(-1);
92
+ const hit = matchFailure(this.settings.config, entry?.messages.at(-1));
93
+ if (!entry || !hit) return undefined;
94
+ const step = this.advance(hit, ctx);
95
+ if (!step) return undefined;
96
+ const draft: Continue =
97
+ hit.policy.action === "resend"
98
+ ? { type: "context_edit", targetId: entry.sourceEntry.id, replacement: null }
99
+ : {
100
+ type: "custom_message",
101
+ customType: CUSTOM_TYPE,
102
+ content: this.prompt(hit, step),
103
+ display: true,
104
+ details: { rule: hit.rule.name, attempt: step.attempt, max: hit.policy.maxRetries },
105
+ };
106
+ say(ctx, retryNotice(step, draft));
107
+ this.setStatus(ctx, "retrying", retryStatus(hit, step));
108
+ if (await this.wait(step.delay, ctx.signal)) return undefined;
109
+ // 等的时候用户发了消息:pi 会接着处理它,这算用户开的新一轮。
110
+ if (ctx.hasPendingMessages()) {
111
+ this.reset(ctx);
112
+ return undefined;
113
+ }
114
+ this.continuing = true;
115
+ // 边界结果会整体替换前面扩展提出的条目,所以带上它们。
116
+ return { entries: [...event.entries, draft], continue: true };
117
+ }
118
+
119
+ /**
120
+ * 这一轮彻底结束了;pi 不接受续跑时,`continuing` 不能留到下一轮。没有接着跑(按了 Esc、错误没命中规则),
121
+ * 「第几次」就不再成立;停了的提示留着。
122
+ */
123
+ settled(ctx: Ctx): void {
124
+ this.continuing = false;
125
+ if (this.statusBar === "retrying") this.setStatus(ctx, undefined);
126
+ }
127
+
128
+ /** 关掉、恢复默认时:打断正在等的续跑,清零计数。 */
129
+ stop(ctx: Ctx): void {
130
+ this.waiting?.abort();
131
+ this.reset(ctx);
132
+ this.continuing = false;
133
+ }
134
+
135
+ shutdown(ctx: Ctx): void {
136
+ this.stop(ctx);
137
+ const session = ctx.sessionManager.getSessionId();
138
+ if (owners.get(session) === this) owners.delete(session);
139
+ }
140
+
141
+ progress(): Progress {
142
+ return this.tracker.progress();
143
+ }
144
+
145
+ private owns(ctx: Ctx): boolean {
146
+ const session = ctx.sessionManager.getSessionId();
147
+ const owner = owners.get(session);
148
+ if (owner === undefined) owners.set(session, this);
149
+ return owner === undefined || owner === this;
150
+ }
151
+
152
+ /** 再试就返回这一步;该停了就提醒并返回 undefined。 */
153
+ private advance(hit: Hit, ctx: ExtensionContext): Retry | undefined {
154
+ const step = this.tracker.next(hit.rule.name, hit.failure, hit.policy);
155
+ if (step.retry) return step;
156
+ if (step.notify) say(ctx, giveUpNotice(step));
157
+ this.setStatus(ctx, "gave-up", giveUpStatus(hit, step));
158
+ return undefined;
159
+ }
160
+
161
+ /** 计数从头算,状态栏也清掉。 */
162
+ private reset(ctx: Ctx): void {
163
+ this.tracker.reset();
164
+ if (this.statusBar !== undefined) this.setStatus(ctx, undefined);
165
+ }
166
+
167
+ /** 没有界面时(`pi -p`)不写;RPC 下 pi 把它发给客户端。 */
168
+ private setStatus(ctx: Ctx, status: "retrying" | "gave-up" | undefined, text?: string): void {
169
+ this.statusBar = status;
170
+ if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, text);
171
+ }
172
+
173
+ private prompt(hit: Hit, step: Retry): string {
174
+ return renderPrompt(hit.policy.prompt, {
175
+ attempt: step.attempt,
176
+ max: hit.policy.maxRetries,
177
+ error: errorExcerpt(hit.failure, 120),
178
+ rule: hit.rule.name,
179
+ });
180
+ }
181
+
182
+ /** 返回 true 表示被打断。 */
183
+ private async wait(ms: number, signal: AbortSignal | undefined): Promise<boolean> {
184
+ const waiting = new AbortController();
185
+ this.waiting = waiting;
186
+ try {
187
+ return await sleep(ms, signal ? AbortSignal.any([signal, waiting.signal]) : waiting.signal);
188
+ } finally {
189
+ if (this.waiting === waiting) this.waiting = undefined;
190
+ }
191
+ }
192
+ }
193
+
194
+ /** 不 unref:等待期间这一轮还忙,进程不该因为只剩它在等就退出。 */
195
+ function sleep(ms: number, signal: AbortSignal): Promise<boolean> {
196
+ if (signal.aborted) return Promise.resolve(true);
197
+ if (ms <= 0) return Promise.resolve(false);
198
+ return new Promise((resolve) => {
199
+ const finish = (aborted: boolean): void => {
200
+ clearTimeout(timer);
201
+ signal.removeEventListener("abort", onAbort);
202
+ resolve(aborted);
203
+ };
204
+ const onAbort = (): void => finish(true);
205
+ const timer = setTimeout(() => finish(false), ms);
206
+ signal.addEventListener("abort", onAbort, { once: true });
207
+ });
208
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 续跑消息在会话里的样子:第一行是标签「⏩ onward · 续跑 2/10 · auth」,下面是发给模型的原文。
3
+ * 没有这个渲染器时 pi 画成「[pi-onward]」加原文,看不出是第几次、哪条规则;恢复会话时通知不会重放,
4
+ * 只有这条消息还在。模型只读到原文,标签不进上下文。
5
+ */
6
+ import type { MessageRenderer } from "@earendil-works/pi-coding-agent";
7
+ import { Box, Text } from "@earendil-works/pi-tui";
8
+ import { continueLabel } from "./text.ts";
9
+
10
+ export const renderContinue: MessageRenderer = (message, { outputPad }, theme) => {
11
+ const body =
12
+ typeof message.content === "string"
13
+ ? message.content
14
+ : message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
15
+ const lines = [
16
+ theme.fg("customMessageLabel", theme.bold(continueLabel(message.details))),
17
+ ...body.split("\n").map((line) => theme.fg("customMessageText", line)),
18
+ ];
19
+ const box = new Box(outputPad, 1, (text) => theme.bg("customMessageBg", text));
20
+ box.addChild(new Text(lines.join("\n"), 0, 0));
21
+ return box;
22
+ };
@@ -0,0 +1,123 @@
1
+ /**
2
+ * 设置文件 `onward.json` 的读写;放在哪里由 index.ts 决定。
3
+ *
4
+ * `rules` 只能手写;命令只改 `enabled` 和顶层的参数字段。每次写之前重读文件,在它当前的内容上合并,免得盖掉
5
+ * 加载之后才手改的内容;文件读不了(不是合法 JSON、顶层不是对象)时拒绝写,让用户自己修。
6
+ */
7
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
+ import { dirname } from "node:path";
9
+ import { type Config, fileOrder, parseConfig } from "../policy/config.ts";
10
+ import { FIELD_NAMES } from "../policy/policy.ts";
11
+ import { errorText, isRecord } from "../util.ts";
12
+
13
+ /** 当前设置从哪里来。 */
14
+ export type Source = { kind: "file" | "none" } | { kind: "broken"; error: string };
15
+
16
+ /** 一次命令改了什么:`set` 是设置文件里的值,`unset` 是要去掉的键;没写的不动。 */
17
+ export interface SettingsChange {
18
+ enabled?: boolean;
19
+ set?: Record<string, unknown>;
20
+ unset?: readonly string[];
21
+ }
22
+
23
+ /** 改动的结果:写好了;文件坏了,什么都没改;或者写不进去,这次运行仍按改过的设置走。 */
24
+ export type Saved =
25
+ | { kind: "saved"; value: Record<string, unknown> }
26
+ | { kind: "broken"; error: string }
27
+ | { kind: "unwritten"; error: string };
28
+
29
+ /** reset 去掉的键:开关和顶层的参数。 */
30
+ const COMMAND_KEYS: readonly string[] = ["enabled", ...FIELD_NAMES];
31
+
32
+ interface Loaded {
33
+ config: Config;
34
+ source: Source;
35
+ }
36
+
37
+ export class Settings {
38
+ readonly path: string;
39
+ private loaded: Loaded;
40
+
41
+ constructor(path: string) {
42
+ this.path = path;
43
+ this.loaded = load(path);
44
+ }
45
+
46
+ get config(): Config {
47
+ return this.loaded.config;
48
+ }
49
+
50
+ get source(): Source {
51
+ return this.loaded.source;
52
+ }
53
+
54
+ reload(): void {
55
+ this.loaded = load(this.path);
56
+ }
57
+
58
+ /** 在文件当前的内容上合并后写回;文件坏了时不动它。 */
59
+ update(change: SettingsChange): Saved {
60
+ const current = readJson(this.path);
61
+ if (current.kind === "broken") return current;
62
+ const next = applyChange(current.kind === "ok" ? current.value : {}, change);
63
+ this.loaded = { config: parseConfig(next), source: { kind: "file" } };
64
+ try {
65
+ writeJson(this.path, next);
66
+ } catch (error: unknown) {
67
+ return { kind: "unwritten", error: errorText(error) };
68
+ }
69
+ return { kind: "saved", value: next };
70
+ }
71
+
72
+ /** 去掉开关和顶层的参数,手写的 rules 和其他内容留着。 */
73
+ reset(): Saved {
74
+ return this.update({ unset: COMMAND_KEYS });
75
+ }
76
+ }
77
+
78
+ function applyChange(base: Record<string, unknown>, change: SettingsChange): Record<string, unknown> {
79
+ const next: Record<string, unknown> = { ...base, ...change.set };
80
+ if (change.enabled !== undefined) next.enabled = change.enabled;
81
+ for (const name of change.unset ?? []) delete next[name];
82
+ return fileOrder(next);
83
+ }
84
+
85
+ function load(path: string): Loaded {
86
+ const current = readJson(path);
87
+ if (current.kind === "ok") return { config: parseConfig(current.value), source: { kind: "file" } };
88
+ return { config: parseConfig(undefined), source: current.kind === "broken" ? current : { kind: "none" } };
89
+ }
90
+
91
+ type ReadResult =
92
+ | { kind: "missing" }
93
+ | { kind: "broken"; error: string }
94
+ | { kind: "ok"; value: Record<string, unknown> };
95
+
96
+ function readJson(path: string): ReadResult {
97
+ let text: string;
98
+ try {
99
+ text = readFileSync(path, "utf8");
100
+ } catch (error: unknown) {
101
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { kind: "missing" };
102
+ return { kind: "broken", error: errorText(error) };
103
+ }
104
+ let value: unknown;
105
+ try {
106
+ value = JSON.parse(text);
107
+ } catch (error: unknown) {
108
+ return { kind: "broken", error: `不是合法 JSON:${errorText(error)}` };
109
+ }
110
+ return isRecord(value) ? { kind: "ok", value } : { kind: "broken", error: "顶层需要是对象 {}" };
111
+ }
112
+
113
+ /** 先写临时文件再改名:写到一半失败也不会留下半个文件;改名之后临时文件已不在,删它不做事。 */
114
+ function writeJson(path: string, value: unknown): void {
115
+ mkdirSync(dirname(path), { recursive: true });
116
+ const temp = `${path}.${process.pid}.tmp`;
117
+ try {
118
+ writeFileSync(temp, `${JSON.stringify(value, null, "\t")}\n`, { mode: 0o600 });
119
+ renameSync(temp, path);
120
+ } finally {
121
+ rmSync(temp, { force: true });
122
+ }
123
+ }
@@ -0,0 +1,322 @@
1
+ /**
2
+ * 给用户看的通知、状态栏和设置说明;命令的用法在 command.ts,和命令的写法放在一起。
3
+ *
4
+ * pi 把 info 通知画成暗色、warning 画成黄色并加上「Warning:」,所以颜色只分轻重;状态靠开头的图标看:
5
+ * ⏩ 在管(开着、有规则,或正在续跑),💤 不会续跑(关了、没有规则),🛑 停了或要先修。三个图标都占两格,
6
+ * 后面的字始终在同一列。
7
+ *
8
+ * 续跑和停手时状态栏写状态(图标、第几次、哪条规则);会话里的提示只补状态栏没有的:续跑说接下来做什么,
9
+ * 停手说为什么、怎么办,不重复图标、次数和规则名。错误本身 pi 已经在上面用红字显示,提示里也不再摘。
10
+ */
11
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import type { Config, Hit } from "../policy/config.ts";
13
+ import { formatDelay, retryDelay, totalDelay } from "../policy/delay.ts";
14
+ import { errorSignature, type Failure } from "../policy/failure.ts";
15
+ import { DEFAULT_POLICY, FIELDS, type Field, type Policy, resolvePolicy } from "../policy/policy.ts";
16
+ 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";
20
+ import type { Saved, Settings } from "./settings.ts";
21
+
22
+ export const COMMAND = "onward";
23
+
24
+ export interface Notice {
25
+ message: string;
26
+ level: "info" | "warning";
27
+ }
28
+
29
+ /** 没有界面时(`pi -p`)不提示;RPC 下 pi 把它发给客户端,显不显示由客户端定。 */
30
+ export function say(ctx: Pick<ExtensionContext, "hasUI" | "ui">, notice: Notice): void {
31
+ if (ctx.hasUI) ctx.ui.notify(notice.message, notice.level);
32
+ }
33
+
34
+ export const info = (message: string): Notice => ({ message, level: "info" });
35
+ const warning = (message: string): Notice => ({ message, level: "warning" });
36
+
37
+ const RUNNING = "⏩";
38
+ const IDLE = "💤";
39
+ const STOPPED = "🛑";
40
+
41
+ const UNTIL_FIXED = "修好之前不会自动续跑";
42
+ const addRules = (where = "设置文件") => `在${where}的 rules 里写规则(常见规则见 README),再 /${COMMAND} reload`;
43
+
44
+ // ── 排版 ──
45
+
46
+ /** 帮助和状态里的表:行首空两格,名字一列、内容一列,按终端里的宽度对齐;内容的后几行对齐在第一行下面。 */
47
+ export function table(rows: [name: string, text: string][]): string[] {
48
+ const width = Math.max(0, ...rows.map(([name]) => cells(name)));
49
+ return rows.flatMap(([name, text]) => {
50
+ const [first, ...more] = text.split("\n");
51
+ return [
52
+ ` ${name}${" ".repeat(width - cells(name))} ${first}`,
53
+ ...more.map((line) => ` ${" ".repeat(width)} ${line}`),
54
+ ];
55
+ });
56
+ }
57
+
58
+ /**
59
+ * 菜单和补全的每一项:名字一列、说明一列,按终端里的宽度对齐。说明里的换行换成空格,所以一项正好一行,
60
+ * 返回的第几行就是第几项,调用方按下标取回。
61
+ */
62
+ export function columns(rows: [name: string, text: string][]): string[] {
63
+ const width = Math.max(0, ...rows.map(([name]) => cells(name)));
64
+ return rows.map(([name, text]) => `${name}${" ".repeat(width - cells(name))} ${text.replace(/\s*\n\s*/g, " ")}`);
65
+ }
66
+
67
+ /** 有内容才出这一节,前面空一行。 */
68
+ export function section(title: string, lines: string[]): string[] {
69
+ return lines.length ? ["", title, ...lines] : [];
70
+ }
71
+
72
+ /** 终端里占几格:中文和全角字符占两格。 */
73
+ export function cells(text: string): number {
74
+ return [...text].reduce(
75
+ (sum, char) =>
76
+ sum + (/[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\uff00-\uff60\uffe0-\uffe6]/.test(char) ? 2 : 1),
77
+ 0,
78
+ );
79
+ }
80
+
81
+ // ── /onward ──
82
+
83
+ /** `topic`:出错的动作,用法指到它自己的帮助。 */
84
+ export function commandErrorNotice(message: string, topic?: string): Notice {
85
+ return warning(`onward:${message};用法见 /${COMMAND}${topic ? ` ${topic}` : ""} --help`);
86
+ }
87
+
88
+ /** 一行说清现在会不会续跑:`/onward status` 的第一行,也是 `/onward` 菜单的标题。 */
89
+ export function statusHeadline(settings: Settings): string {
90
+ const { config, source } = settings;
91
+ if (source.kind === "broken") return `${STOPPED} onward:设置文件读不了,${UNTIL_FIXED}`;
92
+ const problems = config.problems.length;
93
+ if (problems && !config.enabled) return `${STOPPED} onward:关;设置文件有 ${problems} 处问题,打开前要先修好`;
94
+ if (problems) return `${STOPPED} onward:开,但设置文件有 ${problems} 处问题,${UNTIL_FIXED}`;
95
+ if (!config.enabled) return `${IDLE} onward:关,出错时不会自动续跑`;
96
+ const usable = usableRules(config);
97
+ return usable
98
+ ? `${RUNNING} onward:开,${usable} 条规则生效`
99
+ : `${IDLE} onward:开,但没有可用的规则,出错时不会自动续跑`;
100
+ }
101
+
102
+ export function statusNotice(settings: Settings, progress: Progress, note?: string): Notice {
103
+ return { message: statusText(settings, progress, note), level: needsFix(settings) ? "warning" : "info" };
104
+ }
105
+
106
+ /**
107
+ * `/onward status`:标题一行,正在续跑时下一行是进度;再是规则没写的参数和设置文件,最后一行是下一步。
108
+ * `note` 是刚做完的事,跟在标题后面。
109
+ */
110
+ function statusText(settings: Settings, { used, streak }: Progress, note?: string): string {
111
+ const { config, source } = settings;
112
+ const lines = [statusHeadline(settings), ...(note ? [note] : [])];
113
+ if (used || streak) lines.push(`上次正常返回之后已续跑 ${used} 次,同一个错误连续 ${streak} 次`);
114
+ const usable = source.kind !== "broken" && !config.problems.length;
115
+ if (usable) lines.push(...section("规则没写的参数", table(policyRows(resolvePolicy(config.defaults)))));
116
+ lines.push(...section("设置文件", fileLines(settings)), "");
117
+ if (!usable) lines.push(`改好之后 /${COMMAND} reload;问题见 /${COMMAND} show`);
118
+ else if (!config.enabled) lines.push(`/${COMMAND} on 打开`);
119
+ else if (!usableRules(config)) lines.push(addRules());
120
+ else lines.push(`规则见 /${COMMAND} show rules`);
121
+ return lines.join("\n");
122
+ }
123
+
124
+ /** 设置文件在哪、能不能读。 */
125
+ function fileLines({ source, path }: Settings): string[] {
126
+ switch (source.kind) {
127
+ case "file":
128
+ return [` ${path}`];
129
+ case "none":
130
+ return [` ${path}(还没有,改设置时自动建)`];
131
+ case "broken":
132
+ return [` ${path}`, ` 读不了:${source.error}`];
133
+ }
134
+ }
135
+
136
+ /** `/onward show`:每个参数的值和它从哪来,再是规则,最后是设置文件。 */
137
+ export function showNotice(settings: Settings): Notice {
138
+ if (settings.source.kind === "broken") return rulesNotice(settings);
139
+ const { defaults } = settings.config;
140
+ const rows = FIELDS.map((item): [string, string] => {
141
+ const set = Object.hasOwn(defaults, item.name);
142
+ const value = (set ? defaults : DEFAULT_POLICY)[item.name] as never;
143
+ return [item.name, `${(item as Field<typeof item.name>).show(value)}(${set ? "设置文件" : "内置默认值"})`];
144
+ });
145
+ return info(
146
+ [
147
+ "规则没写的参数",
148
+ ...table(rows),
149
+ "",
150
+ describeRules(settings.config),
151
+ ...section("设置文件", fileLines(settings)),
152
+ ].join("\n"),
153
+ );
154
+ }
155
+
156
+ /** `/onward show rules`。设置文件读不了时说读不了:规则一条也没读到,不是没写。 */
157
+ export function rulesNotice(settings: Settings): Notice {
158
+ if (settings.source.kind !== "broken") return info(describeRules(settings.config));
159
+ return info(
160
+ [`设置文件读不了,${UNTIL_FIXED}`, ...fileLines(settings), "", `改好之后 /${COMMAND} reload`].join("\n"),
161
+ );
162
+ }
163
+
164
+ /** 一次修改之后:写好了就是当前状态,`done` 跟在标题后面;否则说明为什么。 */
165
+ export function changedNotice(saved: Saved, settings: Settings, progress: Progress, done?: string): Notice {
166
+ switch (saved.kind) {
167
+ case "saved":
168
+ return statusNotice(settings, progress, done);
169
+ case "broken":
170
+ return warning(`${STOPPED} onward:${settings.path} 读不了(${saved.error}),先修好;未做任何修改`);
171
+ case "unwritten":
172
+ return warning(
173
+ `onward:设置没能保存(${saved.error}),这次运行仍按改过的设置走\n${statusText(settings, progress)}`,
174
+ );
175
+ }
176
+ }
177
+
178
+ // ── 设置说明 ──
179
+
180
+ /** 一组参数:怎么续跑、上限、间隔。`stop` 不续跑,只有一行。 */
181
+ function policyRows(policy: Policy): [string, string][] {
182
+ if (policy.action === "stop") return [["做法", "命中就停,只提醒,不续跑"]];
183
+ return [
184
+ ["做法", policy.action === "resend" ? "静默重发同一个请求" : `发「${policy.prompt}」`],
185
+ ["上限", `最多 ${policy.maxRetries} 次;同一个错误连续 ${policy.maxSameError} 次后也停`],
186
+ ["间隔", describeDelay(policy)],
187
+ ];
188
+ }
189
+
190
+ /**
191
+ * 间隔表:列到不再变为止,后面的说「之后每次」;太长的中间用 … 省掉。单位都一样时只在最后写一次。
192
+ * 例如 `3 → 6 → 9 → 12 → 15 秒,之后每次 15 秒;50 次合计约 12 分`。
193
+ */
194
+ export function describeDelay(policy: Policy): string {
195
+ const count = policy.maxRetries;
196
+ const steps = Array.from({ length: count }, (_, i) => retryDelay(i + 1, policy.delay));
197
+ // 从这一次起间隔不再变。
198
+ let flat = count - 1;
199
+ while (flat > 0 && steps[flat - 1] === steps[count - 1]) flat--;
200
+ const total = `${count} 次合计约 ${formatDelay(totalDelay(count, policy.delay))}`;
201
+ if (count === 1) return formatDelay(steps[0]!);
202
+ if (flat === 0) return `每次 ${formatDelay(steps[0]!)};${total}`;
203
+ const shown = steps.slice(0, flat + 1);
204
+ const head = shown.length > 7 ? [...shown.slice(0, 5), undefined, shown.at(-1)!] : shown;
205
+ const tail = flat < count - 1 ? `,之后每次 ${formatDelay(steps[count - 1]!)}` : "";
206
+ return `${sequence(head)}${tail};${total}`;
207
+ }
208
+
209
+ /** `undefined` 是省掉的那段。单位都一样时数字之间不重复单位:`3 → 6 → 9 秒`。 */
210
+ function sequence(values: (number | undefined)[]): string {
211
+ const texts = values.map((ms) => (ms === undefined ? "…" : formatDelay(ms)));
212
+ const unit = (text: string) => /^[\d.]+ (毫秒|秒|分)$/.exec(text)?.[1];
213
+ const units = new Set(texts.filter((text) => text !== "…").map(unit));
214
+ if (units.size !== 1 || units.has(undefined)) return texts.join(" → ");
215
+ const [only] = units;
216
+ return `${texts.map((text) => text.replace(` ${only}`, "")).join(" → ")} ${only}`;
217
+ }
218
+
219
+ /** `/onward show rules` 的全文。有问题时只列问题:规则反正不生效,列出来反而像在跑。 */
220
+ export function describeRules(config: Config): string {
221
+ if (config.problems.length)
222
+ return `设置文件有 ${config.problems.length} 处问题,${UNTIL_FIXED}:\n${config.problems.map((p) => `- ${p}`).join("\n")}\n改完 /${COMMAND} reload`;
223
+ if (!config.rules.length) return `没有可用的规则,出错时不会自动续跑。${addRules()}`;
224
+ const blocks = config.rules.map((rule, index) => {
225
+ const rows: [string, string][] = [
226
+ ["条件", describeWhen(rule)],
227
+ ...policyRows(resolvePolicy(config.defaults, rule.patch)),
228
+ ];
229
+ return [
230
+ `${index + 1}. ${rule.name}${rule.enabled ? "" : "(已停用)"}`,
231
+ ...table(rows).map((line) => ` ${line}`),
232
+ ];
233
+ });
234
+ return ["规则(按顺序,第一条命中的生效;没命中的错误不处理)", ...blocks.flat()].join("\n");
235
+ }
236
+
237
+ function describeWhen({ when }: Rule): string {
238
+ const parts = [
239
+ when.error && `错误匹配 /${when.error.source}/i`,
240
+ when.provider && `provider=${when.provider}`,
241
+ when.model && `model=${when.model}`,
242
+ ].filter(Boolean);
243
+ return parts.length ? parts.join(",") : "任何错误";
244
+ }
245
+
246
+ /** 文件读不了,或者内容有读不懂的地方。 */
247
+ function needsFix(settings: Settings): boolean {
248
+ return settings.source.kind === "broken" || settings.config.problems.length > 0;
249
+ }
250
+
251
+ function usableRules(config: Config): number {
252
+ return config.rules.filter((rule) => rule.enabled).length;
253
+ }
254
+
255
+ // ── 运行中的通知 ──
256
+
257
+ /** 启动时值得说的事:设置文件读不了或有问题(关着也说,可能就是 enabled 写错了)、没有可用的规则。 */
258
+ export function startupNotices(settings: Settings): Notice[] {
259
+ const { config, source, path } = settings;
260
+ if (source.kind === "broken") return [warning(`${STOPPED} onward:${path} 读不了:${source.error},${UNTIL_FIXED}`)];
261
+ if (config.problems.length)
262
+ return [
263
+ warning(
264
+ `${STOPPED} onward:设置文件有 ${config.problems.length} 处问题,${UNTIL_FIXED}(/${COMMAND} show 查看)`,
265
+ ),
266
+ ];
267
+ if (config.enabled && !usableRules(config))
268
+ return [info(`${IDLE} onward:没有可用的规则,出错时不会自动续跑;${addRules(` ${path} `)}`)];
269
+ return [];
270
+ }
271
+
272
+ /** 和状态栏同一个写法:`⏩ onward:续跑 1/20 · auth,3 秒后静默重发`。错误本身 pi 已经显示过了。 */
273
+ /** 状态栏已经写了第几次、哪条规则,这里只说接下来做什么:`onward:3 秒后静默重发`。 */
274
+ export function retryNotice(step: Retry, draft: Continue): Notice {
275
+ const action = draft.type === "context_edit" ? "静默重发" : `发「${truncate(draft.content, 30)}」`;
276
+ return info(`onward:${formatDelay(step.delay)}后${action}`);
277
+ }
278
+
279
+ /** 状态栏已经写了停了、哪条规则,这里只说为什么停、怎么办。 */
280
+ export function giveUpNotice(step: GiveUp): Notice {
281
+ const again = ";发任意消息重新计数";
282
+ switch (step.reason) {
283
+ case "stop":
284
+ return warning("onward:这条规则只提醒,需要你自己处理");
285
+ case "same-error":
286
+ return warning(`onward:同一个错误已连续 ${step.streak} 次${again}`);
287
+ case "budget":
288
+ return warning(`onward:已续跑 ${step.attempt} 次仍未恢复${again}`);
289
+ }
290
+ }
291
+
292
+ /** 状态栏:正在续跑第几次。 */
293
+ export function retryStatus(hit: Hit, step: Retry): string {
294
+ return `${RUNNING} ${progressText(hit.rule.name, step.attempt, hit.policy.maxRetries)}`;
295
+ }
296
+
297
+ /** 状态栏:停了,留到恢复或用户发新消息。 */
298
+ export function giveUpStatus(hit: Hit, step: GiveUp): string {
299
+ return `${STOPPED} ${step.reason === "stop" ? "不续跑" : "续跑已停"} · ${hit.rule.name}`;
300
+ }
301
+
302
+ /** 续跑消息在会话里的标签;`details` 来自会话记录,旧的或别处写的可能不全。 */
303
+ export function continueLabel(details: unknown): string {
304
+ if (!isRecord(details) || typeof details.rule !== "string") return `${RUNNING} onward`;
305
+ const { rule, attempt, max } = details;
306
+ return Number.isInteger(attempt) && Number.isInteger(max)
307
+ ? `${RUNNING} onward · ${progressText(rule, attempt as number, max as number)}`
308
+ : `${RUNNING} onward · ${rule}`;
309
+ }
310
+
311
+ function progressText(rule: string, attempt: number, max: number): string {
312
+ return `续跑 ${attempt}/${max} · ${rule}`;
313
+ }
314
+
315
+ /** 归一化后的错误摘要,不带每次都变的 request id。 */
316
+ export function errorExcerpt(failure: Failure, limit = 40): string {
317
+ return truncate(errorSignature(failure), limit);
318
+ }
319
+
320
+ function truncate(text: string, limit: number): string {
321
+ return text.length <= limit ? text : `${text.slice(0, limit - 1)}…`;
322
+ }