@cobia/pi-onward 0.1.2 → 0.3.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,8 +1,8 @@
1
1
  /**
2
- * 续跑的参数:一张字段表,设置文件、规则、命令、帮助和补全都用它。设置文件顶层写的就是每条规则的默认值,
3
- * 规则里同名的字段覆盖它。
2
+ * 续跑的参数:一张字段表,设置文件、规则、命令、帮助、补全和 JSON Schema 都用它。设置文件顶层写的就是每条规则的
3
+ * 默认值,规则里同名的字段覆盖它。
4
4
  */
5
- import { DELAY_SYNTAX, type Delay, delayText, parseDelay } from "./delay.ts";
5
+ import { DELAY_PATTERN, DELAY_SYNTAX, type Delay, delayText, parseDelay } from "./delay.ts";
6
6
 
7
7
  /** message 发一条看得见的消息再接着跑;resend 从上下文里省略失败的那条,重发同一个请求;stop 不续跑,只提醒。 */
8
8
  export type Action = "message" | "resend" | "stop";
@@ -25,6 +25,8 @@ export interface Field<K extends keyof Policy = keyof Policy> {
25
25
  /** 帮助里的写法。 */
26
26
  syntax: string;
27
27
  description: string;
28
+ /** 只在这些动作下使用;不写表示都使用。规则显式写了不适用的参数时只提醒。 */
29
+ appliesTo?: readonly Action[];
28
30
  /** 补全的候选值。 */
29
31
  choices?: readonly { value: string; description: string }[];
30
32
  /** 设置文件里的值;合法时返回 value,否则返回原因。 */
@@ -33,8 +35,14 @@ export interface Field<K extends keyof Policy = keyof Policy> {
33
35
  fromText(text: string): unknown;
34
36
  /** 给人看的值。 */
35
37
  show(value: Policy[K]): string;
38
+ /** 设置文件里这个字段的 JSON Schema:和 `read` 收下的一致,只管写法,含义上的检查留给 `read`。 */
39
+ schema: Readonly<Record<string, unknown>>;
36
40
  }
37
41
 
42
+ /** 两个次数上限的范围。一条规则最多续跑 maxRetries 次,同错上限比它大时用不上,所以范围一样。 */
43
+ const RETRIES = { min: 1, max: 50 } as const;
44
+ const PROMPT_MAX = 500;
45
+
38
46
  const ACTIONS: readonly { value: Action; description: string }[] = [
39
47
  { value: "message", description: "发一条看得见的消息再接着跑" },
40
48
  { value: "resend", description: "静默重发同一个请求" },
@@ -55,36 +63,44 @@ export const FIELDS: readonly Field[] = [
55
63
  : { problem: "只能是 message、resend 或 stop" },
56
64
  fromText: (text) => text,
57
65
  show: String,
66
+ schema: { enum: ACTIONS.map((item) => item.value) },
58
67
  }),
59
68
  field({
60
69
  name: "prompt",
70
+ appliesTo: ["message"],
61
71
  syntax: "文字",
62
72
  description: "message 发的消息,可含 {attempt} {max} {error} {rule}",
63
73
  read: (v) =>
64
- typeof v === "string" && v.trim() && v.trim().length <= 500
74
+ typeof v === "string" && v.trim() && v.trim().length <= PROMPT_MAX
65
75
  ? { value: v.trim() }
66
- : { problem: "需要 1–500 字的文字" },
76
+ : { problem: `需要 1–${PROMPT_MAX} 字的文字` },
67
77
  fromText: (text) => text,
68
78
  show: (prompt) => `「${prompt}」`,
79
+ schema: { type: "string", pattern: "\\S", maxLength: PROMPT_MAX },
69
80
  }),
70
81
  field({
71
82
  name: "maxRetries",
72
- syntax: "1–50",
83
+ appliesTo: ["message", "resend"],
84
+ syntax: `${RETRIES.min}–${RETRIES.max}`,
73
85
  description: "连续失败时最多续跑几次",
74
- read: (v) => integer(v, 1, 50),
86
+ read: (v) => integer(v, RETRIES.min, RETRIES.max),
75
87
  fromText: number,
76
88
  show: String,
89
+ schema: { type: "integer", minimum: RETRIES.min, maximum: RETRIES.max },
77
90
  }),
78
91
  field({
79
92
  name: "maxSameError",
80
- syntax: "1–100",
93
+ appliesTo: ["message", "resend"],
94
+ syntax: `${RETRIES.min}–${RETRIES.max}`,
81
95
  description: "同一个错误最多续跑几次,再出现就彻底停",
82
- read: (v) => integer(v, 1, 100),
96
+ read: (v) => integer(v, RETRIES.min, RETRIES.max),
83
97
  fromText: number,
84
98
  show: String,
99
+ schema: { type: "integer", minimum: RETRIES.min, maximum: RETRIES.max },
85
100
  }),
86
101
  field({
87
102
  name: "delay",
103
+ appliesTo: ["message", "resend"],
88
104
  syntax: DELAY_SYNTAX,
89
105
  description: "列表按顺序等,最后一个值重复;起步..封顶按次数增长",
90
106
  read: (v) => {
@@ -93,13 +109,15 @@ export const FIELDS: readonly Field[] = [
93
109
  },
94
110
  fromText: (text) => text,
95
111
  show: delayText,
112
+ schema: { type: "string", pattern: DELAY_PATTERN },
96
113
  }),
97
114
  ];
98
115
 
99
116
  export const FIELD_NAMES: readonly string[] = FIELDS.map((item) => item.name);
100
117
 
118
+ /** 字段名区分大小写,和设置文件一样。 */
101
119
  export function fieldNamed(name: string): Field | undefined {
102
- return FIELDS.find((item) => item.name.toLowerCase() === name.toLowerCase());
120
+ return FIELDS.find((item) => item.name === name);
103
121
  }
104
122
 
105
123
  export const DEFAULT_POLICY: Readonly<Policy> = Object.freeze<Policy>({
@@ -1,17 +1,16 @@
1
1
  /**
2
2
  * 规则 = 条件(when)+ 参数,按顺序第一条命中的生效。参数和设置文件顶层同名,只写和顶层不同的。
3
- * 没写 `when.empty` 的规则管出错,写了的只管空回复;不带 when 的兜底因此不会碰空回复。
4
- * 没有内置规则:没写或没命中,都不处理。读不懂的内容只记问题,不替用户猜;有问题时整份设置不生效(见 config.ts)。
3
+ * when.failure 统一用正则匹配失败文本:普通错误用原文,空回复用空串;不写就不限制失败类型。
4
+ * 没有内置规则:没写或没命中,都不处理。无条件兜底必须显式写 action;读不懂的内容让整份设置不生效(见 config.ts)。
5
+ * 遮挡和不适用的显式参数单独提醒,不影响设置生效,也不改变规则顺序。
5
6
  */
6
7
  import { errorText, isRecord } from "../util.ts";
7
- import type { Failure } from "./failure.ts";
8
- import { FIELD_NAMES, type PolicyPatch, readParams } from "./policy.ts";
8
+ import { type Failure, failureText } from "./failure.ts";
9
+ import { FIELD_NAMES, FIELDS, type PolicyPatch, readParams, resolvePolicy } from "./policy.ts";
9
10
 
10
11
  export interface RuleWhen {
11
- /** 只管空回复;只能是 true,不写就是管出错。 */
12
- empty?: true;
13
- /** 大小写不敏感,对原始错误文案匹配;读设置时编译一次。 */
14
- error?: RegExp;
12
+ /** 大小写不敏感,对统一的失败文本匹配;读设置时编译一次。 */
13
+ failure?: RegExp;
15
14
  /** 通配,只有 `*` 有特殊含义。 */
16
15
  provider?: string;
17
16
  model?: string;
@@ -25,15 +24,14 @@ export interface Rule {
25
24
  patch: PolicyPatch;
26
25
  }
27
26
 
28
- const RULE_KEYS = new Set(["name", "enabled", "when", ...FIELD_NAMES]);
27
+ export const RULE_KEYS: ReadonlySet<string> = new Set(["name", "enabled", "when", ...FIELD_NAMES]);
29
28
 
30
29
  export function findRule(rules: readonly Rule[], failure: Failure): Rule | undefined {
31
30
  return rules.find((rule) => rule.enabled && matches(rule.when, failure));
32
31
  }
33
32
 
34
33
  function matches(when: RuleWhen, failure: Failure): boolean {
35
- if ((when.empty === true) !== (failure.stopReason === "stop")) return false;
36
- if (when.error !== undefined && !when.error.test(failure.errorMessage ?? "")) return false;
34
+ if (when.failure !== undefined && !when.failure.test(failureText(failure))) return false;
37
35
  if (when.provider !== undefined && !glob(when.provider, failure.provider)) return false;
38
36
  if (when.model !== undefined && !glob(when.model, failure.model)) return false;
39
37
  return true;
@@ -48,6 +46,29 @@ export function glob(pattern: string, value: string): boolean {
48
46
  return new RegExp(`^${source}$`, "i").test(value);
49
47
  }
50
48
 
49
+ /** 省略或空的 when 是无条件失败兜底;不猜测正则或通配条件的覆盖关系。 */
50
+ function isFallbackWhen(when: unknown): boolean {
51
+ return when === undefined || (isRecord(when) && Object.keys(when).length === 0);
52
+ }
53
+
54
+ /** 按合并后的参数诊断启用的规则;提醒不进入 problems,调用方不因此停用设置。 */
55
+ export function ruleWarnings(rules: readonly Rule[], defaults: PolicyPatch): string[] {
56
+ const warnings: string[] = [];
57
+ let fallback: string | undefined;
58
+ for (const [index, rule] of rules.entries()) {
59
+ 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} 时不使用`);
68
+ }
69
+ return warnings;
70
+ }
71
+
51
72
  /** 校验规则列表:读得懂的规则返回,读不懂的地方逐条记进 problems。 */
52
73
  export function parseRules(raw: unknown, problems: string[]): Rule[] {
53
74
  if (raw === undefined) return [];
@@ -79,6 +100,8 @@ function parseRule(raw: unknown, index: number, problems: string[]): Rule | unde
79
100
  problems.push(`${label}enabled 需要 true 或 false`);
80
101
  const when = parseWhen(raw.when, `${label}when`, problems);
81
102
  const patch = readParams(raw, label, problems);
103
+ if (isFallbackWhen(raw.when) && raw.action === undefined)
104
+ problems.push(`${label}action 不能省略:兜底规则需要明确写 message、resend 或 stop`);
82
105
  for (const key of Object.keys(raw)) if (!RULE_KEYS.has(key)) problems.push(`${label}${key} 不认识`);
83
106
  // name 是 undefined 时已经记过问题,后一个条件只为收窄类型。
84
107
  if (problems.length > before || name === undefined) return undefined;
@@ -101,19 +124,15 @@ function parseWhen(raw: unknown, where: string, problems: string[]): RuleWhen {
101
124
  }
102
125
  for (const [key, value] of Object.entries(raw)) {
103
126
  switch (key) {
104
- case "empty":
105
- if (value === true) when.empty = true;
106
- else problems.push(`${where}.empty 只能是 true;不写就是管出错`);
107
- break;
108
- case "error":
127
+ case "failure":
109
128
  if (typeof value !== "string" || !value) {
110
- problems.push(`${where}.error 需要非空正则字符串`);
129
+ problems.push(`${where}.failure 需要非空正则字符串;空回复用 ^$,所有失败用 .*`);
111
130
  break;
112
131
  }
113
132
  try {
114
- when.error = new RegExp(value, "i");
133
+ when.failure = new RegExp(value, "i");
115
134
  } catch (error: unknown) {
116
- problems.push(`${where}.error 不是合法正则(${errorText(error)})`);
135
+ problems.push(`${where}.failure 不是合法正则(${errorText(error)})`);
117
136
  }
118
137
  break;
119
138
  case "provider":
@@ -125,7 +144,5 @@ function parseWhen(raw: unknown, where: string, problems: string[]): RuleWhen {
125
144
  problems.push(`${where}.${key} 不认识`);
126
145
  }
127
146
  }
128
- if (raw.empty === true && raw.error !== undefined)
129
- problems.push(`${where} 里 empty 和 error 不能一起写:空回复没有错误文案`);
130
147
  return when;
131
148
  }
@@ -0,0 +1,101 @@
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` 写它。 */
12
+ 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
+ export function configSchema(): Record<string, unknown> {
35
+ return {
36
+ $schema: "https://json-schema.org/draft/2020-12/schema",
37
+ $id: SCHEMA_URL,
38
+ title: "pi-onward 设置",
39
+ description:
40
+ "~/.pi/agent/onward.json(全局)或 .pi/onward.json(项目级)。顶层的参数是每条规则的默认值,规则里同名的字段覆盖它",
41
+ type: "object",
42
+ additionalProperties: false,
43
+ 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
+ },
57
+ },
58
+ $defs: {
59
+ rule: {
60
+ description: "规则需要匹配条件或显式动作;不写 when 或写成 {} 的失败兜底必须显式写 action",
61
+ type: "object",
62
+ additionalProperties: false,
63
+ anyOf: [{ required: ["action"] }, { required: ["when"], properties: { when: { minProperties: 1 } } }],
64
+ properties: {
65
+ name: {
66
+ description: "规则名,出现在通知里,不能重名;不写时按位置叫 rule-1、rule-2",
67
+ type: "string",
68
+ pattern: "\\S",
69
+ },
70
+ enabled: { description: "false 时保留但跳过", type: "boolean", default: true },
71
+ when: { $ref: "#/$defs/when" },
72
+ ...Object.fromEntries(FIELDS.map((item) => [item.name, param(item)])),
73
+ },
74
+ },
75
+ when: {
76
+ description:
77
+ "命中条件,几项都要满足;不写 failure 就不限制失败类型;不写 when 或写成 {} 时必须显式写 action",
78
+ type: "object",
79
+ additionalProperties: false,
80
+ properties: {
81
+ failure: {
82
+ description:
83
+ "非空正则,大小写不敏感;普通错误匹配原始文案,缺少文案时匹配「未知错误」,空回复匹配空串。^$ 匹配空回复,.+ 匹配普通错误,.* 匹配所有失败",
84
+ type: "string",
85
+ minLength: 1,
86
+ },
87
+ provider: {
88
+ description: "通配,只有 * 有特殊含义,大小写不敏感,整串匹配",
89
+ type: "string",
90
+ pattern: "\\S",
91
+ },
92
+ model: {
93
+ description: "通配,只有 * 有特殊含义,大小写不敏感,整串匹配",
94
+ type: "string",
95
+ pattern: "\\S",
96
+ },
97
+ },
98
+ },
99
+ },
100
+ };
101
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 上次正常返回之后的连续失败计数。每条规则各自计次数,预算互不挤占;同一个错误的连续次数是全局的:
2
+ * 上次正常返回之后的连续失败计数。每条规则各自计次数,预算互不挤占;同一个错误的连续次数不分规则:
3
3
  * 不管落到哪条规则,同一个错误连着出现都说明没恢复。扩展在正常返回或用户开新一轮时 reset。
4
4
  */
5
5
  import { retryDelay } from "./delay.ts";