@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 CHANGED
@@ -1,6 +1,41 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.7.0] - 2026-08-24
4
+
5
+ ### Added
6
+
7
+ - **Fleet inspector native transcript rendering.** `/subagents-fleet` now
8
+ renders structured session transcripts through `@xzzpig/pi-components`
9
+ native components (tool calls via `ToolExecutionComponent`, messages via the
10
+ native message components). A new adapter (`src/tui/fleet-native-transcript.ts`)
11
+ converts persisted child-transcript JSONL records into library entries,
12
+ fills the tool-component registry per cache generation, synthesizes results
13
+ for calls without a result record, and degrades truncated (>32KB) argument
14
+ payloads to renderable entries with a truncation preview + result notice.
15
+ - **`v` key toggles the renderer.** Switches the inspector between the native
16
+ transcript and the legacy rail renderer (rebindable via
17
+ `FLEET_KEYBINDING_ACTIONS`; session-scoped state; inactive in Prompt Audit
18
+ mode). When the native module is missing or fails to load, the legacy
19
+ renderer is used automatically.
20
+
21
+ ### Changed
22
+
23
+ - `@xzzpig/pi-components@0.3.0` is bundled via `bundledDependencies` (private,
24
+ never published to npm); `prepack` rebuilds it so the bundle always carries
25
+ fresh `dist`.
26
+ - Tool-call theming follows the host's global theme: the shared library never
27
+ re-initializes an already-active theme (fixes dark-theme tool backgrounds in
28
+ the main session after opening the inspector).
29
+
30
+ ### Fixed
31
+
32
+ - Truncated or corrupt `argsPayload` records no longer produce empty tool
33
+ entries; they degrade with the recorded preview and outcome visible.
34
+
35
+ ## [0.6.0] - 2026-08-23
36
+
37
+ ### Added
38
+ - Context injection: agents that opt in with `injectToContext: true` frontmatter, plus names listed under the new `subagents.injectAgents` setting, are pre-declared to the parent agent in a compact `<available_subagents>` system-prompt block. The union resolves once per session (canonical names or aliases; builtins allowed), stays byte-identical across turns to preserve provider prompt caching, skips disabled and capability-ceiling-restricted agents and spawned child sessions, ignores unknown setting names (reported by `/subagents-doctor`), and never duplicates itself on forked or resumed sessions.
4
39
 
5
40
  ## [0.5.0] - 2026-08-22
6
41
 
package/README.md CHANGED
@@ -50,6 +50,10 @@ Installing the extension does not start an automatic reviewer in the background.
50
50
  When you finish implementing, run a reviewer subagent before summarizing.
51
51
  ```
52
52
 
53
+ ### Pre-declaring agents in context (context injection)
54
+
55
+ By default Pi discovers agents by calling `subagent({ action: "list" })`. You can pre-declare selected agents in the parent system prompt so routing happens without that round trip: set `injectToContext: true` in an agent's frontmatter, or list names under `subagents.injectAgents` in settings. The union is injected once per session as a compact block — byte-stable across turns, so prompt caching stays effective. Disabled and capability-restricted agents are never advertised; unknown setting names are ignored and reported by `/subagents-doctor`. See [docs/agents.md](docs/agents.md#context-injection).
56
+
53
57
  ## Builtin agents
54
58
 
55
59
  The extension ships with agents you can use immediately:
package/docs/agents.md CHANGED
@@ -178,6 +178,7 @@ acceptanceRole: read-only
178
178
  completionGuard: false
179
179
  interactive: true
180
180
  maxSubagentDepth: 1
181
+ injectToContext: true
181
182
  ---
182
183
 
183
184
  Your system prompt goes here.
@@ -224,8 +225,46 @@ Field notes:
224
225
  | `completionGuard` | Set `false` only for non-implementation agents that may mention implementation words while using mutation-capable tools such as `bash`. |
225
226
  | `interactive` | Parsed for compatibility but not currently enforced. |
226
227
  | `maxSubagentDepth` | Tightens nested delegation for this agent's children. |
228
+ | `injectToContext` | Advertise this agent in the parent system prompt at session start so the main agent can select it without calling `{ action: "list" }` first. See [Context injection](#context-injection). |
227
229
  | `memory` | Opt-in role-specific persistent memory. See below. |
228
230
 
231
+ ## Context injection
232
+
233
+ By default the parent agent learns which agents exist only by calling `subagent({ action: "list" })`. Context injection pre-declares selected agents in the parent system prompt through a compact `<available_subagents>` block, so routing decisions can happen without a discovery round trip.
234
+
235
+ Two sources contribute, and the union is advertised:
236
+
237
+ 1. Agent files that opt in with `injectToContext: true` in their frontmatter.
238
+ 2. The `subagents.injectAgents` setting, which lists agent names (canonical names or aliases; builtins allowed):
239
+
240
+ ```json
241
+ {
242
+ "subagents": {
243
+ "injectAgents": ["worker", "reviewer", "security-reviewer"]
244
+ }
245
+ }
246
+ ```
247
+
248
+ Rendered block shape:
249
+
250
+ ```text
251
+ <available_subagents>
252
+ The following pre-declared subagents are available.
253
+ Launch them with the subagent tool when a task matches their description.
254
+
255
+ - security-reviewer: Security review specialist
256
+ - worker: Implementation work, including approved oracle handoffs.
257
+ </available_subagents>
258
+ ```
259
+
260
+ Semantics and guarantees:
261
+
262
+ - **Snapshot per session.** The list resolves once at session start (and on reload) and stays byte-identical for every turn, so provider prompt caching is never invalidated mid-session. Edits to agent files or settings take effect in a new session, not the current one; `{ action: "list" }` remains the runtime source of truth.
263
+ - **Only executable agents are advertised.** Disabled agents and agents restricted by the session capability ceiling are never injected.
264
+ - **Children never see it.** Spawned child sessions do not load the parent injection; fanout children can still call `{ action: "list" }`.
265
+ - **Unknown setting names are ignored** and reported by `/subagents-doctor` instead of failing startup.
266
+ - The block is appended only when it is not already present, so forked or resumed sessions never duplicate it.
267
+
229
268
  ## Per-agent persistent memory
230
269
 
231
270
  A recurring custom agent can opt into a durable, role-specific memory scope with the `memory` frontmatter field:
@@ -2,7 +2,7 @@
2
2
 
3
3
  `pi-subagents` reads optional JSON config from `~/.pi/agent/extensions/subagent/config.json`. This page lists every key, plus the environment variables and the settings-file keys that affect config resolution.
4
4
 
5
- Settings-level keys (`subagents.defaultModel`, `defaultThinking`, `defaultExtensions`, `agentOverrides`, `modelScope`, `disableThinking`, `disableBuiltins`, watchdog settings) live in Pi settings files, not this config file. See [models.md](models.md), [agents.md](agents.md), and [watchdog.md](watchdog.md).
5
+ Settings-level keys (`subagents.defaultModel`, `defaultThinking`, `defaultExtensions`, `agentOverrides`, `modelScope`, `disableThinking`, `disableBuiltins`, `injectAgents`, watchdog settings) live in Pi settings files, not this config file. See [models.md](models.md), [agents.md](agents.md), and [watchdog.md](watchdog.md).
6
6
 
7
7
  ## Project root resolution (settings)
8
8
 
@@ -0,0 +1,102 @@
1
+ # Changelog
2
+
3
+ All notable changes to the internal `@xzzpig/pi-components` shared library are
4
+ documented here.
5
+
6
+ ## 0.3.0
7
+
8
+ ### Added
9
+
10
+ - **Public builder API for historical-record ingestion.** The entry-state
11
+ operations previously private to the module are now exported so hosts can
12
+ construct transcripts from persisted records instead of live agent events:
13
+ `appendEntry`, `ensureTurn`, `finishTurn`, `findLatestEntry`,
14
+ `ensureToolCall`, `upsertText`, `upsertToolResult`, and `appendNotice`.
15
+ Signatures match the internal implementations; existing exports are
16
+ unchanged.
17
+ - `ensureToolCall` backfills arguments onto a placeholder call entry when a
18
+ tool result was recorded before its start event (result-before-call replay).
19
+ - New `maxToolArgsChars` option (`SessionTranscriptOptions`) caps per-call
20
+ argument size. Oversized or non-serializable arguments degrade to a stored
21
+ `TruncatedToolArgs` marker (`{ truncated: true, preview, ... }`) instead of
22
+ throwing, keeping ingestion total and rendering bounded.
23
+
24
+ ### Fixed
25
+
26
+ - **`ensureTranscriptTheme` never clobbers a live host theme.** The previous
27
+ implementation called `initTheme()` unconditionally on first use, which
28
+ re-resolves the default theme from environment detection and can silently
29
+ replace the user's chosen theme with the dark fallback — changing tool-call
30
+ background colors in the main session after opening an embedded transcript
31
+ view (e.g. `/subagents-fleet`). It now probes the SDK's shared
32
+ `globalThis` theme symbol (`@earendil-works/pi-coding-agent:theme`, plus the
33
+ legacy `@mariozechner/...` spelling) and is a strict no-op when the host has
34
+ already initialized the theme; `initTheme()` is only called when nothing is
35
+ active (headless embeds, unit tests).
36
+
37
+ ## 0.2.0
38
+
39
+ ### Breaking
40
+
41
+ - **Tool calls render through Pi's native `ToolExecutionComponent`.** The
42
+ hand-drawn badge/result renderer (`formatToolPreview`,
43
+ `summarizeToolResult`, tool badges, `↳ result` labels, and the
44
+ `maxToolResultChars` cap) is removed. `tool-call` entries now store raw
45
+ provider `args`, and `tool-result` entries store structured
46
+ `TranscriptToolResultPayload` data verbatim so built-in tools keep their
47
+ rich main-transcript output (diffs, file previews, images).
48
+ - `SessionTranscriptOptions` extends `NativeToolRenderOptions` (`tui`, `cwd`,
49
+ `resolveToolDefinition`, `showImages`, `imageWidthCells`, `expanded`) and no
50
+ longer accepts `maxToolResultChars`.
51
+ - `renderTranscriptLines` options replace `toolLabel` / `toolBadgeBackground`
52
+ / `toolBadgeForeground` with `toolComponents` (a `ToolComponentLookup`); a
53
+ persistent component registry is available via `TranscriptToolComponents`
54
+ and `SessionTranscript.toolComponents`. Tool rows bypass line wrapping and
55
+ width truncation because components own their geometry.
56
+ - `snapshot()` deep-copies structured tool `args`/`result` data.
57
+
58
+ ### Changed
59
+
60
+ - Tool result entries whose call entry was trimmed away are dropped together
61
+ with their component instances; `trimTranscriptState`,
62
+ `removeCurrentTurn()`, and `clear()` prune the registry in lockstep with the
63
+ entry list.
64
+ - `TranscriptToolComponents` requests a TUI repaint after every tool event
65
+ (matching Pi's interactive mode) and routes component repaint signals
66
+ through a forwarder, so `attachTui()` can wire — or replace — the host TUI
67
+ at any time, even after instances exist. This keeps streaming tool output
68
+ (e.g. bash's per-second invalidate interval) visible while a command runs.
69
+ - **Runtime entry ships TypeScript source again** (`exports["./transcript"]`
70
+ now resolves to `src/transcript.ts`; types still resolve to the compiled
71
+ `dist/src/transcript.d.ts`, so consumer typechecks are unchanged). Pi loads
72
+ extension code through jiti, whose core-package alias map only applies to
73
+ files jiti transforms itself; a precompiled `.js` entry was delegated to
74
+ native import and resolved `@earendil-works/pi-coding-agent` by physical
75
+ location, splitting into a second module instance in local-development
76
+ layouts (repo workspace + npm-installed plugins). With a `.ts` entry the
77
+ component library shares the host's core-package instances in every layout,
78
+ so prototype patches from other plugins (e.g. pi-starline's user-message
79
+ rail) apply to overlay transcripts again. This supersedes the 0.1.1
80
+ bundle-safe rationale: consumers run exclusively inside Pi's jiti loader,
81
+ which executes TypeScript directly. The unused legacy `"."` export
82
+ (`dist/index.js`) was removed and `files` now includes `src`.
83
+
84
+ ## 0.1.1
85
+
86
+ ### Fixed
87
+
88
+ - **Bundle-safe runtime artifacts.** Consumer Pi packages now bundle compiled
89
+ JavaScript and declarations rather than relying on Node to execute TypeScript
90
+ from `node_modules`.
91
+
92
+ ### Changed
93
+
94
+ - **Internal distribution.** This package is intentionally private and is
95
+ bundled into consumer package tarballs instead of being published separately.
96
+
97
+ ## 0.1.0
98
+
99
+ ### Added
100
+
101
+ - Bounded session transcript state, native Pi message rendering, terminal-safe
102
+ tool output, and a scrollable transcript viewport for Pi extensions.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xzzpig
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,59 @@
1
+ # pi-components
2
+
3
+ Reusable, internal Pi TUI primitives for extension authors. This is a shared
4
+ library package, not a Pi extension: consumer packages bundle it into their
5
+ release tarballs instead of publishing it independently. Bundled artifacts
6
+ expose compiled runtime JavaScript and declarations from `dist/`; the
7
+ TypeScript source remains in this repository for development.
8
+
9
+ ## Transcript components
10
+
11
+ `@xzzpig/pi-components/transcript` provides a bounded `SessionTranscript`
12
+ that consumes `AgentSessionEvent` values and a keyboard- and wheel-scrollable
13
+ `TranscriptViewport`. User messages, assistant text, thinking, markdown, and
14
+ code fences render through Pi's native `UserMessageComponent`,
15
+ `AssistantMessageComponent`, and `getMarkdownTheme()`; tool calls render
16
+ through Pi's native `ToolExecutionComponent` (raw `args` and structured
17
+ results are preserved verbatim so built-in tools keep their rich
18
+ main-transcript output), so embedded transcripts match the main session
19
+ instead of approximating its styling.
20
+
21
+ ```ts
22
+ import {
23
+ SessionTranscript,
24
+ TranscriptViewport,
25
+ } from "@xzzpig/pi-components/transcript";
26
+
27
+ const transcript = new SessionTranscript({
28
+ maxEntries: 500,
29
+ maxChars: 512 * 1024,
30
+ // Optional native tool context: tui, cwd, resolveToolDefinition,
31
+ // showImages, imageWidthCells, expanded.
32
+ });
33
+ const unsubscribe = session.subscribe((event) => transcript.apply(event));
34
+
35
+ const viewport = new TranscriptViewport({
36
+ tui,
37
+ theme,
38
+ readEntries: () => transcript.entries,
39
+ assistantLabel: "Auditor",
40
+ thinkingLabel: "Thinking",
41
+ // Live component registry keeps incremental renderer state per tool call;
42
+ // omit it and tool blocks still render via stateless ad-hoc components.
43
+ toolComponents: transcript.toolComponents,
44
+ });
45
+
46
+ const visible = viewport.render(width, height);
47
+ ```
48
+
49
+ `TranscriptViewport` owns follow-latest plus keyboard and SGR mouse-wheel
50
+ scrolling. Hosts keep ownership of terminal mouse-reporting setup, dialog
51
+ chrome, focus behavior, input controls, session lifecycle, and cancellation
52
+ policy. `Esc` handling is intentionally delegated to the host overlay.
53
+
54
+ The transcript normalizes user/assistant events, streaming thinking and text,
55
+ tool calls and results, and automatic retry notices. It bounds retained history
56
+ (entries and total chars — raw tool data is uncapped by design) and sanitizes
57
+ untrusted terminal control sequences in message text before rendering. Pi core
58
+ packages are peer dependencies, so installed extensions use the same Pi runtime
59
+ and active theme as their host.
@@ -0,0 +1 @@
1
+ export * from "./src/transcript.js";
@@ -0,0 +1 @@
1
+ export * from "./src/transcript.js";
@@ -0,0 +1,345 @@
1
+ import { ToolExecutionComponent } from "@earendil-works/pi-coding-agent";
2
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ /**
4
+ * Structural subset of Pi's theme used by transcript rendering.
5
+ * Pi theme-key unions vary across supported SDK versions, while the public
6
+ * transcript API only passes named string keys.
7
+ */
8
+ export interface TranscriptTheme {
9
+ fg(color: string, text: string): string;
10
+ bg(color: string, text: string): string;
11
+ bold(text: string): string;
12
+ }
13
+ /** Structural subset of Pi's TUI used by the scroll viewport. */
14
+ export interface TranscriptTui {
15
+ requestRender(): void;
16
+ }
17
+ /**
18
+ * Structured tool result payload as delivered by agent session events. It is
19
+ * stored verbatim so Pi's native tool renderers receive the same shape the
20
+ * main transcript would.
21
+ */
22
+ export interface TranscriptToolResultPayload {
23
+ content?: Array<{
24
+ type?: string;
25
+ text?: string;
26
+ data?: string;
27
+ mimeType?: string;
28
+ }>;
29
+ details?: unknown;
30
+ }
31
+ /**
32
+ * Host context used to construct Pi's native `ToolExecutionComponent`
33
+ * instances. Every field is optional: missing values fall back to a detached
34
+ * stub TUI and `process.cwd()`.
35
+ */
36
+ export interface NativeToolRenderOptions {
37
+ /** Structural TUI subset; only `requestRender` is required. */
38
+ tui?: TranscriptTui;
39
+ /** Working directory used to resolve built-in tool definitions. */
40
+ cwd?: string;
41
+ /** Resolver for extension-registered custom tool definitions. */
42
+ resolveToolDefinition?: (toolName: string) => ToolDefinition | undefined;
43
+ /** Pass-through for Pi's image rendering settings. */
44
+ showImages?: boolean;
45
+ imageWidthCells?: number;
46
+ /** Initial expanded state for tool output. */
47
+ expanded?: boolean;
48
+ }
49
+ /** Structural lookup accepted by render functions; maps satisfy this. */
50
+ export interface ToolComponentLookup {
51
+ get(toolCallId: string): ToolExecutionComponent | undefined;
52
+ }
53
+ type Theme = TranscriptTheme;
54
+ type ThemeColor = string;
55
+ type ThemeBackground = string;
56
+ export type TranscriptNoticeTone = "info" | "warning" | "error";
57
+ export type TranscriptEntry = {
58
+ id: number;
59
+ turnId: number;
60
+ type: "turn-boundary";
61
+ phase: "start" | "end";
62
+ } | {
63
+ id: number;
64
+ turnId: number;
65
+ type: "user-message";
66
+ text: string;
67
+ } | {
68
+ id: number;
69
+ turnId: number;
70
+ type: "thinking";
71
+ text: string;
72
+ streaming: boolean;
73
+ } | {
74
+ id: number;
75
+ turnId: number;
76
+ type: "assistant-text";
77
+ text: string;
78
+ streaming: boolean;
79
+ } | {
80
+ id: number;
81
+ turnId: number;
82
+ type: "tool-call";
83
+ toolCallId: string;
84
+ toolName: string;
85
+ /** Raw provider arguments object, preserved for native renderers. */
86
+ args: unknown;
87
+ } | {
88
+ id: number;
89
+ turnId: number;
90
+ type: "tool-result";
91
+ toolCallId: string;
92
+ toolName: string;
93
+ /** Raw structured result; `null` until the first result arrives. */
94
+ result: TranscriptToolResultPayload | null;
95
+ isError: boolean;
96
+ streaming: boolean;
97
+ } | {
98
+ id: number;
99
+ turnId: number;
100
+ type: "notice";
101
+ text: string;
102
+ tone: TranscriptNoticeTone;
103
+ };
104
+ interface ActiveAssistantSegment {
105
+ turnId: number;
106
+ thinkingEntryId?: number;
107
+ textEntryId?: number;
108
+ }
109
+ export interface TranscriptState {
110
+ entries: TranscriptEntry[];
111
+ nextEntryId: number;
112
+ nextTurnId: number;
113
+ currentTurnId: number | null;
114
+ lastTurnId: number | null;
115
+ activeAssistant: ActiveAssistantSegment | null;
116
+ toolCalls: Map<string, {
117
+ turnId: number;
118
+ callEntryId: number;
119
+ resultEntryId?: number;
120
+ }>;
121
+ /** Persistent native tool components keyed by tool call id. */
122
+ toolComponents: TranscriptToolComponents;
123
+ /** Argument char cap applied to every recorded tool call. */
124
+ toolArgsCharLimit: number;
125
+ }
126
+ export interface SessionTranscriptOptions extends NativeToolRenderOptions {
127
+ /** Maximum retained entries. Oldest entries are discarded first. */
128
+ maxEntries?: number;
129
+ /** Maximum retained text across all entries. */
130
+ maxChars?: number;
131
+ /**
132
+ * Per-tool-call argument size cap in JSON characters. Oversized arguments
133
+ * are replaced by a truncated marker object so pathological payloads cannot
134
+ * break rendering or memory bounds. Defaults to 64 KiB.
135
+ */
136
+ maxToolArgsChars?: number;
137
+ }
138
+ /**
139
+ * Ensures Pi's global theme is initialized so native message/tool components
140
+ * can render outside a live interactive session (headless embeds, unit tests).
141
+ *
142
+ * IMPORTANT: when the host has already initialized the theme (interactive Pi
143
+ * installs the user's chosen theme before any transcript renders), this is a
144
+ * strict no-op. Re-calling `initTheme()` would re-resolve the default theme
145
+ * from environment detection and can silently replace the user's selection
146
+ * with the dark fallback — changing tool-call colors in the main session too.
147
+ */
148
+ export declare function ensureTranscriptTheme(): void;
149
+ /**
150
+ * Owns the persistent `ToolExecutionComponent` instance for every live tool
151
+ * call, mirroring how Pi's interactive mode keeps pending components keyed by
152
+ * `toolCallId`. Instances are updated incrementally as events arrive and are
153
+ * pruned by the host once their transcript entries disappear.
154
+ */
155
+ export declare class TranscriptToolComponents implements ToolComponentLookup {
156
+ private readonly components;
157
+ private readonly options;
158
+ private attachedTui;
159
+ /**
160
+ * Components capture their TUI at construction. This forwarder lets a host
161
+ * attach (or replace) the real TUI at any time — including after tool
162
+ * events already created instances — without rebuilding them.
163
+ */
164
+ private readonly forwardedTui;
165
+ constructor(options?: NativeToolRenderOptions);
166
+ /** Wires (or replaces) the host TUI that receives repaint requests. */
167
+ attachTui(tui: TranscriptTui): void;
168
+ get size(): number;
169
+ has(toolCallId: string): boolean;
170
+ get(toolCallId: string): ToolExecutionComponent | undefined;
171
+ handleStart(toolCallId: string, toolName: string, args: unknown): void;
172
+ handleUpdate(toolCallId: string, toolName: string, partialResult: unknown): void;
173
+ handleEnd(toolCallId: string, toolName: string, result: unknown, isError: boolean): void;
174
+ /** Drops instances whose transcript entries no longer exist. */
175
+ retainOnly(aliveToolCallIds: ReadonlySet<string>): void;
176
+ clear(): void;
177
+ private ensure;
178
+ private requestRender;
179
+ private readonly createdWithoutArgs;
180
+ }
181
+ export declare function createTranscriptState(nativeTools?: NativeToolRenderOptions & SessionTranscriptOptions): TranscriptState;
182
+ /** Escapes terminal control sequences in model and tool output before rendering. */
183
+ export declare function safeTerminalText(value: string): string;
184
+ /**
185
+ * Appends a fully-formed entry, assigning the next sequential id.
186
+ *
187
+ * Public building block for hosts that construct transcripts from historical
188
+ * records instead of live agent events. The entry must be structurally valid
189
+ * for its `type`; ids and array placement are owned by this function.
190
+ */
191
+ export declare function appendEntry(state: TranscriptState, entry: Omit<TranscriptEntry, "id"> & Record<string, unknown>): TranscriptEntry;
192
+ /**
193
+ * Returns the active turn id, opening a new turn (with a start boundary)
194
+ * when none is open. Public building block for historical-record ingestion.
195
+ */
196
+ export declare function ensureTurn(state: TranscriptState): number;
197
+ /**
198
+ * Finds the most recent entry of `type` inside `turnId`, scanning backwards.
199
+ * Public building block used by upsert-style helpers and hosts that merge
200
+ * repeated records (e.g. streamed message updates persisted as several lines).
201
+ */
202
+ export declare function findLatestEntry<TType extends TranscriptEntry["type"]>(state: TranscriptState, turnId: number, type: TType): Extract<TranscriptEntry, {
203
+ type: TType;
204
+ }> | undefined;
205
+ /**
206
+ * Closes `turnId` (defaulting to the current turn): appends the end boundary
207
+ * unless one already exists, clears streaming flags on the turn's entries,
208
+ * and updates bookkeeping. Idempotent — finishing an already-finished turn is
209
+ * a no-op for boundary creation. Public building block for hosts that know
210
+ * when a replayed exchange is complete.
211
+ */
212
+ export declare function finishTurn(state: TranscriptState, turnId?: number | null): void;
213
+ export declare function removeTranscriptTurn(state: TranscriptState, turnId: number | null): void;
214
+ /**
215
+ * Degraded stand-in stored on a tool-call entry when the original arguments
216
+ * exceed the state's char limit or cannot be serialized. Consumers can narrow
217
+ * with the `truncated` flag; rendering falls back to the preview text.
218
+ */
219
+ export interface TruncatedToolArgs {
220
+ truncated: true;
221
+ /** Present only when JSON serialization of the original payload failed. */
222
+ reason?: "unserializable";
223
+ /** Serialized length of the original payload, when it was serializable. */
224
+ originalChars?: number;
225
+ preview: string;
226
+ }
227
+ /**
228
+ * Finds or creates the tool-call record for `toolCallId`, appending a
229
+ * tool-call entry when none exists yet.
230
+ *
231
+ * Public building block for hosts that ingest historical records where calls
232
+ * and results may arrive in either order: when the result was recorded first,
233
+ * the placeholder entry's arguments are backfilled here from the later call
234
+ * record. Arguments exceeding the state's char limit are stored as a
235
+ * truncated marker object instead of failing.
236
+ */
237
+ export declare function ensureToolCall(state: TranscriptState, turnId: number, toolCallId: string, toolName: string, args: unknown): {
238
+ turnId: number;
239
+ callEntryId: number;
240
+ resultEntryId?: number;
241
+ };
242
+ /**
243
+ * Inserts or updates the thinking/assistant-text entry for `turnId`.
244
+ * Repeated records for the same turn merge into one entry (latest text wins).
245
+ * Public building block for hosts that replay completed message records.
246
+ */
247
+ export declare function upsertText(state: TranscriptState, turnId: number, type: "thinking" | "assistant-text", text: string, streaming: boolean): void;
248
+ /**
249
+ * Inserts or updates the structured result of a tool call, creating the call
250
+ * placeholder first when the result arrives before its start event. Safe to
251
+ * call repeatedly — the latest result wins and streaming flags update in place.
252
+ * Public building block for hosts that ingest persisted tool results.
253
+ */
254
+ export declare function upsertToolResult(state: TranscriptState, turnId: number, toolCallId: string, toolName: string, result: TranscriptToolResultPayload | null, isError: boolean, streaming: boolean): void;
255
+ /**
256
+ * Appends a notice attached to the current turn (or the most recent one).
257
+ * Text is sanitized before storage. Public building block for hosts that
258
+ * surface stderr output, retry banners, or other non-conversation events.
259
+ */
260
+ export declare function appendNotice(state: TranscriptState, text: string, tone: TranscriptNoticeTone): void;
261
+ export declare function trimTranscriptState(state: TranscriptState, options?: SessionTranscriptOptions): void;
262
+ export declare function applyAgentSessionEvent(state: TranscriptState, input: unknown, options?: SessionTranscriptOptions): void;
263
+ export declare class SessionTranscript {
264
+ private readonly state;
265
+ private readonly options;
266
+ constructor(options?: SessionTranscriptOptions);
267
+ get entries(): readonly TranscriptEntry[];
268
+ /** Live native tool components keyed by tool call id. */
269
+ get toolComponents(): ToolComponentLookup;
270
+ snapshot(): TranscriptEntry[];
271
+ get currentTurnId(): number | null;
272
+ apply(event: unknown): void;
273
+ appendCompletedTurn(details: {
274
+ user?: string;
275
+ thinking?: string;
276
+ assistant: string;
277
+ }): void;
278
+ appendFailure(message: string): void;
279
+ appendNotice(message: string, tone?: TranscriptNoticeTone): void;
280
+ removeCurrentTurn(): void;
281
+ clear(): void;
282
+ }
283
+ export declare function hasStreamingTranscriptEntry(entries: readonly TranscriptEntry[]): boolean;
284
+ export declare function getCompletedTranscriptExchangeCount(entries: readonly TranscriptEntry[]): number;
285
+ export interface TranscriptRenderOptions {
286
+ width: number;
287
+ theme: Theme;
288
+ emptyText?: string;
289
+ assistantLabel?: string;
290
+ thinkingLabel?: string;
291
+ assistantBadgeBackground?: ThemeBackground;
292
+ assistantBadgeForeground?: ThemeColor;
293
+ /**
294
+ * Live native tool components keyed by tool call id. When omitted, tool
295
+ * blocks are rendered through stateless ad-hoc components rebuilt from the
296
+ * entry data on every frame.
297
+ */
298
+ toolComponents?: ToolComponentLookup;
299
+ }
300
+ /**
301
+ * Render normalized transcript entries as terminal lines. User and assistant
302
+ * messages deliberately use Pi's native components so markdown, code,
303
+ * thinking, and message theming stay consistent with the main transcript.
304
+ * Tool calls are rendered by Pi's native `ToolExecutionComponent`, giving
305
+ * built-in tools their familiar rich output (diffs, file previews, images).
306
+ */
307
+ export declare function renderTranscriptLines(entries: readonly TranscriptEntry[], options: TranscriptRenderOptions): string[];
308
+ export interface TranscriptViewportOptions extends Omit<TranscriptRenderOptions, "width"> {
309
+ tui: TranscriptTui;
310
+ readEntries: () => readonly TranscriptEntry[];
311
+ }
312
+ export interface TranscriptViewportRender {
313
+ lines: string[];
314
+ hiddenAbove: number;
315
+ hiddenBelow: number;
316
+ totalLines: number;
317
+ following: boolean;
318
+ }
319
+ /**
320
+ * Decodes an SGR mouse-wheel event into a transcript line delta.
321
+ * Hosts remain responsible for enabling terminal mouse reporting when their
322
+ * TUI mode does not already provide it.
323
+ */
324
+ export declare function getTranscriptMouseScrollDelta(data: string): number | null;
325
+ /**
326
+ * Stateful scrolling viewport for a transcript. It owns no dialog chrome, so
327
+ * extensions can compose it into their own overlay layout and controls.
328
+ */
329
+ export declare class TranscriptViewport {
330
+ private readonly tui;
331
+ private readonly readEntries;
332
+ private readonly renderOptions;
333
+ private scrollOffset;
334
+ private viewportHeight;
335
+ private totalLines;
336
+ private follow;
337
+ constructor(options: TranscriptViewportOptions);
338
+ get following(): boolean;
339
+ refresh(): void;
340
+ scroll(delta: number): void;
341
+ followLatest(): void;
342
+ handleInput(data: string): boolean;
343
+ render(width: number, height: number): TranscriptViewportRender;
344
+ }
345
+ export {};