@andares/pi-toolkits 1.0.2 → 1.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,340 @@
1
+ /**
2
+ * keep feature — the keep ledger.
3
+ *
4
+ * `keep.jsonl` is an append-only event stream, folded into state by a pure
5
+ * function:
6
+ *
7
+ * keep this session is unfinished and should come back
8
+ * drop it is not (the operator finished it, or never wants it back)
9
+ * load a pi process opened it through `/keep-load`
10
+ * unload that process is gone (clean exit) or no longer holds it
11
+ *
12
+ * The distinction matters because loading does **not** remove anything: a
13
+ * kept session stays in the backlog until it is dropped. "Loaded" is a
14
+ * separate axis, and it is a record, not a lock — a hard kill leaves a stale
15
+ * `load` behind, which is why an owner whose pid no longer exists is treated
16
+ * as gone on read (and reaped with one `unload` line, idempotently).
17
+ *
18
+ * Reasons for a ledger rather than a JSON document: appending one line needs
19
+ * no lock and no read-modify-write, so two pi processes cannot clobber each
20
+ * other's state, and every decision keeps its timestamp for free.
21
+ */
22
+ import { existsSync } from "node:fs";
23
+ import { hostname } from "node:os";
24
+ import { join } from "node:path";
25
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
26
+ import {
27
+ appendLedgerLine,
28
+ type LedgerEventBase,
29
+ newLedgerEventId,
30
+ readLedgerLines,
31
+ } from "../../lib/event-ledger.js";
32
+ import { KEEP_DIR, KEEP_LEDGER_FILE } from "./constants.js";
33
+
34
+ export const KEEP_LEDGER_VERSION = 1;
35
+
36
+ /** The pi process that holds a loaded session. */
37
+ export interface KeepOwner {
38
+ readonly pid: number;
39
+ readonly host: string;
40
+ readonly since: string;
41
+ }
42
+
43
+ export interface KeepEvent extends LedgerEventBase {
44
+ readonly type: "keep";
45
+ readonly session: string;
46
+ readonly file: string;
47
+ readonly cwd: string;
48
+ readonly note: string;
49
+ readonly name?: string;
50
+ }
51
+
52
+ export interface DropEvent extends LedgerEventBase {
53
+ readonly type: "drop";
54
+ readonly session: string;
55
+ }
56
+
57
+ export interface LoadEvent extends LedgerEventBase {
58
+ readonly type: "load";
59
+ readonly session: string;
60
+ readonly owner: KeepOwner;
61
+ }
62
+
63
+ export interface UnloadEvent extends LedgerEventBase {
64
+ readonly type: "unload";
65
+ readonly session: string;
66
+ readonly pid: number;
67
+ }
68
+
69
+ export type KeepLedgerEvent = KeepEvent | DropEvent | LoadEvent | UnloadEvent;
70
+
71
+ /** `<agent-dir>/pi-toolkits-keep/keep.jsonl`. */
72
+ export function keepLedgerPath(agentDir: string = getAgentDir()): string {
73
+ return join(agentDir, KEEP_DIR, KEEP_LEDGER_FILE);
74
+ }
75
+
76
+ export function isKeepLedgerEvent(value: unknown): value is KeepLedgerEvent {
77
+ if (!value || typeof value !== "object") return false;
78
+ const event = value as Record<string, unknown>;
79
+ if (typeof event.id !== "string" || typeof event.ts !== "string") return false;
80
+ if (typeof event.v !== "number") return false;
81
+ if (typeof event.session !== "string") return false;
82
+ const isString = (input: unknown): boolean => typeof input === "string";
83
+ const optionalString = (input: unknown): boolean =>
84
+ input === undefined || isString(input);
85
+
86
+ switch (event.type) {
87
+ case "keep":
88
+ return (
89
+ isString(event.file) && isString(event.cwd) && isString(event.note) && optionalString(event.name)
90
+ );
91
+ case "drop":
92
+ return true;
93
+ case "load": {
94
+ const owner = event.owner as Record<string, unknown> | undefined;
95
+ return (
96
+ !!owner &&
97
+ typeof owner === "object" &&
98
+ typeof owner.pid === "number" &&
99
+ isString(owner.host) &&
100
+ isString(owner.since)
101
+ );
102
+ }
103
+ case "unload":
104
+ return typeof event.pid === "number";
105
+ default:
106
+ return false;
107
+ }
108
+ }
109
+
110
+ /** One kept session, folded from the stream. */
111
+ export interface KeepEntryView {
112
+ readonly session: string;
113
+ readonly file: string;
114
+ readonly cwd: string;
115
+ readonly note: string;
116
+ readonly name?: string;
117
+ /** Timestamp of the last `keep`. */
118
+ readonly keptAt: string;
119
+ /** At least one live owner process holds it. */
120
+ readonly loaded: boolean;
121
+ /** The session file is gone; only `ctrl+r` can clear it. */
122
+ readonly missing: boolean;
123
+ }
124
+
125
+ export interface KeepState {
126
+ /** Not loaded first, then loaded; newest `keep` first inside each group. */
127
+ readonly entries: readonly KeepEntryView[];
128
+ readonly notLoaded: readonly KeepEntryView[];
129
+ readonly loaded: readonly KeepEntryView[];
130
+ /** Owners whose pid is gone; the caller appends one `unload` each. */
131
+ readonly staleOwners: readonly { readonly session: string; readonly pid: number }[];
132
+ }
133
+
134
+ export interface DeriveOptions {
135
+ /** Host of this process; owners on other hosts are assumed live. */
136
+ readonly host: string;
137
+ /** Liveness probe for an owner pid on this host. */
138
+ readonly isAlive: (pid: number) => boolean;
139
+ /** Session file probe (injected so the fold stays testable). */
140
+ readonly fileExists: (file: string) => boolean;
141
+ }
142
+
143
+ /** Default liveness probe: signal 0, `EPERM` still means the process exists. */
144
+ export function processIsAlive(pid: number): boolean {
145
+ try {
146
+ process.kill(pid, 0);
147
+ return true;
148
+ } catch (error) {
149
+ return (error as NodeJS.ErrnoException).code === "EPERM";
150
+ }
151
+ }
152
+
153
+ export function defaultFileExists(file: string): boolean {
154
+ return existsSync(file);
155
+ }
156
+
157
+ /**
158
+ * Fold the stream into state. Pure: same events and probes, same result.
159
+ *
160
+ * Order inside a group is newest `keep` first; loaded entries always sort
161
+ * after unloaded ones (that is the picker's two-block layout).
162
+ */
163
+ export function deriveKeepState(
164
+ events: readonly KeepLedgerEvent[],
165
+ options: DeriveOptions,
166
+ ): KeepState {
167
+ const kept = new Map<string, KeepEvent>();
168
+ const owners = new Map<string, Map<number, KeepOwner>>();
169
+
170
+ for (const event of events) {
171
+ switch (event.type) {
172
+ case "keep":
173
+ kept.set(event.session, event);
174
+ break;
175
+ case "drop":
176
+ kept.delete(event.session);
177
+ owners.delete(event.session);
178
+ break;
179
+ case "load": {
180
+ const held = owners.get(event.session) ?? new Map<number, KeepOwner>();
181
+ held.set(event.owner.pid, event.owner);
182
+ owners.set(event.session, held);
183
+ break;
184
+ }
185
+ case "unload":
186
+ owners.get(event.session)?.delete(event.pid);
187
+ break;
188
+ }
189
+ }
190
+
191
+ const staleOwners: Array<{ session: string; pid: number }> = [];
192
+ const entries: KeepEntryView[] = [];
193
+
194
+ for (const [session, event] of kept) {
195
+ const held = owners.get(session);
196
+ let loaded = false;
197
+ if (held) {
198
+ for (const [pid, owner] of held) {
199
+ if (owner.host !== options.host) {
200
+ // Another machine: no way to probe, so the record stands.
201
+ loaded = true;
202
+ continue;
203
+ }
204
+ if (options.isAlive(pid)) {
205
+ loaded = true;
206
+ } else {
207
+ held.delete(pid);
208
+ staleOwners.push({ session, pid });
209
+ }
210
+ }
211
+ }
212
+ entries.push({
213
+ session,
214
+ file: event.file,
215
+ cwd: event.cwd,
216
+ note: event.note,
217
+ name: event.name,
218
+ keptAt: event.ts,
219
+ loaded,
220
+ missing: !options.fileExists(event.file),
221
+ });
222
+ }
223
+
224
+ entries.sort((a, b) => {
225
+ if (a.loaded !== b.loaded) return a.loaded ? 1 : -1;
226
+ return b.keptAt.localeCompare(a.keptAt);
227
+ });
228
+
229
+ return {
230
+ entries,
231
+ notLoaded: entries.filter((entry) => !entry.loaded),
232
+ loaded: entries.filter((entry) => entry.loaded),
233
+ staleOwners,
234
+ };
235
+ }
236
+
237
+ /** Read the ledger and fold it with this process's probes. */
238
+ export function readKeepState(
239
+ file: string,
240
+ probes: Partial<DeriveOptions> = {},
241
+ ): { state: KeepState; skipped: number } {
242
+ const { events, skipped } = readLedgerLines(file, isKeepLedgerEvent);
243
+ const state = deriveKeepState(events, {
244
+ host: probes.host ?? currentHost(),
245
+ isAlive: probes.isAlive ?? processIsAlive,
246
+ fileExists: probes.fileExists ?? defaultFileExists,
247
+ });
248
+ return { state, skipped };
249
+ }
250
+
251
+ /** Hostname used to decide whether a pid probe is meaningful. */
252
+ export function currentHost(): string {
253
+ try {
254
+ return hostname();
255
+ } catch {
256
+ // No hostname is better than a wrong one: owners then fall into the
257
+ // "cannot probe" branch and stay loaded.
258
+ return "";
259
+ }
260
+ }
261
+
262
+ export interface KeepEventInput {
263
+ readonly session: string;
264
+ readonly file: string;
265
+ readonly cwd: string;
266
+ readonly note: string;
267
+ readonly name?: string;
268
+ }
269
+
270
+ export function appendKeep(file: string, input: KeepEventInput, now: Date = new Date()): void {
271
+ appendLedgerLine(file, {
272
+ v: KEEP_LEDGER_VERSION,
273
+ id: newLedgerEventId(now),
274
+ ts: now.toISOString(),
275
+ type: "keep",
276
+ session: input.session,
277
+ file: input.file,
278
+ cwd: input.cwd,
279
+ note: input.note,
280
+ // Undefined is dropped by JSON.stringify, so the line stays compact.
281
+ name: input.name,
282
+ } satisfies KeepEvent);
283
+ }
284
+
285
+ export function appendDrop(file: string, session: string, now: Date = new Date()): void {
286
+ appendLedgerLine(file, {
287
+ v: KEEP_LEDGER_VERSION,
288
+ id: newLedgerEventId(now),
289
+ ts: now.toISOString(),
290
+ type: "drop",
291
+ session,
292
+ } satisfies DropEvent);
293
+ }
294
+
295
+ export function appendLoad(
296
+ file: string,
297
+ session: string,
298
+ owner: KeepOwner,
299
+ now: Date = new Date(),
300
+ ): void {
301
+ appendLedgerLine(file, {
302
+ v: KEEP_LEDGER_VERSION,
303
+ id: newLedgerEventId(now),
304
+ ts: now.toISOString(),
305
+ type: "load",
306
+ session,
307
+ owner,
308
+ } satisfies LoadEvent);
309
+ }
310
+
311
+ export function appendUnload(
312
+ file: string,
313
+ session: string,
314
+ pid: number,
315
+ now: Date = new Date(),
316
+ ): void {
317
+ appendLedgerLine(file, {
318
+ v: KEEP_LEDGER_VERSION,
319
+ id: newLedgerEventId(now),
320
+ ts: now.toISOString(),
321
+ type: "unload",
322
+ session,
323
+ pid,
324
+ } satisfies UnloadEvent);
325
+ }
326
+
327
+ /**
328
+ * Reap owners whose process is gone. One `unload` per stale owner; a second
329
+ * reader that folds the same stream sees the owner already gone and appends
330
+ * nothing, so the repair converges instead of growing.
331
+ */
332
+ export function reapStaleOwners(
333
+ file: string,
334
+ stale: readonly { readonly session: string; readonly pid: number }[],
335
+ now: Date = new Date(),
336
+ ): void {
337
+ for (const owner of stale) {
338
+ appendUnload(file, owner.session, owner.pid, now);
339
+ }
340
+ }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * keep feature — the picker and the switch-before dialog.
3
+ *
4
+ * Two blocks in one list: not-loaded rows first, loaded rows after them,
5
+ * dimmed. Both are selectable on purpose — the loaded flag is a record, not a
6
+ * lock, so a session whose process was killed must stay reachable without
7
+ * hand-editing the ledger.
8
+ *
9
+ * Why a dedicated component instead of `SelectList`:
10
+ * - `SelectItem` is `{value,label,description}` and the list applies one
11
+ * style to every unselected row, so "this row is dim, that row is red"
12
+ * cannot be expressed;
13
+ * - there is no group header item (a header would be a selectable row);
14
+ * - `ctrl+r` drops a row, and `SelectList` has no `setItems` — the removal
15
+ * would mean rebuilding the component on every keystroke.
16
+ * The rendering itself follows the repo's existing per-row precedent
17
+ * (`src/features/favorites/patch-selector.ts` re-renders the host selector's
18
+ * rows the same way). The three-way dialog below the picker *does* reuse
19
+ * `SelectList`: it needs no per-row styling.
20
+ */
21
+ import { getSelectListTheme } from "@earendil-works/pi-coding-agent";
22
+ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
23
+ import {
24
+ type Component,
25
+ matchesKey,
26
+ SelectList,
27
+ Text,
28
+ truncateToWidth,
29
+ } from "@earendil-works/pi-tui";
30
+ import { KEEP_DROP_KEY, KEEP_MAX_ROWS } from "./constants.js";
31
+ import { pickerTitle, rowText } from "./format.js";
32
+ import type { KeepEntryView } from "./ledger.js";
33
+
34
+ export type KeepPick =
35
+ | { readonly action: "load"; readonly entry: KeepEntryView }
36
+ | { readonly action: "cancel" };
37
+
38
+ export interface KeepPickerOptions {
39
+ readonly now: Date;
40
+ /** Add the project column (`--all`). */
41
+ readonly showProject: boolean;
42
+ readonly maxRows?: number;
43
+ /** Persist the drop; called before the row disappears. */
44
+ readonly drop: (entry: KeepEntryView) => void;
45
+ }
46
+
47
+ const HINT = "↑↓ move · enter load · ctrl+r drop · esc cancel";
48
+
49
+ export class KeepPicker implements Component {
50
+ private readonly rows: KeepEntryView[];
51
+ private cursor = 0;
52
+ private offset = 0;
53
+ private settled = false;
54
+
55
+ constructor(
56
+ entries: readonly KeepEntryView[],
57
+ private readonly options: KeepPickerOptions,
58
+ private readonly theme: Theme,
59
+ private readonly done: (result: KeepPick) => void,
60
+ private readonly requestRender: () => void,
61
+ ) {
62
+ this.rows = [...entries];
63
+ }
64
+
65
+ handleInput(data: string): void {
66
+ if (matchesKey(data, "up")) {
67
+ this.move(-1);
68
+ return;
69
+ }
70
+ if (matchesKey(data, "down")) {
71
+ this.move(1);
72
+ return;
73
+ }
74
+ if (matchesKey(data, "enter")) {
75
+ const entry = this.rows[this.cursor];
76
+ if (entry) this.finish({ action: "load", entry });
77
+ return;
78
+ }
79
+ if (matchesKey(data, "escape")) {
80
+ this.finish({ action: "cancel" });
81
+ return;
82
+ }
83
+ if (matchesKey(data, KEEP_DROP_KEY)) {
84
+ this.dropSelected();
85
+ }
86
+ }
87
+
88
+ render(width: number): string[] {
89
+ const notLoaded = this.rows.filter((entry) => !entry.loaded).length;
90
+ const lines = [
91
+ truncateToWidth(this.theme.bold(pickerTitle(notLoaded, this.rows.length - notLoaded)), width, ""),
92
+ truncateToWidth(this.theme.fg("dim", HINT), width, ""),
93
+ "",
94
+ ];
95
+
96
+ const maxRows = Math.max(1, this.options.maxRows ?? KEEP_MAX_ROWS);
97
+ if (this.cursor < this.offset) this.offset = this.cursor;
98
+ if (this.cursor >= this.offset + maxRows) this.offset = this.cursor - maxRows + 1;
99
+
100
+ for (let index = this.offset; index < Math.min(this.rows.length, this.offset + maxRows); index += 1) {
101
+ const entry = this.rows[index];
102
+ const selected = index === this.cursor;
103
+ const text = `${selected ? "→ " : " "}${rowText(entry, this.options)}`;
104
+ const fitted = truncateToWidth(text, width, "…");
105
+ // One colour per row keeps the SGR sequences flat: no nesting between
106
+ // the selected style and the dim style.
107
+ if (selected) lines.push(this.theme.fg("accent", fitted));
108
+ else if (entry.missing) lines.push(this.theme.fg("error", fitted));
109
+ else if (entry.loaded) lines.push(this.theme.fg("dim", fitted));
110
+ else lines.push(fitted);
111
+ }
112
+
113
+ if (this.rows.length > maxRows) {
114
+ lines.push(
115
+ truncateToWidth(
116
+ this.theme.fg("dim", ` ${this.cursor + 1}/${this.rows.length}`),
117
+ width,
118
+ "",
119
+ ),
120
+ );
121
+ }
122
+ return lines;
123
+ }
124
+
125
+ invalidate(): void {
126
+ // Rows are rebuilt from the field state on every render.
127
+ }
128
+
129
+ private move(delta: number): void {
130
+ const next = Math.max(0, Math.min(this.rows.length - 1, this.cursor + delta));
131
+ if (next === this.cursor) return;
132
+ this.cursor = next;
133
+ this.requestRender();
134
+ }
135
+
136
+ private dropSelected(): void {
137
+ const entry = this.rows[this.cursor];
138
+ if (!entry) return;
139
+ this.options.drop(entry);
140
+ this.rows.splice(this.cursor, 1);
141
+ if (this.rows.length === 0) {
142
+ this.finish({ action: "cancel" });
143
+ return;
144
+ }
145
+ if (this.cursor >= this.rows.length) this.cursor = this.rows.length - 1;
146
+ this.requestRender();
147
+ }
148
+
149
+ private finish(result: KeepPick): void {
150
+ if (this.settled) return;
151
+ this.settled = true;
152
+ this.done(result);
153
+ }
154
+ }
155
+
156
+ /** Ask for one entry. `undefined` means "no UI, or cancelled". */
157
+ export async function pickKeepEntry(
158
+ ctx: ExtensionContext,
159
+ entries: readonly KeepEntryView[],
160
+ options: KeepPickerOptions,
161
+ ): Promise<KeepPick | undefined> {
162
+ if (!ctx.hasUI || entries.length === 0) return undefined;
163
+
164
+ const notLoaded = entries.filter((entry) => !entry.loaded).length;
165
+ const title = pickerTitle(notLoaded, entries.length - notLoaded);
166
+
167
+ if (ctx.mode !== "tui") {
168
+ const labels = entries.map((entry) => rowText(entry, options));
169
+ const choice = await ctx.ui.select(`${title} — ${HINT}`, labels);
170
+ if (choice === undefined) return undefined;
171
+ const index = labels.indexOf(choice);
172
+ const entry = entries[index];
173
+ return entry ? { action: "load", entry } : undefined;
174
+ }
175
+
176
+ return ctx.ui.custom<KeepPick>((tui, theme, _keybindings, done) =>
177
+ new KeepPicker(entries, options, theme, done, () => tui.requestRender()),
178
+ );
179
+ }
180
+
181
+ export type SwitchChoice = "keep" | "load" | "cancel";
182
+
183
+ interface ChoiceOption {
184
+ readonly value: SwitchChoice;
185
+ readonly label: string;
186
+ readonly description: string;
187
+ }
188
+
189
+ function switchOptions(): ChoiceOption[] {
190
+ return [
191
+ {
192
+ value: "keep",
193
+ label: "Keep it & load",
194
+ description: "Mark this session unfinished, then load the other one",
195
+ },
196
+ {
197
+ value: "load",
198
+ label: "Load anyway",
199
+ description: "Leave this session out of the keep list",
200
+ },
201
+ {
202
+ value: "cancel",
203
+ label: "Cancel",
204
+ description: "Stay where you are",
205
+ },
206
+ ];
207
+ }
208
+
209
+ /**
210
+ * The current session has work in it and is not kept: switching away would
211
+ * leave it out of the backlog. Three answers, no typing.
212
+ */
213
+ export async function askSwitchChoice(
214
+ ctx: ExtensionContext,
215
+ entry: KeepEntryView,
216
+ ): Promise<SwitchChoice | undefined> {
217
+ if (!ctx.hasUI) return "load";
218
+ const options = switchOptions();
219
+ const title = `This session is not kept — ${entry.note}`;
220
+
221
+ if (ctx.mode !== "tui") {
222
+ const labels = options.map((option) => option.label);
223
+ const choice = await ctx.ui.select(title, labels);
224
+ if (choice === undefined) return undefined;
225
+ return options[labels.indexOf(choice)]?.value;
226
+ }
227
+
228
+ return ctx.ui.custom<SwitchChoice | undefined>((_tui, theme, _keybindings, done) => {
229
+ const header = new Text(
230
+ [
231
+ theme.fg("accent", "This session is not kept"),
232
+ theme.fg("muted", `Loading: ${entry.note}`),
233
+ ].join("\n"),
234
+ 1,
235
+ 0,
236
+ );
237
+ const list = new SelectList(
238
+ options.map((option) => ({
239
+ value: option.value,
240
+ label: option.label,
241
+ description: option.description,
242
+ })),
243
+ options.length,
244
+ getSelectListTheme(),
245
+ );
246
+ list.onSelect = (item) => done(item.value as SwitchChoice);
247
+ list.onCancel = () => done(undefined);
248
+ return {
249
+ handleInput: (data: string) => list.handleInput(data),
250
+ render: (width: number) => [...header.render(width), ...list.render(width)],
251
+ invalidate: () => {
252
+ header.invalidate();
253
+ list.invalidate();
254
+ },
255
+ };
256
+ });
257
+ }