@sion10032/pi-sessions 0.1.0 → 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.
- package/README.md +11 -0
- package/package.json +1 -1
- package/src/index.ts +5 -0
- package/src/undo.ts +183 -0
package/README.md
CHANGED
|
@@ -39,6 +39,7 @@ pi -e ./packages/pi-sessions
|
|
|
39
39
|
| 名称 | 用法 | 说明 |
|
|
40
40
|
| --- | --- | --- |
|
|
41
41
|
| `/sessions` | `/sessions [active\|archived\|all]` | 打开会话列表;可选参数只决定初始的归档筛选,打开后仍可切换 |
|
|
42
|
+
| `/undo` | `/undo` | 回滚到最新一条用户消息之前:原文回到输入框,尾部从会话文件里真正删掉,不新建子树 |
|
|
42
43
|
| `/archive` | `/archive` | 把当前会话标记为“关闭后归档” |
|
|
43
44
|
| `archive_session` | 工具调用,无参数 | 同上,供 agent 在用户说“工作完成了”时调用 |
|
|
44
45
|
| `/resume` | 原生命令 | 仍可正常使用,只看活跃会话(归档会话不在其中) |
|
|
@@ -86,6 +87,14 @@ pi -e ./packages/pi-sessions
|
|
|
86
87
|
- `tab` 切换作用域时,列表会立即清空并显示 `Loading… 已加载/总数`,live 会话按 `SessionManager.listAll` 的进度分批出现,归档目录随后逐个合并;再次切换或关闭 picker 会中止上一次加载。
|
|
87
88
|
- `tab`、`ctrl+s`、`ctrl+n`、`ctrl+p`、`ctrl+r`、`ctrl+d`、`ctrl+backspace` 使用 pi 的键位名 `tui.input.tab`、`app.session.toggleSort`、`app.session.toggleNamedFilter`、`app.session.togglePath`、`app.session.rename`、`app.session.delete`、`app.session.deleteNoninvasive`,可在 `~/.pi/agent/keybindings.json` 里改;`ctrl+t`、`ctrl+e`、`ctrl+a` 是本插件直接读取的按键,不可改。
|
|
88
89
|
|
|
90
|
+
## `/undo` 语义
|
|
91
|
+
|
|
92
|
+
**落点。** `/undo` 取当前分支上离 leaf 最近的一条用户消息,把 leaf 退回到它的上一条,并把这句原文放回输入框(编辑器里已经有草稿时不覆盖,只提示未写回)。分支优先级按 `getBranch()`,不是文件里最后一条:早前用 `/tree` 切过分支时,被放弃的那条线上的用户消息不会被选中。注入的 `custom_message`、bash 结果、压缩摘要都不算“用户消息”。
|
|
93
|
+
|
|
94
|
+
**真删,不是旁支。** 该条及其之后的行会从会话 JSONL 里删掉(`header` 保留),随后用 `ctx.switchSession(同一文件)` 让宿主从文件重建会话。所以 `/tree` 里不会多出一条旁支,`/sessions` 里也不会多出一棵子树 —— 这正是它与 `/fork` 的区别:`/fork` 是新建子会话文件,`/undo` 是同一个文件往回退。
|
|
95
|
+
|
|
96
|
+
**限制。** 只在空闲时可用:正在生成回复、或还有排队的 steering/follow-up 消息时会直接拒绝并提示等待。回滚到第一条用户消息会让会话变成空会话(只剩 header),之后可以照常开始新的对话。被删的内容**不可恢复**,写盘顺序在保留点之后的兄弟分支(早前 `/tree` 留下的那条线)以及它们携带的改名、label 也会一并消失。
|
|
97
|
+
|
|
89
98
|
## 归档语义
|
|
90
99
|
|
|
91
100
|
**物理移动。** 归档把 `<agent>/sessions/<cwd-slug>/x.jsonl` 移到 `<agent>/sessions-archive/<cwd-slug>/x.jsonl`,取消归档做反向移动。归档状态只由目录位置推导,不写进会话文件,也不依赖索引。
|
|
@@ -178,6 +187,7 @@ pi -e ./packages/pi-sessions
|
|
|
178
187
|
- **`.superseded-*` 不自动清理**:被替换下来的旧归档文件需要手动删除。
|
|
179
188
|
- **删除不可撤销**:插件没有自己的回收站,整批路径(会话文件、孪生副本、伴生目录、截图、子代理产物)一次交给系统 `trash`;`trash` 不存在或返回失败时全部回退为永久删除,此时无法恢复。删除同样不检测其他 pi 实例是否正在使用该会话。
|
|
180
189
|
- **非 TUI 模式没有重命名与删除**:`ctx.ui.select` 的扁平列表只能选择恢复;需要在列表里改名或删除请用原生 `/resume`,本插件不提供 `/rename`、`/delete` 命令。
|
|
190
|
+
- **`/undo` 会真的删掉尾部**:它是物理截断而不是 `/tree` 式旁支,被回滚的那一轮(以及写盘顺序在保留点之后的其它分支、改名、label)不可恢复;编辑器里已有草稿时不写回原文。请在空闲时使用。
|
|
181
191
|
|
|
182
192
|
## 隐私
|
|
183
193
|
|
|
@@ -229,6 +239,7 @@ nix develop -c env -u NODE_ENV npm install
|
|
|
229
239
|
| `src/paths.ts` | 路径、目录名、标题与 session header 读取 |
|
|
230
240
|
| `src/state.ts` | `index.json` 与 `pi-sessions-state.json` 的读写 |
|
|
231
241
|
| `src/search.ts` | 查询解析与相关性排序 |
|
|
242
|
+
| `src/undo.ts` | `/undo` 的目标选择、会话文件截断与重载 |
|
|
232
243
|
| `src/types.ts` | 共享类型 |
|
|
233
244
|
|
|
234
245
|
## 手动验收清单
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sion10032/pi-sessions",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Browse, archive, restore and resume pi sessions, including their subagent sessions",
|
|
5
5
|
"keywords": ["pi-package", "pi-extension", "session", "archive", "resume"],
|
|
6
6
|
"license": "MIT",
|
package/src/index.ts
CHANGED
|
@@ -19,6 +19,7 @@ import { Type } from "typebox";
|
|
|
19
19
|
|
|
20
20
|
import { archiveSessionFile } from "./archive.ts";
|
|
21
21
|
import { deferArchive, runSessions } from "./commands.ts";
|
|
22
|
+
import { runUndo } from "./undo.ts";
|
|
22
23
|
import { isArchived } from "./paths.ts";
|
|
23
24
|
import { clearPending, readPending } from "./state.ts";
|
|
24
25
|
|
|
@@ -78,6 +79,10 @@ export default function piSessions(pi: ExtensionAPI): void {
|
|
|
78
79
|
description: "Archive the current session when it closes",
|
|
79
80
|
handler: async (_args, ctx) => deferArchive(pi, ctx),
|
|
80
81
|
});
|
|
82
|
+
pi.registerCommand("undo", {
|
|
83
|
+
description: "Rewind to just before your last message, without creating a fork",
|
|
84
|
+
handler: (_args, ctx) => runUndo(ctx),
|
|
85
|
+
});
|
|
81
86
|
pi.registerTool({
|
|
82
87
|
name: "archive_session",
|
|
83
88
|
label: "Archive Session",
|
package/src/undo.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/undo`: rewind the current session to just before its newest user message.
|
|
3
|
+
*
|
|
4
|
+
* Unlike `/fork`, which writes a child session file, undo stays in the same
|
|
5
|
+
* file: the tail is cut from the JSONL and the session is reloaded from disk,
|
|
6
|
+
* so the abandoned turn leaves neither a fork subtree nor an unselected branch
|
|
7
|
+
* behind in `/tree`.
|
|
8
|
+
*/
|
|
9
|
+
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { basename, dirname, join } from "node:path";
|
|
11
|
+
|
|
12
|
+
import type { ExtensionCommandContext, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
|
|
14
|
+
/** Where an undo rewinds to: the parent entry, and the prompt to restore. */
|
|
15
|
+
export interface UndoTarget {
|
|
16
|
+
entryId: string;
|
|
17
|
+
parentId: string | null;
|
|
18
|
+
/** The prompt text, as `/fork` would put it back in the editor. */
|
|
19
|
+
text: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The newest user message on the active branch, nearest the leaf. Only real
|
|
24
|
+
* user messages count: injected `custom_message` entries, bash results and
|
|
25
|
+
* compaction summaries are not something the user typed, so they are skipped
|
|
26
|
+
* even when they sit above the prompt.
|
|
27
|
+
*/
|
|
28
|
+
export function findUndoTarget(
|
|
29
|
+
sessionManager: Pick<SessionManager, "getBranch">,
|
|
30
|
+
): UndoTarget | undefined {
|
|
31
|
+
for (const entry of [...sessionManager.getBranch()].reverse()) {
|
|
32
|
+
if (entry.type !== "message" || entry.message.role !== "user") continue;
|
|
33
|
+
return {
|
|
34
|
+
entryId: entry.id,
|
|
35
|
+
parentId: entry.parentId,
|
|
36
|
+
text: messageText(entry.message.content),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Text of a user message, extracted the way pi's fork path extracts it. */
|
|
43
|
+
function messageText(content: string | readonly { type: string; text?: string }[]): string {
|
|
44
|
+
if (typeof content === "string") return content;
|
|
45
|
+
return content
|
|
46
|
+
.filter((part) => part.type === "text" && typeof part.text === "string")
|
|
47
|
+
.map((part) => part.text ?? "")
|
|
48
|
+
.join("");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** How many rows an undo kept and dropped. */
|
|
52
|
+
export interface TruncateResult {
|
|
53
|
+
kept: number;
|
|
54
|
+
removed: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Keep the header row and every row up to and including the last row whose
|
|
59
|
+
* parsed `id` is `throughId`, dropping the rest. `throughId === null` keeps the
|
|
60
|
+
* header alone, which is what undoing the very first prompt leaves behind.
|
|
61
|
+
*
|
|
62
|
+
* Rows are compared by parsed id rather than by index because a session file is
|
|
63
|
+
* append-ordered across branches: rows written after the kept one belong either
|
|
64
|
+
* to the abandoned turn or to an older branch, and both go.
|
|
65
|
+
*/
|
|
66
|
+
export function truncateSessionFile(file: string, throughId: string | null): TruncateResult {
|
|
67
|
+
const rows = readFileSync(file, "utf8").split("\n");
|
|
68
|
+
while (rows.length > 0 && rows[rows.length - 1] === "") rows.pop();
|
|
69
|
+
const keepIndex = throughId === null ? 0 : lastRowWithId(rows, throughId);
|
|
70
|
+
if (keepIndex === -1) throw new Error(`Session entry not found: ${throughId}`);
|
|
71
|
+
const kept = rows.slice(0, keepIndex + 1);
|
|
72
|
+
writeAtomically(file, `${kept.join("\n")}\n`);
|
|
73
|
+
return { kept: kept.length, removed: rows.length - kept.length };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Index of the last row that parses to an entry with this id, or -1. */
|
|
77
|
+
function lastRowWithId(rows: string[], id: string): number {
|
|
78
|
+
for (let index = rows.length - 1; index >= 0; index -= 1) {
|
|
79
|
+
if (parseRowId(rows[index]!) === id) return index;
|
|
80
|
+
}
|
|
81
|
+
return -1;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The `id` of one JSONL row; blank and unparseable rows have none. */
|
|
85
|
+
function parseRowId(row: string): string | undefined {
|
|
86
|
+
if (row.trim() === "") return undefined;
|
|
87
|
+
try {
|
|
88
|
+
const parsed: unknown = JSON.parse(row);
|
|
89
|
+
if (typeof parsed !== "object" || parsed === null) return undefined;
|
|
90
|
+
const id = (parsed as { id?: unknown }).id;
|
|
91
|
+
return typeof id === "string" ? id : undefined;
|
|
92
|
+
} catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Replace `file` in one step; pi appends per entry and holds no descriptor, so a rename is safe. */
|
|
98
|
+
function writeAtomically(file: string, content: string): void {
|
|
99
|
+
const tmp = join(dirname(file), `.${basename(file)}.tmp`);
|
|
100
|
+
writeFileSync(tmp, content);
|
|
101
|
+
renameSync(tmp, file);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A thrown value's message, for a one-line notification. */
|
|
105
|
+
function errorMessage(error: unknown): string {
|
|
106
|
+
return error instanceof Error ? error.message : String(error);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Whether the host already replaced this command's session. Every `ctx` member
|
|
111
|
+
* is a getter that asserts the extension runner is still active, so reading one
|
|
112
|
+
* after a replacement throws.
|
|
113
|
+
*/
|
|
114
|
+
function isStale(ctx: ExtensionCommandContext): boolean {
|
|
115
|
+
try {
|
|
116
|
+
ctx.sessionManager.getSessionFile();
|
|
117
|
+
return false;
|
|
118
|
+
} catch {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Rewind the current session to just before its newest user message: cut the
|
|
125
|
+
* tail from the file, reload the session from it, and put the prompt back in
|
|
126
|
+
* the editor when the editor is empty.
|
|
127
|
+
*
|
|
128
|
+
* The cut happens before the reload because the reload reads the file, so a
|
|
129
|
+
* reload the host refuses has to put the original bytes back. Once the host has
|
|
130
|
+
* replaced the session the old context is stale and the file is what the new
|
|
131
|
+
* session already holds, so nothing is restored after that point.
|
|
132
|
+
*/
|
|
133
|
+
export async function runUndo(ctx: ExtensionCommandContext): Promise<void> {
|
|
134
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
135
|
+
ctx.ui.notify("Wait for the current response to finish before undoing", "warning");
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const file = ctx.sessionManager.getSessionFile();
|
|
139
|
+
if (file === undefined) {
|
|
140
|
+
ctx.ui.notify("This session has no saved file yet", "warning");
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const target = findUndoTarget(ctx.sessionManager);
|
|
144
|
+
if (target === undefined) {
|
|
145
|
+
ctx.ui.notify("No user message to undo", "warning");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const editorEmpty = ctx.ui.getEditorText().trim() === "";
|
|
149
|
+
const original = readFileSync(file, "utf8");
|
|
150
|
+
let removed = 0;
|
|
151
|
+
let swapped = false;
|
|
152
|
+
try {
|
|
153
|
+
removed = truncateSessionFile(file, target.parentId).removed;
|
|
154
|
+
} catch (error) {
|
|
155
|
+
ctx.ui.notify(`Undo failed: ${errorMessage(error)}`, "error");
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
const result = await ctx.switchSession(file, {
|
|
160
|
+
withSession: async (next) => {
|
|
161
|
+
swapped = true;
|
|
162
|
+
try {
|
|
163
|
+
if (editorEmpty) next.ui.setEditorText(target.text);
|
|
164
|
+
else next.ui.notify("Undo: editor kept as-is, prompt not restored", "warning");
|
|
165
|
+
next.ui.notify(`Undone: rewound before your last message (${removed} entries removed)`, "info");
|
|
166
|
+
} catch (error) {
|
|
167
|
+
next.ui.notify(`Undo failed: ${errorMessage(error)}`, "error");
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
if (result.cancelled && !swapped) {
|
|
172
|
+
writeAtomically(file, original);
|
|
173
|
+
ctx.ui.notify("Undo cancelled, session unchanged", "warning");
|
|
174
|
+
}
|
|
175
|
+
} catch (error) {
|
|
176
|
+
// A throw can arrive before the reload starts or after the host already
|
|
177
|
+
// swapped in the truncated session; only the first may put the old bytes
|
|
178
|
+
// back. After a swap this context is stale, and so is its notice.
|
|
179
|
+
if (swapped || isStale(ctx)) return;
|
|
180
|
+
writeAtomically(file, original);
|
|
181
|
+
ctx.ui.notify(`Undo failed: ${errorMessage(error)}`, "error");
|
|
182
|
+
}
|
|
183
|
+
}
|