@noppu-labs/opencode-permission-reviewer 3.0.0 → 3.1.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,161 @@
1
+ // Ships to the TUI, so it imports no shell module.
2
+
3
+ import type { ActionSegment, ReviewUiStatus } from "../ui-protocol.ts";
4
+ import { ELISION, elideMiddle, keepHead, keepTail } from "../ui-text-elide.ts";
5
+ import {
6
+ type FitPart,
7
+ merged,
8
+ partsColumns,
9
+ shown,
10
+ sliceParts,
11
+ textColumns,
12
+ } from "./fit-parts.ts";
13
+
14
+ export interface ActionFitPart {
15
+ text: string;
16
+ muted: boolean;
17
+ }
18
+
19
+ const ELLIPSIS = "⋯";
20
+ /** Narrowest width that still shows a character on each side of " ⋯ ". */
21
+ const MIN_ELIDED_COLUMNS = 5;
22
+
23
+ /** Collapses line breaks and tabs so a value renders on one row. */
24
+ export const singleLine = (value: string): string =>
25
+ value.replace(/[\r\n\t]+/g, " ");
26
+
27
+ function separatorText(separator: string | undefined): string {
28
+ if (separator === undefined) return "";
29
+ return separator === ";" ? ";" : ` ${separator}`;
30
+ }
31
+
32
+ function segmentParts(segment: ActionSegment): FitPart[] {
33
+ const parts: FitPart[] = [{ text: singleLine(segment.text), muted: false }];
34
+ if (segment.heredocLines !== undefined)
35
+ parts.push({
36
+ text: ` ${ELLIPSIS} ${segment.heredocLines}-line heredoc ${ELLIPSIS}`,
37
+ muted: true,
38
+ });
39
+ parts.push({
40
+ text: separatorText(segment.separator),
41
+ muted: false,
42
+ whole: true,
43
+ });
44
+ return parts;
45
+ }
46
+
47
+ function joined(segments: readonly ActionSegment[]): FitPart[] {
48
+ return segments.flatMap(
49
+ (segment: ActionSegment, index: number): FitPart[] => [
50
+ { text: index === 0 ? "" : " ", muted: false },
51
+ ...segmentParts(segment),
52
+ ],
53
+ );
54
+ }
55
+
56
+ const hiddenCount = (hidden: number): string =>
57
+ ` ${ELLIPSIS} ${hidden} more ${ELLIPSIS} `;
58
+
59
+ /** The first segment, a muted count of the hidden ones, and the most
60
+ * trailing segments that fit; undefined when not even the last one fits,
61
+ * or fewer than three segments leave nothing to hide. */
62
+ function elided(
63
+ segments: readonly ActionSegment[],
64
+ columns: number,
65
+ ): FitPart[] | undefined {
66
+ const [first, ...rest] = segments;
67
+ if (first === undefined) return undefined;
68
+ let fitted: FitPart[] | undefined;
69
+ for (let kept = 1; kept < rest.length; kept += 1) {
70
+ const candidate = [
71
+ ...segmentParts(first),
72
+ { text: hiddenCount(rest.length - kept), muted: true },
73
+ ...joined(rest.slice(-kept)),
74
+ ];
75
+ if (partsColumns(candidate) > columns) break;
76
+ fitted = candidate;
77
+ }
78
+ return fitted;
79
+ }
80
+
81
+ /** The muted marker at the cut: a count of the whole segments hidden when it
82
+ * leaves a column for each side, else " ⋯ ". */
83
+ function cutMarker(hidden: number, columns: number): string {
84
+ const counted = hiddenCount(hidden);
85
+ return hidden > 0 && columns - textColumns(counted) >= 2 ? counted : ELISION;
86
+ }
87
+
88
+ const headOf = (parts: readonly FitPart[], max: number): FitPart[] =>
89
+ sliceParts(parts, 0, textColumns(keepHead(shown(parts), max)));
90
+
91
+ function tailOf(parts: readonly FitPart[], max: number): FitPart[] {
92
+ const columns = partsColumns(parts);
93
+ const tail = keepTail(shown(parts), max);
94
+ return sliceParts(parts, columns - textColumns(tail), columns);
95
+ }
96
+
97
+ /** The start of the first segment and the end of the last (the same segment
98
+ * when there is only one) around a muted marker of their own, so a kept
99
+ * heredoc label never stands in for the cut. Heredocs stay collapsed, and
100
+ * the last segment's label is not shown without its command. */
101
+ function firstAndLast(
102
+ segments: readonly ActionSegment[],
103
+ first: ActionSegment,
104
+ last: ActionSegment,
105
+ columns: number,
106
+ ): FitPart[] {
107
+ const marker = cutMarker(Math.max(0, segments.length - 2), columns);
108
+ const headParts = segmentParts(first);
109
+ const tailParts = segmentParts(last);
110
+ const budget = columns - textColumns(marker);
111
+ let kept = headOf(
112
+ headParts,
113
+ Math.max(Math.ceil(budget / 2), budget - partsColumns(tailParts)),
114
+ );
115
+ let ending = tailOf(tailParts, budget - partsColumns(kept));
116
+ if (first !== last && ending[0]?.muted === true) ending = [];
117
+ if (ending.length === 0) kept = headOf(headParts, budget);
118
+ const spaced = ending[0]?.text.startsWith(" ") ?? true;
119
+ return [
120
+ ...kept,
121
+ { text: spaced ? marker.trimEnd() : marker, muted: true },
122
+ ...ending,
123
+ ];
124
+ }
125
+
126
+ function headAndTail(action: string, columns: number): ActionFitPart[] {
127
+ const parts = elideMiddle(singleLine(action), columns);
128
+ if (parts === undefined)
129
+ return merged([{ text: singleLine(action), muted: false }]);
130
+ return merged([
131
+ { text: parts.head, muted: false },
132
+ { text: ELISION, muted: true },
133
+ { text: parts.tail, muted: false },
134
+ ]);
135
+ }
136
+
137
+ /** A fitting `action` is shown as sent unless a segment collapses a heredoc
138
+ * body, which `action` shows flattened. */
139
+ export function fitAction(
140
+ status: Pick<ReviewUiStatus, "action" | "actionSegments">,
141
+ columns: number,
142
+ ): ActionFitPart[] {
143
+ const width = Math.floor(columns);
144
+ if (!(width > 0)) return [];
145
+ const segments = status.actionSegments ?? [];
146
+ const first = segments[0];
147
+ const last = segments.at(-1);
148
+ const asSent = [{ text: singleLine(status.action), muted: false }];
149
+ const collapsesBody = segments.some(
150
+ (segment: ActionSegment): boolean => segment.heredocLines !== undefined,
151
+ );
152
+ if (!collapsesBody && partsColumns(asSent) <= width) return merged(asSent);
153
+ const full = joined(segments);
154
+ if (first !== undefined && partsColumns(full) <= width) return merged(full);
155
+ if (width < MIN_ELIDED_COLUMNS) return [{ text: ELLIPSIS, muted: true }];
156
+ if (first === undefined || last === undefined)
157
+ return headAndTail(status.action, width);
158
+ return merged(
159
+ elided(segments, width) ?? firstAndLast(segments, first, last, width),
160
+ );
161
+ }
@@ -0,0 +1,60 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import type { ColorInput } from "@opentui/core";
4
+ import type { JSX } from "solid-js";
5
+ import { For } from "solid-js";
6
+ import type { ActionFitPart } from "./action-fit.ts";
7
+ import { textColumns } from "./fit-parts.ts";
8
+
9
+ /** Rows the v1 overlay's action may wrap over; with the overlay's six other
10
+ * rows this stays inside its 12-row cap. */
11
+ const OVERLAY_ACTION_ROWS = 3;
12
+ /** Overlay action-row columns that are not the permission, the action or the
13
+ * actor: the left border, the panel's side padding (2 + 3), the row's indent
14
+ * (2) and the gap after the permission. */
15
+ const OVERLAY_ACTION_INSET = 9;
16
+
17
+ const less = (columns: number, fixed: readonly string[]): number =>
18
+ fixed.reduce(
19
+ (left: number, text: string): number => left - textColumns(text),
20
+ columns,
21
+ );
22
+
23
+ /** Columns a strip row leaves for the action: the terminal width less the
24
+ * strip's one-column side padding and the fixed text sharing the row. */
25
+ export function stripActionColumns(
26
+ columns: number,
27
+ ...fixed: string[]
28
+ ): number {
29
+ return less(columns - 2, fixed);
30
+ }
31
+
32
+ export function overlayActionColumns(
33
+ columns: number,
34
+ permission: string,
35
+ actorName: string | undefined,
36
+ ): number {
37
+ const actor = actorName ? ` · actor ${actorName}` : "";
38
+ return (
39
+ OVERLAY_ACTION_ROWS *
40
+ less(columns - OVERLAY_ACTION_INSET, [permission, actor])
41
+ );
42
+ }
43
+
44
+ /** A fitted action as inline spans: muted parts in `muted`, the rest in
45
+ * `color`. */
46
+ export function ActionSpans(props: {
47
+ parts: ActionFitPart[];
48
+ color: ColorInput;
49
+ muted: ColorInput;
50
+ }): JSX.Element {
51
+ return (
52
+ <For each={props.parts}>
53
+ {(part: ActionFitPart): JSX.Element => (
54
+ <span style={{ fg: part.muted ? props.muted : props.color }}>
55
+ {part.text}
56
+ </span>
57
+ )}
58
+ </For>
59
+ );
60
+ }
@@ -0,0 +1,113 @@
1
+ // Who decided, and why the reasoning reviewer ran, as the TUI shows it.
2
+ import type { HandoffInfo } from "../system-one/backend.ts";
3
+ import type { HandoffTrigger } from "../types.ts";
4
+ import type { ReviewUiStatus } from "../ui-protocol.ts";
5
+
6
+ type PhraseSource = Pick<
7
+ ReviewUiStatus,
8
+ "handoff" | "phase" | "resolution" | "escalationDisposition"
9
+ >;
10
+
11
+ const AFTER: Record<
12
+ Exclude<HandoffTrigger, "jev-failure" | "jev-uncertain-deny">,
13
+ string
14
+ > = {
15
+ "jev-escalate": "after Jev's escalation",
16
+ "jev-uncertain-allow": "after Jev's uncertain approval",
17
+ "jev-gate": "after a safety gate stopped Jev's approval",
18
+ "jev-invalid": "after Jev's invalid response",
19
+ };
20
+
21
+ const CAUSE: Record<Exclude<HandoffTrigger, "jev-failure">, string> = {
22
+ "jev-escalate": "Jev escalated",
23
+ "jev-uncertain-allow": "Jev's approval was uncertain",
24
+ "jev-gate": "a safety gate stopped Jev's approval",
25
+ "jev-invalid": "Jev's response was invalid",
26
+ "jev-uncertain-deny": "Jev's denial was uncertain",
27
+ };
28
+
29
+ /** Last path segment of a provider model id: "omniroute/auto/gpt-6-luna" -> "gpt-6-luna". */
30
+ export function shortModelName(model: string): string {
31
+ const segments = model
32
+ .split("/")
33
+ .map((segment) => segment.trim())
34
+ .filter((segment) => segment.length > 0);
35
+ return segments.at(-1) ?? "";
36
+ }
37
+
38
+ /** The last non-blank path segment, or the whole id when there is none ("///"). */
39
+ export function modelLabel(model: string): string {
40
+ return shortModelName(model) || model;
41
+ }
42
+
43
+ const jevFailed = (kind: string | undefined): string =>
44
+ kind === undefined ? "Jev failed" : `Jev failed (${kind})`;
45
+
46
+ /** A "denied" phase with `escalationDisposition: "deny"` is a fail-closed
47
+ * escalation, not the reasoning reviewer's own block, so it does not confirm
48
+ * Jev's denial. */
49
+ function denialVerdict(status: PhraseSource): string {
50
+ if (status.phase === "approved") return "overturned Jev's denial";
51
+ if (status.phase === "denied" && status.escalationDisposition !== "deny")
52
+ return "confirmed Jev's denial";
53
+ return "after Jev's uncertain denial";
54
+ }
55
+
56
+ /** Undefined on `budget-exhausted` (the reasoning reviewer never ran) and on
57
+ * `reasoning-unavailable` (it made no decision). */
58
+ export function handoffPhrase(status: PhraseSource): string | undefined {
59
+ const { handoff } = status;
60
+ if (
61
+ handoff === undefined ||
62
+ status.resolution === "budget-exhausted" ||
63
+ status.resolution === "reasoning-unavailable"
64
+ )
65
+ return;
66
+ if (handoff.trigger === "jev-failure")
67
+ return `after ${jevFailed(handoff.failureKind)}`;
68
+ if (handoff.trigger === "jev-uncertain-deny") return denialVerdict(status);
69
+ return AFTER[handoff.trigger];
70
+ }
71
+
72
+ /** `decidedBy`, except a `budget-exhausted` status that carries a hand-off,
73
+ * which credits `status.model`: the reasoning reviewer never ran. */
74
+ function creditedModel(status: ReviewUiStatus): string | undefined {
75
+ if (status.handoff !== undefined && status.resolution === "budget-exhausted")
76
+ return status.model;
77
+ return status.decidedBy;
78
+ }
79
+
80
+ /** Line 2's attribution; undefined when no model is credited. */
81
+ export function attributionText(status: ReviewUiStatus): string | undefined {
82
+ const phrase = handoffPhrase(status);
83
+ if (phrase !== undefined && status.handoff !== undefined)
84
+ return `${modelLabel(status.handoff.to)} ${phrase}`;
85
+ const model = modelLabel(creditedModel(status) ?? "");
86
+ return model === "" ? undefined : model;
87
+ }
88
+
89
+ /** Why Jev handed off, for the budget toast ("Jev timed out"). */
90
+ export function handoffCause(handoff: HandoffInfo): string {
91
+ if (handoff.trigger !== "jev-failure") return CAUSE[handoff.trigger];
92
+ return handoff.failureKind === "timeout"
93
+ ? "Jev timed out"
94
+ : jevFailed(handoff.failureKind);
95
+ }
96
+
97
+ /** The progress strip's reviewer: the hand-off while the reasoning reviewer
98
+ * runs, else the model's label. */
99
+ export function reviewerLabel(status: ReviewUiStatus): string {
100
+ if (status.handoff === undefined) return modelLabel(status.model);
101
+ return attributionText(status) ?? modelLabel(status.model);
102
+ }
103
+
104
+ /** Result strip line 2: "<attribution> — <reason>". The reason alone when no
105
+ * model decided or the status is unknown; undefined without a reason. */
106
+ export function resultDetail(status: ReviewUiStatus): string | undefined {
107
+ if (!status.reason) return;
108
+ const attribution =
109
+ status.phase === "unknown" ? undefined : attributionText(status);
110
+ return attribution === undefined
111
+ ? status.reason
112
+ : `${attribution} — ${status.reason}`;
113
+ }
@@ -1,9 +1,14 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
2
 
3
3
  import type { ColorInput } from "@opentui/core";
4
+ import { useTerminalDimensions } from "@opentui/solid";
4
5
  import type { JSX } from "solid-js";
5
6
  import { Show } from "solid-js";
6
7
  import type { ReviewUiStatus } from "../ui-protocol.ts";
8
+ import { type ActionFitPart, fitAction, singleLine } from "./action-fit.ts";
9
+ import { ActionSpans, stripActionColumns } from "./action-spans.tsx";
10
+ import { reviewerLabel } from "./attribution.ts";
11
+ import type { SidebarLine } from "./config-notices.ts";
7
12
 
8
13
  export interface ReviewTheme {
9
14
  backgroundPanel: ColorInput;
@@ -12,12 +17,25 @@ export interface ReviewTheme {
12
17
  info: ColorInput;
13
18
  success: ColorInput;
14
19
  error: ColorInput;
20
+ warning: ColorInput;
15
21
  }
16
22
  export const SPINNER = ["◐", "◓", "◑", "◒"] as const;
17
23
 
18
- /** Collapses line breaks and tabs so a value renders on one row. */
19
- export const singleLine = (value: string): string =>
20
- value.replace(/[\r\n\t]+/g, " ");
24
+ /** The reviewer's config line in the host sidebar; nothing when healthy. */
25
+ export function ConfigNoticeSlot(props: {
26
+ theme: () => ReviewTheme;
27
+ line: SidebarLine | undefined;
28
+ }): JSX.Element {
29
+ return (
30
+ <Show when={props.line} keyed>
31
+ {(line: SidebarLine) => (
32
+ <text fg={props.theme()[line.tone]} wrapMode="none" truncate>
33
+ {singleLine(line.text)}
34
+ </text>
35
+ )}
36
+ </Show>
37
+ );
38
+ }
21
39
 
22
40
  /** Compact, non-modal progress strip for hosts with an editable composer. */
23
41
  export function ReviewProgress(props: {
@@ -29,6 +47,20 @@ export function ReviewProgress(props: {
29
47
  props.frame();
30
48
  return `${(Math.max(0, Date.now() - props.status.emittedAt) / 1_000).toFixed(1)}s`;
31
49
  };
50
+ const terminal = useTerminalDimensions();
51
+ const actor = (): string =>
52
+ props.status.actorName
53
+ ? ` · actor ${singleLine(props.status.actorName)}`
54
+ : "";
55
+ const action = (): ActionFitPart[] =>
56
+ fitAction(
57
+ props.status,
58
+ stripActionColumns(
59
+ terminal().width,
60
+ `${props.status.permission} · `,
61
+ actor(),
62
+ ),
63
+ );
32
64
  return (
33
65
  <box
34
66
  height={2}
@@ -52,7 +84,7 @@ export function ReviewProgress(props: {
52
84
  permission
53
85
  <span style={{ fg: props.theme().textMuted }}>
54
86
  {" "}
55
- · {singleLine(props.status.model)} ·{" "}
87
+ · {singleLine(reviewerLabel(props.status))} ·{" "}
56
88
  {singleLine(props.status.variant)}
57
89
  </span>
58
90
  </text>
@@ -64,7 +96,11 @@ export function ReviewProgress(props: {
64
96
  <span style={{ fg: props.theme().textMuted }}>
65
97
  {props.status.permission} ·{" "}
66
98
  </span>
67
- {singleLine(props.status.action)}
99
+ <ActionSpans
100
+ parts={action()}
101
+ color={props.theme().text}
102
+ muted={props.theme().textMuted}
103
+ />
68
104
  <Show when={props.status.actorName}>
69
105
  <span style={{ fg: props.theme().textMuted }}>
70
106
  {" "}
@@ -0,0 +1,137 @@
1
+ // The server's config warnings in the TUI: one toast per distinct entry per
2
+ // TUI session, and a one-line sidebar summary while any remain. The same
3
+ // `status` read also names the server's reasoning reviewer.
4
+ import { asObjectLike } from "../is-record.ts";
5
+
6
+ interface NoticeLists {
7
+ configWarnings?: readonly string[] | undefined;
8
+ configDegraded?: readonly string[] | undefined;
9
+ }
10
+
11
+ export interface ConfigToast {
12
+ variant: "warning" | "error";
13
+ title: string;
14
+ message: string;
15
+ }
16
+
17
+ export interface SidebarLine {
18
+ text: string;
19
+ tone: "warning" | "error";
20
+ }
21
+
22
+ /** Keyed by the exact text `systemOneRoutingWarnings` emits; a reworded
23
+ * warning falls back to its full text. */
24
+ const SHORT_WARNINGS: Readonly<Record<string, string>> = {
25
+ 'systemOneEscalation "reasoning-first" is inactive: no escalationReviewer is configured; Jev escalations still go to you':
26
+ "reasoning-first inactive (no escalationReviewer)",
27
+ 'systemOneEscalation "reasoning-first" is inactive: the reviewer model is not Jev':
28
+ "reasoning-first inactive (model is not Jev)",
29
+ "systemOneDenialReview is inactive: no escalationReviewer is configured; Jev denials stay final":
30
+ "denial review inactive (no escalationReviewer)",
31
+ "systemOneDenialReview is inactive: the reviewer model is not Jev":
32
+ "denial review inactive (model is not Jev)",
33
+ };
34
+
35
+ const strings = (value: unknown): string[] =>
36
+ Array.isArray(value)
37
+ ? value.filter((entry): entry is string => typeof entry === "string")
38
+ : [];
39
+
40
+ const warningToast = (warning: string): ConfigToast => ({
41
+ variant: "warning",
42
+ title: "Permission reviewer config",
43
+ message: warning,
44
+ });
45
+
46
+ const degradedToast = (reason: string): ConfigToast => ({
47
+ variant: "error",
48
+ title: "Permission reviewer config degraded",
49
+ message: `Automatic approval is disabled: ${reason}.`,
50
+ });
51
+
52
+ /** No dedupe here: `ConfigNotices.update` shows each entry once per session. */
53
+ export function configToasts(
54
+ warnings: readonly string[],
55
+ degraded: readonly string[],
56
+ ): ConfigToast[] {
57
+ return [...degraded.map(degradedToast), ...warnings.map(warningToast)];
58
+ }
59
+
60
+ /** The sidebar summary: the only entry, or the count and the first, degraded
61
+ * reasons first; undefined for a healthy config. */
62
+ export function sidebarLine(
63
+ warnings: readonly string[],
64
+ degraded: readonly string[],
65
+ ): SidebarLine | undefined {
66
+ const items = [
67
+ ...degraded.map((reason) => `auto-approval disabled (${reason})`),
68
+ ...warnings.map((warning) => SHORT_WARNINGS[warning] ?? warning),
69
+ ];
70
+ const first = items[0];
71
+ if (first === undefined) return;
72
+ const tone: SidebarLine["tone"] = degraded.length > 0 ? "error" : "warning";
73
+ const icon = tone === "error" ? "✕" : "⚠";
74
+ const body =
75
+ items.length === 1 ? first : `${items.length} config warnings · ${first}`;
76
+ return { text: `${icon} reviewer: ${body}`, tone };
77
+ }
78
+
79
+ export class ConfigNotices {
80
+ private readonly shown = new Set<string>();
81
+ private warnings: readonly string[] = [];
82
+ private degraded: readonly string[] = [];
83
+ private reviewer: string | undefined;
84
+
85
+ constructor(private readonly show: (toast: ConfigToast) => void) {}
86
+
87
+ /** The server's `escalationReviewer` model from the last applied `status`
88
+ * read; undefined before one, after `reset`, or when none is configured. */
89
+ get reasoningModel(): string | undefined {
90
+ return this.reviewer;
91
+ }
92
+
93
+ /** For another directory's server. Keeps `shown`, so an entry already
94
+ * toasted is not toasted again. */
95
+ reset(): void {
96
+ this.reviewer = undefined;
97
+ this.update({});
98
+ }
99
+
100
+ /** Takes the server's current lists (absent means none) and toasts each
101
+ * entry not yet shown in this TUI session. */
102
+ update(lists: NoticeLists): void {
103
+ this.warnings = lists.configWarnings ?? [];
104
+ this.degraded = lists.configDegraded ?? [];
105
+ for (const toast of configToasts(this.warnings, this.degraded)) {
106
+ const key = `${toast.variant}:${toast.message}`;
107
+ if (this.shown.has(key)) continue;
108
+ this.shown.add(key);
109
+ this.show(toast);
110
+ }
111
+ }
112
+
113
+ /** Reads the lists from the reviewer's `status` RPC. True when applied; a
114
+ * failed call, or one whose connection was dropped, changes nothing. */
115
+ async refresh(
116
+ call: () => Promise<unknown>,
117
+ signal: AbortSignal,
118
+ ): Promise<boolean> {
119
+ try {
120
+ const status = asObjectLike(await call());
121
+ if (status === undefined || signal.aborted) return false;
122
+ const model = status.escalationReviewerModel;
123
+ this.reviewer = typeof model === "string" ? model : undefined;
124
+ this.update({
125
+ configWarnings: strings(status.configWarnings),
126
+ configDegraded: strings(status.configDegraded),
127
+ });
128
+ return true;
129
+ } catch {
130
+ return false;
131
+ }
132
+ }
133
+
134
+ sidebar(): SidebarLine | undefined {
135
+ return sidebarLine(this.warnings, this.degraded);
136
+ }
137
+ }
@@ -0,0 +1,76 @@
1
+ // Measuring, slicing and merging fitted action parts.
2
+
3
+ import { LINE_BREAK } from "../ui-text-elide.ts";
4
+ import type { ActionFitPart } from "./action-fit.ts";
5
+
6
+ /** A part as the fit builds it; `whole` marks one a cut may not split. */
7
+ export interface FitPart extends ActionFitPart {
8
+ whole?: boolean;
9
+ }
10
+
11
+ const STANDALONE_BREAK = new RegExp(`(?<!\\\\)${LINE_BREAK}`);
12
+
13
+ /** Columns `text` takes, one per code point. */
14
+ export function textColumns(text: string): number {
15
+ return Array.from(text).length;
16
+ }
17
+
18
+ export function partsColumns(parts: readonly FitPart[]): number {
19
+ return parts.reduce(
20
+ (sum: number, part: ActionFitPart): number => sum + textColumns(part.text),
21
+ 0,
22
+ );
23
+ }
24
+
25
+ export const shown = (parts: readonly ActionFitPart[]): string =>
26
+ parts.map((part: ActionFitPart): string => part.text).join("");
27
+
28
+ function expandPart(part: FitPart): ActionFitPart[] {
29
+ if (part.muted || !STANDALONE_BREAK.test(part.text))
30
+ return [{ text: part.text, muted: part.muted }];
31
+ return part.text
32
+ .split(STANDALONE_BREAK)
33
+ .flatMap((piece, index) => [
34
+ ...(index === 0 ? [] : [{ text: LINE_BREAK, muted: true }]),
35
+ { text: piece, muted: false },
36
+ ]);
37
+ }
38
+
39
+ /** Drops empty parts, mutes line-break markers, and merges neighbours that
40
+ * share `muted`. */
41
+ export function merged(parts: readonly FitPart[]): ActionFitPart[] {
42
+ const out: ActionFitPart[] = [];
43
+ for (const part of parts.flatMap(expandPart)) {
44
+ const last = out.at(-1);
45
+ if (part.text === "") continue;
46
+ if (last !== undefined && last.muted === part.muted)
47
+ out[out.length - 1] = {
48
+ text: `${last.text}${part.text}`,
49
+ muted: part.muted,
50
+ };
51
+ else out.push(part);
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /** The code points `start` to `end` of `parts`. A muted or `whole` part (a
57
+ * heredoc marker or a separator) is kept whole or dropped, never cut. */
58
+ export function sliceParts(
59
+ parts: readonly FitPart[],
60
+ start: number,
61
+ end: number,
62
+ ): FitPart[] {
63
+ const out: FitPart[] = [];
64
+ let offset = 0;
65
+ for (const part of parts) {
66
+ const chars = Array.from(part.text);
67
+ const from = Math.max(start - offset, 0);
68
+ const to = Math.max(0, Math.min(end - offset, chars.length));
69
+ offset += chars.length;
70
+ const text = chars.slice(from, to).join("");
71
+ const cut = text.trim() !== part.text.trim();
72
+ if (text === "" || ((part.muted || part.whole === true) && cut)) continue;
73
+ out.push({ ...part, text });
74
+ }
75
+ return out;
76
+ }