@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.
- package/CHANGELOG.md +12 -0
- package/README.md +42 -1
- package/README.zh-CN.md +36 -1
- package/package.json +4 -3
- package/src/features/keep/constants.ts +44 -0
- package/src/features/keep/format.ts +77 -0
- package/src/features/keep/index.ts +409 -0
- package/src/features/keep/keep.test.ts +955 -0
- package/src/features/keep/ledger.ts +340 -0
- package/src/features/keep/picker.ts +257 -0
- package/src/features/keep/store.ts +271 -0
- package/src/features/spec/index.test.ts +121 -0
- package/src/features/spec/index.ts +81 -22
- package/src/features/spec/server.test.ts +49 -0
- package/src/features/spec/server.ts +18 -2
- package/src/features/uat/ledger.ts +13 -62
- package/src/index.ts +3 -0
- package/src/lib/event-ledger.ts +112 -0
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* keep feature — `/keep-quit`, `/keep-load`, `/keep-drop`.
|
|
3
|
+
*
|
|
4
|
+
* The problem: a project with several parallel tasks is a pile of sessions,
|
|
5
|
+
* and after a day away nobody remembers which one was finished. `/resume`
|
|
6
|
+
* lists every session by time, so it cannot answer that (and it happily opens
|
|
7
|
+
* one that another pi already has open).
|
|
8
|
+
*
|
|
9
|
+
* The shape here is a backlog with two independent axes:
|
|
10
|
+
*
|
|
11
|
+
* kept — "this task is unfinished"; only `/keep-quit` sets it and only
|
|
12
|
+
* `/keep-drop` (or `ctrl+r` in the list) clears it;
|
|
13
|
+
* loaded — "some pi process has it open right now"; written on load, cleared
|
|
14
|
+
* on clean exit. A hard kill leaves it stale, so an owner whose pid
|
|
15
|
+
* is gone is treated as gone on read, and a loaded row is still
|
|
16
|
+
* selectable (that is the manual override).
|
|
17
|
+
*
|
|
18
|
+
* Loading never removes anything. That is deliberate: an automatic removal has
|
|
19
|
+
* nowhere to put "loaded" and nothing to recover when the deciding process is
|
|
20
|
+
* wrong.
|
|
21
|
+
*/
|
|
22
|
+
import type {
|
|
23
|
+
ExtensionAPI,
|
|
24
|
+
ExtensionCommandContext,
|
|
25
|
+
ExtensionContext,
|
|
26
|
+
} from "@earendil-works/pi-coding-agent";
|
|
27
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
28
|
+
import { existsSync } from "node:fs";
|
|
29
|
+
import { resolve } from "node:path";
|
|
30
|
+
import {
|
|
31
|
+
KEEP_ENTRY,
|
|
32
|
+
KEEP_NOTICE_ENTRY,
|
|
33
|
+
KEEP_RESUME_ENTRY,
|
|
34
|
+
} from "./constants.js";
|
|
35
|
+
import { noticeText, resumeText } from "./format.js";
|
|
36
|
+
import {
|
|
37
|
+
appendDrop,
|
|
38
|
+
appendKeep,
|
|
39
|
+
appendLoad,
|
|
40
|
+
appendUnload,
|
|
41
|
+
type KeepEntryView,
|
|
42
|
+
type KeepOwner,
|
|
43
|
+
type KeepState,
|
|
44
|
+
keepLedgerPath,
|
|
45
|
+
currentHost,
|
|
46
|
+
readKeepState,
|
|
47
|
+
reapStaleOwners,
|
|
48
|
+
processIsAlive,
|
|
49
|
+
} from "./ledger.js";
|
|
50
|
+
import { askSwitchChoice, pickKeepEntry, type KeepPick, type SwitchChoice } from "./picker.js";
|
|
51
|
+
import {
|
|
52
|
+
currentSessionInfo,
|
|
53
|
+
defaultNote,
|
|
54
|
+
rebuildKeepLedger,
|
|
55
|
+
type KeepSessionInfo,
|
|
56
|
+
} from "./store.js";
|
|
57
|
+
|
|
58
|
+
export interface KeepOptions {
|
|
59
|
+
/** Ledger file; defaults to `<agent-dir>/pi-toolkits-keep/keep.jsonl`. */
|
|
60
|
+
readonly ledgerFile?: string;
|
|
61
|
+
readonly now?: () => Date;
|
|
62
|
+
readonly host?: string;
|
|
63
|
+
readonly pid?: number;
|
|
64
|
+
readonly isAlive?: (pid: number) => boolean;
|
|
65
|
+
readonly fileExists?: (file: string) => boolean;
|
|
66
|
+
/** Test seam for the list UI. */
|
|
67
|
+
readonly pick?: (
|
|
68
|
+
ctx: ExtensionContext,
|
|
69
|
+
entries: readonly KeepEntryView[],
|
|
70
|
+
options: Parameters<typeof pickKeepEntry>[2],
|
|
71
|
+
) => Promise<KeepPick | undefined> | KeepPick | undefined;
|
|
72
|
+
/** Test seam for the "keep the current session first?" dialog. */
|
|
73
|
+
readonly ask?: (
|
|
74
|
+
ctx: ExtensionContext,
|
|
75
|
+
entry: KeepEntryView,
|
|
76
|
+
) => Promise<SwitchChoice | undefined> | SwitchChoice | undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface LoadArgs {
|
|
80
|
+
readonly all: boolean;
|
|
81
|
+
readonly rebuild: boolean;
|
|
82
|
+
readonly target?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `"" | "--all" | "rebuild" | "2" | "<id-prefix>"` (flags in any order). */
|
|
86
|
+
export function parseLoadArgs(raw: string): LoadArgs {
|
|
87
|
+
const tokens = raw
|
|
88
|
+
.split(/\s+/)
|
|
89
|
+
.map((token) => token.trim())
|
|
90
|
+
.filter((token) => token.length > 0);
|
|
91
|
+
let all = false;
|
|
92
|
+
let rebuild = false;
|
|
93
|
+
let target: string | undefined;
|
|
94
|
+
for (const token of tokens) {
|
|
95
|
+
if (token === "--all" || token === "-a") {
|
|
96
|
+
all = true;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (token === "rebuild") {
|
|
100
|
+
rebuild = true;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (target === undefined) target = token;
|
|
104
|
+
}
|
|
105
|
+
return { all, rebuild, target };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Same directory, tolerant of trailing separators and `..`. */
|
|
109
|
+
export function samePath(left: string, right: string): boolean {
|
|
110
|
+
if (left.length === 0 || right.length === 0) return false;
|
|
111
|
+
return resolve(left) === resolve(right);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Index (1-based) or session id / unique id prefix. */
|
|
115
|
+
export function findTarget(
|
|
116
|
+
entries: readonly KeepEntryView[],
|
|
117
|
+
target: string,
|
|
118
|
+
): KeepEntryView | undefined {
|
|
119
|
+
if (/^\d+$/.test(target)) {
|
|
120
|
+
const index = Number(target) - 1;
|
|
121
|
+
return index >= 0 && index < entries.length ? entries[index] : undefined;
|
|
122
|
+
}
|
|
123
|
+
const exact = entries.find((entry) => entry.session === target);
|
|
124
|
+
if (exact) return exact;
|
|
125
|
+
const matches = entries.filter((entry) => entry.session.startsWith(target));
|
|
126
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function registerKeep(pi: ExtensionAPI, options: KeepOptions = {}): void {
|
|
130
|
+
const ledger = options.ledgerFile ?? keepLedgerPath();
|
|
131
|
+
const now = options.now ?? (() => new Date());
|
|
132
|
+
const host = options.host ?? currentHost();
|
|
133
|
+
const pid = options.pid ?? process.pid;
|
|
134
|
+
const isAlive = options.isAlive ?? processIsAlive;
|
|
135
|
+
const fileExists = options.fileExists ?? ((file: string): boolean => {
|
|
136
|
+
try {
|
|
137
|
+
return existsSync(file);
|
|
138
|
+
} catch {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
const pick = options.pick ?? pickKeepEntry;
|
|
143
|
+
const ask = options.ask ?? askSwitchChoice;
|
|
144
|
+
|
|
145
|
+
/** The session this process loaded through `/keep-load`, if any. */
|
|
146
|
+
let loadedHere: string | undefined;
|
|
147
|
+
/** Dedupe repeated `session_start` emissions for the same session. */
|
|
148
|
+
let noticeSession: string | undefined;
|
|
149
|
+
|
|
150
|
+
function readState(): KeepState {
|
|
151
|
+
const { state } = readKeepState(ledger, { host, isAlive, fileExists });
|
|
152
|
+
// Repair stale owners once, on read: a hard-killed process must not keep
|
|
153
|
+
// showing as "loaded" forever, and the repair is idempotent.
|
|
154
|
+
if (state.staleOwners.length > 0) reapStaleOwners(ledger, state.staleOwners, now());
|
|
155
|
+
return state;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function owner(): KeepOwner {
|
|
159
|
+
const at = now();
|
|
160
|
+
return { pid, host, since: at.toISOString() };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Write the keep for a session that is here right now. */
|
|
164
|
+
function keepCurrent(
|
|
165
|
+
session: KeepSessionInfo,
|
|
166
|
+
explicit: string | undefined,
|
|
167
|
+
previous: string | undefined,
|
|
168
|
+
): string {
|
|
169
|
+
const at = now();
|
|
170
|
+
const note = defaultNote({ explicit, info: session, previous });
|
|
171
|
+
pi.appendEntry(KEEP_ENTRY, { note, at: at.getTime() });
|
|
172
|
+
appendKeep(
|
|
173
|
+
ledger,
|
|
174
|
+
{ session: session.session, file: session.file, cwd: session.cwd, note, name: session.name },
|
|
175
|
+
at,
|
|
176
|
+
);
|
|
177
|
+
if (!session.name) pi.setSessionName(note);
|
|
178
|
+
return note;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function runKeepQuit(args: string, ctx: ExtensionCommandContext): Promise<void> {
|
|
182
|
+
if (ctx.mode !== "tui") {
|
|
183
|
+
ctx.ui.notify("keep-quit needs the interactive TUI", "warning");
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (!ctx.isIdle()) {
|
|
187
|
+
ctx.ui.notify("Still working — run /keep-quit after this turn finishes", "warning");
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const info = currentSessionInfo(ctx);
|
|
191
|
+
if (!info) {
|
|
192
|
+
ctx.ui.notify("This session is not persisted — there is nothing to keep", "warning");
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (!info.hasConversation) {
|
|
196
|
+
ctx.ui.notify("Nothing to keep yet — this session has no messages", "warning");
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (!fileExists(info.file)) {
|
|
200
|
+
ctx.ui.notify("This session is not saved on disk — there is nothing to keep", "warning");
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const state = readState();
|
|
205
|
+
const previous = state.entries.find((entry) => entry.session === info.session)?.note;
|
|
206
|
+
const note = keepCurrent(info, args.trim() || undefined, previous);
|
|
207
|
+
ctx.ui.notify(`Kept for later: ${note}`, "info");
|
|
208
|
+
ctx.shutdown();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function runKeepDrop(_args: string, ctx: ExtensionCommandContext): Promise<void> {
|
|
212
|
+
const info = currentSessionInfo(ctx);
|
|
213
|
+
if (!info) {
|
|
214
|
+
ctx.ui.notify("This session is not persisted — there is nothing to drop", "warning");
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const entry = readState().entries.find((item) => item.session === info.session);
|
|
218
|
+
if (!entry) {
|
|
219
|
+
ctx.ui.notify("This session is not in the keep list", "info");
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
appendDrop(ledger, info.session, now());
|
|
223
|
+
ctx.ui.notify(`Dropped from keep: ${entry.note}`, "info");
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function runKeepLoad(args: string, ctx: ExtensionCommandContext): Promise<void> {
|
|
227
|
+
const parsed = parseLoadArgs(args);
|
|
228
|
+
|
|
229
|
+
if (parsed.rebuild) {
|
|
230
|
+
const result = rebuildKeepLedger({
|
|
231
|
+
dir: ctx.sessionManager.getSessionDir(),
|
|
232
|
+
ledger,
|
|
233
|
+
state: readState(),
|
|
234
|
+
now: now(),
|
|
235
|
+
});
|
|
236
|
+
ctx.ui.notify(
|
|
237
|
+
result.restored > 0
|
|
238
|
+
? `Rebuilt ${result.restored} kept session${result.restored === 1 ? "" : "s"} from ${result.scanned} files`
|
|
239
|
+
: `No missing keeps found in ${result.scanned} session file${result.scanned === 1 ? "" : "s"}`,
|
|
240
|
+
"info",
|
|
241
|
+
);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const info = currentSessionInfo(ctx);
|
|
246
|
+
const state = readState();
|
|
247
|
+
// The current session is managed by /keep-quit and /keep-drop, not by the
|
|
248
|
+
// backlog: listing it would offer to load the session you are already in.
|
|
249
|
+
const visible = state.entries.filter(
|
|
250
|
+
(entry) =>
|
|
251
|
+
entry.session !== info?.session && (parsed.all || samePath(entry.cwd, ctx.cwd)),
|
|
252
|
+
);
|
|
253
|
+
|
|
254
|
+
if (visible.length === 0) {
|
|
255
|
+
ctx.ui.notify(
|
|
256
|
+
parsed.all
|
|
257
|
+
? "No kept sessions"
|
|
258
|
+
: "No kept sessions in this project — try /keep-load --all",
|
|
259
|
+
"info",
|
|
260
|
+
);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
let entry: KeepEntryView | undefined;
|
|
265
|
+
if (parsed.target) {
|
|
266
|
+
entry = findTarget(visible, parsed.target);
|
|
267
|
+
if (!entry) {
|
|
268
|
+
ctx.ui.notify(`No kept session matches "${parsed.target}"`, "warning");
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
} else {
|
|
272
|
+
const picked = await pick(ctx, visible, {
|
|
273
|
+
now: now(),
|
|
274
|
+
showProject: parsed.all,
|
|
275
|
+
drop: (dropped) => appendDrop(ledger, dropped.session, now()),
|
|
276
|
+
});
|
|
277
|
+
if (!picked || picked.action === "cancel") return;
|
|
278
|
+
entry = picked.entry;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (entry.missing) {
|
|
282
|
+
ctx.ui.notify(
|
|
283
|
+
`Session file is gone: ${entry.file} — press ctrl+r in the list to drop it`,
|
|
284
|
+
"warning",
|
|
285
|
+
);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Switching away from unkept work loses it from the backlog.
|
|
290
|
+
let keepBefore = false;
|
|
291
|
+
if (info && info.hasConversation && fileExists(info.file)) {
|
|
292
|
+
const current = state.entries.find((item) => item.session === info.session);
|
|
293
|
+
if (!current) {
|
|
294
|
+
const choice = await ask(ctx, entry);
|
|
295
|
+
if (choice === undefined || choice === "cancel") return;
|
|
296
|
+
keepBefore = choice === "keep";
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (keepBefore && info) keepCurrent(info, undefined, undefined);
|
|
300
|
+
|
|
301
|
+
appendLoad(ledger, entry.session, owner(), now());
|
|
302
|
+
try {
|
|
303
|
+
const result = await ctx.switchSession(entry.file, {
|
|
304
|
+
withSession: async (newCtx) => {
|
|
305
|
+
// Claim ownership only after the switch landed: the old session's
|
|
306
|
+
// `session_shutdown` fires during the switch and must release the
|
|
307
|
+
// session we are leaving, not the one we just loaded.
|
|
308
|
+
loadedHere = entry.session;
|
|
309
|
+
try {
|
|
310
|
+
await newCtx.sendMessage(
|
|
311
|
+
{
|
|
312
|
+
customType: KEEP_RESUME_ENTRY,
|
|
313
|
+
content: resumeText(entry),
|
|
314
|
+
display: true,
|
|
315
|
+
},
|
|
316
|
+
{},
|
|
317
|
+
);
|
|
318
|
+
} catch (error) {
|
|
319
|
+
// The switch already succeeded. A note-write failure must not
|
|
320
|
+
// unload the session that is open now, and it must not fall
|
|
321
|
+
// back to the old (stale) command context.
|
|
322
|
+
newCtx.ui.notify(
|
|
323
|
+
`Loaded ${entry.note}, but the resume note could not be saved: ${error instanceof Error ? error.message : String(error)}`,
|
|
324
|
+
"warning",
|
|
325
|
+
);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
newCtx.ui.notify(`Loaded: ${entry.note}`, "info");
|
|
329
|
+
},
|
|
330
|
+
});
|
|
331
|
+
if (!result.cancelled) return;
|
|
332
|
+
writeUnload(entry.session);
|
|
333
|
+
ctx.ui.notify("Load cancelled", "warning");
|
|
334
|
+
} catch (error) {
|
|
335
|
+
writeUnload(entry.session);
|
|
336
|
+
ctx.ui.notify(
|
|
337
|
+
`Failed to load: ${error instanceof Error ? error.message : String(error)}`,
|
|
338
|
+
"error",
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Append the `unload` for `session` and forget the claim if it was ours. */
|
|
344
|
+
function writeUnload(session: string): void {
|
|
345
|
+
if (loadedHere === session) loadedHere = undefined;
|
|
346
|
+
appendUnload(ledger, session, pid, now());
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
pi.registerCommand("keep-quit", {
|
|
350
|
+
description: "Keep this session as unfinished and quit",
|
|
351
|
+
handler: async (args, ctx) => runKeepQuit(args, ctx),
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
pi.registerCommand("keep-load", {
|
|
355
|
+
description: "Load a kept session: no argument opens the list; <n|id>, --all, rebuild",
|
|
356
|
+
handler: async (args, ctx) => runKeepLoad(args, ctx),
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
pi.registerCommand("keep-drop", {
|
|
360
|
+
description: "Remove this session from the keep list",
|
|
361
|
+
handler: async (args, ctx) => runKeepDrop(args, ctx),
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
const supportsEntryRenderer = typeof pi.registerEntryRenderer === "function";
|
|
365
|
+
if (supportsEntryRenderer) {
|
|
366
|
+
pi.registerEntryRenderer<{ count?: unknown }>(KEEP_NOTICE_ENTRY, (entry, _options, theme) => {
|
|
367
|
+
const count = entry.data?.count;
|
|
368
|
+
if (typeof count !== "number") return undefined;
|
|
369
|
+
return new Text(theme.fg("dim", noticeText(count)), 1, 0);
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// The resume note is a real message (the model needs it), but the default
|
|
374
|
+
// custom-message chrome (`[keep:resume]`) is noise in the transcript.
|
|
375
|
+
if (typeof pi.registerMessageRenderer === "function") {
|
|
376
|
+
pi.registerMessageRenderer(KEEP_RESUME_ENTRY, (message, _options, theme) => {
|
|
377
|
+
const content = message.content;
|
|
378
|
+
if (typeof content !== "string" || content.length === 0) return undefined;
|
|
379
|
+
return new Text(theme.fg("muted", content), 1, 0);
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
pi.on("session_start", (event, ctx) => {
|
|
384
|
+
if (event.reason !== "startup") return;
|
|
385
|
+
if (ctx.mode !== "tui") return;
|
|
386
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
387
|
+
if (sessionId === noticeSession) return;
|
|
388
|
+
noticeSession = sessionId;
|
|
389
|
+
|
|
390
|
+
const state = readState();
|
|
391
|
+
const count = state.notLoaded.filter(
|
|
392
|
+
(entry) => entry.session !== sessionId && samePath(entry.cwd, ctx.cwd),
|
|
393
|
+
).length;
|
|
394
|
+
if (count === 0) return;
|
|
395
|
+
if (supportsEntryRenderer) {
|
|
396
|
+
pi.appendEntry(KEEP_NOTICE_ENTRY, { count });
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
ctx.ui.notify(noticeText(count), "info");
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
pi.on("session_shutdown", (event) => {
|
|
403
|
+
// `reload` keeps the same session alive: it is not a release.
|
|
404
|
+
if (event.reason === "reload") return;
|
|
405
|
+
const session = loadedHere;
|
|
406
|
+
if (!session) return;
|
|
407
|
+
writeUnload(session);
|
|
408
|
+
});
|
|
409
|
+
}
|