@xynogen/pix-pretty 2.1.0 → 3.0.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.
@@ -0,0 +1,356 @@
1
+ import {
2
+ type Component,
3
+ MouseRegion,
4
+ type mixColors,
5
+ Text,
6
+ truncateToWidth,
7
+ visibleWidth,
8
+ } from "@earendil-works/pi-tui";
9
+ import { BG_BASE, BG_ERROR, BOLD, BOLD_OFF, hasAnsi } from "./ansi.ts";
10
+ import { MAX_PREVIEW_LINES } from "./config.ts";
11
+ import {
12
+ BODY_PAD,
13
+ bodyLine,
14
+ type ExpandHintCtx,
15
+ moreLines,
16
+ type RulePaint,
17
+ ruleFrame,
18
+ unframeToolResult,
19
+ } from "./frame.ts";
20
+ import { icon } from "./icon-catalog.ts";
21
+ import { fadeLine, fadePaint, fadeRowsOf, fadeText, normalizeLineEndings } from "./text.ts";
22
+ import type { FgTheme } from "./types.ts";
23
+ import { fillToolBackground, terminalWidth } from "./utils.ts";
24
+ export function renderToolError(error: string, theme: FgTheme): string {
25
+ return fillToolBackground(theme.fg("error", error), BG_ERROR);
26
+ }
27
+
28
+ export type CollapsedToolStatus = "success" | "error" | "warning";
29
+
30
+ /**
31
+ * Status glyphs for collapsed tool rows. `⚠` (warning) is East-Asian *wide*
32
+ * (2 cells) while `✓`/`✗` are 1 cell — render them through `padIcon` so every
33
+ * marker occupies the same fixed column and rows stay vertically aligned.
34
+ * (`⚡` is reserved for strength / model-score badges, not warnings.)
35
+ */
36
+ export const COLLAPSED_TOOL_GLYPH: Record<CollapsedToolStatus, string> = {
37
+ get success() {
38
+ return icon("status.ok");
39
+ },
40
+ get warning() {
41
+ return icon("status.warn");
42
+ },
43
+ get error() {
44
+ return icon("status.error");
45
+ },
46
+ };
47
+
48
+ /**
49
+ * Normalize a marker glyph to a fixed display width so mixed 1-cell and 2-cell
50
+ * (East-Asian wide / emoji) icons align in a column and the following text
51
+ * always starts at the same offset. Measures actual terminal cells via pi-tui's
52
+ * `visibleWidth` (ANSI-aware), then right-pads with spaces. A glyph already
53
+ * at/over `width` is returned unchanged (never truncated — clipping a marker is
54
+ * worse than a 1-cell overflow).
55
+ *
56
+ * The default width (2) makes every marker occupy exactly two cells, so with a
57
+ * single separator space the following text always starts at the same column:
58
+ *
59
+ * `${padIcon("✓")} bash` // "✓ bash" (1 cell + 1 pad + separator)
60
+ * `${padIcon("⚠")} bash` // "⚠ bash" (2 cells + separator — same column)
61
+ */
62
+ export function padIcon(glyph: string, width = 2): string {
63
+ const pad = width - visibleWidth(glyph);
64
+ return pad > 0 ? glyph + " ".repeat(pad) : glyph;
65
+ }
66
+
67
+ /** Fixed icon/name columns align the divider across compact activity widgets. */
68
+ export function widgetTitle(
69
+ theme: { fg: (role: "toolTitle" | "muted", text: string) => string },
70
+ glyph: string,
71
+ name: string,
72
+ ): string {
73
+ return theme.fg("toolTitle", `${padIcon(glyph, 3)} ${name.padEnd(8)}`) + theme.fg("muted", " │ ");
74
+ }
75
+
76
+ /**
77
+ * Join non-empty parts with a middot separator: `dotJoin(["a", "", "b"])` → `"a · b"`.
78
+ * Empty/nullish parts are dropped so callers can pass conditional pieces inline.
79
+ * Pass `paint` (e.g. `(s) => theme.fg("dim", s)`) to tint the separator to theme.
80
+ */
81
+ export function dotJoin(
82
+ parts: Array<string | false | null | undefined>,
83
+ paint?: RulePaint,
84
+ ): string {
85
+ const sep = paint ? paint(" · ") : " · ";
86
+ return parts.filter((p): p is string => Boolean(p)).join(sep);
87
+ }
88
+
89
+ type CollapsedToolTheme = {
90
+ fg: (
91
+ key: "success" | "error" | "warning" | "toolTitle" | "muted" | "dim",
92
+ text: string,
93
+ ) => string;
94
+ bold: (text: string) => string;
95
+ colors?: {
96
+ dim: Parameters<typeof mixColors>[0];
97
+ customMessageBg: Parameters<typeof mixColors>[1];
98
+ };
99
+ style?: (text: string, style: { fg: ReturnType<typeof mixColors> }) => string;
100
+ };
101
+
102
+ /** Keep identity/stats fixed; only the trailing activity consumes spare columns. */
103
+ export function widgetActivityRow(
104
+ theme: Pick<CollapsedToolTheme, "fg" | "colors" | "style">,
105
+ prefix: string,
106
+ activity: string,
107
+ width: number,
108
+ stats = "",
109
+ ): string {
110
+ const paint = fadePaint(theme);
111
+ if (stats) {
112
+ const room = width - visibleWidth(stats) - 2;
113
+ if (room < visibleWidth(prefix)) return fadeLine(`${prefix} ${stats}`, width, paint);
114
+ const body = widgetActivityRow(theme, prefix, activity, room);
115
+ return body + " ".repeat(width - visibleWidth(body) - visibleWidth(stats)) + stats;
116
+ }
117
+ const separator = theme.fg("muted", " · ");
118
+ const room = width - visibleWidth(prefix) - 3;
119
+ if (!activity || room < 1) return fadeLine(prefix, width, paint);
120
+ return prefix + separator + fadeText(activity, room, paint);
121
+ }
122
+
123
+ /** Use the host lifecycle fields so every call has the same status marker. */
124
+ export function renderTitle(
125
+ theme: {
126
+ fg: (role: "muted" | "warning" | "error" | "success" | "toolTitle", text: string) => string;
127
+ bold?: (text: string) => string;
128
+ },
129
+ tool: string,
130
+ context: { executionStarted?: boolean; isPartial?: boolean; isError?: boolean } = {},
131
+ action?: string,
132
+ ): string {
133
+ const complete = context.isPartial === false;
134
+ const role = complete
135
+ ? context.isError
136
+ ? "error"
137
+ : "success"
138
+ : context.executionStarted
139
+ ? "warning"
140
+ : "muted";
141
+ const marker = complete
142
+ ? context.isError
143
+ ? "status.error"
144
+ : "status.ok"
145
+ : context.executionStarted
146
+ ? "status.running"
147
+ : "status.pending";
148
+ const label = action ? `${tool} · ${action}` : tool;
149
+ return `${theme.fg(role, padIcon(icon(marker)))} ${theme.fg("toolTitle", theme.bold?.(label) ?? label)}`;
150
+ }
151
+
152
+ /** Build a plain call renderer; command and rich previews keep their own body. */
153
+ export function renderCall<TArgs = Record<string, unknown>>(
154
+ tool: string,
155
+ target: (args: TArgs) => string,
156
+ action?: (args: TArgs) => string | undefined,
157
+ ) {
158
+ return (
159
+ args: TArgs,
160
+ theme: Parameters<typeof renderTitle>[0] & { fg: (role: "dim", text: string) => string },
161
+ context: Parameters<typeof renderTitle>[2] & {
162
+ lastComponent?: Component;
163
+ state: Record<string, unknown>;
164
+ expanded: boolean;
165
+ },
166
+ ): Component => {
167
+ const previous = context.lastComponent && unframeToolResult(context.lastComponent);
168
+ const text =
169
+ previous && "setText" in previous && typeof previous.setText === "function"
170
+ ? (previous as Component & { setText(value: string): void })
171
+ : new Text("", 0, 0);
172
+ if (hideCollapsedToolCall(context.state, context.expanded, (value) => text.setText(value)))
173
+ return text;
174
+ const value = target(args);
175
+ text.setText(
176
+ `${renderTitle(theme, tool, context, action?.(args))}${value ? ` ${theme.fg("dim", value)}` : ""}`,
177
+ );
178
+ return text;
179
+ };
180
+ }
181
+
182
+ /** Format the shared one-row content without assuming a render shell. */
183
+ export function renderRow(
184
+ theme: CollapsedToolTheme,
185
+ tool: string,
186
+ target: string,
187
+ meta = "",
188
+ status: CollapsedToolStatus = "success",
189
+ width?: number,
190
+ ): string {
191
+ const marker = padIcon(
192
+ icon(status === "success" ? "status.ok" : status === "error" ? "status.error" : "status.warn"),
193
+ );
194
+ const title = `${theme.fg(status, marker)} ${theme.fg("toolTitle", theme.bold(tool))}`;
195
+ const metadata = meta ? ` ${theme.fg("muted", "·")} ${theme.fg("muted", meta)}` : "";
196
+ if (width === undefined)
197
+ return `${title}${target ? ` ${theme.fg("dim", target)}` : ""}${metadata}`;
198
+ const room = width - visibleWidth(title) - visibleWidth(metadata) - 1;
199
+ const fitted = target && room > 0 ? fadeText(target, room, fadePaint(theme)) : "";
200
+ return truncateToWidth(`${title}${fitted ? ` ${fitted}` : ""}${metadata}`, width, "…");
201
+ }
202
+
203
+ /** Render shared one-row content for tools using the self-rendered shell. */
204
+ export function renderCollapsed(
205
+ theme: CollapsedToolTheme,
206
+ tool: string,
207
+ target: string,
208
+ meta = "",
209
+ status: CollapsedToolStatus = "success",
210
+ width?: number,
211
+ ): string {
212
+ return fillToolBackground(
213
+ renderRow(theme, tool, target, meta, status, width ?? terminalWidth()),
214
+ BG_BASE,
215
+ width,
216
+ );
217
+ }
218
+
219
+ /** Hide renderCall after its paired result has auto-collapsed. */
220
+ export function hideCollapsedToolCall(
221
+ state: { collapsed?: boolean },
222
+ expanded: boolean,
223
+ setText: (text: string) => void,
224
+ ): boolean {
225
+ if (!state.collapsed || expanded) return false;
226
+ setText("");
227
+ return true;
228
+ }
229
+
230
+ export type DimPreviewOptions = {
231
+ maxLines?: number;
232
+ /** Header line shown above the body. NON-FRAMED mode only — in framed mode
233
+ * the header is intentionally dropped (the collapsed row already carries the
234
+ * count, so a floating header above the frame is redundant). */
235
+ header?: string;
236
+ /** Pattern whose matches are highlighted (bold, themed) inside dim lines.
237
+ * A string is matched literally (case-insensitive); a RegExp is used as-is
238
+ * (callers pass the compiled search pattern so regex greps highlight too). */
239
+ highlight?: string | RegExp;
240
+ /** Wrap the body in a top/bottom rule frame (overflow below), like bash/ls/mcp. */
241
+ frame?: boolean;
242
+ /** Tint the frame rules (green ok, red error) — same status color as bash/ls. */
243
+ paint?: RulePaint;
244
+ /** Renderer context: the overflow row shows the user's expand key. */
245
+ ctx?: ExpandHintCtx;
246
+ };
247
+
248
+ /** Compile a highlight pattern into a global RegExp, or null when it can't
249
+ * match anything. Strings match literally (case-insensitive); a RegExp is
250
+ * re-flagged global so every occurrence on a line lights up. */
251
+ function toHighlightRegex(pattern: string | RegExp): RegExp | null {
252
+ if (typeof pattern !== "string") {
253
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
254
+ try {
255
+ return new RegExp(pattern.source, flags);
256
+ } catch {
257
+ return null;
258
+ }
259
+ }
260
+ if (!pattern) return null;
261
+ // Literal string → escape regex metacharacters, case-insensitive.
262
+ const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
263
+ try {
264
+ return new RegExp(escaped, "gi");
265
+ } catch {
266
+ return null;
267
+ }
268
+ }
269
+
270
+ function dimLineWithHighlight(line: string, theme: FgTheme, pattern?: string | RegExp): string {
271
+ if (!pattern) return theme.fg("dim", line);
272
+ // A line that already carries ANSI (e.g. a source that emitted its own color)
273
+ // can't be safely index-sliced — a match could land inside an escape and
274
+ // corrupt it. Skip highlighting and dim the whole line instead.
275
+ if (hasAnsi(line)) return theme.fg("dim", line);
276
+ const re = pattern ? toHighlightRegex(pattern) : null;
277
+ if (!re) return theme.fg("dim", line);
278
+
279
+ // Themed bold hit: theme.fg carries its own reset, so re-open BOLD after it
280
+ // and close with the bold-off code (\x1b[22m) to avoid leaking bold onward.
281
+ const hit = (s: string) => `${BOLD}${theme.fg("success", s)}${BOLD_OFF}`;
282
+ const parts: string[] = [];
283
+ let start = 0;
284
+ for (let m = re.exec(line); m !== null; m = re.exec(line)) {
285
+ const idx = m.index;
286
+ const text = m[0];
287
+ if (text.length === 0) {
288
+ re.lastIndex++; // zero-width match (e.g. /a*/) — advance to avoid a loop
289
+ continue;
290
+ }
291
+ if (idx > start) parts.push(theme.fg("dim", line.slice(start, idx)));
292
+ parts.push(hit(text));
293
+ start = idx + text.length;
294
+ }
295
+ if (start < line.length) parts.push(theme.fg("dim", line.slice(start)));
296
+ return parts.length > 0 ? parts.join("") : theme.fg("dim", line);
297
+ }
298
+
299
+ export function renderDimPreview(
300
+ text: string,
301
+ theme: FgTheme,
302
+ opts: DimPreviewOptions = {},
303
+ ): string {
304
+ const maxLines = opts.maxLines ?? MAX_PREVIEW_LINES;
305
+ const highlight = opts.highlight;
306
+ const output = normalizeLineEndings(text).trim() || "done";
307
+ const lines = output.split("\n");
308
+ // Highlight only the preview rows (+1 so the fade still knows it was cut), then fade the
309
+ // last of them instead of a hard cut.
310
+ const body = fadeRowsOf(
311
+ lines
312
+ .slice(0, maxLines + 1)
313
+ .map((line) => bodyLine(line, theme, (l) => dimLineWithHighlight(l, theme, highlight))),
314
+ theme,
315
+ maxLines,
316
+ );
317
+ const header = opts.header ? `${BODY_PAD}${theme.fg("dim", opts.header)}` : undefined;
318
+ const overflow =
319
+ lines.length > maxLines ? moreLines(lines.length - maxLines, theme, opts.ctx) : undefined;
320
+
321
+ if (opts.frame) {
322
+ // One shape regardless of line count: a single framed box, no floating
323
+ // header (the collapsed row carries the count). Rules follow status color.
324
+ const out = ruleFrame(body, overflow ? [overflow] : [], undefined, opts.paint);
325
+ return fillToolBackground(out.join("\n"));
326
+ }
327
+
328
+ const preview = body;
329
+ if (header) preview.unshift(header);
330
+ if (overflow) preview.push(overflow);
331
+ return fillToolBackground(preview.join("\n"));
332
+ }
333
+
334
+ /**
335
+ * Make a custom message/entry card toggle on left click, like Pi's tool results.
336
+ * Pi gives custom renderers no click handling, so a renderer returns
337
+ * `clickToggle(expanded, (open) => card(open))`: a left click rebuilds the card
338
+ * with the flipped state. A host Ctrl+O rebuild resets it to the host `expanded`.
339
+ * Other mouse events are left unhandled (drag selects text, wheel scrolls).
340
+ */
341
+ export function clickToggle(
342
+ expanded: boolean,
343
+ build: (expanded: boolean) => Component,
344
+ ): MouseRegion {
345
+ let open = expanded;
346
+ let view = build(open);
347
+ return new MouseRegion(
348
+ { render: (width) => view.render(width), invalidate: () => view.invalidate() },
349
+ (event) => {
350
+ if (event.type !== "click" || event.button !== "left") return undefined;
351
+ open = !open;
352
+ view = build(open);
353
+ return { handled: true };
354
+ },
355
+ );
356
+ }
package/src/renderers.ts CHANGED
@@ -4,25 +4,17 @@ import { prettySection } from "@xynogen/pix-runtime/sections";
4
4
 
5
5
  import { FG_DIM, FG_LNUM, FG_RULE, RST } from "./ansi.ts";
6
6
  import { MAX_PREVIEW_LINES } from "./config.ts";
7
+ import { BODY_PAD, type ExpandHintCtx, expandHint, rule } from "./frame.ts";
7
8
  import { hlBlock } from "./highlight.ts";
8
9
  import { dirIcon, fileColor, fileIcon } from "./icons.ts";
9
10
  import { lang } from "./lang.ts";
10
- import { type FadeTheme, fadeRowsOf } from "./text.ts";
11
+ import { type FadeTheme, fadeRowsOf, normalizeLineEndings, pluralize } from "./text.ts";
11
12
  import type { FgTheme } from "./types.ts";
12
- import {
13
- BODY_PAD,
14
- type ExpandHintCtx,
15
- expandHint,
16
- lnum,
17
- normalizeLineEndings,
18
- pluralize,
19
- rule,
20
- termW,
21
- } from "./utils.ts";
13
+ import { lineNumber, terminalWidth } from "./utils.ts";
22
14
 
23
15
  /** Layout controls for {@link renderFileContent}. */
24
16
  export interface RenderFileContentOptions {
25
- /** Total render width. Defaults to the live terminal width (`termW()`). */
17
+ /** Total render width. Defaults to the live terminal width (`terminalWidth()`). */
26
18
  width?: number;
27
19
  /**
28
20
  * Wrap over-wide code lines onto continuation rows instead of clipping the
@@ -53,7 +45,7 @@ export async function renderFileContent(
53
45
  const codeRows = show.map((line, i) => hl[i] ?? line);
54
46
  const body = theme && total > maxLines ? fadeTail(codeRows, theme) : codeRows;
55
47
 
56
- const tw = options.width ?? termW();
48
+ const tw = options.width ?? terminalWidth();
57
49
  const startLine = offset;
58
50
  const endLine = startLine + show.length - 1;
59
51
  const nw = Math.max(3, String(endLine).length);
@@ -72,13 +64,13 @@ export async function renderFileContent(
72
64
  const rows = wrapTextWithAnsi(code, cw);
73
65
  const pad = " ".repeat(nw);
74
66
  rows.forEach((rowText, r) => {
75
- const gutter = r === 0 ? lnum(ln, nw) : `${FG_LNUM}${pad}${RST}`;
67
+ const gutter = r === 0 ? lineNumber(ln, nw) : `${FG_LNUM}${pad}${RST}`;
76
68
  out.push(`${gutter} ${FG_RULE}│${RST} ${rowText}${RST}`);
77
69
  });
78
70
  continue;
79
71
  }
80
72
  const display = truncateToWidth(code, cw, `${FG_DIM}›`);
81
- out.push(`${lnum(ln, nw)} ${FG_RULE}│${RST} ${display}${RST}`);
73
+ out.push(`${lineNumber(ln, nw)} ${FG_RULE}│${RST} ${display}${RST}`);
82
74
  }
83
75
 
84
76
  out.push(rule(tw));
@@ -210,7 +202,7 @@ function renderLsGrid(
210
202
  }
211
203
 
212
204
  // Layout into columns that fit the terminal width
213
- const tw = termW();
205
+ const tw = terminalWidth();
214
206
  const GAP = 3; // spaces between columns
215
207
  const rows = layoutGrid(cells, cellWidths, tw, GAP);
216
208
 
package/src/result.ts ADDED
@@ -0,0 +1,59 @@
1
+ import type { ToolContent, ToolImageContent, ToolResultLike, ToolTextContent } from "./types.ts";
2
+
3
+ export function isTextContent(content: ToolContent): content is ToolTextContent {
4
+ return content.type === "text";
5
+ }
6
+
7
+ export function isImageContent(content: ToolContent): content is ToolImageContent {
8
+ return content.type === "image";
9
+ }
10
+
11
+ export function getTextContent(result: ToolResultLike): string {
12
+ return (
13
+ result.content
14
+ ?.filter(isTextContent)
15
+ .map((content) => content.text || "")
16
+ .join("\n") ?? ""
17
+ );
18
+ }
19
+
20
+ /** Add renderer metadata without discarding execution metadata from the upstream tool. */
21
+ export function setResultDetails<T>(result: ToolResultLike, details: T): void {
22
+ const upstream =
23
+ result.details && typeof result.details === "object"
24
+ ? (result.details as Record<string, unknown>)
25
+ : undefined;
26
+ result.details = upstream ? { ...upstream, ...details } : details;
27
+ }
28
+
29
+ export function makeTextResult<TDetails>(
30
+ text: string,
31
+ details: TDetails,
32
+ ): ToolResultLike<TDetails> {
33
+ return {
34
+ content: [{ type: "text", text }],
35
+ details,
36
+ };
37
+ }
38
+
39
+ /** Details of an action tool (download, proc): an outcome plus model-facing lines or an error. */
40
+ export interface ActionResultDetails {
41
+ action: string;
42
+ ok: boolean;
43
+ lines: string[];
44
+ error?: string;
45
+ }
46
+
47
+ /** Tool result for an action: the error, else the lines, else `<action> ok`. */
48
+ export function makeActionResult<TDetails extends ActionResultDetails>(details: TDetails) {
49
+ return {
50
+ content: [
51
+ {
52
+ type: "text" as const,
53
+ text: details.error ?? (details.lines.join("\n") || `${details.action} ok`),
54
+ },
55
+ ],
56
+ details,
57
+ isError: !details.ok,
58
+ };
59
+ }
package/src/shell-tool.ts CHANGED
@@ -10,9 +10,19 @@
10
10
 
11
11
  import type { AgentToolUpdateCallback, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
12
  import { type CollapseState, tickCollapse } from "@xynogen/pix-runtime/collapse";
13
+ import { getErrorMessage } from "@xynogen/pix-runtime/errors";
13
14
  import { resolveBaseBackground } from "./ansi.ts";
14
15
  import { collapsedCommandRow, commandPreview } from "./command-preview.ts";
16
+ import { BODY_PAD, bodyLine, frameToolResult, outputBodyRows, reuseText } from "./frame.ts";
17
+ import {
18
+ dotJoin,
19
+ hideCollapsedToolCall,
20
+ renderRow,
21
+ renderTitle,
22
+ renderToolError,
23
+ } from "./render-row.ts";
15
24
  import { renderBashOutput } from "./renderers.ts";
25
+ import { getTextContent, isTextContent, setResultDetails } from "./result.ts";
16
26
  import type { ToolContext } from "./tools/context.ts";
17
27
  import type {
18
28
  BashParams,
@@ -22,23 +32,7 @@ import type {
22
32
  ToolFactory,
23
33
  ToolResultLike,
24
34
  } from "./types.ts";
25
- import {
26
- BODY_PAD,
27
- bodyLine,
28
- dotJoin,
29
- fillToolBackground,
30
- frameToolResult,
31
- getErrorMessage,
32
- getTextContent,
33
- hideCollapsedToolCall,
34
- isTextContent,
35
- outputBodyRows,
36
- renderRow,
37
- renderTitle,
38
- renderToolError,
39
- reuseText,
40
- setResultDetails,
41
- } from "./utils.ts";
35
+ import { fillToolBackground } from "./utils.ts";
42
36
  import { formatDuration } from "./widget-format.ts";
43
37
 
44
38
  export interface ShellToolOptions {
@@ -102,7 +96,7 @@ export function registerShellTool(
102
96
  pi.registerTool({
103
97
  ...origTool,
104
98
  name,
105
- // Full-width framing (rules + bg fill) baked at termW(); the default
99
+ // Full-width framing (rules + bg fill) baked at terminalWidth(); the default
106
100
  // Box shell pads x by 1 and re-wraps at width-2, splitting every line.
107
101
  renderShell: "self",
108
102
 
@@ -250,3 +244,143 @@ export function registerShellTool(
250
244
  },
251
245
  });
252
246
  }
247
+
248
+ // ── Approval-gated command tools (ssh_run, sudo_run) ─────────────────────────
249
+
250
+ /** Lifecycle of a command that waits for user approval, then runs once. */
251
+ export type GatedCommandOutcome =
252
+ | "awaiting-approval"
253
+ | "running"
254
+ | "success"
255
+ | "denied"
256
+ | "timed-out"
257
+ | "cancelled"
258
+ | "error";
259
+
260
+ /** The result fields every gated command tool reports. */
261
+ export interface GatedCommandDetails {
262
+ command: string;
263
+ outcome: GatedCommandOutcome;
264
+ exitCode?: number;
265
+ lineCount?: number;
266
+ truncated?: boolean;
267
+ errorKind?: string;
268
+ _render?: string;
269
+ }
270
+
271
+ export type GatedCancellationKind = "denied" | "timeout" | "missing-password" | "aborted";
272
+
273
+ /** A closed approval overlay (timeout, deny, or no password) as an outcome plus a message. */
274
+ export function gatedCancellation(action: string): {
275
+ outcome: "timed-out" | "denied" | "cancelled";
276
+ cancellationKind: GatedCancellationKind;
277
+ text: string;
278
+ } {
279
+ if (action === "timeout")
280
+ return {
281
+ outcome: "timed-out",
282
+ cancellationKind: "timeout",
283
+ text: "Cancelled — Timed out — auto-denied.",
284
+ };
285
+ if (action === "denied")
286
+ return { outcome: "denied", cancellationKind: "denied", text: "Cancelled — Denied by user." };
287
+ return {
288
+ outcome: "cancelled",
289
+ cancellationKind: "missing-password",
290
+ text: "Cancelled — Cancelled — no password entered.",
291
+ };
292
+ }
293
+
294
+ /** One line of untrusted text: controls and runs of whitespace fold to single spaces. */
295
+ export function safeOneLine(value: string): string {
296
+ return value
297
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")
298
+ .replace(/\s+/g, " ")
299
+ .trim();
300
+ }
301
+
302
+ /** Collapsed-row meta: the terminal outcome, else exit code, extras, line count, truncation. */
303
+ export function gatedCommandMeta(
304
+ details: GatedCommandDetails,
305
+ errorLabels: Record<string, string>,
306
+ extras: Array<string | false | undefined> = [],
307
+ ): string {
308
+ if (details.outcome === "denied") return "denied";
309
+ if (details.outcome === "timed-out") return "timed out";
310
+ if (details.outcome === "cancelled") return "cancelled";
311
+ const label = details.errorKind ? errorLabels[details.errorKind] : undefined;
312
+ if (label) return label;
313
+ const hasLines = typeof details.lineCount === "number" && details.lineCount > 0;
314
+ return dotJoin([
315
+ typeof details.exitCode === "number" && `exit ${details.exitCode}`,
316
+ ...extras,
317
+ hasLines && `${details.lineCount} ${details.lineCount === 1 ? "line" : "lines"}`,
318
+ details.truncated && "truncated",
319
+ ]);
320
+ }
321
+
322
+ /**
323
+ * Result card for a gated command once its details are known: collapsed row when finished,
324
+ * a muted status line while waiting or running, the diagnostic on failure, else the output.
325
+ */
326
+ export function renderGatedCommandResult(
327
+ result: ToolResultLike,
328
+ details: GatedCommandDetails,
329
+ opts: { name: string; target: string; meta: string },
330
+ isPartial: boolean,
331
+ theme: ThemeLike,
332
+ renderCtx: RenderContextLike,
333
+ ) {
334
+ const text = reuseText(renderCtx.lastComponent);
335
+ const completed = (isError: boolean) => frameToolResult(text, theme, isError);
336
+ const status = details.outcome === "success" ? "success" : "error";
337
+ const running = details.outcome === "awaiting-approval" || details.outcome === "running";
338
+
339
+ if (
340
+ !isPartial &&
341
+ !running &&
342
+ tickCollapse(
343
+ opts.name,
344
+ renderCtx.state as CollapseState,
345
+ renderCtx.invalidate,
346
+ renderCtx.expanded,
347
+ )
348
+ ) {
349
+ return collapsedCommandRow(
350
+ renderRow(theme, opts.name, opts.target, opts.meta, status).trimEnd(),
351
+ safeOneLine(details.command),
352
+ theme,
353
+ );
354
+ }
355
+
356
+ if (running) {
357
+ text.setText(
358
+ fillToolBackground(`${BODY_PAD}${theme.fg("muted", getTextContent(result) || "working")}`),
359
+ );
360
+ return text;
361
+ }
362
+
363
+ if (details.outcome !== "success" && details.errorKind !== "exit-code") {
364
+ const diagnostic = getTextContent(result) || "Error";
365
+ text.setText(
366
+ details.outcome === "error"
367
+ ? renderToolError(diagnostic, theme)
368
+ : fillToolBackground(`${BODY_PAD}${theme.fg("warning", diagnostic)}`),
369
+ );
370
+ return isPartial ? text : completed(true);
371
+ }
372
+
373
+ const code = typeof details.exitCode === "number" ? details.exitCode : null;
374
+ const rendered = typeof details._render === "string" ? details._render : "";
375
+ if (!rendered) {
376
+ const { summary } = renderBashOutput(rendered, code, theme);
377
+ text.setText(fillToolBackground(`${BODY_PAD}${summary}`));
378
+ return isPartial ? text : completed(details.outcome !== "success");
379
+ }
380
+
381
+ // Every result (including single-line) is framed; the rules follow exit status: green ok,
382
+ // red failure. The `✓ exit N` header is dropped — the collapsed row already carries status.
383
+ const rows = outputBodyRows(rendered.split("\n"), theme, renderCtx, status, isPartial);
384
+ text.setText(fillToolBackground(rows.join("\n")));
385
+ return text;
386
+ }