@sion10032/pi-sessions 0.0.0-stage → 0.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,401 @@
1
+ /**
2
+ * The `/sessions` command: load this folder's sessions, let the user pick one,
3
+ * resume it, and archive or unarchive a session from the picker.
4
+ *
5
+ * Picking uses the terminal picker (`picker.ts`) in TUI mode and a plain
6
+ * `ctx.ui.select` list in every other mode. Resuming is shared by both paths:
7
+ * an archived session is moved back into the live tree first - pi only opens
8
+ * session files from its own sessions root - and only then is the switch
9
+ * requested.
10
+ *
11
+ * Archiving moves a session and its whole subtree. The session pi is still
12
+ * writing cannot be moved, so archiving it only records a pending archive that
13
+ * the shutdown hook completes.
14
+ */
15
+ import { existsSync } from "node:fs";
16
+ import { resolve } from "node:path";
17
+
18
+ import type {
19
+ ExtensionAPI,
20
+ ExtensionCommandContext,
21
+ } from "@earendil-works/pi-coding-agent";
22
+
23
+ import { archiveSessionFile, restoreSessionFile } from "./archive.ts";
24
+ import { deleteSessionFile, type DeleteResult } from "./delete.ts";
25
+ import {
26
+ displayTitle,
27
+ isArchived,
28
+ relativeTime,
29
+ sessionsRoot,
30
+ twinPaths,
31
+ underRoot,
32
+ } from "./paths.ts";
33
+ import { PickerState } from "./picker-state.ts";
34
+ import { SessionPicker } from "./picker.ts";
35
+ import { renameSessionFile } from "./rename.ts";
36
+ import {
37
+ filterRecords,
38
+ loadSessions,
39
+ } from "./sessions.ts";
40
+ import { setPending } from "./state.ts";
41
+ import type {
42
+ ArchiveFilter,
43
+ Scope,
44
+ SessionRecord,
45
+ } from "./types.ts";
46
+
47
+ /** Shown in a select label when the session header carries no working directory. */
48
+ const UNKNOWN_CWD = "(unknown cwd)";
49
+
50
+ /** Archive filters the `/sessions` argument accepts. */
51
+ const ARCHIVE_FILTERS: readonly ArchiveFilter[] = ["active", "archived", "all"];
52
+
53
+ /** Parse the `/sessions` argument: an archive filter, or undefined for none. */
54
+ export function parseFilterArg(arg: string): ArchiveFilter | undefined {
55
+ const value = arg.trim().toLowerCase();
56
+ return ARCHIVE_FILTERS.find((filter) => filter === value);
57
+ }
58
+
59
+ /**
60
+ * One line describing a session in the non-TUI list. It shows the archive date
61
+ * (which falls back to the last activity for live sessions) and the working
62
+ * directory, so two sessions with the same title still read differently. The
63
+ * archived marker is appended rather than joined so it reads as a tag after
64
+ * the location.
65
+ */
66
+ export function formatOption(record: SessionRecord): string {
67
+ const { info } = record;
68
+ const cwd = info.cwd || UNKNOWN_CWD;
69
+ const label = `${displayTitle(info)} · ${relativeTime(record.archiveDate)} · ${cwd}`;
70
+ return record.archived ? `${label} [archived]` : label;
71
+ }
72
+
73
+ /**
74
+ * The context archive actions need. A `Pick` rather than the full command
75
+ * context, so the `archive_session` tool can hand in its own context, which
76
+ * shares these members without being an `ExtensionCommandContext`.
77
+ */
78
+ export type SessionCtx = Pick<ExtensionCommandContext, "sessionManager" | "ui" | "cwd">;
79
+
80
+ /**
81
+ * Archive a live session - or restore an archived one - together with its
82
+ * whole subtree. The session pi is still writing cannot be moved: archiving it
83
+ * only records a pending archive for shutdown, reported as `deferred`. It is
84
+ * passed as `protect` to both moves, so a selected ancestor is archived
85
+ * without taking the live session down with it.
86
+ *
87
+ * Every failure is notified and turns into an empty result, so the picker
88
+ * keeps running and simply reloads the unchanged trees.
89
+ */
90
+ export async function toggleArchive(
91
+ pi: ExtensionAPI,
92
+ ctx: SessionCtx,
93
+ record: SessionRecord,
94
+ ): Promise<{ moved: string[]; deferred: boolean }> {
95
+ try {
96
+ const currentFile = ctx.sessionManager.getSessionFile();
97
+ const protect = currentFile === undefined ? [] : [currentFile];
98
+ if (
99
+ !record.archived
100
+ && currentFile !== undefined
101
+ && resolve(record.info.path) === resolve(currentFile)
102
+ ) {
103
+ deferArchive(pi, ctx);
104
+ return { moved: [], deferred: true };
105
+ }
106
+ if (record.archived) {
107
+ if (currentFile !== undefined && resolve(record.info.path) === resolve(currentFile)) {
108
+ ctx.ui.notify("The current session cannot be moved", "warning");
109
+ return { moved: [], deferred: false };
110
+ }
111
+ const moved = restoreSessionFile(record.info.path, { protect });
112
+ // Nothing moves when the live twin already exists; the archived copy
113
+ // stays put, so "Restored 0 sessions" would be misleading.
114
+ if (moved.length === 0) ctx.ui.notify("A live copy already exists", "warning");
115
+ else ctx.ui.notify(`Restored ${moved.length} sessions`, "info");
116
+ return { moved, deferred: false };
117
+ }
118
+ const moved = archiveSessionFile(record.info.path, { name: record.info.name, protect });
119
+ if (moved.length === 0) {
120
+ // Only reachable for a stale record or a file outside `sessions/`; the
121
+ // current session takes the deferred branch above.
122
+ ctx.ui.notify("Nothing was archived", "warning");
123
+ return { moved, deferred: false };
124
+ }
125
+ const children = moved.length - 1;
126
+ const suffix = children > 0 ? ` (+${children} child sessions)` : "";
127
+ ctx.ui.notify(`Archived ${displayTitle(record.info)}${suffix}`, "info");
128
+ return { moved, deferred: false };
129
+ } catch (error) {
130
+ const action = record.archived ? "restore" : "archive";
131
+ ctx.ui.notify(`Failed to ${action} session: ${errorMessage(error)}`, "error");
132
+ return { moved: [], deferred: false };
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Record an archive request for the session pi is running now; the shutdown
138
+ * hook moves the file once pi is done writing it. A session without a file or
139
+ * an id cannot be recorded and is reported instead, and so is a session whose
140
+ * file lives outside `sessions/` (a custom `--session-dir`): the archive move
141
+ * could never run for it, so arming a pending entry would only mislead.
142
+ */
143
+ export function deferArchive(_pi: ExtensionAPI, ctx: SessionCtx): void {
144
+ const file = ctx.sessionManager.getSessionFile();
145
+ const id = ctx.sessionManager.getSessionId();
146
+ if (!file || !id) {
147
+ ctx.ui.notify("No current session to archive yet", "warning");
148
+ return;
149
+ }
150
+ if (underRoot(sessionsRoot(), file) === undefined) {
151
+ ctx.ui.notify("This session lives outside the sessions directory and cannot be archived", "warning");
152
+ return;
153
+ }
154
+ setPending(id, { path: file, cwd: ctx.cwd, requestedAt: new Date().toISOString() });
155
+ ctx.ui.notify("Session will be archived when it closes", "info");
156
+ }
157
+
158
+ /**
159
+ * The path to hand to `switchSession` and the live files a restore moved.
160
+ *
161
+ * A live session resumes in place. An archived one has to go back under the
162
+ * live sessions root first: when its twin is already there (pi kept writing to
163
+ * the live path after the archive) that copy wins and nothing moves; otherwise
164
+ * the whole archive subtree is restored. `protect` names the session pi is
165
+ * still writing, so selecting its archived copy never moves that file. When
166
+ * the restore moved nothing and the live path still does not exist, `target`
167
+ * is that missing live path so the caller can warn instead of switching to a
168
+ * file that is not there.
169
+ */
170
+ export function resolveResumeTarget(
171
+ record: SessionRecord,
172
+ protect?: string,
173
+ ): { target: string; restored: string[] } {
174
+ if (!record.archived) return { target: record.info.path, restored: [] };
175
+ const live = twinPaths(record.info.path).find((path) => !isArchived(path)) ?? record.info.path;
176
+ if (existsSync(live)) return { target: live, restored: [] };
177
+ return {
178
+ target: live,
179
+ restored: restoreSessionFile(record.info.path, protect === undefined ? {} : { protect: [protect] }),
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Switch to `record`, restoring it first when it is archived. A missing file
185
+ * is reported instead: pi cannot open a session that is not there, and the
186
+ * picker may be showing a record whose file was moved behind its back. A
187
+ * failure to move or open the file is reported too, so it never surfaces as
188
+ * the host's command error.
189
+ */
190
+ async function resume(ctx: ExtensionCommandContext, record: SessionRecord): Promise<void> {
191
+ let target: string;
192
+ let restored: string[];
193
+ try {
194
+ // The session pi is writing stays where it is even when its archived
195
+ // copy is the record the user picked.
196
+ ({ target, restored } = resolveResumeTarget(record, ctx.sessionManager.getSessionFile()));
197
+ } catch (error) {
198
+ ctx.ui.notify(`Failed to restore session: ${errorMessage(error)}`, "error");
199
+ return;
200
+ }
201
+ if (!existsSync(target)) {
202
+ ctx.ui.notify("Session file is missing", "warning");
203
+ return;
204
+ }
205
+ if (restored.length > 0) ctx.ui.notify("Restored to the active sessions list", "info");
206
+ try {
207
+ // A cancelled switch keeps the current session, which needs no follow-up.
208
+ await ctx.switchSession(target);
209
+ } catch (error) {
210
+ ctx.ui.notify(`Failed to switch session: ${errorMessage(error)}`, "error");
211
+ }
212
+ }
213
+
214
+ /** A thrown value's message, for a one-line notification. */
215
+ function errorMessage(error: unknown): string {
216
+ return error instanceof Error ? error.message : String(error);
217
+ }
218
+
219
+ /**
220
+ * Rename a session from the picker. The session pi is running has to go
221
+ * through `pi.setSessionName`, which also refreshes the footer; every other
222
+ * one, archived included, gets a `session_info` entry in its own file.
223
+ */
224
+ export function renameSession(
225
+ pi: ExtensionAPI,
226
+ ctx: SessionCtx,
227
+ record: SessionRecord,
228
+ name: string,
229
+ ): void {
230
+ const next = name.trim();
231
+ if (next === "") return;
232
+ try {
233
+ const currentFile = ctx.sessionManager.getSessionFile();
234
+ if (currentFile !== undefined && resolve(record.info.path) === resolve(currentFile)) {
235
+ pi.setSessionName(next);
236
+ } else {
237
+ renameSessionFile(record.info.path, next);
238
+ }
239
+ } catch (error) {
240
+ ctx.ui.notify(`Failed to rename session: ${errorMessage(error)}`, "error");
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Delete a session and its whole subtree from the picker. The running session
246
+ * is passed as `protect`, so a delete that raced a selection change cannot take
247
+ * the file pi is still writing. The count in the notice is the sessions, not
248
+ * every companion file that went with them.
249
+ */
250
+ export function deleteSession(ctx: SessionCtx, record: SessionRecord): DeleteResult {
251
+ const currentFile = ctx.sessionManager.getSessionFile();
252
+ try {
253
+ const result = deleteSessionFile(
254
+ record.info.path,
255
+ currentFile === undefined ? {} : { protect: [currentFile] },
256
+ );
257
+ if (result.refused) {
258
+ ctx.ui.notify("Cannot delete the currently active session", "warning");
259
+ return result;
260
+ }
261
+ const count = result.deleted.filter((path) => path.endsWith(".jsonl")).length;
262
+ const failed = result.failed.length > 0 ? ` (${result.failed.length} failed)` : "";
263
+ ctx.ui.notify(`Deleted ${count} session${count === 1 ? "" : "s"}${failed}`, "info");
264
+ return result;
265
+ } catch (error) {
266
+ ctx.ui.notify(`Failed to delete session: ${errorMessage(error)}`, "error");
267
+ return { deleted: [], failed: [], refused: false };
268
+ }
269
+ }
270
+
271
+ /** The terminal picker; resolves to the chosen record, or null when cancelled. */
272
+ async function pickInTui(
273
+ pi: ExtensionAPI,
274
+ ctx: ExtensionCommandContext,
275
+ records: SessionRecord[],
276
+ filter: ArchiveFilter | undefined,
277
+ ): Promise<SessionRecord | null> {
278
+ return ctx.ui.custom<SessionRecord | null>((tui, theme, keybindings, done) => {
279
+ const state = new PickerState(records, ctx.sessionManager.getSessionFile(), ctx.cwd);
280
+ if (filter !== undefined) state.setArchiveFilter(filter);
281
+
282
+ let loadToken = 0;
283
+ let loadController: AbortController | undefined;
284
+ const reload = (scope: Scope): void => {
285
+ const token = ++loadToken;
286
+ loadController?.abort();
287
+ const controller = new AbortController();
288
+ loadController = controller;
289
+ state.beginLoading();
290
+ tui.requestRender();
291
+ void loadSessions(scope, ctx.cwd, {
292
+ signal: controller.signal,
293
+ onProgress: (next, progress) => {
294
+ if (token !== loadToken || state.scope !== scope) return;
295
+ state.setRecords(next);
296
+ state.setLoadingProgress(progress.loaded, progress.total, progress.phase);
297
+ tui.requestRender();
298
+ },
299
+ }).then((next) => {
300
+ if (token !== loadToken || state.scope !== scope) return;
301
+ state.finishLoading(next);
302
+ tui.requestRender();
303
+ }).catch((error) => {
304
+ if (token !== loadToken || controller.signal.aborted) return;
305
+ state.failLoading();
306
+ tui.requestRender();
307
+ ctx.ui.notify(`Failed to reload sessions: ${errorMessage(error)}`, "error");
308
+ });
309
+ };
310
+ const finish = (value: SessionRecord | null): void => {
311
+ // Invalidate the in-flight load before aborting so its rejection does
312
+ // not surface as an error after the picker has closed.
313
+ loadToken++;
314
+ loadController?.abort();
315
+ done(value);
316
+ };
317
+
318
+ return new SessionPicker({
319
+ state,
320
+ theme,
321
+ tui,
322
+ keybindings,
323
+ onResume: (record) => finish(record),
324
+ onCancel: () => finish(null),
325
+ onToggleArchive: (record) => {
326
+ void toggleArchive(pi, ctx, record)
327
+ .then((result) => {
328
+ // A deferred archive moves nothing until shutdown, so the rows
329
+ // are still accurate and need no reload.
330
+ if (result.deferred) return;
331
+ reload(state.scope);
332
+ })
333
+ .catch((error) => ctx.ui.notify(`Failed to archive session: ${errorMessage(error)}`, "error"));
334
+ },
335
+ onRename: (record, name) => {
336
+ renameSession(pi, ctx, record, name);
337
+ reload(state.scope);
338
+ },
339
+ onDelete: (record) => {
340
+ const result = deleteSession(ctx, record);
341
+ // A refused delete moved nothing; reloading would only redraw.
342
+ if (!result.refused) reload(state.scope);
343
+ },
344
+ onDeleteRefused: (reason) => ctx.ui.notify(
345
+ reason === "current"
346
+ ? "Cannot delete the currently active session"
347
+ : "The current session is inside this session's tree",
348
+ "warning",
349
+ ),
350
+ onReload: reload,
351
+ });
352
+ });
353
+ }
354
+
355
+ /**
356
+ * The flat list for modes without custom components. Numbered labels keep two
357
+ * sessions with the same title apart: `select` only hands back the label, so
358
+ * the number - not the text - is what maps back to the record.
359
+ */
360
+ async function pickWithSelect(
361
+ ctx: ExtensionCommandContext,
362
+ records: SessionRecord[],
363
+ filter: ArchiveFilter | undefined,
364
+ ): Promise<SessionRecord | undefined> {
365
+ // There is no `ctrl+t` here, so archived sessions stay listed unless the
366
+ // argument asks for one archive state only.
367
+ const visible = filterRecords(records, { archiveFilter: filter ?? "all" });
368
+ if (visible.length === 0) {
369
+ ctx.ui.notify("No sessions match the current filter", "info");
370
+ return undefined;
371
+ }
372
+ const byLabel = new Map<string, SessionRecord>();
373
+ const labels = visible.map((record, index) => {
374
+ const label = `${index + 1}. ${formatOption(record)}`;
375
+ byLabel.set(label, record);
376
+ return label;
377
+ });
378
+ const choice = await ctx.ui.select("Resume session", labels);
379
+ return choice === undefined ? undefined : byLabel.get(choice);
380
+ }
381
+
382
+ /**
383
+ * `/sessions [active|archived|all]`: browse, resume and archive sessions. The
384
+ * argument only picks the starting archive filter; the picker can still change
385
+ * it.
386
+ */
387
+ export async function runSessions(pi: ExtensionAPI, ctx: ExtensionCommandContext, args: string): Promise<void> {
388
+ const records = await loadSessions("current", ctx.cwd);
389
+ // The terminal picker stays reachable without sessions in this folder: `tab`
390
+ // switches to the `all` scope, which reloads sessions from everywhere.
391
+ if (records.length === 0 && ctx.mode !== "tui") {
392
+ ctx.ui.notify("No sessions found", "info");
393
+ return;
394
+ }
395
+ const filter = parseFilterArg(args);
396
+ const chosen = ctx.mode === "tui"
397
+ ? await pickInTui(pi, ctx, records, filter)
398
+ : await pickWithSelect(ctx, records, filter);
399
+ if (chosen === undefined || chosen === null) return;
400
+ await resume(ctx, chosen);
401
+ }
package/src/delete.ts ADDED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * File-level primitives for deleting sessions.
3
+ *
4
+ * Deleting follows the same shape as archiving: a session is not just its
5
+ * JSONL file. Its derived sessions (`parentSession` chain in the same folder)
6
+ * belong to the subtree, its companions live beside it, and the same session
7
+ * may also exist in the archive tree as a twin. All of them go together, or a
8
+ * deleted session would come back as an orphan, a leftover directory, or a
9
+ * row that reappears in the `archived` view.
10
+ *
11
+ * Moves go through the system trash first - the same `trash` CLI pi's own
12
+ * picker tries - and fall back to a permanent `rm`. Everything is best
13
+ * effort: one failure never stops the rest, and it is reported so the caller
14
+ * can show it.
15
+ */
16
+ import { spawnSync } from "node:child_process";
17
+ import { existsSync, rmSync } from "node:fs";
18
+ import { dirname, join, resolve } from "node:path";
19
+
20
+ import { descendantFiles, findCompanions } from "./archive.ts";
21
+ import { archiveRoot, sessionIdFromFile, twinPaths, underRoot } from "./paths.ts";
22
+ import { clearPending, readIndex, writeIndex } from "./state.ts";
23
+
24
+ /** The two filesystem operations a delete needs; injectable for tests. */
25
+ export interface DeleteOps {
26
+ /** Move every path to the system trash. True only when all of them are gone. */
27
+ trash(paths: string[]): boolean;
28
+ /** Remove one file or directory tree. Throws when it cannot. */
29
+ remove(path: string): void;
30
+ }
31
+
32
+ export interface DeleteOptions {
33
+ /**
34
+ * Session files that must not be deleted: typically the session pi is
35
+ * writing. A protected file anywhere in the subtree refuses the whole
36
+ * delete instead of leaving a half tree behind.
37
+ */
38
+ protect?: readonly string[];
39
+ ops?: Partial<DeleteOps>;
40
+ }
41
+
42
+ export interface DeleteResult {
43
+ /** Paths that are gone, including companions and twins. */
44
+ deleted: string[];
45
+ /** Paths the filesystem refused to remove. */
46
+ failed: string[];
47
+ /** True when a protected file was part of the subtree; nothing was touched. */
48
+ refused: boolean;
49
+ }
50
+
51
+ /** Trash arguments: `--` first, so a file named `-rf.jsonl` is not a flag. */
52
+ export function trashArgs(paths: string[]): string[] {
53
+ return ["--", ...paths];
54
+ }
55
+
56
+ /**
57
+ * The real operations. `trash` succeeds when the CLI exits 0 and the paths are
58
+ * really gone (a `trash` that ignores its arguments must not look successful);
59
+ * `remove` is recursive so one call covers files and companion directories.
60
+ */
61
+ export function defaultDeleteOps(): DeleteOps {
62
+ return {
63
+ trash(paths: string[]): boolean {
64
+ if (paths.length === 0) return true;
65
+ const result = spawnSync("trash", trashArgs(paths), { encoding: "utf-8" });
66
+ return result.status === 0 && paths.every((path) => !existsSync(path));
67
+ },
68
+ remove(path: string): void {
69
+ rmSync(path, { recursive: true, force: true });
70
+ },
71
+ };
72
+ }
73
+
74
+ /** Resolved keys of the protected files, twins included. */
75
+ function protectedKeys(protect: readonly string[] | undefined): Set<string> {
76
+ const keys = new Set<string>();
77
+ for (const path of protect ?? []) {
78
+ for (const twin of twinPaths(path)) keys.add(resolve(twin));
79
+ }
80
+ return keys;
81
+ }
82
+
83
+ /** Absolute paths, first occurrence wins. */
84
+ function unique(paths: string[]): string[] {
85
+ const seen = new Set<string>();
86
+ const result: string[] = [];
87
+ for (const path of paths) {
88
+ const absolute = resolve(path);
89
+ if (seen.has(absolute)) continue;
90
+ seen.add(absolute);
91
+ result.push(absolute);
92
+ }
93
+ return result;
94
+ }
95
+
96
+ /**
97
+ * Delete `file` and its whole subtree, together with the companions and the
98
+ * archive-tree twins of every session in it. Returns what disappeared and what
99
+ * did not; a protected file inside the subtree refuses the delete whole.
100
+ */
101
+ export function deleteSessionFile(file: string, options: DeleteOptions = {}): DeleteResult {
102
+ const root = resolve(file);
103
+ const protect = protectedKeys(options.protect);
104
+ if (protect.has(root)) return { deleted: [], failed: [], refused: true };
105
+
106
+ // Session files first, root first: their twins and descendants follow.
107
+ const sessions = unique([root, ...descendantFiles(dirname(root), root)]);
108
+ const sessionFiles = unique(
109
+ sessions.flatMap((sessionFile) => twinPaths(sessionFile).filter((twin) => existsSync(twin))),
110
+ );
111
+ const companions = unique(
112
+ sessionFiles.flatMap((sessionFile) => {
113
+ const sessionDir = dirname(sessionFile);
114
+ return findCompanions(sessionDir, sessionFile).map((rel) => join(sessionDir, rel));
115
+ }),
116
+ );
117
+ if ([...sessionFiles, ...companions].some((path) => protect.has(path))) {
118
+ return { deleted: [], failed: [], refused: true };
119
+ }
120
+
121
+ const base = defaultDeleteOps();
122
+ const ops: DeleteOps = {
123
+ trash: options.ops?.trash ?? base.trash,
124
+ remove: options.ops?.remove ?? base.remove,
125
+ };
126
+ const deleted: string[] = [];
127
+ const failed: string[] = [];
128
+
129
+ // Trash handles the whole set in one call, companions included: a delete
130
+ // that can be undone should be undone for the subagent artifacts and
131
+ // screenshots too, not just for the JSONL files. A trash that cannot take
132
+ // directories fails on the call and every path is removed individually.
133
+ const all = [...sessionFiles, ...companions];
134
+ if (all.length > 0) {
135
+ if (ops.trash(all)) {
136
+ deleted.push(...all);
137
+ } else {
138
+ for (const path of all) {
139
+ try {
140
+ ops.remove(path);
141
+ deleted.push(path);
142
+ } catch {
143
+ failed.push(path);
144
+ }
145
+ }
146
+ }
147
+ }
148
+
149
+ // The archive metadata follows the files: an index entry that names a deleted
150
+ // file would keep a phantom archive alive. Only the removed keys are written
151
+ // back, so a corrupt (empty-read) index is left untouched.
152
+ const index = readIndex();
153
+ let indexChanged = false;
154
+ for (const path of deleted) {
155
+ if (!path.endsWith(".jsonl")) continue;
156
+ const key = underRoot(archiveRoot(), path);
157
+ if (key !== undefined && key in index) {
158
+ delete index[key];
159
+ indexChanged = true;
160
+ }
161
+ clearPending(sessionIdFromFile(path));
162
+ }
163
+ if (indexChanged) writeIndex(index);
164
+
165
+ return { deleted, failed, refused: false };
166
+ }
package/src/index.ts ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The pi-sessions extension entry point.
3
+ *
4
+ * `/sessions` browses, resumes and archives sessions; `/archive` and the
5
+ * `archive_session` tool defer archiving the session pi is running now. The
6
+ * running session's file cannot be moved while pi still writes it, so a
7
+ * deferred archive is only completed by the `session_shutdown` hook - and not
8
+ * when the shutdown is a reload or a switch to the same file.
9
+ */
10
+ import { existsSync } from "node:fs";
11
+
12
+ import type {
13
+ ExtensionAPI,
14
+ ExtensionContext,
15
+ SessionShutdownEvent,
16
+ SessionStartEvent,
17
+ } from "@earendil-works/pi-coding-agent";
18
+ import { Type } from "typebox";
19
+
20
+ import { archiveSessionFile } from "./archive.ts";
21
+ import { deferArchive, runSessions } from "./commands.ts";
22
+ import { isArchived } from "./paths.ts";
23
+ import { clearPending, readPending } from "./state.ts";
24
+
25
+ /** A thrown value's message, for a one-line notification. */
26
+ function errorMessage(error: unknown): string {
27
+ return error instanceof Error ? error.message : String(error);
28
+ }
29
+
30
+ /**
31
+ * Forget a deferred archive whose session is already archived: the request was
32
+ * completed by an earlier shutdown, or the session was archived from the
33
+ * picker. A live session keeps its pending entry armed for shutdown.
34
+ */
35
+ function sessionStart(ctx: ExtensionContext): void {
36
+ const id = ctx.sessionManager.getSessionId();
37
+ if (!readPending()[id]) return;
38
+ const file = ctx.sessionManager.getSessionFile();
39
+ if (file !== undefined && isArchived(file)) clearPending(id);
40
+ }
41
+
42
+ /**
43
+ * Complete a deferred archive. A reload keeps the file where it is: pi is
44
+ * about to reopen the same session, so moving it would lose the session the
45
+ * user is in. A switch whose target is the current file does not move it
46
+ * either, and a switch to a derived session - `/fork` and resuming a child
47
+ * both write the new session as a child of this one - protects that target:
48
+ * pi is about to append to it, so moving it would leave a headerless file.
49
+ * A file that is already archived or gone only needs its pending entry
50
+ * dropped; a failure to move is notified and leaves the request pending.
51
+ */
52
+ function sessionShutdown(pi: ExtensionAPI, event: SessionShutdownEvent, ctx: ExtensionContext): void {
53
+ const id = ctx.sessionManager.getSessionId();
54
+ if (!readPending()[id]) return;
55
+ if (event.reason === "reload") return;
56
+ const file = ctx.sessionManager.getSessionFile();
57
+ if (!file || event.targetSessionFile === file) return;
58
+ if (isArchived(file) || !existsSync(file)) {
59
+ clearPending(id);
60
+ return;
61
+ }
62
+ try {
63
+ archiveSessionFile(file, {
64
+ name: pi.getSessionName(),
65
+ protect: event.targetSessionFile === undefined ? [] : [event.targetSessionFile],
66
+ });
67
+ } catch (error) {
68
+ ctx.ui.notify(`Archive failed: ${errorMessage(error)}`, "error");
69
+ }
70
+ }
71
+
72
+ export default function piSessions(pi: ExtensionAPI): void {
73
+ pi.registerCommand("sessions", {
74
+ description: "Browse and resume sessions, including archived ones",
75
+ handler: (args, ctx) => runSessions(pi, ctx, args),
76
+ });
77
+ pi.registerCommand("archive", {
78
+ description: "Archive the current session when it closes",
79
+ handler: async (_args, ctx) => deferArchive(pi, ctx),
80
+ });
81
+ pi.registerTool({
82
+ name: "archive_session",
83
+ label: "Archive Session",
84
+ description: "Archive the current session when it closes. Use when the user says work is complete.",
85
+ parameters: Type.Object({}),
86
+ execute: async (_toolCallId, _params, _signal, _onUpdate, ctx) => {
87
+ deferArchive(pi, ctx);
88
+ return {
89
+ content: [{ type: "text", text: "Session will be archived when it closes" }],
90
+ details: undefined,
91
+ };
92
+ },
93
+ });
94
+ pi.on("session_start", (_event: SessionStartEvent, ctx) => sessionStart(ctx));
95
+ pi.on("session_shutdown", (event, ctx) => sessionShutdown(pi, event, ctx));
96
+ }