@yusukeshib/pi-babysit 0.6.36 → 0.7.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/README.md CHANGED
@@ -227,35 +227,20 @@ Set `PI_BABYSIT_ALLOW_BASH=1` only as an explicit emergency escape hatch.
227
227
 
228
228
  ### Subagent log format
229
229
 
230
- A subagent's babysit log is a subset of Pi's standard RPC event stream
231
- (`rpc-stream-format.mjs`):
232
-
233
- - The first line is `{"type":"pi_babysit_stream","version":1,"profile":"compact"}`
234
- (`"standard"` with `PI_BABYSIT_RPC_LOG_MODE=standard`).
235
- - Standard events keep their type and field meaning. The compact profile only
236
- omits fields whose value is exactly reproducible from other lines; it never
237
- reshapes a field. pi-babysit's own data uses separate `pi_babysit_*` events.
238
- - `message_update` is delta-only, as in Pi >= 1.4 (older Pi's cumulative
239
- `message` / `partial` snapshots are stripped).
240
- - Compact omissions: `message.content` / `message.details` of a non-assistant
241
- `message_start` that is immediately followed by an identical `message_end`;
242
- `result.content` / `result.details` of a non-error `tool_execution_end` (they
243
- equal the `toolResult` `message_end` with the same `toolCallId`, otherwise a
244
- `pi_babysit_tool_execution_result` event carries the original); and
245
- `turn_end.message` / `turn_end.toolResults` / `agent_end.messages` when they
246
- equal the values derived from the run's `message_end` events.
247
- - Every `agent_end` is preceded by `{"type":"pi_babysit_agent_end","parked":bool}`,
248
- which completion detection uses.
249
-
250
- `createRpcEventRestorer()` turns a log back into standard Pi events for
251
- viewers.
230
+ A subagent's babysit log is Pi's `pi --mode rpc` stdout as-is: the standard
231
+ RPC event stream (JSONL), recorded through the worker's PTY, so lines end in
232
+ `\r\n`. pi-babysit adds no records and removes no fields. Parked-turn
233
+ detection reads `agent_end.messages`.
252
234
 
253
235
  ### Subagent transcript viewer
254
236
 
255
- `view.mjs` shows a subagent the way Pi shows its own chat: it restores the log
256
- to standard events and renders them with the installed Pi's components
257
- (`AssistantMessageComponent`, `ToolExecutionComponent`, …), following the log
258
- live. The widget's copy icon on a local subagent row copies this command:
237
+ `view.mjs` shows a subagent the way Pi shows its own chat. It is a thin wrapper
238
+ around [`@yusukeshib/pi-tail`](https://github.com/yusukeshib/pi-tail), which
239
+ renders a Pi event log with the installed Pi's components
240
+ (`AssistantMessageComponent`, `ToolExecutionComponent`, …) and follows it live.
241
+ The wrapper resolves a session id, uses the worker's directory, and shows the
242
+ session state. The widget's copy icon on a local subagent row copies this
243
+ command:
259
244
 
260
245
  ```sh
261
246
  node ~/.pi/agent/npm/node_modules/@yusukeshib/pi-babysit/view.mjs <session-id | session dir | output.log>
@@ -263,16 +248,10 @@ node ~/.pi/agent/npm/node_modules/@yusukeshib/pi-babysit/view.mjs <session-id |
263
248
 
264
249
  Keys: `q` / `Ctrl-C` quit, `Ctrl-O` expand or collapse tool output, `t`
265
250
  toggle thinking blocks. `--print` renders the current transcript once to stdout;
266
- `--cwd DIR` overrides the worker directory used to shorten tool paths. Pi
267
- packages are loaded from the managed install (`~/.pi/agent/install`), the `pi`
268
- on `PATH`, or `PI_BABYSIT_PI_PACKAGE_DIR`. The viewer sets up the worker's
269
- environment the way Pi does for its directory: settings (global and, for a
270
- trusted project, project), themes from `settings.themes` and packages, terminal
271
- colors, keybindings, and the extensions' tool, message and Markdown renderers.
272
- Extensions are loaded but no session starts, so their session handlers never
273
- run; missing packages are skipped, never installed; a project that Pi has not
274
- been told to trust is loaded without its project-local resources. Live `/babysit` and attach views render either profile, as well as logs
275
- written by older pi-babysit releases.
251
+ `--cwd DIR` overrides the worker directory. Because the log is a plain Pi RPC
252
+ stream, `pi-tail <output.log>` works on it too. See the pi-tail README for how
253
+ Pi packages, settings, themes and extension renderers are loaded
254
+ (`PI_TAIL_PI_PACKAGE_DIR` overrides the Pi package directory).
276
255
 
277
256
  ## Execution timeouts
278
257
 
@@ -395,7 +374,6 @@ session totals.
395
374
  | `PI_BABYSIT_QUICK_GRACE` | `2s` | interactive process grace before a still-running command is returned as background work; use `foreground: true` to wait explicitly |
396
375
  | `PI_BABYSIT_REAP_AFTER` | `120s` | idle grace before a finished subagent self-exits (`off`/`none`/`0` disables) |
397
376
  | `PI_BABYSIT_BUDGET_GRACE` | `90s` | grace after a subagent budget is exceeded before verified termination |
398
- | `PI_BABYSIT_RPC_LOG_MODE` | `compact` | `compact` omits reproducible duplicate RPC payloads; `standard` records Pi's events unchanged (see Subagent log format) |
399
377
  | `PI_BABYSIT_RETENTION_DAYS` | `3` | at most once per day, remove safe terminal roots older than this (in a background child process, so session start never waits); set `0` to disable automatic retention |
400
378
  | `PI_BABYSIT_TAIL_MAX_BYTES` | `4000` | default cap for explicit log tails/screens returned by `babysit_check`; override per call with `maxBytes` |
401
379
  | `PI_BABYSIT_INLINE_OUTPUT_MAX_BYTES` | `8000` | cap for complete process output and aggregate multi-wait results |
package/format-stream.mjs CHANGED
@@ -3,8 +3,8 @@
3
3
  * format-stream.mjs — human-readable view for a `pi --mode rpc` event stream.
4
4
  *
5
5
  * This filter sits on the interactive attach path via `babysit run --view-cmd`.
6
- * It accepts both Pi's raw cumulative updates and pi-babysit's compact deltas,
7
- * then prints a colored, incrementally streamed transcript so a human sees
6
+ * It accepts delta-only `message_update` events (Pi >= 0.84) as well as older
7
+ * cumulative snapshots, then prints a colored, incrementally streamed transcript so a human sees
8
8
  * turns, thinking, tool calls and answers instead of a JSON firehose.
9
9
  */
10
10
  import * as readline from "node:readline";
@@ -51,8 +51,8 @@ function summarizeTool(name, a = {}) {
51
51
  }
52
52
 
53
53
  // Join the text of a given block kind ("text" or "thinking") in a message's
54
- // content array. Unfiltered RPC streams repeat the whole growing message;
55
- // pi-babysit's compact stream instead retains only assistantMessageEvent.delta.
54
+ // content array. Pi < 0.84 repeated the whole growing message on every update;
55
+ // newer releases send only assistantMessageEvent.delta.
56
56
  function blockText(content, kind) {
57
57
  if (!Array.isArray(content)) return "";
58
58
  let s = "";
package/index.ts CHANGED
@@ -160,10 +160,9 @@ export function planSubagentSpawn(
160
160
  // apart from any other turn end (see isParkedMessages / self-reap.ts).
161
161
  export const NOTIFY_MARKER = "[notify-on-exit]";
162
162
 
163
- // Human-readable view for the compact subagent JSONL stream when a human
164
- // attaches. The RPC proxy removes cumulative streaming snapshots before both
165
- // recording and display; authoritative events remain intact for parsers. Set
166
- // PI_BABYSIT_VIEW_CMD="" to disable formatting, or provide a custom command.
163
+ // Human-readable view for the subagent's Pi RPC event stream when a human
164
+ // attaches. Set PI_BABYSIT_VIEW_CMD="" to disable formatting, or provide a
165
+ // custom command.
167
166
  const EXT_DIR = path.dirname(fileURLToPath(import.meta.url));
168
167
  const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
169
168
  const VIEW_CMD =
@@ -1960,22 +1959,12 @@ function parseEventLine(progress: Progress, raw: string): void {
1960
1959
  case "agent_start":
1961
1960
  progress.agentStarts++;
1962
1961
  break;
1963
- // The compact log precedes every agent_end with this marker and may omit
1964
- // agent_end.messages (see rpc-stream-format.mjs).
1965
- case "pi_babysit_agent_end":
1966
- if (typeof event.parked === "boolean") progress.lastEndWasProcessWait = event.parked;
1967
- break;
1968
- case "agent_end": {
1962
+ case "agent_end":
1969
1963
  progress.agentEnds++;
1970
- if (typeof event.piBabysitParked === "boolean") {
1971
- // Logs written by pi-babysit <= 0.6.32.
1972
- progress.lastEndWasProcessWait = event.piBabysitParked;
1973
- } else if (Array.isArray(event.messages)) {
1974
- progress.lastEndWasProcessWait = isParkedMessages(event.messages as ParkedMessage[]);
1975
- }
1976
- // Otherwise keep the value from the preceding pi_babysit_agent_end marker.
1964
+ progress.lastEndWasProcessWait = isParkedMessages(
1965
+ Array.isArray(event.messages) ? (event.messages as ParkedMessage[]) : undefined,
1966
+ );
1977
1967
  break;
1978
- }
1979
1968
  case "agent_settled":
1980
1969
  progress.agentSettled++;
1981
1970
  break;
@@ -2378,9 +2367,8 @@ async function spawnSubagent(
2378
2367
  "--timeout",
2379
2368
  opts.timeout,
2380
2369
  ];
2381
- // Pretty-print the JSONL stream for humans who `attach`. The RPC proxy
2382
- // writes a standard-event subset that omits only reproducible duplicate
2383
- // payloads (rpc-stream-format.mjs); parseEvents accepts every log format.
2370
+ // Pretty-print the JSONL stream for humans who `attach`. The log is Pi's
2371
+ // RPC event stream as-is.
2384
2372
  if (VIEW_CMD.trim()) bsArgs.push("--view-cmd", VIEW_CMD);
2385
2373
  if (opts.idleTimeout && opts.idleTimeout !== "none") {
2386
2374
  bsArgs.push("--idle-timeout", opts.idleTimeout);
@@ -2388,9 +2376,6 @@ async function spawnSubagent(
2388
2376
  const reservedId = opts.name ? await reserveUniqueSessionId(opts.name) : undefined;
2389
2377
  if (reservedId) bsArgs.push("--id", reservedId);
2390
2378
  bsArgs.push(
2391
- "--",
2392
- process.execPath,
2393
- path.join(EXT_DIR, "rpc-stream-proxy.mjs"),
2394
2379
  "--",
2395
2380
  PI_BIN,
2396
2381
  ...piArgs,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yusukeshib/pi-babysit",
3
- "version": "0.6.36",
3
+ "version": "0.7.0",
4
4
  "description": "Run any shell command and pi subagents under babysit, with context-safe captured output.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -23,11 +23,6 @@
23
23
  "agents.ts",
24
24
  "self-reap.ts",
25
25
  "format-stream.mjs",
26
- "rpc-stream-proxy.mjs",
27
- "rpc-stream-format.mjs",
28
- "transcript-view.mjs",
29
- "pi-runtime.mjs",
30
- "pi-environment.mjs",
31
26
  "view.mjs",
32
27
  "search-log.mjs",
33
28
  "gc.mjs",
@@ -44,6 +39,9 @@
44
39
  "./index.ts"
45
40
  ]
46
41
  },
42
+ "dependencies": {
43
+ "@yusukeshib/pi-tail": "^0.1.0"
44
+ },
47
45
  "peerDependencies": {
48
46
  "@earendil-works/pi-ai": "*",
49
47
  "@earendil-works/pi-coding-agent": ">=1.0.0",
package/view.mjs CHANGED
@@ -1,37 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * view.mjs — live, read-only view of a pi-babysit subagent rendered with Pi's
4
- * own TUI components.
3
+ * view.mjs — live, read-only view of a pi-babysit subagent, rendered by
4
+ * @yusukeshib/pi-tail with Pi's own TUI components.
5
5
  *
6
6
  * node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]
7
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.
8
+ * A subagent log is Pi's `pi --mode rpc` event stream. This wrapper resolves
9
+ * the session, uses the worker's directory, and shows the session state.
11
10
  */
12
11
  import fs from "node:fs";
13
12
  import os from "node:os";
14
13
  import path from "node:path";
15
14
  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";
15
+ import { parseArgs, runCli, runViewer } from "@yusukeshib/pi-tail";
20
16
 
21
- const USAGE = "Usage: node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]";
17
+ export { parseArgs };
22
18
 
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
- }
19
+ const USAGE = "Usage: node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]";
35
20
 
36
21
  /** Resolve a session id, session directory, or log path to the log file. */
37
22
  export function resolveLogPath(target, rootBase = process.env.PI_BABYSIT_DIR ?? path.join(os.homedir(), ".pi-babysit")) {
@@ -73,161 +58,22 @@ function sessionInfo(logPath) {
73
58
  };
74
59
  }
75
60
 
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
61
  export async function main(argv = process.argv.slice(2)) {
122
62
  const options = parseArgs(argv);
123
63
  if (options.help || !options.target) {
124
64
  console.log(USAGE);
125
65
  return options.help ? 0 : 2;
126
66
  }
127
- const logPath = resolveLogPath(options.target);
128
- const info = sessionInfo(logPath);
129
- const cwd = options.cwd ?? info.meta?.cwd ?? process.cwd();
130
- const runtime = await loadPiRuntime();
131
- // The worker's settings, themes and extension renderers, as Pi loads them for its cwd.
132
- const environment = await loadPiEnvironment(runtime, { cwd });
133
- applyTerminalSettings(runtime, environment);
134
- const newView = (tui) => createTranscriptView({ runtime, tui, cwd, render: environment.render });
135
-
136
- const decoder = new TextDecoder();
137
- if (options.print) {
138
- initPiTheme(runtime, environment);
139
- for (const message of environment.diagnostics) process.stderr.write(`${message}\n`);
140
- const view = newView({ requestRender() {} });
141
- const reader = createLogReader((event) => view.apply(event));
142
- reader.push(decoder.decode(fs.readFileSync(logPath)));
143
- reader.end();
144
- const width = process.stdout.columns || 120;
145
- await new Promise((resolve) => process.stdout.write(`${view.container.render(width).join("\n")}\n`, resolve));
146
- return 0;
147
- }
148
-
149
- const { Container, ProcessTerminal, Spacer, Text } = runtime.tui;
150
- // Pi >= 1.5 renders regular (scrollback) mode with TuiMainScreen; older
151
- // pi-tui releases export the TUI class itself.
152
- const Screen = runtime.tui.TuiMainScreen ?? runtime.tui.TUI;
153
- if (typeof Screen !== "function") throw new Error("Unsupported pi-tui: no TuiMainScreen or TUI export");
154
- const settingsManager = environment.settingsManager;
155
- const ui = new Screen(
156
- new ProcessTerminal(),
157
- settingsManager?.getShowHardwareCursor?.(),
158
- runtime.agent.getAgentDir?.(),
159
- );
160
- if (settingsManager?.getClearOnShrink) ui.setClearOnShrink?.(settingsManager.getClearOnShrink());
161
- const theme = initPiTheme(runtime, environment, ui);
162
- if (environment.diagnostics.length > 0) {
163
- const diagnostics = new Container();
164
- for (const message of environment.diagnostics) diagnostics.addChild(new Text(`\x1b[31m${message}\x1b[0m`, 1, 0));
165
- diagnostics.addChild(new Spacer(1));
166
- ui.addChild(diagnostics);
167
- }
168
- let view = newView(ui);
169
- let reader = createLogReader((event) => view.apply(event));
170
- const status = new Text("", 1, 0);
171
- const statusLine = () => {
172
- const state = readJson(info.statusFile)?.state ?? "unknown";
173
- const label = info.meta?.name && info.meta.name !== info.id ? `${info.id} (${info.meta.name})` : info.id;
174
- status.setText(
175
- `\x1b[2m${label} · ${state} · q quit · ctrl+o ${view.expanded ? "collapse" : "expand"} tools · t thinking\x1b[0m`,
176
- );
177
- };
178
- ui.addChild(view.container);
179
- ui.addChild(status);
180
-
181
- let offset = 0;
182
- const poll = () => {
183
- const chunk = readFrom(logPath, offset);
184
- if (chunk.truncated) {
185
- // The log was replaced; start over.
186
- const index = ui.children.indexOf(view.container);
187
- view = newView(ui);
188
- reader = createLogReader((event) => view.apply(event));
189
- ui.children.splice(index, 1, view.container);
190
- }
191
- offset = chunk.offset;
192
- if (chunk.text.length) reader.push(decoder.decode(chunk.text, { stream: true }));
193
- statusLine();
194
- ui.requestRender();
195
- };
196
-
197
- const quit = () => {
198
- clearInterval(timer);
199
- ui.stop();
200
- process.exit(0);
201
- };
202
- // pi-tui may enable the kitty keyboard protocol, so compare parsed keys.
203
- const key = (data, name) => runtime.tui.matchesKey?.(data, name) ?? false;
204
- ui.addInputListener((data) => {
205
- if (key(data, "q") || key(data, "ctrl+c") || data === "q" || data === "\x03") quit();
206
- else if (key(data, "ctrl+o") || data === "\x0f") view.setToolsExpanded(!view.expanded);
207
- else if (key(data, "t") || data === "t") view.toggleThinking();
208
- else return { consume: true };
209
- statusLine();
210
- ui.requestRender();
211
- return { consume: true };
67
+ const file = resolveLogPath(options.target);
68
+ const info = sessionInfo(file);
69
+ const label = info.meta?.name && info.meta.name !== info.id ? `${info.id} (${info.meta.name})` : info.id;
70
+ return runViewer({
71
+ file,
72
+ cwd: options.cwd ?? info.meta?.cwd ?? process.cwd(),
73
+ print: options.print,
74
+ status: () => `${label} · ${readJson(info.statusFile)?.state ?? "unknown"}`,
212
75
  });
213
-
214
- poll();
215
- ui.start();
216
- theme.start();
217
- const timer = setInterval(poll, 200);
218
- return undefined;
219
76
  }
220
77
 
221
78
  const entry = process.argv[1] ? pathToFileURL(fs.realpathSync(process.argv[1])).href : undefined;
222
- if (entry === import.meta.url) {
223
- main().then(
224
- (code) => {
225
- // Loaded extensions may keep timers alive; a finished one-shot run exits.
226
- if (typeof code === "number") process.exit(code);
227
- },
228
- (error) => {
229
- console.error(error instanceof Error ? error.message : String(error));
230
- process.exit(1);
231
- },
232
- );
233
- }
79
+ if (entry === import.meta.url) runCli(main);
@@ -1,176 +0,0 @@
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
- }