@lune_99/pi-subagent 0.0.0-stage → 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.
- package/CHANGELOG.md +57 -0
- package/LICENSE +21 -0
- package/README.md +185 -2
- package/docs/capture.json +30 -0
- package/docs/previews.md +22 -0
- package/docs/reference.md +264 -0
- package/docs/subagent-auto-tiers.png +0 -0
- package/docs/subagent-inspector.png +0 -0
- package/docs/subagent-overview.png +0 -0
- package/package.json +82 -5
- package/skills/create-lune-subagent/SKILL.md +190 -0
- package/src/auto-model.ts +601 -0
- package/src/catalog.ts +111 -0
- package/src/definition-file.ts +147 -0
- package/src/definitions.ts +330 -0
- package/src/dock/dock-alert.ts +78 -0
- package/src/dock/dock-contribution.ts +328 -0
- package/src/extension-tools.ts +46 -0
- package/src/index.ts +194 -0
- package/src/inspector/details.ts +119 -0
- package/src/inspector/inspector.ts +677 -0
- package/src/inspector/layout.ts +119 -0
- package/src/inspector/transcript.ts +735 -0
- package/src/inspector/viewport.ts +62 -0
- package/src/inspector/wrap.ts +136 -0
- package/src/models.ts +69 -0
- package/src/notify/notification-box.ts +408 -0
- package/src/notify/notifier.ts +586 -0
- package/src/paths.ts +34 -0
- package/src/render/lune-theme.ts +68 -0
- package/src/render/text.ts +121 -0
- package/src/run/guide.ts +31 -0
- package/src/run/report-tool.ts +90 -0
- package/src/run/run-file.ts +194 -0
- package/src/run/run-manager.ts +935 -0
- package/src/run/run-session.ts +307 -0
- package/src/run/run.ts +773 -0
- package/src/run/session-start.ts +283 -0
- package/src/run/types.ts +175 -0
- package/src/run/worktree.ts +138 -0
- package/src/schema.ts +9 -0
- package/src/settings/agents-menu.ts +376 -0
- package/src/settings/panel.ts +221 -0
- package/src/settings/schema.ts +75 -0
- package/src/settings/thinking-choices.ts +92 -0
- package/src/tools/format.ts +397 -0
- package/src/tools/subagent-tools.ts +355 -0
package/src/run/run.ts
ADDED
|
@@ -0,0 +1,773 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdirSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
7
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
8
|
+
import type {
|
|
9
|
+
AgentSession,
|
|
10
|
+
AgentSessionEvent,
|
|
11
|
+
ModelRuntime,
|
|
12
|
+
Theme,
|
|
13
|
+
} from "@earendil-works/pi-coding-agent";
|
|
14
|
+
|
|
15
|
+
import type { ExtensionTool } from "../extension-tools.ts";
|
|
16
|
+
import { formatModelRef, parseModelRef } from "../models.ts";
|
|
17
|
+
import { markUserMessage, SUBAGENT_GUIDE } from "./guide.ts";
|
|
18
|
+
import { openRunFile, readRunEntries, transcriptMessages, usageFromEntries } from "./run-file.ts";
|
|
19
|
+
import { errorDiagnostic, type Diagnostic, type LiveSession } from "./run-session.ts";
|
|
20
|
+
import { SessionSink, startRunSession, type RunEventTarget } from "./session-start.ts";
|
|
21
|
+
import {
|
|
22
|
+
TURN_ENTRY_TYPE,
|
|
23
|
+
type RunReport,
|
|
24
|
+
type RunSnapshot,
|
|
25
|
+
type RunState,
|
|
26
|
+
type RunUsage,
|
|
27
|
+
type SettledState,
|
|
28
|
+
type StopSource,
|
|
29
|
+
type TurnRecord,
|
|
30
|
+
} from "./types.ts";
|
|
31
|
+
import { assertWorktreeUsable } from "./worktree.ts";
|
|
32
|
+
|
|
33
|
+
/** The longest last message a turn without a report hands to the main agent. */
|
|
34
|
+
const MAX_UNREPORTED_CHARS = 20_000;
|
|
35
|
+
/** The longest user message a turn record keeps; the run's transcript keeps the whole message. */
|
|
36
|
+
const MAX_USER_MESSAGE_CHARS = 20_000;
|
|
37
|
+
const MAX_DIAGNOSTICS = 50;
|
|
38
|
+
|
|
39
|
+
export type RunChange = "state" | "transcript";
|
|
40
|
+
|
|
41
|
+
/** What a run needs from the session that owns it. */
|
|
42
|
+
export interface RunHost {
|
|
43
|
+
readonly agentDir: string;
|
|
44
|
+
readonly modelRuntime?: ModelRuntime;
|
|
45
|
+
projectTrusted(): boolean;
|
|
46
|
+
theme(): Theme;
|
|
47
|
+
/** The parent's current extension tools; a resumed run loads the extensions of its own again. */
|
|
48
|
+
extensionTools(): readonly ExtensionTool[];
|
|
49
|
+
onChange(run: Run, change: RunChange): void;
|
|
50
|
+
onTurnEnd(run: Run, record: TurnRecord): void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface RunIdentity {
|
|
54
|
+
id: string;
|
|
55
|
+
file: string;
|
|
56
|
+
spawnEntryId: string;
|
|
57
|
+
/** The session that started the run; a different one inherited it through /fork or /clone. */
|
|
58
|
+
parentSessionId: string;
|
|
59
|
+
readOnly: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface RunningTool {
|
|
63
|
+
toolCallId: string;
|
|
64
|
+
name: string;
|
|
65
|
+
args: unknown;
|
|
66
|
+
partialResult?: unknown;
|
|
67
|
+
startedAt: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface ActiveTurn {
|
|
71
|
+
startedAt: string;
|
|
72
|
+
/** Every report of the turn, oldest first; the last one is the turn's report. */
|
|
73
|
+
reports: RunReport[];
|
|
74
|
+
/** What the user wrote from the inspector during the turn, oldest first, already cut. */
|
|
75
|
+
userMessages: string[];
|
|
76
|
+
stoppedBy?: StopSource;
|
|
77
|
+
error?: string;
|
|
78
|
+
/** The turn's last assistant reply, which the session may no longer hold. */
|
|
79
|
+
lastReply?: AssistantMessage;
|
|
80
|
+
/** Resolves once the turn's end is recorded. */
|
|
81
|
+
ended: Promise<void>;
|
|
82
|
+
end: () => void;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export type SendOutcome = "started" | "steered" | "deferred";
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* One subagent run: its snapshot, its state, and its session while it is live.
|
|
89
|
+
*
|
|
90
|
+
* A turn is everything between accepting a message and the session's `agent_settled`; that event is
|
|
91
|
+
* the only end of a turn, so steering messages and retries stay inside the turn they joined.
|
|
92
|
+
*/
|
|
93
|
+
export class Run implements RunEventTarget {
|
|
94
|
+
readonly id: string;
|
|
95
|
+
readonly file: string;
|
|
96
|
+
readonly spawnEntryId: string;
|
|
97
|
+
readonly parentSessionId: string;
|
|
98
|
+
readonly readOnly: boolean;
|
|
99
|
+
|
|
100
|
+
snapshot: RunSnapshot | undefined;
|
|
101
|
+
/** Set when the run file could not be read; such a run shows as failed and cannot continue. */
|
|
102
|
+
loadError: string | undefined;
|
|
103
|
+
state: RunState = "idle";
|
|
104
|
+
lastTurn: TurnRecord | undefined;
|
|
105
|
+
turns = 0;
|
|
106
|
+
usage: RunUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, cost: 0 };
|
|
107
|
+
readonly diagnostics: Diagnostic[] = [];
|
|
108
|
+
/** The assistant message being streamed, until its message_end. */
|
|
109
|
+
streaming: AgentMessage | undefined;
|
|
110
|
+
readonly runningTools = new Map<string, RunningTool>();
|
|
111
|
+
/** A retry or compaction in progress. */
|
|
112
|
+
activity: string | undefined;
|
|
113
|
+
/** Bumped on every change, so views can cache what they derive from the run. */
|
|
114
|
+
revision = 0;
|
|
115
|
+
|
|
116
|
+
private readonly host: RunHost;
|
|
117
|
+
private live: LiveSession | undefined;
|
|
118
|
+
private opening: Promise<LiveSession> | undefined;
|
|
119
|
+
private submitting: Promise<void> = Promise.resolve();
|
|
120
|
+
private turn: ActiveTurn | undefined;
|
|
121
|
+
/** User messages that Pi deferred to the next turn, which has not begun yet. */
|
|
122
|
+
private deferredUserMessages: string[] = [];
|
|
123
|
+
private fileCache: { mtimeMs: number; messages: AgentMessage[] } | undefined;
|
|
124
|
+
|
|
125
|
+
constructor(identity: RunIdentity, host: RunHost) {
|
|
126
|
+
this.id = identity.id;
|
|
127
|
+
this.file = identity.file;
|
|
128
|
+
this.spawnEntryId = identity.spawnEntryId;
|
|
129
|
+
this.parentSessionId = identity.parentSessionId;
|
|
130
|
+
this.readOnly = identity.readOnly;
|
|
131
|
+
this.host = host;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A run from an earlier start of the parent session, read from its file. */
|
|
135
|
+
static restore(identity: RunIdentity, host: RunHost): Run {
|
|
136
|
+
const run = new Run(identity, host);
|
|
137
|
+
|
|
138
|
+
try {
|
|
139
|
+
const state = readRunEntries(openRunFile(identity.file).getEntries(), identity.file);
|
|
140
|
+
|
|
141
|
+
run.snapshot = state.snapshot;
|
|
142
|
+
run.lastTurn = state.lastTurn;
|
|
143
|
+
run.turns = state.turns;
|
|
144
|
+
run.usage = state.usage;
|
|
145
|
+
// A turn that never recorded its end was cut off when the parent stopped.
|
|
146
|
+
run.state = state.unfinishedTurn ? "interrupted" : (state.lastTurn?.state ?? "idle");
|
|
147
|
+
} catch (error) {
|
|
148
|
+
run.loadError = error instanceof Error ? error.message : String(error);
|
|
149
|
+
run.state = "failed";
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return run;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** A new run whose session the manager already started and checked. */
|
|
156
|
+
static started(
|
|
157
|
+
identity: RunIdentity,
|
|
158
|
+
snapshot: RunSnapshot,
|
|
159
|
+
live: LiveSession,
|
|
160
|
+
sink: SessionSink,
|
|
161
|
+
host: RunHost,
|
|
162
|
+
): Run {
|
|
163
|
+
const run = new Run(identity, host);
|
|
164
|
+
|
|
165
|
+
run.snapshot = snapshot;
|
|
166
|
+
run.live = live;
|
|
167
|
+
sink.attach(run);
|
|
168
|
+
|
|
169
|
+
return run;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
get name(): string {
|
|
173
|
+
return this.snapshot?.name ?? this.id;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
get title(): string {
|
|
177
|
+
return this.snapshot?.title ?? this.name;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
get isLive(): boolean {
|
|
181
|
+
return this.live !== undefined;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** `provider/id` of the model the run's requests go to; the start value while it is not live. */
|
|
185
|
+
get model(): string | undefined {
|
|
186
|
+
const model = this.live?.session.model;
|
|
187
|
+
|
|
188
|
+
return model ? formatModelRef(model) : this.snapshot?.model;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The live session's level, which Pi limits to what the model supports; else the start value. */
|
|
192
|
+
get thinkingLevel(): ThinkingLevel | undefined {
|
|
193
|
+
return this.live ? this.live.session.thinkingLevel : this.snapshot?.thinking;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Whether the user still has to see the outcome: a failure or a blocked task. */
|
|
197
|
+
get needsAttention(): boolean {
|
|
198
|
+
return this.state === "failed" || this.lastTurn?.report?.status === "blocked";
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
get needsInput(): boolean {
|
|
202
|
+
return this.state !== "running" && this.lastTurn?.report?.status === "needs_input";
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Start time of the turn in progress. */
|
|
206
|
+
get turnStartedAt(): string | undefined {
|
|
207
|
+
return this.turn?.startedAt;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** What the user wrote during the turn in progress, oldest first. */
|
|
211
|
+
get turnUserMessages(): readonly string[] {
|
|
212
|
+
return this.turn?.userMessages ?? [];
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The first turn: the task goes in unchanged, as the run's first user message. */
|
|
216
|
+
async startTask(task: string): Promise<void> {
|
|
217
|
+
await this.send(task, "main-agent");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Steer a running run, or start a new turn. Resolves once the session accepted the message;
|
|
222
|
+
* a session that is not live is reopened from the run file first.
|
|
223
|
+
*/
|
|
224
|
+
async send(
|
|
225
|
+
text: string,
|
|
226
|
+
from: "main-agent" | "user",
|
|
227
|
+
options: { signal?: AbortSignal; onProgress?: (text: string) => void } = {},
|
|
228
|
+
): Promise<SendOutcome> {
|
|
229
|
+
this.assertWritable();
|
|
230
|
+
|
|
231
|
+
// Pi marks a session busy only once a prompt reaches its run, after awaiting input handlers
|
|
232
|
+
// and auth; a second prompt before that would start a second run instead of steering.
|
|
233
|
+
const previous = this.submitting;
|
|
234
|
+
let release!: () => void;
|
|
235
|
+
|
|
236
|
+
this.submitting = new Promise<void>((resolve) => {
|
|
237
|
+
release = resolve;
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
try {
|
|
241
|
+
await previous;
|
|
242
|
+
|
|
243
|
+
return await this.sendNow(text, from, options);
|
|
244
|
+
} finally {
|
|
245
|
+
release();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private async sendNow(
|
|
250
|
+
text: string,
|
|
251
|
+
from: "main-agent" | "user",
|
|
252
|
+
options: { signal?: AbortSignal; onProgress?: (text: string) => void },
|
|
253
|
+
): Promise<SendOutcome> {
|
|
254
|
+
const session = await this.ensureLive(options);
|
|
255
|
+
const message = from === "user" ? markUserMessage(text) : text;
|
|
256
|
+
const userText = from === "user" ? cutUserMessage(text) : undefined;
|
|
257
|
+
|
|
258
|
+
if (this.state === "running") {
|
|
259
|
+
// A message that starts a turn is recorded when that turn begins.
|
|
260
|
+
const result = await this.submit(session, message, userText);
|
|
261
|
+
|
|
262
|
+
if (userText !== undefined) {
|
|
263
|
+
if (result === "deferred") {
|
|
264
|
+
this.deferredUserMessages.push(userText);
|
|
265
|
+
} else if (result === "queued") {
|
|
266
|
+
this.turn?.userMessages.push(userText);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return outcome(result);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
this.beginTurn(userText);
|
|
274
|
+
|
|
275
|
+
try {
|
|
276
|
+
return outcome(await this.submit(session, message, undefined));
|
|
277
|
+
} catch (error) {
|
|
278
|
+
// The session rejected the message before its run began, so no agent_settled follows.
|
|
279
|
+
// The caller gets the error, so the main agent is not notified as well.
|
|
280
|
+
if (this.turn) {
|
|
281
|
+
this.turn.error = error instanceof Error ? error.message : String(error);
|
|
282
|
+
this.finishTurn(false, false);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Abort the turn in progress and wait until its end is recorded; the session, the file and the
|
|
291
|
+
* worktree stay.
|
|
292
|
+
*/
|
|
293
|
+
async stop(by: StopSource): Promise<boolean> {
|
|
294
|
+
const turn = this.turn;
|
|
295
|
+
|
|
296
|
+
if (this.state !== "running" || !this.live || !turn) {
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
turn.stoppedBy = by;
|
|
301
|
+
await this.live.session.abort();
|
|
302
|
+
// agent_settled comes before abort() resolves, except for a run that failed while it was
|
|
303
|
+
// starting; that turn ends when its prompt rejects.
|
|
304
|
+
await turn.ended;
|
|
305
|
+
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Close the live session; the run can be reopened from its file. */
|
|
310
|
+
async close(): Promise<void> {
|
|
311
|
+
const opening = this.opening;
|
|
312
|
+
|
|
313
|
+
if (opening) {
|
|
314
|
+
await opening.catch(() => undefined);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const live = this.live;
|
|
318
|
+
|
|
319
|
+
this.live = undefined;
|
|
320
|
+
|
|
321
|
+
if (live) {
|
|
322
|
+
await live.close();
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** The run's messages, from the live session or from its file. */
|
|
327
|
+
transcript(): AgentMessage[] {
|
|
328
|
+
if (this.live) {
|
|
329
|
+
return transcriptMessages(this.live.session.sessionManager.getEntries());
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (this.loadError) {
|
|
333
|
+
return [];
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const mtimeMs = statSync(this.file).mtimeMs;
|
|
337
|
+
|
|
338
|
+
if (this.fileCache?.mtimeMs !== mtimeMs) {
|
|
339
|
+
this.fileCache = {
|
|
340
|
+
mtimeMs,
|
|
341
|
+
messages: transcriptMessages(openRunFile(this.file).getEntries()),
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return this.fileCache.messages;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
handleEvent(event: AgentSessionEvent): void {
|
|
349
|
+
switch (event.type) {
|
|
350
|
+
case "agent_start":
|
|
351
|
+
// A run can also start without a message from here, such as a built-in's triggerTurn.
|
|
352
|
+
this.beginTurn(undefined);
|
|
353
|
+
return;
|
|
354
|
+
case "message_start":
|
|
355
|
+
case "message_update":
|
|
356
|
+
if (event.message.role === "assistant") {
|
|
357
|
+
this.streaming = event.message;
|
|
358
|
+
this.changed("transcript");
|
|
359
|
+
}
|
|
360
|
+
return;
|
|
361
|
+
case "message_end":
|
|
362
|
+
this.streaming = undefined;
|
|
363
|
+
|
|
364
|
+
if (this.turn && event.message.role === "assistant") {
|
|
365
|
+
this.turn.lastReply = event.message;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
this.changed("transcript");
|
|
369
|
+
return;
|
|
370
|
+
case "tool_execution_start":
|
|
371
|
+
this.runningTools.set(event.toolCallId, {
|
|
372
|
+
toolCallId: event.toolCallId,
|
|
373
|
+
name: event.toolName,
|
|
374
|
+
args: event.args,
|
|
375
|
+
startedAt: Date.now(),
|
|
376
|
+
});
|
|
377
|
+
this.changed("transcript");
|
|
378
|
+
return;
|
|
379
|
+
case "tool_execution_update": {
|
|
380
|
+
const tool = this.runningTools.get(event.toolCallId);
|
|
381
|
+
|
|
382
|
+
if (tool) {
|
|
383
|
+
tool.partialResult = event.partialResult;
|
|
384
|
+
this.changed("transcript");
|
|
385
|
+
}
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
case "tool_execution_end":
|
|
389
|
+
this.runningTools.delete(event.toolCallId);
|
|
390
|
+
this.changed("transcript");
|
|
391
|
+
return;
|
|
392
|
+
case "auto_retry_start":
|
|
393
|
+
this.activity = `Retrying ${event.attempt}/${event.maxAttempts}: ${event.errorMessage}`;
|
|
394
|
+
this.changed("state");
|
|
395
|
+
return;
|
|
396
|
+
case "auto_retry_end":
|
|
397
|
+
case "compaction_end":
|
|
398
|
+
if (event.type === "compaction_end" && event.errorMessage) {
|
|
399
|
+
this.addDiagnostic({
|
|
400
|
+
level: "error",
|
|
401
|
+
message: `Compaction failed: ${event.errorMessage}`,
|
|
402
|
+
at: Date.now(),
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
this.activity = undefined;
|
|
406
|
+
this.changed("state");
|
|
407
|
+
return;
|
|
408
|
+
case "compaction_start":
|
|
409
|
+
this.activity = "Compacting the context";
|
|
410
|
+
this.changed("state");
|
|
411
|
+
return;
|
|
412
|
+
case "agent_settled":
|
|
413
|
+
this.finishTurn(event.aborted);
|
|
414
|
+
return;
|
|
415
|
+
default:
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
addDiagnostic(diagnostic: Diagnostic): void {
|
|
421
|
+
this.diagnostics.push(diagnostic);
|
|
422
|
+
|
|
423
|
+
if (this.diagnostics.length > MAX_DIAGNOSTICS) {
|
|
424
|
+
this.diagnostics.splice(0, this.diagnostics.length - MAX_DIAGNOSTICS);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
this.changed("state");
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
recordReport(report: RunReport): void {
|
|
431
|
+
// The tool only runs inside a turn. A message that reaches the run after its report keeps
|
|
432
|
+
// the turn going, and the main agent must still get the report it replaces.
|
|
433
|
+
this.turn?.reports.push(report);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
private assertWritable(): void {
|
|
437
|
+
if (this.readOnly) {
|
|
438
|
+
throw new Error(
|
|
439
|
+
`Run ${this.id} belongs to session ${this.parentSessionId} and came ` +
|
|
440
|
+
"here through /fork or /clone, so it is read-only. Start a new run to continue " +
|
|
441
|
+
"that work.",
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
if (this.loadError || !this.snapshot) {
|
|
446
|
+
throw new Error(`Run ${this.id} cannot continue: ${this.loadError ?? "no snapshot"}`);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
private async ensureLive(options: {
|
|
451
|
+
signal?: AbortSignal;
|
|
452
|
+
onProgress?: (text: string) => void;
|
|
453
|
+
}): Promise<AgentSession> {
|
|
454
|
+
if (this.live) {
|
|
455
|
+
return this.live.session;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
this.opening ??= this.reopen(options).finally(() => {
|
|
459
|
+
this.opening = undefined;
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
return (await this.opening).session;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** Recreate the session from the snapshot, in the same working directory. */
|
|
466
|
+
private async reopen(options: {
|
|
467
|
+
signal?: AbortSignal;
|
|
468
|
+
onProgress?: (text: string) => void;
|
|
469
|
+
}): Promise<LiveSession> {
|
|
470
|
+
const snapshot = this.snapshot!;
|
|
471
|
+
|
|
472
|
+
if (snapshot.worktree) {
|
|
473
|
+
await assertWorktreeUsable(snapshot.worktree, snapshot.cwd);
|
|
474
|
+
} else if (!isDirectory(snapshot.cwd)) {
|
|
475
|
+
throw new Error(`The run's working directory is missing: ${snapshot.cwd}`);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const model = parseModelRef(snapshot.model);
|
|
479
|
+
|
|
480
|
+
if (!model) {
|
|
481
|
+
throw new Error(`The run snapshot has an invalid model: ${snapshot.model}`);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const sink = new SessionSink();
|
|
485
|
+
|
|
486
|
+
sink.attach(this);
|
|
487
|
+
|
|
488
|
+
const live = await startRunSession({
|
|
489
|
+
cwd: snapshot.cwd,
|
|
490
|
+
agentDir: this.host.agentDir,
|
|
491
|
+
projectTrusted: this.host.projectTrusted(),
|
|
492
|
+
modelRuntime: this.host.modelRuntime,
|
|
493
|
+
appendSystemPrompt: [snapshot.definition?.body ?? "", SUBAGENT_GUIDE],
|
|
494
|
+
model,
|
|
495
|
+
thinkingLevel: snapshot.thinking,
|
|
496
|
+
// The snapshot's list is the allowlist from now on, the default selection included.
|
|
497
|
+
tools: snapshot.tools,
|
|
498
|
+
check: snapshot.tools,
|
|
499
|
+
extensionTools: this.host.extensionTools(),
|
|
500
|
+
reason: "resume",
|
|
501
|
+
theme: this.host.theme(),
|
|
502
|
+
openSessionManager: () => openRunFile(this.file),
|
|
503
|
+
sink,
|
|
504
|
+
signal: options.signal,
|
|
505
|
+
onProgress: options.onProgress,
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
this.live = live;
|
|
509
|
+
this.usage = usageFromEntries(live.session.sessionManager.getEntries());
|
|
510
|
+
this.changed("state");
|
|
511
|
+
|
|
512
|
+
return live;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Hand a message to the session and wait until it is accepted.
|
|
517
|
+
*
|
|
518
|
+
* A prompt that arrives while the session emits agent_settled is deferred by Pi and returns
|
|
519
|
+
* before any preflight; it runs, and starts its own turn, once the settle finishes.
|
|
520
|
+
* `userText` goes to the turn that the message starts, if it starts one.
|
|
521
|
+
*/
|
|
522
|
+
private submit(
|
|
523
|
+
session: AgentSession,
|
|
524
|
+
message: string,
|
|
525
|
+
userText: string | undefined,
|
|
526
|
+
): Promise<"started" | "queued" | "deferred"> {
|
|
527
|
+
return new Promise((resolve, reject) => {
|
|
528
|
+
let answered = false;
|
|
529
|
+
|
|
530
|
+
session
|
|
531
|
+
.prompt(message, {
|
|
532
|
+
expandPromptTemplates: false,
|
|
533
|
+
source: "extension",
|
|
534
|
+
streamingBehavior: "steer",
|
|
535
|
+
preflightResult: (disposition) => {
|
|
536
|
+
if (disposition === "started") {
|
|
537
|
+
this.beginTurn(userText);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
if (answered) {
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
answered = true;
|
|
545
|
+
|
|
546
|
+
if (disposition === "handled") {
|
|
547
|
+
reject(
|
|
548
|
+
new Error("The run session consumed the message without a turn."),
|
|
549
|
+
);
|
|
550
|
+
} else {
|
|
551
|
+
resolve(disposition);
|
|
552
|
+
}
|
|
553
|
+
},
|
|
554
|
+
})
|
|
555
|
+
.then(
|
|
556
|
+
() => {
|
|
557
|
+
if (!answered) {
|
|
558
|
+
answered = true;
|
|
559
|
+
resolve("deferred");
|
|
560
|
+
}
|
|
561
|
+
},
|
|
562
|
+
(error: unknown) => {
|
|
563
|
+
if (!answered) {
|
|
564
|
+
answered = true;
|
|
565
|
+
reject(error);
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// The turn's own end reports its outcome; this error must still stay visible.
|
|
570
|
+
this.addDiagnostic(errorDiagnostic("The run's turn failed", error));
|
|
571
|
+
},
|
|
572
|
+
);
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Begin a turn, or join the turn in progress; `userText` is what the user wrote, if anything. */
|
|
577
|
+
private beginTurn(userText: string | undefined): void {
|
|
578
|
+
if (this.turn) {
|
|
579
|
+
if (userText !== undefined) {
|
|
580
|
+
this.turn.userMessages.push(userText);
|
|
581
|
+
}
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
let end!: () => void;
|
|
586
|
+
const ended = new Promise<void>((resolve) => {
|
|
587
|
+
end = resolve;
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
this.turn = {
|
|
591
|
+
startedAt: new Date().toISOString(),
|
|
592
|
+
reports: [],
|
|
593
|
+
// Deferred messages were written first.
|
|
594
|
+
userMessages: [
|
|
595
|
+
...this.deferredUserMessages,
|
|
596
|
+
...(userText === undefined ? [] : [userText]),
|
|
597
|
+
],
|
|
598
|
+
ended,
|
|
599
|
+
end,
|
|
600
|
+
};
|
|
601
|
+
this.deferredUserMessages = [];
|
|
602
|
+
this.state = "running";
|
|
603
|
+
this.changed("state");
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
private finishTurn(aborted: boolean, notify = true): void {
|
|
607
|
+
const turn: Omit<ActiveTurn, "ended" | "end"> = this.turn ?? {
|
|
608
|
+
startedAt: new Date().toISOString(),
|
|
609
|
+
reports: [],
|
|
610
|
+
userMessages: [],
|
|
611
|
+
};
|
|
612
|
+
const session = this.live?.session;
|
|
613
|
+
// Pi drops a failed or cut reply from the session to recover, and may then not retry, so the
|
|
614
|
+
// session's last reply can be an older one. A tracked turn goes by its own last reply.
|
|
615
|
+
const reply = this.turn
|
|
616
|
+
? this.turn.lastReply
|
|
617
|
+
: session?.messages.findLast(
|
|
618
|
+
(message): message is AssistantMessage => message.role === "assistant",
|
|
619
|
+
);
|
|
620
|
+
let state: SettledState = "idle";
|
|
621
|
+
let error = turn.error;
|
|
622
|
+
|
|
623
|
+
if (aborted) {
|
|
624
|
+
state = "interrupted";
|
|
625
|
+
} else if (error) {
|
|
626
|
+
state = "failed";
|
|
627
|
+
} else if (reply?.stopReason === "error") {
|
|
628
|
+
state = "failed";
|
|
629
|
+
error = reply.errorMessage ?? "The model request failed.";
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const record: TurnRecord = {
|
|
633
|
+
state,
|
|
634
|
+
userWrote: turn.userMessages.length > 0,
|
|
635
|
+
startedAt: turn.startedAt,
|
|
636
|
+
endedAt: new Date().toISOString(),
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
if (turn.userMessages.length > 0) {
|
|
640
|
+
record.userMessages = turn.userMessages;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const report = turn.reports.at(-1);
|
|
644
|
+
|
|
645
|
+
if (report) {
|
|
646
|
+
record.report = report;
|
|
647
|
+
|
|
648
|
+
if (turn.reports.length > 1) {
|
|
649
|
+
record.earlierReports = turn.reports.slice(0, -1);
|
|
650
|
+
}
|
|
651
|
+
} else {
|
|
652
|
+
let text = reply ? replyText(reply) : "";
|
|
653
|
+
|
|
654
|
+
// An interrupted reply can be empty and a rejected message leaves none, so the text
|
|
655
|
+
// before them is the run's last message.
|
|
656
|
+
if (text === "" && (aborted || !reply)) {
|
|
657
|
+
text = session?.getLastAssistantText() ?? "";
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
record.unreportedMessage = this.unreportedMessage(text);
|
|
661
|
+
|
|
662
|
+
if (state === "idle" && (reply?.stopReason === "length" || text === "")) {
|
|
663
|
+
record.cutShort = true;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
if (error) {
|
|
668
|
+
record.error = error;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
if (turn.stoppedBy) {
|
|
672
|
+
record.stoppedBy = turn.stoppedBy;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
if (session) {
|
|
676
|
+
try {
|
|
677
|
+
session.sessionManager.appendCustomEntry(TURN_ENTRY_TYPE, record);
|
|
678
|
+
} catch (appendError) {
|
|
679
|
+
this.addDiagnostic(
|
|
680
|
+
errorDiagnostic("Recording the turn in the run file failed", appendError),
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
this.usage = usageFromEntries(session.sessionManager.getEntries());
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
const active = this.turn;
|
|
688
|
+
|
|
689
|
+
this.turn = undefined;
|
|
690
|
+
this.lastTurn = record;
|
|
691
|
+
this.state = state;
|
|
692
|
+
this.turns += 1;
|
|
693
|
+
this.streaming = undefined;
|
|
694
|
+
this.runningTools.clear();
|
|
695
|
+
this.activity = undefined;
|
|
696
|
+
this.changed("state");
|
|
697
|
+
active?.end();
|
|
698
|
+
|
|
699
|
+
if (notify) {
|
|
700
|
+
this.host.onTurnEnd(this, record);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
private unreportedMessage(text: string): string {
|
|
705
|
+
if (text.length <= MAX_UNREPORTED_CHARS) {
|
|
706
|
+
return text;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
const preview = text.slice(0, MAX_UNREPORTED_CHARS);
|
|
710
|
+
const omitted = text.length - MAX_UNREPORTED_CHARS;
|
|
711
|
+
let location: string;
|
|
712
|
+
|
|
713
|
+
try {
|
|
714
|
+
const directory = join(tmpdir(), "pi-lune-subagent-responses");
|
|
715
|
+
|
|
716
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
717
|
+
|
|
718
|
+
// Content hashes keep a later turn from overwriting an earlier reply's copy.
|
|
719
|
+
const hash = createHash("sha256").update(text).digest("hex");
|
|
720
|
+
const file = join(directory, `${this.id}.${hash}.md`);
|
|
721
|
+
|
|
722
|
+
writeFileSync(file, text, { encoding: "utf8", mode: 0o600 });
|
|
723
|
+
location = `full response: ${JSON.stringify(file)}`;
|
|
724
|
+
} catch (error) {
|
|
725
|
+
const diagnostic = errorDiagnostic("Writing the full response file failed", error);
|
|
726
|
+
|
|
727
|
+
this.addDiagnostic(diagnostic);
|
|
728
|
+
location = `full response file unavailable: ${diagnostic.message}`;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
return `${preview}\n[${omitted} more characters in the run transcript; ${location}]`;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
private changed(change: RunChange): void {
|
|
735
|
+
this.revision += 1;
|
|
736
|
+
this.host.onChange(this, change);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/** A long user message keeps its start and its end; the run's transcript has all of it. */
|
|
741
|
+
function cutUserMessage(text: string): string {
|
|
742
|
+
if (text.length <= MAX_USER_MESSAGE_CHARS) {
|
|
743
|
+
return text;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
const half = MAX_USER_MESSAGE_CHARS / 2;
|
|
747
|
+
const omitted = text.length - MAX_USER_MESSAGE_CHARS;
|
|
748
|
+
|
|
749
|
+
return (
|
|
750
|
+
`${text.slice(0, half)}\n[${omitted} characters cut from the middle]\n` +
|
|
751
|
+
text.slice(text.length - half)
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/** A message queued into a busy session steers the turn in progress. */
|
|
756
|
+
function outcome(disposition: "started" | "queued" | "deferred"): SendOutcome {
|
|
757
|
+
return disposition === "queued" ? "steered" : disposition;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
function replyText(reply: AssistantMessage): string {
|
|
761
|
+
return reply.content
|
|
762
|
+
.map((part) => (part.type === "text" ? part.text : ""))
|
|
763
|
+
.join("")
|
|
764
|
+
.trim();
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
function isDirectory(path: string): boolean {
|
|
768
|
+
try {
|
|
769
|
+
return statSync(path).isDirectory();
|
|
770
|
+
} catch {
|
|
771
|
+
return false;
|
|
772
|
+
}
|
|
773
|
+
}
|