@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,43 +1,36 @@
1
- /**
2
- * 规则 = 条件(when)+ 参数,按顺序第一条命中的生效。参数和设置文件顶层同名,只写和顶层不同的。
3
- * when.failure 统一用正则匹配失败文本:普通错误用原文,空回复用空串;不写就不限制失败类型。
4
- * 没有内置规则:没写或没命中,都不处理。无条件兜底必须显式写 action;读不懂的内容让整份设置不生效(见 config.ts)。
5
- * 遮挡和不适用的显式参数单独提醒,不影响设置生效,也不改变规则顺序。
6
- */
1
+ /** First matching rule wins. Within it, select the last stage whose inclusive threshold has been reached. */
2
+ import { ACTION_NAME_PATTERN, type ActionCall } from "../actions/protocol.ts";
7
3
  import { errorText, isRecord } from "../util.ts";
4
+ import { type Delay, parseDelay } from "./delay.ts";
8
5
  import { type Failure, failureText } from "./failure.ts";
9
- import { FIELD_NAMES, FIELDS, type PolicyPatch, readParams, resolvePolicy } from "./policy.ts";
10
6
 
11
7
  export interface RuleWhen {
12
- /** 大小写不敏感,对统一的失败文本匹配;读设置时编译一次。 */
13
8
  failure?: RegExp;
14
- /** 通配,只有 `*` 有特殊含义。 */
15
9
  provider?: string;
16
10
  model?: string;
17
11
  }
18
-
12
+ export interface Stage {
13
+ minFailures: number;
14
+ delay: Delay;
15
+ action: ActionCall;
16
+ }
19
17
  export interface Rule {
20
18
  name: string;
21
19
  enabled: boolean;
22
20
  when: RuleWhen;
23
- /** 规则自己写的参数,只覆盖写了的字段。 */
24
- patch: PolicyPatch;
21
+ stages: Stage[];
25
22
  }
26
-
27
- export const RULE_KEYS: ReadonlySet<string> = new Set(["name", "enabled", "when", ...FIELD_NAMES]);
28
-
23
+ export const RULE_KEYS = new Set(["name", "enabled", "when", "stages"]);
29
24
  export function findRule(rules: readonly Rule[], failure: Failure): Rule | undefined {
30
25
  return rules.find((rule) => rule.enabled && matches(rule.when, failure));
31
26
  }
32
-
33
27
  function matches(when: RuleWhen, failure: Failure): boolean {
34
- if (when.failure !== undefined && !when.failure.test(failureText(failure))) return false;
35
- if (when.provider !== undefined && !glob(when.provider, failure.provider)) return false;
36
- if (when.model !== undefined && !glob(when.model, failure.model)) return false;
37
- return true;
28
+ return (
29
+ (when.failure === undefined || when.failure.test(failureText(failure))) &&
30
+ (when.provider === undefined || glob(when.provider, failure.provider)) &&
31
+ (when.model === undefined || glob(when.model, failure.model))
32
+ );
38
33
  }
39
-
40
- /** 大小写不敏感,整串匹配。 */
41
34
  export function glob(pattern: string, value: string): boolean {
42
35
  const source = pattern
43
36
  .split("*")
@@ -45,104 +38,134 @@ export function glob(pattern: string, value: string): boolean {
45
38
  .join(".*");
46
39
  return new RegExp(`^${source}$`, "i").test(value);
47
40
  }
48
-
49
- /** 省略或空的 when 是无条件失败兜底;不猜测正则或通配条件的覆盖关系。 */
50
- function isFallbackWhen(when: unknown): boolean {
51
- return when === undefined || (isRecord(when) && Object.keys(when).length === 0);
41
+ export function selectStage(rule: Rule, failures: number): Stage {
42
+ for (let index = rule.stages.length - 1; index >= 0; index--) {
43
+ const stage = rule.stages[index]!;
44
+ if (stage.minFailures <= failures) return stage;
45
+ }
46
+ throw new Error("No recovery stage covers the current failure count");
52
47
  }
53
-
54
- /** 按合并后的参数诊断启用的规则;提醒不进入 problems,调用方不因此停用设置。 */
55
- export function ruleWarnings(rules: readonly Rule[], defaults: PolicyPatch): string[] {
56
- const warnings: string[] = [];
48
+ export function ruleWarnings(rules: readonly Rule[]): string[] {
57
49
  let fallback: string | undefined;
58
- for (const [index, rule] of rules.entries()) {
50
+ const warnings: string[] = [];
51
+ for (const rule of rules) {
59
52
  if (!rule.enabled) continue;
60
- const label = `rules[${index}](${rule.name})`;
61
- if (fallback !== undefined) warnings.push(`${label}被前面的兜底规则「${fallback}」挡住,不会命中`);
62
- if (fallback === undefined && isFallbackWhen(rule.when)) fallback = rule.name;
63
- const { action } = resolvePolicy(defaults, rule.patch);
64
- const unused = FIELDS.filter(
65
- (item) => Object.hasOwn(rule.patch, item.name) && item.appliesTo && !item.appliesTo.includes(action),
66
- ).map((item) => item.name);
67
- if (unused.length) warnings.push(`${label}的 ${unused.join("、")} 在 action=${action} 时不使用`);
53
+ if (fallback)
54
+ warnings.push(`Rule "${rule.name}" is shadowed by earlier catch-all rule "${fallback}" and cannot match`);
55
+ if (!fallback && !Object.keys(rule.when).length) fallback = rule.name;
68
56
  }
69
57
  return warnings;
70
58
  }
71
-
72
- /** 校验规则列表:读得懂的规则返回,读不懂的地方逐条记进 problems。 */
73
59
  export function parseRules(raw: unknown, problems: string[]): Rule[] {
74
- if (raw === undefined) return [];
75
60
  if (!Array.isArray(raw)) {
76
- problems.push("rules 需要数组");
61
+ problems.push("rules must be an array");
77
62
  return [];
78
63
  }
79
64
  const rules: Rule[] = [];
80
- for (const [index, item] of raw.entries()) {
81
- const rule = parseRule(item, index, problems);
82
- if (!rule) continue;
83
- if (rules.some((r) => r.name === rule.name)) problems.push(`rules[${index}] 与前面的规则重名(${rule.name})`);
84
- else rules.push(rule);
65
+ for (const [index, value] of raw.entries()) {
66
+ const label = `rules[${index}]`;
67
+ if (!isRecord(value)) {
68
+ problems.push(`${label} must be an object`);
69
+ continue;
70
+ }
71
+ const before = problems.length;
72
+ unknownKeys(value, RULE_KEYS, label, problems);
73
+ const name = value.name === undefined ? `rule-${index + 1}` : value.name;
74
+ if (typeof name !== "string" || !name.trim()) problems.push(`${label}.name must be a non-empty string`);
75
+ if (value.enabled !== undefined && typeof value.enabled !== "boolean")
76
+ problems.push(`${label}.enabled must be true or false`);
77
+ const when = parseWhen(value.when, `${label}.when`, problems);
78
+ const stages = parseStages(value.stages, `${label}.stages`, problems);
79
+ if (problems.length !== before || typeof name !== "string") continue;
80
+ if (rules.some((rule) => rule.name === name.trim()))
81
+ problems.push(`${label}.name duplicates an earlier rule name`);
82
+ else rules.push({ name: name.trim(), enabled: value.enabled !== false, when, stages });
85
83
  }
86
84
  return rules;
87
85
  }
88
-
89
- /** 一处读不懂就不返回这条规则,所有问题都记下来,一次改完。 */
90
- function parseRule(raw: unknown, index: number, problems: string[]): Rule | undefined {
91
- if (!isRecord(raw)) {
92
- problems.push(`rules[${index}] 不是对象`);
93
- return undefined;
86
+ function parseStages(raw: unknown, label: string, problems: string[]): Stage[] {
87
+ if (!Array.isArray(raw) || !raw.length) {
88
+ problems.push(`${label} must be a non-empty array`);
89
+ return [];
94
90
  }
95
- const before = problems.length;
96
- const name = ruleName(raw.name, index);
97
- if (name === undefined) problems.push(`rules[${index}].name 需要非空文字`);
98
- const label = name === undefined ? `rules[${index}].` : `rules[${index}](${name}).`;
99
- if (raw.enabled !== undefined && typeof raw.enabled !== "boolean")
100
- problems.push(`${label}enabled 需要 true 或 false`);
101
- const when = parseWhen(raw.when, `${label}when`, problems);
102
- const patch = readParams(raw, label, problems);
103
- if (isFallbackWhen(raw.when) && raw.action === undefined)
104
- problems.push(`${label}action 不能省略:兜底规则需要明确写 message、resend 或 stop`);
105
- for (const key of Object.keys(raw)) if (!RULE_KEYS.has(key)) problems.push(`${label}${key} 不认识`);
106
- // name 是 undefined 时已经记过问题,后一个条件只为收窄类型。
107
- if (problems.length > before || name === undefined) return undefined;
108
- return { name, enabled: raw.enabled !== false, when, patch };
109
- }
110
-
111
- /** 没写名字时按位置叫 `rule-1`、`rule-2`;写了但不是非空文字时返回 undefined。 */
112
- function ruleName(raw: unknown, index: number): string | undefined {
113
- if (raw === undefined) return `rule-${index + 1}`;
114
- return typeof raw === "string" && raw.trim() ? raw.trim() : undefined;
91
+ const stages: Stage[] = [];
92
+ let previous = 0;
93
+ for (const [index, value] of raw.entries()) {
94
+ const at = `${label}[${index}]`;
95
+ if (!isRecord(value)) {
96
+ problems.push(`${at} must be an object`);
97
+ continue;
98
+ }
99
+ const before = problems.length;
100
+ unknownKeys(value, new Set(["minFailures", "delay", "action"]), at, problems);
101
+ const minFailures = value.minFailures;
102
+ if (!Number.isSafeInteger(minFailures) || (minFailures as number) < 1 || (minFailures as number) > 1000)
103
+ problems.push(`${at}.minFailures must be an integer between 1 and 1000`);
104
+ else {
105
+ if (index === 0 && minFailures !== 1) problems.push(`${at}.minFailures must be 1 for the first stage`);
106
+ if ((minFailures as number) <= previous) problems.push(`${at}.minFailures must be strictly increasing`);
107
+ previous = minFailures as number;
108
+ }
109
+ const delay =
110
+ value.delay === undefined
111
+ ? parseDelay("0s")
112
+ : typeof value.delay === "string"
113
+ ? parseDelay(value.delay)
114
+ : "must be a delay string with units";
115
+ if (typeof delay === "string") problems.push(`${at}.delay ${delay}`);
116
+ const action = value.action;
117
+ if (!isRecord(action)) {
118
+ problems.push(`${at}.action must be an object with "use" and optional "with"`);
119
+ continue;
120
+ }
121
+ unknownKeys(action, new Set(["use", "with"]), `${at}.action`, problems);
122
+ if (typeof action.use !== "string" || !new RegExp(ACTION_NAME_PATTERN).test(action.use))
123
+ problems.push(`${at}.action.use must be a qualified action name such as onward.resend`);
124
+ if (action.with !== undefined && !isRecord(action.with)) problems.push(`${at}.action.with must be an object`);
125
+ if (problems.length === before && typeof delay !== "string")
126
+ stages.push({
127
+ minFailures: minFailures as number,
128
+ delay,
129
+ action: {
130
+ use: action.use as string,
131
+ ...(action.with === undefined ? {} : { with: structuredClone(action.with) as Record<string, unknown> }),
132
+ },
133
+ });
134
+ }
135
+ return stages;
115
136
  }
116
-
117
- /** 读得懂的条件;读不懂的记进 problems。`where` 如 `rules[2](auth).when`。 */
118
- function parseWhen(raw: unknown, where: string, problems: string[]): RuleWhen {
119
- const when: RuleWhen = {};
120
- if (raw === undefined) return when;
137
+ function parseWhen(raw: unknown, label: string, problems: string[]): RuleWhen {
138
+ if (raw === undefined) return {};
121
139
  if (!isRecord(raw)) {
122
- problems.push(`${where} 需要对象`);
123
- return when;
140
+ problems.push(`${label} must be an object`);
141
+ return {};
124
142
  }
125
- for (const [key, value] of Object.entries(raw)) {
126
- switch (key) {
127
- case "failure":
128
- if (typeof value !== "string" || !value) {
129
- problems.push(`${where}.failure 需要非空正则字符串;空回复用 ^$,所有失败用 .*`);
130
- break;
131
- }
132
- try {
133
- when.failure = new RegExp(value, "i");
134
- } catch (error: unknown) {
135
- problems.push(`${where}.failure 不是合法正则(${errorText(error)})`);
136
- }
137
- break;
138
- case "provider":
139
- case "model":
140
- if (typeof value === "string" && value.trim()) when[key] = value.trim();
141
- else problems.push(`${where}.${key} 需要非空字符串`);
142
- break;
143
- default:
144
- problems.push(`${where}.${key} 不认识`);
143
+ const when: RuleWhen = {};
144
+ unknownKeys(raw, new Set(["failure", "provider", "model"]), label, problems);
145
+ for (const key of ["failure", "provider", "model"] as const) {
146
+ const value = raw[key];
147
+ if (value === undefined) continue;
148
+ if (typeof value !== "string" || !value.trim()) {
149
+ problems.push(`${label}.${key} must be a non-empty string`);
150
+ continue;
151
+ }
152
+ if (key !== "failure") when[key] = value.trim();
153
+ else {
154
+ try {
155
+ when.failure = new RegExp(value, "i");
156
+ } catch (error) {
157
+ problems.push(`${label}.failure is not a valid regular expression (${errorText(error)})`);
158
+ }
145
159
  }
146
160
  }
147
161
  return when;
148
162
  }
163
+ export function unknownKeys(
164
+ raw: Record<string, unknown>,
165
+ allowed: ReadonlySet<string>,
166
+ label: string,
167
+ problems: string[],
168
+ ): void {
169
+ for (const key of Object.keys(raw))
170
+ if (!allowed.has(key)) problems.push(`${label ? `${label}.` : ""}${key} is not a recognized field`);
171
+ }
@@ -1,99 +1,92 @@
1
- /**
2
- * 设置文件 `onward.json` 的 JSON Schema,给编辑器补全和检查用。参数来自 policy.ts 的同一张字段表,和读设置时
3
- * 收下的写法一致。生成的文件是仓库根目录的 onward.schema.json:`npm run gen:schema` 重新生成,测试检查它没有过期。
4
- *
5
- * Schema 只管写法,而且不拒绝读设置时收下的:正则对不对、重名的规则、封顶小于起步这类问题,仍由 config.ts
6
- * 记成问题。`failure` 不写 `format: "regex"`:校验器按 `u` 模式检查,会拒绝读设置时收下的写法,如 `[\w-.]`。
7
- */
8
- import { delayText } from "./delay.ts";
9
- import { DEFAULT_POLICY, FIELDS, type Field } from "./policy.ts";
10
-
11
- /** 发布的位置:同步到 GitHub 的仓库根目录。设置文件的 `$schema` 写它。 */
1
+ /** Structural JSON Schema. Loaded action providers validate their own parameters at runtime. */
2
+ import { ACTION_NAME_PATTERN } from "../actions/protocol.ts";
3
+ import { DELAY_PATTERN } from "./delay.ts";
4
+ import { DEFAULT_LIMITS, FIELDS } from "./policy.ts";
12
5
  export const SCHEMA_URL = "https://raw.githubusercontent.com/cobia68/pi-onward/main/onward.schema.json";
13
-
14
- /** 一个参数:作用和取值说明。顶层的带内置默认值 `fallback`;规则里的不带,说它覆盖顶层的。 */
15
- function param(item: Field, fallback?: unknown): Record<string, unknown> {
16
- const choices = item.choices?.map((choice) => `${choice.value}:${choice.description}`).join(";");
17
- // 写法是「文字」时不重复:类型已经是 string。
18
- const syntax = item.syntax === "文字" ? "" : `(${item.syntax})`;
19
- const usage = item.appliesTo ? `。仅在 action 为 ${item.appliesTo.join(" 或 ")} 时使用` : "";
20
- const what = (choices ? `${item.description}。${choices}` : `${item.description}${syntax}`) + usage;
21
- return {
22
- description: fallback === undefined ? `${what}。覆盖顶层的同名字段` : what,
23
- ...item.schema,
24
- ...(fallback !== undefined && { default: fallback }),
25
- };
26
- }
27
-
28
- /** 内置默认值写成设置文件里的样子:间隔是 `3s..15s` 这样的文字。 */
29
- function fileValue(name: string): unknown {
30
- const value = DEFAULT_POLICY[name as keyof typeof DEFAULT_POLICY];
31
- return name === "delay" ? delayText(DEFAULT_POLICY.delay) : value;
32
- }
33
-
34
6
  export function configSchema(): Record<string, unknown> {
35
7
  return {
36
8
  $schema: "https://json-schema.org/draft/2020-12/schema",
37
9
  $id: SCHEMA_URL,
38
- title: "pi-onward 设置",
39
- description:
40
- "~/.pi/agent/onward.json(全局)或 .pi/onward.json(项目级)。顶层的参数是每条规则的默认值,规则里同名的字段覆盖它",
10
+ title: "pi-onward 阶段恢复策略",
41
11
  type: "object",
42
12
  additionalProperties: false,
43
13
  properties: {
44
- $schema: { description: "这份 JSON Schema 的地址,给编辑器用", type: "string" },
45
- enabled: { description: "插件开关", type: "boolean", default: true },
46
- ...Object.fromEntries(FIELDS.map((item) => [item.name, param(item, fileValue(item.name))])),
47
- quietStartup: {
48
- description:
49
- "启动时的提示(用上了项目级设置、没有可用的规则):true 不显示,false 照常显示,不写时跟着 pi 的 quietStartup;设置有问题时照样警告。只能写在全局设置",
50
- type: "boolean",
51
- },
52
- rules: {
53
- description: "按顺序第一条命中的生效;没命中的错误和空回复不处理",
54
- type: "array",
55
- items: { $ref: "#/$defs/rule" },
56
- },
14
+ $schema: { type: "string" },
15
+ enabled: { type: "boolean", default: true },
16
+ quietStartup: { type: "boolean", description: "仅允许写在全局;未配置时跟随 Pi" },
17
+ ...Object.fromEntries(
18
+ FIELDS.map((field) => [
19
+ field.name,
20
+ {
21
+ ...field.schema,
22
+ description: field.description,
23
+ default: field.name === "actionTimeout" ? "30s" : DEFAULT_LIMITS[field.name],
24
+ },
25
+ ]),
26
+ ),
27
+ rules: { type: "array", items: { $ref: "#/$defs/rule" } },
57
28
  },
58
29
  $defs: {
59
30
  rule: {
60
- description: "规则需要匹配条件或显式动作;不写 when 或写成 {} 的失败兜底必须显式写 action",
61
31
  type: "object",
62
32
  additionalProperties: false,
63
- anyOf: [{ required: ["action"] }, { required: ["when"], properties: { when: { minProperties: 1 } } }],
33
+ required: ["stages"],
64
34
  properties: {
65
- name: {
66
- description: "规则名,出现在通知里,不能重名;不写时按位置叫 rule-1、rule-2",
67
- type: "string",
68
- pattern: "\\S",
69
- },
70
- enabled: { description: "false 时保留但跳过", type: "boolean", default: true },
35
+ name: { type: "string", pattern: "\\S" },
36
+ enabled: { type: "boolean", default: true },
71
37
  when: { $ref: "#/$defs/when" },
72
- ...Object.fromEntries(FIELDS.map((item) => [item.name, param(item)])),
38
+ stages: {
39
+ type: "array",
40
+ minItems: 1,
41
+ description: "minFailures 严格递增;每次失败选择达到下限的最后一个阶段",
42
+ prefixItems: [
43
+ {
44
+ allOf: [
45
+ { $ref: "#/$defs/stage" },
46
+ { type: "object", properties: { minFailures: { const: 1 } } },
47
+ ],
48
+ },
49
+ ],
50
+ items: { $ref: "#/$defs/stage" },
51
+ },
73
52
  },
74
53
  },
75
54
  when: {
76
- description:
77
- "命中条件,几项都要满足;不写 failure 就不限制失败类型;不写 when 或写成 {} 时必须显式写 action",
78
55
  type: "object",
79
56
  additionalProperties: false,
80
57
  properties: {
81
- failure: {
82
- description:
83
- "非空正则,大小写不敏感;普通错误匹配原始文案,缺少文案时匹配「未知错误」,空回复匹配空串。^$ 匹配空回复,.+ 匹配普通错误,.* 匹配所有失败",
84
- type: "string",
85
- minLength: 1,
86
- },
87
- provider: {
88
- description: "通配,只有 * 有特殊含义,大小写不敏感,整串匹配",
89
- type: "string",
90
- pattern: "\\S",
58
+ failure: { type: "string", minLength: 1, description: "大小写不敏感的正则;空回复用 ^$,所有失败用 .*" },
59
+ provider: { type: "string", pattern: "\\S" },
60
+ model: { type: "string", pattern: "\\S" },
61
+ },
62
+ },
63
+ stage: {
64
+ type: "object",
65
+ additionalProperties: false,
66
+ required: ["minFailures", "action"],
67
+ properties: {
68
+ minFailures: {
69
+ type: "integer",
70
+ minimum: 1,
71
+ maximum: 1000,
72
+ description: "阶段生效的连续失败次数下限,包含当前失败",
91
73
  },
92
- model: {
93
- description: "通配,只有 * 有特殊含义,大小写不敏感,整串匹配",
74
+ delay: {
94
75
  type: "string",
95
- pattern: "\\S",
76
+ pattern: DELAY_PATTERN,
77
+ default: "0s",
78
+ description: "在当前阶段内按失败次数推进;省略时不等待",
96
79
  },
80
+ action: { $ref: "#/$defs/action" },
81
+ },
82
+ },
83
+ action: {
84
+ type: "object",
85
+ additionalProperties: false,
86
+ required: ["use"],
87
+ properties: {
88
+ use: { type: "string", pattern: ACTION_NAME_PATTERN },
89
+ with: { type: "object", description: "由已加载动作提供的 JSON Schema 校验;不执行隐式类型转换" },
97
90
  },
98
91
  },
99
92
  },
@@ -0,0 +1,19 @@
1
+ /** One recovery episode, independent of rule changes. Only confirmed boundary failures advance it. */
2
+ import { randomUUID } from "node:crypto";
3
+ import type { RecoveryChain } from "../actions/protocol.ts";
4
+ export class Episode {
5
+ id = randomUUID();
6
+ failures = 0;
7
+ started = 0;
8
+ chain: RecoveryChain;
9
+ private seen = new Set<string>();
10
+ constructor(maxHandoffs: number) {
11
+ this.chain = { id: randomUUID(), handoffs: 0, maxHandoffs };
12
+ }
13
+ observe(entryId: string): boolean {
14
+ if (this.seen.has(entryId)) return false;
15
+ this.seen.add(entryId);
16
+ this.failures++;
17
+ return true;
18
+ }
19
+ }