proper-base 0.2.8 → 0.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.
package/README.md CHANGED
@@ -29,7 +29,7 @@ and footer layout.
29
29
 
30
30
  | Input | Behavior |
31
31
  | --- | --- |
32
- | Shift+Enter or Alt+Enter | Insert a newline. Alt+Enter no longer queues a follow-up. |
32
+ | Alt+Enter | Insert a newline instead of queuing a follow-up. Pi's own Shift+Enter and Ctrl+J stay intact. |
33
33
  | Home | Move to the current visible-row start, then the full prompt start. |
34
34
  | End | Move to the current logical-line end, then the full prompt end. |
35
35
  | Ctrl+C with text | Clear the prompt without arming exit. |
@@ -158,7 +158,7 @@ highlight. Custom replacement footers are not changed.
158
158
 
159
159
  ## Install
160
160
 
161
- Node 22.19 or newer is required. The package is tested against Pi 0.84.2.
161
+ Node 22.19 or newer is required. The package is tested against Pi 0.84.4.
162
162
 
163
163
  From npm:
164
164
 
package/index.ts CHANGED
@@ -15,7 +15,9 @@ import {
15
15
  type ExtensionAPI,
16
16
  type ExtensionContext,
17
17
  getAgentDir,
18
+ SessionManager,
18
19
  } from "@earendil-works/pi-coding-agent";
20
+ import { matchesKey } from "@earendil-works/pi-tui";
19
21
 
20
22
  import {
21
23
  installAutocompleteDetails,
@@ -23,6 +25,7 @@ import {
23
25
  installModelAutocompleteSubmit,
24
26
  sortModelAutocompleteDescending,
25
27
  } from "./src/autocomplete-details.ts";
28
+ import { installClipboardLeakGuard } from "./src/clipboard-guard.ts";
26
29
  import { commitGuardReason } from "./src/commit-guard.ts";
27
30
  import {
28
31
  installEditorNavigation,
@@ -30,6 +33,11 @@ import {
30
33
  installReverseHistorySearch,
31
34
  type ReverseHistorySearchController,
32
35
  } from "./src/editor-navigation.ts";
36
+ import {
37
+ FastOverlay,
38
+ fastToggleNotice,
39
+ isFastToggle,
40
+ } from "./src/fast-mode.ts";
33
41
  import { installFooterColors } from "./src/footer-colors.ts";
34
42
  import {
35
43
  isRecallable,
@@ -40,17 +48,20 @@ import {
40
48
  import { type HistoryGuard, installHistoryGuard } from "./src/history-guard.ts";
41
49
  import { omitPriorTurnImages } from "./src/image-context.ts";
42
50
  import {
43
- enableScribeImageCapability,
51
+ enableScribeCapabilities,
44
52
  type ImagePreviewController,
45
53
  installImagePreview,
46
54
  } from "./src/image-preview.ts";
47
55
  import { installJumpToBottom } from "./src/jump-to-bottom.ts";
56
+ import { installOsc8LinkIds } from "./src/osc8-link-ids.ts";
48
57
  import {
49
58
  createPromptDisplay,
50
59
  PROMPT_DISPLAY_ENTRY,
51
60
  } from "./src/prompt-display.ts";
52
61
  import { installPromptJump } from "./src/prompt-jump.ts";
53
62
  import { installRecorder } from "./src/recorder.ts";
63
+ import { installSelectionDismiss } from "./src/selection-dismiss.ts";
64
+ import { installFastSessionList } from "./src/session-list.ts";
54
65
  import { pinSkillContext } from "./src/skill-context.ts";
55
66
  import { installSmartSelection } from "./src/smart-selection.ts";
56
67
  import {
@@ -64,6 +75,7 @@ import {
64
75
  type TranscriptCleanupController,
65
76
  } from "./src/transcript-cleanup.ts";
66
77
  import { normalizeCpaTransientError } from "./src/transient-retry.ts";
78
+ import { installWheelScrollLines } from "./src/wheel-scroll.ts";
67
79
 
68
80
  /** Prompts seeded into the editor. Older prompts past this point are dropped. */
69
81
  const MAX_ENTRIES = 200;
@@ -111,10 +123,11 @@ function installKeybindings(keybindings: EditorKeybindings): void {
111
123
  "ctrl+shift+v" as const,
112
124
  ]),
113
125
  ];
126
+ // Shift+Enter is already Pi's `tui.input.newLine` default; only Alt+Enter
127
+ // needs adding, and only because it must leave `app.message.followUp`.
114
128
  const newLineKeys = [
115
129
  ...new Set([
116
130
  ...keybindings.getKeys("tui.input.newLine"),
117
- "shift+enter" as const,
118
131
  "alt+enter" as const,
119
132
  ]),
120
133
  ];
@@ -162,8 +175,33 @@ type PendingPrompt = {
162
175
  processed: boolean;
163
176
  cancelled: boolean;
164
177
  entryId?: string;
178
+ originId?: string | undefined;
165
179
  };
166
- type RestoreRequest = { entryId: string };
180
+ type RestoreRequest = { entryId: string; originId?: string | undefined };
181
+
182
+ /**
183
+ * Extensions may append transcript entries between submission and the prompt's
184
+ * own session entry; proper-pacify writes one before it rewrites the text. Those
185
+ * entries are the prompt's parents, so navigating to the prompt keeps them and
186
+ * leaves orphan rows behind. Aim at the leaf the submission started from, unless
187
+ * it is a prompt entry of its own (navigating there would drop that turn too) or
188
+ * no longer an ancestor because the tree moved meanwhile.
189
+ */
190
+ function cancelTargetId(
191
+ ctx: ExtensionContext,
192
+ request: RestoreRequest,
193
+ ): string {
194
+ if (!request.originId) return request.entryId;
195
+ const origin = ctx.sessionManager.getEntry(request.originId);
196
+ if (!origin || origin.type === "custom_message") return request.entryId;
197
+ if (origin.type === "message" && origin.message.role === "user") {
198
+ return request.entryId;
199
+ }
200
+ const ancestor = ctx.sessionManager
201
+ .getBranch(request.entryId)
202
+ .some((entry) => entry.id === request.originId);
203
+ return ancestor ? request.originId : request.entryId;
204
+ }
167
205
 
168
206
  /**
169
207
  * `details` shape of the `ask_user_question` tool result, from
@@ -213,19 +251,56 @@ function decodeModelReference(value: string): ModelReference | undefined {
213
251
  }
214
252
 
215
253
  export default function (pi: ExtensionAPI) {
216
- enableScribeImageCapability();
254
+ // @lat: [[lat.md/proper-base/proper-base#proper-base#Clipboard leak guard]]
255
+ installClipboardLeakGuard();
256
+ enableScribeCapabilities();
257
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session listing]]
258
+ installFastSessionList(SessionManager, getAgentDir());
259
+
260
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Fast tier scopes]]
261
+ const fastOverlay = new FastOverlay(getAgentDir());
262
+ pi.on("before_provider_request", (event, ctx) =>
263
+ fastOverlay.rewritePayload(event.payload, ctx.model ?? undefined),
264
+ );
265
+ pi.registerCommand?.("fast-global", {
266
+ description: "Toggle CLIProxyAPI Fast mode for all sessions.",
267
+ handler: async (args, ctx) => {
268
+ if (args.trim()) {
269
+ ctx.ui.notify("Usage: /fast-global", "error");
270
+ return;
271
+ }
272
+ let enabled: boolean;
273
+ try {
274
+ enabled = fastOverlay.toggleGlobal();
275
+ } catch (error) {
276
+ const message = error instanceof Error ? error.message : String(error);
277
+ ctx.ui.notify(`Failed to save Fast mode: ${message}`, "error");
278
+ return;
279
+ }
280
+ const notice = fastToggleNotice({
281
+ scope: "global",
282
+ enabled,
283
+ otherEnabled: fastOverlay.isSessionEnabled(),
284
+ modelSupported: fastOverlay.supportsModel(ctx.model ?? undefined),
285
+ });
286
+ ctx.ui.notify(notice.message, notice.level);
287
+ },
288
+ });
217
289
 
218
290
  let removeFooterColors: (() => void) | undefined;
219
291
  let removeJumpToBottom: (() => void) | undefined;
220
292
  let removePromptJump: (() => void) | undefined;
221
293
  let removePromptClear: (() => void) | undefined;
222
294
  let removeSmartSelection: (() => void) | undefined;
295
+ let removeSelectionDismiss: (() => void) | undefined;
296
+ let removeOsc8LinkIds: (() => void) | undefined;
223
297
  let imagePreview: ImagePreviewController | undefined;
224
298
  let removeTerminalInput: (() => void) | undefined;
225
299
  let transcriptCleanup: TranscriptCleanupController | undefined;
226
300
  let activeEditor: PromptEditor | undefined;
227
301
  let activeTui: EditorTui | undefined;
228
302
  let submittedPrompt: string | undefined;
303
+ let submittedOriginId: string | undefined;
229
304
  let pendingPrompt: PendingPrompt | undefined;
230
305
  let restoreRequest: RestoreRequest | undefined;
231
306
  let sessionTitlePending = false;
@@ -299,11 +374,12 @@ export default function (pi: ExtensionAPI) {
299
374
 
300
375
  const target = ctx.sessionManager.getEntry(request.entryId);
301
376
  if (target?.type !== "message" || target.message.role !== "user") return;
377
+ const targetId = cancelTargetId(ctx, request);
302
378
  try {
303
- if (ctx.sessionManager.getLeafId() === request.entryId) {
304
- pi.appendEntry(CANCEL_ANCHOR, { targetId: request.entryId });
379
+ if (ctx.sessionManager.getLeafId() === targetId) {
380
+ pi.appendEntry(CANCEL_ANCHOR, { targetId });
305
381
  }
306
- await ctx.navigateTree(request.entryId, { summarize: false });
382
+ await ctx.navigateTree(targetId, { summarize: false });
307
383
  } catch (error) {
308
384
  ctx.ui.notify(
309
385
  `Could not remove cancelled prompt: ${error instanceof Error ? error.message : String(error)}`,
@@ -329,6 +405,7 @@ export default function (pi: ExtensionAPI) {
329
405
  if (event.source !== "interactive" || !event.text.trim()) return;
330
406
  pendingPrompt = {
331
407
  text: submittedPrompt ?? event.text,
408
+ originId: submittedPrompt ? submittedOriginId : undefined,
332
409
  processed: false,
333
410
  cancelled: false,
334
411
  };
@@ -348,7 +425,13 @@ export default function (pi: ExtensionAPI) {
348
425
  event.message.role === "assistant" &&
349
426
  event.message.stopReason !== "aborted"
350
427
  ) {
351
- pendingPrompt.processed = true;
428
+ // Streaming opens the assistant message with a "pending" partial as
429
+ // soon as response headers arrive — instantly behind a local proxy,
430
+ // with zero tokens produced. That is not assistant processing yet;
431
+ // content arrival marks it through message_update instead.
432
+ if (event.message.stopReason !== "pending") {
433
+ pendingPrompt.processed = true;
434
+ }
352
435
  imagePreview?.clear();
353
436
  }
354
437
  });
@@ -454,7 +537,7 @@ export default function (pi: ExtensionAPI) {
454
537
  ? ctx.sessionManager.getEntry(candidate.entryId)
455
538
  : findPendingEntry(ctx);
456
539
  if (entry?.type === "message" && entry.message.role === "user") {
457
- restoreRequest = { entryId: entry.id };
540
+ restoreRequest = { entryId: entry.id, originId: candidate.originId };
458
541
  pendingPrompt = undefined;
459
542
  pi.sendUserMessage(`/${CANCEL_PROMPT_COMMAND}`, {
460
543
  expandPromptTemplates: true,
@@ -489,6 +572,10 @@ export default function (pi: ExtensionAPI) {
489
572
  removePromptClear = undefined;
490
573
  removeSmartSelection?.();
491
574
  removeSmartSelection = undefined;
575
+ removeSelectionDismiss?.();
576
+ removeSelectionDismiss = undefined;
577
+ removeOsc8LinkIds?.();
578
+ removeOsc8LinkIds = undefined;
492
579
  imagePreview?.dispose();
493
580
  imagePreview = undefined;
494
581
  removeTerminalInput?.();
@@ -505,6 +592,8 @@ export default function (pi: ExtensionAPI) {
505
592
  });
506
593
 
507
594
  pi.on("session_start", async (_event, ctx) => {
595
+ // Session Fast never survives into a new or restored session.
596
+ fastOverlay.resetSession();
508
597
  promptDisplay.restore(ctx.sessionManager.getBranch());
509
598
  sessionTitlePending =
510
599
  !pi.getSessionName?.() &&
@@ -569,6 +658,10 @@ export default function (pi: ExtensionAPI) {
569
658
  !sourceText.trimStart().startsWith("!")
570
659
  ) {
571
660
  submittedPrompt = sourceText;
661
+ // Captured here rather than on the `input` event: extensions that
662
+ // wrap Pi's input dispatch have already appended their own entries
663
+ // by the time that event reaches this extension.
664
+ submittedOriginId = ctx.sessionManager.getLeafId() ?? undefined;
572
665
  }
573
666
  };
574
667
 
@@ -582,11 +675,24 @@ export default function (pi: ExtensionAPI) {
582
675
  new CustomEditor(tui, theme, keybindings);
583
676
  activeEditor = editor as PromptEditor;
584
677
  activeTui = tui;
678
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Wheel scroll rate]]
679
+ installWheelScrollLines(tui);
585
680
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Settled transcript]]
586
681
  transcriptCleanup?.uninstall();
587
682
  transcriptCleanup = installTranscriptCleanup(tui, ctx);
588
683
  removeSmartSelection?.();
589
684
  removeSmartSelection = installSmartSelection(tui);
685
+ removeSelectionDismiss?.();
686
+ // The copy action reads the active selection after this listener runs,
687
+ // so its keystroke must not dismiss the selection it is about to copy.
688
+ removeSelectionDismiss = installSelectionDismiss(tui, (data) =>
689
+ keybindings
690
+ .getKeys("app.message.copy")
691
+ .some((key) => matchesKey(data, key)),
692
+ );
693
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Hyperlink identity]]
694
+ removeOsc8LinkIds?.();
695
+ removeOsc8LinkIds = installOsc8LinkIds(tui);
590
696
  historyGuard = installHistoryGuard(editor);
591
697
  removeJumpToBottom?.();
592
698
  removeJumpToBottom = installJumpToBottom(editor, tui);
@@ -606,6 +712,20 @@ export default function (pi: ExtensionAPI) {
606
712
  editor,
607
713
  record,
608
714
  (text) => imagePreview?.prepare(text) ?? text,
715
+ // pi dispatches extension commands before the `input` event, so the
716
+ // provider's global `/fast` can only be repurposed as a session
717
+ // toggle by consuming it at the editor before pi ever parses it.
718
+ (text) => {
719
+ if (!isFastToggle(text)) return false;
720
+ const notice = fastToggleNotice({
721
+ scope: "session",
722
+ enabled: fastOverlay.toggleSession(),
723
+ otherEnabled: fastOverlay.isGlobalEnabled(),
724
+ modelSupported: fastOverlay.supportsModel(ctx.model ?? undefined),
725
+ });
726
+ ctx.ui.notify(notice.message, notice.level);
727
+ return true;
728
+ },
609
729
  );
610
730
  installModelAutocompleteSubmit(editor, keybindings);
611
731
  removePromptClear?.();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.2.8",
3
+ "version": "0.4.0",
4
4
  "description": "Baseline Pi behavior for session naming, history, prompt editing, fullscreen navigation, and footer styling",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -53,8 +53,8 @@
53
53
  "@earendil-works/pi-tui": "*"
54
54
  },
55
55
  "devDependencies": {
56
- "@earendil-works/pi-coding-agent": "0.84.2",
57
- "@earendil-works/pi-tui": "0.84.2",
56
+ "@earendil-works/pi-coding-agent": "0.84.4",
57
+ "@earendil-works/pi-tui": "0.84.4",
58
58
  "@types/node": "25.9.5",
59
59
  "typescript": "6.0.2"
60
60
  },
@@ -19,6 +19,16 @@ const INLINE_SLASH_INSTALLED = Symbol.for(
19
19
  "pi-proper-base.inline-slash-autocomplete",
20
20
  );
21
21
 
22
+ /**
23
+ * One collator for the `/model` sort. `localeCompare` with an options object
24
+ * constructs a collator per call, which the per-keystroke sort would pay
25
+ * hundreds of times per keypress.
26
+ */
27
+ const MODEL_ORDER = new Intl.Collator("en", {
28
+ numeric: true,
29
+ sensitivity: "base",
30
+ });
31
+
22
32
  type AutocompleteEditor = Component & {
23
33
  autocompleteList?: {
24
34
  getSelectedItem(): { description?: string } | null;
@@ -192,10 +202,8 @@ export function sortModelAutocompleteDescending(
192
202
  ...suggestions,
193
203
  items: [...items].sort(
194
204
  (a, b) =>
195
- b.label.localeCompare(a.label, "en", {
196
- numeric: true,
197
- sensitivity: "base",
198
- }) || b.value.localeCompare(a.value),
205
+ MODEL_ORDER.compare(b.label, a.label) ||
206
+ b.value.localeCompare(a.value),
199
207
  ),
200
208
  };
201
209
  },
@@ -335,9 +343,17 @@ export function installAutocompleteDetails(
335
343
  const render = target.render.bind(target);
336
344
  target.render = (width: number) => {
337
345
  const lines = render(width);
346
+ // rowsBelow re-renders every component below the editor, so frames
347
+ // without a selected description skip the measurement entirely.
348
+ const description = target.autocompleteList?.getSelectedItem()?.description;
349
+ if (!description) {
350
+ detail.setDescription(undefined, 0);
351
+ releaseOverlay();
352
+ return lines;
353
+ }
338
354
  margin.bottom = lines.length + rowsBelow(tui, target, width);
339
355
  detail.setDescription(
340
- target.autocompleteList?.getSelectedItem()?.description,
356
+ description,
341
357
  Math.max(0, tui.terminal.rows - margin.bottom),
342
358
  );
343
359
  if (detail.isVisible() && isMounted(tui, target)) ensureOverlay();
@@ -0,0 +1,181 @@
1
+ /**
2
+ * pi's bundled `@mariozechner/clipboard` addon constructs a fresh clipboard-rs
3
+ * `ClipboardContext` on every exported call. On X11 each context opens two X
4
+ * connections and a detached service thread, and the crate defines no `Drop`
5
+ * for the context, so every clipboard read leaks both connections for the life
6
+ * of the pi process. Days of pasting across long-lived sessions exhaust Xorg's
7
+ * ~256 client slots, after which every X client on the machine — including the
8
+ * `xclip` calls behind image paste — fails with "Maximum number of clients
9
+ * reached".
10
+ *
11
+ * pi already distrusts the crate for Linux clipboard writes and shells out to
12
+ * platform tools there. This guard extends that policy to the two Linux read
13
+ * paths that still call the addon: `readClipboardText()` (which has no
14
+ * subprocess fallback of its own) and the `hasImage()` probe that runs ahead
15
+ * of pi's complete `xclip`/`wl-paste` image path. macOS and Windows keep the
16
+ * addon: pi has no subprocess clipboard implementation on either.
17
+ */
18
+
19
+ import { spawn } from "node:child_process";
20
+ import { realpathSync } from "node:fs";
21
+ import { createRequire } from "node:module";
22
+
23
+ /** Installed once per process; the flag lives on pi's cached module object. */
24
+ const PATCHED = Symbol.for("proper-base.clipboard-leak-guard");
25
+
26
+ // Mirrors pi's own READ_CLIPBOARD_OPTIONS in dist/utils/clipboard.js.
27
+ const READ_TIMEOUT_MS = 5000;
28
+ const READ_MAX_BUFFER = 50 * 1024 * 1024;
29
+
30
+ interface NativeClipboardModule {
31
+ getText: unknown;
32
+ hasImage: unknown;
33
+ }
34
+
35
+ function isRecord(value: unknown): value is Record<string, unknown> {
36
+ return typeof value === "object" && value !== null;
37
+ }
38
+
39
+ /**
40
+ * Resolve the exact module instance pi loaded. pi's `clipboard-native.js`
41
+ * requires the addon from inside the pi package, and Node's CJS cache is keyed
42
+ * by resolved filename, so a `createRequire` rooted anywhere in that package
43
+ * returns the same exports object. `process.argv[1]` is pi's entry script; its
44
+ * realpath lands inside the package in both the plain and bundled layouts.
45
+ */
46
+ function resolveNativeClipboard(
47
+ entryPoint: string | undefined,
48
+ ): NativeClipboardModule | null {
49
+ if (!entryPoint) return null;
50
+ const bases = [entryPoint];
51
+ try {
52
+ bases.unshift(realpathSync(entryPoint));
53
+ } catch {
54
+ // Keep the raw entry point as the only candidate.
55
+ }
56
+ for (const base of bases) {
57
+ try {
58
+ const loaded: unknown = createRequire(base)("@mariozechner/clipboard");
59
+ if (isRecord(loaded)) return loaded as unknown as NativeClipboardModule;
60
+ } catch {
61
+ // Not resolvable from this base; try the next one.
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /** One bounded asynchronous tool run; null means this tool cannot serve. */
68
+ function runTool(
69
+ command: string,
70
+ args: string[],
71
+ env: NodeJS.ProcessEnv,
72
+ ): Promise<string | null> {
73
+ return new Promise((resolve) => {
74
+ let child: ReturnType<typeof spawn>;
75
+ try {
76
+ child = spawn(command, args, {
77
+ env,
78
+ stdio: ["ignore", "pipe", "ignore"],
79
+ });
80
+ } catch {
81
+ resolve(null);
82
+ return;
83
+ }
84
+ let timer: NodeJS.Timeout | undefined;
85
+ let settled = false;
86
+ const finish = (value: string | null): void => {
87
+ if (settled) return;
88
+ settled = true;
89
+ if (timer) clearTimeout(timer);
90
+ resolve(value);
91
+ };
92
+ // The timeout bounds a stuck clipboard owner; the size cap mirrors pi's
93
+ // own read bounds and stops a pathological selection from accumulating.
94
+ timer = setTimeout(() => {
95
+ child.kill("SIGKILL");
96
+ finish(null);
97
+ }, READ_TIMEOUT_MS);
98
+ timer.unref?.();
99
+ const chunks: Buffer[] = [];
100
+ let size = 0;
101
+ child.on("error", () => finish(null));
102
+ child.stdout?.on("data", (chunk: Buffer) => {
103
+ size += chunk.length;
104
+ if (size > READ_MAX_BUFFER) {
105
+ child.kill("SIGKILL");
106
+ finish(null);
107
+ return;
108
+ }
109
+ chunks.push(chunk);
110
+ });
111
+ child.on("close", (code) => {
112
+ finish(code === 0 ? Buffer.concat(chunks).toString("utf8") : null);
113
+ });
114
+ });
115
+ }
116
+
117
+ /**
118
+ * Read clipboard text through the platform tools pi already trusts for
119
+ * writes. Fully asynchronous: runtime extensions never synchronously wait on
120
+ * child processes, and pi awaits `getText()` anyway.
121
+ */
122
+ export async function readClipboardTextViaTools(
123
+ env: NodeJS.ProcessEnv = process.env,
124
+ ): Promise<string> {
125
+ const attempts: Array<[string, string[]]> = env.WAYLAND_DISPLAY
126
+ ? [
127
+ ["wl-paste", ["--no-newline", "--type", "text"]],
128
+ ["xclip", ["-selection", "clipboard", "-o"]],
129
+ ]
130
+ : [
131
+ ["xclip", ["-selection", "clipboard", "-o"]],
132
+ ["xsel", ["--clipboard", "--output"]],
133
+ ];
134
+ for (const [command, args] of attempts) {
135
+ const text = await runTool(command, args, env);
136
+ if (text !== null) return text;
137
+ }
138
+ return "";
139
+ }
140
+
141
+ export interface ClipboardGuardOptions {
142
+ platform?: NodeJS.Platform;
143
+ env?: NodeJS.ProcessEnv;
144
+ entryPoint?: string;
145
+ /** Test seam; defaults to resolving pi's cached addon instance. */
146
+ loadModule?: () => NativeClipboardModule | null;
147
+ /** Test seam; defaults to the subprocess reader above. */
148
+ readText?: () => string | Promise<string>;
149
+ }
150
+
151
+ // @lat: [[lat.md/proper-base/proper-base#proper-base#Clipboard leak guard]]
152
+ export function installClipboardLeakGuard(
153
+ options: ClipboardGuardOptions = {},
154
+ ): boolean {
155
+ const platform = options.platform ?? process.platform;
156
+ if (platform !== "linux") return false;
157
+ const native = options.loadModule
158
+ ? options.loadModule()
159
+ : resolveNativeClipboard(options.entryPoint ?? process.argv[1]);
160
+ if (
161
+ !native ||
162
+ typeof native.getText !== "function" ||
163
+ typeof native.hasImage !== "function"
164
+ ) {
165
+ return false;
166
+ }
167
+ const flags = native as unknown as Record<PropertyKey, unknown>;
168
+ if (flags[PATCHED]) return true;
169
+ const readText =
170
+ options.readText ?? (() => readClipboardTextViaTools(options.env));
171
+ // pi awaits getText(); an async wrapper keeps that contract, and an empty
172
+ // read becomes `null` through pi's own `text || null`.
173
+ native.getText = async () => readText();
174
+ // hasImage() gates pi's only getImageBinary() call, and on Linux pi's own
175
+ // xclip/wl-paste image path runs immediately after a false, so image paste
176
+ // loses nothing. setText and getImageBinary stay native: pi never calls
177
+ // either on Linux (writes already use the platform tools).
178
+ native.hasImage = () => false;
179
+ flags[PATCHED] = true;
180
+ return true;
181
+ }