@yandy0725/pi-subagents 0.5.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -7
- package/README.zh.md +4 -7
- package/package.json +3 -3
- package/src/lifecycle/child-lifecycle.ts +9 -1
- package/src/runtime.ts +0 -1
- package/src/session/prompts.ts +2 -2
- package/src/ui/session-navigation.ts +4 -3
- package/src/ui/session-navigator.ts +114 -209
- package/src/ui/transcript-body.ts +398 -0
package/README.md
CHANGED
|
@@ -107,6 +107,12 @@ Send a steering message to a running agent.
|
|
|
107
107
|
| `/subagents:settings` | Configure concurrency, turn limits |
|
|
108
108
|
| `/subagents:sessions` | View a subagent's session transcript |
|
|
109
109
|
|
|
110
|
+
The session viewer renders the transcript read-only with Pi's own per-entry
|
|
111
|
+
components and follows the running agent live. Tool results appear in Pi's
|
|
112
|
+
collapsed form (summaries and previews), so a `read` call is represented by its
|
|
113
|
+
call line only. The viewer has no expand key, so the "… to expand" hints some
|
|
114
|
+
tools print do not apply here.
|
|
115
|
+
|
|
110
116
|
## Concurrency
|
|
111
117
|
|
|
112
118
|
Background agents are subject to a configurable concurrency limit (default: 4). Excess agents queue automatically. Foreground agents bypass the queue.
|
|
@@ -130,13 +136,6 @@ Lifecycle events emitted via `pi.events` for other extensions to consume:
|
|
|
130
136
|
| `subagents:settings_loaded` | Persisted settings applied |
|
|
131
137
|
| `subagents:settings_changed` | Settings mutation applied |
|
|
132
138
|
|
|
133
|
-
## Permission System Integration
|
|
134
|
-
|
|
135
|
-
When `@yandy0725/pi-permission-system` is installed, the package integrates automatically:
|
|
136
|
-
- Per-agent permission policies via YAML frontmatter
|
|
137
|
-
- Tool filtering before agent start
|
|
138
|
-
- `ask`-state forwarding from child to parent UI
|
|
139
|
-
|
|
140
139
|
## Development
|
|
141
140
|
|
|
142
141
|
```bash
|
package/README.zh.md
CHANGED
|
@@ -107,6 +107,10 @@ max_turns: 30
|
|
|
107
107
|
| `/subagents:settings` | 配置并发数、轮次限制 |
|
|
108
108
|
| `/subagents:sessions` | 查看子代理的会话记录 |
|
|
109
109
|
|
|
110
|
+
会话查看器以只读方式复用 Pi 自身的逐条消息组件渲染会话记录,并实时跟随运行中的代理。
|
|
111
|
+
工具结果按 Pi 的折叠形态显示(摘要与预览),因此 `read` 调用只显示其调用行。
|
|
112
|
+
查看器没有展开键,部分工具调用行里提示的"to expand"键在此不适用。
|
|
113
|
+
|
|
110
114
|
## 并发控制
|
|
111
115
|
|
|
112
116
|
后台代理受可配置并发限制约束(默认 4)。超出限制的代理自动排队。前台代理绕过队列。
|
|
@@ -130,13 +134,6 @@ max_turns: 30
|
|
|
130
134
|
| `subagents:settings_loaded` | 持久化设置已应用 |
|
|
131
135
|
| `subagents:settings_changed` | 设置变更已生效 |
|
|
132
136
|
|
|
133
|
-
## 权限系统集成
|
|
134
|
-
|
|
135
|
-
当安装了 `@yandy0725/pi-permission-system` 时,本包自动集成:
|
|
136
|
-
- 通过 YAML frontmatter 为各代理类型设置权限策略
|
|
137
|
-
- Agent 启动前过滤工具
|
|
138
|
-
- `ask` 状态从子代理转发到父级 UI
|
|
139
|
-
|
|
140
137
|
## 开发
|
|
141
138
|
|
|
142
139
|
```bash
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.5.
|
|
6
|
+
"version": "0.5.4",
|
|
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": {
|
|
@@ -39,9 +39,9 @@
|
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
41
|
"@biomejs/biome": "^2.5.14",
|
|
42
|
-
"@types/node": "^26.6.
|
|
42
|
+
"@types/node": "^26.6.3",
|
|
43
43
|
"typebox": "^1.3.34",
|
|
44
44
|
"typescript": "~7.0.2",
|
|
45
|
-
"vitest": "^5.0.
|
|
45
|
+
"vitest": "^5.0.2"
|
|
46
46
|
}
|
|
47
47
|
}
|
|
@@ -25,7 +25,15 @@ export const SUBAGENT_CHILD_SESSION_CREATED = "subagents:child:session-created";
|
|
|
25
25
|
/** Emitted after the child's prompt resolves (normal, steered, or aborted). */
|
|
26
26
|
export const SUBAGENT_CHILD_COMPLETED = "subagents:child:completed";
|
|
27
27
|
|
|
28
|
-
/**
|
|
28
|
+
/**
|
|
29
|
+
* Emitted when the child's **session record** is torn down — the eviction sweep
|
|
30
|
+
* (`SubagentManager.cleanup()`), `clearCompleted()` on session start/switch, or
|
|
31
|
+
* the manager's `dispose()` on session shutdown — and immediately when binding a
|
|
32
|
+
* freshly created session fails. It does **not** fire when a run finishes: a
|
|
33
|
+
* completed agent keeps its session (and this registration) until one of the
|
|
34
|
+
* above happens, so subscribers must treat it as teardown, not per-run cleanup.
|
|
35
|
+
* For per-run completion use `SUBAGENT_CHILD_COMPLETED`.
|
|
36
|
+
*/
|
|
29
37
|
export const SUBAGENT_CHILD_DISPOSED = "subagents:child:disposed";
|
|
30
38
|
|
|
31
39
|
/** Payload for `subagents:child:spawning`. */
|
package/src/runtime.ts
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Eliminates module-scope state in agent-runner.ts and closure-scoped state
|
|
5
5
|
* in index.ts by consolidating them into a single, testable object.
|
|
6
|
-
* Follows the same pattern as pi-permission-system's ExtensionRuntime.
|
|
7
6
|
*/
|
|
8
7
|
|
|
9
8
|
import { buildParentSnapshot, type ParentSnapshot } from "./lifecycle/parent-snapshot";
|
package/src/session/prompts.ts
CHANGED
|
@@ -22,8 +22,8 @@ import type { AgentPromptConfig } from "../types";
|
|
|
22
22
|
* - "append" with empty systemPrompt: pure parent clone.
|
|
23
23
|
*
|
|
24
24
|
* Both modes include an `<active_agent name="${config.name}"/>` tag so
|
|
25
|
-
* downstream extensions
|
|
26
|
-
*
|
|
25
|
+
* downstream extensions can resolve per-agent policy inside the child session
|
|
26
|
+
* by parsing the system prompt.
|
|
27
27
|
* The tag follows the cacheable parent prefix in both modes.
|
|
28
28
|
*
|
|
29
29
|
* @param parentSystemPrompt The parent agent's effective system prompt.
|
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
*
|
|
8
8
|
* The `TranscriptSource` seam decouples *how messages are sourced* (live record
|
|
9
9
|
* here; a file snapshot in a follow-up) from *how they render* — the renderer
|
|
10
|
-
* (`
|
|
11
|
-
* this seam. Rendering lives in
|
|
12
|
-
* components require a `TUI`, `cwd`,
|
|
10
|
+
* (`transcript-body.ts`, mounted by the `session-navigator.ts` overlay, which
|
|
11
|
+
* uses Pi's per-entry components) talks only to this seam. Rendering lives in
|
|
12
|
+
* the SDK/TUI modules because the per-entry components require a `TUI`, `cwd`,
|
|
13
|
+
* and markdown theme.
|
|
13
14
|
*/
|
|
14
15
|
|
|
15
16
|
import {
|
|
@@ -4,43 +4,29 @@
|
|
|
4
4
|
*
|
|
5
5
|
* SDK/TUI consumer half of native session navigation. The unit-testable core
|
|
6
6
|
* (selection, sourcing) lives in `session-navigation.ts`; this module wires that
|
|
7
|
-
* core to the command picker and a read-only scrollable overlay
|
|
8
|
-
*
|
|
9
|
-
* `
|
|
10
|
-
*
|
|
11
|
-
* because the components require a `TUI`, `cwd`, and markdown theme.
|
|
7
|
+
* core to the command picker and a read-only scrollable overlay. The per-entry
|
|
8
|
+
* component tree lives in `transcript-body.ts` (incremental, mirrors Pi's own
|
|
9
|
+
* `renderSessionContext`/`updateContent` lifecycle); this module owns the
|
|
10
|
+
* viewport: scroll state, chrome, the sync throttle, and the line cache.
|
|
12
11
|
*
|
|
13
12
|
* The overlay is strictly read-only — steering stays in the `steer_subagent` tool
|
|
14
13
|
* and the widget. It consumes a `TranscriptSource`, so the evicted-agent-source
|
|
15
|
-
* follow-up swaps the source without touching the
|
|
14
|
+
* follow-up swaps the source without touching the body or the overlay.
|
|
16
15
|
*/
|
|
17
16
|
|
|
18
|
-
import {
|
|
19
|
-
AssistantMessageComponent,
|
|
20
|
-
BashExecutionComponent,
|
|
21
|
-
BranchSummaryMessageComponent,
|
|
22
|
-
CompactionSummaryMessageComponent,
|
|
23
|
-
getMarkdownTheme,
|
|
24
|
-
parseSkillBlock,
|
|
25
|
-
SkillInvocationMessageComponent,
|
|
26
|
-
type ToolDefinition,
|
|
27
|
-
ToolExecutionComponent,
|
|
28
|
-
UserMessageComponent,
|
|
29
|
-
} from "@earendil-works/pi-coding-agent";
|
|
17
|
+
import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
|
|
30
18
|
import {
|
|
31
19
|
type Component,
|
|
32
|
-
Container,
|
|
33
20
|
type MarkdownTheme,
|
|
34
21
|
matchesKey,
|
|
35
|
-
Spacer,
|
|
36
22
|
type TUI,
|
|
37
23
|
truncateToWidth,
|
|
38
24
|
visibleWidth,
|
|
39
25
|
} from "@earendil-works/pi-tui";
|
|
40
26
|
import type { AgentConfigLookup } from "../config/agent-types";
|
|
41
27
|
import type { EvictedSubagent } from "../lifecycle/subagent-manager";
|
|
42
|
-
import type { SessionMessage } from "../types";
|
|
43
28
|
import { describeActivity, type Theme } from "../ui/display";
|
|
29
|
+
import { TranscriptBody } from "../ui/transcript-body";
|
|
44
30
|
import {
|
|
45
31
|
fileSnapshotSource,
|
|
46
32
|
listNavigableAgents,
|
|
@@ -150,33 +136,33 @@ export class SessionNavigatorHandler {
|
|
|
150
136
|
}
|
|
151
137
|
|
|
152
138
|
/**
|
|
153
|
-
* Minimum interval between two
|
|
139
|
+
* Minimum interval between two body syncs for a live (streaming) source.
|
|
154
140
|
*
|
|
155
|
-
* A running agent emits many events per second (text deltas, tool calls).
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
* `q`) stopped responding. Coalescing bursts into at most one rebuild per tick
|
|
141
|
+
* A running agent emits many events per second (text deltas, tool calls). Each
|
|
142
|
+
* event can change a message — or only the activity indicator — and every change
|
|
143
|
+
* ends in a line-cache rebuild. Coalescing bursts into at most one sync per tick
|
|
159
144
|
* keeps the overlay responsive while still streaming.
|
|
160
145
|
*/
|
|
161
|
-
const
|
|
146
|
+
const SYNC_THROTTLE_MS = 120;
|
|
162
147
|
|
|
163
148
|
/**
|
|
164
149
|
* Read-only scrollable transcript overlay.
|
|
165
150
|
*
|
|
166
151
|
* Two caches keep it responsive even for long, live-streaming transcripts:
|
|
167
152
|
*
|
|
168
|
-
* - `
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
* markdown
|
|
153
|
+
* - `body` (a `TranscriptBody`) is synced only when the source changes, and
|
|
154
|
+
* syncs are *throttled* — a burst of streaming events coalesces into at most
|
|
155
|
+
* one sync per `SYNC_THROTTLE_MS`, and the sync itself touches only the
|
|
156
|
+
* messages that changed, so markdown/tool rendering never re-runs for the
|
|
157
|
+
* whole transcript on every token.
|
|
172
158
|
* - `renderedLines` caches the laid-out, width-wrapped lines. `render()` and
|
|
173
159
|
* `handleInput()` read the cache (O(1) slice / length) instead of
|
|
174
160
|
* re-rendering the whole container on every frame and every keystroke.
|
|
175
161
|
*
|
|
176
|
-
* The cache is invalidated (`linesDirty`) whenever the
|
|
177
|
-
*
|
|
178
|
-
* chrome, and the running-agent streaming indicator;
|
|
179
|
-
* in `
|
|
162
|
+
* The cache is invalidated (`linesDirty`) whenever the body changed, and
|
|
163
|
+
* recomputed lazily at the width it was requested at. This class owns scroll
|
|
164
|
+
* state, chrome, and the running-agent streaming indicator; per-entry component
|
|
165
|
+
* mapping and lifecycle live in `transcript-body.ts`.
|
|
180
166
|
*/
|
|
181
167
|
export class TranscriptOverlay implements Component {
|
|
182
168
|
private scrollOffset = 0;
|
|
@@ -188,40 +174,45 @@ export class TranscriptOverlay implements Component {
|
|
|
188
174
|
private readonly theme: Theme;
|
|
189
175
|
private readonly source: TranscriptSource;
|
|
190
176
|
private readonly done: (result: undefined) => void;
|
|
191
|
-
private readonly cwd: string;
|
|
192
|
-
private readonly markdownTheme: MarkdownTheme;
|
|
193
177
|
private readonly modelName?: string;
|
|
194
178
|
private readonly thinking?: string;
|
|
195
|
-
private
|
|
179
|
+
private readonly body: TranscriptBody;
|
|
196
180
|
|
|
197
|
-
/** Throttle bookkeeping for coalescing live-source
|
|
198
|
-
private
|
|
199
|
-
private
|
|
181
|
+
/** Throttle bookkeeping for coalescing live-source syncs. */
|
|
182
|
+
private syncTimer: ReturnType<typeof setTimeout> | undefined;
|
|
183
|
+
private lastSyncAt = 0;
|
|
200
184
|
|
|
201
185
|
/** Cached laid-out lines + the width they were computed at; recomputed lazily when `linesDirty`. */
|
|
202
186
|
private renderedLines: string[] = [];
|
|
203
187
|
private renderedWidth = -1;
|
|
188
|
+
/** Width of the last layout, kept across `invalidate()` so a keystroke cannot pick the wrong one. */
|
|
189
|
+
private lastRenderWidth = -1;
|
|
204
190
|
private linesDirty = true;
|
|
191
|
+
/** Running-agent indicator baked into `renderedLines` — invalidates the cache when it changes. */
|
|
192
|
+
private renderedIndicator = "";
|
|
205
193
|
|
|
206
194
|
constructor({ tui, theme, source, done, cwd, markdownTheme, modelName, thinking }: TranscriptOverlayOptions) {
|
|
207
195
|
this.tui = tui;
|
|
208
196
|
this.theme = theme;
|
|
209
197
|
this.source = source;
|
|
210
198
|
this.done = done;
|
|
211
|
-
this.cwd = cwd;
|
|
212
|
-
this.markdownTheme = markdownTheme;
|
|
213
199
|
this.modelName = modelName;
|
|
214
200
|
this.thinking = thinking;
|
|
215
|
-
this.
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
//
|
|
223
|
-
|
|
224
|
-
|
|
201
|
+
this.body = new TranscriptBody({
|
|
202
|
+
tui,
|
|
203
|
+
cwd,
|
|
204
|
+
markdownTheme,
|
|
205
|
+
getToolDefinition: (name) => source.getToolDefinition(name),
|
|
206
|
+
});
|
|
207
|
+
this.body.sync(source.getMessages());
|
|
208
|
+
// Seed `lastSyncAt` far in the past so the first source-change event
|
|
209
|
+
// always syncs immediately (leading-edge throttle). The constructor
|
|
210
|
+
// already materialized the snapshot at construction time, but the source
|
|
211
|
+
// may have accumulated events between construction and subscription —
|
|
212
|
+
// that first sync surfaces them without delay. Subsequent events inside
|
|
213
|
+
// the throttle window are coalesced into a single trailing sync.
|
|
214
|
+
this.lastSyncAt = 0;
|
|
215
|
+
this.unsubscribe = source.subscribe(() => this.scheduleSync());
|
|
225
216
|
}
|
|
226
217
|
|
|
227
218
|
// fallow-ignore-next-line unused-class-member
|
|
@@ -232,21 +223,25 @@ export class TranscriptOverlay implements Component {
|
|
|
232
223
|
return;
|
|
233
224
|
}
|
|
234
225
|
|
|
235
|
-
const totalLines = this.getRenderedLines(this.
|
|
226
|
+
const totalLines = this.getRenderedLines(this.layoutWidth()).length;
|
|
236
227
|
const viewportHeight = this.viewportHeight();
|
|
237
228
|
const maxScroll = Math.max(0, totalLines - viewportHeight);
|
|
238
229
|
let scrolled = false;
|
|
239
230
|
|
|
240
231
|
if (matchesKey(data, "up") || matchesKey(data, "k")) {
|
|
241
232
|
this.scrollOffset = Math.max(0, this.scrollOffset - 1);
|
|
242
|
-
//
|
|
243
|
-
// making maxScroll larger
|
|
244
|
-
//
|
|
233
|
+
// Upward keys pause following unconditionally: streaming may add lines
|
|
234
|
+
// between handleInput and render, making maxScroll larger, and a "was I
|
|
235
|
+
// at the bottom?" test against the stale value would let render() reset
|
|
236
|
+
// a viewport the operator just left.
|
|
245
237
|
this.autoScroll = false;
|
|
246
238
|
scrolled = true;
|
|
247
239
|
} else if (matchesKey(data, "down") || matchesKey(data, "j")) {
|
|
248
240
|
this.scrollOffset = Math.min(maxScroll, this.scrollOffset + 1);
|
|
249
|
-
|
|
241
|
+
// Downward keys re-arm following when they land on the bottom, so the
|
|
242
|
+
// live tail resumes as soon as the operator scrolls back down (or was
|
|
243
|
+
// already there).
|
|
244
|
+
this.autoScroll = this.scrollOffset >= maxScroll;
|
|
250
245
|
scrolled = true;
|
|
251
246
|
} else if (matchesKey(data, "pageUp") || matchesKey(data, "shift+up")) {
|
|
252
247
|
this.scrollOffset = Math.max(0, this.scrollOffset - viewportHeight);
|
|
@@ -254,7 +249,7 @@ export class TranscriptOverlay implements Component {
|
|
|
254
249
|
scrolled = true;
|
|
255
250
|
} else if (matchesKey(data, "pageDown") || matchesKey(data, "shift+down")) {
|
|
256
251
|
this.scrollOffset = Math.min(maxScroll, this.scrollOffset + viewportHeight);
|
|
257
|
-
this.autoScroll =
|
|
252
|
+
this.autoScroll = this.scrollOffset >= maxScroll;
|
|
258
253
|
scrolled = true;
|
|
259
254
|
} else if (matchesKey(data, "home")) {
|
|
260
255
|
this.scrollOffset = 0;
|
|
@@ -314,7 +309,7 @@ export class TranscriptOverlay implements Component {
|
|
|
314
309
|
|
|
315
310
|
// fallow-ignore-next-line unused-class-member
|
|
316
311
|
invalidate(): void {
|
|
317
|
-
this.
|
|
312
|
+
this.body.invalidate();
|
|
318
313
|
this.linesDirty = true;
|
|
319
314
|
this.renderedWidth = -1;
|
|
320
315
|
}
|
|
@@ -322,9 +317,9 @@ export class TranscriptOverlay implements Component {
|
|
|
322
317
|
// fallow-ignore-next-line unused-class-member
|
|
323
318
|
dispose(): void {
|
|
324
319
|
this.closed = true;
|
|
325
|
-
if (this.
|
|
326
|
-
clearTimeout(this.
|
|
327
|
-
this.
|
|
320
|
+
if (this.syncTimer) {
|
|
321
|
+
clearTimeout(this.syncTimer);
|
|
322
|
+
this.syncTimer = undefined;
|
|
328
323
|
}
|
|
329
324
|
if (this.unsubscribe) {
|
|
330
325
|
this.unsubscribe();
|
|
@@ -334,6 +329,20 @@ export class TranscriptOverlay implements Component {
|
|
|
334
329
|
|
|
335
330
|
// ---- Private ----
|
|
336
331
|
|
|
332
|
+
/**
|
|
333
|
+
* Inner width the laid-out line cache belongs to.
|
|
334
|
+
*
|
|
335
|
+
* The overlay is rendered by TUI at its *own* width (90% of the terminal),
|
|
336
|
+
* not at the terminal width, so the scroll math must reuse the width the
|
|
337
|
+
* cache was laid out at — otherwise every keystroke misses the cache and
|
|
338
|
+
* re-lays out the whole transcript. Falls back to the terminal width before
|
|
339
|
+
* the first layout.
|
|
340
|
+
*/
|
|
341
|
+
private layoutWidth(): number {
|
|
342
|
+
return this.lastRenderWidth > 0 ? this.lastRenderWidth : this.innerWidth();
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Terminal-width-derived inner width — used before the first layout has happened. */
|
|
337
346
|
private innerWidth(): number {
|
|
338
347
|
return Math.max(0, this.tui.terminal.columns - 4);
|
|
339
348
|
}
|
|
@@ -344,181 +353,77 @@ export class TranscriptOverlay implements Component {
|
|
|
344
353
|
}
|
|
345
354
|
|
|
346
355
|
/**
|
|
347
|
-
* Coalesce a burst of source-change events into at most one
|
|
348
|
-
* per `
|
|
356
|
+
* Coalesce a burst of source-change events into at most one body sync
|
|
357
|
+
* per `SYNC_THROTTLE_MS`. The first event after an idle gap syncs
|
|
349
358
|
* immediately (so a freshly-picked agent paints without delay); subsequent
|
|
350
|
-
* events inside the gap are merged into a single trailing
|
|
359
|
+
* events inside the gap are merged into a single trailing sync.
|
|
351
360
|
*/
|
|
352
|
-
private
|
|
361
|
+
private scheduleSync(): void {
|
|
353
362
|
if (this.closed) return;
|
|
354
363
|
const now = Date.now();
|
|
355
|
-
const elapsed = now - this.
|
|
356
|
-
if (elapsed >=
|
|
357
|
-
this.
|
|
364
|
+
const elapsed = now - this.lastSyncAt;
|
|
365
|
+
if (elapsed >= SYNC_THROTTLE_MS) {
|
|
366
|
+
this.doSync();
|
|
358
367
|
return;
|
|
359
368
|
}
|
|
360
|
-
if (this.
|
|
361
|
-
this.
|
|
362
|
-
this.
|
|
363
|
-
this.
|
|
364
|
-
},
|
|
369
|
+
if (this.syncTimer) return; // a trailing sync is already pending
|
|
370
|
+
this.syncTimer = setTimeout(() => {
|
|
371
|
+
this.syncTimer = undefined;
|
|
372
|
+
this.doSync();
|
|
373
|
+
}, SYNC_THROTTLE_MS - elapsed);
|
|
365
374
|
}
|
|
366
375
|
|
|
367
|
-
/**
|
|
368
|
-
private
|
|
376
|
+
/** Invalidate the line cache when the sync changed anything, then request a paint. */
|
|
377
|
+
private doSync(): void {
|
|
369
378
|
if (this.closed) return;
|
|
370
|
-
this.
|
|
371
|
-
|
|
372
|
-
this.linesDirty = true;
|
|
379
|
+
this.lastSyncAt = Date.now();
|
|
380
|
+
const outcome = this.body.sync(this.source.getMessages());
|
|
381
|
+
if (outcome.appended + outcome.refreshed + outcome.rebuilt > 0) this.linesDirty = true;
|
|
373
382
|
this.tui.requestRender();
|
|
374
383
|
}
|
|
375
384
|
|
|
376
385
|
/**
|
|
377
386
|
* Return the laid-out content lines at `innerW`, recomputing the cache only
|
|
378
|
-
* when the
|
|
387
|
+
* when the body or indicator changed (`linesDirty`) or the width changed.
|
|
379
388
|
* Cheap O(1) on the hot path (every render frame and every keystroke).
|
|
380
389
|
*/
|
|
381
390
|
private getRenderedLines(innerW: number): string[] {
|
|
382
391
|
if (innerW <= 0) return [];
|
|
383
|
-
if (!this.linesDirty && this.renderedWidth === innerW)
|
|
392
|
+
if (!this.linesDirty && this.renderedWidth === innerW) {
|
|
393
|
+
// The running-agent indicator lives outside the message list (`activeTools`,
|
|
394
|
+
// streamed preview, and the status flip when the agent finishes), so no
|
|
395
|
+
// event necessarily marks the cache dirty. Re-check it here, where every
|
|
396
|
+
// frame and every keystroke reads the cache, and it self-heals.
|
|
397
|
+
if (this.indicatorLine() === this.renderedIndicator) return this.renderedLines;
|
|
398
|
+
}
|
|
384
399
|
this.renderedLines = this.buildContentLines(innerW);
|
|
385
400
|
this.renderedWidth = innerW;
|
|
401
|
+
this.lastRenderWidth = innerW;
|
|
386
402
|
this.linesDirty = false;
|
|
387
403
|
return this.renderedLines;
|
|
388
404
|
}
|
|
389
405
|
|
|
406
|
+
/**
|
|
407
|
+
* Lay out the materialized transcript plus the running-agent indicator.
|
|
408
|
+
*
|
|
409
|
+
* Over-wide lines are truncated where they are *displayed* (in `render`), not
|
|
410
|
+
* here: truncating every line of the transcript on each layout was an O(whole
|
|
411
|
+
* transcript) pass just to show a viewport of it.
|
|
412
|
+
*/
|
|
390
413
|
private buildContentLines(innerW: number): string[] {
|
|
391
414
|
if (innerW <= 0) return [];
|
|
392
|
-
const lines = this.
|
|
393
|
-
|
|
394
|
-
if (
|
|
395
|
-
lines.push("",
|
|
396
|
-
}
|
|
397
|
-
return lines.map((l) => truncateToWidth(l, innerW));
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
private rebuild(): Container {
|
|
401
|
-
return buildTranscriptComponents(this.source.getMessages(), {
|
|
402
|
-
tui: this.tui,
|
|
403
|
-
cwd: this.cwd,
|
|
404
|
-
markdownTheme: this.markdownTheme,
|
|
405
|
-
getToolDefinition: (name) => this.source.getToolDefinition(name),
|
|
406
|
-
});
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
/** Dependencies the per-entry component tree needs from the SDK/TUI environment. */
|
|
411
|
-
interface TranscriptRenderOptions {
|
|
412
|
-
tui: TUI;
|
|
413
|
-
cwd: string;
|
|
414
|
-
markdownTheme: MarkdownTheme;
|
|
415
|
-
getToolDefinition: (name: string) => ToolDefinition | undefined;
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
/**
|
|
419
|
-
* Build a `Container` of Pi's per-entry components from a message snapshot,
|
|
420
|
-
* mirroring Pi's own interactive-mode `renderSessionContext` mapping. Tool
|
|
421
|
-
* results are matched to their tool-call components by id, exactly as Pi does.
|
|
422
|
-
* `custom`-role messages are skipped — rendering them needs the child session's
|
|
423
|
-
* message-renderer registry, which the navigator does not hold.
|
|
424
|
-
*/
|
|
425
|
-
function buildTranscriptComponents(messages: readonly SessionMessage[], opts: TranscriptRenderOptions): Container {
|
|
426
|
-
const container = new Container();
|
|
427
|
-
const pendingTools = new Map<string, ToolExecutionComponent>();
|
|
428
|
-
for (const message of messages) {
|
|
429
|
-
addMessageComponents(container, message, pendingTools, opts);
|
|
430
|
-
}
|
|
431
|
-
return container;
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
function addMessageComponents(
|
|
435
|
-
container: Container,
|
|
436
|
-
message: SessionMessage,
|
|
437
|
-
pendingTools: Map<string, ToolExecutionComponent>,
|
|
438
|
-
opts: TranscriptRenderOptions,
|
|
439
|
-
): void {
|
|
440
|
-
switch (message.role) {
|
|
441
|
-
case "assistant": {
|
|
442
|
-
container.addChild(new AssistantMessageComponent(message, false, opts.markdownTheme));
|
|
443
|
-
for (const content of message.content) {
|
|
444
|
-
if (content.type !== "toolCall") continue;
|
|
445
|
-
const tool = new ToolExecutionComponent(
|
|
446
|
-
content.name,
|
|
447
|
-
content.id,
|
|
448
|
-
content.arguments,
|
|
449
|
-
{ showImages: false },
|
|
450
|
-
opts.getToolDefinition(content.name),
|
|
451
|
-
opts.tui,
|
|
452
|
-
opts.cwd,
|
|
453
|
-
);
|
|
454
|
-
tool.setExpanded(true);
|
|
455
|
-
container.addChild(tool);
|
|
456
|
-
pendingTools.set(content.id, tool);
|
|
457
|
-
}
|
|
458
|
-
break;
|
|
459
|
-
}
|
|
460
|
-
case "toolResult": {
|
|
461
|
-
pendingTools.get(message.toolCallId)?.updateResult(message);
|
|
462
|
-
pendingTools.delete(message.toolCallId);
|
|
463
|
-
break;
|
|
464
|
-
}
|
|
465
|
-
case "user": {
|
|
466
|
-
addUserComponents(container, message.content, opts.markdownTheme);
|
|
467
|
-
break;
|
|
468
|
-
}
|
|
469
|
-
case "bashExecution": {
|
|
470
|
-
const bash = new BashExecutionComponent(message.command, opts.tui, message.excludeFromContext);
|
|
471
|
-
if (message.output) bash.appendOutput(message.output);
|
|
472
|
-
bash.setComplete(message.exitCode, message.cancelled, undefined, message.fullOutputPath);
|
|
473
|
-
container.addChild(bash);
|
|
474
|
-
break;
|
|
475
|
-
}
|
|
476
|
-
case "compactionSummary": {
|
|
477
|
-
container.addChild(new Spacer(1));
|
|
478
|
-
const summary = new CompactionSummaryMessageComponent(message, opts.markdownTheme);
|
|
479
|
-
summary.setExpanded(true);
|
|
480
|
-
container.addChild(summary);
|
|
481
|
-
break;
|
|
482
|
-
}
|
|
483
|
-
case "branchSummary": {
|
|
484
|
-
container.addChild(new Spacer(1));
|
|
485
|
-
const summary = new BranchSummaryMessageComponent(message, opts.markdownTheme);
|
|
486
|
-
summary.setExpanded(true);
|
|
487
|
-
container.addChild(summary);
|
|
488
|
-
break;
|
|
415
|
+
const lines = this.body.render(innerW);
|
|
416
|
+
this.renderedIndicator = this.indicatorLine();
|
|
417
|
+
if (this.renderedIndicator) {
|
|
418
|
+
lines.push("", this.renderedIndicator);
|
|
489
419
|
}
|
|
420
|
+
return lines;
|
|
490
421
|
}
|
|
491
|
-
}
|
|
492
422
|
|
|
493
|
-
/**
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
markdownTheme: MarkdownTheme,
|
|
498
|
-
): void {
|
|
499
|
-
const text = userMessageText(content);
|
|
500
|
-
if (!text) return;
|
|
501
|
-
if (container.children.length > 0) container.addChild(new Spacer(1));
|
|
502
|
-
|
|
503
|
-
const skillBlock = parseSkillBlock(text);
|
|
504
|
-
if (!skillBlock) {
|
|
505
|
-
container.addChild(new UserMessageComponent(text, markdownTheme));
|
|
506
|
-
return;
|
|
507
|
-
}
|
|
508
|
-
const skill = new SkillInvocationMessageComponent(skillBlock, markdownTheme);
|
|
509
|
-
skill.setExpanded(true);
|
|
510
|
-
container.addChild(skill);
|
|
511
|
-
if (skillBlock.userMessage) {
|
|
512
|
-
container.addChild(new Spacer(1));
|
|
513
|
-
container.addChild(new UserMessageComponent(skillBlock.userMessage, markdownTheme));
|
|
423
|
+
/** Running-agent indicator line, or "" when the source is not streaming. */
|
|
424
|
+
private indicatorLine(): string {
|
|
425
|
+
const streaming = this.source.streaming();
|
|
426
|
+
return streaming ? `◍ ${describeActivity(streaming.activeTools, streaming.responseText)}` : "";
|
|
514
427
|
}
|
|
515
428
|
}
|
|
516
429
|
|
|
517
|
-
/** Concatenate the text blocks of a user message's content (mirrors Pi). */
|
|
518
|
-
function userMessageText(content: string | readonly { type: string; text?: string }[]): string {
|
|
519
|
-
if (typeof content === "string") return content;
|
|
520
|
-
return content
|
|
521
|
-
.filter((block) => block.type === "text")
|
|
522
|
-
.map((block) => block.text ?? "")
|
|
523
|
-
.join("");
|
|
524
|
-
}
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* transcript-body.ts — Incremental materialization of a subagent transcript.
|
|
3
|
+
*
|
|
4
|
+
* Owns the per-entry component tree the `/subagents:sessions` overlay renders.
|
|
5
|
+
* Pi's own interactive mode materializes each session entry once and then updates
|
|
6
|
+
* the affected component in place (`AssistantMessageComponent.updateContent`,
|
|
7
|
+
* `ToolExecutionComponent.updateArgs`/`updateResult`), rebuilding only after a
|
|
8
|
+
* compaction. This module mirrors that lifecycle for the read-only overlay:
|
|
9
|
+
* `sync()` diffs the source's message list against what is already materialized
|
|
10
|
+
* and touches only the messages that changed, so a streaming agent costs one
|
|
11
|
+
* message refresh per event instead of a full transcript rebuild.
|
|
12
|
+
*
|
|
13
|
+
* Rendering (scroll state, chrome, line cache) stays in the overlay; the body
|
|
14
|
+
* only answers "what components does this message list produce?".
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
AssistantMessageComponent,
|
|
19
|
+
BashExecutionComponent,
|
|
20
|
+
BranchSummaryMessageComponent,
|
|
21
|
+
CompactionSummaryMessageComponent,
|
|
22
|
+
parseSkillBlock,
|
|
23
|
+
SkillInvocationMessageComponent,
|
|
24
|
+
type ToolDefinition,
|
|
25
|
+
ToolExecutionComponent,
|
|
26
|
+
UserMessageComponent,
|
|
27
|
+
} from "@earendil-works/pi-coding-agent";
|
|
28
|
+
import { Container, type Component, type MarkdownTheme, Spacer, type TUI } from "@earendil-works/pi-tui";
|
|
29
|
+
import type { SessionMessage } from "../types";
|
|
30
|
+
|
|
31
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
/** Dependencies the per-entry component tree needs from the SDK/TUI environment. */
|
|
34
|
+
export interface TranscriptRenderOptions {
|
|
35
|
+
tui: TUI;
|
|
36
|
+
cwd: string;
|
|
37
|
+
markdownTheme: MarkdownTheme;
|
|
38
|
+
getToolDefinition: (name: string) => ToolDefinition | undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** What one `sync()` changed, so callers can skip line-cache invalidation when nothing did. */
|
|
42
|
+
export interface TranscriptSyncOutcome {
|
|
43
|
+
/** Messages materialized for the first time. */
|
|
44
|
+
readonly appended: number;
|
|
45
|
+
/** Existing entries whose content was updated in place (streaming tail). */
|
|
46
|
+
readonly refreshed: number;
|
|
47
|
+
/** Entries dropped after the transcript diverged (their replacements count as `appended`). */
|
|
48
|
+
readonly rebuilt: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A materialized tool component plus the tool name it was built for (the renderer is name-bound). */
|
|
52
|
+
interface MaterializedTool {
|
|
53
|
+
readonly name: string;
|
|
54
|
+
readonly component: ToolExecutionComponent;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** One materialized message plus the components it contributed, in render order. */
|
|
58
|
+
interface MaterializedEntry {
|
|
59
|
+
/** The message as last materialized — refreshed in place when it mutates. */
|
|
60
|
+
message: SessionMessage;
|
|
61
|
+
/** Assistant text/thinking component, when the message produced one. */
|
|
62
|
+
assistant?: AssistantMessageComponent;
|
|
63
|
+
/** Tool components created by this message's tool calls, keyed by call id (with the name they were built for). */
|
|
64
|
+
readonly tools: Map<string, MaterializedTool>;
|
|
65
|
+
/** Children contributed to the container, in add order. */
|
|
66
|
+
readonly children: Component[];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Message roles that pi mutates in place while streaming (everything else is immutable once emitted). */
|
|
70
|
+
const REFRESHABLE_ROLES = new Set(["assistant", "toolResult"]);
|
|
71
|
+
|
|
72
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Materialized component tree for one transcript, updated incrementally.
|
|
76
|
+
*
|
|
77
|
+
* Not a `Component` itself: the overlay needs the *lines* plus its own chrome and
|
|
78
|
+
* scroll state, so the body exposes `render(width)` as a plain line producer.
|
|
79
|
+
*/
|
|
80
|
+
export class TranscriptBody {
|
|
81
|
+
private readonly container = new Container();
|
|
82
|
+
/** One entry per materialized message, index-aligned with the source's message list. */
|
|
83
|
+
private readonly entries: MaterializedEntry[] = [];
|
|
84
|
+
/** Tool components by tool-call id; each result message is applied to the component its call created. */
|
|
85
|
+
private readonly pendingTools = new Map<string, ToolExecutionComponent>();
|
|
86
|
+
/** Fingerprint of the tail message's rendered content — detects an in-place streaming mutation. */
|
|
87
|
+
private tailFingerprint = "";
|
|
88
|
+
|
|
89
|
+
constructor(private readonly opts: TranscriptRenderOptions) {}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Diff `messages` against what is materialized and update only what changed.
|
|
93
|
+
*
|
|
94
|
+
* Three kinds of change are recognized:
|
|
95
|
+
* - append: the source grew (the common case for a live agent);
|
|
96
|
+
* - refresh: the tail message was mutated in place (streaming text, more
|
|
97
|
+
* tool calls, a resolved tool result) — its components are reused;
|
|
98
|
+
* - rebuild: the transcript diverged (compaction, branch switch, edited
|
|
99
|
+
* message) — everything from the divergence point is dropped and
|
|
100
|
+
* re-materialized, mirroring pi's `rebuildChatFromMessages`.
|
|
101
|
+
*/
|
|
102
|
+
sync(messages: readonly SessionMessage[]): TranscriptSyncOutcome {
|
|
103
|
+
let shared = this.sharedPrefix(messages);
|
|
104
|
+
let refreshed = 0;
|
|
105
|
+
|
|
106
|
+
// A divergence at the tail keeps its components: pi rewrites the streaming
|
|
107
|
+
// assistant message in place, so the same entry is refreshed rather than
|
|
108
|
+
// rebuilt (which would re-render every tool output of that message).
|
|
109
|
+
if (shared < this.entries.length && this.isRefreshableTail(messages, shared)) {
|
|
110
|
+
this.refreshEntry(this.entries[shared] as MaterializedEntry, messages[shared] as SessionMessage);
|
|
111
|
+
shared++;
|
|
112
|
+
refreshed++;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const rebuilt = shared < this.entries.length ? this.dropEntriesFrom(shared) : 0;
|
|
116
|
+
|
|
117
|
+
let appended = 0;
|
|
118
|
+
for (let i = this.entries.length; i < messages.length; i++) {
|
|
119
|
+
this.appendEntry(messages[i] as SessionMessage);
|
|
120
|
+
appended++;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Same length, same identities: the only thing that can have changed is the
|
|
124
|
+
// tail message's content, streamed into the object pi already pushed.
|
|
125
|
+
if (appended === 0 && rebuilt === 0 && refreshed === 0 && messages.length > 0) {
|
|
126
|
+
const tail = messages[messages.length - 1] as SessionMessage;
|
|
127
|
+
if (this.tailFingerprint !== fingerprintOf(tail)) {
|
|
128
|
+
const entry = this.entries[messages.length - 1] as MaterializedEntry;
|
|
129
|
+
this.refreshEntry(entry, tail);
|
|
130
|
+
refreshed++;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return { appended, refreshed, rebuilt };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Laid-out lines for every materialized message. */
|
|
138
|
+
render(width: number): string[] {
|
|
139
|
+
return this.container.render(width);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Drop cached layout inside every materialized component (theme or width change). */
|
|
143
|
+
invalidate(): void {
|
|
144
|
+
this.container.invalidate();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ---- Materialization ----
|
|
148
|
+
|
|
149
|
+
/** Longest prefix of messages that is still the exact object it was materialized from. */
|
|
150
|
+
private sharedPrefix(messages: readonly SessionMessage[]): number {
|
|
151
|
+
const limit = Math.min(this.entries.length, messages.length);
|
|
152
|
+
let shared = 0;
|
|
153
|
+
while (shared < limit && this.entries[shared]?.message === messages[shared]) shared++;
|
|
154
|
+
return shared;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* True when the divergence at `shared` is a streaming rewrite of the tail
|
|
159
|
+
* message (same role) rather than the transcript being replaced.
|
|
160
|
+
*/
|
|
161
|
+
private isRefreshableTail(messages: readonly SessionMessage[], shared: number): boolean {
|
|
162
|
+
const entry = this.entries[shared];
|
|
163
|
+
const message = messages[shared];
|
|
164
|
+
if (!entry || !message) return false;
|
|
165
|
+
if (shared !== this.entries.length - 1) return false;
|
|
166
|
+
return entry.message.role === message.role && REFRESHABLE_ROLES.has(message.role);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Update the tail entry in place, reusing every component it already owns. */
|
|
170
|
+
private refreshEntry(entry: MaterializedEntry, message: SessionMessage): void {
|
|
171
|
+
if (message.role === "assistant") {
|
|
172
|
+
entry.assistant?.updateContent(message);
|
|
173
|
+
this.syncToolCalls(entry, message);
|
|
174
|
+
} else if (message.role === "toolResult") {
|
|
175
|
+
this.pendingTools.get(message.toolCallId)?.updateResult(message);
|
|
176
|
+
}
|
|
177
|
+
entry.message = message;
|
|
178
|
+
this.tailFingerprint = fingerprintOf(message);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Materialize one message's components, appending them to the container. */
|
|
182
|
+
private appendEntry(message: SessionMessage): void {
|
|
183
|
+
const entry: MaterializedEntry = { message, tools: new Map(), children: [] };
|
|
184
|
+
switch (message.role) {
|
|
185
|
+
case "assistant": {
|
|
186
|
+
const assistant = new AssistantMessageComponent(message, false, this.opts.markdownTheme);
|
|
187
|
+
entry.assistant = assistant;
|
|
188
|
+
this.addChild(entry, assistant);
|
|
189
|
+
this.syncToolCalls(entry, message);
|
|
190
|
+
break;
|
|
191
|
+
}
|
|
192
|
+
case "toolResult": {
|
|
193
|
+
this.pendingTools.get(message.toolCallId)?.updateResult(message);
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
case "user": {
|
|
197
|
+
this.appendUserComponents(entry, message.content);
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
case "bashExecution": {
|
|
201
|
+
const bash = new BashExecutionComponent(message.command, this.opts.tui, message.excludeFromContext);
|
|
202
|
+
if (message.output) bash.appendOutput(message.output);
|
|
203
|
+
bash.setComplete(message.exitCode, message.cancelled, undefined, message.fullOutputPath);
|
|
204
|
+
this.addChild(entry, bash);
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
case "compactionSummary": {
|
|
208
|
+
this.addChild(entry, new Spacer(1));
|
|
209
|
+
const summary = new CompactionSummaryMessageComponent(message, this.opts.markdownTheme);
|
|
210
|
+
summary.setExpanded(true);
|
|
211
|
+
this.addChild(entry, summary);
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
case "branchSummary": {
|
|
215
|
+
this.addChild(entry, new Spacer(1));
|
|
216
|
+
const summary = new BranchSummaryMessageComponent(message, this.opts.markdownTheme);
|
|
217
|
+
summary.setExpanded(true);
|
|
218
|
+
this.addChild(entry, summary);
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
this.entries.push(entry);
|
|
223
|
+
this.tailFingerprint = fingerprintOf(message);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Create (or update) the tool component of every tool call in an assistant
|
|
228
|
+
* message. A tool call that appears mid-stream is appended after the message's
|
|
229
|
+
* earlier children, matching pi's own ordering.
|
|
230
|
+
*/
|
|
231
|
+
private syncToolCalls(entry: MaterializedEntry, message: SessionMessage): void {
|
|
232
|
+
if (message.role !== "assistant") return;
|
|
233
|
+
const present = new Set<string>();
|
|
234
|
+
for (const content of message.content) {
|
|
235
|
+
if (content.type !== "toolCall") continue;
|
|
236
|
+
present.add(content.id);
|
|
237
|
+
const existing = entry.tools.get(content.id);
|
|
238
|
+
if (existing && existing.name === content.name) {
|
|
239
|
+
existing.component.updateArgs(content.arguments);
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
// A call can vanish or change tool in an in-place rewrite of the tail
|
|
243
|
+
// message, so the reconciled set — not just additions — is what renders.
|
|
244
|
+
if (existing) this.dropTool(entry, content.id);
|
|
245
|
+
this.addTool(entry, content.id, content.name, content.arguments);
|
|
246
|
+
}
|
|
247
|
+
for (const id of entry.tools.keys()) {
|
|
248
|
+
if (!present.has(id)) this.dropTool(entry, id);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Materialize one tool-call component and register it for its result. */
|
|
253
|
+
private addTool(entry: MaterializedEntry, id: string, name: string, args: unknown): void {
|
|
254
|
+
const component = new ToolExecutionComponent(
|
|
255
|
+
name,
|
|
256
|
+
id,
|
|
257
|
+
args,
|
|
258
|
+
{ showImages: false },
|
|
259
|
+
this.opts.getToolDefinition(name),
|
|
260
|
+
this.opts.tui,
|
|
261
|
+
this.opts.cwd,
|
|
262
|
+
);
|
|
263
|
+
entry.tools.set(id, { name, component });
|
|
264
|
+
this.pendingTools.set(id, component);
|
|
265
|
+
this.addChild(entry, component);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Drop one tool-call component (its call disappeared or changed tool). */
|
|
269
|
+
private dropTool(entry: MaterializedEntry, id: string): void {
|
|
270
|
+
const materialized = entry.tools.get(id);
|
|
271
|
+
if (!materialized) return;
|
|
272
|
+
entry.tools.delete(id);
|
|
273
|
+
this.pendingTools.delete(id);
|
|
274
|
+
this.removeChild(entry, materialized.component);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Render a user message (skill block + text) into the container, mirroring pi. */
|
|
278
|
+
private appendUserComponents(entry: MaterializedEntry, content: UserMessageContent): void {
|
|
279
|
+
const text = userMessageText(content);
|
|
280
|
+
if (!text) return;
|
|
281
|
+
if (this.container.children.length > 0) this.addChild(entry, new Spacer(1));
|
|
282
|
+
|
|
283
|
+
const skillBlock = parseSkillBlock(text);
|
|
284
|
+
if (!skillBlock) {
|
|
285
|
+
this.addChild(entry, new UserMessageComponent(text, this.opts.markdownTheme));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const skill = new SkillInvocationMessageComponent(skillBlock, this.opts.markdownTheme);
|
|
289
|
+
skill.setExpanded(true);
|
|
290
|
+
this.addChild(entry, skill);
|
|
291
|
+
if (skillBlock.userMessage) {
|
|
292
|
+
this.addChild(entry, new Spacer(1));
|
|
293
|
+
this.addChild(entry, new UserMessageComponent(skillBlock.userMessage, this.opts.markdownTheme));
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Attach a child to both the container and the entry that owns it. */
|
|
298
|
+
private addChild(entry: MaterializedEntry, child: Component): void {
|
|
299
|
+
entry.children.push(child);
|
|
300
|
+
this.container.addChild(child);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Detach a child from both the container and the entry that owns it. */
|
|
304
|
+
private removeChild(entry: MaterializedEntry, child: Component): void {
|
|
305
|
+
const index = entry.children.indexOf(child);
|
|
306
|
+
if (index !== -1) entry.children.splice(index, 1);
|
|
307
|
+
this.container.removeChild(child);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Drop every entry from `index` on, removing its children. Returns how many
|
|
312
|
+
* entries were dropped — the caller re-materializes the tail.
|
|
313
|
+
*/
|
|
314
|
+
private dropEntriesFrom(index: number): number {
|
|
315
|
+
const dropped = this.entries.splice(index);
|
|
316
|
+
for (const entry of dropped) {
|
|
317
|
+
for (const child of entry.children) this.container.removeChild(child);
|
|
318
|
+
for (const id of entry.tools.keys()) this.pendingTools.delete(id);
|
|
319
|
+
}
|
|
320
|
+
const tail = this.entries[this.entries.length - 1];
|
|
321
|
+
this.tailFingerprint = tail ? fingerprintOf(tail.message) : "";
|
|
322
|
+
return dropped.length;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ── Fingerprints ───────────────────────────────────────────────────────────────
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Content fingerprint that changes whenever a message would render differently.
|
|
330
|
+
*
|
|
331
|
+
* Only ever stored for the tail message: pi emits every earlier message once and
|
|
332
|
+
* never mutates it (compaction replaces the list instead, which identity-diffing
|
|
333
|
+
* catches). Values — not lengths — are captured, so an edit that keeps the byte
|
|
334
|
+
* count identical still registers.
|
|
335
|
+
*/
|
|
336
|
+
function fingerprintOf(message: SessionMessage): string {
|
|
337
|
+
switch (message.role) {
|
|
338
|
+
case "bashExecution":
|
|
339
|
+
return `bashExecution\u0000${message.command}\u0000${message.output}`;
|
|
340
|
+
case "branchSummary":
|
|
341
|
+
return `branchSummary\u0000${message.summary}`;
|
|
342
|
+
case "compactionSummary":
|
|
343
|
+
return `compactionSummary\u0000${message.summary}`;
|
|
344
|
+
case "assistant":
|
|
345
|
+
// `stopReason`/`errorMessage` drive the aborted/error footer lines, and an
|
|
346
|
+
// extension's `message_end` replacement can flip them on a message that
|
|
347
|
+
// keeps its object identity.
|
|
348
|
+
return `assistant\u0000${message.stopReason ?? ""}\u0000${message.errorMessage ?? ""}\u0000${contentFingerprint(message.content)}`;
|
|
349
|
+
case "toolResult":
|
|
350
|
+
// `isError` picks the success/error background, `toolName` the renderer.
|
|
351
|
+
return `toolResult\u0000${message.toolCallId}\u0000${message.toolName}\u0000${message.isError}\u0000${contentFingerprint(message.content)}`;
|
|
352
|
+
default:
|
|
353
|
+
return `${message.role}\u0000${contentFingerprint(message.content)}`;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Fingerprint a message body; non-array shapes degrade to their string form instead of throwing. */
|
|
358
|
+
function contentFingerprint(content: unknown): string {
|
|
359
|
+
if (typeof content === "string") return content;
|
|
360
|
+
if (!Array.isArray(content)) return String(content);
|
|
361
|
+
return content.map(fingerprintOfBlock).join("\u0001");
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Fingerprint one content block; unknown block types (e.g. images) only contribute their type. */
|
|
365
|
+
function fingerprintOfBlock(block: { type: string }): string {
|
|
366
|
+
const value = block as {
|
|
367
|
+
type: string;
|
|
368
|
+
text?: string;
|
|
369
|
+
thinking?: string;
|
|
370
|
+
id?: string;
|
|
371
|
+
name?: string;
|
|
372
|
+
arguments?: unknown;
|
|
373
|
+
};
|
|
374
|
+
switch (block.type) {
|
|
375
|
+
case "text":
|
|
376
|
+
return `text:${value.text ?? ""}`;
|
|
377
|
+
case "thinking":
|
|
378
|
+
return `thinking:${value.thinking ?? ""}`;
|
|
379
|
+
case "toolCall":
|
|
380
|
+
return `toolCall:${value.id ?? ""}:${value.name ?? ""}:${JSON.stringify(value.arguments ?? null)}`;
|
|
381
|
+
default:
|
|
382
|
+
return block.type;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// ── User message helpers ───────────────────────────────────────────────────────
|
|
387
|
+
|
|
388
|
+
/** Content shape of a user message as the SDK emits it. */
|
|
389
|
+
type UserMessageContent = string | readonly { type: string; text?: string }[];
|
|
390
|
+
|
|
391
|
+
/** Concatenate the text blocks of a user message's content (mirrors pi). */
|
|
392
|
+
function userMessageText(content: UserMessageContent): string {
|
|
393
|
+
if (typeof content === "string") return content;
|
|
394
|
+
return content
|
|
395
|
+
.filter((block) => block.type === "text")
|
|
396
|
+
.map((block) => block.text ?? "")
|
|
397
|
+
.join("");
|
|
398
|
+
}
|