@xynogen/pix-pretty 2.1.0 → 2.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xynogen/pix-pretty",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Enhanced tool output rendering with syntax highlighting, file icons, tree views, diff rendering, and FFF search",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -73,7 +73,7 @@
73
73
  "access": "public"
74
74
  },
75
75
  "dependencies": {
76
- "@xynogen/pix-runtime": "^0.20.0",
76
+ "@xynogen/pix-runtime": "^0.21.0",
77
77
  "chalk": "^4.1.2",
78
78
  "cli-highlight": "^2.1.11",
79
79
  "@ff-labs/fff-node": "^0.10.6",
package/src/batch.ts CHANGED
@@ -34,6 +34,30 @@ export function sliceBatchTargets(targets: string[]): { targets: string[]; omitt
34
34
  };
35
35
  }
36
36
 
37
+ export type BatchOutcome<R> = { target: string; result: R } | { target: string; error: string };
38
+
39
+ /**
40
+ * Run every target in parallel. One target's failure becomes its `error` (via `describe`), so
41
+ * the rest still report; an abort rethrows, so a cancelled batch stops as a whole.
42
+ */
43
+ export function runBatch<R>(
44
+ targets: string[],
45
+ run: (target: string, index: number) => Promise<R>,
46
+ signal: AbortSignal | undefined,
47
+ describe: (error: unknown, target: string) => string | Promise<string>,
48
+ ): Promise<BatchOutcome<R>[]> {
49
+ return Promise.all(
50
+ targets.map(async (target, index) => {
51
+ try {
52
+ return { target, result: await run(target, index) };
53
+ } catch (error) {
54
+ if (signal?.aborted) throw error;
55
+ return { target, error: await describe(error, target) };
56
+ }
57
+ }),
58
+ );
59
+ }
60
+
37
61
  /** Minimal JSON-schema object shape we touch when adding a batch field. */
38
62
  export interface SchemaObject {
39
63
  properties: Record<string, unknown>;
package/src/shell-tool.ts CHANGED
@@ -250,3 +250,143 @@ export function registerShellTool(
250
250
  },
251
251
  });
252
252
  }
253
+
254
+ // ── Approval-gated command tools (ssh_run, sudo_run) ─────────────────────────
255
+
256
+ /** Lifecycle of a command that waits for user approval, then runs once. */
257
+ export type GatedCommandOutcome =
258
+ | "awaiting-approval"
259
+ | "running"
260
+ | "success"
261
+ | "denied"
262
+ | "timed-out"
263
+ | "cancelled"
264
+ | "error";
265
+
266
+ /** The result fields every gated command tool reports. */
267
+ export interface GatedCommandDetails {
268
+ command: string;
269
+ outcome: GatedCommandOutcome;
270
+ exitCode?: number;
271
+ lineCount?: number;
272
+ truncated?: boolean;
273
+ errorKind?: string;
274
+ _render?: string;
275
+ }
276
+
277
+ export type GatedCancellationKind = "denied" | "timeout" | "missing-password" | "aborted";
278
+
279
+ /** A closed approval overlay (timeout, deny, or no password) as an outcome plus a message. */
280
+ export function gatedCancellation(action: string): {
281
+ outcome: "timed-out" | "denied" | "cancelled";
282
+ cancellationKind: GatedCancellationKind;
283
+ text: string;
284
+ } {
285
+ if (action === "timeout")
286
+ return {
287
+ outcome: "timed-out",
288
+ cancellationKind: "timeout",
289
+ text: "Cancelled — Timed out — auto-denied.",
290
+ };
291
+ if (action === "denied")
292
+ return { outcome: "denied", cancellationKind: "denied", text: "Cancelled — Denied by user." };
293
+ return {
294
+ outcome: "cancelled",
295
+ cancellationKind: "missing-password",
296
+ text: "Cancelled — Cancelled — no password entered.",
297
+ };
298
+ }
299
+
300
+ /** One line of untrusted text: controls and runs of whitespace fold to single spaces. */
301
+ export function safeOneLine(value: string): string {
302
+ return value
303
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")
304
+ .replace(/\s+/g, " ")
305
+ .trim();
306
+ }
307
+
308
+ /** Collapsed-row meta: the terminal outcome, else exit code, extras, line count, truncation. */
309
+ export function gatedCommandMeta(
310
+ details: GatedCommandDetails,
311
+ errorLabels: Record<string, string>,
312
+ extras: Array<string | false | undefined> = [],
313
+ ): string {
314
+ if (details.outcome === "denied") return "denied";
315
+ if (details.outcome === "timed-out") return "timed out";
316
+ if (details.outcome === "cancelled") return "cancelled";
317
+ const label = details.errorKind ? errorLabels[details.errorKind] : undefined;
318
+ if (label) return label;
319
+ const hasLines = typeof details.lineCount === "number" && details.lineCount > 0;
320
+ return dotJoin([
321
+ typeof details.exitCode === "number" && `exit ${details.exitCode}`,
322
+ ...extras,
323
+ hasLines && `${details.lineCount} ${details.lineCount === 1 ? "line" : "lines"}`,
324
+ details.truncated && "truncated",
325
+ ]);
326
+ }
327
+
328
+ /**
329
+ * Result card for a gated command once its details are known: collapsed row when finished,
330
+ * a muted status line while waiting or running, the diagnostic on failure, else the output.
331
+ */
332
+ export function renderGatedCommandResult(
333
+ result: ToolResultLike,
334
+ details: GatedCommandDetails,
335
+ opts: { name: string; target: string; meta: string },
336
+ isPartial: boolean,
337
+ theme: ThemeLike,
338
+ renderCtx: RenderContextLike,
339
+ ) {
340
+ const text = reuseText(renderCtx.lastComponent);
341
+ const completed = (isError: boolean) => frameToolResult(text, theme, isError);
342
+ const status = details.outcome === "success" ? "success" : "error";
343
+ const running = details.outcome === "awaiting-approval" || details.outcome === "running";
344
+
345
+ if (
346
+ !isPartial &&
347
+ !running &&
348
+ tickCollapse(
349
+ opts.name,
350
+ renderCtx.state as CollapseState,
351
+ renderCtx.invalidate,
352
+ renderCtx.expanded,
353
+ )
354
+ ) {
355
+ return collapsedCommandRow(
356
+ renderRow(theme, opts.name, opts.target, opts.meta, status).trimEnd(),
357
+ safeOneLine(details.command),
358
+ theme,
359
+ );
360
+ }
361
+
362
+ if (running) {
363
+ text.setText(
364
+ fillToolBackground(`${BODY_PAD}${theme.fg("muted", getTextContent(result) || "working")}`),
365
+ );
366
+ return text;
367
+ }
368
+
369
+ if (details.outcome !== "success" && details.errorKind !== "exit-code") {
370
+ const diagnostic = getTextContent(result) || "Error";
371
+ text.setText(
372
+ details.outcome === "error"
373
+ ? renderToolError(diagnostic, theme)
374
+ : fillToolBackground(`${BODY_PAD}${theme.fg("warning", diagnostic)}`),
375
+ );
376
+ return isPartial ? text : completed(true);
377
+ }
378
+
379
+ const code = typeof details.exitCode === "number" ? details.exitCode : null;
380
+ const rendered = typeof details._render === "string" ? details._render : "";
381
+ if (!rendered) {
382
+ const { summary } = renderBashOutput(rendered, code, theme);
383
+ text.setText(fillToolBackground(`${BODY_PAD}${summary}`));
384
+ return isPartial ? text : completed(details.outcome !== "success");
385
+ }
386
+
387
+ // Every result (including single-line) is framed; the rules follow exit status: green ok,
388
+ // red failure. The `✓ exit N` header is dropped — the collapsed row already carries status.
389
+ const rows = outputBodyRows(rendered.split("\n"), theme, renderCtx, status, isPartial);
390
+ text.setText(fillToolBackground(rows.join("\n")));
391
+ return text;
392
+ }
package/src/tool-card.ts CHANGED
@@ -7,8 +7,11 @@
7
7
  * text, and the body.
8
8
  */
9
9
 
10
+ import { Box, Markdown } from "@earendil-works/pi-tui";
10
11
  import { type CollapseState, tickCollapse } from "@xynogen/pix-runtime/collapse";
11
12
  import { resolveBaseBackground } from "./ansi.ts";
13
+ import { fadeRowsOf } from "./text.ts";
14
+ import { getMarkdownTheme } from "./tui.ts";
12
15
  import type {
13
16
  RenderContextLike,
14
17
  TextComponentCtor,
@@ -17,10 +20,15 @@ import type {
17
20
  ToolResultLike,
18
21
  } from "./types.ts";
19
22
  import {
23
+ BODY_PAD,
24
+ bodyLine,
25
+ type CollapsedToolStatus,
20
26
  frameToolResult,
21
27
  getTextContent,
22
28
  hideCollapsedToolCall,
29
+ moreLines,
23
30
  renderCollapsed,
31
+ renderRow,
24
32
  renderToolError,
25
33
  reuseText,
26
34
  } from "./utils.ts";
@@ -109,3 +117,116 @@ export function toolCallRenderer<A, S extends RenderState = RenderState>(
109
117
  return text;
110
118
  };
111
119
  }
120
+
121
+ /** A tool whose result body is fetched/searched text: a preview while collapsed, all when expanded. */
122
+ export interface BodyCardSpec<D> {
123
+ /** Tool name: the collapse key and the default collapsed-row title. */
124
+ tool: string;
125
+ /** Collapsed-row title when it differs from `tool`. */
126
+ title?: string;
127
+ /** Collapsed-row target and summary; both default to empty. */
128
+ target?(d: D): string;
129
+ meta?(d: D): string;
130
+ status?(d: D): CollapsedToolStatus;
131
+ /** Preview budget in rows while collapsed; expanding shows everything. Default 16. */
132
+ maxPreviewLines?: number;
133
+ /** Render a successful body as Markdown (fades its tail) instead of dim text. */
134
+ markdown?: boolean;
135
+ }
136
+
137
+ /**
138
+ * `renderResult` for a text-body tool: error and empty states first, then the auto-collapsed
139
+ * row, then the body — dim text, or Markdown for `spec.markdown` — inside the result frame.
140
+ */
141
+ export function bodyCardRenderer<D = Record<string, unknown>, S extends RenderState = RenderState>(
142
+ TextComponent: TextComponentCtor,
143
+ spec: BodyCardSpec<D>,
144
+ ) {
145
+ const maxPreview = spec.maxPreviewLines ?? 16;
146
+ const dimBody = (
147
+ body: string,
148
+ theme: ThemeLike,
149
+ ctx: RenderContextLike<S>,
150
+ expanded: boolean,
151
+ ) => {
152
+ const lines = body.split("\n");
153
+ const shown = expanded ? lines.length : maxPreview;
154
+ const out = fadeRowsOf(
155
+ lines.slice(0, shown + 1).map((line) => bodyLine(line, theme, (l) => theme.fg("dim", l))),
156
+ theme,
157
+ shown,
158
+ );
159
+ const hidden = lines.length - shown;
160
+ if (hidden > 0) out.push(moreLines(hidden, theme, ctx));
161
+ return out.join("\n");
162
+ };
163
+ const markdownBody = (
164
+ body: string,
165
+ theme: ThemeLike,
166
+ ctx: RenderContextLike<S>,
167
+ expanded: boolean,
168
+ ) => {
169
+ const view = new Box(0, 0);
170
+ const page = new Markdown(body, 3, 0, getMarkdownTheme(), {
171
+ color: (value) => theme.fg("dim", value),
172
+ });
173
+ if (expanded) view.addChild(page);
174
+ // Fade the last preview rows of the rendered page instead of a hard cut.
175
+ else
176
+ view.addChild({
177
+ invalidate: () => page.invalidate(),
178
+ render: (width: number) => {
179
+ const rows = page.render(width);
180
+ const hidden = rows.length - maxPreview;
181
+ const shownRows = fadeRowsOf(rows, theme, maxPreview);
182
+ return hidden > 0 ? [...shownRows, moreLines(hidden, theme, ctx)] : shownRows;
183
+ },
184
+ });
185
+ return view;
186
+ };
187
+
188
+ return (
189
+ result: ToolResultLike,
190
+ options: { isPartial?: boolean; expanded?: boolean } | undefined,
191
+ theme: ThemeLike,
192
+ ctx: RenderContextLike<S>,
193
+ ) => {
194
+ resolveBaseBackground(theme);
195
+ const text = reuseText(ctx.lastComponent, TextComponent);
196
+ const isPartial = options?.isPartial === true;
197
+ const expanded = options?.expanded ?? ctx.expanded;
198
+ const body = getTextContent(result);
199
+
200
+ if (ctx.isError || !body.trim()) {
201
+ text.setText(
202
+ `${BODY_PAD}${ctx.isError ? theme.fg("error", body || "Error") : theme.fg("muted", "(empty)")}`,
203
+ );
204
+ return isPartial ? text : frameToolResult(text, theme, ctx.isError);
205
+ }
206
+
207
+ // SAFETY: the renderer receives the tool's own details; the spec types them as D.
208
+ const d = (result.details ?? undefined) as D | undefined;
209
+ if (
210
+ !isPartial &&
211
+ d &&
212
+ tickCollapse(spec.tool, ctx.state as CollapseState, ctx.invalidate, expanded)
213
+ ) {
214
+ text.setText(
215
+ renderRow(
216
+ theme,
217
+ spec.title ?? spec.tool,
218
+ spec.target?.(d) ?? "",
219
+ spec.meta?.(d) ?? "",
220
+ spec.status?.(d) ?? "success",
221
+ ),
222
+ );
223
+ return text;
224
+ }
225
+
226
+ const failed = Boolean(d && spec.status?.(d) === "error");
227
+ if (spec.markdown && !failed && !isPartial)
228
+ return frameToolResult(markdownBody(body, theme, ctx, expanded), theme, false);
229
+ text.setText(dimBody(body, theme, ctx, expanded));
230
+ return isPartial ? text : frameToolResult(text, theme, failed);
231
+ };
232
+ }