@yusukeshib/pi-tail 0.1.0 → 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.
Files changed (3) hide show
  1. package/README.md +20 -14
  2. package/package.json +1 -1
  3. package/pi-tail.mjs +48 -18
package/README.md CHANGED
@@ -5,13 +5,14 @@ way Pi renders its own chat, with the installed Pi's TUI components
5
5
  (`AssistantMessageComponent`, `ToolExecutionComponent`, …).
6
6
 
7
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.
8
+ writes to stdout. The interface follows tail(1).
10
9
 
11
10
  ```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
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
15
16
  ```
16
17
 
17
18
  ## Install
@@ -32,13 +33,17 @@ So the transcript is rendered by the same Pi release that you run.
32
33
  ## Usage
33
34
 
34
35
  ```
35
- pi-tail <file> [--print] [--cwd DIR]
36
+ pi-tail [-f] [-n N] [--cwd DIR] [file]
36
37
  ```
37
38
 
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.
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`.
42
47
  - `--cwd DIR` is the agent's working directory (default: the current
43
48
  directory). It decides which Pi settings, themes and extensions are loaded,
44
49
  and tool paths are shown relative to it.
@@ -52,8 +57,7 @@ skipped, never installed; a project that Pi has not been told to trust is
52
57
  loaded without its project-local resources.
53
58
 
54
59
  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.
60
+ ignored, so a log may carry other records.
57
61
 
58
62
  ## Library
59
63
 
@@ -63,12 +67,14 @@ import { runViewer } from "@yusukeshib/pi-tail";
63
67
  await runViewer({
64
68
  file: "/path/to/run.jsonl",
65
69
  cwd: "/path/to/project",
70
+ follow: true,
66
71
  status: () => "worker · running", // shown before the key hints
67
72
  });
68
73
  ```
69
74
 
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.
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.
72
78
 
73
79
  Lower-level pieces are exported too: `createTranscriptView` (apply events,
74
80
  read `.container`), `createLogReader`, `loadPiRuntime`, `loadPiEnvironment`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yusukeshib/pi-tail",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Follow a Pi RPC / JSON event log and render it with Pi's own TUI components.",
5
5
  "keywords": [
6
6
  "pi",
package/pi-tail.mjs CHANGED
@@ -3,11 +3,12 @@
3
3
  * pi-tail — live, read-only view of a Pi RPC / JSON event log, rendered with
4
4
  * the installed Pi's own TUI components.
5
5
  *
6
- * pi-tail <file> [--print] [--cwd DIR]
6
+ * pi-tail [-f] [-n N] [--cwd DIR] [file]
7
7
  *
8
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.
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).
11
12
  */
12
13
  import fs from "node:fs";
13
14
  import path from "node:path";
@@ -16,21 +17,43 @@ import { applyTerminalSettings, initPiTheme, loadPiEnvironment } from "./pi-envi
16
17
  import { loadPiRuntime } from "./pi-runtime.mjs";
17
18
  import { createTranscriptView } from "./transcript-view.mjs";
18
19
 
19
- export const USAGE = "Usage: pi-tail <file> [--print] [--cwd DIR]";
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
+ }
20
26
 
21
27
  export function parseArgs(argv) {
22
- const options = { print: false, cwd: undefined, target: undefined };
28
+ const options = { follow: false, lines: undefined, cwd: undefined, target: undefined };
23
29
  for (let index = 0; index < argv.length; index++) {
24
30
  const arg = argv[index];
25
- if (arg === "--print") options.print = true;
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));
26
35
  else if (arg === "--cwd") options.cwd = argv[++index];
27
36
  else if (arg === "-h" || arg === "--help") options.help = true;
28
- else if (!options.target) options.target = arg;
37
+ else if (arg !== "-" && arg.startsWith("-")) throw new Error(`Unknown option: ${arg}`);
38
+ else if (options.target === undefined) options.target = arg;
29
39
  else throw new Error(`Unexpected argument: ${arg}`);
30
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
+ }
31
45
  return options;
32
46
  }
33
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
+
34
57
  /**
35
58
  * Incremental JSONL reader: feed text, get parsed event objects. Lines that are
36
59
  * not JSON objects are skipped, and a trailing `\r` (a PTY's line ending) is
@@ -96,18 +119,20 @@ export function createViewerInputListener({ tui, getView, quit, onChange }) {
96
119
  }
97
120
 
98
121
  /**
99
- * Render `file` with Pi's components.
122
+ * Render a Pi event log with Pi's components.
100
123
  *
124
+ * - `file`: the log. Without `follow`, omit it to read stdin.
101
125
  * - `cwd`: directory whose Pi settings, themes and extensions are loaded, and
102
126
  * 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.
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.
105
130
  * - `status()`: text shown before the key hints in the status line, refreshed
106
131
  * on every poll (default: the file path).
107
132
  */
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}`);
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}`);
111
136
  const statusPrefix = status ?? (() => file);
112
137
  const runtime = await loadPiRuntime();
113
138
  // Settings, themes and extension renderers, as Pi loads them for `cwd`.
@@ -116,15 +141,18 @@ export async function runViewer({ file, cwd = process.cwd(), print = false, stat
116
141
  const newView = (tui) => createTranscriptView({ runtime, tui, cwd, render: environment.render });
117
142
 
118
143
  const decoder = new TextDecoder();
119
- if (print) {
144
+ if (!follow) {
120
145
  initPiTheme(runtime, environment);
121
146
  for (const message of environment.diagnostics) process.stderr.write(`${message}\n`);
122
147
  const view = newView({ requestRender() {} });
123
148
  const reader = createLogReader((event) => view.apply(event));
124
- reader.push(decoder.decode(fs.readFileSync(file)));
149
+ reader.push(decoder.decode(file ? fs.readFileSync(file) : await readStdin()));
125
150
  reader.end();
126
151
  const width = process.stdout.columns || 120;
127
- await new Promise((resolve) => process.stdout.write(`${view.container.render(width).join("\n")}\n`, resolve));
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));
128
156
  return 0;
129
157
  }
130
158
 
@@ -198,11 +226,13 @@ export async function runViewer({ file, cwd = process.cwd(), print = false, stat
198
226
 
199
227
  export async function main(argv = process.argv.slice(2)) {
200
228
  const options = parseArgs(argv);
201
- if (options.help || !options.target) {
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)) {
202
231
  console.log(USAGE);
203
232
  return options.help ? 0 : 2;
204
233
  }
205
- return runViewer({ file: path.resolve(options.target), cwd: options.cwd, print: options.print });
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 });
206
236
  }
207
237
 
208
238
  /** Run `run()` as a CLI entry point: exit with its code, or keep following. */