proper-base 0.5.1 → 0.7.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,310 @@
1
+ import {
2
+ type Component,
3
+ sliceByColumn,
4
+ stripTerminalSequences,
5
+ type TUI,
6
+ visibleWidth,
7
+ wrapTextWithAnsi,
8
+ } from "@earendil-works/pi-tui";
9
+
10
+ const INSTALLED = Symbol.for("pi-proper-base.clipboard-selection");
11
+ type Point = {
12
+ row: number;
13
+ col: number;
14
+ scrollView?: Component;
15
+ boundary?: boolean;
16
+ };
17
+ type Bounds = { start: Point; end: Point };
18
+ type Row = {
19
+ source: string;
20
+ offset: number;
21
+ end: number;
22
+ column: number;
23
+ group: object;
24
+ skip: number;
25
+ };
26
+ type Token = { type: string };
27
+ type MarkdownHost = Component & {
28
+ text: string;
29
+ paddingX: number;
30
+ paddingY: number;
31
+ theme: { codeBlockIndent?: string };
32
+ cachedLines?: string[];
33
+ renderToken(token: Token, width: number, ...rest: unknown[]): string[];
34
+ };
35
+ type Layout = {
36
+ children: Layout[];
37
+ scrollView?: Component;
38
+ scrollContentLines?: readonly string[];
39
+ rect: { width: number };
40
+ };
41
+ type Host = TUI & {
42
+ currentLayout?: { root?: Layout };
43
+ getActiveSelectionText?(): string | undefined;
44
+ getSelectionBounds?(): Bounds | undefined;
45
+ getSelectionColumns?(
46
+ line: string,
47
+ row: number,
48
+ bounds: Bounds,
49
+ ): { start: number; end: number };
50
+ [INSTALLED]?: () => void;
51
+ };
52
+
53
+ function plain(line: string): string {
54
+ return stripTerminalSequences(line).trimEnd();
55
+ }
56
+
57
+ /** Map native wrapping back to the logical line, including spaces lost at wraps. */
58
+ function wrappedRows(
59
+ line: string,
60
+ width: number,
61
+ skip: number,
62
+ ): { lines: string[]; rows: Row[] } | undefined {
63
+ const source = stripTerminalSequences(line);
64
+ const lines = wrapTextWithAnsi(line, width).map(plain);
65
+ const group = {};
66
+ const rows: Row[] = [];
67
+ let offset = 0;
68
+ for (const fragment of lines) {
69
+ let start = offset;
70
+ while (!source.startsWith(fragment, start) && source[start] === " ")
71
+ start++;
72
+ if (!source.startsWith(fragment, start)) return undefined;
73
+ rows.push({
74
+ source,
75
+ offset: start,
76
+ end: start + fragment.length,
77
+ column: 0,
78
+ group,
79
+ skip,
80
+ });
81
+ offset = start + fragment.length;
82
+ }
83
+ return { lines, rows };
84
+ }
85
+
86
+ /**
87
+ * Replay only a Markdown clone. Its native token renderer supplies the logical
88
+ * lines and wrapping widths; the live component and terminal output stay intact.
89
+ */
90
+ function markdownRows(component: MarkdownHost, width: number) {
91
+ const clone = Object.assign(
92
+ Object.create(Object.getPrototypeOf(component)),
93
+ component,
94
+ ) as MarkdownHost;
95
+ delete clone.cachedLines;
96
+ const renderToken = component.renderToken;
97
+ const rows = new Map<number, Row>();
98
+ let depth = 0;
99
+ let blocked = 0;
100
+ let rowOffset = component.paddingY;
101
+ let groups: Array<{ lines: string[]; rows: Row[] }> = [];
102
+ clone.renderToken = function (token, tokenWidth, ...rest) {
103
+ const outer = depth++ === 0;
104
+ if (outer) groups = [];
105
+ const unsupported = ![
106
+ "blockquote",
107
+ "paragraph",
108
+ "text",
109
+ "code",
110
+ "space",
111
+ ].includes(token.type);
112
+ if (unsupported) blocked++;
113
+ const lines = renderToken.call(this, token, tokenWidth, ...rest);
114
+ if (!blocked && token.type !== "blockquote") {
115
+ const indent = stripTerminalSequences(
116
+ this.theme.codeBlockIndent ?? " ",
117
+ ).length;
118
+ for (const [index, line] of lines.entries()) {
119
+ // Code fences are display framing, not source code.
120
+ if (token.type === "code" && (index === 0 || plain(line) === "```"))
121
+ continue;
122
+ for (const logical of line.split(/\r\n|\r|\n/u)) {
123
+ const group = wrappedRows(
124
+ logical,
125
+ tokenWidth,
126
+ token.type === "code" ? indent : 0,
127
+ );
128
+ if (group) groups.push(group);
129
+ }
130
+ }
131
+ }
132
+ if (unsupported) blocked--;
133
+ depth--;
134
+ if (outer) {
135
+ const rendered = lines
136
+ .flatMap((line) => wrapTextWithAnsi(line, tokenWidth))
137
+ .map(plain);
138
+ let cursor = 0;
139
+ for (const group of groups) {
140
+ for (
141
+ let start = cursor;
142
+ start <= rendered.length - group.lines.length;
143
+ start++
144
+ ) {
145
+ const prefixes = group.lines.map((fragment, index) => {
146
+ const line = rendered[start + index] ?? "";
147
+ if (!line.endsWith(fragment)) return undefined;
148
+ const prefix = line.slice(0, line.length - fragment.length);
149
+ return /^[ │]*$/u.test(prefix) ? prefix : undefined;
150
+ });
151
+ if (prefixes.some((prefix) => prefix === undefined)) continue;
152
+ for (const [index, row] of group.rows.entries()) {
153
+ rows.set(rowOffset + start + index, {
154
+ ...row,
155
+ column: component.paddingX + visibleWidth(prefixes[index] ?? ""),
156
+ });
157
+ }
158
+ cursor = start + group.lines.length;
159
+ break;
160
+ }
161
+ }
162
+ rowOffset += rendered.length;
163
+ }
164
+ return lines;
165
+ };
166
+ return { lines: clone.render(width).map(plain), rows };
167
+ }
168
+
169
+ function findScrollBox(box: Layout, scrollView: Component): Layout | undefined {
170
+ if (box.scrollView === scrollView) return box;
171
+ for (const child of box.children ?? []) {
172
+ const found = findScrollBox(child, scrollView);
173
+ if (found) return found;
174
+ }
175
+ return undefined;
176
+ }
177
+
178
+ function selectionRows(
179
+ root: Component,
180
+ width: number,
181
+ source: readonly string[],
182
+ bounds: Bounds,
183
+ ): Map<number, Row> {
184
+ const result = new Map<number, Row>();
185
+ const ambiguous = new Set<number>();
186
+ const sourceLines = source.map(plain);
187
+ function visit(component: Component, available: number, padding: number) {
188
+ const candidate = component as Partial<MarkdownHost> & {
189
+ children?: Component[];
190
+ };
191
+ if (
192
+ typeof candidate.renderToken === "function" &&
193
+ typeof candidate.text === "string" &&
194
+ typeof candidate.paddingX === "number" &&
195
+ typeof candidate.paddingY === "number" &&
196
+ candidate.theme
197
+ ) {
198
+ const mapped = markdownRows(candidate as MarkdownHost, available);
199
+ if (!mapped.lines.some((line) => line.trim())) return;
200
+ const lines = mapped.lines.map((line) =>
201
+ (" ".repeat(padding) + line).trimEnd(),
202
+ );
203
+ for (
204
+ let start = Math.max(0, bounds.start.row - lines.length + 1);
205
+ start <= bounds.end.row;
206
+ start++
207
+ ) {
208
+ if (!lines.every((line, index) => sourceLines[start + index] === line))
209
+ continue;
210
+ for (const [index, row] of mapped.rows) {
211
+ const target = start + index;
212
+ if (result.has(target)) ambiguous.add(target);
213
+ result.set(target, { ...row, column: row.column + padding });
214
+ }
215
+ }
216
+ return;
217
+ }
218
+ const inset =
219
+ typeof candidate.paddingX === "number" ? candidate.paddingX : 0;
220
+ for (const child of candidate.children ?? [])
221
+ visit(child, Math.max(1, available - inset * 2), padding + inset);
222
+ }
223
+ // ponytail: scan Markdown on copy only; add a render-time source map if large transcripts make copying slow.
224
+ visit(root, width, 0);
225
+ for (const row of ambiguous) result.delete(row);
226
+ return result;
227
+ }
228
+
229
+ /** @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Clipboard selection cleanup]] */
230
+ export function installClipboardSelection(tui: TUI): (() => void) | undefined {
231
+ const host = tui as Host;
232
+ if (
233
+ typeof host.getActiveSelectionText !== "function" ||
234
+ typeof host.getSelectionBounds !== "function" ||
235
+ typeof host.getSelectionColumns !== "function"
236
+ )
237
+ return undefined;
238
+ host[INSTALLED]?.();
239
+ const original = host.getActiveSelectionText;
240
+ const own = Object.hasOwn(host, "getActiveSelectionText");
241
+ const wrapped = () => {
242
+ const native = original.call(host);
243
+ const bounds = host.getSelectionBounds?.();
244
+ if (!native || !bounds?.start.scrollView || !host.currentLayout?.root)
245
+ return native;
246
+ const scrollView = bounds.start.scrollView;
247
+ const box = findScrollBox(host.currentLayout.root, scrollView);
248
+ if (!box?.scrollContentLines) return native;
249
+ const getWidth = (
250
+ scrollView as Component & { getContentWidth?(width: number): number }
251
+ ).getContentWidth;
252
+ if (typeof getWidth !== "function") return native;
253
+ const rows = selectionRows(
254
+ scrollView,
255
+ getWidth.call(scrollView, box.rect.width),
256
+ box.scrollContentLines,
257
+ bounds,
258
+ );
259
+ if (rows.size === 0) return native;
260
+ let text = "";
261
+ let previous: { row: Row; end: number } | undefined;
262
+ for (let index = bounds.start.row; index <= bounds.end.row; index++) {
263
+ const line = box.scrollContentLines[index] ?? "";
264
+ const columns = host.getSelectionColumns?.(line, index, bounds);
265
+ if (!columns) return native;
266
+ const row = rows.get(index);
267
+ if (!row) {
268
+ text +=
269
+ (index === bounds.start.row ? "" : "\n") +
270
+ plain(
271
+ sliceByColumn(
272
+ line,
273
+ columns.start,
274
+ Math.max(0, columns.end - columns.start),
275
+ true,
276
+ ),
277
+ );
278
+ previous = undefined;
279
+ continue;
280
+ }
281
+ const fragment = row.source.slice(row.offset, row.end);
282
+ const at = (column: number) =>
283
+ Math.max(
284
+ row.skip,
285
+ row.offset +
286
+ sliceByColumn(fragment, 0, Math.max(0, column - row.column), true)
287
+ .length,
288
+ );
289
+ const start = at(columns.start);
290
+ const end = Math.max(start, at(columns.end));
291
+ if (previous?.row.group === row.group)
292
+ text += row.source.slice(previous.end, start);
293
+ else if (index !== bounds.start.row) text += "\n";
294
+ text += row.source.slice(start, end);
295
+ previous = { row, end };
296
+ }
297
+ return text || undefined;
298
+ };
299
+ host.getActiveSelectionText = wrapped;
300
+ const dispose = () => {
301
+ if (host[INSTALLED] !== dispose) return;
302
+ if (host.getActiveSelectionText === wrapped) {
303
+ if (own) host.getActiveSelectionText = original;
304
+ else delete host.getActiveSelectionText;
305
+ }
306
+ delete host[INSTALLED];
307
+ };
308
+ host[INSTALLED] = dispose;
309
+ return dispose;
310
+ }
package/src/fast-mode.ts CHANGED
@@ -61,6 +61,11 @@ export function isFastToggle(text: string): boolean {
61
61
  export class FastOverlay {
62
62
  private sessionEnabled = false;
63
63
  private modelsCache: { mtimeMs: number; ids: Set<string> } | undefined;
64
+ private display:
65
+ | { provider: string; global: boolean; ids: Set<string> }
66
+ | undefined;
67
+ private displayTimer: ReturnType<typeof setInterval> | undefined;
68
+ private displayChanged: (() => void) | undefined;
64
69
  private readonly agentDir: string;
65
70
  private readonly env: Record<string, string | undefined>;
66
71
 
@@ -90,17 +95,18 @@ export class FastOverlay {
90
95
  return this.sessionEnabled;
91
96
  }
92
97
 
93
- /**
94
- * The provider's Fast default: `CLIPROXYAPI_FAST` when set, else the
95
- * persisted `fast` key. Re-read per call so other sessions' writes count.
96
- */
98
+ /** A valid environment override, which makes the JSON flag read-only. */
99
+ globalEnvironmentOverride(): boolean | undefined {
100
+ const value = this.env.CLIPROXYAPI_FAST;
101
+ return value === undefined ? undefined : parseBooleanSetting(value);
102
+ }
103
+
104
+ /** The effective provider default, re-read for every request. */
97
105
  isGlobalEnabled(): boolean {
98
- const envValue = this.env.CLIPROXYAPI_FAST;
99
- if (envValue !== undefined) {
100
- const parsed = parseBooleanSetting(envValue);
101
- if (parsed !== undefined) return parsed;
102
- }
103
- return readJsonObject(this.configPath())?.fast === true;
106
+ return (
107
+ this.globalEnvironmentOverride() ??
108
+ readJsonObject(this.configPath())?.fast === true
109
+ );
104
110
  }
105
111
 
106
112
  /**
@@ -108,6 +114,9 @@ export class FastOverlay {
108
114
  * the provider's own file format. Write failures propagate to the caller.
109
115
  */
110
116
  toggleGlobal(): boolean {
117
+ if (this.globalEnvironmentOverride() !== undefined) {
118
+ throw new Error("CLIPROXYAPI_FAST is set in the environment");
119
+ }
111
120
  const existing = readJsonObject(this.configPath()) ?? {};
112
121
  const next = !this.isGlobalEnabled();
113
122
  writeFileSync(
@@ -115,6 +124,7 @@ export class FastOverlay {
115
124
  `${JSON.stringify({ ...existing, fast: next }, null, 2)}\n`,
116
125
  "utf8",
117
126
  );
127
+ this.refreshDisplay();
118
128
  return next;
119
129
  }
120
130
 
@@ -131,13 +141,17 @@ export class FastOverlay {
131
141
  /** Whether the provider's cached catalog marks this model Fast-capable. */
132
142
  supportsModel(model: FastModel | undefined): boolean {
133
143
  if (!model || model.provider !== this.providerId()) return false;
144
+ return this.fastModelIds().has(model.id);
145
+ }
146
+
147
+ private fastModelIds(): Set<string> {
134
148
  const path = join(this.agentDir, MODELS_CACHE_FILE_NAME);
135
149
  let mtimeMs: number;
136
150
  try {
137
151
  mtimeMs = statSync(path).mtimeMs;
138
152
  } catch {
139
153
  this.modelsCache = undefined;
140
- return false;
154
+ return new Set();
141
155
  }
142
156
  if (this.modelsCache?.mtimeMs !== mtimeMs) {
143
157
  const ids = readJsonObject(path)?.fastModelIds;
@@ -150,7 +164,62 @@ export class FastOverlay {
150
164
  ),
151
165
  };
152
166
  }
153
- return this.modelsCache.ids.has(model.id);
167
+ return this.modelsCache.ids;
168
+ }
169
+
170
+ /** Refresh outside rendering; request-time reads remain uncached. */
171
+ startDisplayRefresh(onChange: () => void): void {
172
+ this.stopDisplayRefresh();
173
+ this.displayChanged = onChange;
174
+ this.refreshDisplay();
175
+ this.displayTimer = setInterval(() => this.refreshDisplay(), 1000);
176
+ this.displayTimer.unref?.();
177
+ }
178
+
179
+ stopDisplayRefresh(): void {
180
+ clearInterval(this.displayTimer);
181
+ this.displayTimer = undefined;
182
+ this.displayChanged = undefined;
183
+ this.display = undefined;
184
+ }
185
+
186
+ private refreshDisplay(): void {
187
+ if (!this.displayChanged) return;
188
+ const next = {
189
+ provider: this.providerId(),
190
+ global: this.isGlobalEnabled(),
191
+ ids: this.fastModelIds(),
192
+ };
193
+ const previous = this.display;
194
+ this.display = next;
195
+ if (
196
+ !previous ||
197
+ previous.provider !== next.provider ||
198
+ previous.global !== next.global ||
199
+ previous.ids.size !== next.ids.size ||
200
+ [...next.ids].some((id) => !previous.ids.has(id))
201
+ ) {
202
+ this.displayChanged();
203
+ }
204
+ }
205
+
206
+ /** In-memory only: safe on every animation frame and keypress. */
207
+ isEffectiveForDisplay(model: FastModel | undefined): boolean {
208
+ return !!(
209
+ model &&
210
+ this.display &&
211
+ model.provider === this.display.provider &&
212
+ (this.sessionEnabled || this.display.global) &&
213
+ this.display.ids.has(model.id)
214
+ );
215
+ }
216
+
217
+ /** Whether requests for this model currently carry the priority tier. */
218
+ isEffectiveFor(model: FastModel | undefined): boolean {
219
+ return (
220
+ (this.sessionEnabled || this.isGlobalEnabled()) &&
221
+ this.supportsModel(model)
222
+ );
154
223
  }
155
224
 
156
225
  /**
@@ -166,11 +235,11 @@ export class FastOverlay {
166
235
  return undefined;
167
236
  }
168
237
  const record = payload as JsonObject;
169
- const effective = this.sessionEnabled || this.isGlobalEnabled();
170
- if (effective && this.supportsModel(model)) {
238
+ if (this.isEffectiveFor(model)) {
171
239
  if (record.service_tier === PRIORITY_TIER) return undefined;
172
240
  return { ...record, service_tier: PRIORITY_TIER };
173
241
  }
242
+ const effective = this.sessionEnabled || this.isGlobalEnabled();
174
243
  if (!effective && record.service_tier === PRIORITY_TIER) {
175
244
  const { service_tier: _dropped, ...rest } = record;
176
245
  return rest;
@@ -32,6 +32,9 @@ const RAINBOW = [
32
32
  ] as const;
33
33
  const ANIMATION_INTERVAL_MS = 120;
34
34
  const HIGHLIGHT_CYCLE_MS = 4000;
35
+ // Upper bound on how long cached footer lines may survive an input we cannot
36
+ // observe (git branch switches, ctx.ui.setStatus from another extension).
37
+ const BASE_CACHE_TTL_MS = 1000;
35
38
  const USAGE_THROUGH_COST =
36
39
  /^((?:(?:↑|↓|R|W|CH)\S+\s+)*\$\S+(?:\s+\(sub\))?)(?:\s+|$)/;
37
40
  const USAGE_FIELD =
@@ -42,6 +45,7 @@ type FooterTheme = ExtensionContext["ui"]["theme"];
42
45
  type FooterState = {
43
46
  ctx: ExtensionContext;
44
47
  tui: TUI;
48
+ fast: (() => boolean) | undefined;
45
49
  };
46
50
  type FooterController = {
47
51
  update(state: FooterState): void;
@@ -63,17 +67,18 @@ type FooterColorState = {
63
67
  export function installFooterColors(
64
68
  tui: TUI,
65
69
  ctx: ExtensionContext,
70
+ fast?: () => boolean,
66
71
  ): (() => void) | undefined {
67
72
  const footer = findFooter(tui);
68
73
  if (!footer) return undefined;
69
74
 
70
75
  const existing = footer[INSTALLED];
71
76
  if (existing) {
72
- existing.update({ ctx, tui });
77
+ existing.update({ ctx, tui, fast });
73
78
  return existing.uninstall;
74
79
  }
75
80
 
76
- let state = { ctx, tui };
81
+ let state: FooterState = { ctx, tui, fast };
77
82
  let timer: ReturnType<typeof setInterval> | undefined;
78
83
  const ownsRender = Object.hasOwn(footer, "render");
79
84
  const render = footer.render;
@@ -102,6 +107,9 @@ export function installFooterColors(
102
107
  uninstall() {
103
108
  if (footer[INSTALLED] !== controller) return;
104
109
  stopAnimation();
110
+ baseCache.clear();
111
+ baseKey = undefined;
112
+ baseTheme = undefined;
105
113
  if (ownsRender) footer.render = render;
106
114
  else Reflect.deleteProperty(footer, "render");
107
115
  if (dispose) footer.dispose = dispose;
@@ -109,22 +117,68 @@ export function installFooterColors(
109
117
  delete footer[INSTALLED];
110
118
  },
111
119
  };
120
+ // Pi's FooterComponent.render() sums usage over every session entry, and
121
+ // SessionManager.getEntries() allocates a fresh array per call, so a single
122
+ // frame costs O(session entries). layoutFooter needs a second render at a
123
+ // wider width, doubling that. Pi's footer output has no time-dependent part,
124
+ // so cache the raw lines per width and drop them whenever a visible input
125
+ // changes. getLeafId() is O(1) and moves on every appended entry, which is
126
+ // what the usage totals are derived from.
127
+ const baseCache = new Map<number, string[]>();
128
+ let baseKey: string | undefined;
129
+ let baseTheme: FooterTheme | undefined;
130
+ let baseAt = 0;
131
+ const baseLines = (
132
+ at: number,
133
+ key: string,
134
+ theme: FooterTheme,
135
+ now: number,
136
+ ): string[] => {
137
+ if (
138
+ key !== baseKey ||
139
+ theme !== baseTheme ||
140
+ now - baseAt > BASE_CACHE_TTL_MS
141
+ ) {
142
+ baseCache.clear();
143
+ baseKey = key;
144
+ baseTheme = theme;
145
+ baseAt = now;
146
+ }
147
+ let lines = baseCache.get(at);
148
+ if (!lines) {
149
+ lines = render.call(footer, at);
150
+ baseCache.set(at, lines);
151
+ }
152
+ return lines;
153
+ };
154
+
112
155
  footer.render = (width: number) => {
113
156
  const level = state.ctx.thinkingLevel as FooterThinkingLevel;
114
157
  if (level === "max" || level === "ultra") startAnimation();
115
158
  else stopAnimation();
116
159
  const theme = state.ctx.ui.theme;
117
- return colorFooter(
118
- layoutFooter(render.call(footer, width), width, theme, (wide) =>
119
- render.call(footer, wide),
120
- ),
121
- {
122
- level,
123
- model: state.ctx.model?.id,
124
- now: Date.now(),
125
- theme,
126
- },
127
- );
160
+ const model = state.ctx.model?.id;
161
+ const isFast = model ? state.fast?.() === true : false;
162
+ const now = Date.now();
163
+ // A host without getLeafId() only loses entry-driven invalidation; the
164
+ // TTL still bounds staleness. Never let a footer cache key crash render.
165
+ const leafId =
166
+ typeof state.ctx.sessionManager?.getLeafId === "function"
167
+ ? (state.ctx.sessionManager.getLeafId() ?? "")
168
+ : "";
169
+ const key = `${leafId}\u0000${model ?? ""}\u0000${level}\u0000${
170
+ isFast ? "1" : "0"
171
+ }`;
172
+ const base = (at: number) => {
173
+ const lines = baseLines(at, key, theme, now);
174
+ return model && isFast ? tagFast(lines, at, model, theme) : lines;
175
+ };
176
+ return colorFooter(layoutFooter(base(width), width, theme, base), {
177
+ level,
178
+ model,
179
+ now,
180
+ theme,
181
+ });
128
182
  };
129
183
  footer.dispose = () => {
130
184
  controller.uninstall();
@@ -134,6 +188,53 @@ export function installFooterColors(
134
188
  return controller.uninstall;
135
189
  }
136
190
 
191
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Fast tier scopes]]
192
+ /**
193
+ * Append the provider's `fast` chip when the session overlay makes Fast
194
+ * effective but the provider's own global flag is off. Pads are trimmed so
195
+ * the line keeps its width, matching how the provider's label would sit.
196
+ */
197
+ function tagFast(
198
+ lines: string[],
199
+ width: number,
200
+ model: string,
201
+ theme: FooterTheme,
202
+ ): string[] {
203
+ const index = lines.findIndex((line) =>
204
+ stripTerminalSequences(line).includes(model),
205
+ );
206
+ const line = lines[index];
207
+ if (line === undefined) return lines;
208
+ const plain = stripTerminalSequences(line);
209
+ if (/ • fast(?: • |$)/.test(plain)) return lines;
210
+
211
+ const tag = ` • ${theme.fg("warning", "fast")}`;
212
+ const tagWidth = 7;
213
+ const total = visibleWidth(line);
214
+ const pausedAt = plain.lastIndexOf(" • paused");
215
+ const cut = pausedAt >= 0 ? pausedAt : total;
216
+ let head = sliceByColumn(line, 0, cut, true);
217
+ const tail = sliceByColumn(line, cut, total - cut, true);
218
+ const gap = [...plain.slice(0, cut).matchAll(/ {2,}/g)].at(-1);
219
+ if (gap?.index !== undefined) {
220
+ const trim = Math.min(
221
+ gap[0].length - 2,
222
+ Math.max(0, total + tagWidth - width),
223
+ );
224
+ if (trim > 0) {
225
+ head = `${sliceByColumn(head, 0, gap.index, true)}${sliceByColumn(
226
+ head,
227
+ gap.index + trim,
228
+ cut - gap.index - trim,
229
+ true,
230
+ )}`;
231
+ }
232
+ }
233
+ const result = [...lines];
234
+ result[index] = `${head}${tag}${tail}`;
235
+ return result;
236
+ }
237
+
137
238
  function layoutFooter(
138
239
  lines: string[],
139
240
  width: number,
@@ -0,0 +1,49 @@
1
+ // This small protocol ships in independent packages. The root integration
2
+ // test requires identical copies; packages do not depend on one another.
3
+ export const ORIGINAL_INPUT = Symbol.for("proper-pi.original-input.v1");
4
+ const WRAPPER = Symbol.for("proper-pi.method-wrapper.v1");
5
+ type WrapperState = {
6
+ original: unknown;
7
+ descriptor: PropertyDescriptor | undefined;
8
+ active: boolean;
9
+ };
10
+
11
+ export function originalInput(
12
+ text: string,
13
+ options: object | undefined,
14
+ ): string {
15
+ const value = options && Reflect.get(options, ORIGINAL_INPUT);
16
+ return typeof value === "string" ? value : text;
17
+ }
18
+
19
+ /** Owners deactivate their callbacks before disposal. Unlink inactive peers
20
+ * even when shutdown runs in installation order rather than stack order.
21
+ */
22
+ export function installWrapper(
23
+ target: object,
24
+ key: PropertyKey,
25
+ wrapped: object,
26
+ ): () => void {
27
+ const state: WrapperState = {
28
+ original: Reflect.get(target, key),
29
+ descriptor: Object.getOwnPropertyDescriptor(target, key),
30
+ active: true,
31
+ };
32
+ Reflect.set(wrapped, WRAPPER, state);
33
+ Reflect.set(target, key, wrapped);
34
+ return () => {
35
+ state.active = false;
36
+ if (Reflect.get(target, key) !== wrapped) return;
37
+ let previous = state;
38
+ while (typeof previous.original === "function") {
39
+ const prior = Reflect.get(previous.original, WRAPPER) as
40
+ | WrapperState
41
+ | undefined;
42
+ if (!prior || prior.active) break;
43
+ previous = prior;
44
+ }
45
+ if (previous.descriptor)
46
+ Object.defineProperty(target, key, previous.descriptor);
47
+ else Reflect.deleteProperty(target, key);
48
+ };
49
+ }