@cobia/pi-onward 0.3.1 → 0.4.1
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 +186 -171
- package/docs/actions.md +97 -0
- package/example.json +18 -57
- package/onward.schema.json +86 -90
- package/package.json +9 -2
- package/src/actions/builtins.ts +25 -0
- package/src/actions/pi.ts +70 -0
- package/src/actions/protocol.ts +136 -0
- package/src/actions/registry.ts +112 -0
- package/src/extension/autocomplete.ts +1 -3
- package/src/extension/command.ts +157 -184
- package/src/extension/index.ts +1 -12
- package/src/extension/install.ts +10 -7
- package/src/extension/render.ts +2 -10
- package/src/extension/settings.ts +81 -77
- package/src/extension/text.ts +309 -438
- package/src/policy/config.ts +35 -85
- package/src/policy/delay.ts +10 -27
- package/src/policy/failure.ts +3 -31
- package/src/policy/policy.ts +63 -157
- package/src/policy/rules.ts +124 -101
- package/src/policy/schema.ts +65 -72
- package/src/runtime/episode.ts +19 -0
- package/src/runtime/recovery.ts +470 -0
- package/src/runtime/task-prompt.ts +82 -0
- package/src/extension/onward.ts +0 -208
- package/src/policy/tracker.ts +0 -64
|
@@ -0,0 +1,470 @@
|
|
|
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
|
+
BeforeAgentStartEvent,
|
|
9
|
+
ExtensionAPI,
|
|
10
|
+
ExtensionCommandContext,
|
|
11
|
+
ExtensionContext,
|
|
12
|
+
InputEvent,
|
|
13
|
+
MessageEndEvent,
|
|
14
|
+
} from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { builtinActions } from "../actions/builtins.ts";
|
|
16
|
+
import {
|
|
17
|
+
type ActionContext,
|
|
18
|
+
type ActionDefinition,
|
|
19
|
+
type ActionResult,
|
|
20
|
+
isRecoveryChain,
|
|
21
|
+
RESUME_RECOVERY,
|
|
22
|
+
type RecoveryChain,
|
|
23
|
+
} from "../actions/protocol.ts";
|
|
24
|
+
import { ActionRegistry } from "../actions/registry.ts";
|
|
25
|
+
import type { Settings } from "../extension/settings.ts";
|
|
26
|
+
import { type Hit, isActive, matchFailure } from "../policy/config.ts";
|
|
27
|
+
import { formatDelay, retryDelay } from "../policy/delay.ts";
|
|
28
|
+
import { failureText, isFailure, isSuccess } from "../policy/failure.ts";
|
|
29
|
+
import { resolveLimits } from "../policy/policy.ts";
|
|
30
|
+
import { errorText, isRecord } from "../util.ts";
|
|
31
|
+
import { Episode } from "./episode.ts";
|
|
32
|
+
import { INPUT_RECORD, TaskPrompt } from "./task-prompt.ts";
|
|
33
|
+
|
|
34
|
+
export interface RunState {
|
|
35
|
+
phase: "idle" | "waiting" | "submitted" | "retrying" | "queued" | "executing" | "stopped";
|
|
36
|
+
hit?: Hit;
|
|
37
|
+
invocationId?: string;
|
|
38
|
+
result?: ActionResult["kind"];
|
|
39
|
+
message?: string;
|
|
40
|
+
}
|
|
41
|
+
export interface OnwardStatus {
|
|
42
|
+
state: RunState;
|
|
43
|
+
failures: number;
|
|
44
|
+
started: number;
|
|
45
|
+
handoffs: number;
|
|
46
|
+
}
|
|
47
|
+
interface Invocation {
|
|
48
|
+
id: string;
|
|
49
|
+
hit: Hit;
|
|
50
|
+
definition: ActionDefinition;
|
|
51
|
+
targetId: string;
|
|
52
|
+
controller: AbortController;
|
|
53
|
+
config: Settings["config"];
|
|
54
|
+
sessionId: string;
|
|
55
|
+
taskPrompt: string | undefined;
|
|
56
|
+
}
|
|
57
|
+
const shared = globalThis as typeof globalThis & { __piOnwardRecoveryOwners?: Map<string, object> };
|
|
58
|
+
shared.__piOnwardRecoveryOwners ??= new Map();
|
|
59
|
+
const owners = shared.__piOnwardRecoveryOwners;
|
|
60
|
+
const ENTRY_PATH = fileURLToPath(new URL("../extension/index.ts", import.meta.url));
|
|
61
|
+
|
|
62
|
+
export class Recovery {
|
|
63
|
+
readonly registry = new ActionRegistry();
|
|
64
|
+
private episode: Episode;
|
|
65
|
+
private state: RunState = { phase: "idle" };
|
|
66
|
+
private pending: Invocation | undefined;
|
|
67
|
+
private disposed = false;
|
|
68
|
+
private sessionId: string | undefined;
|
|
69
|
+
private readonly taskPrompt = new TaskPrompt();
|
|
70
|
+
private statusText: string | undefined;
|
|
71
|
+
private restored: { sessionId: string; chain: RecoveryChain } | undefined;
|
|
72
|
+
constructor(
|
|
73
|
+
private readonly pi: ExtensionAPI,
|
|
74
|
+
private readonly settings: Settings,
|
|
75
|
+
) {
|
|
76
|
+
this.episode = new Episode(resolveLimits(settings.config.limits).maxHandoffs);
|
|
77
|
+
pi.events.on(RESUME_RECOVERY, (value) => {
|
|
78
|
+
if (!isRecord(value) || typeof value.sessionId !== "string" || !isRecoveryChain(value.chain)) return;
|
|
79
|
+
if (this.disposed || (this.sessionId && value.sessionId !== this.sessionId)) return;
|
|
80
|
+
if (this.sessionId === value.sessionId) {
|
|
81
|
+
this.episode.chain = { ...value.chain };
|
|
82
|
+
} else this.restored = { sessionId: value.sessionId, chain: { ...value.chain } };
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
start(ctx: ExtensionContext): void {
|
|
86
|
+
this.sessionId = ctx.sessionManager.getSessionId();
|
|
87
|
+
this.disposed = false;
|
|
88
|
+
if (!this.owns(ctx)) return;
|
|
89
|
+
this.registry.discover(this.pi, builtinActions(this.pi));
|
|
90
|
+
this.settings.setActionValidator((config) => this.registry.problems(config));
|
|
91
|
+
this.branch(ctx);
|
|
92
|
+
if (this.restored?.sessionId === ctx.sessionManager.getSessionId())
|
|
93
|
+
this.episode.chain = { ...this.restored.chain };
|
|
94
|
+
this.restored = undefined;
|
|
95
|
+
}
|
|
96
|
+
input(event: InputEvent, ctx: ExtensionContext): void {
|
|
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);
|
|
101
|
+
}
|
|
102
|
+
agentStart(ctx: ExtensionContext): void {
|
|
103
|
+
if (!this.owns(ctx)) return;
|
|
104
|
+
if (this.state.phase === "submitted" && this.pending) {
|
|
105
|
+
const invocation = this.pending;
|
|
106
|
+
this.pending = undefined;
|
|
107
|
+
if (ctx.signal?.aborted) {
|
|
108
|
+
this.setState(ctx, { phase: "idle" });
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
this.episode.started++;
|
|
112
|
+
this.setState(ctx, { phase: "retrying", hit: invocation.hit, invocationId: invocation.id });
|
|
113
|
+
} else if (this.pending) {
|
|
114
|
+
// Another extension continued after our proposal. The old settled action must not survive.
|
|
115
|
+
this.pending.controller.abort();
|
|
116
|
+
this.pending = undefined;
|
|
117
|
+
this.setState(ctx, { phase: "idle" });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
messageEnd(event: MessageEndEvent, ctx: ExtensionContext): void {
|
|
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);
|
|
135
|
+
}
|
|
136
|
+
async beforeSettle(
|
|
137
|
+
event: AgentBeforeSettleEvent,
|
|
138
|
+
ctx: ExtensionContext,
|
|
139
|
+
): Promise<AgentBeforeSettleEventResult | undefined> {
|
|
140
|
+
if (
|
|
141
|
+
!this.owns(ctx) ||
|
|
142
|
+
this.disposed ||
|
|
143
|
+
this.state.phase === "stopped" ||
|
|
144
|
+
this.pending ||
|
|
145
|
+
!isActive(this.settings.config)
|
|
146
|
+
)
|
|
147
|
+
return;
|
|
148
|
+
if (event.outcome === "aborted" || ctx.signal?.aborted || event.continue || ctx.hasPendingMessages()) return;
|
|
149
|
+
const entry = event.context.contextEntries.at(-1);
|
|
150
|
+
const message = entry?.messages.at(-1);
|
|
151
|
+
if (!entry || !isFailure(message) || !this.episode.observe(entry.sourceEntry.id)) return;
|
|
152
|
+
const hit = matchFailure(this.settings.config, message, this.episode.failures);
|
|
153
|
+
if (!hit) {
|
|
154
|
+
this.finish(ctx, { kind: "stopped", message: "没有命中恢复规则" });
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (this.episode.failures > hit.limits.maxFailures) {
|
|
158
|
+
this.finish(ctx, { kind: "stopped", message: `连续失败超过 ${hit.limits.maxFailures} 次上限` }, hit);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const definition = this.registry.get(hit.stage.action.use)?.definition;
|
|
162
|
+
const problem = this.registry.check(hit.stage.action);
|
|
163
|
+
if (problem || !definition) {
|
|
164
|
+
this.finish(ctx, { kind: "failed", message: problem ?? "Action is not loaded" }, hit);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!definition.modes.includes(ctx.mode)) {
|
|
168
|
+
this.finish(ctx, { kind: "failed", message: `${definition.name} does not support ${ctx.mode} mode` }, hit);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const chain = this.episode.chain;
|
|
172
|
+
chain.maxHandoffs = Math.min(chain.maxHandoffs, hit.limits.maxHandoffs);
|
|
173
|
+
if (definition.handoff && chain.handoffs >= chain.maxHandoffs) {
|
|
174
|
+
this.finish(ctx, { kind: "stopped", message: `达到跨会话接管上限 ${chain.maxHandoffs} 次` }, hit);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
this.taskPrompt.refresh(ctx.sessionManager.getBranch());
|
|
178
|
+
const invocation: Invocation = {
|
|
179
|
+
id: randomUUID(),
|
|
180
|
+
hit,
|
|
181
|
+
definition,
|
|
182
|
+
targetId: entry.sourceEntry.id,
|
|
183
|
+
controller: new AbortController(),
|
|
184
|
+
config: this.settings.config,
|
|
185
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
186
|
+
taskPrompt: this.taskPrompt.value,
|
|
187
|
+
};
|
|
188
|
+
this.pending = invocation;
|
|
189
|
+
const signal = ctx.signal
|
|
190
|
+
? AbortSignal.any([ctx.signal, invocation.controller.signal])
|
|
191
|
+
: invocation.controller.signal;
|
|
192
|
+
this.setState(ctx, { phase: "waiting", hit, invocationId: invocation.id });
|
|
193
|
+
const delay = retryDelay(this.episode.failures - hit.stage.minFailures + 1, hit.stage.delay);
|
|
194
|
+
this.notice(ctx, `${formatDelay(delay)}后执行 ${definition.name}(连续失败 ${this.episode.failures} 次)`);
|
|
195
|
+
await wait(delay, signal);
|
|
196
|
+
if (!this.current(invocation, ctx)) return;
|
|
197
|
+
if (signal.aborted || ctx.hasPendingMessages()) {
|
|
198
|
+
this.cancel(ctx, "等待已取消");
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (definition.phase === "settled") {
|
|
202
|
+
this.setState(ctx, { phase: "queued", hit, invocationId: invocation.id });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const result = await this.invoke(invocation, {
|
|
206
|
+
...this.execution(invocation, signal),
|
|
207
|
+
phase: "boundary",
|
|
208
|
+
targetId: invocation.targetId,
|
|
209
|
+
});
|
|
210
|
+
if (!this.current(invocation, ctx)) return;
|
|
211
|
+
if (signal.aborted || ctx.hasPendingMessages()) {
|
|
212
|
+
this.cancel(ctx, "续跑提议已取消");
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (result.kind === "continue") {
|
|
216
|
+
this.setState(ctx, { phase: "submitted", hit, invocationId: invocation.id });
|
|
217
|
+
return { entries: [...event.entries, ...result.entries], continue: true };
|
|
218
|
+
}
|
|
219
|
+
this.pending = undefined;
|
|
220
|
+
this.finish(ctx, result, hit);
|
|
221
|
+
}
|
|
222
|
+
settled(event: AgentSettledEvent, ctx: ExtensionContext): void {
|
|
223
|
+
if (!this.owns(ctx)) return;
|
|
224
|
+
if (!ctx.hasPendingMessages()) this.taskPrompt.clearPending();
|
|
225
|
+
if (event.aborted) {
|
|
226
|
+
if (this.pending) this.cancel(ctx, "用户取消了恢复");
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (this.state.phase === "queued" && this.pending) {
|
|
230
|
+
const invocation = this.pending;
|
|
231
|
+
if (!this.current(invocation, ctx) || ctx.hasPendingMessages()) {
|
|
232
|
+
this.cancel(ctx, "待执行动作已取消");
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const command = this.pi
|
|
236
|
+
.getCommands()
|
|
237
|
+
.find(
|
|
238
|
+
(command) =>
|
|
239
|
+
command.source === "extension" &&
|
|
240
|
+
command.sourceInfo.path === ENTRY_PATH &&
|
|
241
|
+
(command.name === "onward" || command.name.startsWith("onward:")),
|
|
242
|
+
);
|
|
243
|
+
if (!command) {
|
|
244
|
+
this.pending = undefined;
|
|
245
|
+
this.finish(ctx, { kind: "failed", message: "Onward dispatch command is unavailable" }, invocation.hit);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
// Pi defers this command until ALL agent_settled handlers finish.
|
|
249
|
+
this.pi.sendUserMessage(`/${command.name} _dispatch ${invocation.id}`, { expandPromptTemplates: true });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (this.state.phase === "submitted") {
|
|
253
|
+
this.pending = undefined;
|
|
254
|
+
this.setState(ctx, { phase: "idle" });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/** Private nonce-based bridge, reached through Pi's real ExtensionCommandContext. */
|
|
258
|
+
async dispatch(id: string, ctx: ExtensionCommandContext): Promise<void> {
|
|
259
|
+
const invocation = this.pending;
|
|
260
|
+
if (!invocation || invocation.id !== id || this.state.phase !== "queued" || !this.current(invocation, ctx))
|
|
261
|
+
return;
|
|
262
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
263
|
+
this.cancel(ctx, "新的任务优先,待执行动作已取消");
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
this.setState(ctx, { phase: "executing", hit: invocation.hit, invocationId: id });
|
|
267
|
+
if (invocation.definition.handoff) this.episode.chain.handoffs++;
|
|
268
|
+
// Durable intent, without prompts or errors: it is diagnostic only and never replayed.
|
|
269
|
+
this.pi.appendEntry("onward.action", {
|
|
270
|
+
invocationId: id,
|
|
271
|
+
episodeId: this.episode.id,
|
|
272
|
+
action: invocation.definition.name,
|
|
273
|
+
status: "started",
|
|
274
|
+
chain: { ...this.episode.chain },
|
|
275
|
+
});
|
|
276
|
+
const result = await this.invoke(invocation, {
|
|
277
|
+
...this.execution(invocation, invocation.controller.signal),
|
|
278
|
+
phase: "settled",
|
|
279
|
+
host: ctx,
|
|
280
|
+
});
|
|
281
|
+
if (!this.current(invocation, ctx)) return;
|
|
282
|
+
if (invocation.definition.handoff && ["completed", "failed", "cancelled", "stopped"].includes(result.kind))
|
|
283
|
+
this.episode.chain.handoffs--;
|
|
284
|
+
this.pending = undefined;
|
|
285
|
+
this.pi.appendEntry("onward.action", { invocationId: id, status: result.kind });
|
|
286
|
+
this.finish(ctx, result, invocation.hit);
|
|
287
|
+
}
|
|
288
|
+
branch(ctx: ExtensionContext): void {
|
|
289
|
+
if (!this.owns(ctx)) return;
|
|
290
|
+
this.taskPrompt.restore(ctx.sessionManager.getBranch());
|
|
291
|
+
this.reset(ctx);
|
|
292
|
+
}
|
|
293
|
+
stop(ctx: ExtensionContext): void {
|
|
294
|
+
if (this.owns(ctx)) this.reset(ctx);
|
|
295
|
+
}
|
|
296
|
+
shutdown(ctx: ExtensionContext): void {
|
|
297
|
+
this.taskPrompt.clearPending();
|
|
298
|
+
this.pending?.controller.abort();
|
|
299
|
+
this.pending = undefined;
|
|
300
|
+
this.disposed = true;
|
|
301
|
+
if (owners.get(ctx.sessionManager.getSessionId()) === this) {
|
|
302
|
+
this.setState(ctx, { phase: "idle" });
|
|
303
|
+
owners.delete(ctx.sessionManager.getSessionId());
|
|
304
|
+
}
|
|
305
|
+
this.registry.clear();
|
|
306
|
+
}
|
|
307
|
+
status(): OnwardStatus {
|
|
308
|
+
return {
|
|
309
|
+
state: this.state,
|
|
310
|
+
failures: this.episode.failures,
|
|
311
|
+
started: this.episode.started,
|
|
312
|
+
handoffs: this.episode.chain.handoffs,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
private execution(invocation: Invocation, signal: AbortSignal) {
|
|
316
|
+
const { failure, rule, stage } = invocation.hit;
|
|
317
|
+
return {
|
|
318
|
+
invocationId: invocation.id,
|
|
319
|
+
episodeId: this.episode.id,
|
|
320
|
+
sessionId: invocation.sessionId,
|
|
321
|
+
rule: rule.name,
|
|
322
|
+
failures: this.episode.failures,
|
|
323
|
+
minFailures: stage.minFailures,
|
|
324
|
+
taskPrompt: invocation.taskPrompt,
|
|
325
|
+
signal,
|
|
326
|
+
chain: Object.freeze({ ...this.episode.chain }),
|
|
327
|
+
failure: Object.freeze({
|
|
328
|
+
kind: failure.stopReason === "error" ? ("error" as const) : ("empty" as const),
|
|
329
|
+
text: failureText(failure),
|
|
330
|
+
provider: failure.provider,
|
|
331
|
+
model: failure.model,
|
|
332
|
+
}),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
private async invoke(invocation: Invocation, context: ActionContext): Promise<ActionResult> {
|
|
336
|
+
const timeout = new AbortController();
|
|
337
|
+
const signal = AbortSignal.any([context.signal, timeout.signal]);
|
|
338
|
+
const timer = setTimeout(() => timeout.abort(), invocation.hit.limits.actionTimeout);
|
|
339
|
+
try {
|
|
340
|
+
if (signal.aborted) return { kind: "cancelled", message: "动作已取消" };
|
|
341
|
+
const execute = async (): Promise<ActionResult> => {
|
|
342
|
+
const definition = invocation.definition;
|
|
343
|
+
const params = this.registry.parameters(invocation.hit.stage.action);
|
|
344
|
+
if (definition.phase === "boundary" && context.phase === "boundary")
|
|
345
|
+
return definition.execute(params, { ...context, signal });
|
|
346
|
+
if (definition.phase === "settled" && context.phase === "settled")
|
|
347
|
+
return definition.execute(params, { ...context, signal });
|
|
348
|
+
return { kind: "failed", message: "Action execution phase does not match its context" };
|
|
349
|
+
};
|
|
350
|
+
const result = await raceAbort(execute(), signal);
|
|
351
|
+
if (signal.aborted)
|
|
352
|
+
return {
|
|
353
|
+
kind: "unknown",
|
|
354
|
+
message: timeout.signal.aborted
|
|
355
|
+
? "Action timed out; outcome unknown; not replayed"
|
|
356
|
+
: "Execution cancelled; side-effect outcome unknown",
|
|
357
|
+
};
|
|
358
|
+
if (!validResult(result, invocation.definition))
|
|
359
|
+
return { kind: "unknown", message: "Action returned an invalid result; not replayed" };
|
|
360
|
+
return result;
|
|
361
|
+
} catch (error) {
|
|
362
|
+
return { kind: "unknown", message: `Action threw an exception; outcome unknown: ${errorText(error)}` };
|
|
363
|
+
} finally {
|
|
364
|
+
clearTimeout(timer);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
private current(invocation: Invocation, ctx: ExtensionContext): boolean {
|
|
368
|
+
return (
|
|
369
|
+
!this.disposed &&
|
|
370
|
+
this.pending === invocation &&
|
|
371
|
+
!invocation.controller.signal.aborted &&
|
|
372
|
+
invocation.config === this.settings.config &&
|
|
373
|
+
isActive(this.settings.config) &&
|
|
374
|
+
ctx.sessionManager.getSessionId() === invocation.sessionId &&
|
|
375
|
+
owners.get(invocation.sessionId) === this
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
private owns(ctx: Pick<ExtensionContext, "sessionManager">): boolean {
|
|
379
|
+
if (this.disposed) return false;
|
|
380
|
+
const id = ctx.sessionManager.getSessionId();
|
|
381
|
+
if (!owners.has(id)) owners.set(id, this);
|
|
382
|
+
return owners.get(id) === this;
|
|
383
|
+
}
|
|
384
|
+
private reset(ctx: ExtensionContext): void {
|
|
385
|
+
this.pending?.controller.abort();
|
|
386
|
+
this.pending = undefined;
|
|
387
|
+
this.episode = new Episode(resolveLimits(this.settings.config.limits).maxHandoffs);
|
|
388
|
+
this.setState(ctx, { phase: "idle" });
|
|
389
|
+
}
|
|
390
|
+
private cancel(ctx: ExtensionContext, message: string): void {
|
|
391
|
+
const hit = this.pending?.hit;
|
|
392
|
+
this.pending?.controller.abort();
|
|
393
|
+
this.pending = undefined;
|
|
394
|
+
if (this.state.phase !== "idle") this.finish(ctx, { kind: "cancelled", message }, hit);
|
|
395
|
+
}
|
|
396
|
+
private finish(ctx: ExtensionContext, result: ActionResult, hit?: Hit): void {
|
|
397
|
+
const message = "message" in result ? result.message : undefined;
|
|
398
|
+
this.setState(ctx, { phase: "stopped", hit, result: result.kind, message });
|
|
399
|
+
this.notice(
|
|
400
|
+
ctx,
|
|
401
|
+
message ?? `${hit?.stage.action.use ?? "恢复"}:${result.kind}`,
|
|
402
|
+
!["completed", "handoff", "dispatched"].includes(result.kind),
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
private notice(ctx: ExtensionContext, text: string, warning = false): void {
|
|
406
|
+
if (ctx.hasUI) ctx.ui.notify(`onward:${text}`, warning ? "warning" : "info");
|
|
407
|
+
}
|
|
408
|
+
private setState(ctx: ExtensionContext, state: RunState): void {
|
|
409
|
+
this.state = state;
|
|
410
|
+
const after = stateText(state, this.episode.failures);
|
|
411
|
+
if (ctx.hasUI && this.statusText !== after) ctx.ui.setStatus("pi-onward", after);
|
|
412
|
+
this.statusText = after;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
export function stateText(state: RunState, failures: number): string | undefined {
|
|
416
|
+
if (state.phase === "idle") return undefined;
|
|
417
|
+
const phases = {
|
|
418
|
+
waiting: "等待",
|
|
419
|
+
submitted: "提议已提交",
|
|
420
|
+
retrying: "续跑中",
|
|
421
|
+
queued: "待执行",
|
|
422
|
+
executing: "执行中",
|
|
423
|
+
stopped: "已停止",
|
|
424
|
+
};
|
|
425
|
+
return `${state.phase === "stopped" ? "🛑" : "⏩"} onward · ${phases[state.phase]} · 失败 ${failures} 次${state.hit ? ` · ${state.hit.stage.action.use}` : ""}`;
|
|
426
|
+
}
|
|
427
|
+
function validResult(value: unknown, definition: ActionDefinition): value is ActionResult {
|
|
428
|
+
if (!isRecord(value) || typeof value.kind !== "string") return false;
|
|
429
|
+
if (value.kind === "continue")
|
|
430
|
+
return (
|
|
431
|
+
definition.phase === "boundary" &&
|
|
432
|
+
Array.isArray(value.entries) &&
|
|
433
|
+
value.entries.every(
|
|
434
|
+
(entry: unknown) =>
|
|
435
|
+
isRecord(entry) &&
|
|
436
|
+
["custom", "custom_message", "context_edit", "compaction"].includes(String(entry.type)),
|
|
437
|
+
)
|
|
438
|
+
);
|
|
439
|
+
if (value.kind === "handoff" && !definition.handoff) return false;
|
|
440
|
+
if (["completed", "dispatched", "handoff"].includes(value.kind))
|
|
441
|
+
return value.message === undefined || typeof value.message === "string";
|
|
442
|
+
return ["stopped", "failed", "cancelled", "unknown"].includes(value.kind) && typeof value.message === "string";
|
|
443
|
+
}
|
|
444
|
+
async function wait(ms: number, signal: AbortSignal): Promise<void> {
|
|
445
|
+
if (signal.aborted || ms <= 0) return;
|
|
446
|
+
await new Promise<void>((resolve) => {
|
|
447
|
+
const done = () => {
|
|
448
|
+
clearTimeout(timer);
|
|
449
|
+
signal.removeEventListener("abort", done);
|
|
450
|
+
resolve();
|
|
451
|
+
};
|
|
452
|
+
const timer = setTimeout(done, ms);
|
|
453
|
+
signal.addEventListener("abort", done, { once: true });
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
async function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | undefined> {
|
|
457
|
+
let abort: () => void = () => {};
|
|
458
|
+
try {
|
|
459
|
+
return await Promise.race([
|
|
460
|
+
promise,
|
|
461
|
+
new Promise<undefined>((resolve) => {
|
|
462
|
+
abort = () => resolve(undefined);
|
|
463
|
+
if (signal.aborted) abort();
|
|
464
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
465
|
+
}),
|
|
466
|
+
]);
|
|
467
|
+
} finally {
|
|
468
|
+
signal.removeEventListener("abort", abort);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
@@ -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
|
+
}
|