@xzzpig/pi-subagents 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -1
- package/README.md +4 -0
- package/docs/agents.md +39 -0
- package/docs/configuration.md +1 -1
- package/node_modules/@xzzpig/pi-components/CHANGELOG.md +102 -0
- package/node_modules/@xzzpig/pi-components/LICENSE +21 -0
- package/node_modules/@xzzpig/pi-components/README.md +59 -0
- package/node_modules/@xzzpig/pi-components/dist/index.d.ts +1 -0
- package/node_modules/@xzzpig/pi-components/dist/index.js +1 -0
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +345 -0
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +1169 -0
- package/node_modules/@xzzpig/pi-components/package.json +49 -0
- package/node_modules/@xzzpig/pi-components/src/transcript.ts +1785 -0
- package/package.json +5 -1
- package/src/agents/agent-serializer.ts +2 -0
- package/src/agents/agents.ts +43 -11
- package/src/agents/runtime-agent-registry.ts +5 -1
- package/src/extension/context-injection.ts +118 -0
- package/src/extension/doctor.ts +11 -0
- package/src/extension/index.ts +41 -0
- package/src/shared/types.ts +5 -0
- package/src/tui/fleet-native-transcript.ts +374 -0
- package/src/tui/fleet-transcript.ts +47 -1
- package/src/tui/fleet.ts +96 -24
|
@@ -0,0 +1,1169 @@
|
|
|
1
|
+
import { AssistantMessageComponent, getMarkdownTheme, initTheme, ToolExecutionComponent, UserMessageComponent, } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
|
|
3
|
+
const DEFAULT_MAX_ENTRIES = 500;
|
|
4
|
+
const DEFAULT_MAX_CHARS = 512 * 1024;
|
|
5
|
+
const DEFAULT_MAX_TOOL_ARGS_CHARS = 64 * 1024;
|
|
6
|
+
let themeEnsured = false;
|
|
7
|
+
/**
|
|
8
|
+
* The SDK shares its global theme across module instances (tsx/jiti/host) via
|
|
9
|
+
* these globalThis symbols — the same keys its exported `theme` proxy checks
|
|
10
|
+
* before throwing "Theme not initialized" (see theme.js in pi-coding-agent).
|
|
11
|
+
* Both historical and current spellings are probed for older host support.
|
|
12
|
+
*/
|
|
13
|
+
const THEME_GLOBAL_KEY = Symbol.for("@earendil-works/pi-coding-agent:theme");
|
|
14
|
+
const THEME_GLOBAL_KEY_OLD = Symbol.for("@mariozechner/pi-coding-agent:theme");
|
|
15
|
+
function isTranscriptThemeInitialized() {
|
|
16
|
+
// SAFETY: the SDK stores its theme on globalThis under a symbol key; the
|
|
17
|
+
// proxy does `if (!t) throw` on the same lookup, so a defined value means
|
|
18
|
+
// a fully constructed Theme instance the proxy will hand back directly.
|
|
19
|
+
const globals = globalThis;
|
|
20
|
+
return (globals[THEME_GLOBAL_KEY] !== undefined ||
|
|
21
|
+
globals[THEME_GLOBAL_KEY_OLD] !== undefined);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Ensures Pi's global theme is initialized so native message/tool components
|
|
25
|
+
* can render outside a live interactive session (headless embeds, unit tests).
|
|
26
|
+
*
|
|
27
|
+
* IMPORTANT: when the host has already initialized the theme (interactive Pi
|
|
28
|
+
* installs the user's chosen theme before any transcript renders), this is a
|
|
29
|
+
* strict no-op. Re-calling `initTheme()` would re-resolve the default theme
|
|
30
|
+
* from environment detection and can silently replace the user's selection
|
|
31
|
+
* with the dark fallback — changing tool-call colors in the main session too.
|
|
32
|
+
*/
|
|
33
|
+
export function ensureTranscriptTheme() {
|
|
34
|
+
if (themeEnsured)
|
|
35
|
+
return;
|
|
36
|
+
themeEnsured = true;
|
|
37
|
+
if (isTranscriptThemeInitialized())
|
|
38
|
+
return;
|
|
39
|
+
initTheme();
|
|
40
|
+
}
|
|
41
|
+
const DETACHED_TUI = { requestRender() { } };
|
|
42
|
+
/**
|
|
43
|
+
* Owns the persistent `ToolExecutionComponent` instance for every live tool
|
|
44
|
+
* call, mirroring how Pi's interactive mode keeps pending components keyed by
|
|
45
|
+
* `toolCallId`. Instances are updated incrementally as events arrive and are
|
|
46
|
+
* pruned by the host once their transcript entries disappear.
|
|
47
|
+
*/
|
|
48
|
+
export class TranscriptToolComponents {
|
|
49
|
+
components = new Map();
|
|
50
|
+
options;
|
|
51
|
+
attachedTui;
|
|
52
|
+
/**
|
|
53
|
+
* Components capture their TUI at construction. This forwarder lets a host
|
|
54
|
+
* attach (or replace) the real TUI at any time — including after tool
|
|
55
|
+
* events already created instances — without rebuilding them.
|
|
56
|
+
*/
|
|
57
|
+
forwardedTui;
|
|
58
|
+
constructor(options = {}) {
|
|
59
|
+
this.options = options;
|
|
60
|
+
this.attachedTui = options.tui ?? null;
|
|
61
|
+
this.forwardedTui = {
|
|
62
|
+
requestRender: () => this.attachedTui?.requestRender(),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Wires (or replaces) the host TUI that receives repaint requests. */
|
|
66
|
+
attachTui(tui) {
|
|
67
|
+
this.attachedTui = tui;
|
|
68
|
+
}
|
|
69
|
+
get size() {
|
|
70
|
+
return this.components.size;
|
|
71
|
+
}
|
|
72
|
+
has(toolCallId) {
|
|
73
|
+
return this.components.has(toolCallId);
|
|
74
|
+
}
|
|
75
|
+
get(toolCallId) {
|
|
76
|
+
return this.components.get(toolCallId);
|
|
77
|
+
}
|
|
78
|
+
handleStart(toolCallId, toolName, args) {
|
|
79
|
+
const component = this.ensure(toolCallId, toolName);
|
|
80
|
+
if (this.createdWithoutArgs.delete(toolCallId)) {
|
|
81
|
+
component.updateArgs(args ?? {});
|
|
82
|
+
}
|
|
83
|
+
component.setArgsComplete();
|
|
84
|
+
component.markExecutionStarted();
|
|
85
|
+
this.requestRender();
|
|
86
|
+
}
|
|
87
|
+
handleUpdate(toolCallId, toolName, partialResult) {
|
|
88
|
+
const component = this.ensure(toolCallId, toolName);
|
|
89
|
+
component.updateResult(toComponentResult(partialResult, false), true);
|
|
90
|
+
this.requestRender();
|
|
91
|
+
}
|
|
92
|
+
handleEnd(toolCallId, toolName, result, isError) {
|
|
93
|
+
const component = this.ensure(toolCallId, toolName);
|
|
94
|
+
component.updateResult(toComponentResult(result, isError), false);
|
|
95
|
+
this.requestRender();
|
|
96
|
+
}
|
|
97
|
+
/** Drops instances whose transcript entries no longer exist. */
|
|
98
|
+
retainOnly(aliveToolCallIds) {
|
|
99
|
+
for (const toolCallId of this.components.keys()) {
|
|
100
|
+
if (!aliveToolCallIds.has(toolCallId))
|
|
101
|
+
this.components.delete(toolCallId);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
clear() {
|
|
105
|
+
this.components.clear();
|
|
106
|
+
}
|
|
107
|
+
ensure(toolCallId, toolName) {
|
|
108
|
+
const existing = this.components.get(toolCallId);
|
|
109
|
+
if (existing)
|
|
110
|
+
return existing;
|
|
111
|
+
// Results may arrive before their start event; remember the placeholder so
|
|
112
|
+
// handleStart can backfill the real arguments later.
|
|
113
|
+
this.createdWithoutArgs.add(toolCallId);
|
|
114
|
+
const component = new ToolExecutionComponent(toolName, toolCallId, {}, {
|
|
115
|
+
showImages: this.options.showImages,
|
|
116
|
+
imageWidthCells: this.options.imageWidthCells,
|
|
117
|
+
}, this.options.resolveToolDefinition?.(toolName),
|
|
118
|
+
// Forwards to the attached host TUI; only requestRender is invoked.
|
|
119
|
+
this.forwardedTui, this.options.cwd ?? process.cwd());
|
|
120
|
+
if (this.options.expanded)
|
|
121
|
+
component.setExpanded(true);
|
|
122
|
+
this.components.set(toolCallId, component);
|
|
123
|
+
return component;
|
|
124
|
+
}
|
|
125
|
+
requestRender() {
|
|
126
|
+
// Matches Pi's interactive mode, which repaints after every tool event.
|
|
127
|
+
this.attachedTui?.requestRender();
|
|
128
|
+
}
|
|
129
|
+
createdWithoutArgs = new Set();
|
|
130
|
+
}
|
|
131
|
+
function toComponentResult(value, isError) {
|
|
132
|
+
const payload = value && typeof value === "object"
|
|
133
|
+
? value
|
|
134
|
+
: {};
|
|
135
|
+
const content = Array.isArray(payload.content)
|
|
136
|
+
? payload.content.map((part) => ({
|
|
137
|
+
type: part?.type ?? "text",
|
|
138
|
+
text: part?.text,
|
|
139
|
+
data: part?.data,
|
|
140
|
+
mimeType: part?.mimeType,
|
|
141
|
+
}))
|
|
142
|
+
: [];
|
|
143
|
+
return { content, details: payload.details, isError };
|
|
144
|
+
}
|
|
145
|
+
export function createTranscriptState(nativeTools = {}) {
|
|
146
|
+
return {
|
|
147
|
+
entries: [],
|
|
148
|
+
nextEntryId: 1,
|
|
149
|
+
nextTurnId: 1,
|
|
150
|
+
currentTurnId: null,
|
|
151
|
+
lastTurnId: null,
|
|
152
|
+
activeAssistant: null,
|
|
153
|
+
toolCalls: new Map(),
|
|
154
|
+
toolComponents: new TranscriptToolComponents(nativeTools),
|
|
155
|
+
toolArgsCharLimit: Math.max(16, nativeTools.maxToolArgsChars ?? DEFAULT_MAX_TOOL_ARGS_CHARS),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function codePointWidth(codePoint) {
|
|
159
|
+
return codePoint > 0xffff ? 2 : 1;
|
|
160
|
+
}
|
|
161
|
+
function isUnsafeTerminalCodePoint(codePoint) {
|
|
162
|
+
return ((codePoint <= 0x1f && codePoint !== 0x09 && codePoint !== 0x0a) ||
|
|
163
|
+
(codePoint >= 0x7f && codePoint <= 0x9f) ||
|
|
164
|
+
codePoint === 0x061c ||
|
|
165
|
+
codePoint === 0x200e ||
|
|
166
|
+
codePoint === 0x200f ||
|
|
167
|
+
(codePoint >= 0x202a && codePoint <= 0x202e) ||
|
|
168
|
+
(codePoint >= 0x2066 && codePoint <= 0x2069) ||
|
|
169
|
+
(codePoint >= 0xe000 && codePoint <= 0xf8ff) ||
|
|
170
|
+
(codePoint >= 0xf0000 && codePoint <= 0xffffd) ||
|
|
171
|
+
(codePoint >= 0x100000 && codePoint <= 0x10fffd) ||
|
|
172
|
+
(codePoint >= 0xd800 && codePoint <= 0xdfff) ||
|
|
173
|
+
(codePoint >= 0xfdd0 && codePoint <= 0xfdef) ||
|
|
174
|
+
(codePoint & 0xffff) === 0xfffe ||
|
|
175
|
+
(codePoint & 0xffff) === 0xffff);
|
|
176
|
+
}
|
|
177
|
+
function consumeControlString(value, index, osc) {
|
|
178
|
+
while (index < value.length) {
|
|
179
|
+
const codePoint = value.codePointAt(index);
|
|
180
|
+
if (codePoint === undefined)
|
|
181
|
+
break;
|
|
182
|
+
const width = codePointWidth(codePoint);
|
|
183
|
+
if (osc && codePoint === 0x07)
|
|
184
|
+
return index + width;
|
|
185
|
+
if (codePoint === 0x9c)
|
|
186
|
+
return index + width;
|
|
187
|
+
if (codePoint === 0x1b && value.charCodeAt(index + 1) === 0x5c)
|
|
188
|
+
return index + 2;
|
|
189
|
+
index += width;
|
|
190
|
+
}
|
|
191
|
+
return value.length;
|
|
192
|
+
}
|
|
193
|
+
function consumeCsi(value, index) {
|
|
194
|
+
while (index < value.length) {
|
|
195
|
+
const codePoint = value.codePointAt(index);
|
|
196
|
+
if (codePoint === undefined)
|
|
197
|
+
break;
|
|
198
|
+
const width = codePointWidth(codePoint);
|
|
199
|
+
if (codePoint >= 0x40 && codePoint <= 0x7e)
|
|
200
|
+
return index + width;
|
|
201
|
+
index += width;
|
|
202
|
+
}
|
|
203
|
+
return value.length;
|
|
204
|
+
}
|
|
205
|
+
function looksLikeBinaryContent(text) {
|
|
206
|
+
if (text.includes("\0"))
|
|
207
|
+
return true;
|
|
208
|
+
let suspiciousControls = 0;
|
|
209
|
+
let replacementCharacters = 0;
|
|
210
|
+
let codePoints = 0;
|
|
211
|
+
for (const character of text) {
|
|
212
|
+
codePoints++;
|
|
213
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
214
|
+
if (codePoint <= 0x08 || (codePoint >= 0x0e && codePoint <= 0x1f))
|
|
215
|
+
suspiciousControls++;
|
|
216
|
+
if (codePoint === 0xfffd)
|
|
217
|
+
replacementCharacters++;
|
|
218
|
+
}
|
|
219
|
+
return (codePoints > 0 &&
|
|
220
|
+
((suspiciousControls >= 4 && suspiciousControls / codePoints >= 0.1) ||
|
|
221
|
+
(replacementCharacters >= 3 && replacementCharacters / codePoints >= 0.1)));
|
|
222
|
+
}
|
|
223
|
+
/** Escapes terminal control sequences in model and tool output before rendering. */
|
|
224
|
+
export function safeTerminalText(value) {
|
|
225
|
+
const normalized = value.replace(/\r\n/g, "\n");
|
|
226
|
+
if (looksLikeBinaryContent(normalized))
|
|
227
|
+
return "[binary content omitted for safe display]";
|
|
228
|
+
let safe = "";
|
|
229
|
+
for (let index = 0; index < normalized.length;) {
|
|
230
|
+
const codePoint = normalized.codePointAt(index);
|
|
231
|
+
if (codePoint === undefined)
|
|
232
|
+
break;
|
|
233
|
+
const width = codePointWidth(codePoint);
|
|
234
|
+
if (codePoint === 0x1b) {
|
|
235
|
+
const next = normalized.charCodeAt(index + 1);
|
|
236
|
+
if (next === 0x5b) {
|
|
237
|
+
index = consumeCsi(normalized, index + 2);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (next === 0x5d ||
|
|
241
|
+
next === 0x50 ||
|
|
242
|
+
next === 0x58 ||
|
|
243
|
+
next === 0x5e ||
|
|
244
|
+
next === 0x5f) {
|
|
245
|
+
index = consumeControlString(normalized, index + 2, next === 0x5d);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
index += next ? 2 : 1;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (codePoint === 0x9b) {
|
|
252
|
+
index = consumeCsi(normalized, index + width);
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (codePoint === 0x90 ||
|
|
256
|
+
codePoint === 0x98 ||
|
|
257
|
+
codePoint === 0x9d ||
|
|
258
|
+
codePoint === 0x9e ||
|
|
259
|
+
codePoint === 0x9f) {
|
|
260
|
+
index = consumeControlString(normalized, index + width, codePoint === 0x9d);
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
safe += isUnsafeTerminalCodePoint(codePoint)
|
|
264
|
+
? `[U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}]`
|
|
265
|
+
: String.fromCodePoint(codePoint);
|
|
266
|
+
index += width;
|
|
267
|
+
}
|
|
268
|
+
return safe;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Appends a fully-formed entry, assigning the next sequential id.
|
|
272
|
+
*
|
|
273
|
+
* Public building block for hosts that construct transcripts from historical
|
|
274
|
+
* records instead of live agent events. The entry must be structurally valid
|
|
275
|
+
* for its `type`; ids and array placement are owned by this function.
|
|
276
|
+
*/
|
|
277
|
+
export function appendEntry(state, entry) {
|
|
278
|
+
const nextEntry = { ...entry, id: state.nextEntryId++ };
|
|
279
|
+
state.entries.push(nextEntry);
|
|
280
|
+
return nextEntry;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Returns the active turn id, opening a new turn (with a start boundary)
|
|
284
|
+
* when none is open. Public building block for historical-record ingestion.
|
|
285
|
+
*/
|
|
286
|
+
export function ensureTurn(state) {
|
|
287
|
+
if (state.currentTurnId !== null)
|
|
288
|
+
return state.currentTurnId;
|
|
289
|
+
const turnId = state.nextTurnId++;
|
|
290
|
+
state.currentTurnId = turnId;
|
|
291
|
+
state.lastTurnId = turnId;
|
|
292
|
+
appendEntry(state, { type: "turn-boundary", turnId, phase: "start" });
|
|
293
|
+
return turnId;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Finds the most recent entry of `type` inside `turnId`, scanning backwards.
|
|
297
|
+
* Public building block used by upsert-style helpers and hosts that merge
|
|
298
|
+
* repeated records (e.g. streamed message updates persisted as several lines).
|
|
299
|
+
*/
|
|
300
|
+
export function findLatestEntry(state, turnId, type) {
|
|
301
|
+
for (let index = state.entries.length - 1; index >= 0; index--) {
|
|
302
|
+
const entry = state.entries[index];
|
|
303
|
+
if (!entry)
|
|
304
|
+
continue;
|
|
305
|
+
if (entry.turnId === turnId && entry.type === type) {
|
|
306
|
+
return entry;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return undefined;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Closes `turnId` (defaulting to the current turn): appends the end boundary
|
|
313
|
+
* unless one already exists, clears streaming flags on the turn's entries,
|
|
314
|
+
* and updates bookkeeping. Idempotent — finishing an already-finished turn is
|
|
315
|
+
* a no-op for boundary creation. Public building block for hosts that know
|
|
316
|
+
* when a replayed exchange is complete.
|
|
317
|
+
*/
|
|
318
|
+
export function finishTurn(state, turnId = state.currentTurnId) {
|
|
319
|
+
if (turnId === null)
|
|
320
|
+
return;
|
|
321
|
+
const alreadyFinished = state.entries.some((entry) => entry.turnId === turnId &&
|
|
322
|
+
entry.type === "turn-boundary" &&
|
|
323
|
+
entry.phase === "end");
|
|
324
|
+
if (!alreadyFinished)
|
|
325
|
+
appendEntry(state, { type: "turn-boundary", turnId, phase: "end" });
|
|
326
|
+
for (const entry of state.entries) {
|
|
327
|
+
if (entry.turnId !== turnId)
|
|
328
|
+
continue;
|
|
329
|
+
if (entry.type === "thinking" ||
|
|
330
|
+
entry.type === "assistant-text" ||
|
|
331
|
+
entry.type === "tool-result") {
|
|
332
|
+
entry.streaming = false;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
state.lastTurnId = turnId;
|
|
336
|
+
if (state.currentTurnId === turnId)
|
|
337
|
+
state.currentTurnId = null;
|
|
338
|
+
if (state.activeAssistant?.turnId === turnId)
|
|
339
|
+
state.activeAssistant = null;
|
|
340
|
+
}
|
|
341
|
+
export function removeTranscriptTurn(state, turnId) {
|
|
342
|
+
if (turnId === null)
|
|
343
|
+
return;
|
|
344
|
+
state.entries = state.entries.filter((entry) => entry.turnId !== turnId);
|
|
345
|
+
for (const [toolCallId, toolCall] of state.toolCalls.entries()) {
|
|
346
|
+
if (toolCall.turnId === turnId)
|
|
347
|
+
state.toolCalls.delete(toolCallId);
|
|
348
|
+
}
|
|
349
|
+
if (state.currentTurnId === turnId)
|
|
350
|
+
state.currentTurnId = null;
|
|
351
|
+
if (state.lastTurnId === turnId)
|
|
352
|
+
state.lastTurnId = null;
|
|
353
|
+
if (state.activeAssistant?.turnId === turnId)
|
|
354
|
+
state.activeAssistant = null;
|
|
355
|
+
state.toolComponents.retainOnly(new Set(state.toolCalls.keys()));
|
|
356
|
+
}
|
|
357
|
+
function extractMessageText(message) {
|
|
358
|
+
if (typeof message.content === "string")
|
|
359
|
+
return safeTerminalText(message.content);
|
|
360
|
+
if (!Array.isArray(message.content))
|
|
361
|
+
return "";
|
|
362
|
+
const textParts = [];
|
|
363
|
+
for (const part of message.content) {
|
|
364
|
+
if (!part || typeof part !== "object")
|
|
365
|
+
continue;
|
|
366
|
+
const typedPart = part;
|
|
367
|
+
if (typedPart.type === "text" && typeof typedPart.text === "string") {
|
|
368
|
+
textParts.push(safeTerminalText(typedPart.text));
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return textParts.join("\n").trim();
|
|
372
|
+
}
|
|
373
|
+
function extractThinking(message) {
|
|
374
|
+
if (!Array.isArray(message.content))
|
|
375
|
+
return "";
|
|
376
|
+
const thinkingParts = [];
|
|
377
|
+
for (const part of message.content) {
|
|
378
|
+
if (!part || typeof part !== "object")
|
|
379
|
+
continue;
|
|
380
|
+
const typedPart = part;
|
|
381
|
+
if (typedPart.type === "thinking" &&
|
|
382
|
+
typeof typedPart.thinking === "string") {
|
|
383
|
+
thinkingParts.push(safeTerminalText(typedPart.thinking));
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return thinkingParts.join("\n").trim();
|
|
387
|
+
}
|
|
388
|
+
function jsonSize(value) {
|
|
389
|
+
if (value === undefined || value === null)
|
|
390
|
+
return 0;
|
|
391
|
+
try {
|
|
392
|
+
return JSON.stringify(value)?.length ?? 0;
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return String(value).length;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
function estimateToolResultSize(result) {
|
|
399
|
+
if (!result)
|
|
400
|
+
return 0;
|
|
401
|
+
let size = 0;
|
|
402
|
+
if (Array.isArray(result.content)) {
|
|
403
|
+
for (const part of result.content) {
|
|
404
|
+
if (!part || typeof part !== "object")
|
|
405
|
+
continue;
|
|
406
|
+
if (typeof part.text === "string")
|
|
407
|
+
size += part.text.length;
|
|
408
|
+
if (typeof part.data === "string")
|
|
409
|
+
size += part.data.length;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return size + jsonSize(result.details);
|
|
413
|
+
}
|
|
414
|
+
/** Deep-copies structured tool data for snapshots; falls back to the reference. */
|
|
415
|
+
function cloneStructured(value) {
|
|
416
|
+
if (value === null || typeof value !== "object")
|
|
417
|
+
return value;
|
|
418
|
+
try {
|
|
419
|
+
return structuredClone(value);
|
|
420
|
+
}
|
|
421
|
+
catch {
|
|
422
|
+
return value;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function buildTruncatedToolArgs(serialized, raw, limit) {
|
|
426
|
+
if (serialized === undefined) {
|
|
427
|
+
return {
|
|
428
|
+
truncated: true,
|
|
429
|
+
reason: "unserializable",
|
|
430
|
+
preview: String(raw).slice(0, limit),
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
return {
|
|
434
|
+
truncated: true,
|
|
435
|
+
originalChars: serialized.length,
|
|
436
|
+
preview: serialized.slice(0, limit),
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Returns a truncation marker when pathological tool arguments exceed
|
|
441
|
+
* `limit` (or cannot be serialized), and `null` when the payload may be
|
|
442
|
+
* stored verbatim. Ingestion therefore never throws and rendering stays
|
|
443
|
+
* bounded regardless of provider payload size.
|
|
444
|
+
*/
|
|
445
|
+
function oversizedToolArgs(args, limit) {
|
|
446
|
+
if (args === undefined || args === null)
|
|
447
|
+
return null;
|
|
448
|
+
let serialized;
|
|
449
|
+
try {
|
|
450
|
+
serialized = JSON.stringify(args);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
serialized = undefined;
|
|
454
|
+
}
|
|
455
|
+
if (serialized === undefined) {
|
|
456
|
+
return buildTruncatedToolArgs(undefined, args, limit);
|
|
457
|
+
}
|
|
458
|
+
return serialized.length <= limit
|
|
459
|
+
? null
|
|
460
|
+
: buildTruncatedToolArgs(serialized, args, limit);
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Finds or creates the tool-call record for `toolCallId`, appending a
|
|
464
|
+
* tool-call entry when none exists yet.
|
|
465
|
+
*
|
|
466
|
+
* Public building block for hosts that ingest historical records where calls
|
|
467
|
+
* and results may arrive in either order: when the result was recorded first,
|
|
468
|
+
* the placeholder entry's arguments are backfilled here from the later call
|
|
469
|
+
* record. Arguments exceeding the state's char limit are stored as a
|
|
470
|
+
* truncated marker object instead of failing.
|
|
471
|
+
*/
|
|
472
|
+
export function ensureToolCall(state, turnId, toolCallId, toolName, args) {
|
|
473
|
+
const existing = state.toolCalls.get(toolCallId);
|
|
474
|
+
if (existing) {
|
|
475
|
+
// Result-before-call replay: backfill arguments onto the placeholder.
|
|
476
|
+
if (args !== undefined && args !== null) {
|
|
477
|
+
const callEntry = state.entries.find((entry) => entry.id === existing.callEntryId && entry.type === "tool-call");
|
|
478
|
+
if (callEntry &&
|
|
479
|
+
callEntry.type === "tool-call" &&
|
|
480
|
+
(callEntry.args === undefined || callEntry.args === null)) {
|
|
481
|
+
callEntry.args =
|
|
482
|
+
oversizedToolArgs(args, state.toolArgsCharLimit) ?? args;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return existing;
|
|
486
|
+
}
|
|
487
|
+
const callEntry = appendEntry(state, {
|
|
488
|
+
type: "tool-call",
|
|
489
|
+
turnId,
|
|
490
|
+
toolCallId,
|
|
491
|
+
toolName,
|
|
492
|
+
args: oversizedToolArgs(args, state.toolArgsCharLimit) ?? args,
|
|
493
|
+
});
|
|
494
|
+
const record = { turnId, callEntryId: callEntry.id };
|
|
495
|
+
state.toolCalls.set(toolCallId, record);
|
|
496
|
+
return record;
|
|
497
|
+
}
|
|
498
|
+
function findActiveAssistantEntry(state, entryId, type) {
|
|
499
|
+
if (entryId === undefined)
|
|
500
|
+
return undefined;
|
|
501
|
+
const entry = state.entries.find((candidate) => candidate.id === entryId);
|
|
502
|
+
return entry?.type === type ? entry : undefined;
|
|
503
|
+
}
|
|
504
|
+
function updateActiveAssistantText(state, segment, type, text, streaming) {
|
|
505
|
+
if (!text)
|
|
506
|
+
return;
|
|
507
|
+
const entryId = type === "thinking" ? segment.thinkingEntryId : segment.textEntryId;
|
|
508
|
+
const existing = findActiveAssistantEntry(state, entryId, type);
|
|
509
|
+
if (existing) {
|
|
510
|
+
existing.text = text;
|
|
511
|
+
existing.streaming = streaming;
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
const entry = appendEntry(state, {
|
|
515
|
+
type,
|
|
516
|
+
turnId: segment.turnId,
|
|
517
|
+
text,
|
|
518
|
+
streaming,
|
|
519
|
+
});
|
|
520
|
+
if (type === "thinking")
|
|
521
|
+
segment.thinkingEntryId = entry.id;
|
|
522
|
+
else
|
|
523
|
+
segment.textEntryId = entry.id;
|
|
524
|
+
}
|
|
525
|
+
function ensureActiveAssistantSegment(state, turnId, startNew) {
|
|
526
|
+
if (startNew || state.activeAssistant?.turnId !== turnId) {
|
|
527
|
+
state.activeAssistant = { turnId };
|
|
528
|
+
}
|
|
529
|
+
return state.activeAssistant;
|
|
530
|
+
}
|
|
531
|
+
function finishActiveAssistantSegment(state) {
|
|
532
|
+
const segment = state.activeAssistant;
|
|
533
|
+
if (!segment)
|
|
534
|
+
return;
|
|
535
|
+
const thinking = findActiveAssistantEntry(state, segment.thinkingEntryId, "thinking");
|
|
536
|
+
if (thinking)
|
|
537
|
+
thinking.streaming = false;
|
|
538
|
+
const text = findActiveAssistantEntry(state, segment.textEntryId, "assistant-text");
|
|
539
|
+
if (text)
|
|
540
|
+
text.streaming = false;
|
|
541
|
+
state.activeAssistant = null;
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Inserts or updates the thinking/assistant-text entry for `turnId`.
|
|
545
|
+
* Repeated records for the same turn merge into one entry (latest text wins).
|
|
546
|
+
* Public building block for hosts that replay completed message records.
|
|
547
|
+
*/
|
|
548
|
+
export function upsertText(state, turnId, type, text, streaming) {
|
|
549
|
+
if (!text)
|
|
550
|
+
return;
|
|
551
|
+
const existing = findLatestEntry(state, turnId, type);
|
|
552
|
+
if (existing) {
|
|
553
|
+
existing.text = text;
|
|
554
|
+
existing.streaming = streaming;
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
appendEntry(state, { type, turnId, text, streaming });
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Inserts or updates the structured result of a tool call, creating the call
|
|
561
|
+
* placeholder first when the result arrives before its start event. Safe to
|
|
562
|
+
* call repeatedly — the latest result wins and streaming flags update in place.
|
|
563
|
+
* Public building block for hosts that ingest persisted tool results.
|
|
564
|
+
*/
|
|
565
|
+
export function upsertToolResult(state, turnId, toolCallId, toolName, result, isError, streaming) {
|
|
566
|
+
const toolCall = ensureToolCall(state, turnId, toolCallId, toolName, undefined);
|
|
567
|
+
const existing = toolCall.resultEntryId === undefined
|
|
568
|
+
? undefined
|
|
569
|
+
: state.entries.find((entry) => entry.id === toolCall.resultEntryId && entry.type === "tool-result");
|
|
570
|
+
if (existing && existing.type === "tool-result") {
|
|
571
|
+
existing.result = result;
|
|
572
|
+
existing.isError = isError;
|
|
573
|
+
existing.streaming = streaming;
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const resultEntry = appendEntry(state, {
|
|
577
|
+
type: "tool-result",
|
|
578
|
+
turnId,
|
|
579
|
+
toolCallId,
|
|
580
|
+
toolName,
|
|
581
|
+
result,
|
|
582
|
+
isError,
|
|
583
|
+
streaming,
|
|
584
|
+
});
|
|
585
|
+
toolCall.resultEntryId = resultEntry.id;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Appends a notice attached to the current turn (or the most recent one).
|
|
589
|
+
* Text is sanitized before storage. Public building block for hosts that
|
|
590
|
+
* surface stderr output, retry banners, or other non-conversation events.
|
|
591
|
+
*/
|
|
592
|
+
export function appendNotice(state, text, tone) {
|
|
593
|
+
const turnId = state.currentTurnId ?? state.lastTurnId ?? ensureTurn(state);
|
|
594
|
+
appendEntry(state, {
|
|
595
|
+
type: "notice",
|
|
596
|
+
turnId,
|
|
597
|
+
text: safeTerminalText(text),
|
|
598
|
+
tone,
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
function entryLength(entry) {
|
|
602
|
+
switch (entry.type) {
|
|
603
|
+
case "user-message":
|
|
604
|
+
case "thinking":
|
|
605
|
+
case "assistant-text":
|
|
606
|
+
case "notice":
|
|
607
|
+
return entry.text.length;
|
|
608
|
+
case "tool-call":
|
|
609
|
+
return entry.toolName.length + jsonSize(entry.args);
|
|
610
|
+
case "tool-result":
|
|
611
|
+
return entry.toolName.length + estimateToolResultSize(entry.result);
|
|
612
|
+
default:
|
|
613
|
+
return 0;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
function pruneToolCallIndex(state) {
|
|
617
|
+
const entryIds = new Set(state.entries.map((entry) => entry.id));
|
|
618
|
+
const aliveToolCallIds = new Set();
|
|
619
|
+
for (const [toolCallId, record] of state.toolCalls.entries()) {
|
|
620
|
+
if (!entryIds.has(record.callEntryId)) {
|
|
621
|
+
state.toolCalls.delete(toolCallId);
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
aliveToolCallIds.add(toolCallId);
|
|
625
|
+
if (record.resultEntryId !== undefined &&
|
|
626
|
+
!entryIds.has(record.resultEntryId)) {
|
|
627
|
+
record.resultEntryId = undefined;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
// Result entries whose call entry was trimmed away have no renderable
|
|
631
|
+
// position: their visual is owned by the component attached to the call.
|
|
632
|
+
let hasOrphanResults = false;
|
|
633
|
+
for (const entry of state.entries) {
|
|
634
|
+
if (entry.type === "tool-result" &&
|
|
635
|
+
!aliveToolCallIds.has(entry.toolCallId)) {
|
|
636
|
+
hasOrphanResults = true;
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
if (hasOrphanResults) {
|
|
641
|
+
state.entries = state.entries.filter((entry) => !(entry.type === "tool-result" &&
|
|
642
|
+
!aliveToolCallIds.has(entry.toolCallId)));
|
|
643
|
+
}
|
|
644
|
+
state.toolComponents.retainOnly(aliveToolCallIds);
|
|
645
|
+
}
|
|
646
|
+
export function trimTranscriptState(state, options = {}) {
|
|
647
|
+
const maxEntries = Math.max(16, options.maxEntries ?? DEFAULT_MAX_ENTRIES);
|
|
648
|
+
const maxChars = Math.max(1024, options.maxChars ?? DEFAULT_MAX_CHARS);
|
|
649
|
+
while (state.entries.length > maxEntries)
|
|
650
|
+
state.entries.shift();
|
|
651
|
+
let chars = state.entries.reduce((total, entry) => total + entryLength(entry), 0);
|
|
652
|
+
while (chars > maxChars && state.entries.length > 1) {
|
|
653
|
+
const removed = state.entries.shift();
|
|
654
|
+
if (removed)
|
|
655
|
+
chars -= entryLength(removed);
|
|
656
|
+
}
|
|
657
|
+
pruneToolCallIndex(state);
|
|
658
|
+
}
|
|
659
|
+
function eventString(value, fallback = "") {
|
|
660
|
+
return typeof value === "string" && value.trim()
|
|
661
|
+
? safeTerminalText(value)
|
|
662
|
+
: fallback;
|
|
663
|
+
}
|
|
664
|
+
function eventNumber(value, fallback = 0) {
|
|
665
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
666
|
+
}
|
|
667
|
+
function applyTranscriptMessageEvent(state, event, phase) {
|
|
668
|
+
const message = event.message ?? {};
|
|
669
|
+
if (message.role === "user") {
|
|
670
|
+
const turnId = ensureTurn(state);
|
|
671
|
+
const text = extractMessageText(message);
|
|
672
|
+
if (!text)
|
|
673
|
+
return;
|
|
674
|
+
const existing = findLatestEntry(state, turnId, "user-message");
|
|
675
|
+
if (existing)
|
|
676
|
+
existing.text = text;
|
|
677
|
+
else
|
|
678
|
+
appendEntry(state, { type: "user-message", turnId, text });
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
if (message.role !== "assistant")
|
|
682
|
+
return;
|
|
683
|
+
const turnId = ensureTurn(state);
|
|
684
|
+
const segment = ensureActiveAssistantSegment(state, turnId, phase === "start");
|
|
685
|
+
const streaming = phase !== "end";
|
|
686
|
+
updateActiveAssistantText(state, segment, "thinking", extractThinking(message), streaming);
|
|
687
|
+
updateActiveAssistantText(state, segment, "assistant-text", extractMessageText(message), streaming);
|
|
688
|
+
if (phase === "end")
|
|
689
|
+
finishActiveAssistantSegment(state);
|
|
690
|
+
}
|
|
691
|
+
function eventToolCallId(state, event) {
|
|
692
|
+
return eventString(event.toolCallId, `unknown-tool-${state.nextEntryId}`);
|
|
693
|
+
}
|
|
694
|
+
function normalizeToolResultPayload(value) {
|
|
695
|
+
if (value === undefined || value === null)
|
|
696
|
+
return null;
|
|
697
|
+
if (typeof value === "object")
|
|
698
|
+
return value;
|
|
699
|
+
if (typeof value === "string")
|
|
700
|
+
return { content: [{ type: "text", text: value }] };
|
|
701
|
+
return { content: [{ type: "text", text: String(value) }] };
|
|
702
|
+
}
|
|
703
|
+
function applyTranscriptToolResult(state, event, value, isError, streaming) {
|
|
704
|
+
const toolCallId = eventToolCallId(state, event);
|
|
705
|
+
const toolName = eventString(event.toolName, "tool");
|
|
706
|
+
const turnId = state.toolCalls.get(toolCallId)?.turnId ?? ensureTurn(state);
|
|
707
|
+
const payload = normalizeToolResultPayload(value);
|
|
708
|
+
upsertToolResult(state, turnId, toolCallId, toolName, payload, isError, streaming);
|
|
709
|
+
if (streaming) {
|
|
710
|
+
state.toolComponents.handleUpdate(toolCallId, toolName, payload);
|
|
711
|
+
}
|
|
712
|
+
else {
|
|
713
|
+
state.toolComponents.handleEnd(toolCallId, toolName, payload, isError);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
function appendRetryStartNotice(state, event) {
|
|
717
|
+
const attempt = eventNumber(event.attempt);
|
|
718
|
+
const maxAttempts = eventNumber(event.maxAttempts);
|
|
719
|
+
const delaySeconds = Math.max(0, Math.ceil(eventNumber(event.delayMs) / 1000));
|
|
720
|
+
const error = eventString(event.errorMessage, "temporary error");
|
|
721
|
+
appendNotice(state, `Retry ${attempt}/${maxAttempts} in ${delaySeconds}s: ${error}`, "warning");
|
|
722
|
+
}
|
|
723
|
+
function appendRetryEndNotice(state, event) {
|
|
724
|
+
const attempt = eventNumber(event.attempt);
|
|
725
|
+
if (event.success === true) {
|
|
726
|
+
appendNotice(state, `Retry ${attempt} succeeded.`, "info");
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const finalError = eventString(event.finalError);
|
|
730
|
+
const message = finalError
|
|
731
|
+
? `Retry ${attempt} failed: ${finalError}`
|
|
732
|
+
: `Retry ${attempt} failed.`;
|
|
733
|
+
appendNotice(state, message, "error");
|
|
734
|
+
}
|
|
735
|
+
export function applyAgentSessionEvent(state, input, options = {}) {
|
|
736
|
+
if (!input || typeof input !== "object")
|
|
737
|
+
return;
|
|
738
|
+
const event = input;
|
|
739
|
+
if (typeof event.type !== "string")
|
|
740
|
+
return;
|
|
741
|
+
switch (event.type) {
|
|
742
|
+
case "turn_start":
|
|
743
|
+
ensureTurn(state);
|
|
744
|
+
break;
|
|
745
|
+
case "message_start":
|
|
746
|
+
applyTranscriptMessageEvent(state, event, "start");
|
|
747
|
+
break;
|
|
748
|
+
case "message_update":
|
|
749
|
+
applyTranscriptMessageEvent(state, event, "update");
|
|
750
|
+
break;
|
|
751
|
+
case "message_end":
|
|
752
|
+
applyTranscriptMessageEvent(state, event, "end");
|
|
753
|
+
break;
|
|
754
|
+
case "tool_execution_start": {
|
|
755
|
+
const turnId = ensureTurn(state);
|
|
756
|
+
const toolCallId = eventToolCallId(state, event);
|
|
757
|
+
const toolName = eventString(event.toolName, "tool");
|
|
758
|
+
ensureToolCall(state, turnId, toolCallId, toolName, event.args);
|
|
759
|
+
state.toolComponents.handleStart(toolCallId, toolName, event.args);
|
|
760
|
+
break;
|
|
761
|
+
}
|
|
762
|
+
case "tool_execution_update":
|
|
763
|
+
applyTranscriptToolResult(state, event, event.partialResult, false, true);
|
|
764
|
+
break;
|
|
765
|
+
case "tool_execution_end":
|
|
766
|
+
applyTranscriptToolResult(state, event, event.result, event.isError === true, false);
|
|
767
|
+
break;
|
|
768
|
+
case "turn_end":
|
|
769
|
+
finishTurn(state);
|
|
770
|
+
break;
|
|
771
|
+
case "auto_retry_start":
|
|
772
|
+
appendRetryStartNotice(state, event);
|
|
773
|
+
break;
|
|
774
|
+
case "auto_retry_end":
|
|
775
|
+
appendRetryEndNotice(state, event);
|
|
776
|
+
break;
|
|
777
|
+
default:
|
|
778
|
+
break;
|
|
779
|
+
}
|
|
780
|
+
trimTranscriptState(state, options);
|
|
781
|
+
}
|
|
782
|
+
export class SessionTranscript {
|
|
783
|
+
state;
|
|
784
|
+
options;
|
|
785
|
+
constructor(options = {}) {
|
|
786
|
+
this.options = options;
|
|
787
|
+
this.state = createTranscriptState(options);
|
|
788
|
+
}
|
|
789
|
+
get entries() {
|
|
790
|
+
return this.state.entries;
|
|
791
|
+
}
|
|
792
|
+
/** Live native tool components keyed by tool call id. */
|
|
793
|
+
get toolComponents() {
|
|
794
|
+
return this.state.toolComponents;
|
|
795
|
+
}
|
|
796
|
+
snapshot() {
|
|
797
|
+
return this.state.entries.map((entry) => {
|
|
798
|
+
const copy = { ...entry };
|
|
799
|
+
if (copy.type === "tool-call")
|
|
800
|
+
copy.args = cloneStructured(copy.args);
|
|
801
|
+
else if (copy.type === "tool-result") {
|
|
802
|
+
copy.result = cloneStructured(copy.result);
|
|
803
|
+
}
|
|
804
|
+
return copy;
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
get currentTurnId() {
|
|
808
|
+
return this.state.currentTurnId;
|
|
809
|
+
}
|
|
810
|
+
apply(event) {
|
|
811
|
+
applyAgentSessionEvent(this.state, event, this.options);
|
|
812
|
+
}
|
|
813
|
+
appendCompletedTurn(details) {
|
|
814
|
+
const turnId = ensureTurn(this.state);
|
|
815
|
+
if (details.user)
|
|
816
|
+
appendEntry(this.state, {
|
|
817
|
+
type: "user-message",
|
|
818
|
+
turnId,
|
|
819
|
+
text: safeTerminalText(details.user),
|
|
820
|
+
});
|
|
821
|
+
if (details.thinking)
|
|
822
|
+
upsertText(this.state, turnId, "thinking", safeTerminalText(details.thinking), false);
|
|
823
|
+
upsertText(this.state, turnId, "assistant-text", safeTerminalText(details.assistant), false);
|
|
824
|
+
finishTurn(this.state, turnId);
|
|
825
|
+
trimTranscriptState(this.state, this.options);
|
|
826
|
+
}
|
|
827
|
+
appendFailure(message) {
|
|
828
|
+
const turnId = this.state.currentTurnId ??
|
|
829
|
+
this.state.lastTurnId ??
|
|
830
|
+
ensureTurn(this.state);
|
|
831
|
+
upsertText(this.state, turnId, "assistant-text", `Error: ${safeTerminalText(message)}`, false);
|
|
832
|
+
finishTurn(this.state, turnId);
|
|
833
|
+
trimTranscriptState(this.state, this.options);
|
|
834
|
+
}
|
|
835
|
+
appendNotice(message, tone = "info") {
|
|
836
|
+
appendNotice(this.state, message, tone);
|
|
837
|
+
trimTranscriptState(this.state, this.options);
|
|
838
|
+
}
|
|
839
|
+
removeCurrentTurn() {
|
|
840
|
+
removeTranscriptTurn(this.state, this.state.currentTurnId ?? this.state.lastTurnId);
|
|
841
|
+
}
|
|
842
|
+
clear() {
|
|
843
|
+
this.state.entries = [];
|
|
844
|
+
this.state.currentTurnId = null;
|
|
845
|
+
this.state.lastTurnId = null;
|
|
846
|
+
this.state.toolCalls.clear();
|
|
847
|
+
this.state.toolComponents.clear();
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
export function hasStreamingTranscriptEntry(entries) {
|
|
851
|
+
return entries.some((entry) => (entry.type === "thinking" ||
|
|
852
|
+
entry.type === "assistant-text" ||
|
|
853
|
+
entry.type === "tool-result") &&
|
|
854
|
+
entry.streaming);
|
|
855
|
+
}
|
|
856
|
+
export function getCompletedTranscriptExchangeCount(entries) {
|
|
857
|
+
return entries.filter((entry) => entry.type === "assistant-text" && !entry.streaming).length;
|
|
858
|
+
}
|
|
859
|
+
function buildRenderBlocks(entries) {
|
|
860
|
+
const blocks = [];
|
|
861
|
+
let pendingAssistant;
|
|
862
|
+
// Tool results are upserted in place, so the last entry per call id wins.
|
|
863
|
+
// Their visual output is owned by the native component rendered at the call
|
|
864
|
+
// position, so result entries never emit blocks of their own.
|
|
865
|
+
const latestResults = new Map();
|
|
866
|
+
for (const entry of entries) {
|
|
867
|
+
if (entry.type === "tool-result")
|
|
868
|
+
latestResults.set(entry.toolCallId, entry);
|
|
869
|
+
}
|
|
870
|
+
const flushAssistant = () => {
|
|
871
|
+
if (!pendingAssistant)
|
|
872
|
+
return;
|
|
873
|
+
blocks.push(pendingAssistant);
|
|
874
|
+
pendingAssistant = undefined;
|
|
875
|
+
};
|
|
876
|
+
const appendAssistantText = (type, text) => {
|
|
877
|
+
const safeText = safeTerminalText(text);
|
|
878
|
+
if (!safeText)
|
|
879
|
+
return;
|
|
880
|
+
const field = type === "thinking" ? "thinking" : "text";
|
|
881
|
+
if (pendingAssistant?.[field])
|
|
882
|
+
flushAssistant();
|
|
883
|
+
if (!pendingAssistant)
|
|
884
|
+
pendingAssistant = { kind: "assistant", thinking: "", text: "" };
|
|
885
|
+
pendingAssistant[field] = safeText;
|
|
886
|
+
};
|
|
887
|
+
for (const entry of entries) {
|
|
888
|
+
switch (entry.type) {
|
|
889
|
+
case "turn-boundary":
|
|
890
|
+
flushAssistant();
|
|
891
|
+
if (entry.phase === "start" && blocks.length > 0)
|
|
892
|
+
blocks.push({ kind: "separator" });
|
|
893
|
+
break;
|
|
894
|
+
case "user-message":
|
|
895
|
+
flushAssistant();
|
|
896
|
+
blocks.push({ kind: "user", text: entry.text });
|
|
897
|
+
break;
|
|
898
|
+
case "thinking":
|
|
899
|
+
appendAssistantText("thinking", entry.text);
|
|
900
|
+
break;
|
|
901
|
+
case "assistant-text":
|
|
902
|
+
appendAssistantText("assistant-text", entry.text);
|
|
903
|
+
break;
|
|
904
|
+
case "tool-call": {
|
|
905
|
+
flushAssistant();
|
|
906
|
+
const result = latestResults.get(entry.toolCallId);
|
|
907
|
+
blocks.push({
|
|
908
|
+
kind: "tool-native",
|
|
909
|
+
toolCallId: entry.toolCallId,
|
|
910
|
+
toolName: entry.toolName,
|
|
911
|
+
args: entry.args,
|
|
912
|
+
result: result?.result ?? null,
|
|
913
|
+
isError: result?.isError ?? false,
|
|
914
|
+
streaming: result?.streaming ?? false,
|
|
915
|
+
});
|
|
916
|
+
break;
|
|
917
|
+
}
|
|
918
|
+
case "tool-result":
|
|
919
|
+
break;
|
|
920
|
+
case "notice":
|
|
921
|
+
flushAssistant();
|
|
922
|
+
blocks.push({ kind: "notice", text: entry.text, tone: entry.tone });
|
|
923
|
+
break;
|
|
924
|
+
default:
|
|
925
|
+
break;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
flushAssistant();
|
|
929
|
+
return blocks;
|
|
930
|
+
}
|
|
931
|
+
const OSC_133_SEQUENCE = /\x1b]133;[ABC]\x07/g;
|
|
932
|
+
function stripOsc133(lines) {
|
|
933
|
+
return lines.map((line) => line.replace(OSC_133_SEQUENCE, ""));
|
|
934
|
+
}
|
|
935
|
+
function createPresentationAssistantMessage(thinking, text) {
|
|
936
|
+
const content = [
|
|
937
|
+
...(thinking
|
|
938
|
+
? [{ type: "thinking", thinking: safeTerminalText(thinking) }]
|
|
939
|
+
: []),
|
|
940
|
+
...(text ? [{ type: "text", text: safeTerminalText(text) }] : []),
|
|
941
|
+
];
|
|
942
|
+
// Pi's renderer reads only role/content. A transcript can merge events that
|
|
943
|
+
// have no single provider response, so it intentionally has no transport metadata.
|
|
944
|
+
return { role: "assistant", content };
|
|
945
|
+
}
|
|
946
|
+
function renderNativeUserMessage(text, width) {
|
|
947
|
+
return stripOsc133(new UserMessageComponent(safeTerminalText(text), getMarkdownTheme(), 1).render(width));
|
|
948
|
+
}
|
|
949
|
+
function renderNativeAssistantMessage(thinking, text, width, thinkingLabel) {
|
|
950
|
+
return stripOsc133(new AssistantMessageComponent(createPresentationAssistantMessage(thinking, text), false, getMarkdownTheme(), thinkingLabel, 1).render(width));
|
|
951
|
+
}
|
|
952
|
+
function wrapRenderedLines(lines, width, verbatimLines) {
|
|
953
|
+
const wrapped = [];
|
|
954
|
+
for (const [index, line] of lines.entries()) {
|
|
955
|
+
// Native tool components own their geometry (diffs, borders, tables);
|
|
956
|
+
// re-wrapping their output would corrupt it, same as Pi's main transcript.
|
|
957
|
+
if (verbatimLines?.has(index)) {
|
|
958
|
+
wrapped.push(line);
|
|
959
|
+
continue;
|
|
960
|
+
}
|
|
961
|
+
if (!line)
|
|
962
|
+
wrapped.push("");
|
|
963
|
+
else
|
|
964
|
+
wrapped.push(...wrapTextWithAnsi(line, Math.max(1, width)));
|
|
965
|
+
}
|
|
966
|
+
return wrapped;
|
|
967
|
+
}
|
|
968
|
+
function noticeToneColor(tone) {
|
|
969
|
+
switch (tone) {
|
|
970
|
+
case "error":
|
|
971
|
+
return "error";
|
|
972
|
+
case "warning":
|
|
973
|
+
return "warning";
|
|
974
|
+
default:
|
|
975
|
+
return "dim";
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* Builds a stateless component for tool blocks rendered without a live
|
|
980
|
+
* registry (direct API use). Rebuilt per frame; correct output, no incremental
|
|
981
|
+
* renderer state.
|
|
982
|
+
*/
|
|
983
|
+
function createAdHocToolComponent(block) {
|
|
984
|
+
const component = new ToolExecutionComponent(block.toolName, block.toolCallId, block.args ?? {}, {}, undefined,
|
|
985
|
+
// Only requestRender is ever invoked on the host TUI.
|
|
986
|
+
DETACHED_TUI, process.cwd());
|
|
987
|
+
component.setArgsComplete();
|
|
988
|
+
component.markExecutionStarted();
|
|
989
|
+
if (block.result) {
|
|
990
|
+
component.updateResult(toComponentResult(block.result, block.isError), block.streaming);
|
|
991
|
+
}
|
|
992
|
+
return component;
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* Render normalized transcript entries as terminal lines. User and assistant
|
|
996
|
+
* messages deliberately use Pi's native components so markdown, code,
|
|
997
|
+
* thinking, and message theming stay consistent with the main transcript.
|
|
998
|
+
* Tool calls are rendered by Pi's native `ToolExecutionComponent`, giving
|
|
999
|
+
* built-in tools their familiar rich output (diffs, file previews, images).
|
|
1000
|
+
*/
|
|
1001
|
+
export function renderTranscriptLines(entries, options) {
|
|
1002
|
+
const width = Math.max(1, options.width);
|
|
1003
|
+
const { theme } = options;
|
|
1004
|
+
if (entries.length === 0)
|
|
1005
|
+
return [theme.fg("dim", options.emptyText ?? "No transcript yet.")];
|
|
1006
|
+
const lines = [];
|
|
1007
|
+
const verbatimLines = new Set();
|
|
1008
|
+
const pushVerbatim = (rendered) => {
|
|
1009
|
+
for (const line of rendered) {
|
|
1010
|
+
verbatimLines.add(lines.length);
|
|
1011
|
+
lines.push(line);
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
const assistantBadge = theme.bg(options.assistantBadgeBackground ?? "customMessageBg", theme.fg(options.assistantBadgeForeground ?? "success", theme.bold(` ${options.assistantLabel ?? "Assistant"} `)));
|
|
1015
|
+
const separator = theme.fg("borderMuted", "────────────────────────────────────────");
|
|
1016
|
+
const blankBefore = () => {
|
|
1017
|
+
if (lines.length > 0 && lines.at(-1) !== "")
|
|
1018
|
+
lines.push("");
|
|
1019
|
+
};
|
|
1020
|
+
for (const block of buildRenderBlocks(entries)) {
|
|
1021
|
+
switch (block.kind) {
|
|
1022
|
+
case "separator":
|
|
1023
|
+
blankBefore();
|
|
1024
|
+
lines.push(separator);
|
|
1025
|
+
break;
|
|
1026
|
+
case "user":
|
|
1027
|
+
lines.push(...renderNativeUserMessage(block.text, width));
|
|
1028
|
+
break;
|
|
1029
|
+
case "assistant":
|
|
1030
|
+
blankBefore();
|
|
1031
|
+
lines.push(assistantBadge);
|
|
1032
|
+
lines.push(...renderNativeAssistantMessage(block.thinking, block.text, width, options.thinkingLabel ?? "Thinking"));
|
|
1033
|
+
break;
|
|
1034
|
+
case "tool-native": {
|
|
1035
|
+
blankBefore();
|
|
1036
|
+
const component = options.toolComponents?.get(block.toolCallId) ??
|
|
1037
|
+
createAdHocToolComponent(block);
|
|
1038
|
+
pushVerbatim(component.render(width));
|
|
1039
|
+
break;
|
|
1040
|
+
}
|
|
1041
|
+
case "notice": {
|
|
1042
|
+
blankBefore();
|
|
1043
|
+
const color = noticeToneColor(block.tone);
|
|
1044
|
+
for (const noticeLine of safeTerminalText(block.text).split("\n"))
|
|
1045
|
+
lines.push(theme.fg(color, noticeLine));
|
|
1046
|
+
break;
|
|
1047
|
+
}
|
|
1048
|
+
default:
|
|
1049
|
+
break;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
// wrapRenderedLines preserves length for verbatim lines, so indices stay
|
|
1053
|
+
// aligned for the width-truncation pass below.
|
|
1054
|
+
const wrapped = wrapRenderedLines(lines, width, verbatimLines);
|
|
1055
|
+
return wrapped.map((line, index) => verbatimLines.has(index) || visibleWidth(line) <= width
|
|
1056
|
+
? line
|
|
1057
|
+
: truncateToWidth(line, width, ""));
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Decodes an SGR mouse-wheel event into a transcript line delta.
|
|
1061
|
+
* Hosts remain responsible for enabling terminal mouse reporting when their
|
|
1062
|
+
* TUI mode does not already provide it.
|
|
1063
|
+
*/
|
|
1064
|
+
export function getTranscriptMouseScrollDelta(data) {
|
|
1065
|
+
const match = data.match(/^\x1b\[<(\d+);\d+;\d+[Mm]$/);
|
|
1066
|
+
if (!match)
|
|
1067
|
+
return null;
|
|
1068
|
+
const button = Number(match[1]);
|
|
1069
|
+
if ((button & 64) !== 64)
|
|
1070
|
+
return null;
|
|
1071
|
+
return (button & 1) === 0 ? -3 : 3;
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Stateful scrolling viewport for a transcript. It owns no dialog chrome, so
|
|
1075
|
+
* extensions can compose it into their own overlay layout and controls.
|
|
1076
|
+
*/
|
|
1077
|
+
export class TranscriptViewport {
|
|
1078
|
+
tui;
|
|
1079
|
+
readEntries;
|
|
1080
|
+
renderOptions;
|
|
1081
|
+
scrollOffset = 0;
|
|
1082
|
+
viewportHeight = 8;
|
|
1083
|
+
totalLines = 0;
|
|
1084
|
+
follow = true;
|
|
1085
|
+
constructor(options) {
|
|
1086
|
+
this.tui = options.tui;
|
|
1087
|
+
this.readEntries = options.readEntries;
|
|
1088
|
+
const { tui: _tui, readEntries: _readEntries, ...renderOptions } = options;
|
|
1089
|
+
this.renderOptions = renderOptions;
|
|
1090
|
+
}
|
|
1091
|
+
get following() {
|
|
1092
|
+
return this.follow;
|
|
1093
|
+
}
|
|
1094
|
+
refresh() {
|
|
1095
|
+
this.tui.requestRender();
|
|
1096
|
+
}
|
|
1097
|
+
scroll(delta) {
|
|
1098
|
+
if (delta < 0)
|
|
1099
|
+
this.follow = false;
|
|
1100
|
+
const maxScroll = Math.max(0, this.totalLines - this.viewportHeight);
|
|
1101
|
+
this.scrollOffset = Math.max(0, Math.min(maxScroll, this.scrollOffset + delta));
|
|
1102
|
+
if (this.scrollOffset >= maxScroll)
|
|
1103
|
+
this.follow = true;
|
|
1104
|
+
this.tui.requestRender();
|
|
1105
|
+
}
|
|
1106
|
+
followLatest() {
|
|
1107
|
+
this.follow = true;
|
|
1108
|
+
this.scrollOffset = Math.max(0, this.totalLines - this.viewportHeight);
|
|
1109
|
+
this.tui.requestRender();
|
|
1110
|
+
}
|
|
1111
|
+
handleInput(data) {
|
|
1112
|
+
const mouseScrollDelta = getTranscriptMouseScrollDelta(data);
|
|
1113
|
+
if (mouseScrollDelta !== null) {
|
|
1114
|
+
this.scroll(mouseScrollDelta);
|
|
1115
|
+
return true;
|
|
1116
|
+
}
|
|
1117
|
+
if (matchesKey(data, "up") || matchesKey(data, "k")) {
|
|
1118
|
+
this.scroll(-1);
|
|
1119
|
+
return true;
|
|
1120
|
+
}
|
|
1121
|
+
if (matchesKey(data, "down") || matchesKey(data, "j")) {
|
|
1122
|
+
this.scroll(1);
|
|
1123
|
+
return true;
|
|
1124
|
+
}
|
|
1125
|
+
if (matchesKey(data, "pageUp")) {
|
|
1126
|
+
this.scroll(-Math.max(1, this.viewportHeight - 1));
|
|
1127
|
+
return true;
|
|
1128
|
+
}
|
|
1129
|
+
if (matchesKey(data, "pageDown")) {
|
|
1130
|
+
this.scroll(Math.max(1, this.viewportHeight - 1));
|
|
1131
|
+
return true;
|
|
1132
|
+
}
|
|
1133
|
+
if (matchesKey(data, "home")) {
|
|
1134
|
+
this.follow = false;
|
|
1135
|
+
this.scrollOffset = 0;
|
|
1136
|
+
this.tui.requestRender();
|
|
1137
|
+
return true;
|
|
1138
|
+
}
|
|
1139
|
+
if (matchesKey(data, "end")) {
|
|
1140
|
+
this.followLatest();
|
|
1141
|
+
return true;
|
|
1142
|
+
}
|
|
1143
|
+
return false;
|
|
1144
|
+
}
|
|
1145
|
+
render(width, height) {
|
|
1146
|
+
const lines = renderTranscriptLines(this.readEntries(), {
|
|
1147
|
+
...this.renderOptions,
|
|
1148
|
+
width,
|
|
1149
|
+
});
|
|
1150
|
+
this.viewportHeight = Math.max(1, height);
|
|
1151
|
+
this.totalLines = lines.length;
|
|
1152
|
+
const maxScroll = Math.max(0, lines.length - this.viewportHeight);
|
|
1153
|
+
if (this.follow)
|
|
1154
|
+
this.scrollOffset = maxScroll;
|
|
1155
|
+
else {
|
|
1156
|
+
this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxScroll));
|
|
1157
|
+
if (this.scrollOffset >= maxScroll)
|
|
1158
|
+
this.follow = true;
|
|
1159
|
+
}
|
|
1160
|
+
const visible = lines.slice(this.scrollOffset, this.scrollOffset + this.viewportHeight);
|
|
1161
|
+
return {
|
|
1162
|
+
lines: visible,
|
|
1163
|
+
hiddenAbove: this.scrollOffset,
|
|
1164
|
+
hiddenBelow: Math.max(0, maxScroll - this.scrollOffset),
|
|
1165
|
+
totalLines: lines.length,
|
|
1166
|
+
following: this.follow,
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
}
|