@shelken/pi-command-history 0.1.3

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.
Files changed (4) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +30 -0
  3. package/index.ts +188 -0
  4. package/package.json +38 -0
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ross Z
4
+ Modifications Copyright (c) 2026 shelken
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # pi-command-history
2
+
3
+ 按工作目录持久化输入历史。同一目录下跨 session 可用 `shift+up` / `shift+down` 回填。
4
+
5
+ 初始 fork 自 [ross-jill-ws/pi-command-history](https://github.com/ross-jill-ws/pi-command-history)。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ pi install npm:@shelken/pi-command-history
11
+ ```
12
+
13
+ ## 快捷键
14
+
15
+ | 快捷键 | 作用 |
16
+ |---|---|
17
+ | `shift+up` | 更早的历史 |
18
+ | `shift+down` | 更新的历史 |
19
+
20
+ - 用户输入都会保存(含 `/` 命令)
21
+ - 去重:重复输入会移到最新
22
+ - 每个目录最多 500 条(`session_start`/`load` 时压缩)
23
+ - 文件:`~/.pi/folder-history/*.jsonl`(每行 `{ cwd, text }`,append 写入)
24
+ - 文件名把路径 `/` 换成 `-` 可能碰撞,靠行内 `cwd` 隔离
25
+
26
+ ## 验证
27
+
28
+ ```bash
29
+ bun --filter @shelken/pi-command-history test
30
+ ```
package/index.ts ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * 按工作目录持久化输入历史,shift+up/down 跨 session 回填。
3
+ * 存储:~/.pi/folder-history/<path-with-dashes>.jsonl
4
+ *
5
+ * 文件名把 `/` 换成 `-`,`/a-b` 与 `/a/b` 会撞同一文件;
6
+ * 因此每行必须带 cwd,读写都按 cwd 过滤。
7
+ *
8
+ * 写入用 append(并发更安全);超过上限时在 load 时压缩回写。
9
+ */
10
+
11
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import {
13
+ appendFileSync,
14
+ existsSync,
15
+ mkdirSync,
16
+ readFileSync,
17
+ renameSync,
18
+ writeFileSync,
19
+ } from "node:fs";
20
+ import { homedir } from "node:os";
21
+ import { join } from "node:path";
22
+
23
+ export const HISTORY_DIR = join(homedir(), ".pi", "folder-history");
24
+ export const MAX_HISTORY = 500;
25
+
26
+ interface HistoryRow {
27
+ cwd: string;
28
+ text: string;
29
+ }
30
+
31
+ function historyFile(cwd: string, historyDir: string): string {
32
+ return join(historyDir, `${cwd.replace(/\//g, "-")}.jsonl`);
33
+ }
34
+
35
+ function readRows(file: string): HistoryRow[] {
36
+ if (!existsSync(file)) return [];
37
+ try {
38
+ const rows: HistoryRow[] = [];
39
+ for (const line of readFileSync(file, "utf-8").split("\n")) {
40
+ if (!line.trim()) continue;
41
+ try {
42
+ const entry = JSON.parse(line) as { text?: string; cwd?: string };
43
+ if (!entry.text || !entry.cwd) continue;
44
+ rows.push({ cwd: entry.cwd, text: entry.text });
45
+ } catch {
46
+ // skip malformed lines
47
+ }
48
+ }
49
+ return rows;
50
+ } catch {
51
+ return [];
52
+ }
53
+ }
54
+
55
+ function uniqueTexts(texts: string[]): string[] {
56
+ const seen = new Map<string, number>();
57
+ texts.forEach((text, i) => seen.set(text, i));
58
+ return [...seen.entries()]
59
+ .sort((a, b) => a[1] - b[1])
60
+ .map(([text]) => text);
61
+ }
62
+
63
+ function writeRows(file: string, rows: HistoryRow[]): void {
64
+ const body =
65
+ rows.map((row) => JSON.stringify(row)).join("\n") + (rows.length > 0 ? "\n" : "");
66
+ const tmp = `${file}.${process.pid}.tmp`;
67
+ writeFileSync(tmp, body, "utf-8");
68
+ renameSync(tmp, file);
69
+ }
70
+
71
+ /** 压缩:各 cwd 只保留最近 MAX_HISTORY 条唯一记录。 */
72
+ function compactFile(file: string): void {
73
+ const rows = readRows(file);
74
+ const byCwd = new Map<string, string[]>();
75
+ for (const row of rows) {
76
+ const list = byCwd.get(row.cwd) ?? [];
77
+ list.push(row.text);
78
+ byCwd.set(row.cwd, list);
79
+ }
80
+
81
+ const compacted: HistoryRow[] = [];
82
+ for (const [cwd, texts] of byCwd) {
83
+ for (const text of uniqueTexts(texts).slice(-MAX_HISTORY)) {
84
+ compacted.push({ cwd, text });
85
+ }
86
+ }
87
+
88
+ // 只有确实变短才回写,避免无意义 IO
89
+ if (compacted.length < rows.length) {
90
+ writeRows(file, compacted);
91
+ }
92
+ }
93
+
94
+ export function loadHistory(cwd: string, historyDir = HISTORY_DIR): string[] {
95
+ const file = historyFile(cwd, historyDir);
96
+ const rows = readRows(file);
97
+ const oursRaw = rows.filter((r) => r.cwd === cwd).map((r) => r.text);
98
+ const unique = uniqueTexts(oursRaw);
99
+
100
+ // 文件膨胀时在 load 路径压缩(session_start 触发一次即可)
101
+ if (rows.length > MAX_HISTORY || unique.length > MAX_HISTORY) {
102
+ compactFile(file);
103
+ }
104
+
105
+ return unique.slice(-MAX_HISTORY);
106
+ }
107
+
108
+ /** append 新输入;截断在下次 load/compact 时完成。 */
109
+ export function appendHistory(
110
+ cwd: string,
111
+ text: string,
112
+ historyDir = HISTORY_DIR,
113
+ ): void {
114
+ mkdirSync(historyDir, { recursive: true });
115
+ const file = historyFile(cwd, historyDir);
116
+ appendFileSync(file, `${JSON.stringify({ cwd, text })}\n`, "utf-8");
117
+ }
118
+
119
+ export function pushUniqueHistory(history: string[], text: string): string[] {
120
+ const next = history.filter((item) => item !== text);
121
+ next.push(text);
122
+ if (next.length > MAX_HISTORY) {
123
+ return next.slice(-MAX_HISTORY);
124
+ }
125
+ return next;
126
+ }
127
+
128
+ export default function commandHistoryExtension(pi: ExtensionAPI): void {
129
+ let history: string[] = [];
130
+ let historyIndex = -1;
131
+ let savedEditorText = "";
132
+ let currentCwd = "";
133
+
134
+ const showPreviousCommand = (ctx: ExtensionContext) => {
135
+ if (history.length === 0) return;
136
+
137
+ if (historyIndex === -1) {
138
+ savedEditorText = ctx.ui.getEditorText();
139
+ }
140
+
141
+ const nextIndex = historyIndex + 1;
142
+ if (nextIndex >= history.length) return;
143
+
144
+ historyIndex = nextIndex;
145
+ ctx.ui.setEditorText(history[history.length - 1 - historyIndex]);
146
+ };
147
+
148
+ const showNextCommand = (ctx: ExtensionContext) => {
149
+ if (historyIndex <= -1) return;
150
+
151
+ historyIndex--;
152
+
153
+ if (historyIndex === -1) {
154
+ ctx.ui.setEditorText(savedEditorText);
155
+ } else {
156
+ ctx.ui.setEditorText(history[history.length - 1 - historyIndex]);
157
+ }
158
+ };
159
+
160
+ pi.on("session_start", (_event, ctx) => {
161
+ currentCwd = ctx.cwd;
162
+ history = loadHistory(currentCwd);
163
+ historyIndex = -1;
164
+ savedEditorText = "";
165
+ });
166
+
167
+ pi.on("input", (event, _ctx) => {
168
+ const text = event.text?.trim();
169
+ if (!text || !currentCwd) return;
170
+
171
+ appendHistory(currentCwd, text);
172
+ history = pushUniqueHistory(history, text);
173
+ historyIndex = -1;
174
+ savedEditorText = "";
175
+
176
+ return { action: "continue" as const };
177
+ });
178
+
179
+ pi.registerShortcut("shift+up", {
180
+ description: "Previous command from folder history",
181
+ handler: showPreviousCommand,
182
+ });
183
+
184
+ pi.registerShortcut("shift+down", {
185
+ description: "Next command from folder history",
186
+ handler: showNextCommand,
187
+ });
188
+ }
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@shelken/pi-command-history",
3
+ "version": "0.1.3",
4
+ "description": "按工作目录持久化输入历史,支持 shift+up/down 回填",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "files": [
8
+ "index.ts"
9
+ ],
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/shelken/pi-extensions.git",
13
+ "directory": "extensions/pi-command-history"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "scripts": {
19
+ "test": "vitest run"
20
+ },
21
+ "keywords": [
22
+ "pi-package",
23
+ "command-history"
24
+ ],
25
+ "pi": {
26
+ "extensions": [
27
+ "./index.ts"
28
+ ]
29
+ },
30
+ "peerDependencies": {
31
+ "@earendil-works/pi-coding-agent": "*"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "@earendil-works/pi-coding-agent": {
35
+ "optional": true
36
+ }
37
+ }
38
+ }