@yusukeshib/pi-babysit 0.6.34 → 0.6.36

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
@@ -86,7 +86,7 @@ Descriptions are display metadata, not shell code, stdin, or instructions sent
86
86
  to the subagent.
87
87
 
88
88
  ```text
89
- babysit_run { description: "Run regression tests", command: "bun test", foreground: true }
89
+ babysit_run { description: "Run regression tests", command: "bun test", foreground: true, timeout: "10m" }
90
90
  babysit_run { description: "Review the authentication changes", profile: "subagent", task: "Review the authentication diff for security regressions", maxTurns: 5 }
91
91
  babysit_check { description: "Inspect build errors", id: "build", pattern: "ERROR" }
92
92
  babysit_wait { description: "Wait for the build to finish", id: "build" }
@@ -112,8 +112,8 @@ SSH aliases, keys, known hosts, and ProxyJump are handled by babysit/SSH;
112
112
  pi-babysit does not install remote software or copy credentials.
113
113
 
114
114
  ```text
115
- babysit_run { description: "Run tests on Linux", host: "yusuke-t4", cwd: "/home/yusuke/project", command: "bun test", foreground: true, returnLines: 30 }
116
- babysit_run { description: "Open a remote Python REPL", host: "user@server", command: "python3 -i", name: "remote-repl", continueAfterStart: true }
115
+ babysit_run { description: "Run tests on Linux", host: "yusuke-t4", cwd: "/home/yusuke/project", command: "bun test", foreground: true, timeout: "10m", returnLines: 30 }
116
+ babysit_run { description: "Open a remote Python REPL", host: "user@server", command: "python3 -i", name: "remote-repl", timeout: "none", continueAfterStart: true }
117
117
  babysit_check { description: "Read the remote REPL screen", id: "remote-repl", screen: true }
118
118
  babysit_send { description: "Evaluate a value in the remote REPL", id: "remote-repl", text: "print(42)" }
119
119
  babysit_kill { description: "Close the remote REPL", id: "remote-repl" }
@@ -265,10 +265,41 @@ Keys: `q` / `Ctrl-C` quit, `Ctrl-O` expand or collapse tool output, `t`
265
265
  toggle thinking blocks. `--print` renders the current transcript once to stdout;
266
266
  `--cwd DIR` overrides the worker directory used to shorten tool paths. Pi
267
267
  packages are loaded from the managed install (`~/.pi/agent/install`), the `pi`
268
- on `PATH`, or `PI_BABYSIT_PI_PACKAGE_DIR`. Built-in tools use Pi's renderers;
269
- extension tools fall back to generic rendering. Live `/babysit` and attach views render either profile, as well as logs
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
270
275
  written by older pi-babysit releases.
271
276
 
277
+ ## Execution timeouts
278
+
279
+ Commands default to an absolute **60s execution timeout**, in both foreground
280
+ and background mode, locally and over SSH. Subagents retain their **15m**
281
+ default. The babysit supervisor terminates the process when its deadline is
282
+ reached; a foreground call then returns the terminal result to the agent rather
283
+ than waiting forever. This is an execution limit, not an output-inactivity
284
+ limit or the quick-command background grace period.
285
+
286
+ Set a longer positive duration explicitly for slow work. Only an explicit
287
+ `timeout: "none"` disables the deadline, and only for background runs in
288
+ interactive/RPC mode. It is rejected with `foreground: true` or in non-interactive
289
+ mode, which always waits inline. Empty strings, zero durations, `off`, and
290
+ `never` are rejected rather than forwarded as babysit's infinite-timeout aliases.
291
+
292
+ ```text
293
+ babysit_run { description: "Run a long test suite", command: "bun test", foreground: true, timeout: "10m" }
294
+ babysit_run { description: "Start the development server", command: "bun run dev", name: "dev-server", timeout: "none", continueAfterStart: true }
295
+ ```
296
+
297
+ `idleTimeout` remains disabled by default: a silent command is not necessarily
298
+ stuck. `babysit_wait.timeout` limits only that wait, not the underlying process,
299
+ and its default remains unlimited; the process's execution timeout still applies.
300
+ To wait for readiness of an intentionally unbounded server, set a finite wait
301
+ such as `babysit_wait { description: "Wait for server readiness", id: "dev-server", expect: "listening", timeout: "15s" }`.
302
+
272
303
  ## Process ownership, interruption, shutdown, and reload
273
304
 
274
305
  An inline process wait (`foreground: true`, or process execution in a non-UI
package/index.ts CHANGED
@@ -2131,6 +2131,28 @@ async function reserveUniqueSessionId(name: string): Promise<string> {
2131
2131
  return id;
2132
2132
  }
2133
2133
 
2134
+ /** Resolve a bounded execution deadline before invoking the supervisor. */
2135
+ export function resolveRunTimeout(timeout: string | undefined, isSubagent: boolean, waitsInline: boolean): string {
2136
+ const value = timeout === undefined ? (isSubagent ? "15m" : "60s") : timeout.trim().toLowerCase();
2137
+ if (value === "none") {
2138
+ if (waitsInline) {
2139
+ throw new Error('timeout: "none" requires a background run; foreground and non-interactive runs need a finite timeout.');
2140
+ }
2141
+ return value;
2142
+ }
2143
+ // babysit also accepts empty/zero/off/never as infinite deadlines. Do not
2144
+ // forward those aliases: unbounded execution must be an explicit "none".
2145
+ const match = /^(\d+)\s*(ms|s|m|h|d)?$/.exec(value);
2146
+ const amount = match ? Number(match[1]) : NaN;
2147
+ const unit = match?.[2] ?? "s";
2148
+ const multipliers: Record<string, number> = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 };
2149
+ const multiplier = multipliers[unit]!;
2150
+ if (!Number.isSafeInteger(amount * multiplier) || amount <= 0) {
2151
+ throw new Error('Invalid timeout: use a positive duration (e.g. "60s", "10m") or explicit "none" for a background run.');
2152
+ }
2153
+ return `${amount}${unit}`;
2154
+ }
2155
+
2134
2156
  interface ProcOpts {
2135
2157
  description: string;
2136
2158
  name?: string;
@@ -2138,7 +2160,7 @@ interface ProcOpts {
2138
2160
  cwd?: string;
2139
2161
  host?: string;
2140
2162
  env?: Record<string, string | undefined>;
2141
- timeout?: string; // default: none — dev servers may run indefinitely
2163
+ timeout: string; // resolved to 60s unless explicitly overridden
2142
2164
  idleTimeout?: string;
2143
2165
  pty: boolean;
2144
2166
  notificationGroup?: string;
@@ -2179,7 +2201,7 @@ async function spawnProcess(opts: ProcOpts): Promise<{ id: string } | { error: s
2179
2201
  const remote = !!opts.host && opts.host !== "local";
2180
2202
  const bsArgs = ["run", "-d", "--json", "--size", "120x40"];
2181
2203
  if (!opts.pty) bsArgs.push("--no-tty");
2182
- if (opts.timeout && opts.timeout !== "none") bsArgs.push("--timeout", opts.timeout);
2204
+ if (opts.timeout !== "none") bsArgs.push("--timeout", opts.timeout);
2183
2205
  if (opts.idleTimeout && opts.idleTimeout !== "none")
2184
2206
  bsArgs.push("--idle-timeout", opts.idleTimeout);
2185
2207
  const reservedId = remote ? await reserveUniqueSessionId(opts.name ?? "remote-proc") : opts.name ? await reserveUniqueSessionId(opts.name) : undefined;
@@ -3908,6 +3930,7 @@ export default function (pi: ExtensionAPI) {
3908
3930
  promptSnippet: "Run supervised commands or bounded pi subagents with context-safe logs",
3909
3931
  promptGuidelines: [
3910
3932
  "Use babysit_run for shell commands and give meaningful sessions a stable name; bundle tiny related read-only observations into one command.",
3933
+ "babysit_run commands default to a 60s execution timeout (subagents: 15m). Set a longer timeout for long-running work; timeout: none is allowed only for explicit background runs, never foreground or non-interactive runs.",
3911
3934
  "Use babysit_run foreground mode for one process or subagent whose result is needed now; never issue sibling foreground runs in parallel. For parallel process checks, start background runs with continueAfterStart and collect them with one multi-session babysit_wait.",
3912
3935
  "Use returnPattern/returnLines for noisy commands. During edit/fix loops run targeted checks first and one full validation suite at the end instead of repeating every full gate.",
3913
3936
  "After a background process starts, stop the turn for its automatic notification; never poll or sleep. Use continueAfterStart only for specific non-polling process work.",
@@ -3991,7 +4014,7 @@ export default function (pi: ExtensionAPI) {
3991
4014
  timeout: Type.Optional(
3992
4015
  Type.String({
3993
4016
  description:
3994
- "Absolute auto-kill after this long (e.g. 30m). Default: none for processes (dev servers may run forever), 15m for subagents. 'none' disables.",
4017
+ "Absolute auto-kill after a positive duration (e.g. 60s, 10m). Default: 60s for processes, 15m for subagents. Explicit 'none' disables only for background runs; forbidden with foreground or in non-interactive mode. Zero/empty/off/never are invalid.",
3995
4018
  }),
3996
4019
  ),
3997
4020
  reapAfter: Type.Optional(
@@ -4053,8 +4076,10 @@ export default function (pi: ExtensionAPI) {
4053
4076
  }),
4054
4077
  async execute(_id, params, _signal, _onUpdate, ctx) {
4055
4078
  const description = params.description.trim();
4056
- await requireBabysit();
4057
4079
  const isSubagent = params.profile === "subagent";
4080
+ const waitsInline = !ctx.hasUI || params.foreground === true;
4081
+ const timeout = resolveRunTimeout(params.timeout, isSubagent, waitsInline);
4082
+ await requireBabysit();
4058
4083
  validateProcessHost(params.host);
4059
4084
  if (isSubagent && (params.cwd !== undefined || (params.host && params.host !== "local"))) throw new Error("host/cwd are process-only options; remote subagents are not supported.");
4060
4085
  if (params.host && params.host !== "local" && params.retryOnWorkerDeath) throw new Error("Remote automatic launch retries are unsupported; reconcile the tracked session explicitly.");
@@ -4142,7 +4167,6 @@ export default function (pi: ExtensionAPI) {
4142
4167
 
4143
4168
  // --- process mode ---
4144
4169
  if (!isSubagent) {
4145
- const waitsInline = !ctx.hasUI || params.foreground === true;
4146
4170
  const lifecycle = resolveProcessLifecycle(params.lifecycle, waitsInline);
4147
4171
  if (params.returnPattern) {
4148
4172
  try {
@@ -4165,7 +4189,7 @@ export default function (pi: ExtensionAPI) {
4165
4189
  command: params.command as string,
4166
4190
  host: params.host,
4167
4191
  cwd: params.cwd ?? (params.host && params.host !== "local" ? undefined : ctx.cwd),
4168
- timeout: params.timeout,
4192
+ timeout,
4169
4193
  idleTimeout: params.idleTimeout,
4170
4194
  pty: params.pty ?? true,
4171
4195
  env: processSessionEnvironment(ctx, pi.getThinkingLevel()),
@@ -4330,7 +4354,7 @@ export default function (pi: ExtensionAPI) {
4330
4354
  }
4331
4355
  : undefined,
4332
4356
  reapAfter: params.reapAfter,
4333
- timeout: params.timeout ?? "15m",
4357
+ timeout,
4334
4358
  idleTimeout: params.idleTimeout,
4335
4359
  });
4336
4360
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yusukeshib/pi-babysit",
3
- "version": "0.6.34",
3
+ "version": "0.6.36",
4
4
  "description": "Run any shell command and pi subagents under babysit, with context-safe captured output.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -27,6 +27,7 @@
27
27
  "rpc-stream-format.mjs",
28
28
  "transcript-view.mjs",
29
29
  "pi-runtime.mjs",
30
+ "pi-environment.mjs",
30
31
  "view.mjs",
31
32
  "search-log.mjs",
32
33
  "gc.mjs",
@@ -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 CHANGED
@@ -67,32 +67,54 @@ function siblingPackageEntry(agentDir, name) {
67
67
  }
68
68
 
69
69
  /**
70
- * Load { agent, tui, withBuiltInRenderers, packageDir, version }.
71
- * withBuiltInRenderers is optional (an internal module of pi-coding-agent).
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.
72
99
  */
73
100
  export async function loadPiRuntime() {
74
101
  const packageDir = findPiPackageDir();
75
102
  let agent;
76
103
  let tui;
77
- let withBuiltInRenderers;
78
104
  let version;
105
+ const internal = {};
79
106
  if (packageDir) {
80
107
  const pkg = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
81
108
  version = pkg.version;
82
109
  agent = await import(pathToFileURL(path.join(packageDir, pkg.exports?.["."]?.import ?? "dist/index.js")).href);
83
110
  const tuiEntry = siblingPackageEntry(packageDir, "pi-tui");
84
111
  tui = await import(tuiEntry ?? "@earendil-works/pi-tui");
85
- try {
86
- const renderers = await import(
87
- pathToFileURL(path.join(packageDir, "dist", "core", "tools", "renderers", "index.js")).href
88
- );
89
- withBuiltInRenderers = renderers.withBuiltInRenderers;
90
- } catch {
91
- /* generic tool rendering */
112
+ for (const [key, relativePath] of Object.entries(INTERNAL_MODULES)) {
113
+ internal[key] = await importInternal(packageDir, relativePath);
92
114
  }
93
115
  } else {
94
116
  agent = await import(AGENT_PACKAGE);
95
117
  tui = await import("@earendil-works/pi-tui");
96
118
  }
97
- return { agent, tui, withBuiltInRenderers, packageDir, version };
119
+ return { agent, tui, withBuiltInRenderers: internal.renderers?.withBuiltInRenderers, internal, packageDir, version };
98
120
  }
@@ -60,7 +60,24 @@ export function applyAssistantDelta(message, update) {
60
60
  }
61
61
  }
62
62
 
63
- export function createTranscriptView({ runtime, tui, cwd = process.cwd(), hideThinkingBlock = false }) {
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) }) {
64
81
  const {
65
82
  AssistantMessageComponent,
66
83
  ToolExecutionComponent,
@@ -68,7 +85,8 @@ export function createTranscriptView({ runtime, tui, cwd = process.cwd(), hideTh
68
85
  CustomMessageComponent,
69
86
  CompactionSummaryMessageComponent,
70
87
  BranchSummaryMessageComponent,
71
- getMarkdownTheme,
88
+ SkillInvocationMessageComponent,
89
+ parseSkillBlock,
72
90
  } = runtime.agent;
73
91
  const { Container, Spacer, Text } = runtime.tui;
74
92
 
@@ -77,11 +95,14 @@ export function createTranscriptView({ runtime, tui, cwd = process.cwd(), hideTh
77
95
  const expandables = [];
78
96
  const assistants = [];
79
97
  let expanded = false;
80
- let hideThinking = hideThinkingBlock;
98
+ let hideThinking = render.hideThinkingBlock === true;
81
99
  let streaming;
82
100
 
83
- const markdownTheme = () => getMarkdownTheme();
84
- const toolDefinition = (name) => runtime.withBuiltInRenderers?.(name, undefined);
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 };
85
106
  const add = (component) => {
86
107
  container.addChild(component);
87
108
  return component;
@@ -99,7 +120,7 @@ export function createTranscriptView({ runtime, tui, cwd = process.cwd(), hideTh
99
120
  function toolComponent(name, id, args) {
100
121
  let component = pendingTools.get(id);
101
122
  if (component) return component;
102
- component = new ToolExecutionComponent(name, id, args ?? {}, { showImages: false }, toolDefinition(name), tui, cwd);
123
+ component = new ToolExecutionComponent(name, id, args ?? {}, toolOptions, render.getToolDefinition(name), tui, cwd);
103
124
  addExpandable(component);
104
125
  pendingTools.set(id, component);
105
126
  return component;
@@ -115,7 +136,15 @@ export function createTranscriptView({ runtime, tui, cwd = process.cwd(), hideTh
115
136
  }
116
137
 
117
138
  function newAssistant(message) {
118
- const component = new AssistantMessageComponent(undefined, hideThinking, markdownTheme());
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
+ );
119
148
  assistants.push(component);
120
149
  add(component);
121
150
  component.updateContent(message, true);
@@ -142,19 +171,35 @@ export function createTranscriptView({ runtime, tui, cwd = process.cwd(), hideTh
142
171
  const text = userText(message);
143
172
  if (!text) return;
144
173
  if (container.children.length > 0) add(new Spacer(1));
145
- add(new UserMessageComponent(text, markdownTheme()));
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()));
146
186
  return;
147
187
  }
148
188
  case "custom":
149
- if (message.display) addExpandable(new CustomMessageComponent(message, undefined, markdownTheme()));
189
+ if (message.display) {
190
+ const renderer = render.getMessageRenderer(message.customType);
191
+ addExpandable(new CustomMessageComponent(message, renderer, markdownTheme(), outputPad, transformers()));
192
+ }
150
193
  return;
151
194
  case "compactionSummary":
152
195
  add(new Spacer(1));
153
- addExpandable(new CompactionSummaryMessageComponent(message, markdownTheme()));
196
+ addExpandable(
197
+ new CompactionSummaryMessageComponent(message, markdownTheme(), outputPad, transformers()),
198
+ );
154
199
  return;
155
200
  case "branchSummary":
156
201
  add(new Spacer(1));
157
- addExpandable(new BranchSummaryMessageComponent(message, markdownTheme()));
202
+ addExpandable(new BranchSummaryMessageComponent(message, markdownTheme(), outputPad, transformers()));
158
203
  return;
159
204
  default:
160
205
  return;
package/view.mjs CHANGED
@@ -13,6 +13,7 @@ import fs from "node:fs";
13
13
  import os from "node:os";
14
14
  import path from "node:path";
15
15
  import { pathToFileURL } from "node:url";
16
+ import { applyTerminalSettings, initPiTheme, loadPiEnvironment } from "./pi-environment.mjs";
16
17
  import { loadPiRuntime } from "./pi-runtime.mjs";
17
18
  import { createRpcEventRestorer } from "./rpc-stream-format.mjs";
18
19
  import { createTranscriptView } from "./transcript-view.mjs";
@@ -72,11 +73,6 @@ function sessionInfo(logPath) {
72
73
  };
73
74
  }
74
75
 
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
76
  /** Incremental JSONL reader: feed bytes, get complete event objects. */
81
77
  export function createLogReader(onEvent) {
82
78
  const restorer = createRpcEventRestorer();
@@ -132,28 +128,44 @@ export async function main(argv = process.argv.slice(2)) {
132
128
  const info = sessionInfo(logPath);
133
129
  const cwd = options.cwd ?? info.meta?.cwd ?? process.cwd();
134
130
  const runtime = await loadPiRuntime();
135
- const settings = piSettings();
136
- runtime.agent.initTheme(settings.theme, false);
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 });
137
135
 
138
136
  const decoder = new TextDecoder();
139
137
  if (options.print) {
140
- const stub = { requestRender() {} };
141
- const view = createTranscriptView({ runtime, tui: stub, cwd, hideThinkingBlock: settings.hideThinkingBlock === true });
138
+ initPiTheme(runtime, environment);
139
+ for (const message of environment.diagnostics) process.stderr.write(`${message}\n`);
140
+ const view = newView({ requestRender() {} });
142
141
  const reader = createLogReader((event) => view.apply(event));
143
142
  reader.push(decoder.decode(fs.readFileSync(logPath)));
144
143
  reader.end();
145
144
  const width = process.stdout.columns || 120;
146
- process.stdout.write(`${view.container.render(width).join("\n")}\n`);
145
+ await new Promise((resolve) => process.stdout.write(`${view.container.render(width).join("\n")}\n`, resolve));
147
146
  return 0;
148
147
  }
149
148
 
150
- const { ProcessTerminal, Text } = runtime.tui;
149
+ const { Container, ProcessTerminal, Spacer, Text } = runtime.tui;
151
150
  // Pi >= 1.5 renders regular (scrollback) mode with TuiMainScreen; older
152
151
  // pi-tui releases export the TUI class itself.
153
152
  const Screen = runtime.tui.TuiMainScreen ?? runtime.tui.TUI;
154
153
  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 });
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);
157
169
  let reader = createLogReader((event) => view.apply(event));
158
170
  const status = new Text("", 1, 0);
159
171
  const statusLine = () => {
@@ -171,10 +183,10 @@ export async function main(argv = process.argv.slice(2)) {
171
183
  const chunk = readFrom(logPath, offset);
172
184
  if (chunk.truncated) {
173
185
  // The log was replaced; start over.
174
- ui.removeChild(view.container);
175
- view = createTranscriptView({ runtime, tui: ui, cwd, hideThinkingBlock: settings.hideThinkingBlock === true });
186
+ const index = ui.children.indexOf(view.container);
187
+ view = newView(ui);
176
188
  reader = createLogReader((event) => view.apply(event));
177
- ui.children.unshift(view.container);
189
+ ui.children.splice(index, 1, view.container);
178
190
  }
179
191
  offset = chunk.offset;
180
192
  if (chunk.text.length) reader.push(decoder.decode(chunk.text, { stream: true }));
@@ -201,6 +213,7 @@ export async function main(argv = process.argv.slice(2)) {
201
213
 
202
214
  poll();
203
215
  ui.start();
216
+ theme.start();
204
217
  const timer = setInterval(poll, 200);
205
218
  return undefined;
206
219
  }
@@ -209,11 +222,12 @@ const entry = process.argv[1] ? pathToFileURL(fs.realpathSync(process.argv[1])).
209
222
  if (entry === import.meta.url) {
210
223
  main().then(
211
224
  (code) => {
212
- if (typeof code === "number") process.exitCode = code;
225
+ // Loaded extensions may keep timers alive; a finished one-shot run exits.
226
+ if (typeof code === "number") process.exit(code);
213
227
  },
214
228
  (error) => {
215
229
  console.error(error instanceof Error ? error.message : String(error));
216
- process.exitCode = 1;
230
+ process.exit(1);
217
231
  },
218
232
  );
219
233
  }