@yusukeshib/pi-tail 0.0.0-stage → 0.2.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,97 @@
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. The interface follows tail(1).
9
+
10
+ ```sh
11
+ pi --mode json -p "Summarize README.md" > run.jsonl
12
+ pi-tail run.jsonl # render the transcript once to stdout
13
+ pi-tail -n 40 run.jsonl # only the last 40 rendered lines
14
+ pi-tail -f run.jsonl # follow live in Pi's TUI
15
+ pi --mode json -p "hi" | pi-tail # read stdin
16
+ ```
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ npm install -g @yusukeshib/pi-tail
22
+ ```
23
+
24
+ Pi itself is not bundled. The Pi packages are loaded from, in order:
25
+
26
+ 1. `PI_TAIL_PI_PACKAGE_DIR` (a `@earendil-works/pi-coding-agent` package directory)
27
+ 2. the managed install (`~/.pi/agent/install/current-version`, or under `PI_CODING_AGENT_DIR`)
28
+ 3. the `pi` on `PATH`
29
+ 4. `@earendil-works/pi-coding-agent` / `@earendil-works/pi-tui` resolvable from pi-tail
30
+
31
+ So the transcript is rendered by the same Pi release that you run.
32
+
33
+ ## Usage
34
+
35
+ ```
36
+ pi-tail [-f] [-n N] [--cwd DIR] [file]
37
+ ```
38
+
39
+ - Without `-f`, the transcript is rendered once to stdout. With no file or
40
+ `-`, the log is read from stdin until EOF.
41
+ - `-n N` / `--lines N` / `-nN` prints only the last N rendered lines. Unlike
42
+ tail(1), the default is the whole transcript.
43
+ - `-f` / `--follow` follows the file in Pi's TUI. It re-reads the file every
44
+ 200 ms and starts over if it shrinks. Keys: `q` / `Ctrl-C` quit, `Ctrl-O`
45
+ expand or collapse tool output, `t` toggle thinking blocks. `-f` needs a
46
+ file (the TUI reads keys from stdin) and cannot be combined with `-n`.
47
+ - `--cwd DIR` is the agent's working directory (default: the current
48
+ directory). It decides which Pi settings, themes and extensions are loaded,
49
+ and tool paths are shown relative to it.
50
+
51
+ pi-tail sets up the environment the way Pi's interactive mode does for that
52
+ directory: settings (global and, for a trusted project, project), themes from
53
+ `settings.themes` and packages, terminal colors, keybindings, and the
54
+ extensions' tool, message and Markdown renderers. Extensions are loaded but no
55
+ session starts, so their session handlers never run; missing packages are
56
+ skipped, never installed; a project that Pi has not been told to trust is
57
+ loaded without its project-local resources.
58
+
59
+ Lines that are not JSON objects and event types pi-tail does not render are
60
+ ignored, so a log may carry other records.
61
+
62
+ ## Library
63
+
64
+ ```js
65
+ import { runViewer } from "@yusukeshib/pi-tail";
66
+
67
+ await runViewer({
68
+ file: "/path/to/run.jsonl",
69
+ cwd: "/path/to/project",
70
+ follow: true,
71
+ status: () => "worker · running", // shown before the key hints
72
+ });
73
+ ```
74
+
75
+ Without `follow`, `runViewer` prints (the last `lines` lines, if given; stdin
76
+ when `file` is omitted) and resolves to `0`. With `follow` it resolves once the
77
+ UI is running, and quitting exits the process.
78
+
79
+ Lower-level pieces are exported too: `createTranscriptView` (apply events,
80
+ read `.container`), `createLogReader`, `loadPiRuntime`, `loadPiEnvironment`,
81
+ `initPiTheme`, `applyTerminalSettings`, `createViewerInputListener`.
82
+
83
+ The event-to-component mapping mirrors Pi's interactive mode but is a separate
84
+ implementation, and it uses Pi's component APIs, so a Pi release that changes
85
+ them may need a pi-tail update.
86
+
87
+ ## Development
88
+
89
+ ```sh
90
+ bun test
91
+ ```
92
+
93
+ Tests load the installed Pi (see Install).
94
+
95
+ ## License
96
+
97
+ 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.2.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,253 @@
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 [-f] [-n N] [--cwd DIR] [file]
7
+ *
8
+ * The file is the JSONL event stream `pi --mode rpc` (or `pi --mode json`)
9
+ * writes to stdout. Like tail(1): without -f the transcript is rendered once
10
+ * to stdout (the last N lines with -n); with no file or `-` it is read from
11
+ * stdin. -f follows the file in Pi's TUI until you quit (q / Ctrl-C).
12
+ */
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+ import { applyTerminalSettings, initPiTheme, loadPiEnvironment } from "./pi-environment.mjs";
17
+ import { loadPiRuntime } from "./pi-runtime.mjs";
18
+ import { createTranscriptView } from "./transcript-view.mjs";
19
+
20
+ export const USAGE = "Usage: pi-tail [-f] [-n N] [--cwd DIR] [file]";
21
+
22
+ function lineCount(value) {
23
+ if (!/^\d+$/.test(value ?? "")) throw new Error(`Invalid line count: ${value}`);
24
+ return Number(value);
25
+ }
26
+
27
+ export function parseArgs(argv) {
28
+ const options = { follow: false, lines: undefined, cwd: undefined, target: undefined };
29
+ for (let index = 0; index < argv.length; index++) {
30
+ const arg = argv[index];
31
+ if (arg === "-f" || arg === "--follow") options.follow = true;
32
+ else if (arg === "-n" || arg === "--lines") options.lines = lineCount(argv[++index]);
33
+ else if (/^-n\d+$/.test(arg)) options.lines = lineCount(arg.slice(2));
34
+ else if (arg.startsWith("--lines=")) options.lines = lineCount(arg.slice("--lines=".length));
35
+ else if (arg === "--cwd") options.cwd = argv[++index];
36
+ else if (arg === "-h" || arg === "--help") options.help = true;
37
+ else if (arg !== "-" && arg.startsWith("-")) throw new Error(`Unknown option: ${arg}`);
38
+ else if (options.target === undefined) options.target = arg;
39
+ else throw new Error(`Unexpected argument: ${arg}`);
40
+ }
41
+ if (options.follow && options.lines !== undefined) throw new Error("-n cannot be combined with -f");
42
+ if (options.follow && (options.target === undefined || options.target === "-")) {
43
+ throw new Error("-f needs a file: the terminal UI reads keys from stdin");
44
+ }
45
+ return options;
46
+ }
47
+
48
+ function readStdin() {
49
+ return new Promise((resolve, reject) => {
50
+ const chunks = [];
51
+ process.stdin.on("data", (chunk) => chunks.push(chunk));
52
+ process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
53
+ process.stdin.on("error", reject);
54
+ });
55
+ }
56
+
57
+ /**
58
+ * Incremental JSONL reader: feed text, get parsed event objects. Lines that are
59
+ * not JSON objects are skipped, and a trailing `\r` (a PTY's line ending) is
60
+ * ignored.
61
+ */
62
+ export function createLogReader(onEvent) {
63
+ let pending = "";
64
+ const line = (raw) => {
65
+ const text = raw.replace(/\r$/, "").trim();
66
+ if (!text.startsWith("{")) return;
67
+ let event;
68
+ try {
69
+ event = JSON.parse(text);
70
+ } catch {
71
+ return;
72
+ }
73
+ onEvent(event);
74
+ };
75
+ return {
76
+ push(chunk) {
77
+ pending += chunk;
78
+ let newline;
79
+ while ((newline = pending.indexOf("\n")) >= 0) {
80
+ line(pending.slice(0, newline));
81
+ pending = pending.slice(newline + 1);
82
+ }
83
+ },
84
+ end() {
85
+ if (pending) line(pending);
86
+ pending = "";
87
+ },
88
+ };
89
+ }
90
+
91
+ function readFrom(file, offset) {
92
+ const size = fs.statSync(file).size;
93
+ if (size <= offset) return { text: "", offset: size < offset ? 0 : offset, truncated: size < offset };
94
+ const buffer = Buffer.alloc(size - offset);
95
+ const fd = fs.openSync(file, "r");
96
+ try {
97
+ fs.readSync(fd, buffer, 0, buffer.length, offset);
98
+ } finally {
99
+ fs.closeSync(fd);
100
+ }
101
+ return { text: buffer, offset: size, truncated: false };
102
+ }
103
+
104
+ export function createViewerInputListener({ tui, getView, quit, onChange }) {
105
+ const key = (data, name) => tui.matchesKey?.(data, name) ?? false;
106
+ return (data) => {
107
+ // Input listeners run before Pi's focused-component key-release filter.
108
+ // Toggle once per press, not again on release or while holding the key.
109
+ if (tui.isKeyRelease?.(data) || tui.isKeyRepeat?.(data)) return { consume: true };
110
+ if (key(data, "q") || key(data, "ctrl+c") || data === "q" || data === "\x03") quit();
111
+ else if (key(data, "ctrl+o") || data === "\x0f") {
112
+ const view = getView();
113
+ view.setToolsExpanded(!view.expanded);
114
+ } else if (key(data, "t") || data === "t") getView().toggleThinking();
115
+ else return { consume: true };
116
+ onChange();
117
+ return { consume: true };
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Render a Pi event log with Pi's components.
123
+ *
124
+ * - `file`: the log. Without `follow`, omit it to read stdin.
125
+ * - `cwd`: directory whose Pi settings, themes and extensions are loaded, and
126
+ * that tool paths are shown relative to (default: process.cwd()).
127
+ * - `follow`: follow the file in Pi's TUI until q / Ctrl-C, which exits the
128
+ * process. Otherwise render once to stdout and resolve to 0.
129
+ * - `lines`: without `follow`, print only the last N rendered lines.
130
+ * - `status()`: text shown before the key hints in the status line, refreshed
131
+ * on every poll (default: the file path).
132
+ */
133
+ export async function runViewer({ file, cwd = process.cwd(), follow = false, lines, status } = {}) {
134
+ if (follow && !file) throw new Error("runViewer: follow needs a file");
135
+ if (file && !fs.existsSync(file)) throw new Error(`No such file: ${file}`);
136
+ const statusPrefix = status ?? (() => file);
137
+ const runtime = await loadPiRuntime();
138
+ // Settings, themes and extension renderers, as Pi loads them for `cwd`.
139
+ const environment = await loadPiEnvironment(runtime, { cwd });
140
+ applyTerminalSettings(runtime, environment);
141
+ const newView = (tui) => createTranscriptView({ runtime, tui, cwd, render: environment.render });
142
+
143
+ const decoder = new TextDecoder();
144
+ if (!follow) {
145
+ initPiTheme(runtime, environment);
146
+ for (const message of environment.diagnostics) process.stderr.write(`${message}\n`);
147
+ const view = newView({ requestRender() {} });
148
+ const reader = createLogReader((event) => view.apply(event));
149
+ reader.push(decoder.decode(file ? fs.readFileSync(file) : await readStdin()));
150
+ reader.end();
151
+ const width = process.stdout.columns || 120;
152
+ let rendered = view.container.render(width);
153
+ if (lines !== undefined) rendered = lines === 0 ? [] : rendered.slice(-lines);
154
+ if (rendered.length === 0) return 0;
155
+ await new Promise((resolve) => process.stdout.write(`${rendered.join("\n")}\n`, resolve));
156
+ return 0;
157
+ }
158
+
159
+ const { Container, ProcessTerminal, Spacer, Text } = runtime.tui;
160
+ // Pi >= 1.5 renders regular (scrollback) mode with TuiMainScreen; older
161
+ // pi-tui releases export the TUI class itself.
162
+ const Screen = runtime.tui.TuiMainScreen ?? runtime.tui.TUI;
163
+ if (typeof Screen !== "function") throw new Error("Unsupported pi-tui: no TuiMainScreen or TUI export");
164
+ const settingsManager = environment.settingsManager;
165
+ const ui = new Screen(
166
+ new ProcessTerminal(),
167
+ settingsManager?.getShowHardwareCursor?.(),
168
+ runtime.agent.getAgentDir?.(),
169
+ );
170
+ if (settingsManager?.getClearOnShrink) ui.setClearOnShrink?.(settingsManager.getClearOnShrink());
171
+ const theme = initPiTheme(runtime, environment, ui);
172
+ if (environment.diagnostics.length > 0) {
173
+ const diagnostics = new Container();
174
+ for (const message of environment.diagnostics) diagnostics.addChild(new Text(`\x1b[31m${message}\x1b[0m`, 1, 0));
175
+ diagnostics.addChild(new Spacer(1));
176
+ ui.addChild(diagnostics);
177
+ }
178
+ let view = newView(ui);
179
+ let reader = createLogReader((event) => view.apply(event));
180
+ const statusText = new Text("", 1, 0);
181
+ const statusLine = () => {
182
+ const prefix = statusPrefix();
183
+ const hints = `q quit · ctrl+o ${view.expanded ? "collapse" : "expand"} tools · t thinking`;
184
+ statusText.setText(`\x1b[2m${prefix ? `${prefix} · ` : ""}${hints}\x1b[0m`);
185
+ };
186
+ ui.addChild(view.container);
187
+ ui.addChild(statusText);
188
+
189
+ let offset = 0;
190
+ const poll = () => {
191
+ const chunk = readFrom(file, offset);
192
+ if (chunk.truncated) {
193
+ // The file was replaced; start over.
194
+ const index = ui.children.indexOf(view.container);
195
+ view = newView(ui);
196
+ reader = createLogReader((event) => view.apply(event));
197
+ ui.children.splice(index, 1, view.container);
198
+ }
199
+ offset = chunk.offset;
200
+ if (chunk.text.length) reader.push(decoder.decode(chunk.text, { stream: true }));
201
+ statusLine();
202
+ ui.requestRender();
203
+ };
204
+
205
+ const quit = () => {
206
+ clearInterval(timer);
207
+ ui.stop();
208
+ process.exit(0);
209
+ };
210
+ ui.addInputListener(createViewerInputListener({
211
+ tui: runtime.tui,
212
+ getView: () => view,
213
+ quit,
214
+ onChange() {
215
+ statusLine();
216
+ ui.requestRender();
217
+ },
218
+ }));
219
+
220
+ poll();
221
+ ui.start();
222
+ theme.start();
223
+ const timer = setInterval(poll, 200);
224
+ return undefined;
225
+ }
226
+
227
+ export async function main(argv = process.argv.slice(2)) {
228
+ const options = parseArgs(argv);
229
+ // Without a file, read stdin, unless it is a terminal nobody is piping into.
230
+ if (options.help || (options.target === undefined && process.stdin.isTTY)) {
231
+ console.log(USAGE);
232
+ return options.help ? 0 : 2;
233
+ }
234
+ const file = options.target === undefined || options.target === "-" ? undefined : path.resolve(options.target);
235
+ return runViewer({ file, cwd: options.cwd, follow: options.follow, lines: options.lines });
236
+ }
237
+
238
+ /** Run `run()` as a CLI entry point: exit with its code, or keep following. */
239
+ export function runCli(run) {
240
+ run().then(
241
+ (code) => {
242
+ // Loaded extensions may keep timers alive; a finished one-shot run exits.
243
+ if (typeof code === "number") process.exit(code);
244
+ },
245
+ (error) => {
246
+ console.error(error instanceof Error ? error.message : String(error));
247
+ process.exit(1);
248
+ },
249
+ );
250
+ }
251
+
252
+ const entry = process.argv[1] ? pathToFileURL(fs.realpathSync(process.argv[1])).href : undefined;
253
+ 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
+ }