@yusukeshib/pi-babysit 0.6.32 → 0.6.34

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.
@@ -0,0 +1,279 @@
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
+ export function createTranscriptView({ runtime, tui, cwd = process.cwd(), hideThinkingBlock = false }) {
64
+ const {
65
+ AssistantMessageComponent,
66
+ ToolExecutionComponent,
67
+ UserMessageComponent,
68
+ CustomMessageComponent,
69
+ CompactionSummaryMessageComponent,
70
+ BranchSummaryMessageComponent,
71
+ getMarkdownTheme,
72
+ } = runtime.agent;
73
+ const { Container, Spacer, Text } = runtime.tui;
74
+
75
+ const container = new Container();
76
+ const pendingTools = new Map();
77
+ const expandables = [];
78
+ const assistants = [];
79
+ let expanded = false;
80
+ let hideThinking = hideThinkingBlock;
81
+ let streaming;
82
+
83
+ const markdownTheme = () => getMarkdownTheme();
84
+ const toolDefinition = (name) => runtime.withBuiltInRenderers?.(name, undefined);
85
+ const add = (component) => {
86
+ container.addChild(component);
87
+ return component;
88
+ };
89
+ const addExpandable = (component) => {
90
+ component.setExpanded?.(expanded);
91
+ expandables.push(component);
92
+ return add(component);
93
+ };
94
+ const note = (text, color = DIM) => {
95
+ add(new Spacer(1));
96
+ add(new Text(`${color}${text}${RESET}`, 1, 0));
97
+ };
98
+
99
+ function toolComponent(name, id, args) {
100
+ let component = pendingTools.get(id);
101
+ if (component) return component;
102
+ component = new ToolExecutionComponent(name, id, args ?? {}, { showImages: false }, toolDefinition(name), tui, cwd);
103
+ addExpandable(component);
104
+ pendingTools.set(id, component);
105
+ return component;
106
+ }
107
+
108
+ function syncToolCalls(message) {
109
+ for (const block of message.content ?? []) {
110
+ if (block?.type !== "toolCall" || !block.id) continue;
111
+ const existing = pendingTools.get(block.id);
112
+ if (existing) existing.updateArgs(block.arguments ?? {});
113
+ else toolComponent(block.name, block.id, block.arguments);
114
+ }
115
+ }
116
+
117
+ function newAssistant(message) {
118
+ const component = new AssistantMessageComponent(undefined, hideThinking, markdownTheme());
119
+ assistants.push(component);
120
+ add(component);
121
+ component.updateContent(message, true);
122
+ return component;
123
+ }
124
+
125
+ function finishAssistant(component, message) {
126
+ component.updateContent(message, false);
127
+ if (message.stopReason === "aborted" || message.stopReason === "error") {
128
+ const errorMessage =
129
+ message.errorMessage || (message.stopReason === "aborted" ? "Operation aborted" : "Error");
130
+ for (const tool of pendingTools.values()) {
131
+ tool.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true });
132
+ }
133
+ pendingTools.clear();
134
+ } else {
135
+ for (const tool of pendingTools.values()) tool.setArgsComplete();
136
+ }
137
+ }
138
+
139
+ function addMessage(message) {
140
+ switch (message.role) {
141
+ case "user": {
142
+ const text = userText(message);
143
+ if (!text) return;
144
+ if (container.children.length > 0) add(new Spacer(1));
145
+ add(new UserMessageComponent(text, markdownTheme()));
146
+ return;
147
+ }
148
+ case "custom":
149
+ if (message.display) addExpandable(new CustomMessageComponent(message, undefined, markdownTheme()));
150
+ return;
151
+ case "compactionSummary":
152
+ add(new Spacer(1));
153
+ addExpandable(new CompactionSummaryMessageComponent(message, markdownTheme()));
154
+ return;
155
+ case "branchSummary":
156
+ add(new Spacer(1));
157
+ addExpandable(new BranchSummaryMessageComponent(message, markdownTheme()));
158
+ return;
159
+ default:
160
+ return;
161
+ }
162
+ }
163
+
164
+ function apply(event) {
165
+ switch (event?.type) {
166
+ case "agent_start":
167
+ pendingTools.clear();
168
+ return;
169
+ case "message_start": {
170
+ const message = event.message;
171
+ if (!message) return;
172
+ if (message.role === "assistant") {
173
+ const copy = { ...message, content: [...(Array.isArray(message.content) ? message.content : [])] };
174
+ streaming = { message: copy, component: newAssistant(copy) };
175
+ } else {
176
+ addMessage(message);
177
+ }
178
+ return;
179
+ }
180
+ case "message_update": {
181
+ if (!streaming) return;
182
+ if (event.message?.role === "assistant") {
183
+ // Cumulative snapshot from old Pi releases.
184
+ streaming.message = { ...event.message, content: [...(event.message.content ?? [])] };
185
+ } else {
186
+ applyAssistantDelta(streaming.message, event.assistantMessageEvent);
187
+ }
188
+ if (event.usage) streaming.message.usage = event.usage;
189
+ streaming.component.updateContent(streaming.message, true);
190
+ syncToolCalls(streaming.message);
191
+ return;
192
+ }
193
+ case "message_end": {
194
+ const message = event.message;
195
+ if (message?.role !== "assistant") return;
196
+ const component = streaming?.component ?? newAssistant(message);
197
+ syncToolCalls(message);
198
+ finishAssistant(component, message);
199
+ streaming = undefined;
200
+ return;
201
+ }
202
+ case "tool_execution_start": {
203
+ if (event.parentToolCallId) return;
204
+ const component = toolComponent(event.toolName, event.toolCallId, event.args);
205
+ component.markExecutionStarted?.();
206
+ return;
207
+ }
208
+ case "tool_execution_update":
209
+ pendingTools.get(event.toolCallId)?.updateResult({ ...event.partialResult, isError: false }, true);
210
+ return;
211
+ case "tool_execution_end": {
212
+ const component = pendingTools.get(event.toolCallId);
213
+ if (!component) return;
214
+ component.updateResult({ ...event.result, isError: event.isError, durationMs: event.durationMs });
215
+ pendingTools.delete(event.toolCallId);
216
+ return;
217
+ }
218
+ case "agent_end":
219
+ if (streaming) {
220
+ container.removeChild(streaming.component);
221
+ streaming = undefined;
222
+ }
223
+ pendingTools.clear();
224
+ return;
225
+ case "entry_appended": {
226
+ const entry = event.entry;
227
+ if (entry?.type === "custom_message" && entry.display) {
228
+ addMessage({
229
+ role: "custom",
230
+ customType: entry.customType,
231
+ content: entry.content,
232
+ display: entry.display,
233
+ details: entry.details,
234
+ timestamp: entry.timestamp,
235
+ });
236
+ }
237
+ return;
238
+ }
239
+ case "compaction_end":
240
+ if (event.result?.summary) {
241
+ addMessage({
242
+ role: "compactionSummary",
243
+ summary: event.result.summary,
244
+ tokensBefore: event.result.tokensBefore,
245
+ timestamp: Date.now(),
246
+ });
247
+ }
248
+ return;
249
+ case "extension_error":
250
+ note(`Extension error${event.extensionPath ? ` (${event.extensionPath})` : ""}: ${event.error ?? ""}`, RED);
251
+ return;
252
+ case "error":
253
+ note(`Error: ${event.message ?? event.error ?? JSON.stringify(event)}`, RED);
254
+ return;
255
+ case "response":
256
+ if (event.success === false) note(`RPC ${event.command ?? "command"} failed: ${event.error ?? ""}`, RED);
257
+ return;
258
+ default:
259
+ return;
260
+ }
261
+ }
262
+
263
+ return {
264
+ container,
265
+ apply,
266
+ get expanded() {
267
+ return expanded;
268
+ },
269
+ setToolsExpanded(value) {
270
+ expanded = value;
271
+ for (const component of expandables) component.setExpanded?.(value);
272
+ },
273
+ toggleThinking() {
274
+ hideThinking = !hideThinking;
275
+ for (const component of assistants) component.setHideThinkingBlock(hideThinking);
276
+ return hideThinking;
277
+ },
278
+ };
279
+ }
package/view.mjs ADDED
@@ -0,0 +1,219 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * view.mjs — live, read-only view of a pi-babysit subagent rendered with Pi's
4
+ * own TUI components.
5
+ *
6
+ * node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]
7
+ *
8
+ * The subagent log (rpc-stream-format.mjs) is restored to standard Pi RPC
9
+ * events and replayed into transcript-view.mjs. Follow mode tails the log until
10
+ * you quit (q / Ctrl-C). --print renders the current transcript once to stdout.
11
+ */
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+ import { loadPiRuntime } from "./pi-runtime.mjs";
17
+ import { createRpcEventRestorer } from "./rpc-stream-format.mjs";
18
+ import { createTranscriptView } from "./transcript-view.mjs";
19
+
20
+ const USAGE = "Usage: node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]";
21
+
22
+ export function parseArgs(argv) {
23
+ const options = { print: false, cwd: undefined, target: undefined };
24
+ for (let index = 0; index < argv.length; index++) {
25
+ const arg = argv[index];
26
+ if (arg === "--print") options.print = true;
27
+ else if (arg === "--cwd") options.cwd = argv[++index];
28
+ else if (arg === "-h" || arg === "--help") options.help = true;
29
+ else if (!options.target) options.target = arg;
30
+ else throw new Error(`Unexpected argument: ${arg}`);
31
+ }
32
+ return options;
33
+ }
34
+
35
+ /** Resolve a session id, session directory, or log path to the log file. */
36
+ export function resolveLogPath(target, rootBase = process.env.PI_BABYSIT_DIR ?? path.join(os.homedir(), ".pi-babysit")) {
37
+ if (fs.existsSync(target)) {
38
+ const stat = fs.statSync(target);
39
+ return stat.isDirectory() ? path.join(target, "output.log") : target;
40
+ }
41
+ let best;
42
+ for (const root of fs.existsSync(rootBase) ? fs.readdirSync(rootBase) : []) {
43
+ const log = path.join(rootBase, root, "sessions", target, "output.log");
44
+ try {
45
+ const mtime = fs.statSync(log).mtimeMs;
46
+ if (!best || mtime > best.mtime) best = { log, mtime };
47
+ } catch {
48
+ /* not in this root */
49
+ }
50
+ }
51
+ if (!best) throw new Error(`No babysit session log found for ${target} under ${rootBase}`);
52
+ return best.log;
53
+ }
54
+
55
+ function readJson(file) {
56
+ try {
57
+ return JSON.parse(fs.readFileSync(file, "utf8"));
58
+ } catch {
59
+ return undefined;
60
+ }
61
+ }
62
+
63
+ /** pi-babysit's own metadata for a session log (<root>/meta/<id>.json). */
64
+ function sessionInfo(logPath) {
65
+ const sessionDir = path.dirname(logPath);
66
+ const id = path.basename(sessionDir);
67
+ const root = path.dirname(path.dirname(sessionDir));
68
+ return {
69
+ id,
70
+ meta: readJson(path.join(root, "meta", `${id}.json`)),
71
+ statusFile: path.join(sessionDir, "status.json"),
72
+ };
73
+ }
74
+
75
+ function piSettings() {
76
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? path.join(os.homedir(), ".pi", "agent");
77
+ return readJson(path.join(agentDir, "settings.json")) ?? {};
78
+ }
79
+
80
+ /** Incremental JSONL reader: feed bytes, get complete event objects. */
81
+ export function createLogReader(onEvent) {
82
+ const restorer = createRpcEventRestorer();
83
+ let pending = "";
84
+ const line = (raw) => {
85
+ const text = raw.replace(/\r$/, "").trim();
86
+ if (!text.startsWith("{")) return;
87
+ let event;
88
+ try {
89
+ event = JSON.parse(text);
90
+ } catch {
91
+ return;
92
+ }
93
+ for (const restored of restorer.push(event)) onEvent(restored);
94
+ };
95
+ return {
96
+ push(chunk) {
97
+ pending += chunk;
98
+ let newline;
99
+ while ((newline = pending.indexOf("\n")) >= 0) {
100
+ line(pending.slice(0, newline));
101
+ pending = pending.slice(newline + 1);
102
+ }
103
+ },
104
+ end() {
105
+ if (pending) line(pending);
106
+ pending = "";
107
+ for (const restored of restorer.end()) onEvent(restored);
108
+ },
109
+ };
110
+ }
111
+
112
+ function readFrom(file, offset) {
113
+ const size = fs.statSync(file).size;
114
+ if (size <= offset) return { text: "", offset: size < offset ? 0 : offset, truncated: size < offset };
115
+ const buffer = Buffer.alloc(size - offset);
116
+ const fd = fs.openSync(file, "r");
117
+ try {
118
+ fs.readSync(fd, buffer, 0, buffer.length, offset);
119
+ } finally {
120
+ fs.closeSync(fd);
121
+ }
122
+ return { text: buffer, offset: size, truncated: false };
123
+ }
124
+
125
+ export async function main(argv = process.argv.slice(2)) {
126
+ const options = parseArgs(argv);
127
+ if (options.help || !options.target) {
128
+ console.log(USAGE);
129
+ return options.help ? 0 : 2;
130
+ }
131
+ const logPath = resolveLogPath(options.target);
132
+ const info = sessionInfo(logPath);
133
+ const cwd = options.cwd ?? info.meta?.cwd ?? process.cwd();
134
+ const runtime = await loadPiRuntime();
135
+ const settings = piSettings();
136
+ runtime.agent.initTheme(settings.theme, false);
137
+
138
+ const decoder = new TextDecoder();
139
+ if (options.print) {
140
+ const stub = { requestRender() {} };
141
+ const view = createTranscriptView({ runtime, tui: stub, cwd, hideThinkingBlock: settings.hideThinkingBlock === true });
142
+ const reader = createLogReader((event) => view.apply(event));
143
+ reader.push(decoder.decode(fs.readFileSync(logPath)));
144
+ reader.end();
145
+ const width = process.stdout.columns || 120;
146
+ process.stdout.write(`${view.container.render(width).join("\n")}\n`);
147
+ return 0;
148
+ }
149
+
150
+ const { ProcessTerminal, Text } = runtime.tui;
151
+ // Pi >= 1.5 renders regular (scrollback) mode with TuiMainScreen; older
152
+ // pi-tui releases export the TUI class itself.
153
+ const Screen = runtime.tui.TuiMainScreen ?? runtime.tui.TUI;
154
+ if (typeof Screen !== "function") throw new Error("Unsupported pi-tui: no TuiMainScreen or TUI export");
155
+ const ui = new Screen(new ProcessTerminal());
156
+ let view = createTranscriptView({ runtime, tui: ui, cwd, hideThinkingBlock: settings.hideThinkingBlock === true });
157
+ let reader = createLogReader((event) => view.apply(event));
158
+ const status = new Text("", 1, 0);
159
+ const statusLine = () => {
160
+ const state = readJson(info.statusFile)?.state ?? "unknown";
161
+ const label = info.meta?.name && info.meta.name !== info.id ? `${info.id} (${info.meta.name})` : info.id;
162
+ status.setText(
163
+ `\x1b[2m${label} · ${state} · q quit · ctrl+o ${view.expanded ? "collapse" : "expand"} tools · t thinking\x1b[0m`,
164
+ );
165
+ };
166
+ ui.addChild(view.container);
167
+ ui.addChild(status);
168
+
169
+ let offset = 0;
170
+ const poll = () => {
171
+ const chunk = readFrom(logPath, offset);
172
+ if (chunk.truncated) {
173
+ // The log was replaced; start over.
174
+ ui.removeChild(view.container);
175
+ view = createTranscriptView({ runtime, tui: ui, cwd, hideThinkingBlock: settings.hideThinkingBlock === true });
176
+ reader = createLogReader((event) => view.apply(event));
177
+ ui.children.unshift(view.container);
178
+ }
179
+ offset = chunk.offset;
180
+ if (chunk.text.length) reader.push(decoder.decode(chunk.text, { stream: true }));
181
+ statusLine();
182
+ ui.requestRender();
183
+ };
184
+
185
+ const quit = () => {
186
+ clearInterval(timer);
187
+ ui.stop();
188
+ process.exit(0);
189
+ };
190
+ // pi-tui may enable the kitty keyboard protocol, so compare parsed keys.
191
+ const key = (data, name) => runtime.tui.matchesKey?.(data, name) ?? false;
192
+ ui.addInputListener((data) => {
193
+ if (key(data, "q") || key(data, "ctrl+c") || data === "q" || data === "\x03") quit();
194
+ else if (key(data, "ctrl+o") || data === "\x0f") view.setToolsExpanded(!view.expanded);
195
+ else if (key(data, "t") || data === "t") view.toggleThinking();
196
+ else return { consume: true };
197
+ statusLine();
198
+ ui.requestRender();
199
+ return { consume: true };
200
+ });
201
+
202
+ poll();
203
+ ui.start();
204
+ const timer = setInterval(poll, 200);
205
+ return undefined;
206
+ }
207
+
208
+ const entry = process.argv[1] ? pathToFileURL(fs.realpathSync(process.argv[1])).href : undefined;
209
+ if (entry === import.meta.url) {
210
+ main().then(
211
+ (code) => {
212
+ if (typeof code === "number") process.exitCode = code;
213
+ },
214
+ (error) => {
215
+ console.error(error instanceof Error ? error.message : String(error));
216
+ process.exitCode = 1;
217
+ },
218
+ );
219
+ }