@yusukeshib/pi-tail 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yusuke Shibata
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # pi-tail
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Follow a [Pi](https://github.com/earendil-works/pi) event log and render it the
4
+ way Pi renders its own chat, with the installed Pi's TUI components
5
+ (`AssistantMessageComponent`, `ToolExecutionComponent`, …).
6
+
7
+ The input is the JSONL event stream that `pi --mode rpc` or `pi --mode json`
8
+ writes to stdout. Save that stream to a file and point `pi-tail` at it, while
9
+ the agent is still running or afterwards.
10
+
11
+ ```sh
12
+ pi --mode rpc > run.jsonl # or any process that records Pi's stdout
13
+ pi-tail run.jsonl # follow live
14
+ pi-tail run.jsonl --print # render once to stdout
15
+ ```
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm install -g @yusukeshib/pi-tail
21
+ ```
22
+
23
+ Pi itself is not bundled. The Pi packages are loaded from, in order:
24
+
25
+ 1. `PI_TAIL_PI_PACKAGE_DIR` (a `@earendil-works/pi-coding-agent` package directory)
26
+ 2. the managed install (`~/.pi/agent/install/current-version`, or under `PI_CODING_AGENT_DIR`)
27
+ 3. the `pi` on `PATH`
28
+ 4. `@earendil-works/pi-coding-agent` / `@earendil-works/pi-tui` resolvable from pi-tail
29
+
30
+ So the transcript is rendered by the same Pi release that you run.
31
+
32
+ ## Usage
33
+
34
+ ```
35
+ pi-tail <file> [--print] [--cwd DIR]
36
+ ```
37
+
38
+ - Follow mode re-reads the file every 200 ms and starts over if it shrinks.
39
+ - Keys: `q` / `Ctrl-C` quit, `Ctrl-O` expand or collapse tool output, `t`
40
+ toggle thinking blocks.
41
+ - `--print` renders the current transcript once to stdout.
42
+ - `--cwd DIR` is the agent's working directory (default: the current
43
+ directory). It decides which Pi settings, themes and extensions are loaded,
44
+ and tool paths are shown relative to it.
45
+
46
+ pi-tail sets up the environment the way Pi's interactive mode does for that
47
+ directory: settings (global and, for a trusted project, project), themes from
48
+ `settings.themes` and packages, terminal colors, keybindings, and the
49
+ extensions' tool, message and Markdown renderers. Extensions are loaded but no
50
+ session starts, so their session handlers never run; missing packages are
51
+ skipped, never installed; a project that Pi has not been told to trust is
52
+ loaded without its project-local resources.
53
+
54
+ Lines that are not JSON objects and event types pi-tail does not render are
55
+ ignored, so a log may carry other records. Reading the stream from stdin is not
56
+ supported yet: the terminal UI reads keys from stdin.
57
+
58
+ ## Library
59
+
60
+ ```js
61
+ import { runViewer } from "@yusukeshib/pi-tail";
62
+
63
+ await runViewer({
64
+ file: "/path/to/run.jsonl",
65
+ cwd: "/path/to/project",
66
+ status: () => "worker · running", // shown before the key hints
67
+ });
68
+ ```
69
+
70
+ `runViewer({ print: true })` resolves to `0` after printing. In follow mode it
71
+ resolves once the UI is running, and quitting exits the process.
72
+
73
+ Lower-level pieces are exported too: `createTranscriptView` (apply events,
74
+ read `.container`), `createLogReader`, `loadPiRuntime`, `loadPiEnvironment`,
75
+ `initPiTheme`, `applyTerminalSettings`, `createViewerInputListener`.
76
+
77
+ The event-to-component mapping mirrors Pi's interactive mode but is a separate
78
+ implementation, and it uses Pi's component APIs, so a Pi release that changes
79
+ them may need a pi-tail update.
80
+
81
+ ## Development
82
+
83
+ ```sh
84
+ bun test
85
+ ```
86
+
87
+ Tests load the installed Pi (see Install).
88
+
89
+ ## License
90
+
91
+ MIT
package/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ export { USAGE, createLogReader, createViewerInputListener, main, parseArgs, runCli, runViewer } from "./pi-tail.mjs";
2
+ export { applyAssistantDelta, createTranscriptView, defaultRenderContext } from "./transcript-view.mjs";
3
+ export { applyTerminalSettings, initPiTheme, loadPiEnvironment } from "./pi-environment.mjs";
4
+ export { findPiPackageDir, loadPiRuntime } from "./pi-runtime.mjs";
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@yusukeshib/pi-tail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Follow a Pi RPC / JSON event log and render it with Pi's own TUI components.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-coding-agent",
8
+ "rpc",
9
+ "transcript",
10
+ "viewer",
11
+ "tail"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "Yusuke Shibata <yusukeshib@gmail.com>",
15
+ "homepage": "https://github.com/yusukeshib/pi-tail#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/yusukeshib/pi-tail.git"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/yusukeshib/pi-tail/issues"
22
+ },
23
+ "type": "module",
24
+ "bin": {
25
+ "pi-tail": "./pi-tail.mjs"
26
+ },
27
+ "exports": {
28
+ ".": "./index.mjs",
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "index.mjs",
33
+ "pi-tail.mjs",
34
+ "transcript-view.mjs",
35
+ "pi-runtime.mjs",
36
+ "pi-environment.mjs",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "peerDependencies": {
41
+ "@earendil-works/pi-coding-agent": ">=1.0.0",
42
+ "@earendil-works/pi-tui": ">=1.0.0"
43
+ },
44
+ "peerDependenciesMeta": {
45
+ "@earendil-works/pi-coding-agent": {
46
+ "optional": true
47
+ },
48
+ "@earendil-works/pi-tui": {
49
+ "optional": true
50
+ }
51
+ },
52
+ "engines": {
53
+ "node": ">=20"
54
+ },
55
+ "scripts": {
56
+ "test": "bun test",
57
+ "release": "npm publish --access public"
58
+ }
59
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * pi-environment.mjs — reproduce the parts of Pi's interactive startup that
3
+ * decide how a transcript looks: settings, themes (including ones registered
4
+ * through `settings.themes` and packages), terminal capability overrides,
5
+ * keybindings, and extension tool / message renderers.
6
+ *
7
+ * Extensions are loaded the way Pi loads them (DefaultResourceLoader), but no
8
+ * session is started: extension factories run, session events never fire.
9
+ * Missing packages are skipped, never installed.
10
+ */
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+
14
+ const SYSTEM_THEME_NAME = "system";
15
+
16
+ function call(target, method, ...args) {
17
+ return typeof target?.[method] === "function" ? target[method](...args) : undefined;
18
+ }
19
+
20
+ function defaultAgentDir(agent) {
21
+ return (
22
+ call(agent, "getAgentDir") ?? process.env.PI_CODING_AGENT_DIR ?? path.join(os.homedir(), ".pi", "agent")
23
+ );
24
+ }
25
+
26
+ /**
27
+ * Pi's project trust decision without prompting: a remembered decision, then
28
+ * "trusted" when the project has no trust-requiring resources, then the
29
+ * `defaultProjectTrust` setting. An undecided project stays untrusted, so the
30
+ * viewer never runs project-local extension code the user has not approved.
31
+ */
32
+ function resolveProjectTrusted({ runtime, cwd, agentDir }) {
33
+ const trust = runtime.internal?.trust;
34
+ const { SettingsManager } = runtime.agent;
35
+ try {
36
+ const remembered = trust?.ProjectTrustStore ? new trust.ProjectTrustStore(agentDir).get(cwd) : undefined;
37
+ if (remembered === true || remembered === false) return remembered;
38
+ const requiresTrust = trust?.hasTrustRequiringProjectResources?.(cwd) ?? true;
39
+ if (!requiresTrust) return true;
40
+ const global = SettingsManager.create(cwd, agentDir, { projectTrusted: false });
41
+ return call(global, "getDefaultProjectTrust") === "always";
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+
47
+ async function loadResources({ runtime, cwd, agentDir, settingsManager, diagnostics }) {
48
+ const { DefaultResourceLoader } = runtime.agent;
49
+ if (typeof DefaultResourceLoader !== "function") return undefined;
50
+ const loader = new DefaultResourceLoader({
51
+ cwd,
52
+ agentDir,
53
+ settingsManager,
54
+ extensionFactories: runtime.internal?.builtInExtensions?.builtInExtensions ?? [],
55
+ noSkills: true,
56
+ noPromptTemplates: true,
57
+ noContextFiles: true,
58
+ });
59
+ const packageManager = loader.packageManager;
60
+ if (typeof packageManager?.resolve !== "function") {
61
+ diagnostics.push("Extensions not loaded: this Pi release does not allow resolving packages without installing them");
62
+ return undefined;
63
+ }
64
+ // A viewer must not install packages; Pi's startup prompts do the same.
65
+ const resolve = packageManager.resolve.bind(packageManager);
66
+ packageManager.resolve = (onMissing) => resolve(onMissing ?? (async () => "skip"));
67
+ await loader.reload();
68
+ return loader;
69
+ }
70
+
71
+ function createRenderContext({ runtime, settingsManager, extensions }) {
72
+ const { ExtensionRunner, getMarkdownTheme } = runtime.agent;
73
+ const runner =
74
+ extensions && typeof ExtensionRunner === "function"
75
+ ? new ExtensionRunner(extensions.extensions, extensions.runtime, undefined, undefined, undefined)
76
+ : undefined;
77
+ const builtIn = (name, definition) => runtime.withBuiltInRenderers?.(name, definition) ?? definition;
78
+ const mermaid = runtime.internal?.mermaid?.createMermaidMarkdownTransformer;
79
+ const themeProxy = runtime.internal?.theme?.theme;
80
+ const mermaidTransformer =
81
+ mermaid && themeProxy && typeof settingsManager?.getMermaidRenderingMode === "function"
82
+ ? mermaid({ getMode: () => settingsManager.getMermaidRenderingMode(), theme: themeProxy })
83
+ : undefined;
84
+ return {
85
+ // Same lookup as InteractiveMode.getRegisteredToolDefinition().
86
+ getToolDefinition(name) {
87
+ const base = () => builtIn(name, runner?.getToolDefinition(name));
88
+ return runner ? runner.resolveToolRenderers(name, base) : base();
89
+ },
90
+ getMessageRenderer: (customType) => runner?.getMessageRenderer(customType),
91
+ getMarkdownTransformers: () => [
92
+ ...(mermaidTransformer ? [mermaidTransformer] : []),
93
+ ...(runner?.getMarkdownTransformers() ?? []),
94
+ ],
95
+ markdownTheme: () => {
96
+ const codeBlockIndent = call(settingsManager, "getCodeBlockIndent");
97
+ return codeBlockIndent === undefined ? getMarkdownTheme() : { ...getMarkdownTheme(), codeBlockIndent };
98
+ },
99
+ hideThinkingBlock: call(settingsManager, "getHideThinkingBlock") === true,
100
+ outputPad: call(settingsManager, "getOutputPad"),
101
+ showImages: call(settingsManager, "getShowImages") ?? false,
102
+ imageWidthCells: call(settingsManager, "getImageWidthCells"),
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Load { settingsManager, themes, render, diagnostics } for a worker running in
108
+ * `cwd`. `render` is the transcript-view render context.
109
+ */
110
+ export async function loadPiEnvironment(runtime, { cwd, agentDir = defaultAgentDir(runtime.agent) } = {}) {
111
+ const diagnostics = [];
112
+ const { SettingsManager } = runtime.agent;
113
+ let settingsManager;
114
+ let loader;
115
+ try {
116
+ settingsManager = SettingsManager.create(cwd, agentDir, {
117
+ projectTrusted: resolveProjectTrusted({ runtime, cwd, agentDir }),
118
+ });
119
+ loader = await loadResources({ runtime, cwd, agentDir, settingsManager, diagnostics });
120
+ } catch (error) {
121
+ diagnostics.push(`Pi resources not loaded: ${error instanceof Error ? error.message : String(error)}`);
122
+ }
123
+ const extensions = loader?.getExtensions();
124
+ for (const { path: extensionPath, error } of extensions?.errors ?? []) {
125
+ diagnostics.push(`Failed to load extension "${extensionPath}": ${error}`);
126
+ }
127
+ return {
128
+ settingsManager,
129
+ themes: loader?.getThemes().themes ?? [],
130
+ render: createRenderContext({ runtime, settingsManager, extensions }),
131
+ diagnostics,
132
+ };
133
+ }
134
+
135
+ /** Terminal capability overrides and keybindings, as interactive mode sets them. */
136
+ export function applyTerminalSettings(runtime, environment) {
137
+ const overrides = call(environment.settingsManager, "getTerminalCapabilityOverrides");
138
+ if (overrides) call(runtime.tui, "setCapabilityOverrides", overrides);
139
+ const KeybindingsManager = runtime.internal?.keybindings?.KeybindingsManager;
140
+ if (KeybindingsManager && typeof runtime.tui.setKeybindings === "function") {
141
+ try {
142
+ runtime.tui.setKeybindings(KeybindingsManager.create());
143
+ } catch {
144
+ /* default keybindings */
145
+ }
146
+ }
147
+ }
148
+
149
+ function themeName(runtime, settingsManager) {
150
+ const themeModule = runtime.internal?.theme;
151
+ const setting = call(settingsManager, "getThemeSetting") ?? call(settingsManager, "getTheme");
152
+ if (typeof themeModule?.resolveThemeSetting !== "function") return setting;
153
+ return themeModule.resolveThemeSetting(setting, call(themeModule, "getTerminalTheme")) ?? SYSTEM_THEME_NAME;
154
+ }
155
+
156
+ /**
157
+ * Apply the theme setting. With a `ui`, follow interactive mode: the returned
158
+ * `start()` (call after `ui.start()`) queries the terminal's colors and keeps
159
+ * the system theme and light/dark pairs in sync with the terminal. Without a
160
+ * `ui` (print mode) the theme is applied once.
161
+ */
162
+ export function initPiTheme(runtime, environment, ui) {
163
+ const themeModule = runtime.internal?.theme;
164
+ call(themeModule, "setRegisteredThemes", environment.themes);
165
+ const Controller = runtime.internal?.themeController?.InteractiveThemeController;
166
+ if (ui && Controller && environment.settingsManager) {
167
+ const controller = new Controller(ui, {
168
+ getSettingsManager: () => environment.settingsManager,
169
+ showError: () => {},
170
+ onChanged: () => {},
171
+ });
172
+ return { start: () => controller.applyFromSettings() };
173
+ }
174
+ runtime.agent.initTheme(themeName(runtime, environment.settingsManager), false);
175
+ return { start() {} };
176
+ }
package/pi-runtime.mjs ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Resolve the Pi packages of the INSTALLED pi, so a standalone viewer renders
3
+ * with the same components as the pi that produced the log (not a copy that
4
+ * happens to sit in a dependent package's node_modules).
5
+ */
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { execFileSync } from "node:child_process";
10
+ import { pathToFileURL } from "node:url";
11
+
12
+ const AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
13
+
14
+ function packageName(dir) {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")).name;
17
+ } catch {
18
+ return undefined;
19
+ }
20
+ }
21
+
22
+ function managedInstallDir() {
23
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? path.join(os.homedir(), ".pi", "agent");
24
+ try {
25
+ const version = fs.readFileSync(path.join(agentDir, "install", "current-version"), "utf8").trim();
26
+ if (!version) return undefined;
27
+ return path.join(agentDir, "install", "releases", version, "node_modules", AGENT_PACKAGE);
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ function packageDirFromBinary() {
34
+ try {
35
+ const bin = execFileSync("sh", ["-c", "command -v pi"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
36
+ if (!bin) return undefined;
37
+ let dir = path.dirname(fs.realpathSync(bin));
38
+ for (;;) {
39
+ if (packageName(dir) === AGENT_PACKAGE) return dir;
40
+ const parent = path.dirname(dir);
41
+ if (parent === dir) return undefined;
42
+ dir = parent;
43
+ }
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }
48
+
49
+ /** Directory of the installed pi-coding-agent package, or undefined. */
50
+ export function findPiPackageDir() {
51
+ const candidates = [process.env.PI_TAIL_PI_PACKAGE_DIR, managedInstallDir(), packageDirFromBinary()];
52
+ return candidates.find((dir) => dir && packageName(dir) === AGENT_PACKAGE);
53
+ }
54
+
55
+ function siblingPackageEntry(agentDir, name) {
56
+ for (const dir of [
57
+ path.join(path.dirname(agentDir), name),
58
+ path.join(agentDir, "node_modules", "@earendil-works", name),
59
+ ]) {
60
+ if (packageName(dir) === `@earendil-works/${name}`) {
61
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
62
+ const entry = pkg.exports?.["."]?.import ?? pkg.exports?.["."]?.default ?? pkg.module ?? pkg.main ?? "index.js";
63
+ return pathToFileURL(path.join(dir, entry)).href;
64
+ }
65
+ }
66
+ return undefined;
67
+ }
68
+
69
+ /**
70
+ * Internal (non-exported) modules of pi-coding-agent that interactive mode
71
+ * uses to set up its chat. Each is optional: a pi release that moved or lacks
72
+ * one degrades to the closest public behavior instead of failing.
73
+ */
74
+ const INTERNAL_MODULES = {
75
+ renderers: "dist/core/tools/renderers/index.js",
76
+ builtInExtensions: "dist/extensions/index.js",
77
+ trust: "dist/core/trust-manager.js",
78
+ keybindings: "dist/core/keybindings.js",
79
+ theme: "dist/modes/interactive/theme/theme.js",
80
+ themeController: "dist/modes/interactive/theme/theme-controller.js",
81
+ mermaid: "dist/modes/interactive/components/mermaid.js",
82
+ };
83
+
84
+ async function importInternal(packageDir, relativePath) {
85
+ const file = path.join(packageDir, relativePath);
86
+ if (!fs.existsSync(file)) return undefined;
87
+ try {
88
+ return await import(pathToFileURL(file).href);
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Load { agent, tui, withBuiltInRenderers, internal, packageDir, version }.
96
+ * `internal` holds the optional internal modules (see INTERNAL_MODULES); they
97
+ * resolve to the same module instances the public entry point uses, so module
98
+ * state such as registered themes is shared.
99
+ */
100
+ export async function loadPiRuntime() {
101
+ const packageDir = findPiPackageDir();
102
+ let agent;
103
+ let tui;
104
+ let version;
105
+ const internal = {};
106
+ if (packageDir) {
107
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
108
+ version = pkg.version;
109
+ agent = await import(pathToFileURL(path.join(packageDir, pkg.exports?.["."]?.import ?? "dist/index.js")).href);
110
+ const tuiEntry = siblingPackageEntry(packageDir, "pi-tui");
111
+ tui = await import(tuiEntry ?? "@earendil-works/pi-tui");
112
+ for (const [key, relativePath] of Object.entries(INTERNAL_MODULES)) {
113
+ internal[key] = await importInternal(packageDir, relativePath);
114
+ }
115
+ } else {
116
+ agent = await import(AGENT_PACKAGE);
117
+ tui = await import("@earendil-works/pi-tui");
118
+ }
119
+ return { agent, tui, withBuiltInRenderers: internal.renderers?.withBuiltInRenderers, internal, packageDir, version };
120
+ }
package/pi-tail.mjs ADDED
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pi-tail — live, read-only view of a Pi RPC / JSON event log, rendered with
4
+ * the installed Pi's own TUI components.
5
+ *
6
+ * pi-tail <file> [--print] [--cwd DIR]
7
+ *
8
+ * The file is the JSONL event stream `pi --mode rpc` (or `pi --mode json`)
9
+ * writes to stdout. Follow mode tails the file until you quit (q / Ctrl-C).
10
+ * --print renders the current transcript once to stdout.
11
+ */
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import { pathToFileURL } from "node:url";
15
+ import { applyTerminalSettings, initPiTheme, loadPiEnvironment } from "./pi-environment.mjs";
16
+ import { loadPiRuntime } from "./pi-runtime.mjs";
17
+ import { createTranscriptView } from "./transcript-view.mjs";
18
+
19
+ export const USAGE = "Usage: pi-tail <file> [--print] [--cwd DIR]";
20
+
21
+ export function parseArgs(argv) {
22
+ const options = { print: false, cwd: undefined, target: undefined };
23
+ for (let index = 0; index < argv.length; index++) {
24
+ const arg = argv[index];
25
+ if (arg === "--print") options.print = true;
26
+ else if (arg === "--cwd") options.cwd = argv[++index];
27
+ else if (arg === "-h" || arg === "--help") options.help = true;
28
+ else if (!options.target) options.target = arg;
29
+ else throw new Error(`Unexpected argument: ${arg}`);
30
+ }
31
+ return options;
32
+ }
33
+
34
+ /**
35
+ * Incremental JSONL reader: feed text, get parsed event objects. Lines that are
36
+ * not JSON objects are skipped, and a trailing `\r` (a PTY's line ending) is
37
+ * ignored.
38
+ */
39
+ export function createLogReader(onEvent) {
40
+ let pending = "";
41
+ const line = (raw) => {
42
+ const text = raw.replace(/\r$/, "").trim();
43
+ if (!text.startsWith("{")) return;
44
+ let event;
45
+ try {
46
+ event = JSON.parse(text);
47
+ } catch {
48
+ return;
49
+ }
50
+ onEvent(event);
51
+ };
52
+ return {
53
+ push(chunk) {
54
+ pending += chunk;
55
+ let newline;
56
+ while ((newline = pending.indexOf("\n")) >= 0) {
57
+ line(pending.slice(0, newline));
58
+ pending = pending.slice(newline + 1);
59
+ }
60
+ },
61
+ end() {
62
+ if (pending) line(pending);
63
+ pending = "";
64
+ },
65
+ };
66
+ }
67
+
68
+ function readFrom(file, offset) {
69
+ const size = fs.statSync(file).size;
70
+ if (size <= offset) return { text: "", offset: size < offset ? 0 : offset, truncated: size < offset };
71
+ const buffer = Buffer.alloc(size - offset);
72
+ const fd = fs.openSync(file, "r");
73
+ try {
74
+ fs.readSync(fd, buffer, 0, buffer.length, offset);
75
+ } finally {
76
+ fs.closeSync(fd);
77
+ }
78
+ return { text: buffer, offset: size, truncated: false };
79
+ }
80
+
81
+ export function createViewerInputListener({ tui, getView, quit, onChange }) {
82
+ const key = (data, name) => tui.matchesKey?.(data, name) ?? false;
83
+ return (data) => {
84
+ // Input listeners run before Pi's focused-component key-release filter.
85
+ // Toggle once per press, not again on release or while holding the key.
86
+ if (tui.isKeyRelease?.(data) || tui.isKeyRepeat?.(data)) return { consume: true };
87
+ if (key(data, "q") || key(data, "ctrl+c") || data === "q" || data === "\x03") quit();
88
+ else if (key(data, "ctrl+o") || data === "\x0f") {
89
+ const view = getView();
90
+ view.setToolsExpanded(!view.expanded);
91
+ } else if (key(data, "t") || data === "t") getView().toggleThinking();
92
+ else return { consume: true };
93
+ onChange();
94
+ return { consume: true };
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Render `file` with Pi's components.
100
+ *
101
+ * - `cwd`: directory whose Pi settings, themes and extensions are loaded, and
102
+ * that tool paths are shown relative to (default: process.cwd()).
103
+ * - `print`: render the current transcript once to stdout and resolve to 0.
104
+ * Otherwise follow the file until q / Ctrl-C, which exits the process.
105
+ * - `status()`: text shown before the key hints in the status line, refreshed
106
+ * on every poll (default: the file path).
107
+ */
108
+ export async function runViewer({ file, cwd = process.cwd(), print = false, status } = {}) {
109
+ if (!file) throw new Error("runViewer: file is required");
110
+ if (!fs.existsSync(file)) throw new Error(`No such file: ${file}`);
111
+ const statusPrefix = status ?? (() => file);
112
+ const runtime = await loadPiRuntime();
113
+ // Settings, themes and extension renderers, as Pi loads them for `cwd`.
114
+ const environment = await loadPiEnvironment(runtime, { cwd });
115
+ applyTerminalSettings(runtime, environment);
116
+ const newView = (tui) => createTranscriptView({ runtime, tui, cwd, render: environment.render });
117
+
118
+ const decoder = new TextDecoder();
119
+ if (print) {
120
+ initPiTheme(runtime, environment);
121
+ for (const message of environment.diagnostics) process.stderr.write(`${message}\n`);
122
+ const view = newView({ requestRender() {} });
123
+ const reader = createLogReader((event) => view.apply(event));
124
+ reader.push(decoder.decode(fs.readFileSync(file)));
125
+ reader.end();
126
+ const width = process.stdout.columns || 120;
127
+ await new Promise((resolve) => process.stdout.write(`${view.container.render(width).join("\n")}\n`, resolve));
128
+ return 0;
129
+ }
130
+
131
+ const { Container, ProcessTerminal, Spacer, Text } = runtime.tui;
132
+ // Pi >= 1.5 renders regular (scrollback) mode with TuiMainScreen; older
133
+ // pi-tui releases export the TUI class itself.
134
+ const Screen = runtime.tui.TuiMainScreen ?? runtime.tui.TUI;
135
+ if (typeof Screen !== "function") throw new Error("Unsupported pi-tui: no TuiMainScreen or TUI export");
136
+ const settingsManager = environment.settingsManager;
137
+ const ui = new Screen(
138
+ new ProcessTerminal(),
139
+ settingsManager?.getShowHardwareCursor?.(),
140
+ runtime.agent.getAgentDir?.(),
141
+ );
142
+ if (settingsManager?.getClearOnShrink) ui.setClearOnShrink?.(settingsManager.getClearOnShrink());
143
+ const theme = initPiTheme(runtime, environment, ui);
144
+ if (environment.diagnostics.length > 0) {
145
+ const diagnostics = new Container();
146
+ for (const message of environment.diagnostics) diagnostics.addChild(new Text(`\x1b[31m${message}\x1b[0m`, 1, 0));
147
+ diagnostics.addChild(new Spacer(1));
148
+ ui.addChild(diagnostics);
149
+ }
150
+ let view = newView(ui);
151
+ let reader = createLogReader((event) => view.apply(event));
152
+ const statusText = new Text("", 1, 0);
153
+ const statusLine = () => {
154
+ const prefix = statusPrefix();
155
+ const hints = `q quit · ctrl+o ${view.expanded ? "collapse" : "expand"} tools · t thinking`;
156
+ statusText.setText(`\x1b[2m${prefix ? `${prefix} · ` : ""}${hints}\x1b[0m`);
157
+ };
158
+ ui.addChild(view.container);
159
+ ui.addChild(statusText);
160
+
161
+ let offset = 0;
162
+ const poll = () => {
163
+ const chunk = readFrom(file, offset);
164
+ if (chunk.truncated) {
165
+ // The file was replaced; start over.
166
+ const index = ui.children.indexOf(view.container);
167
+ view = newView(ui);
168
+ reader = createLogReader((event) => view.apply(event));
169
+ ui.children.splice(index, 1, view.container);
170
+ }
171
+ offset = chunk.offset;
172
+ if (chunk.text.length) reader.push(decoder.decode(chunk.text, { stream: true }));
173
+ statusLine();
174
+ ui.requestRender();
175
+ };
176
+
177
+ const quit = () => {
178
+ clearInterval(timer);
179
+ ui.stop();
180
+ process.exit(0);
181
+ };
182
+ ui.addInputListener(createViewerInputListener({
183
+ tui: runtime.tui,
184
+ getView: () => view,
185
+ quit,
186
+ onChange() {
187
+ statusLine();
188
+ ui.requestRender();
189
+ },
190
+ }));
191
+
192
+ poll();
193
+ ui.start();
194
+ theme.start();
195
+ const timer = setInterval(poll, 200);
196
+ return undefined;
197
+ }
198
+
199
+ export async function main(argv = process.argv.slice(2)) {
200
+ const options = parseArgs(argv);
201
+ if (options.help || !options.target) {
202
+ console.log(USAGE);
203
+ return options.help ? 0 : 2;
204
+ }
205
+ return runViewer({ file: path.resolve(options.target), cwd: options.cwd, print: options.print });
206
+ }
207
+
208
+ /** Run `run()` as a CLI entry point: exit with its code, or keep following. */
209
+ export function runCli(run) {
210
+ run().then(
211
+ (code) => {
212
+ // Loaded extensions may keep timers alive; a finished one-shot run exits.
213
+ if (typeof code === "number") process.exit(code);
214
+ },
215
+ (error) => {
216
+ console.error(error instanceof Error ? error.message : String(error));
217
+ process.exit(1);
218
+ },
219
+ );
220
+ }
221
+
222
+ const entry = process.argv[1] ? pathToFileURL(fs.realpathSync(process.argv[1])).href : undefined;
223
+ if (entry === import.meta.url) runCli(main);
@@ -0,0 +1,324 @@
1
+ /**
2
+ * transcript-view.mjs — render standard Pi RPC events with Pi's own TUI
3
+ * components, mirroring interactive mode's event handling.
4
+ *
5
+ * RPC `message_update` events are delta-only, so the streaming assistant
6
+ * message is rebuilt from content-block deltas (see Pi docs/json.md).
7
+ */
8
+
9
+ const RED = "\x1b[31m";
10
+ const DIM = "\x1b[2m";
11
+ const RESET = "\x1b[0m";
12
+
13
+ function userText(message) {
14
+ if (typeof message.content === "string") return message.content;
15
+ if (!Array.isArray(message.content)) return "";
16
+ return message.content
17
+ .filter((block) => block?.type === "text" && typeof block.text === "string")
18
+ .map((block) => block.text)
19
+ .join("");
20
+ }
21
+
22
+ /** Apply one delta-only assistantMessageEvent to a mutable assistant message. */
23
+ export function applyAssistantDelta(message, update) {
24
+ if (!update || typeof update !== "object") return;
25
+ const content = Array.isArray(message.content) ? message.content : (message.content = []);
26
+ const index = update.contentIndex;
27
+ switch (update.type) {
28
+ case "text_start":
29
+ content[index] = { type: "text", text: "" };
30
+ break;
31
+ case "text_delta":
32
+ if (content[index]?.type !== "text") content[index] = { type: "text", text: "" };
33
+ content[index].text += update.delta ?? "";
34
+ break;
35
+ case "text_end":
36
+ content[index] = { ...content[index], type: "text", text: String(update.content ?? content[index]?.text ?? "") };
37
+ break;
38
+ case "thinking_start":
39
+ content[index] = { type: "thinking", thinking: "" };
40
+ break;
41
+ case "thinking_delta":
42
+ if (content[index]?.type !== "thinking") content[index] = { type: "thinking", thinking: "" };
43
+ content[index].thinking += update.delta ?? "";
44
+ break;
45
+ case "thinking_end":
46
+ content[index] = {
47
+ ...content[index],
48
+ type: "thinking",
49
+ thinking: String(update.content ?? content[index]?.thinking ?? ""),
50
+ };
51
+ break;
52
+ case "toolcall_start":
53
+ content[index] = { type: "toolCall", id: update.id, name: update.toolName, arguments: {} };
54
+ break;
55
+ case "toolcall_end":
56
+ if (update.toolCall) content[index] = update.toolCall;
57
+ break;
58
+ default:
59
+ break;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Render context without a loaded Pi environment: built-in tool renderers only
65
+ * and default settings. pi-environment.mjs builds the full one.
66
+ */
67
+ export function defaultRenderContext(runtime) {
68
+ return {
69
+ getToolDefinition: (name) => runtime.withBuiltInRenderers?.(name, undefined),
70
+ getMessageRenderer: () => undefined,
71
+ getMarkdownTransformers: () => [],
72
+ markdownTheme: () => runtime.agent.getMarkdownTheme(),
73
+ hideThinkingBlock: false,
74
+ outputPad: undefined,
75
+ showImages: false,
76
+ imageWidthCells: undefined,
77
+ };
78
+ }
79
+
80
+ export function createTranscriptView({ runtime, tui, cwd = process.cwd(), render = defaultRenderContext(runtime) }) {
81
+ const {
82
+ AssistantMessageComponent,
83
+ ToolExecutionComponent,
84
+ UserMessageComponent,
85
+ CustomMessageComponent,
86
+ CompactionSummaryMessageComponent,
87
+ BranchSummaryMessageComponent,
88
+ SkillInvocationMessageComponent,
89
+ parseSkillBlock,
90
+ } = runtime.agent;
91
+ const { Container, Spacer, Text } = runtime.tui;
92
+
93
+ const container = new Container();
94
+ const pendingTools = new Map();
95
+ const expandables = [];
96
+ const assistants = [];
97
+ let expanded = false;
98
+ let hideThinking = render.hideThinkingBlock === true;
99
+ let streaming;
100
+
101
+ // Constructor arguments below follow interactive mode (InteractiveMode.handleEvent / addMessageToChat).
102
+ const markdownTheme = () => render.markdownTheme();
103
+ const transformers = () => render.getMarkdownTransformers();
104
+ const outputPad = render.outputPad;
105
+ const toolOptions = { showImages: render.showImages, imageWidthCells: render.imageWidthCells, outputPad };
106
+ const add = (component) => {
107
+ container.addChild(component);
108
+ return component;
109
+ };
110
+ const addExpandable = (component) => {
111
+ component.setExpanded?.(expanded);
112
+ expandables.push(component);
113
+ return add(component);
114
+ };
115
+ const note = (text, color = DIM) => {
116
+ add(new Spacer(1));
117
+ add(new Text(`${color}${text}${RESET}`, 1, 0));
118
+ };
119
+
120
+ function toolComponent(name, id, args) {
121
+ let component = pendingTools.get(id);
122
+ if (component) return component;
123
+ component = new ToolExecutionComponent(name, id, args ?? {}, toolOptions, render.getToolDefinition(name), tui, cwd);
124
+ addExpandable(component);
125
+ pendingTools.set(id, component);
126
+ return component;
127
+ }
128
+
129
+ function syncToolCalls(message) {
130
+ for (const block of message.content ?? []) {
131
+ if (block?.type !== "toolCall" || !block.id) continue;
132
+ const existing = pendingTools.get(block.id);
133
+ if (existing) existing.updateArgs(block.arguments ?? {});
134
+ else toolComponent(block.name, block.id, block.arguments);
135
+ }
136
+ }
137
+
138
+ function newAssistant(message) {
139
+ // undefined label: the component's default, as in interactive mode before an extension changes it.
140
+ const component = new AssistantMessageComponent(
141
+ undefined,
142
+ hideThinking,
143
+ markdownTheme(),
144
+ undefined,
145
+ outputPad,
146
+ transformers(),
147
+ );
148
+ assistants.push(component);
149
+ add(component);
150
+ component.updateContent(message, true);
151
+ return component;
152
+ }
153
+
154
+ function finishAssistant(component, message) {
155
+ component.updateContent(message, false);
156
+ if (message.stopReason === "aborted" || message.stopReason === "error") {
157
+ const errorMessage =
158
+ message.errorMessage || (message.stopReason === "aborted" ? "Operation aborted" : "Error");
159
+ for (const tool of pendingTools.values()) {
160
+ tool.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true });
161
+ }
162
+ pendingTools.clear();
163
+ } else {
164
+ for (const tool of pendingTools.values()) tool.setArgsComplete();
165
+ }
166
+ }
167
+
168
+ function addMessage(message) {
169
+ switch (message.role) {
170
+ case "user": {
171
+ const text = userText(message);
172
+ if (!text) return;
173
+ if (container.children.length > 0) add(new Spacer(1));
174
+ const skillBlock = parseSkillBlock?.(text);
175
+ if (skillBlock && SkillInvocationMessageComponent) {
176
+ addExpandable(
177
+ new SkillInvocationMessageComponent(skillBlock, markdownTheme(), outputPad, transformers()),
178
+ );
179
+ if (skillBlock.userMessage) {
180
+ add(new Spacer(1));
181
+ add(new UserMessageComponent(skillBlock.userMessage, markdownTheme(), outputPad, transformers()));
182
+ }
183
+ return;
184
+ }
185
+ add(new UserMessageComponent(text, markdownTheme(), outputPad, transformers()));
186
+ return;
187
+ }
188
+ case "custom":
189
+ if (message.display) {
190
+ const renderer = render.getMessageRenderer(message.customType);
191
+ addExpandable(new CustomMessageComponent(message, renderer, markdownTheme(), outputPad, transformers()));
192
+ }
193
+ return;
194
+ case "compactionSummary":
195
+ add(new Spacer(1));
196
+ addExpandable(
197
+ new CompactionSummaryMessageComponent(message, markdownTheme(), outputPad, transformers()),
198
+ );
199
+ return;
200
+ case "branchSummary":
201
+ add(new Spacer(1));
202
+ addExpandable(new BranchSummaryMessageComponent(message, markdownTheme(), outputPad, transformers()));
203
+ return;
204
+ default:
205
+ return;
206
+ }
207
+ }
208
+
209
+ function apply(event) {
210
+ switch (event?.type) {
211
+ case "agent_start":
212
+ pendingTools.clear();
213
+ return;
214
+ case "message_start": {
215
+ const message = event.message;
216
+ if (!message) return;
217
+ if (message.role === "assistant") {
218
+ const copy = { ...message, content: [...(Array.isArray(message.content) ? message.content : [])] };
219
+ streaming = { message: copy, component: newAssistant(copy) };
220
+ } else {
221
+ addMessage(message);
222
+ }
223
+ return;
224
+ }
225
+ case "message_update": {
226
+ if (!streaming) return;
227
+ if (event.message?.role === "assistant") {
228
+ // Cumulative snapshot from old Pi releases.
229
+ streaming.message = { ...event.message, content: [...(event.message.content ?? [])] };
230
+ } else {
231
+ applyAssistantDelta(streaming.message, event.assistantMessageEvent);
232
+ }
233
+ if (event.usage) streaming.message.usage = event.usage;
234
+ streaming.component.updateContent(streaming.message, true);
235
+ syncToolCalls(streaming.message);
236
+ return;
237
+ }
238
+ case "message_end": {
239
+ const message = event.message;
240
+ if (message?.role !== "assistant") return;
241
+ const component = streaming?.component ?? newAssistant(message);
242
+ syncToolCalls(message);
243
+ finishAssistant(component, message);
244
+ streaming = undefined;
245
+ return;
246
+ }
247
+ case "tool_execution_start": {
248
+ if (event.parentToolCallId) return;
249
+ const component = toolComponent(event.toolName, event.toolCallId, event.args);
250
+ component.markExecutionStarted?.();
251
+ return;
252
+ }
253
+ case "tool_execution_update":
254
+ pendingTools.get(event.toolCallId)?.updateResult({ ...event.partialResult, isError: false }, true);
255
+ return;
256
+ case "tool_execution_end": {
257
+ const component = pendingTools.get(event.toolCallId);
258
+ if (!component) return;
259
+ component.updateResult({ ...event.result, isError: event.isError, durationMs: event.durationMs });
260
+ pendingTools.delete(event.toolCallId);
261
+ return;
262
+ }
263
+ case "agent_end":
264
+ if (streaming) {
265
+ container.removeChild(streaming.component);
266
+ streaming = undefined;
267
+ }
268
+ pendingTools.clear();
269
+ return;
270
+ case "entry_appended": {
271
+ const entry = event.entry;
272
+ if (entry?.type === "custom_message" && entry.display) {
273
+ addMessage({
274
+ role: "custom",
275
+ customType: entry.customType,
276
+ content: entry.content,
277
+ display: entry.display,
278
+ details: entry.details,
279
+ timestamp: entry.timestamp,
280
+ });
281
+ }
282
+ return;
283
+ }
284
+ case "compaction_end":
285
+ if (event.result?.summary) {
286
+ addMessage({
287
+ role: "compactionSummary",
288
+ summary: event.result.summary,
289
+ tokensBefore: event.result.tokensBefore,
290
+ timestamp: Date.now(),
291
+ });
292
+ }
293
+ return;
294
+ case "extension_error":
295
+ note(`Extension error${event.extensionPath ? ` (${event.extensionPath})` : ""}: ${event.error ?? ""}`, RED);
296
+ return;
297
+ case "error":
298
+ note(`Error: ${event.message ?? event.error ?? JSON.stringify(event)}`, RED);
299
+ return;
300
+ case "response":
301
+ if (event.success === false) note(`RPC ${event.command ?? "command"} failed: ${event.error ?? ""}`, RED);
302
+ return;
303
+ default:
304
+ return;
305
+ }
306
+ }
307
+
308
+ return {
309
+ container,
310
+ apply,
311
+ get expanded() {
312
+ return expanded;
313
+ },
314
+ setToolsExpanded(value) {
315
+ expanded = value;
316
+ for (const component of expandables) component.setExpanded?.(value);
317
+ },
318
+ toggleThinking() {
319
+ hideThinking = !hideThinking;
320
+ for (const component of assistants) component.setHideThinkingBlock(hideThinking);
321
+ return hideThinking;
322
+ },
323
+ };
324
+ }