pi-kongdd 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.
package/README.md CHANGED
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # pi-kong
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 个人 Pi 扩展包,包含额度状态、剪贴板图片、上下文状态栏、VS Code 上下文、RTK 命令改写、简短回复和 token 速度统计。
4
+
5
+ ## 安装
6
+
7
+ 本地开发时先安装依赖,再注册包:
8
+
9
+ ```sh
10
+ cd /path/to/pi-kong
11
+ npm install --omit=peer
12
+ pi install /path/to/pi-kong
13
+ ```
14
+
15
+ 发布到 npm 后可使用 `pi install npm:@kongdd/pi-kong`。包内扩展默认全部启用,可通过 `pi config` 单独禁用。剪贴板图片保存在 Pi 配置目录的 `media/clipboard_image/` 下。
16
+
17
+ 运行 `npm test` 可检查包内容和额度状态栏;测试需要支持直接运行 TypeScript 的 Node.js(22.18 或更新版本)。
18
+
19
+ 额度状态需要另行安装并配置 `ai-quota`;RTK 扩展需要另行安装 `rtk`;VS Code 上下文扩展需要配套的「Pi Agent Context」插件。剪贴板图片预览依赖终端的图片协议支持。
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "pi-kongdd",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Personal extensions for Pi coding agent",
5
+ "type": "module",
6
+ "keywords": ["pi-package"],
7
+ "files": ["src/*.ts"],
8
+ "scripts": {
9
+ "test": "node --test"
10
+ },
11
+ "pi": {
12
+ "extensions": [
13
+ "./src/ai-quota-footer.ts",
14
+ "./src/clipimg.ts",
15
+ "./src/context-footer.ts",
16
+ "./src/pi-vscode-context.ts",
17
+ "./src/rtk.ts",
18
+ "./src/short.ts",
19
+ "./src/token-speed.ts"
20
+ ]
21
+ },
22
+ "dependencies": {
23
+ "@silvia-odwyer/photon-node": "0.3.4"
24
+ },
25
+ "peerDependencies": {
26
+ "@earendil-works/pi-coding-agent": "*",
27
+ "@earendil-works/pi-tui": "*"
28
+ }
29
+ }
@@ -0,0 +1,99 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ const STATUS = "ai-quota";
4
+ const PROVIDERS: Record<string, string> = {
5
+ openai: "openai",
6
+ "openai-codex": "openai",
7
+ xai: "grok",
8
+ grok: "grok",
9
+ "grok-cli": "grok",
10
+ "grok-build": "grok",
11
+ minimax: "minimax",
12
+ "minimax-cn": "minimax",
13
+ deepseek: "deepseek",
14
+ "deepseek-api": "deepseek",
15
+ "github-copilot": "github-copilot",
16
+ };
17
+
18
+ // Read the compact report, retaining ai-quota's exact ANSI colors and rounding.
19
+ // Join available windows as 5h%/wk%/mo%; single-pool providers show one percentage.
20
+ // Grok's first column is a weekly pool, not a five-hour window.
21
+ function quotaCell(report: string, provider: string): string | undefined {
22
+ let selected = false;
23
+ const cells: string[] = [];
24
+ let duration = "";
25
+ for (const line of report.split("\n")) {
26
+ const plain = line.replace(/\x1b\[[0-9;]*m/g, "");
27
+ if (plain && !/^\s/.test(plain)) {
28
+ if (cells.length) break;
29
+ const name = plain.replace(/\s*·\s*/g, "·").toLowerCase();
30
+ selected = provider === "openai"
31
+ ? name === "openai·apps"
32
+ : provider === "openai-codex"
33
+ ? /^codex(?:·|$)/.test(name)
34
+ : name.startsWith(provider === "github-copilot" ? "gh-copilot" : provider);
35
+ } else if (selected && provider === "deepseek" && /^\s+bal\s/.test(plain)) {
36
+ return line.replace(/^\s+bal\s+/, "").trim() || undefined;
37
+ } else if (selected && provider !== "deepseek" && /^\s+(?:5h|wk|mo)\s/.test(plain)) {
38
+ const match = line.match(/((?:\x1b\[[0-9;]*m)?\s*\d+%(?:\x1b\[[0-9;]*m)?)\s+(.+)$/);
39
+ if (!match) continue;
40
+ cells.push(match[1]!.replace(/ /g, ""));
41
+ if (!duration) {
42
+ duration = match[2]!.replace(/(\d+)d\s+(\d+)h\s+(\d+)m/, (time, days, hours, minutes) =>
43
+ Number(days) > 2 || (Number(days) === 2 && Number(hours) + Number(minutes) > 0)
44
+ ? `${days}d`
45
+ : time,
46
+ );
47
+ }
48
+ }
49
+ }
50
+ return cells.length ? `${cells.join("/")} ↻ ${duration}` : undefined;
51
+ }
52
+
53
+ export default function quotaFooter(pi: ExtensionAPI): void {
54
+ let pending: AbortController | undefined;
55
+
56
+ const clear = (ctx: ExtensionContext) => {
57
+ pending?.abort();
58
+ pending = undefined;
59
+ ctx.ui.setStatus(STATUS, undefined);
60
+ };
61
+
62
+ const refresh = async (ctx: ExtensionContext) => {
63
+ if (ctx.mode !== "tui") return;
64
+ clear(ctx);
65
+
66
+ const modelProvider = ctx.model?.provider ?? "";
67
+ const provider = PROVIDERS[modelProvider];
68
+ if (!provider) return;
69
+
70
+ const request = new AbortController();
71
+ pending = request;
72
+ let text = ctx.ui.theme.fg("dim", `${provider} n/a`);
73
+ try {
74
+ const args = ["FORCE_COLOR=1", "ai-quota", "-p", provider === "deepseek" ? "deepseek-api" : provider, "--compact"];
75
+ if (modelProvider === "minimax") args.push("--region", "intl");
76
+ const result = await pi.exec("env", args, {
77
+ cwd: ctx.cwd,
78
+ signal: request.signal,
79
+ timeout: 45_000,
80
+ });
81
+ const cell = result.code === 0 && !result.killed
82
+ ? quotaCell(result.stdout, modelProvider === "openai-codex" ? modelProvider : provider)
83
+ : undefined;
84
+ if (cell) text = `${provider} ${cell}`;
85
+ } catch {
86
+ // Missing CLI, credentials or network: no transcript noise or stale quota.
87
+ }
88
+ if (!request.signal.aborted && pending === request) {
89
+ ctx.ui.setStatus(STATUS, text);
90
+ pending = undefined;
91
+ }
92
+ };
93
+
94
+ // Query at startup, on model changes and after each settled conversation; no polling.
95
+ pi.on("agent_settled", (_event, ctx) => { void refresh(ctx); });
96
+ pi.on("session_start", (_event, ctx) => { void refresh(ctx); });
97
+ pi.on("model_select", (_event, ctx) => { void refresh(ctx); });
98
+ pi.on("session_shutdown", (_event, ctx) => clear(ctx));
99
+ }
package/src/clipimg.ts ADDED
@@ -0,0 +1,297 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import { join } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import {
8
+ getAgentDir,
9
+ type ExtensionAPI,
10
+ type ExtensionContext,
11
+ type Theme,
12
+ } from "@earendil-works/pi-coding-agent";
13
+ import {
14
+ allocateImageId,
15
+ Container,
16
+ getCapabilities,
17
+ getCellDimensions,
18
+ getNativeClipboard,
19
+ Image,
20
+ resetCapabilitiesCache,
21
+ Text,
22
+ truncateToWidth,
23
+ } from "@earendil-works/pi-tui";
24
+
25
+ const execFileAsync = promisify(execFile);
26
+ const MAX_PNG = 18 * 1024 * 1024;
27
+ const WIDGET_ID = "clipboard_image";
28
+ const THUMB_W = 20;
29
+ const THUMB_H = 6;
30
+ const GAP = 1;
31
+ const DIR = join(getAgentDir(), "media", "clipboard_image");
32
+ const require = createRequire(import.meta.url);
33
+
34
+ type Shot = { path: string; kb: number };
35
+ type Details = { files?: Shot[] };
36
+
37
+ /** 横排合成一张 PNG,避免同一行多张 Kitty 图片无法被 pi 完整追踪。 */
38
+ function thumbnailStrip(files: Shot[], columns: number) {
39
+ const { PhotonImage, resize, watermark, SamplingFilter } = require("@silvia-odwyer/photon-node");
40
+ const cell = getCellDimensions();
41
+ const height = THUMB_H * cell.heightPx;
42
+ const allocated = [];
43
+ const thumbs = [];
44
+ let used = 0;
45
+ let labels = "";
46
+ try {
47
+ for (const [i, file] of files.entries()) {
48
+ const label = `[${i + 1}] ${file.kb} KB`;
49
+ const x = used + (i ? GAP : 0);
50
+ if (x + Math.min(columns, label.length) > columns) break;
51
+ const data = loadPng(file.path);
52
+ if (!data) throw new Error(`第 ${i + 1} 张图片无法读取`);
53
+ const source = PhotonImage.new_from_base64(data);
54
+ allocated.push(source);
55
+ const scale = Math.min(
56
+ (Math.min(THUMB_W, columns) * cell.widthPx) / source.get_width(),
57
+ height / source.get_height(),
58
+ );
59
+ const width = Math.max(1, Math.round(source.get_width() * scale));
60
+ // 按实际图宽排版,只为标签保留必要空间。
61
+ const slot = Math.min(columns, Math.max(Math.ceil(width / cell.widthPx), label.length));
62
+ if (x + slot > columns) break;
63
+ const image = resize(
64
+ source, width, Math.max(1, Math.round(source.get_height() * scale)),
65
+ SamplingFilter.Lanczos3,
66
+ );
67
+ allocated.push(image);
68
+ thumbs.push({ image, x });
69
+ labels = labels.padEnd(x) + label;
70
+ used = x + slot;
71
+ }
72
+ const width = used * cell.widthPx;
73
+ const sheet = new PhotonImage(new Uint8Array(width * height * 4), width, height);
74
+ allocated.push(sheet);
75
+ for (const { image, x } of thumbs) {
76
+ watermark(sheet, image, BigInt(x * cell.widthPx), 0n);
77
+ }
78
+ return {
79
+ data: Buffer.from(sheet.get_bytes()).toString("base64"),
80
+ labels,
81
+ count: thumbs.length,
82
+ };
83
+ } finally {
84
+ for (const image of allocated) image.free();
85
+ }
86
+ }
87
+
88
+ /** 一个图片块占六行,标签独占一行;占位行不能套 Box 填充背景。 */
89
+ class Thumbnails {
90
+ private imageId = allocateImageId();
91
+ private cache?: { width: number; protocol: string | null; lines: string[] };
92
+
93
+ constructor(private images: Shot[], private theme: Theme) {}
94
+
95
+ invalidate() {
96
+ this.cache = undefined;
97
+ }
98
+
99
+ render(width: number): string[] {
100
+ const protocol = getCapabilities().images;
101
+ if (this.cache?.width === width && this.cache.protocol === protocol) return this.cache.lines;
102
+ let lines: string[] = [];
103
+ let footer = `[${this.images.length} 张图片]`;
104
+ try {
105
+ if (protocol) {
106
+ const columns = Math.max(1, width - 2);
107
+ const strip = thumbnailStrip(this.images, columns);
108
+ const image = new Image(
109
+ strip.data,
110
+ "image/png",
111
+ { fallbackColor: (s) => this.theme.fg("muted", s) },
112
+ { maxWidthCells: columns, maxHeightCells: THUMB_H, imageId: this.imageId },
113
+ );
114
+ const hidden = this.images.length - strip.count;
115
+ const suffix = hidden ? ` +${hidden}` : "";
116
+ footer = truncateToWidth(strip.labels, Math.max(0, width - suffix.length), "") + suffix;
117
+ lines = [...image.render(width)];
118
+ }
119
+ } catch (error) {
120
+ footer = `图片无法预览:${error instanceof Error ? error.message : error}`;
121
+ }
122
+ // 终端间距以整行为单位,隔开大小标签与正文或输入框。
123
+ lines.push(this.theme.fg("muted", truncateToWidth(footer, width)), "");
124
+ this.cache = { width, protocol, lines };
125
+ return lines;
126
+ }
127
+ }
128
+
129
+ /** 管理待发送图片。 */
130
+ export default function clipboard_image(pi: ExtensionAPI) {
131
+ // 必须在 TUI 启动前确定协议;渲染时才开启会导致全屏模式不清理图片。
132
+ // 环境变量仅补充 Herdr 默认值,仍由 terminal.images 设置及显式环境变量覆盖。
133
+ if (process.env.TERM_PROGRAM?.toLowerCase() === "herdr" && !process.env.PI_IMAGE_PROTOCOL) {
134
+ process.env.PI_IMAGE_PROTOCOL = "kitty";
135
+ resetCapabilitiesCache();
136
+ }
137
+ let pending: Shot[] = [];
138
+
139
+ pi.registerShortcut(process.platform === "darwin" ? "ctrl+v" : "alt+v", {
140
+ description: "Paste clipboard text or attach an image",
141
+ handler: async (ctx) => {
142
+ const clipboard = getNativeClipboard();
143
+ // Finder 的文本表示可能带 Shell 引号,优先读取原始文件路径。
144
+ const paths = await clipboard?.getFilePaths?.().catch(() => undefined);
145
+ const text = paths?.length ? paths.join("\n") : await clipboard?.getText().catch(() => undefined);
146
+ if (text) ctx.ui.pasteToEditor(text);
147
+ else await handleCommand("", ctx);
148
+ },
149
+ });
150
+
151
+ pi.registerMessageRenderer(WIDGET_ID, (message, { outputPad }, theme) => {
152
+ const container = new Container();
153
+ const files = (message.details as Details | undefined)?.files ?? [];
154
+ if (files.length) container.addChild(new Thumbnails(files, theme));
155
+ const text = typeof message.content === "string"
156
+ ? message.content
157
+ : message.content.filter((p) => p.type === "text").map((p) => p.text).join("\n");
158
+ if (text) {
159
+ container.addChild(new Text(
160
+ theme.fg("userMessageText", text), outputPad, 0,
161
+ (t) => theme.bg("userMessageBg", t),
162
+ ));
163
+ }
164
+ return container;
165
+ });
166
+
167
+ // 剪贴板图片只保存路径;仅在构造模型上下文时读取为图片数据。
168
+ pi.on("context", (event) => ({
169
+ messages: event.messages.map((m) => {
170
+ if (m.role !== "custom" || m.customType !== WIDGET_ID) return m;
171
+ const files = (m.details as Details | undefined)?.files;
172
+ if (!files?.length) return m;
173
+ const images = files.flatMap((f) => {
174
+ const data = loadPng(f.path);
175
+ return data ? [{ type: "image" as const, data, mimeType: "image/png" }] : [];
176
+ });
177
+ const content = typeof m.content === "string"
178
+ ? (m.content ? [{ type: "text" as const, text: m.content }] : [])
179
+ : m.content;
180
+ return { ...m, content: [...content, ...images] };
181
+ }),
182
+ }));
183
+
184
+ function update(ctx: ExtensionContext) {
185
+ const images = [...pending];
186
+ ctx.ui.setWidget(
187
+ WIDGET_ID,
188
+ images.length ? (_tui, theme) => new Thumbnails(images, theme) : undefined,
189
+ );
190
+ }
191
+
192
+ async function handleCommand(args: string, ctx: ExtensionContext) {
193
+ const data = args.trim();
194
+ try {
195
+ let message: string;
196
+ if (!data) {
197
+ const started = performance.now();
198
+ ctx.ui.notify("saving...", "info");
199
+ pending.push(await captureClipboard());
200
+ message = `saving used ${((performance.now() - started) / 1000).toFixed(2)}s`;
201
+ } else {
202
+ if (!/^clear(?:\s|$)/.test(data)) throw new Error("参数无效");
203
+ const spec = data.slice(5).trim();
204
+ if (!spec) {
205
+ message = pending.length ? `已清空 ${pending.length} 张待发送图片` : "没有待发送图片";
206
+ pending = [];
207
+ } else {
208
+ const selected = new Set(spec.split(",").flatMap((part) => {
209
+ if (!/^\d+(?:\s*-\s*\d+)?$/.test(part.trim())) throw new Error("序号格式无效");
210
+ const [start, end = start] = part.split("-").map(Number);
211
+ if (end < start) throw new Error("序号范围无效");
212
+ // 越界范围只检查端点,避免展开巨大的无效范围。
213
+ if (start < 1 || end > pending.length) return [start, end];
214
+ return Array.from({ length: end - start + 1 }, (_, i) => start + i);
215
+ }));
216
+ const indices = [...selected].sort((a, b) => a - b);
217
+ const invalid = indices.filter((i) => i < 1 || i > pending.length);
218
+ if (invalid.length) throw new Error(`序号无效:${invalid.join(",")}`);
219
+ pending = pending.filter((_, i) => !selected.has(i + 1));
220
+ message = `已删除第 ${indices.join(",")} 张图片`;
221
+ }
222
+ }
223
+ update(ctx);
224
+ ctx.ui.notify(message, "info");
225
+ } catch (error) {
226
+ ctx.ui.notify(`clipboard_image:${error instanceof Error ? error.message : error}`, "error");
227
+ }
228
+ }
229
+
230
+ pi.registerCommand("clipboard_image", {
231
+ description: "Attach the clipboard image; clear [1,3-5,...] removes pending images",
232
+ handler: handleCommand,
233
+ });
234
+
235
+ pi.on("input", (event, ctx) => {
236
+ if (event.source !== "interactive" || pending.length === 0) return { action: "continue" };
237
+ const files = pending;
238
+ pending = [];
239
+ update(ctx);
240
+ pi.sendMessage(
241
+ {
242
+ customType: WIDGET_ID,
243
+ content: event.images?.length
244
+ ? [{ type: "text", text: event.text }, ...event.images]
245
+ : event.text,
246
+ display: true,
247
+ details: { files },
248
+ },
249
+ { triggerTurn: true },
250
+ );
251
+ return { action: "handled" };
252
+ });
253
+ }
254
+
255
+ async function captureClipboard(): Promise<Shot> {
256
+ // 仅显式配置主机时读取 Windows 剪贴板,避免继承 SSH_CONNECTION 导致误判。
257
+ const host = process.env.WIN_SSH_HOST?.trim() ?? "";
258
+ const remote = Boolean(host);
259
+
260
+ mkdirSync(DIR, { recursive: true });
261
+ const path = join(DIR, `${randomUUID()}.png`);
262
+ const command = remote ? "ssh" : process.platform === "win32" ? "clipboard-image.exe" : "clipboard-image";
263
+ const args = remote
264
+ ? [
265
+ "-o", "BatchMode=yes",
266
+ "-o", "ConnectTimeout=3",
267
+ "-o", "ControlMaster=auto",
268
+ "-o", "ControlPersist=10m",
269
+ "-o", `ControlPath=${process.env.HOME}/.ssh/cm-%C`,
270
+ host,
271
+ `"%USERPROFILE%\\.win-launch.exe" --clipboard`,
272
+ ]
273
+ : ["--output", path];
274
+ const { stdout } = await execFileAsync(command, args, {
275
+ encoding: null,
276
+ maxBuffer: MAX_PNG,
277
+ timeout: 10_000,
278
+ });
279
+ if (remote) {
280
+ if (!isPng(stdout)) throw new Error("图片数据无效");
281
+ writeFileSync(path, stdout);
282
+ }
283
+ return { path, kb: Math.floor(statSync(path).size / 1024) };
284
+ }
285
+
286
+ function loadPng(path: string) {
287
+ try {
288
+ const png = readFileSync(path);
289
+ return isPng(png) ? png.toString("base64") : undefined;
290
+ } catch {
291
+ return;
292
+ }
293
+ }
294
+
295
+ function isPng(data: Buffer) {
296
+ return data.length <= MAX_PNG && data.subarray(0, 8).toString("hex") === "89504e470d0a1a0a";
297
+ }
@@ -0,0 +1,125 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+
5
+ // Inlined from pi-coding-agent's FooterComponent (v0.80.6) to avoid a
6
+ // forbidden deep import — the package's `exports` field does not expose
7
+ // `dist/modes/interactive/components/footer.js`.
8
+ function formatTokens(count: number): string {
9
+ if (count < 1000) return count.toString();
10
+ if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
11
+ if (count < 1000000) return `${Math.round(count / 1000)}k`;
12
+ if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;
13
+ return `${Math.round(count / 1000000)}M`;
14
+ }
15
+
16
+ function formatCwdForFooter(cwd: string, home: string | undefined): string {
17
+ if (!home) return cwd;
18
+ const resolvedCwd = resolve(cwd);
19
+ const resolvedHome = resolve(home);
20
+ const relativeToHome = relative(resolvedHome, resolvedCwd);
21
+ const isInsideHome =
22
+ relativeToHome === "" ||
23
+ (relativeToHome !== ".." &&
24
+ !relativeToHome.startsWith(`..${sep}`) &&
25
+ !isAbsolute(relativeToHome));
26
+ if (!isInsideHome) return cwd;
27
+ return relativeToHome === "" ? "~" : `~${sep}${relativeToHome}`;
28
+ }
29
+
30
+ export default function contextFooter(pi: ExtensionAPI): void {
31
+ pi.on("session_start", (_event, ctx) => {
32
+ if (ctx.mode !== "tui") return;
33
+
34
+ ctx.ui.setFooter((tui, theme, footer) => {
35
+ const dispose = footer.onBranchChange(() => tui.requestRender());
36
+
37
+ return {
38
+ dispose,
39
+ invalidate() {},
40
+ render(width: number): string[] {
41
+ let input = 0;
42
+ let output = 0;
43
+ let read = 0;
44
+ let write = 0;
45
+ let cost = 0;
46
+ let cacheHit: number | undefined;
47
+
48
+ for (const entry of ctx.sessionManager.getEntries()) {
49
+ if (entry.type !== "message" || entry.message.role !== "assistant") continue;
50
+ const usage = entry.message.usage;
51
+ input += usage.input;
52
+ output += usage.output;
53
+ read += usage.cacheRead;
54
+ write += usage.cacheWrite;
55
+ cost += usage.cost.total;
56
+ const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
57
+ cacheHit = prompt ? usage.cacheRead / prompt * 100 : undefined;
58
+ }
59
+
60
+ const stats = [
61
+ input && `↑${formatTokens(input)}`,
62
+ output && `↓${formatTokens(output)}`,
63
+ read && `R${formatTokens(read)}`,
64
+ write && `W${formatTokens(write)}`,
65
+ (read || write) && cacheHit !== undefined && `CH${cacheHit.toFixed(1)}%`,
66
+ ].filter(Boolean);
67
+
68
+ const subscription = ctx.model
69
+ ? ctx.modelRegistry.isUsingOAuth(ctx.model)
70
+ : false;
71
+ if (cost || subscription) {
72
+ stats.push(`$${cost.toFixed(3)}${subscription ? " (sub)" : ""}`);
73
+ }
74
+
75
+ const usage = ctx.getContextUsage();
76
+ const used = usage?.tokens == null ? "?" : formatTokens(usage.tokens);
77
+ const limit = formatTokens(usage?.contextWindow ?? ctx.model?.contextWindow ?? 0);
78
+ const context = `${used}/${limit}`;
79
+ const contextColor = (usage?.percent ?? 0) > 90
80
+ ? "error"
81
+ : (usage?.percent ?? 0) > 70 ? "warning" : "dim";
82
+ let left = theme.fg("dim", stats.join(" "));
83
+ if (stats.length) left += " ";
84
+ left += theme.fg(contextColor, context);
85
+
86
+ const statuses = footer.getExtensionStatuses();
87
+ const isAuto = ctx.model?.provider === "jev" && ctx.model.id === "auto-model";
88
+ const model = ctx.model?.id ?? "no-model";
89
+ const thinking = pi.getThinkingLevel();
90
+ let right = ctx.model?.reasoning
91
+ ? `${model} • ${thinking === "off" ? "thinking off" : thinking}`
92
+ : model;
93
+ if (isAuto) {
94
+ right = statuses.get("auto-model") ?? "auto-model: 待路由";
95
+ } else if (footer.getAvailableProviderCount() > 1 && ctx.model) {
96
+ right = `(${ctx.model.provider}) ${right}`;
97
+ }
98
+
99
+ if (visibleWidth(left) > width) left = truncateToWidth(left, width, "...");
100
+ const room = width - visibleWidth(left) - 2;
101
+ right = room > 0 ? truncateToWidth(right, room, "") : "";
102
+ const gap = " ".repeat(Math.max(0, width - visibleWidth(left) - visibleWidth(right)));
103
+
104
+ let cwd = formatCwdForFooter(ctx.cwd, process.env.HOME || process.env.USERPROFILE);
105
+ const branch = footer.getGitBranch();
106
+ if (branch) cwd += ` (${branch})`;
107
+ const name = ctx.sessionManager.getSessionName();
108
+ if (name) cwd += ` • ${name}`;
109
+
110
+ const lines = [
111
+ truncateToWidth(theme.fg("dim", cwd), width, theme.fg("dim", "...")),
112
+ left + theme.fg("dim", gap + right),
113
+ ];
114
+ const extraStatuses = [...statuses]
115
+ .filter(([key]) => key !== "auto-model")
116
+ .sort(([a], [b]) => a.localeCompare(b))
117
+ .map(([, text]) => text.replace(/\s+/g, " ").trim());
118
+ if (extraStatuses.length) lines.push(truncateToWidth(extraStatuses.join(" "), width));
119
+
120
+ return lines;
121
+ },
122
+ };
123
+ });
124
+ });
125
+ }
@@ -0,0 +1,324 @@
1
+ // Pi companion extension for "VSCode Pi Agent Bridge".
2
+ //
3
+ // Included in the pi-kong package.
4
+ //
5
+ // Talks to the VSCode extension over a loopback socket. VSCode owns the server
6
+ // and exports its port via PI_VSCODE_PORT into the terminal env; we dial it.
7
+ //
8
+ // What it does:
9
+ // - Auto-injects your ACTIVE FILE + SELECTED LINES into every message you send,
10
+ // as hidden metadata (deduped). Open-files list is left to the pull tool to
11
+ // keep turns small.
12
+ // - Shows a live footer status of what's selected in the TUI.
13
+ // - Receives `Cmd+Alt+K` mentions from VSCode into the prompt box.
14
+ // - `/vscode-auto [on|off]` toggles auto-injection.
15
+ // - `/vscode` and the `vscode_context` tool pull the FULL context on demand.
16
+ // - `open_in_editor` asks VSCode to open + highlight a line range.
17
+
18
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
19
+ import * as path from "path";
20
+ import * as net from "net";
21
+ import * as crypto from "crypto";
22
+
23
+ const STATUS_KEY = "vscode";
24
+ const PORT_ENV = "PI_VSCODE_PORT";
25
+
26
+ interface Selection {
27
+ startLine: number;
28
+ endLine: number;
29
+ text: string;
30
+ truncated: boolean;
31
+ }
32
+ interface OpenFile {
33
+ path: string;
34
+ active: boolean;
35
+ languageId?: string;
36
+ dirty: boolean;
37
+ }
38
+ interface Ctx {
39
+ activeFile: string | null;
40
+ openFiles: OpenFile[];
41
+ selection: { path: string; languageId: string; cursorLine: number; selections: Selection[] } | null;
42
+ }
43
+
44
+ // Short one-liner for the TUI footer: "vscode: extension.ts L120-148"
45
+ function statusLine(data: Ctx): string {
46
+ const sel = data.selection;
47
+ if (sel && sel.selections.length > 0) {
48
+ const file = path.basename(sel.path);
49
+ const ranges = sel.selections
50
+ .map((s) => (s.startLine === s.endLine ? `L${s.startLine}` : `L${s.startLine}-${s.endLine}`))
51
+ .join(", ");
52
+ return `vscode: ${file} ${ranges}`;
53
+ }
54
+ if (data.activeFile) {
55
+ return `vscode: ${path.basename(data.activeFile)} (no selection)`;
56
+ }
57
+ return "vscode: no file";
58
+ }
59
+
60
+ // Widget factory: renders a single line flush-left (no leading padding, unlike
61
+ // the string-array form of setWidget which prefixes each line with a space).
62
+ function lineWidget(text: string) {
63
+ return () => ({
64
+ render: () => [text],
65
+ invalidate: () => {},
66
+ });
67
+ }
68
+
69
+ // Full markdown view of the editor state (for the pull tool + /vscode command).
70
+ function renderMarkdown(data: Ctx): string {
71
+ const lines: string[] = ["# VSCode editor context", ""];
72
+
73
+ lines.push("## Active file");
74
+ lines.push(data.activeFile ? `\`${data.activeFile}\`` : "_none_");
75
+ lines.push("");
76
+
77
+ lines.push("## Open files");
78
+ if (!data.openFiles.length) {
79
+ lines.push("_none_");
80
+ } else {
81
+ for (const f of data.openFiles) {
82
+ const marks = [f.active ? "active" : null, f.dirty ? "unsaved" : null].filter(Boolean).join(", ");
83
+ lines.push(`- \`${f.path}\`${marks ? ` (${marks})` : ""}`);
84
+ }
85
+ }
86
+ lines.push("");
87
+
88
+ lines.push("## Selection");
89
+ const sel = data.selection;
90
+ if (!sel || sel.selections.length === 0) {
91
+ const cur = sel ? ` (cursor at line ${sel.cursorLine})` : "";
92
+ lines.push(`_no selection_${cur}`);
93
+ } else {
94
+ for (const s of sel.selections) {
95
+ lines.push(`\`${sel.path}\` lines ${s.startLine}-${s.endLine}${s.truncated ? " (truncated)" : ""}:`);
96
+ lines.push("");
97
+ lines.push("```" + sel.languageId);
98
+ lines.push(s.text);
99
+ lines.push("```");
100
+ lines.push("");
101
+ }
102
+ }
103
+ return lines.join("\n") + "\n";
104
+ }
105
+
106
+ // ---- Live socket link to the VSCode extension (server) ----------------------
107
+ // VSCode owns the server and exports its port via PI_VSCODE_PORT. We dial it,
108
+ // receive `context` pushes (drive footer + injection + tools), receive `inject`
109
+ // (drop a mention into the prompt), and send `open` requests.
110
+ interface LiveLink {
111
+ latest: Ctx | null;
112
+ send: (msg: { type: "open"; path: string; line?: number; endLine?: number; column?: number }) => boolean;
113
+ connected: () => boolean;
114
+ }
115
+
116
+ function connectVscode(handlers: {
117
+ onContext: (data: Ctx) => void;
118
+ onInject: (text: string) => void;
119
+ }): LiveLink | null {
120
+ const port = Number(process.env[PORT_ENV]);
121
+ if (!port) return null;
122
+
123
+ const link: LiveLink = { latest: null, send: () => false, connected: () => false };
124
+ let socket: net.Socket | undefined;
125
+ let buffer = "";
126
+ let stopped = false;
127
+
128
+ const dial = () => {
129
+ if (stopped) return;
130
+ socket = net.connect(port, "127.0.0.1");
131
+ socket.setEncoding("utf8");
132
+ link.send = (msg) => {
133
+ if (socket && socket.writable) return socket.write(JSON.stringify(msg) + "\n");
134
+ return false;
135
+ };
136
+ link.connected = () => !!socket && !socket.destroyed && socket.writable;
137
+ socket.on("data", (chunk: string) => {
138
+ buffer += chunk;
139
+ let idx: number;
140
+ while ((idx = buffer.indexOf("\n")) >= 0) {
141
+ const line = buffer.slice(0, idx);
142
+ buffer = buffer.slice(idx + 1);
143
+ if (!line.trim()) continue;
144
+ try {
145
+ const msg = JSON.parse(line);
146
+ if (msg.type === "context") {
147
+ link.latest = msg.data as Ctx;
148
+ handlers.onContext(msg.data as Ctx);
149
+ } else if (msg.type === "inject") {
150
+ handlers.onInject(msg.text as string);
151
+ }
152
+ } catch {
153
+ // ignore malformed line
154
+ }
155
+ }
156
+ });
157
+ const retry = () => {
158
+ socket = undefined;
159
+ buffer = "";
160
+ if (!stopped) setTimeout(dial, 1000);
161
+ };
162
+ socket.on("close", retry);
163
+ socket.on("error", () => socket?.destroy());
164
+ };
165
+ dial();
166
+
167
+ // Best-effort teardown when the process exits.
168
+ process.on("exit", () => { stopped = true; socket?.destroy(); });
169
+ return link;
170
+ }
171
+
172
+ export default function (pi: ExtensionAPI) {
173
+ let lastInjectedHash = "";
174
+ let link: LiveLink | null = null;
175
+ const NO_LINK = "Not connected to VSCode. Run pi in a VSCode integrated terminal.";
176
+
177
+ // ---- Live footer status + socket link ----
178
+ pi.on("session_start", async (_event, ctx) => {
179
+ if (!ctx.hasUI) return;
180
+
181
+ link = connectVscode({
182
+ onContext: (data) => {
183
+ const status = statusLine(data);
184
+ const selected = data.selection?.selections.length;
185
+ const text = selected ? ctx.ui.theme.fg("accent", status) : status;
186
+ ctx.ui.setWidget(STATUS_KEY, lineWidget(text), { placement: "aboveEditor" });
187
+ },
188
+ onInject: (text) => {
189
+ // setEditorText replaces the buffer; append to preserve any draft.
190
+ const existing = ctx.ui.getEditorText?.() ?? "";
191
+ const next = existing ? `${existing} ${text}` : text;
192
+ ctx.ui.setEditorText(next);
193
+ },
194
+ });
195
+
196
+ // Only show a placeholder when we're actually inside VSCode (link != null).
197
+ // Outside VSCode (no PI_VSCODE_PORT) we stay silent entirely.
198
+ if (link) ctx.ui.setWidget(STATUS_KEY, lineWidget("vscode: connecting…"), { placement: "aboveEditor" });
199
+
200
+ });
201
+
202
+ let autoInject = true;
203
+
204
+ // Build a compact, selection-focused payload. Null when nothing worth sending.
205
+ const buildInjection = (data: Ctx): string | null => {
206
+ const sel = data.selection;
207
+ if (sel && sel.selections.length > 0) {
208
+ const parts: string[] = [];
209
+ parts.push(`User is in \`${sel.path}\` (cursor line ${sel.cursorLine}).`);
210
+ for (const s of sel.selections) {
211
+ const range = s.startLine === s.endLine ? `line ${s.startLine}` : `lines ${s.startLine}-${s.endLine}`;
212
+ parts.push(`Selected ${range}${s.truncated ? " (truncated)" : ""}:`);
213
+ parts.push("```" + sel.languageId);
214
+ parts.push(s.text);
215
+ parts.push("```");
216
+ }
217
+ parts.push("(Full open-file list available via the vscode_context tool.)");
218
+ return parts.join("\n");
219
+ }
220
+ if (data.activeFile) {
221
+ return `User is focused on \`${data.activeFile}\` (no selection). Use the vscode_context tool for open files.`;
222
+ }
223
+ return null;
224
+ };
225
+
226
+ // ---- Smart auto-injection: attach active file + selection to each turn ----
227
+ pi.on("before_agent_start", async (_event, _ctx) => {
228
+ if (!autoInject) return;
229
+ const data = link?.latest;
230
+ if (!data) return;
231
+ const payload = buildInjection(data);
232
+ if (!payload) return;
233
+
234
+ // Dedupe: skip if identical to what we injected last turn (saves tokens;
235
+ // the model still has the previous copy in context).
236
+ const hash = crypto.createHash("sha1").update(payload).digest("hex");
237
+ if (hash === lastInjectedHash) return;
238
+ lastInjectedHash = hash;
239
+
240
+ return {
241
+ message: {
242
+ customType: "vscode-context",
243
+ content: `Current VSCode editor state (auto-attached):\n\n${payload}`,
244
+ display: false,
245
+ },
246
+ };
247
+ });
248
+
249
+ // ---- Toggle auto-injection ----
250
+ pi.registerCommand("vscode-auto", {
251
+ description: "Toggle auto-injection of VSCode context (on|off)",
252
+ handler: async (args, ctx) => {
253
+ const a = (args || "").trim().toLowerCase();
254
+ autoInject = a === "on" ? true : a === "off" ? false : !autoInject;
255
+ lastInjectedHash = "";
256
+ ctx.ui.notify(`VSCode auto-inject ${autoInject ? "on" : "off"}`, "info");
257
+ },
258
+ });
259
+
260
+ // ---- Open a file in VSCode at a specific line/range ----
261
+ pi.registerTool({
262
+ name: "open_in_editor",
263
+ label: "Open in VSCode",
264
+ description:
265
+ "Open a file in the user's VSCode window and put the cursor on a line. " +
266
+ "Use when you want to show the user a specific location in a file.",
267
+ parameters: {
268
+ type: "object",
269
+ properties: {
270
+ path: { type: "string", description: "File path (absolute, or relative to the project root)" },
271
+ line: { type: "number", description: "1-based line number to jump to (optional)" },
272
+ endLine: { type: "number", description: "1-based end line to select through (optional)" },
273
+ column: { type: "number", description: "1-based column (optional)" },
274
+ },
275
+ required: ["path"],
276
+ } as never,
277
+ async execute(_id: unknown, params: { path: string; line?: number; endLine?: number; column?: number }) {
278
+ const where = params.line ? `${params.path}:${params.line}` : params.path;
279
+ const sent = link?.connected() && link.send({
280
+ type: "open",
281
+ path: params.path,
282
+ line: params.line,
283
+ endLine: params.endLine,
284
+ column: params.column,
285
+ });
286
+ return {
287
+ content: [{ type: "text", text: sent ? `Opened ${where} in VSCode.` : NO_LINK }],
288
+ details: { via: "socket", sent: !!sent },
289
+ };
290
+ },
291
+ });
292
+
293
+ // ---- On-demand tool the agent can call itself ----
294
+ pi.registerTool({
295
+ name: "vscode_context",
296
+ label: "VSCode context",
297
+ description:
298
+ "Read the user's current VSCode editor state: active file, open files, " +
299
+ "and selected lines of code. Use this to know what the user is looking at.",
300
+ parameters: { type: "object", properties: {} } as never,
301
+ async execute() {
302
+ const data = link?.latest;
303
+ if (!data) return { content: [{ type: "text", text: NO_LINK }], details: {} };
304
+ return { content: [{ type: "text", text: renderMarkdown(data) }], details: {} };
305
+ },
306
+ });
307
+
308
+ // ---- Manual command to inject context on demand ----
309
+ pi.registerCommand("vscode", {
310
+ description: "Inject current VSCode editor context (open files + selection)",
311
+ handler: async (_args, ctx) => {
312
+ const data = link?.latest;
313
+ if (!data) {
314
+ ctx.ui.notify(NO_LINK, "warning");
315
+ return;
316
+ }
317
+ await pi.sendMessage({
318
+ customType: "vscode-context",
319
+ content: `Here is my current VSCode editor context:\n\n${renderMarkdown(data)}`,
320
+ display: true,
321
+ });
322
+ },
323
+ });
324
+ }
package/src/rtk.ts ADDED
@@ -0,0 +1,80 @@
1
+ // RTK Pi extension — rewrites bash commands to use rtk for token savings.
2
+ // Requires: rtk >= 0.23.0 in PATH.
3
+ //
4
+ // This is a thin delegating extension: all rewrite logic lives in `rtk rewrite`,
5
+ // which is the single source of truth (src/discover/registry.rs).
6
+ // To add or change rewrite rules, edit the Rust registry — not this file.
7
+ //
8
+ // Exit code contract for `rtk rewrite`:
9
+ // 0 + stdout Rewrite found → mutate command
10
+ // 1 No RTK equivalent → pass through unchanged
11
+ // 3 + stdout Rewrite (advisory) → mutate command
12
+
13
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"
14
+ import { isToolCallEventType } from "@earendil-works/pi-coding-agent"
15
+
16
+ const REWRITE_TIMEOUT_MS = 2_000
17
+ const MIN_SUPPORTED_RTK_MINOR = 23
18
+
19
+ // Parse "X.Y.Z" semver, return [major, minor, patch] or null.
20
+ function parseSemver(raw: string): [number, number, number] | null {
21
+ const m = raw.trim().match(/(\d+)\.(\d+)\.(\d+)/)
22
+ if (!m) return null
23
+ return [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)]
24
+ }
25
+
26
+ // Calls `rtk rewrite`; returns the rewritten command or null (pass through).
27
+ async function rewriteCommand(
28
+ pi: ExtensionAPI,
29
+ cmd: string,
30
+ signal?: AbortSignal
31
+ ): Promise<string | null> {
32
+ const result = await pi.exec("rtk", ["rewrite", cmd], {
33
+ timeout: REWRITE_TIMEOUT_MS,
34
+ signal,
35
+ })
36
+ if (result.killed) return null
37
+ if (result.code !== 0 && result.code !== 3) return null
38
+ return result.stdout.trim() || null
39
+ }
40
+
41
+ export default async function (pi: ExtensionAPI) {
42
+ // Probe rtk version at load time; disables extension if missing or too old.
43
+ const ver = await pi.exec("rtk", ["--version"], { timeout: REWRITE_TIMEOUT_MS })
44
+ if (ver.code !== 0) {
45
+ console.warn("[rtk] rtk binary not found in PATH — extension disabled")
46
+ return
47
+ }
48
+
49
+ // Warn and bail if rtk predates 0.23.0 (when `rtk rewrite` was introduced).
50
+ const parsed = parseSemver(ver.stdout.replace(/^rtk\s+/, ""))
51
+ if (parsed) {
52
+ const [major, minor] = parsed
53
+ if (major === 0 && minor < MIN_SUPPORTED_RTK_MINOR) {
54
+ console.warn(`[rtk] rtk ${ver.stdout.trim()} is too old (need >= 0.23.0) — extension disabled`)
55
+ return
56
+ }
57
+ }
58
+
59
+ pi.on("tool_call", async (event, ctx) => {
60
+ try {
61
+ if (!isToolCallEventType("bash", event)) return
62
+
63
+ const cmd = event.input.command
64
+ if (typeof cmd !== "string" || cmd.trim() === "") return
65
+
66
+ if (cmd.startsWith("rtk ")) return
67
+ if (process.env.RTK_DISABLED === "1") return
68
+
69
+ // Delegate to RTK.
70
+ const rewritten = await rewriteCommand(pi, cmd, ctx.signal)
71
+ if (rewritten && rewritten !== cmd) {
72
+ event.input.command = rewritten
73
+ }
74
+ } catch (err) {
75
+ // Fail open: never block execution on an unexpected error.
76
+ console.warn("[rtk] unexpected error in tool_call handler; passing through command", err)
77
+ return
78
+ }
79
+ })
80
+ }
package/src/short.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Short extension — 默认注入系统提示;/short 时额外嵌入本轮 user message。
3
+ *
4
+ * 用法:
5
+ * /short on|off 开关系统提示注入(默认 on)
6
+ * /short <问题> 发送带短答约束的 user message,忙碌时加入 steer 队列
7
+ */
8
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
9
+
10
+ const REMINDER = [
11
+ "输出要极其克制,言简意赅,以极其简短、凝练的语言回答问题;",
12
+ "代码编写尽可能简短,但排版要符合规范,不能牺牲代码的易读性。遵循Linux极简主义,一次做好一件事;以最少的代码实现目标功能。",
13
+ ].join("\n");
14
+
15
+ export default function (pi: ExtensionAPI) {
16
+ let enabled = true;
17
+
18
+ pi.on("before_agent_start", (event) => {
19
+ if (!enabled) return;
20
+ return { systemPrompt: `${event.systemPrompt}\n\n${REMINDER}` };
21
+ });
22
+
23
+ pi.registerCommand("short", {
24
+ description: "短答:/short on|off | /short <问题>",
25
+ handler: async (args, ctx) => {
26
+ const text = args.trim();
27
+ const head = text.split(/\s+/)[0]?.toLowerCase();
28
+
29
+ if (head === "on" || head === "off") {
30
+ enabled = head === "on";
31
+ ctx.ui.notify(`短答系统提示:${enabled ? "开" : "关"}`, "info");
32
+ return;
33
+ }
34
+
35
+ if (!text) {
36
+ ctx.ui.notify("用法:/short on|off | /short <问题>", "warning");
37
+ return;
38
+ }
39
+ await pi.sendUserMessage(`${text}\n\n${REMINDER}`, {
40
+ deliverAs: ctx.isIdle() ? undefined : "steer",
41
+ });
42
+ },
43
+ });
44
+ }
@@ -0,0 +1,49 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ const STATUS = "token-speed";
4
+ const MIN_SAMPLE_MS = 500;
5
+ const UPDATE_MS = 300;
6
+
7
+ export default function tokenSpeed(pi: ExtensionAPI): void {
8
+ let startedAt = 0;
9
+ let lastUpdate = 0;
10
+ let chars = 0;
11
+
12
+ const reset = (ctx: ExtensionContext) => {
13
+ startedAt = 0;
14
+ lastUpdate = 0;
15
+ chars = 0;
16
+ ctx.ui.setStatus(STATUS, undefined);
17
+ };
18
+
19
+ const update = (ctx: ExtensionContext, force = false) => {
20
+ const now = Date.now();
21
+ const elapsed = now - startedAt;
22
+ if (!startedAt || !chars || !elapsed) return;
23
+ if (!force && (elapsed < MIN_SAMPLE_MS || now - lastUpdate < UPDATE_MS)) return;
24
+
25
+ const speed = chars * 250 / elapsed; // pi-web: ~4 chars/token
26
+ const color = speed >= 50 ? "accent" : speed >= 30 ? "success" : speed >= 15 ? "warning" : "error";
27
+ ctx.ui.setStatus(STATUS, ctx.ui.theme.fg(color, `${speed.toFixed(1)} t/s`));
28
+ lastUpdate = now;
29
+ };
30
+
31
+ pi.on("session_start", (_event, ctx) => reset(ctx));
32
+
33
+ pi.on("message_start", (event, ctx) => {
34
+ if (event.message.role === "assistant") reset(ctx);
35
+ });
36
+
37
+ pi.on("message_update", (event, ctx) => {
38
+ const stream = event.assistantMessageEvent;
39
+ if (stream.type !== "text_delta" && stream.type !== "thinking_delta" && stream.type !== "toolcall_delta") return;
40
+
41
+ if (!startedAt) startedAt = Date.now();
42
+ chars += stream.delta.length;
43
+ update(ctx);
44
+ });
45
+
46
+ pi.on("message_end", (event, ctx) => {
47
+ if (event.message.role === "assistant") update(ctx, true);
48
+ });
49
+ }