@yusukeshib/pi-babysit 0.6.37 → 0.8.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.
@@ -1,324 +0,0 @@
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
- }
package/view.mjs DELETED
@@ -1,248 +0,0 @@
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 { applyTerminalSettings, initPiTheme, loadPiEnvironment } from "./pi-environment.mjs";
17
- import { loadPiRuntime } from "./pi-runtime.mjs";
18
- import { createRpcEventRestorer } from "./rpc-stream-format.mjs";
19
- import { createTranscriptView } from "./transcript-view.mjs";
20
-
21
- const USAGE = "Usage: node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]";
22
-
23
- export function parseArgs(argv) {
24
- const options = { print: false, cwd: undefined, target: undefined };
25
- for (let index = 0; index < argv.length; index++) {
26
- const arg = argv[index];
27
- if (arg === "--print") options.print = true;
28
- else if (arg === "--cwd") options.cwd = argv[++index];
29
- else if (arg === "-h" || arg === "--help") options.help = true;
30
- else if (!options.target) options.target = arg;
31
- else throw new Error(`Unexpected argument: ${arg}`);
32
- }
33
- return options;
34
- }
35
-
36
- /** Resolve a session id, session directory, or log path to the log file. */
37
- export function resolveLogPath(target, rootBase = process.env.PI_BABYSIT_DIR ?? path.join(os.homedir(), ".pi-babysit")) {
38
- if (fs.existsSync(target)) {
39
- const stat = fs.statSync(target);
40
- return stat.isDirectory() ? path.join(target, "output.log") : target;
41
- }
42
- let best;
43
- for (const root of fs.existsSync(rootBase) ? fs.readdirSync(rootBase) : []) {
44
- const log = path.join(rootBase, root, "sessions", target, "output.log");
45
- try {
46
- const mtime = fs.statSync(log).mtimeMs;
47
- if (!best || mtime > best.mtime) best = { log, mtime };
48
- } catch {
49
- /* not in this root */
50
- }
51
- }
52
- if (!best) throw new Error(`No babysit session log found for ${target} under ${rootBase}`);
53
- return best.log;
54
- }
55
-
56
- function readJson(file) {
57
- try {
58
- return JSON.parse(fs.readFileSync(file, "utf8"));
59
- } catch {
60
- return undefined;
61
- }
62
- }
63
-
64
- /** pi-babysit's own metadata for a session log (<root>/meta/<id>.json). */
65
- function sessionInfo(logPath) {
66
- const sessionDir = path.dirname(logPath);
67
- const id = path.basename(sessionDir);
68
- const root = path.dirname(path.dirname(sessionDir));
69
- return {
70
- id,
71
- meta: readJson(path.join(root, "meta", `${id}.json`)),
72
- statusFile: path.join(sessionDir, "status.json"),
73
- };
74
- }
75
-
76
- /** Incremental JSONL reader: feed bytes, get complete event objects. */
77
- export function createLogReader(onEvent) {
78
- const restorer = createRpcEventRestorer();
79
- let pending = "";
80
- const line = (raw) => {
81
- const text = raw.replace(/\r$/, "").trim();
82
- if (!text.startsWith("{")) return;
83
- let event;
84
- try {
85
- event = JSON.parse(text);
86
- } catch {
87
- return;
88
- }
89
- for (const restored of restorer.push(event)) onEvent(restored);
90
- };
91
- return {
92
- push(chunk) {
93
- pending += chunk;
94
- let newline;
95
- while ((newline = pending.indexOf("\n")) >= 0) {
96
- line(pending.slice(0, newline));
97
- pending = pending.slice(newline + 1);
98
- }
99
- },
100
- end() {
101
- if (pending) line(pending);
102
- pending = "";
103
- for (const restored of restorer.end()) onEvent(restored);
104
- },
105
- };
106
- }
107
-
108
- function readFrom(file, offset) {
109
- const size = fs.statSync(file).size;
110
- if (size <= offset) return { text: "", offset: size < offset ? 0 : offset, truncated: size < offset };
111
- const buffer = Buffer.alloc(size - offset);
112
- const fd = fs.openSync(file, "r");
113
- try {
114
- fs.readSync(fd, buffer, 0, buffer.length, offset);
115
- } finally {
116
- fs.closeSync(fd);
117
- }
118
- return { text: buffer, offset: size, truncated: false };
119
- }
120
-
121
- export function createViewerInputListener({ tui, getView, quit, onChange }) {
122
- const key = (data, name) => tui.matchesKey?.(data, name) ?? false;
123
- return (data) => {
124
- // Input listeners run before Pi's focused-component key-release filter.
125
- // Toggle once per press, not again on release or while holding the key.
126
- if (tui.isKeyRelease?.(data) || tui.isKeyRepeat?.(data)) return { consume: true };
127
- if (key(data, "q") || key(data, "ctrl+c") || data === "q" || data === "\x03") quit();
128
- else if (key(data, "ctrl+o") || data === "\x0f") {
129
- const view = getView();
130
- view.setToolsExpanded(!view.expanded);
131
- } else if (key(data, "t") || data === "t") getView().toggleThinking();
132
- else return { consume: true };
133
- onChange();
134
- return { consume: true };
135
- };
136
- }
137
-
138
- export async function main(argv = process.argv.slice(2)) {
139
- const options = parseArgs(argv);
140
- if (options.help || !options.target) {
141
- console.log(USAGE);
142
- return options.help ? 0 : 2;
143
- }
144
- const logPath = resolveLogPath(options.target);
145
- const info = sessionInfo(logPath);
146
- const cwd = options.cwd ?? info.meta?.cwd ?? process.cwd();
147
- const runtime = await loadPiRuntime();
148
- // The worker's settings, themes and extension renderers, as Pi loads them for its cwd.
149
- const environment = await loadPiEnvironment(runtime, { cwd });
150
- applyTerminalSettings(runtime, environment);
151
- const newView = (tui) => createTranscriptView({ runtime, tui, cwd, render: environment.render });
152
-
153
- const decoder = new TextDecoder();
154
- if (options.print) {
155
- initPiTheme(runtime, environment);
156
- for (const message of environment.diagnostics) process.stderr.write(`${message}\n`);
157
- const view = newView({ requestRender() {} });
158
- const reader = createLogReader((event) => view.apply(event));
159
- reader.push(decoder.decode(fs.readFileSync(logPath)));
160
- reader.end();
161
- const width = process.stdout.columns || 120;
162
- await new Promise((resolve) => process.stdout.write(`${view.container.render(width).join("\n")}\n`, resolve));
163
- return 0;
164
- }
165
-
166
- const { Container, ProcessTerminal, Spacer, Text } = runtime.tui;
167
- // Pi >= 1.5 renders regular (scrollback) mode with TuiMainScreen; older
168
- // pi-tui releases export the TUI class itself.
169
- const Screen = runtime.tui.TuiMainScreen ?? runtime.tui.TUI;
170
- if (typeof Screen !== "function") throw new Error("Unsupported pi-tui: no TuiMainScreen or TUI export");
171
- const settingsManager = environment.settingsManager;
172
- const ui = new Screen(
173
- new ProcessTerminal(),
174
- settingsManager?.getShowHardwareCursor?.(),
175
- runtime.agent.getAgentDir?.(),
176
- );
177
- if (settingsManager?.getClearOnShrink) ui.setClearOnShrink?.(settingsManager.getClearOnShrink());
178
- const theme = initPiTheme(runtime, environment, ui);
179
- if (environment.diagnostics.length > 0) {
180
- const diagnostics = new Container();
181
- for (const message of environment.diagnostics) diagnostics.addChild(new Text(`\x1b[31m${message}\x1b[0m`, 1, 0));
182
- diagnostics.addChild(new Spacer(1));
183
- ui.addChild(diagnostics);
184
- }
185
- let view = newView(ui);
186
- let reader = createLogReader((event) => view.apply(event));
187
- const status = new Text("", 1, 0);
188
- const statusLine = () => {
189
- const state = readJson(info.statusFile)?.state ?? "unknown";
190
- const label = info.meta?.name && info.meta.name !== info.id ? `${info.id} (${info.meta.name})` : info.id;
191
- status.setText(
192
- `\x1b[2m${label} · ${state} · q quit · ctrl+o ${view.expanded ? "collapse" : "expand"} tools · t thinking\x1b[0m`,
193
- );
194
- };
195
- ui.addChild(view.container);
196
- ui.addChild(status);
197
-
198
- let offset = 0;
199
- const poll = () => {
200
- const chunk = readFrom(logPath, offset);
201
- if (chunk.truncated) {
202
- // The log was replaced; start over.
203
- const index = ui.children.indexOf(view.container);
204
- view = newView(ui);
205
- reader = createLogReader((event) => view.apply(event));
206
- ui.children.splice(index, 1, view.container);
207
- }
208
- offset = chunk.offset;
209
- if (chunk.text.length) reader.push(decoder.decode(chunk.text, { stream: true }));
210
- statusLine();
211
- ui.requestRender();
212
- };
213
-
214
- const quit = () => {
215
- clearInterval(timer);
216
- ui.stop();
217
- process.exit(0);
218
- };
219
- ui.addInputListener(createViewerInputListener({
220
- tui: runtime.tui,
221
- getView: () => view,
222
- quit,
223
- onChange() {
224
- statusLine();
225
- ui.requestRender();
226
- },
227
- }));
228
-
229
- poll();
230
- ui.start();
231
- theme.start();
232
- const timer = setInterval(poll, 200);
233
- return undefined;
234
- }
235
-
236
- const entry = process.argv[1] ? pathToFileURL(fs.realpathSync(process.argv[1])).href : undefined;
237
- if (entry === import.meta.url) {
238
- main().then(
239
- (code) => {
240
- // Loaded extensions may keep timers alive; a finished one-shot run exits.
241
- if (typeof code === "number") process.exit(code);
242
- },
243
- (error) => {
244
- console.error(error instanceof Error ? error.message : String(error));
245
- process.exit(1);
246
- },
247
- );
248
- }