@cobia/pi-onward 0.1.1 → 0.2.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,22 +1,27 @@
1
1
  /**
2
- * pi-onward:一轮以错误收尾(401、429、502、Connection error. 等)时,按用户写的规则续跑。没有内置规则。
2
+ * pi-onward:一轮以错误收尾(401、429、502、Connection error. 等)、或者正常结束却是空回复时,按用户写的规则续跑。
3
+ * 没有内置规则。
3
4
  *
4
5
  * - `policy/`:纯逻辑,不碰 pi 的运行时和文件。什么算失败、命中哪条规则、按什么参数、等多久、什么时候停。
5
6
  * - `extension/`:接 pi。`onward` 处理事件并续跑,`command` 是 `/onward`,`autocomplete` 让它的参数里按 Tab 补参数,
6
- * `settings` 读写设置文件,`text` 是给人看的文字,`render` 画会话里的续跑消息,`install` 把它们装起来。
7
+ * `settings` 读写全局和项目级设置文件并合并,`text` 是给人看的文字,`render` 画会话里的续跑消息,`install` 把它们装起来。
7
8
  *
8
- * 这里是 pi 加载的入口,只决定设置文件的位置。目录用 pi 自己的 getAgentDir(),`PI_CODING_AGENT_DIR` 的写法
9
- * (包括 `~`)和 pi 一致。
9
+ * 这里是 pi 加载的入口,只决定设置文件的位置:
10
+ * - 全局在 pi 自己的 getAgentDir() 里,`PI_CODING_AGENT_DIR` 的写法(包括 `~`)和 pi 一致。
11
+ * - 项目级是当前目录下的 `.pi/onward.json`,不往上级目录找:pi 读 `.pi/settings.json` 也只看当前目录。
10
12
  */
11
13
  import { join } from "node:path";
12
- import { type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
14
+ import { CONFIG_DIR_NAME, type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
13
15
  import { install } from "./install.ts";
16
+ import type { ConfigPaths } from "./settings.ts";
14
17
 
15
- /** `PI_ONWARD_CONFIG` 可改路径。 */
16
- export function configPath(): string {
17
- return process.env.PI_ONWARD_CONFIG || join(getAgentDir(), "onward.json");
18
+ export function configPaths(): ConfigPaths {
19
+ return {
20
+ global: join(getAgentDir(), "onward.json"),
21
+ project: (cwd) => join(cwd, CONFIG_DIR_NAME, "onward.json"),
22
+ };
18
23
  }
19
24
 
20
25
  export default function piOnward(pi: ExtensionAPI): void {
21
- install(pi, configPath());
26
+ install(pi, configPaths());
22
27
  }
@@ -4,14 +4,16 @@ import { argumentTabCompletion } from "./autocomplete.ts";
4
4
  import { registerCommand } from "./command.ts";
5
5
  import { CUSTOM_TYPE, Onward } from "./onward.ts";
6
6
  import { renderContinue } from "./render.ts";
7
- import { Settings } from "./settings.ts";
7
+ import { type ConfigPaths, Settings } from "./settings.ts";
8
8
  import { say, startupNotices } from "./text.ts";
9
9
 
10
- export function install(pi: ExtensionAPI, configPath: string): void {
11
- const settings = new Settings(configPath);
10
+ export function install(pi: ExtensionAPI, paths: ConfigPaths): void {
11
+ const settings = new Settings(paths);
12
12
  const onward = new Onward(settings);
13
13
 
14
14
  pi.on("session_start", (_event, ctx) => {
15
+ // pi 到这时才定下当前目录,项目级设置从这里开始读。
16
+ settings.bind(ctx.cwd);
15
17
  // reload 和切换会话时 pi 会清掉扩展装的补全,所以每次都装。
16
18
  ctx.ui.addAutocompleteProvider(argumentTabCompletion);
17
19
  for (const notice of startupNotices(settings)) say(ctx, notice);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 一轮以错误收尾、命中规则时,在 `agent_before_settle` 边界上等一会儿,再要 pi 接着跑:
2
+ * 一轮以错误收尾、或者正常结束却是空回复,并且命中规则时,在 `agent_before_settle` 边界上等一会儿,再要 pi 接着跑:
3
3
  * - message:追加一条看得见的消息(默认「继续」),模型照常读到;
4
4
  * - resend:用 `context_edit` 把失败的那条从模型上下文里省略,重发同一个请求。失败的记录仍留在会话里。
5
5
  *
@@ -75,7 +75,7 @@ export class Onward {
75
75
  }
76
76
 
77
77
  messageEnd(event: MessageEndEvent, ctx: Ctx): void {
78
- // 续跑之后只要正常返回过一次就算恢复了:后面再出错是新的一串,次数从头算。
78
+ // 续跑之后只要正常返回过一次就算恢复了:后面再出错是新的一串,次数从头算。空回复不算正常返回。
79
79
  if (this.owns(ctx) && isSuccess(event.message)) this.reset(ctx);
80
80
  }
81
81
 
@@ -103,7 +103,7 @@ export class Onward {
103
103
  display: true,
104
104
  details: { rule: hit.rule.name, attempt: step.attempt, max: hit.policy.maxRetries },
105
105
  };
106
- say(ctx, retryNotice(step, draft));
106
+ say(ctx, retryNotice(step, draft, hit.failure));
107
107
  this.setStatus(ctx, "retrying", retryStatus(hit, step));
108
108
  if (await this.wait(step.delay, ctx.signal)) return undefined;
109
109
  // 等的时候用户发了消息:pi 会接着处理它,这算用户开的新一轮。
@@ -1,18 +1,41 @@
1
1
  /**
2
- * 设置文件 `onward.json` 的读写;放在哪里由 index.ts 决定。
2
+ * 设置文件 `onward.json` 的读写:全局一份,项目级一份(`.pi/onward.json`),放在哪里由 index.ts 决定。
3
+ * 两份按 config.ts 的规则合并,项目级在后:顶层字段逐个覆盖全局,写了 `rules` 就整份替换全局的。
3
4
  *
4
- * `rules` 只能手写;命令只改 `enabled` 和顶层的参数字段。每次写之前重读文件,在它当前的内容上合并,免得盖掉
5
- * 加载之后才手改的内容;文件读不了(不是合法 JSON、顶层不是对象)时拒绝写,让用户自己修。
5
+ * 项目级要等 `session_start` 才知道:pi 那时才定下当前目录。不看 pi 对项目的信任:有这个文件就读,和它旁边有没有
6
+ * `.pi/settings.json` 无关。
7
+ *
8
+ * `rules` 只能手写;命令只改 `enabled` 和顶层的参数字段,改哪一份由 `--scope` 定,不写就是全局。每次写之前重读
9
+ * 要改的那份,在它当前的内容上合并,免得盖掉加载之后才手改的内容;文件读不了(不是合法 JSON、顶层不是对象)
10
+ * 时拒绝写,让用户自己修。
6
11
  */
7
12
  import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
13
  import { dirname } from "node:path";
9
- import { type Config, fileOrder, parseConfig } from "../policy/config.ts";
14
+ import { type Config, type ConfigLayer, fileOrder, mergeLayers, parseLayer } from "../policy/config.ts";
10
15
  import { FIELD_NAMES } from "../policy/policy.ts";
11
16
  import { errorText, isRecord } from "../util.ts";
12
17
 
13
- /** 当前设置从哪里来。 */
18
+ /** 哪一份设置文件,也是 `--scope` 的取值;合并时后面的覆盖前面的。 */
19
+ export const SCOPES = ["global", "project"] as const;
20
+ export type Scope = (typeof SCOPES)[number];
21
+
22
+ /** 两份设置文件在哪:全局是固定的路径;项目级跟着当前目录走。 */
23
+ export interface ConfigPaths {
24
+ global: string;
25
+ project(cwd: string): string;
26
+ }
27
+
28
+ /** 一份设置文件的情况:读到了、还没有、读不了。 */
14
29
  export type Source = { kind: "file" | "none" } | { kind: "broken"; error: string };
15
30
 
31
+ export interface SettingsFile {
32
+ scope: Scope;
33
+ path: string;
34
+ source: Source;
35
+ /** 读出来的内容;没有或读不了时是空的一层。读不了时带一条问题,让整份设置不生效;给人看的是 source 里的原因。 */
36
+ layer: ConfigLayer;
37
+ }
38
+
16
39
  /** 一次命令改了什么:`set` 是设置文件里的值,`unset` 是要去掉的键;没写的不动。 */
17
40
  export interface SettingsChange {
18
41
  enabled?: boolean;
@@ -20,49 +43,87 @@ export interface SettingsChange {
20
43
  unset?: readonly string[];
21
44
  }
22
45
 
23
- /** 改动的结果:写好了;文件坏了,什么都没改;或者写不进去,这次运行仍按改过的设置走。 */
46
+ /**
47
+ * 改动的结果:写好了(要写的是空对象、文件又不在时不建文件,也算写好);文件坏了,什么都没改;还不知道当前目录,
48
+ * 项目级没法写;或者写不进去,这次运行仍按改过的设置走。
49
+ */
24
50
  export type Saved =
25
51
  | { kind: "saved"; value: Record<string, unknown> }
26
- | { kind: "broken"; error: string }
52
+ | { kind: "broken"; path: string; error: string }
53
+ | { kind: "unbound" }
27
54
  | { kind: "unwritten"; error: string };
28
55
 
29
56
  /** reset 去掉的键:开关和顶层的参数。 */
30
- const COMMAND_KEYS: readonly string[] = ["enabled", ...FIELD_NAMES];
57
+ export const COMMAND_KEYS: readonly string[] = ["enabled", ...FIELD_NAMES];
31
58
 
32
- interface Loaded {
33
- config: Config;
34
- source: Source;
35
- }
59
+ const EMPTY: ConfigLayer = { defaults: {}, problems: [] };
36
60
 
37
61
  export class Settings {
38
- readonly path: string;
39
- private loaded: Loaded;
62
+ private readonly paths: ConfigPaths;
63
+ /** 项目级在哪;`session_start` 之前是 undefined,只看全局。 */
64
+ private projectPath: string | undefined;
65
+ private loaded!: { global: SettingsFile; project?: SettingsFile };
66
+ private merged!: Config;
67
+
68
+ constructor(paths: ConfigPaths) {
69
+ this.paths = paths;
70
+ this.reload();
71
+ }
40
72
 
41
- constructor(path: string) {
42
- this.path = path;
43
- this.loaded = load(path);
73
+ /** 当前目录定下来了:`session_start` 时调用,重新读两份。 */
74
+ bind(cwd: string): void {
75
+ this.projectPath = this.paths.project(cwd);
76
+ this.reload();
44
77
  }
45
78
 
79
+ /** 合并之后的设置。 */
46
80
  get config(): Config {
47
- return this.loaded.config;
81
+ return this.merged;
82
+ }
83
+
84
+ /** 参与合并的文件,全局在前;`session_start` 之前只有全局。 */
85
+ get files(): readonly SettingsFile[] {
86
+ const { project } = this.loaded;
87
+ return project ? [this.loaded.global, project] : [this.loaded.global];
88
+ }
89
+
90
+ /** 全局总是有;项目级在 `session_start` 之前是 undefined。 */
91
+ file(scope: "global"): SettingsFile;
92
+ file(scope: Scope): SettingsFile | undefined;
93
+ file(scope: Scope): SettingsFile | undefined {
94
+ return this.loaded[scope];
48
95
  }
49
96
 
50
- get source(): Source {
51
- return this.loaded.source;
97
+ /** 在用的项目级文件:读到了,或者读不了;没有这个文件时是 undefined。 */
98
+ get projectFile(): SettingsFile | undefined {
99
+ const { project } = this.loaded;
100
+ return project?.source.kind === "none" ? undefined : project;
52
101
  }
53
102
 
54
103
  reload(): void {
55
- this.loaded = load(this.path);
104
+ const global = readFile("global", this.paths.global);
105
+ const project = this.projectPath === undefined ? undefined : readFile("project", this.projectPath);
106
+ this.loaded = project ? { global, project } : { global };
107
+ this.remerge();
56
108
  }
57
109
 
58
- /** 在文件当前的内容上合并后写回;文件坏了时不动它。 */
59
- update(change: SettingsChange): Saved {
60
- const current = readJson(this.path);
61
- if (current.kind === "broken") return current;
110
+ /**
111
+ * 在要改的那份当前的内容上合并后写回;文件坏了时不动它。文件不在、改完又是空的(去掉本来就没有的参数),
112
+ * 不建文件:一份空的项目级设置什么都不改,却会让每次启动都提醒「用上了项目级设置」。
113
+ */
114
+ update(scope: Scope, change: SettingsChange): Saved {
115
+ const path = this.pathOf(scope);
116
+ if (path === undefined) return { kind: "unbound" };
117
+ const current = readJson(path);
118
+ if (current.kind === "broken") return { kind: "broken", path, error: current.error };
62
119
  const next = applyChange(current.kind === "ok" ? current.value : {}, change);
63
- this.loaded = { config: parseConfig(next), source: { kind: "file" } };
120
+ // 两份都重读:显示的状态和磁盘上的一致。
121
+ this.reload();
122
+ if (current.kind === "missing" && Object.keys(next).length === 0) return { kind: "saved", value: next };
123
+ this.loaded[scope] = { scope, path, source: { kind: "file" }, layer: parseLayer(next) };
124
+ this.remerge();
64
125
  try {
65
- writeJson(this.path, next);
126
+ writeJson(path, next);
66
127
  } catch (error: unknown) {
67
128
  return { kind: "unwritten", error: errorText(error) };
68
129
  }
@@ -70,8 +131,44 @@ export class Settings {
70
131
  }
71
132
 
72
133
  /** 去掉开关和顶层的参数,手写的 rules 和其他内容留着。 */
73
- reset(): Saved {
74
- return this.update({ unset: COMMAND_KEYS });
134
+ reset(scope: Scope): Saved {
135
+ return this.update(scope, { unset: COMMAND_KEYS });
136
+ }
137
+
138
+ /**
139
+ * 这份文件写了这个开关、参数或 `rules`。读不懂的开关和参数不算;写坏了的 `rules` 算写了,反正有问题时整份不生效。
140
+ */
141
+ has(scope: Scope, key: string): boolean {
142
+ const layer = this.loaded[scope]?.layer;
143
+ if (!layer) return false;
144
+ if (key === "enabled") return layer.enabled !== undefined;
145
+ if (key === "rules") return layer.rules !== undefined;
146
+ return Object.hasOwn(layer.defaults, key);
147
+ }
148
+
149
+ /** 这个开关、参数或 `rules` 来自哪一份:项目级优先;都没写时是 undefined,用内置默认值。 */
150
+ origin(key: string): Scope | undefined {
151
+ return (["project", "global"] as const).find((scope) => this.has(scope, key));
152
+ }
153
+
154
+ private pathOf(scope: Scope): string | undefined {
155
+ return scope === "global" ? this.paths.global : this.projectPath;
156
+ }
157
+
158
+ private remerge(): void {
159
+ this.merged = mergeLayers(this.files.map((file) => file.layer));
160
+ }
161
+ }
162
+
163
+ function readFile(scope: Scope, path: string): SettingsFile {
164
+ const current = readJson(path);
165
+ switch (current.kind) {
166
+ case "ok":
167
+ return { scope, path, source: { kind: "file" }, layer: parseLayer(current.value) };
168
+ case "missing":
169
+ return { scope, path, source: { kind: "none" }, layer: EMPTY };
170
+ case "broken":
171
+ return { scope, path, source: current, layer: { ...EMPTY, problems: [current.error] } };
75
172
  }
76
173
  }
77
174
 
@@ -82,12 +179,6 @@ function applyChange(base: Record<string, unknown>, change: SettingsChange): Rec
82
179
  return fileOrder(next);
83
180
  }
84
181
 
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
182
  type ReadResult =
92
183
  | { kind: "missing" }
93
184
  | { kind: "broken"; error: string }