@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.
package/README.md CHANGED
@@ -167,7 +167,9 @@ including reusable idle agents. Summary counts use `RUNNING` / `IDLE`; rows show
167
167
  and unknown-status indicators when applicable, and a colored one-line description.
168
168
  Older sessions fall back to their command or task. Rows truncate to terminal width
169
169
  with `…`. In fullscreen mode, click the single `⧉` icon at the right edge of a row
170
- to copy that session's shell-quoted `babysit log` command. It includes the local
170
+ to copy that session's shell-quoted `babysit log` command (for a local subagent,
171
+ its log file path; see [Viewing a subagent transcript](#viewing-a-subagent-transcript)).
172
+ The command includes the local
171
173
  `BABYSIT_DIR` or remote host/worker ID, without executing the command or changing
172
174
  the input buffer. The icon changes in place: `…` while copying, `✓` on success,
173
175
  or `!` on failure. The result stays visible for two seconds before returning to
@@ -227,53 +229,22 @@ Set `PI_BABYSIT_ALLOW_BASH=1` only as an explicit emergency escape hatch.
227
229
 
228
230
  ### Subagent log format
229
231
 
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.
252
-
253
- ### Subagent transcript viewer
254
-
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:
232
+ A subagent's babysit log is Pi's `pi --mode rpc` stdout as-is: the standard
233
+ RPC event stream (JSONL), recorded through the worker's PTY, so lines end in
234
+ `\r\n`. pi-babysit adds no records and removes no fields. Parked-turn
235
+ detection reads `agent_end.messages`.
236
+
237
+ ### Viewing a subagent transcript
238
+
239
+ The widget's copy icon on a local subagent row copies the subagent's log file
240
+ path. The log is Pi's standard RPC event stream, so any Pi event viewer can
241
+ read it, for example [pi-tail](https://github.com/yusukeshib/pi-tail), which
242
+ renders it with Pi's own components:
259
243
 
260
244
  ```sh
261
- node ~/.pi/agent/npm/node_modules/@yusukeshib/pi-babysit/view.mjs <session-id | session dir | output.log>
245
+ pi-tail -f <copied output.log path>
262
246
  ```
263
247
 
264
- Keys: `q` / `Ctrl-C` quit, `Ctrl-O` expand or collapse tool output, `t`
265
- 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.
276
-
277
248
  ## Execution timeouts
278
249
 
279
250
  Commands default to an absolute **60s execution timeout**, in both foreground
@@ -395,7 +366,6 @@ session totals.
395
366
  | `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
367
  | `PI_BABYSIT_REAP_AFTER` | `120s` | idle grace before a finished subagent self-exits (`off`/`none`/`0` disables) |
397
368
  | `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
369
  | `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
370
  | `PI_BABYSIT_TAIL_MAX_BYTES` | `4000` | default cap for explicit log tails/screens returned by `babysit_check`; override per call with `maxBytes` |
401
371
  | `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 =
@@ -639,7 +638,7 @@ interface Meta {
639
638
  // subagent
640
639
  task?: string;
641
640
  launchCommand?: string;
642
- /** Worker working directory; the transcript viewer resolves tool paths against it. */
641
+ /** Worker working directory. */
643
642
  cwd?: string;
644
643
  reapAfter?: string;
645
644
  promptOffset?: number;
@@ -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,
@@ -2709,14 +2694,12 @@ function sessionCliCommand(id: string, command: "log" | "attach"): string {
2709
2694
  }
2710
2695
 
2711
2696
  /**
2712
- * Command copied by the widget icon: local subagents open the transcript
2713
- * viewer (rendered with Pi's components); everything else gets its log.
2697
+ * Text copied by the widget icon: a local subagent's log file path (Pi's RPC
2698
+ * event stream, e.g. for `pi-tail -f`); everything else gets its log command.
2714
2699
  */
2715
2700
  export function widgetCopyCommand(id: string): string {
2716
2701
  const meta = readMeta(id);
2717
- if (meta?.kind === "subagent" && !meta.host) {
2718
- return `${shq(process.execPath)} ${shq(path.join(EXT_DIR, "view.mjs"))} ${shq(logPath(id))}`;
2719
- }
2702
+ if (meta?.kind === "subagent" && !meta.host) return logPath(id);
2720
2703
  return sessionCliCommand(id, "log");
2721
2704
  }
2722
2705
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yusukeshib/pi-babysit",
3
- "version": "0.6.37",
3
+ "version": "0.8.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,12 +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
- "view.mjs",
32
26
  "search-log.mjs",
33
27
  "gc.mjs",
34
28
  "gc.d.mts",
@@ -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
- }
package/pi-runtime.mjs DELETED
@@ -1,120 +0,0 @@
1
- /**
2
- * Resolve the Pi packages of the INSTALLED pi, so a standalone viewer renders
3
- * with the same components as the pi that produced the log (not a copy that
4
- * happens to sit in pi-babysit's own node_modules).
5
- */
6
- import fs from "node:fs";
7
- import os from "node:os";
8
- import path from "node:path";
9
- import { execFileSync } from "node:child_process";
10
- import { pathToFileURL } from "node:url";
11
-
12
- const AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
13
-
14
- function packageName(dir) {
15
- try {
16
- return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")).name;
17
- } catch {
18
- return undefined;
19
- }
20
- }
21
-
22
- function managedInstallDir() {
23
- const agentDir = process.env.PI_CODING_AGENT_DIR ?? path.join(os.homedir(), ".pi", "agent");
24
- try {
25
- const version = fs.readFileSync(path.join(agentDir, "install", "current-version"), "utf8").trim();
26
- if (!version) return undefined;
27
- return path.join(agentDir, "install", "releases", version, "node_modules", AGENT_PACKAGE);
28
- } catch {
29
- return undefined;
30
- }
31
- }
32
-
33
- function packageDirFromBinary() {
34
- try {
35
- const bin = execFileSync("sh", ["-c", "command -v pi"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
36
- if (!bin) return undefined;
37
- let dir = path.dirname(fs.realpathSync(bin));
38
- for (;;) {
39
- if (packageName(dir) === AGENT_PACKAGE) return dir;
40
- const parent = path.dirname(dir);
41
- if (parent === dir) return undefined;
42
- dir = parent;
43
- }
44
- } catch {
45
- return undefined;
46
- }
47
- }
48
-
49
- /** Directory of the installed pi-coding-agent package, or undefined. */
50
- export function findPiPackageDir() {
51
- const candidates = [process.env.PI_BABYSIT_PI_PACKAGE_DIR, managedInstallDir(), packageDirFromBinary()];
52
- return candidates.find((dir) => dir && packageName(dir) === AGENT_PACKAGE);
53
- }
54
-
55
- function siblingPackageEntry(agentDir, name) {
56
- for (const dir of [
57
- path.join(path.dirname(agentDir), name),
58
- path.join(agentDir, "node_modules", "@earendil-works", name),
59
- ]) {
60
- if (packageName(dir) === `@earendil-works/${name}`) {
61
- const pkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
62
- const entry = pkg.exports?.["."]?.import ?? pkg.exports?.["."]?.default ?? pkg.module ?? pkg.main ?? "index.js";
63
- return pathToFileURL(path.join(dir, entry)).href;
64
- }
65
- }
66
- return undefined;
67
- }
68
-
69
- /**
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.
99
- */
100
- export async function loadPiRuntime() {
101
- const packageDir = findPiPackageDir();
102
- let agent;
103
- let tui;
104
- let version;
105
- const internal = {};
106
- if (packageDir) {
107
- const pkg = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
108
- version = pkg.version;
109
- agent = await import(pathToFileURL(path.join(packageDir, pkg.exports?.["."]?.import ?? "dist/index.js")).href);
110
- const tuiEntry = siblingPackageEntry(packageDir, "pi-tui");
111
- tui = await import(tuiEntry ?? "@earendil-works/pi-tui");
112
- for (const [key, relativePath] of Object.entries(INTERNAL_MODULES)) {
113
- internal[key] = await importInternal(packageDir, relativePath);
114
- }
115
- } else {
116
- agent = await import(AGENT_PACKAGE);
117
- tui = await import("@earendil-works/pi-tui");
118
- }
119
- return { agent, tui, withBuiltInRenderers: internal.renderers?.withBuiltInRenderers, internal, packageDir, version };
120
- }