@lune_99/pi-subagent 0.1.0 → 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.
@@ -10,7 +10,6 @@ import type {
10
10
  SessionBeforeTreeResult,
11
11
  Theme,
12
12
  } from "@earendil-works/pi-coding-agent";
13
-
14
13
  import {
15
14
  chooseAutoModel,
16
15
  DEFAULT_AUTO_MODEL_SETTINGS,
@@ -18,7 +17,14 @@ import {
18
17
  } from "../auto-model.ts";
19
18
  import type { AgentDefinition } from "../definitions.ts";
20
19
  import type { ExtensionTool } from "../extension-tools.ts";
21
- import { AUTO_MODEL, allowedModelRefs, formatModelRef, parseModelRef } from "../models.ts";
20
+ import {
21
+ AUTO_MODEL,
22
+ allowedModelRefs,
23
+ allowedModels,
24
+ formatModelRef,
25
+ parseModelRef,
26
+ type ModelRef,
27
+ } from "../models.ts";
22
28
  import {
23
29
  RUN_NOTIFICATION_TYPE,
24
30
  RunNotifier,
@@ -27,6 +33,7 @@ import {
27
33
  type RunNotice,
28
34
  } from "../notify/notifier.ts";
29
35
  import { runSessionFile, runWorktreePath } from "../paths.ts";
36
+ import { displayLine } from "../render/text.ts";
30
37
  import { SUBAGENT_GUIDE } from "./guide.ts";
31
38
  import { REPORT_TOOL_NAME } from "./report-tool.ts";
32
39
  import { createRunFile } from "./run-file.ts";
@@ -47,6 +54,7 @@ import { createRunWorktree, removeRunWorktree, type CreatedWorktree } from "./wo
47
54
 
48
55
  export interface StartParams {
49
56
  task: string;
57
+ title?: string;
50
58
  agent?: string;
51
59
  model?: string;
52
60
  thinking?: ThinkingLevel;
@@ -54,6 +62,43 @@ export interface StartParams {
54
62
  isolation?: Isolation;
55
63
  }
56
64
 
65
+ /** The run settings that only an inline start takes; a named agent runs with its definition's. */
66
+ export const INLINE_SETTINGS = ["model", "thinking", "tools", "isolation"] as const;
67
+
68
+ /**
69
+ * Why a start may not go ahead because it names an agent and sets its settings too, or
70
+ * `undefined`. The definition is the user's, so the main agent gives only the task and a title.
71
+ */
72
+ export function agentSettingsProblem(params: Omit<StartParams, "task">): string | undefined {
73
+ if (params.agent === undefined) {
74
+ return undefined;
75
+ }
76
+
77
+ const set = INLINE_SETTINGS.filter((field) => params[field] !== undefined);
78
+
79
+ return set.length > 0
80
+ ? `The agent "${params.agent}" runs with the model, thinking, tools and isolation of ` +
81
+ `its definition; give only task and title with agent, and leave out ${set.join(", ")}.`
82
+ : undefined;
83
+ }
84
+
85
+ /**
86
+ * Why an inline start may not go ahead because it names a model while Auto mode only is on, or
87
+ * `undefined`. Agent runs keep their definition's model.
88
+ */
89
+ export function autoOnlyProblem(
90
+ params: Omit<StartParams, "task">,
91
+ autoOnly: boolean,
92
+ ): string | undefined {
93
+ return autoOnly &&
94
+ params.agent === undefined &&
95
+ params.model !== undefined &&
96
+ params.model !== AUTO_MODEL
97
+ ? `Auto mode only is on, so an inline run uses model ${AUTO_MODEL}; leave out ` +
98
+ `model "${String(params.model)}".`
99
+ : undefined;
100
+ }
101
+
57
102
  export interface ProgressOptions {
58
103
  signal?: AbortSignal;
59
104
  onProgress?: (text: string) => void;
@@ -71,6 +116,8 @@ export class RunManager implements RunHost {
71
116
  readonly agentDir: string;
72
117
  readonly modelRuntime: ModelRuntime | undefined;
73
118
  readonly sessionId: string;
119
+ /** The run the inspector showed when it closed. Memory only, so it ends with the session. */
120
+ inspectorRunId: string | undefined;
74
121
 
75
122
  private readonly pi: ExtensionAPI;
76
123
  private readonly ctx: ExtensionContext;
@@ -78,6 +125,8 @@ export class RunManager implements RunHost {
78
125
  private readonly definitions: AgentDefinition[];
79
126
  private readonly listExtensionTools: () => readonly ExtensionTool[];
80
127
  private readonly autoModelSettings: (ctx: ExtensionContext) => Promise<AutoModelSettings>;
128
+ private readonly modelSelection: (ctx: ExtensionContext) => Promise<readonly ModelRef[]>;
129
+ private readonly autoOnly: (ctx: ExtensionContext) => Promise<boolean>;
81
130
  private readonly runs = new Map<string, Run>();
82
131
  /** Ended turns of runs on another branch; sent when their branch is active again. */
83
132
  private readonly deferred = new Map<string, RunNotice[]>();
@@ -96,6 +145,10 @@ export class RunManager implements RunHost {
96
145
  extensionTools?: () => readonly ExtensionTool[];
97
146
  /** Read at each `model: auto` start; the defaults when left out. */
98
147
  autoModelSettings?: (ctx: ExtensionContext) => Promise<AutoModelSettings>;
148
+ /** A nonempty selection replaces the parent's scope for new runs. */
149
+ modelSelection?: (ctx: ExtensionContext) => Promise<readonly ModelRef[]>;
150
+ /** Read at each start; when true, inline runs use `model: auto`. Off when left out. */
151
+ autoOnly?: (ctx: ExtensionContext) => Promise<boolean>;
99
152
  /** Tests only: a runtime with an offline provider. Runs otherwise create their own. */
100
153
  modelRuntime?: ModelRuntime;
101
154
  }) {
@@ -107,6 +160,8 @@ export class RunManager implements RunHost {
107
160
  this.listExtensionTools = options.extensionTools ?? (() => []);
108
161
  this.autoModelSettings =
109
162
  options.autoModelSettings ?? (async () => DEFAULT_AUTO_MODEL_SETTINGS);
163
+ this.modelSelection = options.modelSelection ?? (async () => []);
164
+ this.autoOnly = options.autoOnly ?? (async () => false);
110
165
  this.sessionId = options.ctx.sessionManager.getSessionId();
111
166
  this.notifier = new RunNotifier(
112
167
  options.pi,
@@ -157,7 +212,12 @@ export class RunManager implements RunHost {
157
212
  return;
158
213
  }
159
214
 
160
- const notice: RunNotice = { runId: run.id, name: run.name, record };
215
+ const notice: RunNotice = {
216
+ runId: run.id,
217
+ name: run.name,
218
+ title: run.snapshot?.title,
219
+ record,
220
+ };
161
221
 
162
222
  // The notifier checks the branch again when the batch goes out.
163
223
  if (this.isOnBranch(run)) {
@@ -251,12 +311,20 @@ export class RunManager implements RunHost {
251
311
  return run;
252
312
  }
253
313
 
254
- const known = this.branchRuns().map((other) => `${other.id} (${other.name})`);
314
+ const known = this.branchRuns();
315
+ // A model that read a name or title as the handle gets that run's ID spelled out, never aliased.
316
+ const matches = known.filter(
317
+ (other) => other.name === runId || other.snapshot?.title === runId,
318
+ );
319
+ const hint =
320
+ matches.length === 1
321
+ ? ` "${runId}" is a run ${matches[0]!.name === runId ? "name" : "title"}, not an ID; pass ${matches[0]!.id}.`
322
+ : "";
255
323
 
256
324
  throw new Error(
257
- `No subagent run "${runId}" on the current branch.` +
325
+ `No subagent run "${runId}" on the current branch.${hint}` +
258
326
  (known.length > 0
259
- ? ` Runs here: ${known.join(", ")}.`
327
+ ? ` Runs here: ${known.map((other) => other.id).join(", ")}.`
260
328
  : " There are no runs here."),
261
329
  );
262
330
  }
@@ -270,6 +338,13 @@ export class RunManager implements RunHost {
270
338
  ): Promise<Run> {
271
339
  this.assertActive();
272
340
 
341
+ const autoOnly = params.agent === undefined && (await this.autoOnly(ctx));
342
+ const problem = agentSettingsProblem(params) ?? autoOnlyProblem(params, autoOnly);
343
+
344
+ if (problem) {
345
+ throw new Error(problem);
346
+ }
347
+
273
348
  const definition = this.resolveDefinition(params.agent);
274
349
  const taskTools = params.tools ?? definition?.tools;
275
350
  const toolsSource: ValueSource =
@@ -289,11 +364,10 @@ export class RunManager implements RunHost {
289
364
  const model = await this.resolveModel(params, definition, ctx, {
290
365
  tools: taskTools,
291
366
  isolation,
292
- thinkingSet: explicitThinking !== undefined,
367
+ autoOnly,
293
368
  options,
294
369
  });
295
- // An auto run's rating sets the thinking only where the call and definition do not.
296
- const thinking = explicitThinking ?? model.thinking ?? ctx.thinkingLevel;
370
+ const thinking = model.thinking ?? explicitThinking ?? ctx.thinkingLevel;
297
371
  const thinkingSource: ValueSource =
298
372
  params.thinking !== undefined
299
373
  ? "call"
@@ -309,6 +383,7 @@ export class RunManager implements RunHost {
309
383
 
310
384
  const runId = this.reserveRunId();
311
385
  const name = definition?.name ?? `run-${++this.inlineCount}`;
386
+ const title = typeof params.title === "string" ? displayLine(params.title) : undefined;
312
387
  const file = runSessionFile(this.sessionId, runId, this.agentDir);
313
388
  let worktree: CreatedWorktree | undefined;
314
389
  let fileCreated = false;
@@ -410,6 +485,7 @@ export class RunManager implements RunHost {
410
485
  const snapshot: RunSnapshot = {
411
486
  runId,
412
487
  name,
488
+ ...(title ? { title } : {}),
413
489
  ...(definition
414
490
  ? {
415
491
  definition: {
@@ -468,10 +544,9 @@ export class RunManager implements RunHost {
468
544
  this.reservedIds.delete(runId);
469
545
  this.emit("state", this.runs.get(runId));
470
546
 
471
- throw new Error(
472
- `Run ${name} (${runId}) could not record its snapshot: ${message(error)}`,
473
- { cause: error },
474
- );
547
+ throw new Error(`Run ${runId} could not record its snapshot: ${message(error)}`, {
548
+ cause: error,
549
+ });
475
550
  }
476
551
 
477
552
  const run = Run.started(identity, snapshot, live, sink, this);
@@ -484,7 +559,7 @@ export class RunManager implements RunHost {
484
559
  await run.startTask(params.task);
485
560
  } catch (error) {
486
561
  throw new Error(
487
- `Run ${name} (${runId}) could not start its task: ${message(error)}\n` +
562
+ `Run ${runId} could not start its task: ${message(error)}\n` +
488
563
  "The run is kept as failed; continue it with subagent_send once the cause is fixed.",
489
564
  { cause: error },
490
565
  );
@@ -517,16 +592,22 @@ export class RunManager implements RunHost {
517
592
  copyReport(run: Run): void {
518
593
  if (this.isOnBranch(run)) {
519
594
  throw new Error(
520
- `Run ${run.name} is on this branch; its turns reach the main agent already.`,
595
+ `Run ${run.id} is on this branch; its turns reach the main agent already.`,
521
596
  );
522
597
  }
523
598
 
524
599
  if (!run.lastTurn) {
525
- throw new Error(`Run ${run.name} has no ended turn to copy.`);
600
+ throw new Error(`Run ${run.id} has no ended turn to copy.`);
526
601
  }
527
602
 
528
603
  const { content, details } = buildRunNotification([
529
- { runId: run.id, name: run.name, record: run.lastTurn, copied: true },
604
+ {
605
+ runId: run.id,
606
+ name: run.name,
607
+ title: run.snapshot?.title,
608
+ record: run.lastTurn,
609
+ copied: true,
610
+ },
530
611
  ]);
531
612
 
532
613
  this.pi.sendMessage({ customType: RUN_NOTIFICATION_TYPE, content, display: true, details });
@@ -548,7 +629,7 @@ export class RunManager implements RunHost {
548
629
  const stop = "Stop them";
549
630
  const choice = await ctx.ui.select(
550
631
  `${running.length} subagent run${running.length === 1 ? " is" : "s are"} still ` +
551
- `running on the branch you are leaving: ${running.map((run) => run.name).join(", ")}.`,
632
+ `running on the branch you are leaving: ${running.map((run) => run.title).join(", ")}.`,
552
633
  [keep, stop],
553
634
  { signal: event.signal },
554
635
  );
@@ -719,7 +800,7 @@ export class RunManager implements RunHost {
719
800
  }
720
801
 
721
802
  /**
722
- * Requested models must be in the parent's allowed set. The parent's own current model is used
803
+ * Requested models must be in the subagent allowlist. The parent's own current model is used
723
804
  * as it is, since Pi lets a session's default model sit outside its scope.
724
805
  */
725
806
  private async resolveModel(
@@ -729,17 +810,18 @@ export class RunManager implements RunHost {
729
810
  run: {
730
811
  tools?: readonly string[];
731
812
  isolation: Isolation;
732
- thinkingSet: boolean;
813
+ autoOnly: boolean;
733
814
  options: ProgressOptions;
734
815
  },
735
816
  ): Promise<{
736
817
  ref: { provider: string; id: string };
737
818
  source: ValueSource;
738
819
  auto?: AutoModelChoice;
739
- /** The auto rating's thinking level, when the start set none. */
820
+ /** The thinking level selected together with the auto model. */
740
821
  thinking?: ThinkingLevel;
741
822
  }> {
742
- const requested = params.model ?? definition?.model;
823
+ const requested =
824
+ params.model ?? definition?.model ?? (run.autoOnly ? AUTO_MODEL : undefined);
743
825
 
744
826
  if (requested === undefined) {
745
827
  if (!ctx.model) {
@@ -749,19 +831,34 @@ export class RunManager implements RunHost {
749
831
  return { ref: { provider: ctx.model.provider, id: ctx.model.id }, source: "parent" };
750
832
  }
751
833
 
752
- const source: ValueSource = params.model !== undefined ? "call" : "definition";
834
+ const source: ValueSource =
835
+ params.model !== undefined
836
+ ? "call"
837
+ : definition?.model !== undefined
838
+ ? "definition"
839
+ : "settings";
840
+ if (
841
+ requested === AUTO_MODEL &&
842
+ (params.thinking !== undefined || definition?.thinking !== undefined)
843
+ ) {
844
+ throw new Error(
845
+ "Model auto chooses both the model and thinking level; leave out thinking.",
846
+ );
847
+ }
848
+
849
+ const selection = await this.modelSelection(ctx);
753
850
 
754
851
  if (requested === AUTO_MODEL) {
755
- run.options.onProgress?.("Choosing a model");
852
+ run.options.onProgress?.("Choosing a model and thinking level");
756
853
 
757
854
  const { ref, choice, thinking } = await chooseAutoModel({
758
855
  ctx,
759
856
  settings: await this.autoModelSettings(ctx),
857
+ models: allowedModels(ctx, selection),
760
858
  task: params.task,
761
859
  definition,
762
860
  tools: run.tools,
763
861
  isolation: run.isolation,
764
- thinkingSet: run.thinkingSet,
765
862
  signal: run.options.signal,
766
863
  });
767
864
 
@@ -774,7 +871,7 @@ export class RunManager implements RunHost {
774
871
  throw new Error(`Invalid model "${requested}": use provider/id.`);
775
872
  }
776
873
 
777
- const allowed = allowedModelRefs(ctx);
874
+ const allowed = allowedModelRefs(ctx, selection);
778
875
 
779
876
  if (!allowed.includes(requested)) {
780
877
  throw new Error(
package/src/run/run.ts CHANGED
@@ -1,4 +1,7 @@
1
- import { statSync } from "node:fs";
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";
2
5
 
3
6
  import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
4
7
  import type { AssistantMessage } from "@earendil-works/pi-ai";
@@ -29,6 +32,8 @@ import { assertWorktreeUsable } from "./worktree.ts";
29
32
 
30
33
  /** The longest last message a turn without a report hands to the main agent. */
31
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;
32
37
  const MAX_DIAGNOSTICS = 50;
33
38
 
34
39
  export type RunChange = "state" | "transcript";
@@ -66,9 +71,12 @@ interface ActiveTurn {
66
71
  startedAt: string;
67
72
  /** Every report of the turn, oldest first; the last one is the turn's report. */
68
73
  reports: RunReport[];
69
- userWrote: boolean;
74
+ /** What the user wrote from the inspector during the turn, oldest first, already cut. */
75
+ userMessages: string[];
70
76
  stoppedBy?: StopSource;
71
77
  error?: string;
78
+ /** The turn's last assistant reply, which the session may no longer hold. */
79
+ lastReply?: AssistantMessage;
72
80
  /** Resolves once the turn's end is recorded. */
73
81
  ended: Promise<void>;
74
82
  end: () => void;
@@ -110,8 +118,8 @@ export class Run implements RunEventTarget {
110
118
  private opening: Promise<LiveSession> | undefined;
111
119
  private submitting: Promise<void> = Promise.resolve();
112
120
  private turn: ActiveTurn | undefined;
113
- /** A user message that Pi deferred to the next turn, which has not begun yet. */
114
- private deferredUserWrote = false;
121
+ /** User messages that Pi deferred to the next turn, which has not begun yet. */
122
+ private deferredUserMessages: string[] = [];
115
123
  private fileCache: { mtimeMs: number; messages: AgentMessage[] } | undefined;
116
124
 
117
125
  constructor(identity: RunIdentity, host: RunHost) {
@@ -165,6 +173,10 @@ export class Run implements RunEventTarget {
165
173
  return this.snapshot?.name ?? this.id;
166
174
  }
167
175
 
176
+ get title(): string {
177
+ return this.snapshot?.title ?? this.name;
178
+ }
179
+
168
180
  get isLive(): boolean {
169
181
  return this.live !== undefined;
170
182
  }
@@ -195,6 +207,11 @@ export class Run implements RunEventTarget {
195
207
  return this.turn?.startedAt;
196
208
  }
197
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
+
198
215
  /** The first turn: the task goes in unchanged, as the run's first user message. */
199
216
  async startTask(task: string): Promise<void> {
200
217
  await this.send(task, "main-agent");
@@ -236,26 +253,27 @@ export class Run implements RunEventTarget {
236
253
  ): Promise<SendOutcome> {
237
254
  const session = await this.ensureLive(options);
238
255
  const message = from === "user" ? markUserMessage(text) : text;
239
- const userWrote = from === "user";
256
+ const userText = from === "user" ? cutUserMessage(text) : undefined;
240
257
 
241
258
  if (this.state === "running") {
242
- const result = outcome(await this.submit(session, message, userWrote));
259
+ // A message that starts a turn is recorded when that turn begins.
260
+ const result = await this.submit(session, message, userText);
243
261
 
244
- if (userWrote) {
262
+ if (userText !== undefined) {
245
263
  if (result === "deferred") {
246
- this.deferredUserWrote = true;
247
- } else if (this.turn) {
248
- this.turn.userWrote = true;
264
+ this.deferredUserMessages.push(userText);
265
+ } else if (result === "queued") {
266
+ this.turn?.userMessages.push(userText);
249
267
  }
250
268
  }
251
269
 
252
- return result;
270
+ return outcome(result);
253
271
  }
254
272
 
255
- this.beginTurn(userWrote);
273
+ this.beginTurn(userText);
256
274
 
257
275
  try {
258
- return outcome(await this.submit(session, message, userWrote));
276
+ return outcome(await this.submit(session, message, undefined));
259
277
  } catch (error) {
260
278
  // The session rejected the message before its run began, so no agent_settled follows.
261
279
  // The caller gets the error, so the main agent is not notified as well.
@@ -331,7 +349,7 @@ export class Run implements RunEventTarget {
331
349
  switch (event.type) {
332
350
  case "agent_start":
333
351
  // A run can also start without a message from here, such as a built-in's triggerTurn.
334
- this.beginTurn(false);
352
+ this.beginTurn(undefined);
335
353
  return;
336
354
  case "message_start":
337
355
  case "message_update":
@@ -342,6 +360,11 @@ export class Run implements RunEventTarget {
342
360
  return;
343
361
  case "message_end":
344
362
  this.streaming = undefined;
363
+
364
+ if (this.turn && event.message.role === "assistant") {
365
+ this.turn.lastReply = event.message;
366
+ }
367
+
345
368
  this.changed("transcript");
346
369
  return;
347
370
  case "tool_execution_start":
@@ -413,7 +436,7 @@ export class Run implements RunEventTarget {
413
436
  private assertWritable(): void {
414
437
  if (this.readOnly) {
415
438
  throw new Error(
416
- `Run ${this.name} (${this.id}) belongs to session ${this.parentSessionId} and came ` +
439
+ `Run ${this.id} belongs to session ${this.parentSessionId} and came ` +
417
440
  "here through /fork or /clone, so it is read-only. Start a new run to continue " +
418
441
  "that work.",
419
442
  );
@@ -494,11 +517,12 @@ export class Run implements RunEventTarget {
494
517
  *
495
518
  * A prompt that arrives while the session emits agent_settled is deferred by Pi and returns
496
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.
497
521
  */
498
522
  private submit(
499
523
  session: AgentSession,
500
524
  message: string,
501
- userWrote: boolean,
525
+ userText: string | undefined,
502
526
  ): Promise<"started" | "queued" | "deferred"> {
503
527
  return new Promise((resolve, reject) => {
504
528
  let answered = false;
@@ -510,7 +534,7 @@ export class Run implements RunEventTarget {
510
534
  streamingBehavior: "steer",
511
535
  preflightResult: (disposition) => {
512
536
  if (disposition === "started") {
513
- this.beginTurn(userWrote);
537
+ this.beginTurn(userText);
514
538
  }
515
539
 
516
540
  if (answered) {
@@ -549,9 +573,12 @@ export class Run implements RunEventTarget {
549
573
  });
550
574
  }
551
575
 
552
- private beginTurn(userWrote: boolean): void {
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 {
553
578
  if (this.turn) {
554
- this.turn.userWrote ||= userWrote;
579
+ if (userText !== undefined) {
580
+ this.turn.userMessages.push(userText);
581
+ }
555
582
  return;
556
583
  }
557
584
 
@@ -563,11 +590,15 @@ export class Run implements RunEventTarget {
563
590
  this.turn = {
564
591
  startedAt: new Date().toISOString(),
565
592
  reports: [],
566
- userWrote: userWrote || this.deferredUserWrote,
593
+ // Deferred messages were written first.
594
+ userMessages: [
595
+ ...this.deferredUserMessages,
596
+ ...(userText === undefined ? [] : [userText]),
597
+ ],
567
598
  ended,
568
599
  end,
569
600
  };
570
- this.deferredUserWrote = false;
601
+ this.deferredUserMessages = [];
571
602
  this.state = "running";
572
603
  this.changed("state");
573
604
  }
@@ -576,12 +607,16 @@ export class Run implements RunEventTarget {
576
607
  const turn: Omit<ActiveTurn, "ended" | "end"> = this.turn ?? {
577
608
  startedAt: new Date().toISOString(),
578
609
  reports: [],
579
- userWrote: false,
610
+ userMessages: [],
580
611
  };
581
612
  const session = this.live?.session;
582
- const last = session?.messages.findLast(
583
- (message): message is AssistantMessage => message.role === "assistant",
584
- );
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
+ );
585
620
  let state: SettledState = "idle";
586
621
  let error = turn.error;
587
622
 
@@ -589,18 +624,22 @@ export class Run implements RunEventTarget {
589
624
  state = "interrupted";
590
625
  } else if (error) {
591
626
  state = "failed";
592
- } else if (last?.stopReason === "error") {
627
+ } else if (reply?.stopReason === "error") {
593
628
  state = "failed";
594
- error = last.errorMessage ?? "The model request failed.";
629
+ error = reply.errorMessage ?? "The model request failed.";
595
630
  }
596
631
 
597
632
  const record: TurnRecord = {
598
633
  state,
599
- userWrote: turn.userWrote,
634
+ userWrote: turn.userMessages.length > 0,
600
635
  startedAt: turn.startedAt,
601
636
  endedAt: new Date().toISOString(),
602
637
  };
603
638
 
639
+ if (turn.userMessages.length > 0) {
640
+ record.userMessages = turn.userMessages;
641
+ }
642
+
604
643
  const report = turn.reports.at(-1);
605
644
 
606
645
  if (report) {
@@ -610,7 +649,19 @@ export class Run implements RunEventTarget {
610
649
  record.earlierReports = turn.reports.slice(0, -1);
611
650
  }
612
651
  } else {
613
- record.unreportedMessage = limitText(session?.getLastAssistantText() ?? "");
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
+ }
614
665
  }
615
666
 
616
667
  if (error) {
@@ -650,28 +701,69 @@ export class Run implements RunEventTarget {
650
701
  }
651
702
  }
652
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
+
653
734
  private changed(change: RunChange): void {
654
735
  this.revision += 1;
655
736
  this.host.onChange(this, change);
656
737
  }
657
738
  }
658
739
 
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) {
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) {
666
743
  return text;
667
744
  }
668
745
 
746
+ const half = MAX_USER_MESSAGE_CHARS / 2;
747
+ const omitted = text.length - MAX_USER_MESSAGE_CHARS;
748
+
669
749
  return (
670
- `${text.slice(0, MAX_UNREPORTED_CHARS)}\n` +
671
- `[${text.length - MAX_UNREPORTED_CHARS} more characters in the run transcript]`
750
+ `${text.slice(0, half)}\n[${omitted} characters cut from the middle]\n` +
751
+ text.slice(text.length - half)
672
752
  );
673
753
  }
674
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
+
675
767
  function isDirectory(path: string): boolean {
676
768
  try {
677
769
  return statSync(path).isDirectory();