proper-base 0.2.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,155 @@
1
+ import {
2
+ stripTerminalSequences,
3
+ type TUI,
4
+ visibleWidth,
5
+ } from "@earendil-works/pi-tui";
6
+
7
+ const INSTALLED = Symbol.for("pi-proper-base.smart-selection");
8
+ const QUOTES = new Set(['"', "'", "`"]);
9
+ const WRAPPER_PAIRS = new Map([
10
+ ["(", ")"],
11
+ ["[", "]"],
12
+ ["{", "}"],
13
+ ["<", ">"],
14
+ ]);
15
+ const TRAILING_PUNCTUATION = new Set([".", ",", ";", "!", "?"]);
16
+
17
+ type SelectionPoint = {
18
+ row: number;
19
+ col: number;
20
+ scrollView?: unknown;
21
+ boundary?: boolean;
22
+ };
23
+
24
+ type SelectionRange = {
25
+ start: SelectionPoint;
26
+ end: SelectionPoint;
27
+ };
28
+
29
+ type SelectionTui = TUI & {
30
+ getSelectionSourceLine?(point: SelectionPoint): string;
31
+ getWordSelection?(point: SelectionPoint): SelectionRange | undefined;
32
+ [INSTALLED]?: () => void;
33
+ };
34
+
35
+ export type SmartSelectionRange = { start: number; end: number };
36
+
37
+ function columns(
38
+ line: string,
39
+ startIndex: number,
40
+ endIndex: number,
41
+ ): SmartSelectionRange {
42
+ return {
43
+ start: visibleWidth(line.slice(0, startIndex)),
44
+ end: visibleWidth(line.slice(0, endIndex)),
45
+ };
46
+ }
47
+
48
+ function contains(range: SmartSelectionRange, column: number): boolean {
49
+ return column >= range.start && column < range.end;
50
+ }
51
+
52
+ function quotedRange(
53
+ line: string,
54
+ column: number,
55
+ ): SmartSelectionRange | undefined {
56
+ for (const match of line.matchAll(/(["'`])(?:\\.|(?!\1)[^\\])*\1/gu)) {
57
+ const range = columns(line, match.index, match.index + match[0].length);
58
+ if (contains(range, column)) return range;
59
+ }
60
+ return undefined;
61
+ }
62
+
63
+ function trimToken(line: string, start: number, end: number): [number, number] {
64
+ while (
65
+ start < end &&
66
+ WRAPPER_PAIRS.get(line[start] ?? "") === line[end - 1]
67
+ ) {
68
+ start++;
69
+ end--;
70
+ }
71
+ while (start < end && WRAPPER_PAIRS.has(line[start] ?? "")) start++;
72
+ while (start < end && TRAILING_PUNCTUATION.has(line[end - 1] ?? "")) end--;
73
+ for (const [open, close] of WRAPPER_PAIRS) {
74
+ while (line[end - 1] === close) {
75
+ const token = line.slice(start, end);
76
+ if (token.split(close).length <= token.split(open).length) break;
77
+ end--;
78
+ }
79
+ }
80
+ return [start, end];
81
+ }
82
+
83
+ function isSmartToken(token: string): boolean {
84
+ if (/^(?:https?|file):\/\/\S+$/iu.test(token) || /^www\.\S+$/iu.test(token))
85
+ return true;
86
+ if (/^--?[A-Za-z0-9][\w.-]*(?:=\S+)?$/u.test(token)) return true;
87
+ if (/^\d+[\\/]\d+$/u.test(token)) return false;
88
+ if (
89
+ /^(?:~[\\/]|\.{0,2}[\\/]|[A-Za-z]:[\\/])\S+$/u.test(token) ||
90
+ /^[\w@.-]+(?:[\\/][\w@.+~:#%=-]+)+(?::\d+(?::\d+)?)?$/u.test(token)
91
+ )
92
+ return true;
93
+ return /^[A-Za-z_$][\w$-]*(?:(?:::|->|\.)[A-Za-z_$][\w$-]*)+$/u.test(token);
94
+ }
95
+
96
+ export function findSmartSelectionRange(
97
+ line: string,
98
+ column: number,
99
+ ): SmartSelectionRange | undefined {
100
+ const plain = stripTerminalSequences(line);
101
+ const quoted = quotedRange(plain, column);
102
+ if (quoted) return quoted;
103
+
104
+ for (const match of plain.matchAll(/\S+/gu)) {
105
+ const value = match[0];
106
+ const rawStart = match.index;
107
+ let [start, end] = trimToken(plain, rawStart, rawStart + value.length);
108
+ while (start < end && QUOTES.has(plain[start] ?? "")) start++;
109
+ while (start < end && QUOTES.has(plain[end - 1] ?? "")) end--;
110
+ const range = columns(plain, start, end);
111
+ if (contains(range, column) && isSmartToken(plain.slice(start, end))) {
112
+ return range;
113
+ }
114
+ }
115
+ return undefined;
116
+ }
117
+
118
+ /**
119
+ * Extend Pi's native fullscreen word selection without replacing its click,
120
+ * drag, highlight, viewport, or clipboard behavior. Unknown renderer shapes and
121
+ * unrecognized text keep Pi's native selection unchanged.
122
+ */
123
+ export function installSmartSelection(tui: TUI): (() => void) | undefined {
124
+ const host = tui as SelectionTui;
125
+ if (host[INSTALLED]) return host[INSTALLED];
126
+ if (!host.getWordSelection || !host.getSelectionSourceLine) return undefined;
127
+
128
+ const hadOwnMethod = Object.hasOwn(host, "getWordSelection");
129
+ const original = host.getWordSelection;
130
+ const wrapped = (point: SelectionPoint): SelectionRange | undefined => {
131
+ if (point.scrollView) {
132
+ const range = findSmartSelectionRange(
133
+ host.getSelectionSourceLine?.(point) ?? "",
134
+ point.col,
135
+ );
136
+ if (range) {
137
+ return {
138
+ start: { ...point, col: range.start },
139
+ end: { ...point, col: range.end, boundary: true },
140
+ };
141
+ }
142
+ }
143
+ return original.call(host, point);
144
+ };
145
+ host.getWordSelection = wrapped;
146
+
147
+ const dispose = () => {
148
+ if (host.getWordSelection !== wrapped) return;
149
+ if (hadOwnMethod) host.getWordSelection = original;
150
+ else delete host.getWordSelection;
151
+ delete host[INSTALLED];
152
+ };
153
+ host[INSTALLED] = dispose;
154
+ return dispose;
155
+ }
package/src/store.ts ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Append-only prompt store.
3
+ *
4
+ * Pi session messages contain expanded skills and prompt templates rather than
5
+ * exact editor input. This store records each recallable submitted prompt
6
+ * immediately, before those transformations.
7
+ *
8
+ * One file per project, append-only JSONL. Concurrent pi sessions in the same
9
+ * project append to the same file, so entries are written as a single small
10
+ * line each and never rewritten in place.
11
+ */
12
+
13
+ import {
14
+ appendFileSync,
15
+ closeSync,
16
+ existsSync,
17
+ mkdirSync,
18
+ openSync,
19
+ readSync,
20
+ renameSync,
21
+ statSync,
22
+ writeFileSync,
23
+ } from "node:fs";
24
+ import { join } from "node:path";
25
+
26
+ import type { Prompt } from "./history.ts";
27
+
28
+ /**
29
+ * Prompts longer than this are not recorded.
30
+ *
31
+ * Keeps each append small enough to land as one write, and recalling a huge
32
+ * paste through the arrow keys is not useful. Long prompts are skipped rather
33
+ * than truncated: a truncated command that looks complete is dangerous to
34
+ * submit again.
35
+ */
36
+ export const MAX_PROMPT_CHARS = 4096;
37
+
38
+ /** Bytes read from the tail of the store. Older entries stay on disk, unread. */
39
+ export const READ_TAIL_BYTES = 512 * 1024;
40
+
41
+ /** Compaction threshold. Below this the file is only ever appended to. */
42
+ export const COMPACT_ABOVE_BYTES = 2 * 1024 * 1024;
43
+
44
+ /** Entries kept when the store is compacted. */
45
+ export const COMPACT_KEEP = 2000;
46
+
47
+ /** pi's session-directory encoding, reused so store files match `sessions/`. */
48
+ export function projectKey(cwd: string): string {
49
+ return `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
50
+ }
51
+
52
+ export function storePath(agentDir: string, cwd: string): string {
53
+ return join(agentDir, "proper-history", `${projectKey(cwd)}.jsonl`);
54
+ }
55
+
56
+ /** Serialize one entry. Exported so tests do not restate the wire format. */
57
+ export function encodeEntry(prompt: Prompt): string {
58
+ return `${JSON.stringify({ t: prompt.text, ts: prompt.ts })}\n`;
59
+ }
60
+
61
+ function decodeEntry(line: string): Prompt | undefined {
62
+ try {
63
+ const parsed = JSON.parse(line) as { t?: unknown; ts?: unknown };
64
+ if (typeof parsed.t !== "string" || !parsed.t) return undefined;
65
+ const ts =
66
+ typeof parsed.ts === "number" && Number.isFinite(parsed.ts)
67
+ ? parsed.ts
68
+ : 0;
69
+ return { text: parsed.t, ts };
70
+ } catch {
71
+ return undefined;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Record one prompt.
77
+ *
78
+ * Never throws. Losing a history entry must not break the editor, and this
79
+ * runs on the submit path of every keystroke-driven send.
80
+ */
81
+ export function appendPrompt(
82
+ file: string,
83
+ text: string,
84
+ ts: number = Date.now(),
85
+ ): boolean {
86
+ const trimmed = text.trim();
87
+ if (!trimmed || trimmed.length > MAX_PROMPT_CHARS) return false;
88
+ try {
89
+ mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
90
+ if (!existsSync(file)) writeFileSync(file, "", { mode: 0o600 });
91
+ appendFileSync(file, encodeEntry({ text: trimmed, ts }));
92
+ return true;
93
+ } catch {
94
+ return false;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Read recent prompts, oldest first.
100
+ *
101
+ * Only the tail of the file is read, so a store that has grown for months does
102
+ * not slow down startup. A partial line at the read boundary and any damaged
103
+ * line are skipped.
104
+ */
105
+ export function readPrompts(
106
+ file: string,
107
+ maxBytes: number = READ_TAIL_BYTES,
108
+ ): Prompt[] {
109
+ let fd: number | undefined;
110
+ try {
111
+ const size = statSync(file).size;
112
+ if (size === 0) return [];
113
+ const start = Math.max(0, size - maxBytes);
114
+ const length = size - start;
115
+ const buffer = Buffer.allocUnsafe(length);
116
+ fd = openSync(file, "r");
117
+ readSync(fd, buffer, 0, length, start);
118
+ const lines = buffer.toString("utf8").split("\n");
119
+ if (start > 0) lines.shift();
120
+ const prompts: Prompt[] = [];
121
+ for (const line of lines) {
122
+ if (!line) continue;
123
+ const entry = decodeEntry(line);
124
+ if (entry) prompts.push(entry);
125
+ }
126
+ return prompts;
127
+ } catch {
128
+ return [];
129
+ } finally {
130
+ if (fd !== undefined) {
131
+ try {
132
+ closeSync(fd);
133
+ } catch {
134
+ // A close failure must not turn history loading into a startup failure.
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Trim the store when it has grown past the threshold.
142
+ *
143
+ * Writes a temporary file and renames it, so readers see either the old file or
144
+ * the new one. A prompt appended by another pi session during the rename can be
145
+ * lost; that window is small and the cost is one forgotten history entry.
146
+ */
147
+ export function compactIfNeeded(
148
+ file: string,
149
+ aboveBytes: number = COMPACT_ABOVE_BYTES,
150
+ keep: number = COMPACT_KEEP,
151
+ ): boolean {
152
+ try {
153
+ if (!existsSync(file) || statSync(file).size <= aboveBytes) return false;
154
+ const prompts = readPrompts(file, Number.MAX_SAFE_INTEGER).slice(-keep);
155
+ const temp = `${file}.${process.pid}.tmp`;
156
+ writeFileSync(temp, prompts.map(encodeEntry).join(""), { mode: 0o600 });
157
+ renameSync(temp, file);
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }