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