@yandy0725/pi-subagents 0.10.1 → 0.10.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael Ding
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.10.1",
6
+ "version": "0.10.3",
7
7
  "description": "Focused, in-process sub-agent core for pi — autonomous agents plus a typed API and lifecycle events",
8
8
  "license": "MIT",
9
9
  "repository": {
@@ -24,7 +24,9 @@
24
24
  "test:watch": "vitest",
25
25
  "typecheck": "tsc --noEmit",
26
26
  "lint": "biome lint .",
27
- "format": "biome format --write ."
27
+ "format": "biome format --write .",
28
+ "prepack": "node ../scripts/license.mjs",
29
+ "postpack": "node ../scripts/license.mjs --remove"
28
30
  },
29
31
  "pi": {
30
32
  "extensions": [
@@ -38,10 +40,10 @@
38
40
  "typebox": "*"
39
41
  },
40
42
  "devDependencies": {
41
- "@biomejs/biome": "^2.6.2",
42
- "@types/node": "^26.6.5",
43
+ "@biomejs/biome": "^2.6.4",
44
+ "@types/node": "^26.6.6",
43
45
  "typebox": "^1.4.3",
44
46
  "typescript": "~7.0.2",
45
- "vitest": "^5.0.5"
47
+ "vitest": "^5.1.0"
46
48
  }
47
49
  }
@@ -118,7 +118,6 @@ export class SubagentSession {
118
118
  }
119
119
  });
120
120
 
121
- const collector = collectResponseText(session);
122
121
  const cleanupAbort = forwardAbortSignal(session, opts.signal);
123
122
 
124
123
  // Prepend parent context if it was captured at spawn time.
@@ -135,11 +134,10 @@ export class SubagentSession {
135
134
  });
136
135
  } finally {
137
136
  unsubTurns();
138
- collector.unsubscribe();
139
137
  cleanupAbort();
140
138
  }
141
139
 
142
- const responseText = collector.getText().trim() || getLastAssistantText(session);
140
+ const responseText = getLastAssistantText(session);
143
141
  return { responseText, aborted, steered: softLimitReached };
144
142
  }
145
143
 
@@ -149,17 +147,15 @@ export class SubagentSession {
149
147
  // Same early-return as runTurnLoop: an aborted signal must not start a run.
150
148
  if (signal?.aborted) return getLastAssistantText(session);
151
149
 
152
- const collector = collectResponseText(session);
153
150
  const cleanupAbort = forwardAbortSignal(session, signal);
154
151
 
155
152
  try {
156
153
  await session.prompt(prompt);
157
154
  } finally {
158
- collector.unsubscribe();
159
155
  cleanupAbort();
160
156
  }
161
157
 
162
- return collector.getText().trim() || getLastAssistantText(session);
158
+ return getLastAssistantText(session);
163
159
  }
164
160
 
165
161
  /** Deliver a steer to the live session. */
@@ -212,23 +208,6 @@ export class SubagentSession {
212
208
 
213
209
  // ── Private turn-loop helpers ───────────────────────────────────────────────────
214
210
 
215
- /**
216
- * Subscribe to a session and collect the last assistant message text.
217
- * Returns an object with a `getText()` getter and an `unsubscribe` function.
218
- */
219
- function collectResponseText(session: AgentSession) {
220
- let text = "";
221
- const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
222
- if (event.type === "message_start") {
223
- text = "";
224
- }
225
- if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
226
- text += event.assistantMessageEvent.delta;
227
- }
228
- });
229
- return { getText: () => text, unsubscribe };
230
- }
231
-
232
211
  /** Get the last assistant text from the completed session history. */
233
212
  function getLastAssistantText(session: AgentSession): string {
234
213
  for (let i = session.messages.length - 1; i >= 0; i--) {
@@ -3,11 +3,11 @@
3
3
  *
4
4
  * Owns the passive, readable state of a subagent — status, result, error,
5
5
  * timestamps, stats (toolUses, lifetimeUsage, compactionCount), and live-activity
6
- * fields (turnCount, activeTools, responseText) — together with the transition
6
+ * fields (turnCount, activeTools, streamingMessage) — together with the transition
7
7
  * methods (markRunning, markCompleted, …), accumulation methods
8
8
  * (incrementToolUses, addUsage, incrementCompactions), and live-activity
9
9
  * transition methods (incrementTurnCount, addActiveTool, removeActiveTool,
10
- * resetResponseText, appendResponseText) that mutate them.
10
+ * setStreamingMessage) that mutate them.
11
11
  *
12
12
  * State is encapsulated behind getters; external code reads through them but
13
13
  * mutates only via the transition/accumulation methods. The value object owns
@@ -20,6 +20,7 @@
20
20
 
21
21
  import type { LifetimeUsage } from "../lifecycle/usage";
22
22
  import { addUsage } from "../lifecycle/usage";
23
+ import type { SessionMessage } from "../types";
23
24
 
24
25
  export type SubagentStatus = "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error";
25
26
 
@@ -87,9 +88,9 @@ export class SubagentState {
87
88
 
88
89
  private _toolKeySeq = 0;
89
90
 
90
- private _responseText = "";
91
- get responseText(): string {
92
- return this._responseText;
91
+ private _streamingMessage: SessionMessage | undefined;
92
+ get streamingMessage(): SessionMessage | undefined {
93
+ return this._streamingMessage;
93
94
  }
94
95
 
95
96
  constructor(init: SubagentStateInit = {}) {
@@ -135,14 +136,9 @@ export class SubagentState {
135
136
  }
136
137
  }
137
138
 
138
- /** Reset the current response text. Called by record-observer on message_start. */
139
- resetResponseText(): void {
140
- this._responseText = "";
141
- }
142
-
143
- /** Append a text delta to the current response text. Called by record-observer on message_update. */
144
- appendResponseText(delta: string): void {
145
- this._responseText += delta;
139
+ /** Record the in-flight assistant message. Called by record-observer on message_start / message_update. */
140
+ setStreamingMessage(message: SessionMessage | undefined): void {
141
+ this._streamingMessage = message;
146
142
  }
147
143
 
148
144
  /** Transition to running state. Sets status and startedAt. */
@@ -3,11 +3,14 @@
3
3
  *
4
4
  * Status/stats are delegated to the SubagentState value object; listener
5
5
  * lifecycle to RunListeners.
6
+ * The class also owns its own live-state listener set (`changeListeners`), whose
7
+ * lifetime deliberately spans runs (an already-open overlay keeps refreshing
8
+ * after a resume).
6
9
  * Behavior (abort, steer buffering) lives here rather than on SubagentManager.
7
10
  */
8
11
 
9
12
  import type { Model } from "@earendil-works/pi-ai";
10
- import type { AgentSessionEvent, ToolDefinition } from "@earendil-works/pi-coding-agent";
13
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
11
14
  import type { CreateSubagentSessionParams } from "../lifecycle/create-subagent-session";
12
15
  import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
13
16
  import { RunListeners } from "../lifecycle/run-listeners";
@@ -118,8 +121,8 @@ export class Subagent {
118
121
  get activeTools(): ReadonlyMap<string, string> {
119
122
  return this.state.activeTools;
120
123
  }
121
- get responseText(): string {
122
- return this.state.responseText;
124
+ get streamingMessage(): SessionMessage | undefined {
125
+ return this.state.streamingMessage;
123
126
  }
124
127
  get maxTurns(): number | undefined {
125
128
  return this.execution.maxTurns;
@@ -145,6 +148,7 @@ export class Subagent {
145
148
 
146
149
  private readonly execution: SubagentExecution;
147
150
  private readonly listeners = new RunListeners();
151
+ private readonly changeListeners = new Set<() => void>();
148
152
 
149
153
  subagentSession?: SubagentSession;
150
154
  private _notification?: NotificationState;
@@ -193,11 +197,18 @@ export class Subagent {
193
197
  }
194
198
 
195
199
  /**
196
- * Subscribe to session events for live updates (e.g., conversation viewer).
197
- * Returns an unsubscribe function, or undefined if no session is available.
200
+ * Subscribe to live-state changes. Returns an unsubscribe, or undefined before a session exists.
198
201
  */
199
- subscribeToUpdates(fn: (event: AgentSessionEvent) => void): (() => void) | undefined {
200
- return this.subagentSession?.subscribe(fn);
202
+ subscribeToUpdates(fn: () => void): (() => void) | undefined {
203
+ if (!this.subagentSession) return undefined;
204
+ this.changeListeners.add(fn);
205
+ return () => {
206
+ this.changeListeners.delete(fn);
207
+ };
208
+ }
209
+
210
+ private notifyChange(): void {
211
+ for (const listener of this.changeListeners) listener();
201
212
  }
202
213
 
203
214
  /** The session's message history, or an empty array if no session. */
@@ -279,6 +290,7 @@ export class Subagent {
279
290
  this.listeners.attachObserver(
280
291
  subscribeSubagentObserver(this.subagentSession, this.state, {
281
292
  onCompact: (info) => this.execution.observer?.onCompacted?.(this, info),
293
+ onChange: () => this.notifyChange(),
282
294
  }),
283
295
  );
284
296
  this.execution.observer?.onSessionCreated?.(this);
@@ -345,6 +357,7 @@ export class Subagent {
345
357
  this.listeners.attachObserver(
346
358
  subscribeSubagentObserver(subagentSession, this.state, {
347
359
  onCompact: (info) => this.execution.observer?.onCompacted?.(this, info),
360
+ onChange: () => this.notifyChange(),
348
361
  }),
349
362
  );
350
363
 
@@ -1,5 +1,7 @@
1
1
  /**
2
- * record-observer.ts — Subscribes to session events and accumulates SubagentState stats.
2
+ * record-observer.ts — The single interpreter of raw session events for live
3
+ * state: accumulates SubagentState stats, drives `streamingMessage`, and is the
4
+ * single change notifier.
3
5
  *
4
6
  * Replaces the scattered callback-wrapping logic in SubagentManager's startAgent()
5
7
  * and resume() with a single direct subscription. The observer targets the
@@ -12,6 +14,8 @@ import type { CompactionInfo, SubscribableSession } from "../types";
12
14
 
13
15
  export interface SubagentObserverOptions {
14
16
  onCompact?: (info: CompactionInfo) => void;
17
+ /** Called after every event's state mutation, so consumers always read post-mutation state. */
18
+ onChange?: () => void;
15
19
  }
16
20
 
17
21
  /**
@@ -20,9 +24,9 @@ export interface SubagentObserverOptions {
20
24
  * Handles:
21
25
  * - `tool_execution_start` → `state.addActiveTool(name)`
22
26
  * - `tool_execution_end` → `state.removeActiveTool(name)`, `state.incrementToolUses()`
23
- * - `message_start` → `state.resetResponseText()`
24
- * - `message_update` (text_delta) → `state.appendResponseText(delta)`
25
- * - `message_end` (assistant, with usage) → `state.addUsage(…)`
27
+ * - `message_start` → `state.setStreamingMessage(assistant ? message : undefined)`
28
+ * - `message_update` → `state.setStreamingMessage(message)` (assistant only)
29
+ * - `message_end` → `state.setStreamingMessage(undefined)`, `state.addUsage(…)` (assistant, with usage)
26
30
  * - `turn_end` → `state.incrementTurnCount()`
27
31
  * - `compaction_end` (not aborted) → `state.incrementCompactions()`, call `onCompact`
28
32
  *
@@ -44,11 +48,15 @@ export function subscribeSubagentObserver(
44
48
  }
45
49
 
46
50
  if (event.type === "message_start") {
47
- state.resetResponseText();
51
+ state.setStreamingMessage(event.message.role === "assistant" ? event.message : undefined);
48
52
  }
49
53
 
50
- if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
51
- state.appendResponseText(event.assistantMessageEvent.delta);
54
+ if (event.type === "message_update" && event.message.role === "assistant") {
55
+ state.setStreamingMessage(event.message);
56
+ }
57
+
58
+ if (event.type === "message_end") {
59
+ state.setStreamingMessage(undefined);
52
60
  }
53
61
 
54
62
  if (event.type === "turn_end") {
@@ -71,5 +79,7 @@ export function subscribeSubagentObserver(
71
79
  tokensBefore: event.result.tokensBefore,
72
80
  });
73
81
  }
82
+
83
+ options?.onChange?.();
74
84
  });
75
85
  }
@@ -50,7 +50,7 @@ export async function runForeground(
50
50
  maxTurns: recordRef?.maxTurns ?? execution.effectiveMaxTurns,
51
51
  durationMs: Date.now() - startedAt,
52
52
  status: "running",
53
- activity: describeActivity(recordRef?.activeTools ?? new Map(), recordRef?.responseText ?? ""),
53
+ activity: describeActivity(recordRef?.activeTools ?? new Map(), recordRef?.streamingMessage),
54
54
  spinnerFrame: spinnerFrame % SPINNER.length,
55
55
  };
56
56
  onUpdate?.({
@@ -178,7 +178,7 @@ export class AgentWidget implements SubagentManagerObserver {
178
178
  turnCount: record.turnCount,
179
179
  maxTurns: record.maxTurns,
180
180
  activeTools: record.activeTools,
181
- responseText: record.responseText,
181
+ streamingMessage: record.streamingMessage,
182
182
  contextPercent: record.getContextPercent(),
183
183
  modelName: record.invocation?.modelName,
184
184
  thinking: record.invocation?.thinking,
package/src/ui/display.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  import type { AgentConfigLookup } from "../config/agent-types";
9
- import type { AgentInvocation, SubagentType } from "../types";
9
+ import type { AgentInvocation, SessionMessage, SubagentType } from "../types";
10
10
 
11
11
  // ---- Types ----
12
12
 
@@ -146,8 +146,23 @@ function truncateLine(text: string, len = 60): string {
146
146
  return `${line.slice(0, len)}…`;
147
147
  }
148
148
 
149
- /** Build a human-readable activity string from currently-running tools or response text. */
150
- export function describeActivity(activeTools: ReadonlyMap<string, string>, responseText?: string): string {
149
+ /** Concatenate a message's text blocks (mirrors how pi's components read a message). */
150
+ function messageText(message: SessionMessage | undefined): string {
151
+ if (!message) return "";
152
+ const content = (message as { content?: unknown }).content;
153
+ if (typeof content === "string") return content;
154
+ if (!Array.isArray(content)) return "";
155
+ // Join with "\n", not "": `truncateLine` takes the first non-empty line, so
156
+ // a text → toolCall → text message must expose each text run as its own line
157
+ // (joining with "" would fuse "First." and "Second." into a single line).
158
+ return content
159
+ .filter((block) => (block as { type?: string }).type === "text")
160
+ .map((block) => (block as { text?: string }).text ?? "")
161
+ .join("\n");
162
+ }
163
+
164
+ /** Build a human-readable activity string from currently-running tools or the in-flight message. */
165
+ export function describeActivity(activeTools: ReadonlyMap<string, string>, message?: SessionMessage): string {
151
166
  if (activeTools.size > 0) {
152
167
  const groups = new Map<string, number>();
153
168
  for (const toolName of activeTools.values()) {
@@ -166,9 +181,10 @@ export function describeActivity(activeTools: ReadonlyMap<string, string>, respo
166
181
  return `${parts.join(", ")}…`;
167
182
  }
168
183
 
169
- // No tools active — show truncated response text if available
170
- if (responseText && responseText.trim().length > 0) {
171
- return truncateLine(responseText);
184
+ // No tools active — show truncated message text if available
185
+ const text = messageText(message);
186
+ if (text.trim().length > 0) {
187
+ return truncateLine(text);
172
188
  }
173
189
 
174
190
  return "thinking…";
@@ -22,7 +22,7 @@ import {
22
22
  import type { AgentConfigLookup } from "../config/agent-types";
23
23
  import type { EvictedSubagent } from "../lifecycle/subagent-manager";
24
24
  import type { SubagentStatus } from "../lifecycle/subagent-state";
25
- import type { AgentSessionEvent, SessionMessage, SubagentType } from "../types";
25
+ import type { SessionMessage, SubagentType } from "../types";
26
26
  import { formatDuration, getDisplayName } from "../ui/display";
27
27
 
28
28
  // ─────────────────────────────────────────────────────────────────────────────
@@ -37,14 +37,15 @@ export interface NavigableSubagent {
37
37
  readonly completedAt: number | undefined;
38
38
  readonly toolUses: number;
39
39
  readonly activeTools: ReadonlyMap<string, string>;
40
- readonly responseText: string;
41
40
  readonly agentMessages: readonly SessionMessage[];
41
+ /** The assistant message currently being streamed, when one exists (not yet in `agentMessages`). */
42
+ readonly streamingMessage?: SessionMessage;
42
43
  /** Short display model name (always shown; falls back to parent model when unset). */
43
44
  readonly modelName?: string;
44
45
  /** Thinking level when explicitly set (e.g. "high", "off"). */
45
46
  readonly thinking?: string;
46
47
  isSessionReady(): boolean;
47
- subscribeToUpdates(fn: (event: AgentSessionEvent) => void): (() => void) | undefined;
48
+ subscribeToUpdates(fn: () => void): (() => void) | undefined;
48
49
  getToolDefinition(name: string): ToolDefinition | undefined;
49
50
  }
50
51
 
@@ -73,7 +74,7 @@ interface LabelFields {
73
74
  /** Running-agent streaming state, surfaced by a live source. */
74
75
  export interface StreamingState {
75
76
  readonly activeTools: ReadonlyMap<string, string>;
76
- readonly responseText: string;
77
+ readonly streamingMessage?: SessionMessage;
77
78
  }
78
79
 
79
80
  /** Liveness-agnostic transcript source consumed by the renderer. */
@@ -137,13 +138,26 @@ export function fileSnapshotSource(outputFile: string, readFile: (path: string)
137
138
  };
138
139
  }
139
140
 
140
- /** Source a transcript live from an in-memory record (this slice's only source). */
141
+ /**
142
+ * Source a transcript live from an in-memory record (this slice's only source).
143
+ *
144
+ * The transcript is the record's history plus the assistant message still in
145
+ * flight: Pi's agent state only gains an assistant message at `message_end`, so
146
+ * without the tail the overlay would jump one message at a time instead of
147
+ * painting the response as it streams. The tail is re-created on every delta,
148
+ * which the body's tail-refresh path absorbs as a refresh, not a rebuild.
149
+ */
141
150
  export function liveSource(record: NavigableSubagent): TranscriptSource {
142
151
  return {
143
- getMessages: () => record.agentMessages,
144
- subscribe: (onChange) => record.subscribeToUpdates(() => onChange()),
152
+ getMessages: () => {
153
+ const tail = record.streamingMessage;
154
+ return tail ? [...record.agentMessages, tail] : record.agentMessages;
155
+ },
156
+ subscribe: (onChange) => record.subscribeToUpdates(onChange),
145
157
  streaming: () =>
146
- record.status === "running" ? { activeTools: record.activeTools, responseText: record.responseText } : undefined,
158
+ record.status === "running"
159
+ ? { activeTools: record.activeTools, streamingMessage: record.streamingMessage }
160
+ : undefined,
147
161
  getToolDefinition: (name) => record.getToolDefinition(name),
148
162
  };
149
163
  }
@@ -423,7 +423,7 @@ export class TranscriptOverlay implements Component {
423
423
  /** Running-agent indicator line, or "" when the source is not streaming. */
424
424
  private indicatorLine(): string {
425
425
  const streaming = this.source.streaming();
426
- return streaming ? `◍ ${describeActivity(streaming.activeTools, streaming.responseText)}` : "";
426
+ return streaming ? `◍ ${describeActivity(streaming.activeTools, streaming.streamingMessage)}` : "";
427
427
  }
428
428
  }
429
429
 
@@ -9,7 +9,7 @@ import { truncateToWidth } from "@earendil-works/pi-tui";
9
9
  import type { AgentConfigLookup } from "../config/agent-types";
10
10
  import type { LifetimeUsage } from "../lifecycle/usage";
11
11
  import { getLifetimeTotal } from "../lifecycle/usage";
12
- import type { SubagentType } from "../types";
12
+ import type { SessionMessage, SubagentType } from "../types";
13
13
  import {
14
14
  describeActivity,
15
15
  formatMs,
@@ -39,7 +39,7 @@ export interface WidgetAgent {
39
39
  readonly turnCount: number;
40
40
  readonly maxTurns?: number;
41
41
  readonly activeTools: ReadonlyMap<string, string>;
42
- readonly responseText: string;
42
+ readonly streamingMessage?: SessionMessage;
43
43
  /** Context-window utilisation (0–100), or null when unavailable. */
44
44
  readonly contextPercent: number | null;
45
45
  /** Short display model name (always shown; falls back to parent model when unset). */
@@ -119,7 +119,7 @@ export function renderRunningLines(
119
119
  const statsText = parts.join(" · ");
120
120
 
121
121
  const frame = SPINNER[spinnerFrame % SPINNER.length];
122
- const activityText = describeActivity(agent.activeTools, agent.responseText);
122
+ const activityText = describeActivity(agent.activeTools, agent.streamingMessage);
123
123
 
124
124
  const header = `${theme.fg("accent", frame)} ${theme.bold(name)}${modeTag} ${theme.fg("muted", agent.description)} ${theme.fg("dim", "·")} ${theme.fg("dim", statsText)}`;
125
125
  const activityLine = theme.fg("dim", ` \u23BF ${activityText}`);