@cobia/pi-onward 0.4.0 → 0.5.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.
- package/README.md +212 -159
- package/docs/actions.md +3 -3
- package/example.json +2 -2
- package/package.json +1 -1
- package/src/actions/builtins.ts +2 -75
- package/src/actions/pi.ts +70 -0
- package/src/actions/protocol.ts +1 -1
- package/src/extension/command.ts +179 -208
- package/src/extension/install.ts +2 -1
- package/src/extension/settings.ts +6 -10
- package/src/extension/text.ts +2 -13
- package/src/policy/rules.ts +1 -1
- package/src/runtime/recovery.ts +26 -29
- package/src/runtime/task-prompt.ts +82 -0
package/src/extension/install.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { CUSTOM_TYPE } from "../actions/
|
|
2
|
+
import { CUSTOM_TYPE } from "../actions/pi.ts";
|
|
3
3
|
import { Recovery } from "../runtime/recovery.ts";
|
|
4
4
|
import { argumentTabCompletion } from "./autocomplete.ts";
|
|
5
5
|
import { registerCommand } from "./command.ts";
|
|
@@ -21,6 +21,7 @@ export function install(pi: ExtensionAPI, paths: ConfigPaths): void {
|
|
|
21
21
|
if (notice) say(ctx, notice);
|
|
22
22
|
});
|
|
23
23
|
pi.on("input", (event, ctx) => onward.input(event, ctx));
|
|
24
|
+
pi.on("before_agent_start", (event, ctx) => onward.beforeAgentStart(event, ctx));
|
|
24
25
|
pi.on("session_tree", (_event, ctx) => onward.branch(ctx));
|
|
25
26
|
pi.on("agent_start", (_event, ctx) => onward.agentStart(ctx));
|
|
26
27
|
pi.on("message_end", (event, ctx) => onward.messageEnd(event, ctx));
|
|
@@ -46,7 +46,7 @@ const EMPTY: ConfigLayer = { limits: {}, problems: [] };
|
|
|
46
46
|
|
|
47
47
|
export class Settings {
|
|
48
48
|
private readonly paths: ConfigPaths;
|
|
49
|
-
/**
|
|
49
|
+
/** 项目绑定只活在当前会话;读取配置时向 Pi 查询信任状态。 */
|
|
50
50
|
private project: { path: string; isTrusted: () => boolean } | undefined;
|
|
51
51
|
/** undefined 值表示删除键;记录操作而不是整份文件,才能保留后续手工编辑。 */
|
|
52
52
|
private unsaved = new Map<Scope, Record<string, unknown>>();
|
|
@@ -61,12 +61,14 @@ export class Settings {
|
|
|
61
61
|
|
|
62
62
|
constructor(paths: ConfigPaths) {
|
|
63
63
|
this.paths = paths;
|
|
64
|
-
this.
|
|
64
|
+
this.refresh();
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/** 会话开始时以磁盘配置为准,丢弃上一运行的未保存修改。 */
|
|
67
68
|
bind(cwd: string, isTrusted: () => boolean): void {
|
|
68
69
|
this.project = { path: this.paths.project(cwd), isTrusted };
|
|
69
|
-
this.
|
|
70
|
+
this.unsaved.clear();
|
|
71
|
+
this.refresh();
|
|
70
72
|
}
|
|
71
73
|
|
|
72
74
|
get config(): Config {
|
|
@@ -85,12 +87,6 @@ export class Settings {
|
|
|
85
87
|
return this.loaded[scope];
|
|
86
88
|
}
|
|
87
89
|
|
|
88
|
-
/** 显式重载丢弃未保存修改。 */
|
|
89
|
-
reload(): void {
|
|
90
|
-
this.unsaved.clear();
|
|
91
|
-
this.refresh();
|
|
92
|
-
}
|
|
93
|
-
|
|
94
90
|
private refresh(): void {
|
|
95
91
|
const global = readFile("global", this.paths.global, this.unsaved.get("global"));
|
|
96
92
|
const project = this.project;
|
|
@@ -120,7 +116,7 @@ export class Settings {
|
|
|
120
116
|
} catch (error: unknown) {
|
|
121
117
|
saved = { kind: "unwritten", error: errorText(error) };
|
|
122
118
|
}
|
|
123
|
-
//
|
|
119
|
+
// 立即应用新配置,同时保留每一层尚未保存的字段修改。
|
|
124
120
|
this.refresh();
|
|
125
121
|
return saved;
|
|
126
122
|
}
|
package/src/extension/text.ts
CHANGED
|
@@ -157,7 +157,7 @@ function showProblems(settings: Settings): Notice {
|
|
|
157
157
|
...settings.config.problems.map((problem) => `- ${problem}`),
|
|
158
158
|
...section("配置文件", table(fileRows(settings.files))),
|
|
159
159
|
"",
|
|
160
|
-
"
|
|
160
|
+
"修复后使用 Pi 的 /reload 重新加载配置。",
|
|
161
161
|
].join("\n"),
|
|
162
162
|
);
|
|
163
163
|
}
|
|
@@ -202,7 +202,7 @@ function rulesText(settings: Settings): string {
|
|
|
202
202
|
export function describeRules(config: Config, title = `规则(${config.rules.length} 条)`): string {
|
|
203
203
|
if (config.problems.length) return config.problems.join("\n");
|
|
204
204
|
const lines = [title, "按顺序匹配第一条规则;按连续失败次数选择已达到阈值的最后一个阶段。"];
|
|
205
|
-
if (!config.rules.length) lines.push("没有可用的规则;在设置文件的 rules
|
|
205
|
+
if (!config.rules.length) lines.push("没有可用的规则;在设置文件的 rules 里写规则,再用 Pi 的 /reload 加载。");
|
|
206
206
|
for (const [index, rule] of config.rules.entries()) {
|
|
207
207
|
lines.push(`${index + 1}. ${rule.name}${rule.enabled ? "" : "(已停用)"}:${describeWhen(rule)}`);
|
|
208
208
|
for (const stage of rule.stages)
|
|
@@ -331,17 +331,6 @@ export function changedNotice(
|
|
|
331
331
|
if (reason) lines.push(reason);
|
|
332
332
|
return saved.kind === "unwritten" || reason ? warning(lines.join("\n")) : info(lines.join("\n"));
|
|
333
333
|
}
|
|
334
|
-
export function reloadNotice(settings: Settings, status: OnwardStatus): Notice {
|
|
335
|
-
const scopes = settings.files
|
|
336
|
-
.filter((file) => file.source.kind !== "untrusted")
|
|
337
|
-
.map((file) => NAMES[file.scope])
|
|
338
|
-
.join("、");
|
|
339
|
-
if (settings.config.problems.length)
|
|
340
|
-
return warning(`onward:重新加载后配置无效(${scopes})\n修好之前不会自动恢复,详情见 /onward show。`);
|
|
341
|
-
const reason = restriction(settings, status.state);
|
|
342
|
-
const ignored = settings.file("project")?.source.kind === "untrusted" ? "\n项目未受信任,未读取项目配置。" : "";
|
|
343
|
-
return info(`onward:已重新加载配置(${scopes})${ignored}${reason ? `\n${reason}` : ""}`);
|
|
344
|
-
}
|
|
345
334
|
export function startupNotice(settings: Settings, quiet: () => boolean, actionProblems: number): Notice | undefined {
|
|
346
335
|
if (settings.config.problems.length)
|
|
347
336
|
return warning(
|
package/src/policy/rules.ts
CHANGED
|
@@ -120,7 +120,7 @@ function parseStages(raw: unknown, label: string, problems: string[]): Stage[] {
|
|
|
120
120
|
}
|
|
121
121
|
unknownKeys(action, new Set(["use", "with"]), `${at}.action`, problems);
|
|
122
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
|
|
123
|
+
problems.push(`${at}.action.use must be a qualified action name such as pi.message`);
|
|
124
124
|
if (action.with !== undefined && !isRecord(action.with)) problems.push(`${at}.action.with must be an object`);
|
|
125
125
|
if (problems.length === before && typeof delay !== "string")
|
|
126
126
|
stages.push({
|
package/src/runtime/recovery.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type {
|
|
|
5
5
|
AgentBeforeSettleEvent,
|
|
6
6
|
AgentBeforeSettleEventResult,
|
|
7
7
|
AgentSettledEvent,
|
|
8
|
+
BeforeAgentStartEvent,
|
|
8
9
|
ExtensionAPI,
|
|
9
10
|
ExtensionCommandContext,
|
|
10
11
|
ExtensionContext,
|
|
@@ -28,6 +29,7 @@ import { failureText, isFailure, isSuccess } from "../policy/failure.ts";
|
|
|
28
29
|
import { resolveLimits } from "../policy/policy.ts";
|
|
29
30
|
import { errorText, isRecord } from "../util.ts";
|
|
30
31
|
import { Episode } from "./episode.ts";
|
|
32
|
+
import { INPUT_RECORD, TaskPrompt } from "./task-prompt.ts";
|
|
31
33
|
|
|
32
34
|
export interface RunState {
|
|
33
35
|
phase: "idle" | "waiting" | "submitted" | "retrying" | "queued" | "executing" | "stopped";
|
|
@@ -64,7 +66,7 @@ export class Recovery {
|
|
|
64
66
|
private pending: Invocation | undefined;
|
|
65
67
|
private disposed = false;
|
|
66
68
|
private sessionId: string | undefined;
|
|
67
|
-
private taskPrompt
|
|
69
|
+
private readonly taskPrompt = new TaskPrompt();
|
|
68
70
|
private statusText: string | undefined;
|
|
69
71
|
private restored: { sessionId: string; chain: RecoveryChain } | undefined;
|
|
70
72
|
constructor(
|
|
@@ -92,17 +94,10 @@ export class Recovery {
|
|
|
92
94
|
this.restored = undefined;
|
|
93
95
|
}
|
|
94
96
|
input(event: InputEvent, ctx: ExtensionContext): void {
|
|
95
|
-
if (
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
} else {
|
|
100
|
-
this.taskPrompt ??= event.text;
|
|
101
|
-
// Automatic prompts continue the same budget; only a real user task starts a fresh episode.
|
|
102
|
-
this.pending?.controller.abort();
|
|
103
|
-
this.pending = undefined;
|
|
104
|
-
this.setState(ctx, { phase: "idle" });
|
|
105
|
-
}
|
|
97
|
+
if (this.owns(ctx)) this.taskPrompt.observe(event);
|
|
98
|
+
}
|
|
99
|
+
beforeAgentStart(event: BeforeAgentStartEvent, ctx: ExtensionContext): void {
|
|
100
|
+
if (this.owns(ctx)) this.taskPrompt.begin(event);
|
|
106
101
|
}
|
|
107
102
|
agentStart(ctx: ExtensionContext): void {
|
|
108
103
|
if (!this.owns(ctx)) return;
|
|
@@ -123,7 +118,20 @@ export class Recovery {
|
|
|
123
118
|
}
|
|
124
119
|
}
|
|
125
120
|
messageEnd(event: MessageEndEvent, ctx: ExtensionContext): void {
|
|
126
|
-
if (this.owns(ctx)
|
|
121
|
+
if (!this.owns(ctx)) return;
|
|
122
|
+
if (event.message.role === "user") {
|
|
123
|
+
const source = this.taskPrompt.consume();
|
|
124
|
+
// Pi persists the user message after message_end handlers. This metadata follows the same branch,
|
|
125
|
+
// contains no duplicate prompt text and never enters model context.
|
|
126
|
+
this.pi.appendEntry(INPUT_RECORD, { timestamp: event.message.timestamp, source: source ?? "unknown" });
|
|
127
|
+
if (source === "user") this.reset(ctx);
|
|
128
|
+
else {
|
|
129
|
+
// A consumed automatic message cancels stale work but preserves the recovery budget.
|
|
130
|
+
this.pending?.controller.abort();
|
|
131
|
+
this.pending = undefined;
|
|
132
|
+
this.setState(ctx, { phase: "idle" });
|
|
133
|
+
}
|
|
134
|
+
} else if (isSuccess(event.message)) this.reset(ctx);
|
|
127
135
|
}
|
|
128
136
|
async beforeSettle(
|
|
129
137
|
event: AgentBeforeSettleEvent,
|
|
@@ -166,6 +174,7 @@ export class Recovery {
|
|
|
166
174
|
this.finish(ctx, { kind: "stopped", message: `达到跨会话接管上限 ${chain.maxHandoffs} 次` }, hit);
|
|
167
175
|
return;
|
|
168
176
|
}
|
|
177
|
+
this.taskPrompt.refresh(ctx.sessionManager.getBranch());
|
|
169
178
|
const invocation: Invocation = {
|
|
170
179
|
id: randomUUID(),
|
|
171
180
|
hit,
|
|
@@ -174,7 +183,7 @@ export class Recovery {
|
|
|
174
183
|
controller: new AbortController(),
|
|
175
184
|
config: this.settings.config,
|
|
176
185
|
sessionId: ctx.sessionManager.getSessionId(),
|
|
177
|
-
taskPrompt: this.taskPrompt,
|
|
186
|
+
taskPrompt: this.taskPrompt.value,
|
|
178
187
|
};
|
|
179
188
|
this.pending = invocation;
|
|
180
189
|
const signal = ctx.signal
|
|
@@ -212,6 +221,7 @@ export class Recovery {
|
|
|
212
221
|
}
|
|
213
222
|
settled(event: AgentSettledEvent, ctx: ExtensionContext): void {
|
|
214
223
|
if (!this.owns(ctx)) return;
|
|
224
|
+
if (!ctx.hasPendingMessages()) this.taskPrompt.clearPending();
|
|
215
225
|
if (event.aborted) {
|
|
216
226
|
if (this.pending) this.cancel(ctx, "用户取消了恢复");
|
|
217
227
|
return;
|
|
@@ -277,27 +287,14 @@ export class Recovery {
|
|
|
277
287
|
}
|
|
278
288
|
branch(ctx: ExtensionContext): void {
|
|
279
289
|
if (!this.owns(ctx)) return;
|
|
280
|
-
this.taskPrompt
|
|
281
|
-
const entries = ctx.sessionManager.getBranch();
|
|
282
|
-
for (let index = entries.length - 1; index >= 0; index--) {
|
|
283
|
-
const entry = entries[index]!;
|
|
284
|
-
if (entry.type !== "message" || entry.message.role !== "user") continue;
|
|
285
|
-
const content = entry.message.content;
|
|
286
|
-
this.taskPrompt =
|
|
287
|
-
typeof content === "string"
|
|
288
|
-
? content
|
|
289
|
-
: content
|
|
290
|
-
.filter((part) => part.type === "text")
|
|
291
|
-
.map((part) => part.text)
|
|
292
|
-
.join("\n");
|
|
293
|
-
break;
|
|
294
|
-
}
|
|
290
|
+
this.taskPrompt.restore(ctx.sessionManager.getBranch());
|
|
295
291
|
this.reset(ctx);
|
|
296
292
|
}
|
|
297
293
|
stop(ctx: ExtensionContext): void {
|
|
298
294
|
if (this.owns(ctx)) this.reset(ctx);
|
|
299
295
|
}
|
|
300
296
|
shutdown(ctx: ExtensionContext): void {
|
|
297
|
+
this.taskPrompt.clearPending();
|
|
301
298
|
this.pending?.controller.abort();
|
|
302
299
|
this.pending = undefined;
|
|
303
300
|
this.disposed = true;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Resolve consumed input origins and rebuild task text from records on the current branch. */
|
|
2
|
+
import type { BeforeAgentStartEvent, InputEvent, MessageEndEvent, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { isRecord } from "../util.ts";
|
|
4
|
+
|
|
5
|
+
export const INPUT_RECORD = "onward.input";
|
|
6
|
+
type InputOrigin = "user" | "extension";
|
|
7
|
+
type UserMessage = Extract<MessageEndEvent["message"], { role: "user" }>;
|
|
8
|
+
|
|
9
|
+
export class TaskPrompt {
|
|
10
|
+
value: string | undefined;
|
|
11
|
+
private nextRun: InputOrigin[] = [];
|
|
12
|
+
private starting: { source: InputOrigin | undefined } | undefined;
|
|
13
|
+
private queued: InputOrigin[] = [];
|
|
14
|
+
|
|
15
|
+
observe(event: InputEvent): void {
|
|
16
|
+
// Later input handlers may transform or handle it. Observation alone never changes a task.
|
|
17
|
+
const candidates = event.streamingBehavior === undefined ? this.nextRun : this.queued;
|
|
18
|
+
candidates.push(event.source === "extension" ? "extension" : "user");
|
|
19
|
+
}
|
|
20
|
+
begin(event: BeforeAgentStartEvent): void {
|
|
21
|
+
if (event.messageType !== "user") return;
|
|
22
|
+
this.starting = { source: commonOrigin(this.nextRun) };
|
|
23
|
+
this.nextRun = [];
|
|
24
|
+
}
|
|
25
|
+
consume(): InputOrigin | undefined {
|
|
26
|
+
if (this.starting) {
|
|
27
|
+
const { source } = this.starting;
|
|
28
|
+
this.starting = undefined;
|
|
29
|
+
return source;
|
|
30
|
+
}
|
|
31
|
+
const source = commonOrigin(this.queued);
|
|
32
|
+
if (source !== undefined) this.queued.shift();
|
|
33
|
+
return source;
|
|
34
|
+
}
|
|
35
|
+
clearPending(): void {
|
|
36
|
+
this.nextRun = [];
|
|
37
|
+
this.starting = undefined;
|
|
38
|
+
this.queued = [];
|
|
39
|
+
}
|
|
40
|
+
restore(branch: readonly SessionEntry[]): void {
|
|
41
|
+
this.clearPending();
|
|
42
|
+
this.refresh(branch);
|
|
43
|
+
}
|
|
44
|
+
refresh(branch: readonly SessionEntry[]): void {
|
|
45
|
+
this.value = undefined;
|
|
46
|
+
let hasUser = false;
|
|
47
|
+
let record: { timestamp: number; source: InputOrigin | undefined } | undefined;
|
|
48
|
+
for (const entry of branch) {
|
|
49
|
+
if (entry.type === "custom" && entry.customType === INPUT_RECORD) {
|
|
50
|
+
const data = entry.data;
|
|
51
|
+
record =
|
|
52
|
+
isRecord(data) && typeof data.timestamp === "number"
|
|
53
|
+
? { timestamp: data.timestamp, source: inputOrigin(data.source) }
|
|
54
|
+
: undefined;
|
|
55
|
+
} else if (entry.type === "message" && entry.message.role === "user") {
|
|
56
|
+
// message_end appends the record just before Pi persists its user message. A branch cut
|
|
57
|
+
// before that message must not adopt the dangling record as its task.
|
|
58
|
+
const source = record && record.timestamp === entry.message.timestamp ? record.source : undefined;
|
|
59
|
+
if (source === undefined) this.value = undefined;
|
|
60
|
+
else if (source === "user" || !hasUser) this.value = userText(entry.message);
|
|
61
|
+
hasUser = true;
|
|
62
|
+
record = undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function inputOrigin(value: unknown): InputOrigin | undefined {
|
|
68
|
+
return value === "user" || value === "extension" ? value : undefined;
|
|
69
|
+
}
|
|
70
|
+
function commonOrigin(candidates: readonly InputOrigin[]): InputOrigin | undefined {
|
|
71
|
+
// Pi does not expose an accepted-input ID or a source on user messages. Text equality cannot
|
|
72
|
+
// prove origin after transforms/handled inputs. Mixed origins stay unknown until settlement.
|
|
73
|
+
return candidates.every((source) => source === candidates[0]) ? candidates[0] : undefined;
|
|
74
|
+
}
|
|
75
|
+
function userText(message: UserMessage): string {
|
|
76
|
+
return typeof message.content === "string"
|
|
77
|
+
? message.content
|
|
78
|
+
: message.content
|
|
79
|
+
.filter((part) => part.type === "text")
|
|
80
|
+
.map((part) => part.text)
|
|
81
|
+
.join("\n");
|
|
82
|
+
}
|