@cobia/pi-onward 0.3.0 → 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,15 +1,4 @@
1
- /**
2
- * pi-onward:一轮以错误收尾(401、429、502、Connection error. 等)、或者正常结束却是空回复时,按用户写的规则续跑。
3
- * 没有内置规则。
4
- *
5
- * - `policy/`:纯逻辑,不碰 pi 的运行时和文件。什么算失败、命中哪条规则、按什么参数、等多久、什么时候停。
6
- * - `extension/`:接 pi。`onward` 处理事件并续跑,`command` 是 `/onward`,`autocomplete` 让它的参数里按 Tab 补参数,
7
- * `settings` 读写全局和项目级设置文件并合并,`text` 是给人看的文字,`render` 画会话里的续跑消息,`install` 把它们装起来。
8
- *
9
- * 这里是 pi 加载的入口,只决定设置文件的位置:
10
- * - 全局在 pi 自己的 getAgentDir() 里,`PI_CODING_AGENT_DIR` 的写法(包括 `~`)和 pi 一致。
11
- * - 项目级是当前目录下的 `.pi/onward.json`,不往上级目录找:pi 读 `.pi/settings.json` 也只看当前目录。
12
- */
1
+ /** 路径跟随 Pi;项目配置不向上查找。 */
13
2
  import { join } from "node:path";
14
3
  import { CONFIG_DIR_NAME, type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
15
4
  import { install } from "./install.ts";
@@ -1,35 +1,37 @@
1
- /** 把各部分装到 pi 上。设置文件放在哪由调用方给:入口是 index.ts,测试直接给临时路径。 */
2
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { CUSTOM_TYPE } from "../actions/builtins.ts";
3
+ import { Recovery } from "../runtime/recovery.ts";
3
4
  import { argumentTabCompletion } from "./autocomplete.ts";
4
5
  import { registerCommand } from "./command.ts";
5
- import { CUSTOM_TYPE, Onward } from "./onward.ts";
6
6
  import { renderContinue } from "./render.ts";
7
7
  import { type ConfigPaths, Settings } from "./settings.ts";
8
8
  import { say, startupNotice } from "./text.ts";
9
9
 
10
10
  export function install(pi: ExtensionAPI, paths: ConfigPaths): void {
11
11
  const settings = new Settings(paths);
12
- const onward = new Onward(settings);
12
+ const onward = new Recovery(pi, settings);
13
13
 
14
14
  pi.on("session_start", (_event, ctx) => {
15
15
  // pi 到这时才定下当前目录,项目级设置从这里开始读。
16
- settings.bind(ctx.cwd);
16
+ settings.bind(ctx.cwd, () => ctx.isProjectTrusted());
17
+ onward.start(ctx);
17
18
  // reload 和切换会话时 pi 会清掉扩展装的补全,所以每次都装。
18
19
  ctx.ui.addAutocompleteProvider(argumentTabCompletion);
19
- const notice = startupNotice(settings, () => quietStartup(pi, settings));
20
+ const notice = startupNotice(settings, () => quietStartup(pi, settings), onward.registry.diagnostics.length);
20
21
  if (notice) say(ctx, notice);
21
22
  });
23
+ pi.on("input", (event, ctx) => onward.input(event, ctx));
24
+ pi.on("session_tree", (_event, ctx) => onward.branch(ctx));
22
25
  pi.on("agent_start", (_event, ctx) => onward.agentStart(ctx));
23
26
  pi.on("message_end", (event, ctx) => onward.messageEnd(event, ctx));
24
27
  pi.on("agent_before_settle", (event, ctx) => onward.beforeSettle(event, ctx));
25
- pi.on("agent_settled", (_event, ctx) => onward.settled(ctx));
28
+ pi.on("agent_settled", (event, ctx) => onward.settled(event, ctx));
26
29
  pi.on("session_shutdown", (_event, ctx) => onward.shutdown(ctx));
27
30
 
28
31
  registerCommand(pi, settings, onward);
29
32
  pi.registerMessageRenderer(CUSTOM_TYPE, renderContinue);
30
33
  }
31
34
 
32
- /** 启动时的提示收不收起:onward 自己的 quietStartup 写了就按它,没写跟着 pi 的,pi 的 true 和 "header" 都收起。 */
33
35
  function quietStartup(pi: ExtensionAPI, settings: Settings): boolean {
34
36
  const own = settings.config.quietStartup;
35
37
  if (own !== undefined) return own;
@@ -1,21 +1,13 @@
1
- /**
2
- * 续跑消息在会话里的样子:第一行是标签「⏩ onward · 续跑 2/10 · auth」,下面是发给模型的原文。
3
- * 没有这个渲染器时 pi 画成「[pi-onward]」加原文,看不出是第几次、哪条规则;恢复会话时通知不会重放,
4
- * 只有这条消息还在。模型只读到原文,标签不进上下文。
5
- */
1
+ /** 避免 Pi 默认添加 [pi-onward] 标题,续跑消息只显示正文。 */
6
2
  import type { MessageRenderer } from "@earendil-works/pi-coding-agent";
7
3
  import { Box, Text } from "@earendil-works/pi-tui";
8
- import { continueLabel } from "./text.ts";
9
4
 
10
5
  export const renderContinue: MessageRenderer = (message, { outputPad }, theme) => {
11
6
  const body =
12
7
  typeof message.content === "string"
13
8
  ? message.content
14
9
  : 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
- ];
10
+ const lines = body.split("\n").map((line) => theme.fg("customMessageText", line));
19
11
  const box = new Box(outputPad, 1, (text) => theme.bg("customMessageBg", text));
20
12
  box.addChild(new Text(lines.join("\n"), 0, 0));
21
13
  return box;
@@ -1,182 +1,184 @@
1
- /**
2
- * 设置文件 `onward.json` 的读写:全局一份,项目级一份(`.pi/onward.json`),放在哪里由 index.ts 决定。
3
- * 两份按 config.ts 的规则合并,项目级在后:顶层字段逐个覆盖全局,写了 `rules` 就整份替换全局的。
4
- *
5
- * 项目级要等 `session_start` 才知道:pi 那时才定下当前目录。不看 pi 对项目的信任:有这个文件就读,和它旁边有没有
6
- * `.pi/settings.json` 无关。
7
- *
8
- * `rules` 只能手写;命令只改 `enabled`、`quietStartup` 和顶层的参数字段,改哪一份由 `--scope` 定,不写就是全局。每次写之前重读
9
- * 要改的那份,在它当前的内容上合并,免得盖掉加载之后才手改的内容;文件读不了(不是合法 JSON、顶层不是对象)
10
- * 时拒绝写,让用户自己修。
11
- */
1
+ /** 只读写全局和受信任的项目配置;未保存修改与磁盘快照分离。 */
12
2
  import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
13
3
  import { dirname } from "node:path";
14
4
  import { type Config, type ConfigLayer, fileOrder, mergeLayers, parseLayer } from "../policy/config.ts";
15
5
  import { FIELD_NAMES } from "../policy/policy.ts";
16
6
  import { errorText, isRecord } from "../util.ts";
17
7
 
18
- /** 哪一份设置文件,也是 `--scope` 的取值;合并时后面的覆盖前面的。 */
19
8
  export const SCOPES = ["global", "project"] as const;
20
9
  export type Scope = (typeof SCOPES)[number];
21
10
 
22
- /** 两份设置文件在哪:全局是固定的路径;项目级跟着当前目录走。 */
23
11
  export interface ConfigPaths {
24
12
  global: string;
25
13
  project(cwd: string): string;
26
14
  }
27
15
 
28
- /** 一份设置文件的情况:读到了、还没有、读不了。 */
29
- export type Source = { kind: "file" | "none" } | { kind: "broken"; error: string };
16
+ /** 文件的读取状态;未受信任时不探测文件是否存在,也不读取内容。 */
17
+ export type Source = { kind: "file" | "none" | "untrusted" } | { kind: "broken"; error: string };
30
18
 
31
19
  export interface SettingsFile {
32
20
  scope: Scope;
33
21
  path: string;
34
22
  source: Source;
35
- /** 读出来的内容;没有或读不了时是空的一层。读不了时带一条问题,让整份设置不生效;给人看的是 source 里的原因。 */
23
+ /** 未保存的键,包含待删除的字段。 */
24
+ unsaved: readonly string[];
25
+ /** 读取失败时为空层并携带错误,阻止合并配置部分生效。 */
36
26
  layer: ConfigLayer;
37
27
  }
38
28
 
39
- /** 一次命令改了什么:`set` 是设置文件里的值,`unset` 是要去掉的键;没写的不动。 */
40
29
  export interface SettingsChange {
41
30
  enabled?: boolean;
42
31
  set?: Record<string, unknown>;
43
32
  unset?: readonly string[];
44
33
  }
45
34
 
46
- /**
47
- * 改动的结果:写好了(要写的是空对象、文件又不在时不建文件,也算写好);文件坏了,什么都没改;还不知道当前目录,
48
- * 项目级没法写;或者写不进去,这次运行仍按改过的设置走。
49
- */
35
+ /** unwritten 表示修改已保留在内存,尚未落盘。 */
50
36
  export type Saved =
51
37
  | { kind: "saved"; value: Record<string, unknown> }
52
38
  | { kind: "broken"; path: string; error: string }
53
- | { kind: "unbound" }
39
+ | { kind: "unbound" | "untrusted" }
54
40
  | { kind: "unwritten"; error: string };
55
41
 
56
- /** 命令能改、reset 去掉的键:开关、顶层的参数和 quietStartup。 */
42
+ /** reset 仅清除这些键,保留手写规则。 */
57
43
  export const COMMAND_KEYS: readonly string[] = ["enabled", ...FIELD_NAMES, "quietStartup"];
58
44
 
59
- const EMPTY: ConfigLayer = { defaults: {}, problems: [] };
45
+ const EMPTY: ConfigLayer = { limits: {}, problems: [] };
60
46
 
61
47
  export class Settings {
62
48
  private readonly paths: ConfigPaths;
63
- /** 项目级在哪;`session_start` 之前是 undefined,只看全局。 */
64
- private projectPath: string | undefined;
49
+ /** 项目绑定只活在当前会话;重载和写入时向 Pi 重新查询信任状态。 */
50
+ private project: { path: string; isTrusted: () => boolean } | undefined;
51
+ /** undefined 值表示删除键;记录操作而不是整份文件,才能保留后续手工编辑。 */
52
+ private unsaved = new Map<Scope, Record<string, unknown>>();
65
53
  private loaded!: { global: SettingsFile; project?: SettingsFile };
66
54
  private merged!: Config;
55
+ private validateActions: ((config: Config) => string[]) | undefined;
56
+
57
+ setActionValidator(validate: (config: Config) => string[]): void {
58
+ this.validateActions = validate;
59
+ this.remerge();
60
+ }
67
61
 
68
62
  constructor(paths: ConfigPaths) {
69
63
  this.paths = paths;
70
64
  this.reload();
71
65
  }
72
66
 
73
- /** 当前目录定下来了:`session_start` 时调用,重新读两份。 */
74
- bind(cwd: string): void {
75
- this.projectPath = this.paths.project(cwd);
67
+ bind(cwd: string, isTrusted: () => boolean): void {
68
+ this.project = { path: this.paths.project(cwd), isTrusted };
76
69
  this.reload();
77
70
  }
78
71
 
79
- /** 合并之后的设置。 */
80
72
  get config(): Config {
81
73
  return this.merged;
82
74
  }
83
75
 
84
- /** 参与合并的文件,全局在前;`session_start` 之前只有全局。 */
76
+ /** 全局在前、项目在后;会话绑定前只有全局。 */
85
77
  get files(): readonly SettingsFile[] {
86
78
  const { project } = this.loaded;
87
79
  return project ? [this.loaded.global, project] : [this.loaded.global];
88
80
  }
89
81
 
90
- /** 全局总是有;项目级在 `session_start` 之前是 undefined。 */
91
82
  file(scope: "global"): SettingsFile;
92
83
  file(scope: Scope): SettingsFile | undefined;
93
84
  file(scope: Scope): SettingsFile | undefined {
94
85
  return this.loaded[scope];
95
86
  }
96
87
 
97
- /** 在用的项目级文件:读到了,或者读不了;没有这个文件时是 undefined。 */
98
- get projectFile(): SettingsFile | undefined {
99
- const { project } = this.loaded;
100
- return project?.source.kind === "none" ? undefined : project;
101
- }
102
-
88
+ /** 显式重载丢弃未保存修改。 */
103
89
  reload(): void {
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 };
90
+ this.unsaved.clear();
91
+ this.refresh();
92
+ }
93
+
94
+ private refresh(): void {
95
+ const global = readFile("global", this.paths.global, this.unsaved.get("global"));
96
+ const project = this.project;
97
+ this.loaded = { global };
98
+ if (project)
99
+ this.loaded.project = project.isTrusted()
100
+ ? readFile("project", project.path, this.unsaved.get("project"))
101
+ : { scope: "project", path: project.path, source: { kind: "untrusted" }, unsaved: [], layer: EMPTY };
107
102
  this.remerge();
108
103
  }
109
104
 
110
- /**
111
- * 在要改的那份当前的内容上合并后写回;文件坏了时不动它。文件不在、改完又是空的(去掉本来就没有的参数),
112
- * 不建文件:一份空的项目级设置什么都不改,却会让每次启动都提醒「用上了项目级设置」。
113
- */
105
+ /** 写前重读以保留手工编辑;空内容不新建文件,避免无意义的项目提示。 */
114
106
  update(scope: Scope, change: SettingsChange): Saved {
115
107
  const path = this.pathOf(scope);
116
108
  if (path === undefined) return { kind: "unbound" };
109
+ if (scope === "project" && !this.project!.isTrusted()) return { kind: "untrusted" };
117
110
  const current = readJson(path);
118
111
  if (current.kind === "broken") return { kind: "broken", path, error: current.error };
119
- const next = applyChange(current.kind === "ok" ? current.value : {}, change);
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, scope === "project") };
124
- this.remerge();
112
+ const patch = mergeChange(this.unsaved.get(scope), change);
113
+ const next = applyPatch(current.kind === "ok" ? current.value : {}, patch);
114
+ this.unsaved.set(scope, patch);
115
+ let saved: Saved;
125
116
  try {
126
- writeJson(path, next);
117
+ if (current.kind !== "missing" || Object.keys(next).length > 0) writeJson(path, next);
118
+ this.unsaved.delete(scope);
119
+ saved = { kind: "saved", value: next };
127
120
  } catch (error: unknown) {
128
- return { kind: "unwritten", error: errorText(error) };
121
+ saved = { kind: "unwritten", error: errorText(error) };
129
122
  }
130
- return { kind: "saved", value: next };
123
+ // 重读磁盘,但重新叠加每一层尚未保存的字段,不能隐式执行 reload。
124
+ this.refresh();
125
+ return saved;
131
126
  }
132
127
 
133
- /** 去掉开关、顶层的参数和 quietStartup,手写的 rules 和其他内容留着。 */
134
128
  reset(scope: Scope): Saved {
135
129
  return this.update(scope, { unset: COMMAND_KEYS });
136
130
  }
137
131
 
138
- /**
139
- * 这份文件写了这个开关、参数或 `rules`。读不懂的开关和参数不算;写坏了的 `rules` 算写了,反正有问题时整份不生效。
140
- */
132
+ /** 非法标量不算已配置;非法 rules 仍算显式覆盖,但会阻断配置生效。 */
141
133
  has(scope: Scope, key: string): boolean {
142
134
  const layer = this.loaded[scope]?.layer;
143
135
  if (!layer) return false;
144
136
  if (key === "enabled") return layer.enabled !== undefined;
145
137
  if (key === "quietStartup") return layer.quietStartup !== undefined;
146
138
  if (key === "rules") return layer.rules !== undefined;
147
- return Object.hasOwn(layer.defaults, key);
139
+ return Object.hasOwn(layer.limits, key);
148
140
  }
149
141
 
150
- /** 这个开关、参数或 `rules` 来自哪一份:项目级优先;都没写时是 undefined,用内置默认值。 */
142
+ /** 没有可用的显式值时返回 undefined。 */
151
143
  origin(key: string): Scope | undefined {
152
144
  return (["project", "global"] as const).find((scope) => this.has(scope, key));
153
145
  }
154
146
 
155
147
  private pathOf(scope: Scope): string | undefined {
156
- return scope === "global" ? this.paths.global : this.projectPath;
148
+ return scope === "global" ? this.paths.global : this.project?.path;
157
149
  }
158
150
 
159
151
  private remerge(): void {
160
152
  this.merged = mergeLayers(this.files.map((file) => file.layer));
153
+ if (!this.merged.problems.length && this.validateActions)
154
+ this.merged.problems.push(...this.validateActions(this.merged));
161
155
  }
162
156
  }
163
157
 
164
- function readFile(scope: Scope, path: string): SettingsFile {
158
+ function readFile(scope: Scope, path: string, patch?: Record<string, unknown>): SettingsFile {
165
159
  const current = readJson(path);
166
- switch (current.kind) {
167
- case "ok":
168
- return { scope, path, source: { kind: "file" }, layer: parseLayer(current.value, scope === "project") };
169
- case "missing":
170
- return { scope, path, source: { kind: "none" }, layer: EMPTY };
171
- case "broken":
172
- return { scope, path, source: current, layer: { ...EMPTY, problems: [current.error] } };
173
- }
160
+ const file = { scope, path, unsaved: Object.keys(patch ?? {}) };
161
+ if (current.kind === "broken") return { ...file, source: current, layer: { ...EMPTY, problems: [current.error] } };
162
+ return {
163
+ ...file,
164
+ source: { kind: current.kind === "ok" ? "file" : "none" },
165
+ layer: parseLayer(applyPatch(current.kind === "ok" ? current.value : {}, patch), scope === "project"),
166
+ };
174
167
  }
175
168
 
176
- function applyChange(base: Record<string, unknown>, change: SettingsChange): Record<string, unknown> {
177
- const next: Record<string, unknown> = { ...base, ...change.set };
178
- if (change.enabled !== undefined) next.enabled = change.enabled;
179
- for (const name of change.unset ?? []) delete next[name];
169
+ function mergeChange(previous: Record<string, unknown> | undefined, change: SettingsChange): Record<string, unknown> {
170
+ const patch = { ...previous, ...change.set };
171
+ if (change.enabled !== undefined) patch.enabled = change.enabled;
172
+ for (const name of change.unset ?? []) patch[name] = undefined;
173
+ return patch;
174
+ }
175
+
176
+ function applyPatch(base: Record<string, unknown>, patch?: Record<string, unknown>): Record<string, unknown> {
177
+ const next = { ...base };
178
+ for (const [name, value] of Object.entries(patch ?? {})) {
179
+ if (value === undefined) delete next[name];
180
+ else next[name] = value;
181
+ }
180
182
  return fileOrder(next);
181
183
  }
182
184
 
@@ -197,12 +199,14 @@ function readJson(path: string): ReadResult {
197
199
  try {
198
200
  value = JSON.parse(text);
199
201
  } catch (error: unknown) {
200
- return { kind: "broken", error: `不是合法 JSON:${errorText(error)}` };
202
+ return { kind: "broken", error: `Invalid JSON: ${errorText(error)}` };
201
203
  }
202
- return isRecord(value) ? { kind: "ok", value } : { kind: "broken", error: "顶层需要是对象 {}" };
204
+ return isRecord(value)
205
+ ? { kind: "ok", value }
206
+ : { kind: "broken", error: "Top-level configuration must be a JSON object" };
203
207
  }
204
208
 
205
- /** 先写临时文件再改名:写到一半失败也不会留下半个文件;改名之后临时文件已不在,删它不做事。 */
209
+ /** 临时文件写完再原子改名,避免留下半写的配置。 */
206
210
  function writeJson(path: string, value: unknown): void {
207
211
  mkdirSync(dirname(path), { recursive: true });
208
212
  const temp = `${path}.${process.pid}.tmp`;