proper-base 0.3.0 → 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
@@ -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
@@ -17,6 +17,7 @@ import {
17
17
  getAgentDir,
18
18
  SessionManager,
19
19
  } from "@earendil-works/pi-coding-agent";
20
+ import { matchesKey } from "@earendil-works/pi-tui";
20
21
 
21
22
  import {
22
23
  installAutocompleteDetails,
@@ -24,6 +25,7 @@ import {
24
25
  installModelAutocompleteSubmit,
25
26
  sortModelAutocompleteDescending,
26
27
  } from "./src/autocomplete-details.ts";
28
+ import { installClipboardLeakGuard } from "./src/clipboard-guard.ts";
27
29
  import { commitGuardReason } from "./src/commit-guard.ts";
28
30
  import {
29
31
  installEditorNavigation,
@@ -46,11 +48,12 @@ import {
46
48
  import { type HistoryGuard, installHistoryGuard } from "./src/history-guard.ts";
47
49
  import { omitPriorTurnImages } from "./src/image-context.ts";
48
50
  import {
49
- enableScribeImageCapability,
51
+ enableScribeCapabilities,
50
52
  type ImagePreviewController,
51
53
  installImagePreview,
52
54
  } from "./src/image-preview.ts";
53
55
  import { installJumpToBottom } from "./src/jump-to-bottom.ts";
56
+ import { installOsc8LinkIds } from "./src/osc8-link-ids.ts";
54
57
  import {
55
58
  createPromptDisplay,
56
59
  PROMPT_DISPLAY_ENTRY,
@@ -72,6 +75,7 @@ import {
72
75
  type TranscriptCleanupController,
73
76
  } from "./src/transcript-cleanup.ts";
74
77
  import { normalizeCpaTransientError } from "./src/transient-retry.ts";
78
+ import { installWheelScrollLines } from "./src/wheel-scroll.ts";
75
79
 
76
80
  /** Prompts seeded into the editor. Older prompts past this point are dropped. */
77
81
  const MAX_ENTRIES = 200;
@@ -247,7 +251,9 @@ function decodeModelReference(value: string): ModelReference | undefined {
247
251
  }
248
252
 
249
253
  export default function (pi: ExtensionAPI) {
250
- enableScribeImageCapability();
254
+ // @lat: [[lat.md/proper-base/proper-base#proper-base#Clipboard leak guard]]
255
+ installClipboardLeakGuard();
256
+ enableScribeCapabilities();
251
257
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session listing]]
252
258
  installFastSessionList(SessionManager, getAgentDir());
253
259
 
@@ -287,6 +293,7 @@ export default function (pi: ExtensionAPI) {
287
293
  let removePromptClear: (() => void) | undefined;
288
294
  let removeSmartSelection: (() => void) | undefined;
289
295
  let removeSelectionDismiss: (() => void) | undefined;
296
+ let removeOsc8LinkIds: (() => void) | undefined;
290
297
  let imagePreview: ImagePreviewController | undefined;
291
298
  let removeTerminalInput: (() => void) | undefined;
292
299
  let transcriptCleanup: TranscriptCleanupController | undefined;
@@ -418,7 +425,13 @@ export default function (pi: ExtensionAPI) {
418
425
  event.message.role === "assistant" &&
419
426
  event.message.stopReason !== "aborted"
420
427
  ) {
421
- 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
+ }
422
435
  imagePreview?.clear();
423
436
  }
424
437
  });
@@ -561,6 +574,8 @@ export default function (pi: ExtensionAPI) {
561
574
  removeSmartSelection = undefined;
562
575
  removeSelectionDismiss?.();
563
576
  removeSelectionDismiss = undefined;
577
+ removeOsc8LinkIds?.();
578
+ removeOsc8LinkIds = undefined;
564
579
  imagePreview?.dispose();
565
580
  imagePreview = undefined;
566
581
  removeTerminalInput?.();
@@ -660,13 +675,24 @@ export default function (pi: ExtensionAPI) {
660
675
  new CustomEditor(tui, theme, keybindings);
661
676
  activeEditor = editor as PromptEditor;
662
677
  activeTui = tui;
678
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Wheel scroll rate]]
679
+ installWheelScrollLines(tui);
663
680
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Settled transcript]]
664
681
  transcriptCleanup?.uninstall();
665
682
  transcriptCleanup = installTranscriptCleanup(tui, ctx);
666
683
  removeSmartSelection?.();
667
684
  removeSmartSelection = installSmartSelection(tui);
668
685
  removeSelectionDismiss?.();
669
- removeSelectionDismiss = installSelectionDismiss(tui);
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);
670
696
  historyGuard = installHistoryGuard(editor);
671
697
  removeJumpToBottom?.();
672
698
  removeJumpToBottom = installJumpToBottom(editor, tui);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.3.0",
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
  },
@@ -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
+ }
@@ -119,11 +119,18 @@ function installFocusRefresh(tui: TUI, refresh: () => void): () => void {
119
119
  return () => controller.restore();
120
120
  }
121
121
 
122
- export function enableScribeImageCapability(): void {
122
+ /**
123
+ * Pi's terminal allowlist does not know Scribe, so detection leaves Kitty
124
+ * images and OSC 8 hyperlinks off. Scribe supports both. Hyperlinks matter
125
+ * because Pi reopens the OSC 8 sequence on every wrapped physical row, so
126
+ * the terminal's ctrl+click opens the full URL instead of one row's
127
+ * fragment of a hard-wrapped link.
128
+ */
129
+ export function enableScribeCapabilities(): void {
123
130
  if (process.env.TERM_PROGRAM?.toLowerCase() !== "scribe") return;
124
131
  const capabilities = getCapabilities();
125
- if (capabilities.images !== "kitty") {
126
- setCapabilities({ ...capabilities, images: "kitty" });
132
+ if (capabilities.images !== "kitty" || !capabilities.hyperlinks) {
133
+ setCapabilities({ ...capabilities, images: "kitty", hyperlinks: true });
127
134
  }
128
135
  }
129
136
 
@@ -0,0 +1,90 @@
1
+ import type { TUI } from "@earendil-works/pi-tui";
2
+
3
+ const INSTALLED = Symbol.for("pi-proper-base.osc8-link-ids");
4
+ const OSC8_OPEN = "\x1b]8;;";
5
+ const ESC = "\x1b";
6
+ const BEL = "\x07";
7
+
8
+ type TerminalWriter = {
9
+ write(data: string): void;
10
+ [INSTALLED]?: () => void;
11
+ };
12
+
13
+ type TerminalTui = TUI & { terminal?: TerminalWriter };
14
+
15
+ /** FNV-1a of the URI in base36. */
16
+ function linkId(uri: string): string {
17
+ let hash = 0x811c9dc5;
18
+ for (let index = 0; index < uri.length; index++) {
19
+ hash ^= uri.charCodeAt(index);
20
+ hash = Math.imul(hash, 0x01000193);
21
+ }
22
+ return (hash >>> 0).toString(36);
23
+ }
24
+
25
+ /** End of the URI starting at `uriStart`: the position of its BEL or ST
26
+ * terminator, or -1 when the sequence is unterminated or malformed. */
27
+ function uriEndAt(data: string, uriStart: number): number {
28
+ const belAt = data.indexOf(BEL, uriStart);
29
+ const escAt = data.indexOf(ESC, uriStart);
30
+ if (belAt !== -1 && (escAt === -1 || belAt < escAt)) return belAt;
31
+ if (escAt !== -1 && data.startsWith("\\", escAt + 1)) return escAt;
32
+ return -1;
33
+ }
34
+
35
+ /**
36
+ * Give anonymous OSC 8 opens a stable URI-derived id. Pi reopens a wrapped
37
+ * hyperlink on every physical row without an id, so terminals assign each
38
+ * row its own link identity and hover-highlight one row at a time. A shared
39
+ * id lets id-aware terminals treat all rows of one link as a unit. Closes
40
+ * (empty URI), opens that already carry params, and malformed or split
41
+ * sequences stay untouched, and data without an anonymous open passes
42
+ * through by reference.
43
+ */
44
+ export function tagAnonymousOsc8Links(data: string): string {
45
+ let openAt = data.indexOf(OSC8_OPEN);
46
+ if (openAt === -1) return data;
47
+ let result = "";
48
+ let copied = 0;
49
+ while (openAt !== -1) {
50
+ const uriStart = openAt + OSC8_OPEN.length;
51
+ const uriEnd = uriEndAt(data, uriStart);
52
+ if (uriEnd > uriStart) {
53
+ const uri = data.slice(uriStart, uriEnd);
54
+ result += `${data.slice(copied, openAt)}${ESC}]8;id=${linkId(uri)};${uri}`;
55
+ copied = uriEnd;
56
+ }
57
+ openAt = data.indexOf(OSC8_OPEN, uriStart);
58
+ }
59
+ if (copied === 0) return data;
60
+ return result + data.slice(copied);
61
+ }
62
+
63
+ /**
64
+ * Rewrite TUI terminal writes so wrapped links share one hyperlink id.
65
+ * Unknown terminal shapes install nothing and keep Pi's native output.
66
+ */
67
+ export function installOsc8LinkIds(tui: TUI): (() => void) | undefined {
68
+ const terminal = (tui as TerminalTui).terminal;
69
+ if (!terminal || typeof terminal.write !== "function") return undefined;
70
+ if (terminal[INSTALLED]) return terminal[INSTALLED];
71
+
72
+ const hadOwnMethod = Object.hasOwn(terminal, "write");
73
+ const original = terminal.write;
74
+ const wrapped = function (this: TerminalWriter, data: string) {
75
+ return original.call(
76
+ this,
77
+ typeof data === "string" ? tagAnonymousOsc8Links(data) : data,
78
+ );
79
+ };
80
+ terminal.write = wrapped;
81
+
82
+ const dispose = () => {
83
+ if (terminal.write !== wrapped) return;
84
+ if (hadOwnMethod) terminal.write = original;
85
+ else delete (terminal as { write?: unknown }).write;
86
+ delete terminal[INSTALLED];
87
+ };
88
+ terminal[INSTALLED] = dispose;
89
+ return dispose;
90
+ }
@@ -52,7 +52,11 @@ export function isTypingInput(data: string): boolean {
52
52
  *
53
53
  * The listener registers after the renderer's own constructor-installed
54
54
  * listener, so it only sees input the viewport declined: scroll keys and
55
- * mouse gestures keep the selection, matching terminal convention. It resets
55
+ * mouse gestures keep the selection, matching terminal convention. Keys the
56
+ * caller marks preserved also keep it: Pi 0.84.4's `app.message.copy` action
57
+ * (Ctrl+X) copies the active selection when `fullscreenCopyOnSelect` is
58
+ * disabled, and it runs at the editor after this listener, so dismissing on
59
+ * that keystroke would clear the selection before the copy reads it. It resets
56
60
  * the same private fields the renderer's focus-loss branch resets and never
57
61
  * consumes the input, so the keystroke still reaches the editor.
58
62
  *
@@ -62,7 +66,10 @@ export function isTypingInput(data: string): boolean {
62
66
  *
63
67
  * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Selection dismissal]]
64
68
  */
65
- export function installSelectionDismiss(tui: TUI): (() => void) | undefined {
69
+ export function installSelectionDismiss(
70
+ tui: TUI,
71
+ isPreservedInput?: (data: string) => boolean,
72
+ ): (() => void) | undefined {
66
73
  const host = tui as SelectionHost;
67
74
  if (
68
75
  typeof host.getSelectionBounds !== "function" ||
@@ -79,6 +86,7 @@ export function installSelectionDismiss(tui: TUI): (() => void) | undefined {
79
86
  if (host.selectionPressActive) return undefined;
80
87
  if (host.getSelectionBounds?.() === undefined) return undefined;
81
88
  if (!isTypingInput(data)) return undefined;
89
+ if (isPreservedInput?.(data)) return undefined;
82
90
  host.stopSelectionAutoScroll?.();
83
91
  host.selectionAnchor = undefined;
84
92
  host.selectionFocus = undefined;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Pi's fullscreen renderer scrolls its transcript exactly one line per
3
+ * mouse-wheel report: the renderer's `wheelScrollLines` option defaults to 1
4
+ * and pi passes no override and exposes no setting. Terminals natively
5
+ * multiply a wheel notch to about three lines, so fullscreen scrolling feels
6
+ * slower than every other terminal surface.
7
+ *
8
+ * No escape sequence lets an application query the terminal's own wheel
9
+ * configuration, so the step defaults to the 3-line application convention
10
+ * (vim, less) and honors a per-terminal `PROPER_WHEEL_SCROLL_LINES`
11
+ * environment override that each terminal's profile can export.
12
+ */
13
+
14
+ const DEFAULT_WHEEL_SCROLL_LINES = 3;
15
+
16
+ /** Renderer surface carrying the per-wheel-event line count. */
17
+ type WheelHost = { wheelScrollLines?: unknown };
18
+
19
+ /** Lines per wheel event: a positive integer override, else the 3-line convention. */
20
+ export function resolveWheelScrollLines(
21
+ env: Record<string, string | undefined> = process.env,
22
+ ): number {
23
+ const parsed = Number.parseInt(env.PROPER_WHEEL_SCROLL_LINES ?? "", 10);
24
+ return parsed >= 1 ? parsed : DEFAULT_WHEEL_SCROLL_LINES;
25
+ }
26
+
27
+ /**
28
+ * Raise the fullscreen renderer's wheel step. Only a renderer that already
29
+ * exposes a numeric `wheelScrollLines` is touched, so regular mode — where
30
+ * the terminal scrolls natively — and a renamed upstream field fail open to
31
+ * pi's own behavior.
32
+ *
33
+ * ponytail: SGR wheel reports cannot distinguish a discrete mouse notch from
34
+ * one line of a high-rate trackpad stream, so a terminal emitting one report
35
+ * per native line scrolls proportionally faster; exporting
36
+ * PROPER_WHEEL_SCROLL_LINES=1 there restores pi's original pace.
37
+ */
38
+ export function installWheelScrollLines(
39
+ tui: unknown,
40
+ lines: number = resolveWheelScrollLines(),
41
+ ): boolean {
42
+ const host = tui as WheelHost;
43
+ if (typeof host.wheelScrollLines !== "number") return false;
44
+ host.wheelScrollLines = Math.floor(lines);
45
+ return true;
46
+ }