@cobia/pi-onward 0.3.1 → 0.4.1
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.
- package/README.md +186 -171
- package/docs/actions.md +97 -0
- package/example.json +18 -57
- package/onward.schema.json +86 -90
- package/package.json +9 -2
- package/src/actions/builtins.ts +25 -0
- package/src/actions/pi.ts +70 -0
- package/src/actions/protocol.ts +136 -0
- package/src/actions/registry.ts +112 -0
- package/src/extension/autocomplete.ts +1 -3
- package/src/extension/command.ts +157 -184
- package/src/extension/index.ts +1 -12
- package/src/extension/install.ts +10 -7
- package/src/extension/render.ts +2 -10
- package/src/extension/settings.ts +81 -77
- package/src/extension/text.ts +309 -438
- package/src/policy/config.ts +35 -85
- package/src/policy/delay.ts +10 -27
- package/src/policy/failure.ts +3 -31
- package/src/policy/policy.ts +63 -157
- package/src/policy/rules.ts +124 -101
- package/src/policy/schema.ts +65 -72
- package/src/runtime/episode.ts +19 -0
- package/src/runtime/recovery.ts +470 -0
- package/src/runtime/task-prompt.ts +82 -0
- package/src/extension/onward.ts +0 -208
- package/src/policy/tracker.ts +0 -64
package/src/policy/config.ts
CHANGED
|
@@ -1,122 +1,72 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 设置文件的模型:顶层写的参数就是每条规则的默认值,规则里同名的字段覆盖它。
|
|
3
|
-
*
|
|
4
|
-
* ```jsonc
|
|
5
|
-
* {
|
|
6
|
-
* "enabled": true,
|
|
7
|
-
* "action": "message", "maxRetries": 10,
|
|
8
|
-
* "rules": [{ "name": "auth", "when": { "failure": "401" }, "action": "resend", "maxRetries": 20 }]
|
|
9
|
-
* }
|
|
10
|
-
* ```
|
|
11
|
-
*
|
|
12
|
-
* 设置可以分几份文件写:每份先各自读成一层(`parseLayer`),再按顺序合并(`mergeLayers`),后面的层覆盖前面的:
|
|
13
|
-
* 顶层的字段逐个覆盖,`rules` 整份替换。规则按顺序第一条命中、不能重名,拼在一起时顺序和重名都说不清。
|
|
14
|
-
*
|
|
15
|
-
* 读不懂的内容(拼错的键、超出范围的值、重名的规则)都记成问题。有问题时整份设置不生效,修好之前
|
|
16
|
-
* 不会自动续跑:丢掉一部分、其余照跑,会让错误落到更宽的规则或默认值上,多发真实请求。
|
|
17
|
-
*/
|
|
1
|
+
/** Global then project settings. Rules replace as a whole; malformed layers never partially activate. */
|
|
18
2
|
import { type AgentMessage, type Failure, isFailure } from "./failure.ts";
|
|
19
|
-
import { FIELD_NAMES, type
|
|
20
|
-
import { findRule, parseRules, type Rule, ruleWarnings } from "./rules.ts";
|
|
3
|
+
import { FIELD_NAMES, type Limits, type LimitsPatch, readLimits, resolveLimits } from "./policy.ts";
|
|
4
|
+
import { findRule, parseRules, type Rule, ruleWarnings, type Stage, selectStage, unknownKeys } from "./rules.ts";
|
|
21
5
|
|
|
22
6
|
export interface Config {
|
|
23
7
|
enabled: boolean;
|
|
24
|
-
/** 启动时的提示显示不显示;只来自全局设置,没写时跟着 pi 的 quietStartup。 */
|
|
25
8
|
quietStartup?: boolean;
|
|
26
|
-
|
|
27
|
-
defaults: PolicyPatch;
|
|
9
|
+
limits: LimitsPatch;
|
|
28
10
|
rules: Rule[];
|
|
29
|
-
/** 读不懂的内容;不为空时整份设置不生效。 */
|
|
30
11
|
problems: string[];
|
|
31
12
|
}
|
|
32
|
-
|
|
33
|
-
export const CONFIG_KEYS: ReadonlySet<string> = new Set([
|
|
34
|
-
"$schema",
|
|
35
|
-
"enabled",
|
|
36
|
-
"quietStartup",
|
|
37
|
-
"rules",
|
|
38
|
-
...FIELD_NAMES,
|
|
39
|
-
]);
|
|
40
|
-
|
|
41
|
-
/** 一份设置文件读出来的内容:只有写了的字段。 */
|
|
42
13
|
export interface ConfigLayer {
|
|
43
14
|
enabled?: boolean;
|
|
44
15
|
quietStartup?: boolean;
|
|
45
|
-
|
|
46
|
-
/** 写了 `rules` 才有,空数组也算写了:合并时整份替换前面的。 */
|
|
16
|
+
limits: LimitsPatch;
|
|
47
17
|
rules?: Rule[];
|
|
48
18
|
problems: string[];
|
|
49
19
|
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* `raw` 是一份设置文件的内容。不抛,读不懂的记进 problems。`project`:这是项目级的一份,不能写 quietStartup:
|
|
53
|
-
* 不然别人仓库里的设置能关掉「用上了项目级设置」这句提醒。
|
|
54
|
-
*/
|
|
20
|
+
export const CONFIG_KEYS = new Set(["$schema", "enabled", "quietStartup", "rules", ...FIELD_NAMES]);
|
|
55
21
|
export function parseLayer(raw: Record<string, unknown>, project = false): ConfigLayer {
|
|
56
22
|
const problems: string[] = [];
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
if (
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
23
|
+
unknownKeys(raw, CONFIG_KEYS, "", problems);
|
|
24
|
+
if (raw.enabled !== undefined && typeof raw.enabled !== "boolean") problems.push("enabled must be true or false");
|
|
25
|
+
if (raw.quietStartup !== undefined) {
|
|
26
|
+
if (project) problems.push("quietStartup is only allowed in global settings");
|
|
27
|
+
else if (typeof raw.quietStartup !== "boolean") problems.push("quietStartup must be true or false");
|
|
28
|
+
}
|
|
29
|
+
const limits = readLimits(raw, problems);
|
|
63
30
|
const rules = raw.rules === undefined ? undefined : parseRules(raw.rules, problems);
|
|
64
31
|
return {
|
|
65
32
|
...(typeof raw.enabled === "boolean" && { enabled: raw.enabled }),
|
|
66
|
-
...(!project && typeof
|
|
67
|
-
|
|
33
|
+
...(!project && typeof raw.quietStartup === "boolean" && { quietStartup: raw.quietStartup }),
|
|
34
|
+
limits,
|
|
68
35
|
...(rules && { rules }),
|
|
69
36
|
problems,
|
|
70
37
|
};
|
|
71
38
|
}
|
|
72
|
-
|
|
73
|
-
/** 后面的层覆盖前面的:顶层字段逐个覆盖,`rules` 整份替换;问题都留着,任何一层有问题整份设置都不生效。 */
|
|
74
39
|
export function mergeLayers(layers: readonly ConfigLayer[]): Config {
|
|
75
|
-
|
|
76
|
-
let quietStartup: boolean | undefined;
|
|
77
|
-
let defaults: PolicyPatch = {};
|
|
78
|
-
let rules: Rule[] = [];
|
|
79
|
-
const problems: string[] = [];
|
|
40
|
+
const config: Config = { enabled: true, limits: {}, rules: [], problems: [] };
|
|
80
41
|
for (const layer of layers) {
|
|
81
|
-
if (layer.enabled !== undefined) enabled = layer.enabled;
|
|
82
|
-
if (layer.quietStartup !== undefined) quietStartup = layer.quietStartup;
|
|
83
|
-
|
|
84
|
-
if (layer.rules) rules = layer.rules;
|
|
85
|
-
problems.push(...layer.problems);
|
|
42
|
+
if (layer.enabled !== undefined) config.enabled = layer.enabled;
|
|
43
|
+
if (layer.quietStartup !== undefined) config.quietStartup = layer.quietStartup;
|
|
44
|
+
Object.assign(config.limits, layer.limits);
|
|
45
|
+
if (layer.rules !== undefined) config.rules = layer.rules;
|
|
46
|
+
config.problems.push(...layer.problems);
|
|
86
47
|
}
|
|
87
|
-
return
|
|
48
|
+
return config;
|
|
88
49
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
export function isActive(config: Config): boolean {
|
|
92
|
-
return config.enabled && config.problems.length === 0;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/** 只诊断合并后实际采用的规则;有配置错误时先修错,不对部分解析结果给提醒。 */
|
|
96
|
-
export function configWarnings(config: Config): string[] {
|
|
97
|
-
return config.problems.length ? [] : ruleWarnings(config.rules, config.defaults);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** 写回设置文件时的键顺序:`$schema`、`enabled`、参数、`quietStartup`、其他、`rules`。 */
|
|
50
|
+
export const isActive = (config: Config): boolean => config.enabled && !config.problems.length;
|
|
51
|
+
export const configWarnings = (config: Config): string[] => (config.problems.length ? [] : ruleWarnings(config.rules));
|
|
101
52
|
export function fileOrder(raw: Record<string, unknown>): Record<string, unknown> {
|
|
102
53
|
const first = ["$schema", "enabled", ...FIELD_NAMES, "quietStartup"];
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
54
|
+
return Object.fromEntries(
|
|
55
|
+
[
|
|
56
|
+
...first.filter((key) => key in raw),
|
|
57
|
+
...Object.keys(raw).filter((key) => !first.includes(key) && key !== "rules"),
|
|
58
|
+
...("rules" in raw ? ["rules"] : []),
|
|
59
|
+
].map((key) => [key, raw[key]]),
|
|
60
|
+
);
|
|
109
61
|
}
|
|
110
|
-
|
|
111
|
-
/** 一次失败命中了哪条规则,按什么参数处理。 */
|
|
112
62
|
export interface Hit {
|
|
113
63
|
rule: Rule;
|
|
114
|
-
|
|
64
|
+
stage: Stage;
|
|
115
65
|
failure: Failure;
|
|
66
|
+
limits: Limits;
|
|
116
67
|
}
|
|
117
|
-
|
|
118
|
-
export function matchFailure(config: Config, message: AgentMessage | undefined): Hit | undefined {
|
|
68
|
+
export function matchFailure(config: Config, message: AgentMessage | undefined, failures: number): Hit | undefined {
|
|
119
69
|
if (!isActive(config) || !isFailure(message)) return undefined;
|
|
120
70
|
const rule = findRule(config.rules, message);
|
|
121
|
-
return rule && { rule,
|
|
71
|
+
return rule && { rule, stage: selectStage(rule, failures), failure: message, limits: resolveLimits(config.limits) };
|
|
122
72
|
}
|
package/src/policy/delay.ts
CHANGED
|
@@ -1,22 +1,13 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 重试间隔 `delay`,一个带单位的字符串,设置文件和命令写法一样:
|
|
3
|
-
* - `5s,10s,30s`:按列表来,最后一个值重复;
|
|
4
|
-
* - `3s..15s`:按次数增长,第 n 次等 min(3 秒 × n, 15 秒)。
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
1
|
/** 单个间隔的上限,防止手滑写成几小时。 */
|
|
8
2
|
const MAX_DELAY_MS = 3_600_000;
|
|
9
3
|
const MAX_STEPS = 20;
|
|
10
4
|
|
|
11
5
|
export type Delay = { kind: "list"; steps: readonly number[] } | { kind: "ramp"; step: number; cap: number };
|
|
12
6
|
|
|
13
|
-
export const DELAY_SYNTAX = "5s,10s,30s
|
|
14
|
-
const MALFORMED =
|
|
7
|
+
export const DELAY_SYNTAX = "5s,10s,30s or 3s..15s";
|
|
8
|
+
const MALFORMED = `must use ${DELAY_SYNTAX}, with ms, s, or m on each value`;
|
|
15
9
|
|
|
16
|
-
/**
|
|
17
|
-
* JSON Schema 里的写法:单个值、逗号分隔的列表,或者 `起步..封顶`,每个值带单位。只管写法:封顶不小于起步、最多
|
|
18
|
-
* 几个值、每个值不超过一小时,由 parseDelay 检查。
|
|
19
|
-
*/
|
|
10
|
+
/** Schema 只校验格式;时长、列表长度与区间关系由 parseDelay 校验。 */
|
|
20
11
|
const DURATION = "\\d+(\\.\\d+)?(ms|s|m)";
|
|
21
12
|
export const DELAY_PATTERN = `^\\s*(${DURATION}\\.\\.${DURATION}|${DURATION}(\\s*,\\s*${DURATION})*)\\s*$`;
|
|
22
13
|
|
|
@@ -28,44 +19,36 @@ export function parseDelay(text: string): Delay | string {
|
|
|
28
19
|
const step = parseDuration(range[1]!);
|
|
29
20
|
const cap = parseDuration(range[2]!);
|
|
30
21
|
if (step === undefined || cap === undefined) return MALFORMED;
|
|
31
|
-
if (step <= 0 || cap < step) return "
|
|
22
|
+
if (step <= 0 || cap < step) return "ramp start must be positive and the cap must not be smaller than the start";
|
|
32
23
|
return { kind: "ramp", step, cap };
|
|
33
24
|
}
|
|
34
25
|
const parts = value.split(",").map((part) => part.trim());
|
|
35
26
|
const steps = parts.map(parseDuration);
|
|
36
27
|
if (!value || steps.some((ms) => ms === undefined)) return MALFORMED;
|
|
37
|
-
if (steps.length > MAX_STEPS) return
|
|
28
|
+
if (steps.length > MAX_STEPS) return `must contain at most ${MAX_STEPS} delay values`;
|
|
38
29
|
return { kind: "list", steps: steps as number[] };
|
|
39
30
|
}
|
|
40
31
|
|
|
41
|
-
/**
|
|
32
|
+
/** attempt 从 1 开始。 */
|
|
42
33
|
export function retryDelay(attempt: number, delay: Delay): number {
|
|
43
34
|
if (delay.kind === "list") return delay.steps[Math.min(attempt, delay.steps.length) - 1]!;
|
|
44
35
|
return Math.min(delay.step * attempt, delay.cap);
|
|
45
36
|
}
|
|
46
37
|
|
|
47
|
-
/**
|
|
48
|
-
export function totalDelay(count: number, delay: Delay): number {
|
|
49
|
-
let sum = 0;
|
|
50
|
-
for (let n = 1; n <= count; n++) sum += retryDelay(n, delay);
|
|
51
|
-
return sum;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** 写回设置文件的样子:`3s..15s`、`30s,1m,2m`。 */
|
|
38
|
+
/** 配置文件使用的带单位写法。 */
|
|
55
39
|
export function delayText(delay: Delay): string {
|
|
56
40
|
return delay.kind === "ramp"
|
|
57
41
|
? `${duration(delay.step)}..${duration(delay.cap)}`
|
|
58
42
|
: delay.steps.map(duration).join(",");
|
|
59
43
|
}
|
|
60
44
|
|
|
61
|
-
/** 毫秒 → 最短的带单位写法:`500ms`、`1.5s`、`2m`。 */
|
|
62
45
|
function duration(ms: number): string {
|
|
63
46
|
if (ms !== 0 && ms % 60_000 === 0) return `${ms / 60_000}m`;
|
|
64
47
|
if (ms % 1000 === 0) return `${ms / 1000}s`;
|
|
65
48
|
return ms < 1000 ? `${ms}ms` : `${ms / 1000}s`;
|
|
66
49
|
}
|
|
67
50
|
|
|
68
|
-
/**
|
|
51
|
+
/** 供界面展示,不用于写回配置。 */
|
|
69
52
|
export function formatDelay(ms: number): string {
|
|
70
53
|
if (ms < 1000) return `${ms} 毫秒`;
|
|
71
54
|
if (ms < 60_000) return ms % 1000 === 0 ? `${ms / 1000} 秒` : `${(ms / 1000).toFixed(1)} 秒`;
|
|
@@ -76,8 +59,8 @@ export function formatDelay(ms: number): string {
|
|
|
76
59
|
|
|
77
60
|
const UNIT_MS = { ms: 1, s: 1000, m: 60_000 } as const;
|
|
78
61
|
|
|
79
|
-
/**
|
|
80
|
-
function parseDuration(text: string): number | undefined {
|
|
62
|
+
/** 带单位时长转毫秒,超过一小时返回 undefined。 */
|
|
63
|
+
export function parseDuration(text: string): number | undefined {
|
|
81
64
|
const match = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(text);
|
|
82
65
|
if (!match) return undefined;
|
|
83
66
|
const ms = Math.round(Number(match[1]) * UNIT_MS[match[2] as keyof typeof UNIT_MS]);
|
package/src/policy/failure.ts
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
|
-
/** 什么算失败、什么算恢复,以及两次失败算不算「同一个错误」。 */
|
|
2
1
|
import type { MessageEndEvent } from "@earendil-works/pi-coding-agent";
|
|
3
2
|
|
|
4
|
-
/** pi 的会话消息;只取类型,运行时不碰 pi。 */
|
|
5
3
|
export type AgentMessage = MessageEndEvent["message"];
|
|
6
4
|
type AssistantMessage = Extract<AgentMessage, { role: "assistant" }>;
|
|
7
5
|
|
|
8
|
-
/** 以错误结束的助手消息。provider、model 是 pi 必填的;errorMessage 可能没有。 */
|
|
9
6
|
export type ErrorReply = AssistantMessage & { stopReason: "error" };
|
|
10
7
|
|
|
11
|
-
/**
|
|
8
|
+
/** 正常结束但无文字、无工具调用;思考与空白不算输出。 */
|
|
12
9
|
export type EmptyReply = AssistantMessage & { stopReason: "stop" };
|
|
13
10
|
|
|
14
|
-
/** 规则要处理的两种收尾:出错,或者空回复。 */
|
|
15
11
|
export type Failure = ErrorReply | EmptyReply;
|
|
16
12
|
|
|
17
13
|
/** 用户按 Esc 是 `aborted`,不算失败。 */
|
|
@@ -19,7 +15,6 @@ export function isError(message: AgentMessage | undefined): message is ErrorRepl
|
|
|
19
15
|
return message?.role === "assistant" && message.stopReason === "error";
|
|
20
16
|
}
|
|
21
17
|
|
|
22
|
-
/** 只有空白的文字、只有思考也算空:用户什么都没看到。 */
|
|
23
18
|
export function isEmptyReply(message: AgentMessage | undefined): message is EmptyReply {
|
|
24
19
|
if (message?.role !== "assistant" || message.stopReason !== "stop") return false;
|
|
25
20
|
return !message.content.some(
|
|
@@ -31,7 +26,7 @@ export function isFailure(message: AgentMessage | undefined): message is Failure
|
|
|
31
26
|
return isError(message) || isEmptyReply(message);
|
|
32
27
|
}
|
|
33
28
|
|
|
34
|
-
/**
|
|
29
|
+
/** 匹配文本:空回复用空串,缺少文案的错误用非空占位;其余保留原文。 */
|
|
35
30
|
export function failureText(failure: Failure): string {
|
|
36
31
|
if (failure.stopReason === "stop") return "";
|
|
37
32
|
const text = failure.errorMessage ?? "";
|
|
@@ -40,32 +35,9 @@ export function failureText(failure: Failure): string {
|
|
|
40
35
|
|
|
41
36
|
const SUCCESS: ReadonlySet<AssistantMessage["stopReason"]> = new Set(["stop", "length", "toolUse", "deferred"]);
|
|
42
37
|
|
|
43
|
-
/**
|
|
38
|
+
/** 正常回复(包括工具轮)结束恢复;空回复不算成功。 */
|
|
44
39
|
export function isSuccess(message: AgentMessage): boolean {
|
|
45
40
|
return message.role === "assistant" && SUCCESS.has(message.stopReason) && !isEmptyReply(message);
|
|
46
41
|
}
|
|
47
42
|
|
|
48
|
-
/**
|
|
49
|
-
* 中转常把 request id、UUID、时间戳、长十六进制串塞进错误文案,每次都不一样;
|
|
50
|
-
* 不抹掉的话同一个错误永远只出现一次,同错上限就触发不了。
|
|
51
|
-
*/
|
|
52
|
-
export function normalizeError(text: string): string {
|
|
53
|
-
return text
|
|
54
|
-
.replace(/\s+/g, " ")
|
|
55
|
-
.trim()
|
|
56
|
-
.toLowerCase()
|
|
57
|
-
.replace(/request[\s_-]*id\s*[:=]?\s*[^\s,;)]+/g, "request-id")
|
|
58
|
-
.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g, "uuid")
|
|
59
|
-
.replace(/\b\d{10,}\b/g, "num")
|
|
60
|
-
.replace(/\b(?=[0-9a-f]{12,}\b)[0-9a-f]*[a-f][0-9a-f]*\b/g, "id");
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export function errorSignature(failure: Failure): string {
|
|
64
|
-
if (failure.stopReason === "stop") return EMPTY_REPLY;
|
|
65
|
-
return normalizeError(failure.errorMessage ?? "") || UNKNOWN_ERROR;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
43
|
const UNKNOWN_ERROR = "未知错误";
|
|
69
|
-
|
|
70
|
-
/** 空回复的「错误摘要」:提示词里的 {error}、同错计数都用它。 */
|
|
71
|
-
export const EMPTY_REPLY = "空回复";
|
package/src/policy/policy.ts
CHANGED
|
@@ -1,173 +1,79 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
export interface Policy {
|
|
11
|
-
action: Action;
|
|
12
|
-
/** message 发的消息,可含 {attempt} {max} {error} {rule}。 */
|
|
13
|
-
prompt: string;
|
|
14
|
-
/** 连续失败时最多续跑几次,正常返回一次就从头算。 */
|
|
15
|
-
maxRetries: number;
|
|
16
|
-
/** 同一个错误最多续跑几次:连续出现超过这么多次就彻底停。 */
|
|
17
|
-
maxSameError: number;
|
|
18
|
-
delay: Delay;
|
|
1
|
+
/** Recovery-wide limits. Stages own their actions and delays; there are no inherited action parameters. */
|
|
2
|
+
import { formatDelay, parseDuration } from "./delay.ts";
|
|
3
|
+
|
|
4
|
+
export interface Limits {
|
|
5
|
+
maxFailures: number;
|
|
6
|
+
maxHandoffs: number;
|
|
7
|
+
/** Maximum execution time of one action, in milliseconds. Waiting delay is separate. */
|
|
8
|
+
actionTimeout: number;
|
|
19
9
|
}
|
|
20
|
-
|
|
21
|
-
export
|
|
22
|
-
|
|
23
|
-
export interface Field<K extends keyof Policy = keyof Policy> {
|
|
10
|
+
export type LimitsPatch = Partial<Limits>;
|
|
11
|
+
export interface Field<K extends keyof Limits = keyof Limits> {
|
|
24
12
|
name: K;
|
|
25
|
-
/** 帮助里的写法。 */
|
|
26
13
|
syntax: string;
|
|
27
14
|
description: string;
|
|
28
|
-
|
|
29
|
-
appliesTo?: readonly Action[];
|
|
30
|
-
/** 补全的候选值。 */
|
|
31
|
-
choices?: readonly { value: string; description: string }[];
|
|
32
|
-
/** 设置文件里的值;合法时返回 value,否则返回原因。 */
|
|
33
|
-
read(value: unknown): { value: Policy[K] } | { problem: string };
|
|
34
|
-
/** 命令里的文字 → 设置文件里的值。 */
|
|
15
|
+
read(value: unknown): { value: Limits[K] } | { problem: string };
|
|
35
16
|
fromText(text: string): unknown;
|
|
36
|
-
|
|
37
|
-
show(value: Policy[K]): string;
|
|
38
|
-
/** 设置文件里这个字段的 JSON Schema:和 `read` 收下的一致,只管写法,含义上的检查留给 `read`。 */
|
|
17
|
+
show(value: Limits[K]): string;
|
|
39
18
|
schema: Readonly<Record<string, unknown>>;
|
|
40
19
|
}
|
|
41
20
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
{ value:
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
21
|
+
export const DEFAULT_LIMITS: Readonly<Limits> = Object.freeze({
|
|
22
|
+
maxFailures: 20,
|
|
23
|
+
maxHandoffs: 3,
|
|
24
|
+
actionTimeout: 30_000,
|
|
25
|
+
});
|
|
26
|
+
const integer =
|
|
27
|
+
(min: number, max: number) =>
|
|
28
|
+
(value: unknown): { value: number } | { problem: string } =>
|
|
29
|
+
Number.isSafeInteger(value) && (value as number) >= min && (value as number) <= max
|
|
30
|
+
? { value: value as number }
|
|
31
|
+
: { problem: `must be an integer between ${min} and ${max}` };
|
|
54
32
|
export const FIELDS: readonly Field[] = [
|
|
55
|
-
|
|
56
|
-
name: "
|
|
57
|
-
syntax:
|
|
58
|
-
description: "
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
ACTIONS.some((item) => item.value === v)
|
|
62
|
-
? { value: v as Action }
|
|
63
|
-
: { problem: "只能是 message、resend 或 stop" },
|
|
64
|
-
fromText: (text) => text,
|
|
65
|
-
show: String,
|
|
66
|
-
schema: { enum: ACTIONS.map((item) => item.value) },
|
|
67
|
-
}),
|
|
68
|
-
field({
|
|
69
|
-
name: "prompt",
|
|
70
|
-
appliesTo: ["message"],
|
|
71
|
-
syntax: "文字",
|
|
72
|
-
description: "message 发的消息,可含 {attempt} {max} {error} {rule}",
|
|
73
|
-
read: (v) =>
|
|
74
|
-
typeof v === "string" && v.trim() && v.trim().length <= PROMPT_MAX
|
|
75
|
-
? { value: v.trim() }
|
|
76
|
-
: { problem: `需要 1–${PROMPT_MAX} 字的文字` },
|
|
77
|
-
fromText: (text) => text,
|
|
78
|
-
show: (prompt) => `「${prompt}」`,
|
|
79
|
-
schema: { type: "string", pattern: "\\S", maxLength: PROMPT_MAX },
|
|
80
|
-
}),
|
|
81
|
-
field({
|
|
82
|
-
name: "maxRetries",
|
|
83
|
-
appliesTo: ["message", "resend"],
|
|
84
|
-
syntax: `${RETRIES.min}–${RETRIES.max}`,
|
|
85
|
-
description: "连续失败时最多续跑几次",
|
|
86
|
-
read: (v) => integer(v, RETRIES.min, RETRIES.max),
|
|
87
|
-
fromText: number,
|
|
33
|
+
{
|
|
34
|
+
name: "maxFailures",
|
|
35
|
+
syntax: "1–1000",
|
|
36
|
+
description: "一次恢复过程最多处理多少次失败;超过后停止",
|
|
37
|
+
read: integer(1, 1000),
|
|
38
|
+
fromText: (text) => (/^\d+$/.test(text) ? Number(text) : text),
|
|
88
39
|
show: String,
|
|
89
|
-
schema: { type: "integer", minimum:
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
name: "
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
fromText: number,
|
|
40
|
+
schema: { type: "integer", minimum: 1, maximum: 1000 },
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: "maxHandoffs",
|
|
44
|
+
syntax: "0–50",
|
|
45
|
+
description: "恢复链最多跨会话接管多少次;0 禁止接管",
|
|
46
|
+
read: integer(0, 50),
|
|
47
|
+
fromText: (text) => (/^\d+$/.test(text) ? Number(text) : text),
|
|
98
48
|
show: String,
|
|
99
|
-
schema: { type: "integer", minimum:
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
name: "
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
49
|
+
schema: { type: "integer", minimum: 0, maximum: 50 },
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: "actionTimeout",
|
|
53
|
+
syntax: "30s",
|
|
54
|
+
description: "单次动作执行时限;超时结果未知,不自动重放",
|
|
55
|
+
read(value) {
|
|
56
|
+
const ms = typeof value === "string" ? parseDuration(value) : undefined;
|
|
57
|
+
return ms !== undefined && ms > 0
|
|
58
|
+
? { value: ms }
|
|
59
|
+
: { problem: "must be a positive duration no greater than 60m, using ms, s, or m" };
|
|
109
60
|
},
|
|
110
|
-
fromText:
|
|
111
|
-
show:
|
|
112
|
-
schema: { type: "string", pattern:
|
|
113
|
-
}
|
|
61
|
+
fromText: String,
|
|
62
|
+
show: formatDelay,
|
|
63
|
+
schema: { type: "string", pattern: "^\\d+(\\.\\d+)?(ms|s|m)$" },
|
|
64
|
+
},
|
|
114
65
|
];
|
|
115
|
-
|
|
116
|
-
export const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
export function
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
maxRetries: 10,
|
|
127
|
-
maxSameError: 10,
|
|
128
|
-
delay: { kind: "ramp", step: 3_000, cap: 15_000 },
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
/** 内置默认值 ← 设置文件顶层 ← 规则自己的字段。 */
|
|
132
|
-
export function resolvePolicy(defaults: PolicyPatch, rule: PolicyPatch = {}): Policy {
|
|
133
|
-
return { ...DEFAULT_POLICY, ...defaults, ...rule };
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* 读设置文件顶层或一条规则里的参数:合法的收下,不合法的记一条问题,不夹到范围内、也不退回默认值。
|
|
138
|
-
* 有问题的设置整份不生效(见 config.ts),所以这里不用分哪些字段要紧。不是参数的键交给调用方。
|
|
139
|
-
* `where` 是问题里的位置前缀,如 `rules[2](auth).`。
|
|
140
|
-
*/
|
|
141
|
-
export function readParams(raw: Record<string, unknown>, where: string, problems: string[]): PolicyPatch {
|
|
142
|
-
const patch: Record<string, unknown> = {};
|
|
143
|
-
for (const item of FIELDS) {
|
|
144
|
-
if (!Object.hasOwn(raw, item.name)) continue;
|
|
145
|
-
const result = item.read(raw[item.name]);
|
|
146
|
-
if ("value" in result) patch[item.name] = result.value;
|
|
147
|
-
else problems.push(`${where}${item.name} ${result.problem}`);
|
|
66
|
+
export const FIELD_NAMES = FIELDS.map((field) => field.name);
|
|
67
|
+
export const fieldNamed = (name: string): Field | undefined => FIELDS.find((field) => field.name === name);
|
|
68
|
+
export const resolveLimits = (patch: LimitsPatch): Limits => ({ ...DEFAULT_LIMITS, ...patch });
|
|
69
|
+
|
|
70
|
+
export function readLimits(raw: Record<string, unknown>, problems: string[]): LimitsPatch {
|
|
71
|
+
const patch: LimitsPatch = {};
|
|
72
|
+
for (const field of FIELDS) {
|
|
73
|
+
if (!Object.hasOwn(raw, field.name)) continue;
|
|
74
|
+
const result = field.read(raw[field.name]);
|
|
75
|
+
if ("problem" in result) problems.push(`${field.name} ${result.problem}`);
|
|
76
|
+
else patch[field.name] = result.value;
|
|
148
77
|
}
|
|
149
78
|
return patch;
|
|
150
79
|
}
|
|
151
|
-
|
|
152
|
-
export interface PromptVars {
|
|
153
|
-
attempt: number;
|
|
154
|
-
max: number;
|
|
155
|
-
error: string;
|
|
156
|
-
rule: string;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** 不认识的占位原样留着。 */
|
|
160
|
-
export function renderPrompt(template: string, vars: PromptVars): string {
|
|
161
|
-
return template.replace(/\{(attempt|max|error|rule)\}/g, (_, key: keyof PromptVars) => String(vars[key]));
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function integer(value: unknown, min: number, max: number): { value: number } | { problem: string } {
|
|
165
|
-
return Number.isInteger(value) && (value as number) >= min && (value as number) <= max
|
|
166
|
-
? { value: value as number }
|
|
167
|
-
: { problem: `需要 ${min}–${max} 的整数` };
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** 不是数字的文字原样交给 read,由它说明要什么。 */
|
|
171
|
-
function number(text: string): unknown {
|
|
172
|
-
return /^-?\d+(?:\.\d+)?$/.test(text) ? Number(text) : text;
|
|
173
|
-
}
|