@lune_99/pi-shell-inspector 0.1.0 → 1.4.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,4 +1,9 @@
1
- import type { MessageRenderOptions, Theme, ThemeBg, ThemeColor } from "@earendil-works/pi-coding-agent";
1
+ import type {
2
+ MessageRenderOptions,
3
+ Theme,
4
+ ThemeBg,
5
+ ThemeColor,
6
+ } from "@earendil-works/pi-coding-agent";
2
7
 
3
8
  import {
4
9
  sliceByColumn,
@@ -141,7 +146,7 @@ class BackgroundShellNotificationBox implements Component {
141
146
  return this.themed?.component.handleMouse?.(event);
142
147
  }
143
148
 
144
- render(width: number): string[] {
149
+ render(width: number): readonly string[] {
145
150
  const renderer = luneThemeRenderer();
146
151
 
147
152
  if (renderer) {
@@ -212,7 +217,12 @@ class BackgroundShellNotificationBox implements Component {
212
217
  entries: this.jobs.map((job) => ({
213
218
  name: "bash",
214
219
  summary: collapseShellCommand(job.command),
215
- status: job.status === "completed" ? "done" : job.status === "killed" ? "cancelled" : "failed",
220
+ status:
221
+ job.status === "completed"
222
+ ? "done"
223
+ : job.status === "killed"
224
+ ? "cancelled"
225
+ : "failed",
216
226
  detail: job.exitCode === undefined ? undefined : `exit ${job.exitCode}`,
217
227
  durationMs: job.durationMs,
218
228
  error: job.error,
@@ -245,16 +255,22 @@ class BackgroundShellNotificationBox implements Component {
245
255
  const outcome = [
246
256
  this.theme.fg(color, job.status),
247
257
  job.exitCode === undefined ? undefined : this.theme.fg(color, `exit ${job.exitCode}`),
248
- job.durationMs === undefined ? undefined : this.theme.fg("muted", formatDuration(job.durationMs)),
258
+ job.durationMs === undefined
259
+ ? undefined
260
+ : this.theme.fg("muted", formatDuration(job.durationMs)),
249
261
  ].filter((part): part is string => part !== undefined);
250
262
 
251
263
  // Every outcome part is preceded by a separator, so the command gets what is left after all
252
264
  // of them: a long command can never push the status out of the row.
253
265
  const separator = this.theme.fg("dim", " · ");
254
- const outcomeWidth = outcome.reduce((total, part) => total + visibleWidth(part), 0)
255
- + outcome.length * visibleWidth(separator);
266
+ const outcomeWidth =
267
+ outcome.reduce((total, part) => total + visibleWidth(part), 0) +
268
+ outcome.length * visibleWidth(separator);
256
269
  const commandWidth = Math.max(0, width - outcomeWidth);
257
- const command = this.theme.fg("text", clipToWidth(collapseShellCommand(job.command), commandWidth));
270
+ const command = this.theme.fg(
271
+ "text",
272
+ clipToWidth(collapseShellCommand(job.command), commandWidth),
273
+ );
258
274
 
259
275
  return [command, ...outcome].join(separator);
260
276
  }
@@ -281,7 +297,10 @@ class BackgroundShellNotificationBox implements Component {
281
297
  const rows = shown.map((line) => BODY_INDENT + this.theme.fg("toolOutput", line));
282
298
 
283
299
  if (hidden > 0) {
284
- rows.push(BODY_INDENT + this.theme.fg("muted", `… ${hidden} earlier lines · ${EXPAND_KEY} to expand`));
300
+ rows.push(
301
+ BODY_INDENT +
302
+ this.theme.fg("muted", `… ${hidden} earlier lines · ${EXPAND_KEY} to expand`),
303
+ );
285
304
  }
286
305
 
287
306
  return rows;
@@ -307,7 +326,9 @@ class BackgroundShellNotificationBox implements Component {
307
326
  }
308
327
 
309
328
  private bodyRows(text: string, width: number, color: ThemeColor): string[] {
310
- return wrapTextWithAnsi(text, width).map((line) => BODY_INDENT + this.theme.fg(color, line));
329
+ return wrapTextWithAnsi(text, width).map(
330
+ (line) => BODY_INDENT + this.theme.fg(color, line),
331
+ );
311
332
  }
312
333
 
313
334
  private band(row: string, inner: number, paddingX: number): string {
@@ -322,7 +343,9 @@ class BackgroundShellNotificationBox implements Component {
322
343
  }
323
344
 
324
345
  private bandToken(): ThemeBg {
325
- return this.jobs.some((job) => job.status !== "completed") ? "toolErrorBg" : "toolSuccessBg";
346
+ return this.jobs.some((job) => job.status !== "completed")
347
+ ? "toolErrorBg"
348
+ : "toolSuccessBg";
326
349
  }
327
350
  }
328
351
 
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { shellManager } from "./shell-manager.ts";
2
+ import type { ShellManager } from "./shell-manager.ts";
3
3
 
4
4
  /** Custom message type of a settled-shell batch; the transcript box is registered for it. */
5
5
  export const BACKGROUND_SHELL_NOTIFICATION_TYPE = "background-shell-notification";
@@ -80,7 +80,10 @@ export function buildBackgroundShellNotification(batch: readonly BackgroundShell
80
80
  error: item.jobError,
81
81
  durationMs: item.jobDurationMs,
82
82
  // The output is the section's tail, so its slice starts one output length back from the end.
83
- output: { start: offset + section.length - item.jobOutput.length, end: offset + section.length },
83
+ output: {
84
+ start: offset + section.length - item.jobOutput.length,
85
+ end: offset + section.length,
86
+ },
84
87
  fullOutputPath: item.jobFullOutputPath,
85
88
  });
86
89
  offset += section.length + SECTION_SEPARATOR.length;
@@ -185,11 +188,11 @@ class MessageSendBuffer<T> {
185
188
  try {
186
189
  await this.onFlush(batch.map(({ item }) => item));
187
190
  } catch (error) {
188
- const retrying = batch.filter(({ retryCount }) =>
189
- !this.disposed && retryCount < this.MAX_RETRIES,
191
+ const retrying = batch.filter(
192
+ ({ retryCount }) => !this.disposed && retryCount < this.MAX_RETRIES,
190
193
  );
191
- const dropped = batch.filter(({ retryCount }) =>
192
- this.disposed || retryCount >= this.MAX_RETRIES,
194
+ const dropped = batch.filter(
195
+ ({ retryCount }) => this.disposed || retryCount >= this.MAX_RETRIES,
193
196
  );
194
197
  for (const entry of retrying) {
195
198
  entry.retryCount += 1;
@@ -197,7 +200,11 @@ class MessageSendBuffer<T> {
197
200
  // Keep older failures ahead of arrivals during this flush, without immediate retries.
198
201
  this.buffer = retrying.concat(this.buffer);
199
202
  try {
200
- this.onFailure(error, retrying.map(({ item }) => item), dropped.map(({ item }) => item));
203
+ this.onFailure(
204
+ error,
205
+ retrying.map(({ item }) => item),
206
+ dropped.map(({ item }) => item),
207
+ );
201
208
  } catch {
202
209
  // A broken diagnostic sink must not turn a contained delivery error into a rejection.
203
210
  }
@@ -220,6 +227,7 @@ class MessageSendBuffer<T> {
220
227
 
221
228
  export function registerBackgroundShellNotifications(
222
229
  pi: ExtensionAPI,
230
+ manager: ShellManager,
223
231
  ctx?: ExtensionContext,
224
232
  ): () => void {
225
233
  // Resolve the UI before the runtime can invalidate context getters during reload.
@@ -232,10 +240,14 @@ export function registerBackgroundShellNotifications(
232
240
  const reason = error instanceof Error ? error.message : String(error);
233
241
  const messages: string[] = [];
234
242
  if (retrying.length > 0) {
235
- messages.push(`Failed to send background shell notification(s) [${retrying.map((item) => item.jobId).join(", ")}]: ${reason}. Requeued; at most 2 retries per notification.`);
243
+ messages.push(
244
+ `Failed to send background shell notification(s) [${retrying.map((item) => item.jobId).join(", ")}]: ${reason}. Requeued; at most 2 retries per notification.`,
245
+ );
236
246
  }
237
247
  if (dropped.length > 0) {
238
- messages.push(`Permanently failed background shell notification(s) [${dropped.map((item) => item.jobId).join(", ")}]: ${reason}. Dropped; retry limit reached or buffer disposed.`);
248
+ messages.push(
249
+ `Permanently failed background shell notification(s) [${dropped.map((item) => item.jobId).join(", ")}]: ${reason}. Dropped; retry limit reached or buffer disposed.`,
250
+ );
239
251
  }
240
252
  for (const message of messages) {
241
253
  if (ui) {
@@ -249,29 +261,33 @@ export function registerBackgroundShellNotifications(
249
261
  console.error(message);
250
262
  }
251
263
  };
252
- const messageBuffer = new MessageSendBuffer<BackgroundShellNotification>(300, (batch) => {
253
- const { content, details } = buildBackgroundShellNotification(batch);
254
-
255
- return pi.sendMessage(
256
- {
257
- customType: BACKGROUND_SHELL_NOTIFICATION_TYPE,
258
-
259
- content,
260
-
261
- // The box is the only way a settled shell reaches the transcript; the model reads the
262
- // same message either way, because display never affects what is sent to it.
263
- display: true,
264
-
265
- details,
266
- },
267
- {
268
- triggerTurn: true,
269
- deliverAs: "steer",
270
- },
271
- );
272
- }, reportFailure);
264
+ const messageBuffer = new MessageSendBuffer<BackgroundShellNotification>(
265
+ 300,
266
+ (batch) => {
267
+ const { content, details } = buildBackgroundShellNotification(batch);
268
+
269
+ return pi.sendMessage(
270
+ {
271
+ customType: BACKGROUND_SHELL_NOTIFICATION_TYPE,
272
+
273
+ content,
274
+
275
+ // The box is the only way a settled shell reaches the transcript; the model reads the
276
+ // same message either way, because display never affects what is sent to it.
277
+ display: true,
278
+
279
+ details,
280
+ },
281
+ {
282
+ triggerTurn: true,
283
+ deliverAs: "steer",
284
+ },
285
+ );
286
+ },
287
+ reportFailure,
288
+ );
273
289
 
274
- const unsubscribe = shellManager.subscribe((event) => {
290
+ const unsubscribe = manager.subscribe((event) => {
275
291
  if (
276
292
  event.type !== "job-completed" &&
277
293
  event.type !== "job-failed" &&
@@ -280,13 +296,13 @@ export function registerBackgroundShellNotifications(
280
296
  return;
281
297
  }
282
298
 
283
- const job = shellManager.getJob(event.id);
299
+ const job = manager.getJob(event.id);
284
300
 
285
301
  if (!job) {
286
302
  return;
287
303
  }
288
304
 
289
- const output = shellManager.getJobOutput(event.id);
305
+ const output = manager.getJobOutput(event.id);
290
306
 
291
307
  messageBuffer.push({
292
308
  jobId: job.id,
@@ -296,7 +312,8 @@ export function registerBackgroundShellNotifications(
296
312
  jobError: job.error,
297
313
  jobOutput: output,
298
314
  jobFullOutputPath: job.output.fullOutputPath,
299
- jobDurationMs: job.finishedAt === undefined ? undefined : job.finishedAt - job.startedAt,
315
+ jobDurationMs:
316
+ job.finishedAt === undefined ? undefined : job.finishedAt - job.startedAt,
300
317
  });
301
318
  });
302
319
 
@@ -6,7 +6,7 @@ import {
6
6
  type ExtensionContext,
7
7
  } from "@earendil-works/pi-coding-agent";
8
8
 
9
- import { shellManager } from "../shell/shell-manager.ts";
9
+ import type { ShellManager } from "../shell/shell-manager.ts";
10
10
 
11
11
  export const backgroundStartOutputSchema = Type.Object({
12
12
  background: Type.Literal(true),
@@ -26,18 +26,19 @@ const backgroundOps = createLocalBashOperations();
26
26
  * on any other exit - or the execution itself fails.
27
27
  */
28
28
  export function startBackgroundShell(input: {
29
+ manager: ShellManager;
29
30
  toolCallId: string;
30
31
  command: string;
31
32
  label?: string;
32
33
  timeout?: number;
33
34
  ctx: ExtensionContext;
34
35
  }): AgentToolResult {
35
- const { toolCallId, command, ctx, timeout } = input;
36
+ const { manager, toolCallId, command, ctx, timeout } = input;
36
37
 
37
38
  // The job owns this controller so a kill can abort the running process tree.
38
39
  const controller = new AbortController();
39
40
 
40
- shellManager.startJob({
41
+ manager.startJob({
41
42
  id: toolCallId,
42
43
  command,
43
44
  label: normalizeLabel(input.label),
@@ -52,23 +53,23 @@ export function startBackgroundShell(input: {
52
53
 
53
54
  onData(data) {
54
55
  // prevent appending output after the shutdown kills the job
55
- if (shellManager.getJob(toolCallId)?.status !== "running") {
56
+ if (manager.getJob(toolCallId)?.status !== "running") {
56
57
  return;
57
58
  }
58
59
  // Retention (bounded tail plus the full-output file) is enforced by appendOutput.
59
- shellManager.appendOutput(toolCallId, data.toString("utf8"));
60
+ manager.appendOutput(toolCallId, data.toString("utf8"));
60
61
  },
61
62
  })
62
63
  .then(({ exitCode }) => {
63
64
  if (exitCode === 0) {
64
- shellManager.settleJob(toolCallId, {
65
+ manager.settleJob(toolCallId, {
65
66
  type: "completed",
66
67
  exitCode: exitCode ?? undefined,
67
68
  });
68
69
  return;
69
70
  }
70
71
  const errorMessage = `Background shell exited with code ${exitCode ?? "unknown"}`;
71
- shellManager.settleJob(toolCallId, {
72
+ manager.settleJob(toolCallId, {
72
73
  type: "failed",
73
74
  exitCode: exitCode ?? undefined,
74
75
  error: errorMessage,
@@ -80,14 +81,14 @@ export function startBackgroundShell(input: {
80
81
  // any other error (timeout, missing cwd, spawn failure) is an execution failure.
81
82
  // settleJob is idempotent, so a job that was already settled or cleared is ignored.
82
83
  if (controller.signal.aborted) {
83
- shellManager.settleJob(toolCallId, {
84
+ manager.settleJob(toolCallId, {
84
85
  type: "killed",
85
86
  error: error.message,
86
87
  });
87
88
  return;
88
89
  }
89
90
 
90
- shellManager.settleJob(toolCallId, {
91
+ manager.settleJob(toolCallId, {
91
92
  type: "failed",
92
93
  error: error.message,
93
94
  });
@@ -14,8 +14,8 @@
14
14
  * pull side (the immediate `bash` result cannot report a detached job, so the model needs a way to
15
15
  * ask for a job's current status or intermediate output before the completion notification
16
16
  * arrives), and `kill_background_shell`, which stops one managed job through its job id instead of
17
- * a pid. All definitions read the same module-level `ShellManager`, so a job started through one is
18
- * visible to the others.
17
+ * a pid. All definitions of one extension load share its `ShellManager`, so a job started through
18
+ * one is visible to the others.
19
19
  */
20
20
  import {
21
21
  createBashTool,
@@ -29,7 +29,7 @@ import Type from "typebox";
29
29
 
30
30
  import { startBackgroundShell, backgroundStartOutputSchema } from "./background-bash.ts";
31
31
 
32
- import { shellManager, type ShellJob } from "../shell/shell-manager.ts";
32
+ import type { ShellJob, ShellManager } from "../shell/shell-manager.ts";
33
33
  /**
34
34
  * Build the wrapper definition for one extension load.
35
35
  *
@@ -37,7 +37,7 @@ import { shellManager, type ShellJob } from "../shell/shell-manager.ts";
37
37
  * directory at construction time, so the definition must be built where the load-time cwd is known
38
38
  * and can later take extension-level configuration.
39
39
  */
40
- export function BashTool() {
40
+ export function BashTool(manager: ShellManager) {
41
41
  // Reuse the built-in definition and extend its schema with `mode`, so the rest of the tool
42
42
  // contract the model sees cannot drift from the built-in one.
43
43
  const baseBash = createBashToolDefinition(process.cwd());
@@ -123,6 +123,7 @@ export function BashTool() {
123
123
 
124
124
  // Background returns at once; the detached execution settles the job later.
125
125
  return startBackgroundShell({
126
+ manager,
126
127
  toolCallId,
127
128
  command: params.command,
128
129
  label: params.label,
@@ -177,9 +178,9 @@ function formatJobLine(job: Readonly<ShellJob>): string {
177
178
  * later tick, which is why a read issued right after `appendOutput` would still see the previous
178
179
  * screen: writing an empty chunk first flushes through that same queue.
179
180
  */
180
- async function readJobScreen(job: Readonly<ShellJob>): Promise<string[]> {
181
+ async function readJobScreen(manager: ShellManager, job: Readonly<ShellJob>): Promise<string[]> {
181
182
  await new Promise<void>((resolve) => job.terminal.write("", () => resolve()));
182
- return shellManager.getScreenLines(job.id);
183
+ return manager.getScreenLines(job.id);
183
184
  }
184
185
 
185
186
  /**
@@ -187,14 +188,13 @@ async function readJobScreen(job: Readonly<ShellJob>): Promise<string[]> {
187
188
  *
188
189
  * This is the only pull path to a detached job: a background `bash` call returns before its command
189
190
  * printed anything and its transcript row is suppressed, so until the job settles this tool is how
190
- * the model learns whether it still runs and what it printed so far. State comes from the shared
191
- * `shellManager` singleton - the same jobs the dock and `/shell` read - and never from a chat
192
- * transcript.
191
+ * the model learns whether it still runs and what it printed so far. State comes from the load's
192
+ * `ShellManager` - the same jobs the dock and `/shell` read - and never from a chat transcript.
193
193
  *
194
194
  * Output is opt-in per job because a screen can hold up to pi's output tail limit; listing statuses
195
195
  * is cheap, while every requested screen is charged to the model's context.
196
196
  */
197
- export function BackgroundShellTool() {
197
+ export function BackgroundShellTool(manager: ShellManager) {
198
198
  return defineTool({
199
199
  name: "background_shell",
200
200
  label: "Background Shell",
@@ -213,7 +213,7 @@ export function BackgroundShellTool() {
213
213
  // Omitted and empty `jobs` mean the same thing: list every shell.
214
214
  const jobs = params.jobs ?? [];
215
215
  if (jobs.length === 0) {
216
- const allJobs = shellManager.getAllJobsList();
216
+ const allJobs = manager.getAllJobsList();
217
217
  if (allJobs.length === 0) {
218
218
  return backgroundShellText("No background shells.");
219
219
  }
@@ -224,7 +224,7 @@ export function BackgroundShellTool() {
224
224
  // inline instead of thrown, so one stale id cannot fail the whole query.
225
225
  const blocks = await Promise.all(
226
226
  jobs.map(async (job) => {
227
- const jobInfo = shellManager.getJob(job.jobID);
227
+ const jobInfo = manager.getJob(job.jobID);
228
228
  if (!jobInfo) {
229
229
  return `Unknown background shell: ${job.jobID}`;
230
230
  }
@@ -234,7 +234,7 @@ export function BackgroundShellTool() {
234
234
  return line;
235
235
  }
236
236
 
237
- const screen = await readJobScreen(jobInfo);
237
+ const screen = await readJobScreen(manager, jobInfo);
238
238
  return screen.length === 0
239
239
  ? `${line}\n(no output yet)`
240
240
  : `${line}\n${screen.join("\n")}`;
@@ -260,7 +260,7 @@ const killBackgroundShellSchema = Type.Object({
260
260
  * process-kill command. A kill is not a clear: the job keeps its output and terminal, stays
261
261
  * readable through `background_shell` and `/shell`, and is only removed by an explicit clear.
262
262
  */
263
- export function KillBackgroundShellTool() {
263
+ export function KillBackgroundShellTool(manager: ShellManager) {
264
264
  return defineTool({
265
265
  name: "kill_background_shell",
266
266
  label: "Kill Background Shell",
@@ -274,7 +274,7 @@ export function KillBackgroundShellTool() {
274
274
  ],
275
275
 
276
276
  async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
277
- const job = shellManager.getJob(params.jobID);
277
+ const job = manager.getJob(params.jobID);
278
278
 
279
279
  // Unknown ids and jobs that already settled are caller mistakes, not tool failures, so
280
280
  // they are answered inline instead of thrown.
@@ -285,7 +285,7 @@ export function KillBackgroundShellTool() {
285
285
  // settleJob is the manager's single terminal-state entry point, so an agent kill goes
286
286
  // through the same killed outcome path as `/shell`'s kill key; a refusal means the job
287
287
  // is no longer running and the kill must leave it untouched.
288
- const settled = shellManager.settleJob(params.jobID, {
288
+ const settled = manager.settleJob(params.jobID, {
289
289
  type: "killed",
290
290
  error: "Shell killed by agent",
291
291
  });
@@ -2,7 +2,7 @@ import { type AgentToolResult } from "@earendil-works/pi-coding-agent";
2
2
 
3
3
  /**
4
4
  * Concatenates text blocks from pi agent tool result into a single string.
5
- *
5
+ *
6
6
  * @param agentToolResult - The {@link AgentToolResult} to read text from.
7
7
  * @returns The joined text, or an empty string if no text blocks exist.
8
8
  */
@@ -11,4 +11,4 @@ export function getAgentToolTextResult(agentToolResult: AgentToolResult) {
11
11
  .filter((item) => item.type === "text")
12
12
  .map((item) => item.text)
13
13
  .join("");
14
- }
14
+ }