@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.
@@ -0,0 +1,473 @@
1
+ /** Pi lifecycle coordinator. Boundary proposals and settled commands share one action registry and episode. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { fileURLToPath } from "node:url";
4
+ import type {
5
+ AgentBeforeSettleEvent,
6
+ AgentBeforeSettleEventResult,
7
+ AgentSettledEvent,
8
+ ExtensionAPI,
9
+ ExtensionCommandContext,
10
+ ExtensionContext,
11
+ InputEvent,
12
+ MessageEndEvent,
13
+ } from "@earendil-works/pi-coding-agent";
14
+ import { builtinActions } from "../actions/builtins.ts";
15
+ import {
16
+ type ActionContext,
17
+ type ActionDefinition,
18
+ type ActionResult,
19
+ isRecoveryChain,
20
+ RESUME_RECOVERY,
21
+ type RecoveryChain,
22
+ } from "../actions/protocol.ts";
23
+ import { ActionRegistry } from "../actions/registry.ts";
24
+ import type { Settings } from "../extension/settings.ts";
25
+ import { type Hit, isActive, matchFailure } from "../policy/config.ts";
26
+ import { formatDelay, retryDelay } from "../policy/delay.ts";
27
+ import { failureText, isFailure, isSuccess } from "../policy/failure.ts";
28
+ import { resolveLimits } from "../policy/policy.ts";
29
+ import { errorText, isRecord } from "../util.ts";
30
+ import { Episode } from "./episode.ts";
31
+
32
+ export interface RunState {
33
+ phase: "idle" | "waiting" | "submitted" | "retrying" | "queued" | "executing" | "stopped";
34
+ hit?: Hit;
35
+ invocationId?: string;
36
+ result?: ActionResult["kind"];
37
+ message?: string;
38
+ }
39
+ export interface OnwardStatus {
40
+ state: RunState;
41
+ failures: number;
42
+ started: number;
43
+ handoffs: number;
44
+ }
45
+ interface Invocation {
46
+ id: string;
47
+ hit: Hit;
48
+ definition: ActionDefinition;
49
+ targetId: string;
50
+ controller: AbortController;
51
+ config: Settings["config"];
52
+ sessionId: string;
53
+ taskPrompt: string | undefined;
54
+ }
55
+ const shared = globalThis as typeof globalThis & { __piOnwardRecoveryOwners?: Map<string, object> };
56
+ shared.__piOnwardRecoveryOwners ??= new Map();
57
+ const owners = shared.__piOnwardRecoveryOwners;
58
+ const ENTRY_PATH = fileURLToPath(new URL("../extension/index.ts", import.meta.url));
59
+
60
+ export class Recovery {
61
+ readonly registry = new ActionRegistry();
62
+ private episode: Episode;
63
+ private state: RunState = { phase: "idle" };
64
+ private pending: Invocation | undefined;
65
+ private disposed = false;
66
+ private sessionId: string | undefined;
67
+ private taskPrompt: string | undefined;
68
+ private statusText: string | undefined;
69
+ private restored: { sessionId: string; chain: RecoveryChain } | undefined;
70
+ constructor(
71
+ private readonly pi: ExtensionAPI,
72
+ private readonly settings: Settings,
73
+ ) {
74
+ this.episode = new Episode(resolveLimits(settings.config.limits).maxHandoffs);
75
+ pi.events.on(RESUME_RECOVERY, (value) => {
76
+ if (!isRecord(value) || typeof value.sessionId !== "string" || !isRecoveryChain(value.chain)) return;
77
+ if (this.disposed || (this.sessionId && value.sessionId !== this.sessionId)) return;
78
+ if (this.sessionId === value.sessionId) {
79
+ this.episode.chain = { ...value.chain };
80
+ } else this.restored = { sessionId: value.sessionId, chain: { ...value.chain } };
81
+ });
82
+ }
83
+ start(ctx: ExtensionContext): void {
84
+ this.sessionId = ctx.sessionManager.getSessionId();
85
+ this.disposed = false;
86
+ if (!this.owns(ctx)) return;
87
+ this.registry.discover(this.pi, builtinActions(this.pi));
88
+ this.settings.setActionValidator((config) => this.registry.problems(config));
89
+ this.branch(ctx);
90
+ if (this.restored?.sessionId === ctx.sessionManager.getSessionId())
91
+ this.episode.chain = { ...this.restored.chain };
92
+ this.restored = undefined;
93
+ }
94
+ input(event: InputEvent, ctx: ExtensionContext): void {
95
+ if (!this.owns(ctx) || this.disposed) return;
96
+ if (event.source !== "extension") {
97
+ this.taskPrompt = event.text;
98
+ this.reset(ctx);
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
+ }
106
+ }
107
+ agentStart(ctx: ExtensionContext): void {
108
+ if (!this.owns(ctx)) return;
109
+ if (this.state.phase === "submitted" && this.pending) {
110
+ const invocation = this.pending;
111
+ this.pending = undefined;
112
+ if (ctx.signal?.aborted) {
113
+ this.setState(ctx, { phase: "idle" });
114
+ return;
115
+ }
116
+ this.episode.started++;
117
+ this.setState(ctx, { phase: "retrying", hit: invocation.hit, invocationId: invocation.id });
118
+ } else if (this.pending) {
119
+ // Another extension continued after our proposal. The old settled action must not survive.
120
+ this.pending.controller.abort();
121
+ this.pending = undefined;
122
+ this.setState(ctx, { phase: "idle" });
123
+ }
124
+ }
125
+ messageEnd(event: MessageEndEvent, ctx: ExtensionContext): void {
126
+ if (this.owns(ctx) && isSuccess(event.message)) this.reset(ctx);
127
+ }
128
+ async beforeSettle(
129
+ event: AgentBeforeSettleEvent,
130
+ ctx: ExtensionContext,
131
+ ): Promise<AgentBeforeSettleEventResult | undefined> {
132
+ if (
133
+ !this.owns(ctx) ||
134
+ this.disposed ||
135
+ this.state.phase === "stopped" ||
136
+ this.pending ||
137
+ !isActive(this.settings.config)
138
+ )
139
+ return;
140
+ if (event.outcome === "aborted" || ctx.signal?.aborted || event.continue || ctx.hasPendingMessages()) return;
141
+ const entry = event.context.contextEntries.at(-1);
142
+ const message = entry?.messages.at(-1);
143
+ if (!entry || !isFailure(message) || !this.episode.observe(entry.sourceEntry.id)) return;
144
+ const hit = matchFailure(this.settings.config, message, this.episode.failures);
145
+ if (!hit) {
146
+ this.finish(ctx, { kind: "stopped", message: "没有命中恢复规则" });
147
+ return;
148
+ }
149
+ if (this.episode.failures > hit.limits.maxFailures) {
150
+ this.finish(ctx, { kind: "stopped", message: `连续失败超过 ${hit.limits.maxFailures} 次上限` }, hit);
151
+ return;
152
+ }
153
+ const definition = this.registry.get(hit.stage.action.use)?.definition;
154
+ const problem = this.registry.check(hit.stage.action);
155
+ if (problem || !definition) {
156
+ this.finish(ctx, { kind: "failed", message: problem ?? "Action is not loaded" }, hit);
157
+ return;
158
+ }
159
+ if (!definition.modes.includes(ctx.mode)) {
160
+ this.finish(ctx, { kind: "failed", message: `${definition.name} does not support ${ctx.mode} mode` }, hit);
161
+ return;
162
+ }
163
+ const chain = this.episode.chain;
164
+ chain.maxHandoffs = Math.min(chain.maxHandoffs, hit.limits.maxHandoffs);
165
+ if (definition.handoff && chain.handoffs >= chain.maxHandoffs) {
166
+ this.finish(ctx, { kind: "stopped", message: `达到跨会话接管上限 ${chain.maxHandoffs} 次` }, hit);
167
+ return;
168
+ }
169
+ const invocation: Invocation = {
170
+ id: randomUUID(),
171
+ hit,
172
+ definition,
173
+ targetId: entry.sourceEntry.id,
174
+ controller: new AbortController(),
175
+ config: this.settings.config,
176
+ sessionId: ctx.sessionManager.getSessionId(),
177
+ taskPrompt: this.taskPrompt,
178
+ };
179
+ this.pending = invocation;
180
+ const signal = ctx.signal
181
+ ? AbortSignal.any([ctx.signal, invocation.controller.signal])
182
+ : invocation.controller.signal;
183
+ this.setState(ctx, { phase: "waiting", hit, invocationId: invocation.id });
184
+ const delay = retryDelay(this.episode.failures - hit.stage.minFailures + 1, hit.stage.delay);
185
+ this.notice(ctx, `${formatDelay(delay)}后执行 ${definition.name}(连续失败 ${this.episode.failures} 次)`);
186
+ await wait(delay, signal);
187
+ if (!this.current(invocation, ctx)) return;
188
+ if (signal.aborted || ctx.hasPendingMessages()) {
189
+ this.cancel(ctx, "等待已取消");
190
+ return;
191
+ }
192
+ if (definition.phase === "settled") {
193
+ this.setState(ctx, { phase: "queued", hit, invocationId: invocation.id });
194
+ return;
195
+ }
196
+ const result = await this.invoke(invocation, {
197
+ ...this.execution(invocation, signal),
198
+ phase: "boundary",
199
+ targetId: invocation.targetId,
200
+ });
201
+ if (!this.current(invocation, ctx)) return;
202
+ if (signal.aborted || ctx.hasPendingMessages()) {
203
+ this.cancel(ctx, "续跑提议已取消");
204
+ return;
205
+ }
206
+ if (result.kind === "continue") {
207
+ this.setState(ctx, { phase: "submitted", hit, invocationId: invocation.id });
208
+ return { entries: [...event.entries, ...result.entries], continue: true };
209
+ }
210
+ this.pending = undefined;
211
+ this.finish(ctx, result, hit);
212
+ }
213
+ settled(event: AgentSettledEvent, ctx: ExtensionContext): void {
214
+ if (!this.owns(ctx)) return;
215
+ if (event.aborted) {
216
+ if (this.pending) this.cancel(ctx, "用户取消了恢复");
217
+ return;
218
+ }
219
+ if (this.state.phase === "queued" && this.pending) {
220
+ const invocation = this.pending;
221
+ if (!this.current(invocation, ctx) || ctx.hasPendingMessages()) {
222
+ this.cancel(ctx, "待执行动作已取消");
223
+ return;
224
+ }
225
+ const command = this.pi
226
+ .getCommands()
227
+ .find(
228
+ (command) =>
229
+ command.source === "extension" &&
230
+ command.sourceInfo.path === ENTRY_PATH &&
231
+ (command.name === "onward" || command.name.startsWith("onward:")),
232
+ );
233
+ if (!command) {
234
+ this.pending = undefined;
235
+ this.finish(ctx, { kind: "failed", message: "Onward dispatch command is unavailable" }, invocation.hit);
236
+ return;
237
+ }
238
+ // Pi defers this command until ALL agent_settled handlers finish.
239
+ this.pi.sendUserMessage(`/${command.name} _dispatch ${invocation.id}`, { expandPromptTemplates: true });
240
+ return;
241
+ }
242
+ if (this.state.phase === "submitted") {
243
+ this.pending = undefined;
244
+ this.setState(ctx, { phase: "idle" });
245
+ }
246
+ }
247
+ /** Private nonce-based bridge, reached through Pi's real ExtensionCommandContext. */
248
+ async dispatch(id: string, ctx: ExtensionCommandContext): Promise<void> {
249
+ const invocation = this.pending;
250
+ if (!invocation || invocation.id !== id || this.state.phase !== "queued" || !this.current(invocation, ctx))
251
+ return;
252
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) {
253
+ this.cancel(ctx, "新的任务优先,待执行动作已取消");
254
+ return;
255
+ }
256
+ this.setState(ctx, { phase: "executing", hit: invocation.hit, invocationId: id });
257
+ if (invocation.definition.handoff) this.episode.chain.handoffs++;
258
+ // Durable intent, without prompts or errors: it is diagnostic only and never replayed.
259
+ this.pi.appendEntry("onward.action", {
260
+ invocationId: id,
261
+ episodeId: this.episode.id,
262
+ action: invocation.definition.name,
263
+ status: "started",
264
+ chain: { ...this.episode.chain },
265
+ });
266
+ const result = await this.invoke(invocation, {
267
+ ...this.execution(invocation, invocation.controller.signal),
268
+ phase: "settled",
269
+ host: ctx,
270
+ });
271
+ if (!this.current(invocation, ctx)) return;
272
+ if (invocation.definition.handoff && ["completed", "failed", "cancelled", "stopped"].includes(result.kind))
273
+ this.episode.chain.handoffs--;
274
+ this.pending = undefined;
275
+ this.pi.appendEntry("onward.action", { invocationId: id, status: result.kind });
276
+ this.finish(ctx, result, invocation.hit);
277
+ }
278
+ branch(ctx: ExtensionContext): void {
279
+ if (!this.owns(ctx)) return;
280
+ this.taskPrompt = undefined;
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
+ }
295
+ this.reset(ctx);
296
+ }
297
+ stop(ctx: ExtensionContext): void {
298
+ if (this.owns(ctx)) this.reset(ctx);
299
+ }
300
+ shutdown(ctx: ExtensionContext): void {
301
+ this.pending?.controller.abort();
302
+ this.pending = undefined;
303
+ this.disposed = true;
304
+ if (owners.get(ctx.sessionManager.getSessionId()) === this) {
305
+ this.setState(ctx, { phase: "idle" });
306
+ owners.delete(ctx.sessionManager.getSessionId());
307
+ }
308
+ this.registry.clear();
309
+ }
310
+ status(): OnwardStatus {
311
+ return {
312
+ state: this.state,
313
+ failures: this.episode.failures,
314
+ started: this.episode.started,
315
+ handoffs: this.episode.chain.handoffs,
316
+ };
317
+ }
318
+ private execution(invocation: Invocation, signal: AbortSignal) {
319
+ const { failure, rule, stage } = invocation.hit;
320
+ return {
321
+ invocationId: invocation.id,
322
+ episodeId: this.episode.id,
323
+ sessionId: invocation.sessionId,
324
+ rule: rule.name,
325
+ failures: this.episode.failures,
326
+ minFailures: stage.minFailures,
327
+ taskPrompt: invocation.taskPrompt,
328
+ signal,
329
+ chain: Object.freeze({ ...this.episode.chain }),
330
+ failure: Object.freeze({
331
+ kind: failure.stopReason === "error" ? ("error" as const) : ("empty" as const),
332
+ text: failureText(failure),
333
+ provider: failure.provider,
334
+ model: failure.model,
335
+ }),
336
+ };
337
+ }
338
+ private async invoke(invocation: Invocation, context: ActionContext): Promise<ActionResult> {
339
+ const timeout = new AbortController();
340
+ const signal = AbortSignal.any([context.signal, timeout.signal]);
341
+ const timer = setTimeout(() => timeout.abort(), invocation.hit.limits.actionTimeout);
342
+ try {
343
+ if (signal.aborted) return { kind: "cancelled", message: "动作已取消" };
344
+ const execute = async (): Promise<ActionResult> => {
345
+ const definition = invocation.definition;
346
+ const params = this.registry.parameters(invocation.hit.stage.action);
347
+ if (definition.phase === "boundary" && context.phase === "boundary")
348
+ return definition.execute(params, { ...context, signal });
349
+ if (definition.phase === "settled" && context.phase === "settled")
350
+ return definition.execute(params, { ...context, signal });
351
+ return { kind: "failed", message: "Action execution phase does not match its context" };
352
+ };
353
+ const result = await raceAbort(execute(), signal);
354
+ if (signal.aborted)
355
+ return {
356
+ kind: "unknown",
357
+ message: timeout.signal.aborted
358
+ ? "Action timed out; outcome unknown; not replayed"
359
+ : "Execution cancelled; side-effect outcome unknown",
360
+ };
361
+ if (!validResult(result, invocation.definition))
362
+ return { kind: "unknown", message: "Action returned an invalid result; not replayed" };
363
+ return result;
364
+ } catch (error) {
365
+ return { kind: "unknown", message: `Action threw an exception; outcome unknown: ${errorText(error)}` };
366
+ } finally {
367
+ clearTimeout(timer);
368
+ }
369
+ }
370
+ private current(invocation: Invocation, ctx: ExtensionContext): boolean {
371
+ return (
372
+ !this.disposed &&
373
+ this.pending === invocation &&
374
+ !invocation.controller.signal.aborted &&
375
+ invocation.config === this.settings.config &&
376
+ isActive(this.settings.config) &&
377
+ ctx.sessionManager.getSessionId() === invocation.sessionId &&
378
+ owners.get(invocation.sessionId) === this
379
+ );
380
+ }
381
+ private owns(ctx: Pick<ExtensionContext, "sessionManager">): boolean {
382
+ if (this.disposed) return false;
383
+ const id = ctx.sessionManager.getSessionId();
384
+ if (!owners.has(id)) owners.set(id, this);
385
+ return owners.get(id) === this;
386
+ }
387
+ private reset(ctx: ExtensionContext): void {
388
+ this.pending?.controller.abort();
389
+ this.pending = undefined;
390
+ this.episode = new Episode(resolveLimits(this.settings.config.limits).maxHandoffs);
391
+ this.setState(ctx, { phase: "idle" });
392
+ }
393
+ private cancel(ctx: ExtensionContext, message: string): void {
394
+ const hit = this.pending?.hit;
395
+ this.pending?.controller.abort();
396
+ this.pending = undefined;
397
+ if (this.state.phase !== "idle") this.finish(ctx, { kind: "cancelled", message }, hit);
398
+ }
399
+ private finish(ctx: ExtensionContext, result: ActionResult, hit?: Hit): void {
400
+ const message = "message" in result ? result.message : undefined;
401
+ this.setState(ctx, { phase: "stopped", hit, result: result.kind, message });
402
+ this.notice(
403
+ ctx,
404
+ message ?? `${hit?.stage.action.use ?? "恢复"}:${result.kind}`,
405
+ !["completed", "handoff", "dispatched"].includes(result.kind),
406
+ );
407
+ }
408
+ private notice(ctx: ExtensionContext, text: string, warning = false): void {
409
+ if (ctx.hasUI) ctx.ui.notify(`onward:${text}`, warning ? "warning" : "info");
410
+ }
411
+ private setState(ctx: ExtensionContext, state: RunState): void {
412
+ this.state = state;
413
+ const after = stateText(state, this.episode.failures);
414
+ if (ctx.hasUI && this.statusText !== after) ctx.ui.setStatus("pi-onward", after);
415
+ this.statusText = after;
416
+ }
417
+ }
418
+ export function stateText(state: RunState, failures: number): string | undefined {
419
+ if (state.phase === "idle") return undefined;
420
+ const phases = {
421
+ waiting: "等待",
422
+ submitted: "提议已提交",
423
+ retrying: "续跑中",
424
+ queued: "待执行",
425
+ executing: "执行中",
426
+ stopped: "已停止",
427
+ };
428
+ return `${state.phase === "stopped" ? "🛑" : "⏩"} onward · ${phases[state.phase]} · 失败 ${failures} 次${state.hit ? ` · ${state.hit.stage.action.use}` : ""}`;
429
+ }
430
+ function validResult(value: unknown, definition: ActionDefinition): value is ActionResult {
431
+ if (!isRecord(value) || typeof value.kind !== "string") return false;
432
+ if (value.kind === "continue")
433
+ return (
434
+ definition.phase === "boundary" &&
435
+ Array.isArray(value.entries) &&
436
+ value.entries.every(
437
+ (entry: unknown) =>
438
+ isRecord(entry) &&
439
+ ["custom", "custom_message", "context_edit", "compaction"].includes(String(entry.type)),
440
+ )
441
+ );
442
+ if (value.kind === "handoff" && !definition.handoff) return false;
443
+ if (["completed", "dispatched", "handoff"].includes(value.kind))
444
+ return value.message === undefined || typeof value.message === "string";
445
+ return ["stopped", "failed", "cancelled", "unknown"].includes(value.kind) && typeof value.message === "string";
446
+ }
447
+ async function wait(ms: number, signal: AbortSignal): Promise<void> {
448
+ if (signal.aborted || ms <= 0) return;
449
+ await new Promise<void>((resolve) => {
450
+ const done = () => {
451
+ clearTimeout(timer);
452
+ signal.removeEventListener("abort", done);
453
+ resolve();
454
+ };
455
+ const timer = setTimeout(done, ms);
456
+ signal.addEventListener("abort", done, { once: true });
457
+ });
458
+ }
459
+ async function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
460
+ let abort: () => void = () => {};
461
+ try {
462
+ return await Promise.race([
463
+ promise,
464
+ new Promise<undefined>((resolve) => {
465
+ abort = () => resolve(undefined);
466
+ if (signal.aborted) abort();
467
+ else signal.addEventListener("abort", abort, { once: true });
468
+ }),
469
+ ]);
470
+ } finally {
471
+ signal.removeEventListener("abort", abort);
472
+ }
473
+ }
@@ -1,208 +0,0 @@
1
- /**
2
- * 一轮以错误收尾、或者正常结束却是空回复,并且命中规则时,在 `agent_before_settle` 边界上等一会儿,再要 pi 接着跑:
3
- * - message:追加一条看得见的消息(默认「继续」),模型照常读到;
4
- * - resend:用 `context_edit` 把失败的那条从模型上下文里省略,重发同一个请求。失败的记录仍留在会话里。
5
- *
6
- * 等待和续跑都在这一轮之内完成,不靠落定后的定时器,所以 `pi -p`、RPC、subagent 子会话里一样生效。
7
- */
8
- import type {
9
- AgentBeforeSettleEvent,
10
- AgentBeforeSettleEventResult,
11
- ExtensionContext,
12
- MessageEndEvent,
13
- SessionBoundaryDraft,
14
- } from "@earendil-works/pi-coding-agent";
15
- import { type Hit, matchFailure } from "../policy/config.ts";
16
- import { isSuccess } from "../policy/failure.ts";
17
- import { renderPrompt } from "../policy/policy.ts";
18
- import { type Progress, type Retry, Tracker } from "../policy/tracker.ts";
19
- import type { Settings } from "./settings.ts";
20
- import { errorExcerpt, giveUpNotice, giveUpStatus, retryNotice, retryStatus, say } from "./text.ts";
21
-
22
- type Ctx = Pick<ExtensionContext, "sessionManager" | "hasUI" | "ui">;
23
-
24
- /** 状态栏里本扩展的那一格。 */
25
- const STATUS_KEY = "pi-onward";
26
-
27
- /** 续跑消息的类型,render.ts 按它画。 */
28
- export const CUSTOM_TYPE = "pi-onward";
29
-
30
- /** 续跑消息带的 details:只给界面画标签,模型只读到 content。 */
31
- export interface ContinueDetails {
32
- rule: string;
33
- attempt: number;
34
- max: number;
35
- }
36
-
37
- /** 怎么接着跑:resend 省略失败的那条重发,message 追加一条文字消息。 */
38
- export type Continue =
39
- | Extract<SessionBoundaryDraft, { type: "context_edit" }>
40
- | (Extract<SessionBoundaryDraft, { type: "custom_message" }> & { content: string; details: ContinueDetails });
41
-
42
- /**
43
- * 每个会话由哪个实例负责。同一个会话装了两份(例如 subagent 既按包加载、又按路径加载了一份副本),
44
- * 两份各自计数:一份到上限停手,另一份照样续跑,互相接力永远停不下来。所以只让先到的那份干活;
45
- * reload 和子会话销毁前 pi 都会发 session_shutdown,在那里交还。
46
- */
47
- const shared = globalThis as typeof globalThis & { __piOnwardOwners?: Map<string, object> };
48
- shared.__piOnwardOwners ??= new Map();
49
- const owners = shared.__piOnwardOwners;
50
-
51
- export class Onward {
52
- private readonly settings: Settings;
53
- private readonly tracker = new Tracker();
54
- /**
55
- * 接下来的 agent_start 是我们 `continue: true` 出来的。pi 会为它重新发 agent_start,
56
- * 按新一轮清零的话计数永远到不了上限,会死循环。
57
- */
58
- private continuing = false;
59
- /** 正在等待的那次续跑;关掉、恢复默认、会话结束时打断它。 */
60
- private waiting: AbortController | undefined;
61
- /**
62
- * 状态栏里写着什么:retrying 是第几次续跑,这一轮结束就清掉;gave-up 是停了,留到恢复或用户发新消息。
63
- * 只有干活的那份会写,所以清的时候不用再问是谁的。
64
- */
65
- private statusBar: "retrying" | "gave-up" | undefined;
66
-
67
- constructor(settings: Settings) {
68
- this.settings = settings;
69
- }
70
-
71
- agentStart(ctx: Ctx): void {
72
- if (!this.owns(ctx)) return;
73
- if (!this.continuing) this.reset(ctx);
74
- this.continuing = false;
75
- }
76
-
77
- messageEnd(event: MessageEndEvent, ctx: Ctx): void {
78
- // 续跑之后只要正常返回过一次就算恢复了:后面再出错是新的一串,次数从头算。空回复不算正常返回。
79
- if (this.owns(ctx) && isSuccess(event.message)) this.reset(ctx);
80
- }
81
-
82
- /** 等待期间这一轮仍算忙:按 Esc 打断等待;用户输入的消息优先,我们让路。 */
83
- async beforeSettle(
84
- event: AgentBeforeSettleEvent,
85
- ctx: ExtensionContext,
86
- ): Promise<AgentBeforeSettleEventResult | undefined> {
87
- this.continuing = false;
88
- if (!this.owns(ctx)) return undefined;
89
- // 别的扩展已经要求继续:再插一条会改掉它要重发的内容。
90
- if (event.outcome === "aborted" || event.continue || ctx.hasPendingMessages()) return undefined;
91
- const entry = event.context.contextEntries.at(-1);
92
- const hit = matchFailure(this.settings.config, entry?.messages.at(-1));
93
- if (!entry || !hit) return undefined;
94
- const step = this.advance(hit, ctx);
95
- if (!step) return undefined;
96
- const draft: Continue =
97
- hit.policy.action === "resend"
98
- ? { type: "context_edit", targetId: entry.sourceEntry.id, replacement: null }
99
- : {
100
- type: "custom_message",
101
- customType: CUSTOM_TYPE,
102
- content: this.prompt(hit, step),
103
- display: true,
104
- details: { rule: hit.rule.name, attempt: step.attempt, max: hit.policy.maxRetries },
105
- };
106
- say(ctx, retryNotice(step, draft, hit.failure));
107
- this.setStatus(ctx, "retrying", retryStatus(hit, step));
108
- if (await this.wait(step.delay, ctx.signal)) return undefined;
109
- // 等的时候用户发了消息:pi 会接着处理它,这算用户开的新一轮。
110
- if (ctx.hasPendingMessages()) {
111
- this.reset(ctx);
112
- return undefined;
113
- }
114
- this.continuing = true;
115
- // 边界结果会整体替换前面扩展提出的条目,所以带上它们。
116
- return { entries: [...event.entries, draft], continue: true };
117
- }
118
-
119
- /**
120
- * 这一轮彻底结束了;pi 不接受续跑时,`continuing` 不能留到下一轮。没有接着跑(按了 Esc、错误没命中规则),
121
- * 「第几次」就不再成立;停了的提示留着。
122
- */
123
- settled(ctx: Ctx): void {
124
- this.continuing = false;
125
- if (this.statusBar === "retrying") this.setStatus(ctx, undefined);
126
- }
127
-
128
- /** 关掉、恢复默认时:打断正在等的续跑,清零计数。 */
129
- stop(ctx: Ctx): void {
130
- this.waiting?.abort();
131
- this.reset(ctx);
132
- this.continuing = false;
133
- }
134
-
135
- shutdown(ctx: Ctx): void {
136
- this.stop(ctx);
137
- const session = ctx.sessionManager.getSessionId();
138
- if (owners.get(session) === this) owners.delete(session);
139
- }
140
-
141
- progress(): Progress {
142
- return this.tracker.progress();
143
- }
144
-
145
- private owns(ctx: Ctx): boolean {
146
- const session = ctx.sessionManager.getSessionId();
147
- const owner = owners.get(session);
148
- if (owner === undefined) owners.set(session, this);
149
- return owner === undefined || owner === this;
150
- }
151
-
152
- /** 再试就返回这一步;该停了就提醒并返回 undefined。 */
153
- private advance(hit: Hit, ctx: ExtensionContext): Retry | undefined {
154
- const step = this.tracker.next(hit.rule.name, hit.failure, hit.policy);
155
- if (step.retry) return step;
156
- if (step.notify) say(ctx, giveUpNotice(step));
157
- this.setStatus(ctx, "gave-up", giveUpStatus(hit, step));
158
- return undefined;
159
- }
160
-
161
- /** 计数从头算,状态栏也清掉。 */
162
- private reset(ctx: Ctx): void {
163
- this.tracker.reset();
164
- if (this.statusBar !== undefined) this.setStatus(ctx, undefined);
165
- }
166
-
167
- /** 没有界面时(`pi -p`)不写;RPC 下 pi 把它发给客户端。 */
168
- private setStatus(ctx: Ctx, status: "retrying" | "gave-up" | undefined, text?: string): void {
169
- this.statusBar = status;
170
- if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, text);
171
- }
172
-
173
- private prompt(hit: Hit, step: Retry): string {
174
- return renderPrompt(hit.policy.prompt, {
175
- attempt: step.attempt,
176
- max: hit.policy.maxRetries,
177
- error: errorExcerpt(hit.failure, 120),
178
- rule: hit.rule.name,
179
- });
180
- }
181
-
182
- /** 返回 true 表示被打断。 */
183
- private async wait(ms: number, signal: AbortSignal | undefined): Promise<boolean> {
184
- const waiting = new AbortController();
185
- this.waiting = waiting;
186
- try {
187
- return await sleep(ms, signal ? AbortSignal.any([signal, waiting.signal]) : waiting.signal);
188
- } finally {
189
- if (this.waiting === waiting) this.waiting = undefined;
190
- }
191
- }
192
- }
193
-
194
- /** 不 unref:等待期间这一轮还忙,进程不该因为只剩它在等就退出。 */
195
- function sleep(ms: number, signal: AbortSignal): Promise<boolean> {
196
- if (signal.aborted) return Promise.resolve(true);
197
- if (ms <= 0) return Promise.resolve(false);
198
- return new Promise((resolve) => {
199
- const finish = (aborted: boolean): void => {
200
- clearTimeout(timer);
201
- signal.removeEventListener("abort", onAbort);
202
- resolve(aborted);
203
- };
204
- const onAbort = (): void => finish(true);
205
- const timer = setTimeout(() => finish(false), ms);
206
- signal.addEventListener("abort", onAbort, { once: true });
207
- });
208
- }