repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi(ext): footer segment producers (context, timing, cost, runtime, git-status, pr-status, thinking)

b408bba3b8304ec4b674c74000be64b8f331ade1

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (7)

pi/agent/extensions/context/index.ts

Added
new file mode 100644
1 +/**
2 + * Context window usage footer segment producer.
3 + *
4 + * Shows context usage percentage with a progress bar.
5 + * Color shifts: muted → warning (60%) → error (85%).
6 + * Emits footer:segment with zone "llm".
7 + */
9 +import type { AgentMessage } from "@mariozechner/pi-ai";
10 +import {
11 + buildSessionContext,
12 + estimateTokens,
13 + type ContextEvent,
14 + type ExtensionAPI,
15 + type ExtensionContext,
16 + type SessionEntry,
17 +} from "@mariozechner/pi-coding-agent";
19 +type Breakdown = {
20 + system: number;
21 + user: number;
22 + agent: number;
23 + tools: number;
24 + carried: number;
25 + total: number;
26 + turns: number;
27 + approximate: boolean;
28 +};
30 +type View = {
31 + tokens: number | null;
32 + contextWindow: number | null;
33 + percent: number | null;
34 + breakdown: Breakdown;
35 +};
37 +const MIX_MIN_PERCENT = 60;
39 +function fmtCount(v: number): string {
40 + if (!Number.isFinite(v)) return "?";
41 + if (v < 1000) return `${Math.round(v)}`;
42 + if (v < 10_000) return `${(v / 1000).toFixed(1)}k`;
43 + if (v < 1_000_000) return `${Math.round(v / 1000)}k`;
44 + return `${(v / 1_000_000).toFixed(1)}M`;
47 +function getColor(pct: number | null): string {
48 + if (pct === null) return "muted";
49 + if (pct >= 85) return "error";
50 + if (pct >= 60) return "warning";
51 + return "muted";
54 +export default function contextExtension(pi: ExtensionAPI) {
55 + let lastSignature = "";
56 + let hasUI = false;
58 + const sync = (ctx: ExtensionContext, liveMessages?: AgentMessage[]) => {
59 + const view = buildView(ctx, liveMessages);
60 + const cw = view.contextWindow;
62 + if (!cw || cw <= 0 || view.tokens === null || view.percent === null) {
63 + const sig = "missing";
64 + if (sig !== lastSignature) {
65 + lastSignature = sig;
66 + pi.events.emit("footer:segment", { id: "context", text: "ctx --", color: "muted", zone: "llm", order: 1 });
67 + pi.events.emit("footer:segment", { id: "context-mix", text: undefined });
68 + }
69 + return;
70 + }
72 + const pct = view.percent;
73 + const b = view.breakdown;
74 + const approx = b.approximate ? "~" : "";
75 + const suffix = `${approx}${Math.round(pct)}%/${fmtCount(cw)} ${b.turns}t`;
76 + const showMix = pct >= MIX_MIN_PERCENT && b.total > 0;
77 + const mix = showMix
78 + ? `S${fmtCount(b.system)} U${fmtCount(b.user)} A${fmtCount(b.agent)} T${fmtCount(b.tools)} C${fmtCount(b.carried)}`
79 + : "";
80 + const sig = `${Math.round(pct * 10) / 10}|${view.tokens}|${cw}|${suffix}|${mix}`;
81 + if (sig === lastSignature) return;
82 + lastSignature = sig;
84 + pi.events.emit("footer:segment", {
85 + id: "context",
86 + text: "",
87 + suffix,
88 + color: getColor(pct),
89 + bar: pct,
90 + zone: "llm",
91 + order: 1,
92 + });
94 + if (showMix) {
95 + pi.events.emit("footer:segment", {
96 + id: "context-mix",
97 + text: mix,
98 + color: "dim",
99 + zone: "llm",
100 + order: 1.5,
101 + });
102 + } else {
103 + pi.events.emit("footer:segment", { id: "context-mix", text: undefined });
105 + };
107 + const safeSync = (ctx: ExtensionContext, liveMessages?: AgentMessage[]) => {
108 + if (!hasUI && !ctx.hasUI) return;
109 + try { sync(ctx, liveMessages); } catch {}
110 + };
112 + pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; lastSignature = ""; safeSync(ctx); });
113 + pi.on("session_tree", async (_e, ctx) => { lastSignature = ""; safeSync(ctx); });
114 + pi.on("agent_start", async (_e, ctx) => safeSync(ctx));
115 + pi.on("agent_end", async (_e, ctx) => safeSync(ctx));
116 + pi.on("turn_end", async (_e, ctx) => safeSync(ctx));
117 + pi.on("model_select", async (_e, ctx) => { lastSignature = ""; safeSync(ctx); });
118 + pi.on("thinking_level_select", async (_e, ctx) => { lastSignature = ""; safeSync(ctx); });
119 + pi.on("session_compact", async (_e, ctx) => { lastSignature = ""; safeSync(ctx); });
120 + pi.on("context", async (event: ContextEvent, ctx) => safeSync(ctx, event.messages));
121 + pi.on("session_shutdown", async () => { lastSignature = ""; pi.events.emit("footer:segment", { id: "context-mix", text: undefined }); });
124 +function buildView(ctx: ExtensionContext, liveMessages?: AgentMessage[]): View {
125 + const estimated = liveMessages ? buildLiveBreakdown(liveMessages, ctx) : buildCurrentBreakdown(ctx);
126 + const usage = ctx.getContextUsage();
127 + const contextWindow = usage?.contextWindow ?? ctx.model?.contextWindow ?? null;
128 + const canTrustUsage = !liveMessages && typeof usage?.tokens === "number";
129 + const actualTokens = canTrustUsage ? usage?.tokens ?? null : null;
130 + const tokens = actualTokens ?? estimated.total;
131 + const percent = canTrustUsage
132 + ? (usage?.percent ?? (contextWindow && actualTokens !== null ? (actualTokens / contextWindow) * 100 : null))
133 + : contextWindow && tokens > 0
134 + ? (tokens / contextWindow) * 100
135 + : null;
137 + return {
138 + tokens,
139 + contextWindow,
140 + percent,
141 + breakdown: {
142 + ...scaleBreakdownToTotal(estimated, tokens),
143 + approximate: !canTrustUsage,
144 + },
145 + };
148 +function buildCurrentBreakdown(ctx: ExtensionContext): Breakdown {
149 + const entries = ctx.sessionManager.getEntries() as SessionEntry[];
150 + const byId = new Map(entries.map((entry) => [entry.id, entry]));
151 + let messages: AgentMessage[];
152 + try {
153 + messages = buildSessionContext(entries, ctx.sessionManager.getLeafId(), byId).messages;
154 + } catch {
155 + messages = (ctx.sessionManager.getBranch() as SessionEntry[])
156 + .filter((entry) => entry.type === "message")
157 + .map((entry) => entry.message as AgentMessage);
159 + const turns = countAssistantMessages(ctx.sessionManager.getBranch() as SessionEntry[]);
160 + return buildBreakdown(messages, ctx.getSystemPrompt() ?? "", turns);
163 +function buildLiveBreakdown(messages: AgentMessage[], ctx: ExtensionContext): Breakdown {
164 + const turns = countAssistantMessages(ctx.sessionManager.getBranch() as SessionEntry[]) + 1;
165 + return buildBreakdown(messages, ctx.getSystemPrompt() ?? "", turns);
168 +function buildBreakdown(messages: AgentMessage[], systemPrompt: string, turns: number): Breakdown {
169 + const breakdown: Breakdown = {
170 + system: estimateTextTokens(systemPrompt),
171 + user: 0,
172 + agent: 0,
173 + tools: 0,
174 + carried: 0,
175 + total: 0,
176 + turns,
177 + approximate: false,
178 + };
180 + for (const message of messages) {
181 + const tokens = safeEstimateMessage(message);
182 + switch (message.role) {
183 + case "user": breakdown.user += tokens; break;
184 + case "assistant": breakdown.agent += tokens; break;
185 + case "toolResult":
186 + case "bashExecution":
187 + breakdown.tools += tokens;
188 + break;
189 + case "compactionSummary":
190 + case "branchSummary":
191 + case "custom":
192 + default:
193 + breakdown.carried += tokens;
194 + break;
198 + breakdown.total = breakdown.system + breakdown.user + breakdown.agent + breakdown.tools + breakdown.carried;
199 + return breakdown;
202 +function scaleBreakdownToTotal(breakdown: Breakdown, targetTotal: number | null): Breakdown {
203 + if (targetTotal === null || targetTotal < 0 || breakdown.total <= 0 || breakdown.total === targetTotal) {
204 + return breakdown;
207 + const fields = [
208 + { key: "system", value: breakdown.system },
209 + { key: "user", value: breakdown.user },
210 + { key: "agent", value: breakdown.agent },
211 + { key: "tools", value: breakdown.tools },
212 + { key: "carried", value: breakdown.carried },
213 + ] as const;
215 + const scaled = fields.map((field) => {
216 + const raw = (field.value / breakdown.total) * targetTotal;
217 + return { key: field.key, value: Math.floor(raw), remainder: raw - Math.floor(raw) };
218 + });
220 + let assigned = scaled.reduce((sum, field) => sum + field.value, 0);
221 + for (const field of [...scaled].sort((a, b) => b.remainder - a.remainder)) {
222 + if (assigned >= targetTotal) break;
223 + field.value += 1;
224 + assigned += 1;
227 + const next = { ...breakdown, total: targetTotal };
228 + for (const field of scaled) {
229 + next[field.key] = field.value;
231 + return next;
234 +function countAssistantMessages(entries: SessionEntry[]): number {
235 + let count = 0;
236 + for (const entry of entries) {
237 + if (entry.type === "message" && entry.message.role === "assistant") count += 1;
239 + return count;
242 +function estimateTextTokens(text: string): number {
243 + if (!text.trim()) return 0;
244 + return safeEstimateMessage({ role: "user", content: text, timestamp: Date.now() } as AgentMessage);
247 +function safeEstimateMessage(message: AgentMessage): number {
248 + try {
249 + return Math.max(0, estimateTokens(message));
250 + } catch {
251 + return Math.max(0, Math.ceil(extractText(message).length / 4));
255 +function extractText(message: AgentMessage): string {
256 + const parts: string[] = [message.role];
257 + const anyMessage = message as any;
259 + if (typeof anyMessage.content === "string") {
260 + parts.push(anyMessage.content);
261 + } else if (Array.isArray(anyMessage.content)) {
262 + for (const block of anyMessage.content) {
263 + if (block.type === "text") parts.push(block.text ?? "");
264 + else if (block.type === "thinking") parts.push(block.thinking ?? "");
265 + else if (block.type === "toolCall") parts.push(block.name ?? "", JSON.stringify(block.arguments ?? {}));
266 + else parts.push(JSON.stringify(block));
270 + for (const key of ["toolName", "summary", "command", "customType"]) {
271 + if (typeof anyMessage[key] === "string") parts.push(anyMessage[key]);
274 + return parts.join("\n");

pi/agent/extensions/cost/index.ts

Added
new file mode 100644
1 +/**
2 + * Cost & token tracking footer segment producer.
3 + *
4 + * Tracks per-turn cost, session cumulative cost, and monthly cumulative cost.
5 + * Emits footer:segment with zone "llm".
6 + *
7 + * Bug fixes vs old ui/:
8 + * - Uses cumulative sum (not per-message comparison) to avoid skipped duplicates
9 + * - Monthly cost calculation is async and cached per session
10 + * - After compaction, re-sums from full branch (no double-count)
11 + */
13 +import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
14 +import { getAgentDir, parseSessionEntries } from "@mariozechner/pi-coding-agent";
15 +import { readdirSync, readFileSync } from "node:fs";
16 +import { join } from "node:path";
18 +// ── Manual pricing for providers that report $0 cost ────────────────
19 +// Prices per 1M tokens. When usage.cost.total === 0, we compute from these.
21 +type PriceRow = { input: number; cacheRead: number; output: number };
23 +const PRICING: Record<string, Record<string, PriceRow>> = {
24 + zai: {
25 + "glm-5.1": { input: 1.4, cacheRead: 0.26, output: 4.4 },
26 + "glm-5": { input: 1.0, cacheRead: 0.2, output: 4.0 },
27 + "glm-5-turbo": { input: 0.5, cacheRead: 0.1, output: 2.0 },
28 + "glm-4.7": { input: 1.0, cacheRead: 0.2, output: 4.0 },
29 + "glm-4.7-flash": { input: 0.1, cacheRead: 0.02, output: 0.4 },
30 + "glm-4.7-flashx": { input: 0.1, cacheRead: 0.02, output: 0.4 },
31 + "glm-4.6": { input: 1.0, cacheRead: 0.2, output: 4.0 },
32 + "glm-4.5": { input: 1.0, cacheRead: 0.2, output: 4.0 },
33 + "glm-4.5-air": { input: 0.1, cacheRead: 0.02, output: 0.4 },
34 + "glm-4.5-flash": { input: 0.1, cacheRead: 0.02, output: 0.4 },
35 + },
36 + minimax: {
37 + "MiniMax-M2.7": { input: 1.0, cacheRead: 0.06, output: 4.0 },
38 + "MiniMax-M2.7-highspeed": { input: 0.6, cacheRead: 0.06, output: 2.4 },
39 + "MiniMax-M1": { input: 1.0, cacheRead: 0.06, output: 4.0 },
40 + },
41 +};
43 +function getTokenCost(provider: string, model: string, usage: { input: number; output: number; cacheRead: number; cacheWrite: number }): number {
44 + const providerPrices = PRICING[provider];
45 + if (!providerPrices) return 0;
46 + // Try exact match, then prefix match
47 + const prices = providerPrices[model] ??
48 + Object.entries(providerPrices).find(([k]) => model.startsWith(k))?.[1];
49 + if (!prices) return 0;
50 + const m = 1_000_000;
51 + return (usage.input * prices.input / m) +
52 + (usage.cacheRead * prices.cacheRead / m) +
53 + (usage.output * prices.output / m);
56 +function fmtCount(v: number): string {
57 + if (v < 1000) return `${v}`;
58 + if (v < 10_000) return `${(v / 1000).toFixed(1)}k`;
59 + return `${Math.round(v / 1000)}k`;
62 +function fmtCost(v: number): string {
63 + if (v < 0.01) return `$${v.toFixed(4)}`;
64 + if (v < 10) return `$${v.toFixed(2)}`;
65 + return `$${v.toFixed(1)}`;
68 +function fmtProvider(p: string | undefined): string {
69 + if (!p) return "Unknown";
70 + const known: Record<string, string> = {
71 + anthropic: "Anthropic", gemini: "Google", google: "Google",
72 + ollama: "Ollama", openai: "OpenAI", "openai-codex": "OpenAI",
73 + };
74 + return known[p] ?? p.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
77 +/** Sum all assistant message costs in a branch. Falls back to manual pricing when provider reports $0. */
78 +function sumBranchCost(branch: ReturnType<ExtensionContext["sessionManager"]["getBranch"]>): number {
79 + let total = 0;
80 + for (const entry of branch) {
81 + if (entry.type !== "message") continue;
82 + if (entry.message.role !== "assistant") continue;
83 + const u = entry.message?.usage;
84 + if (!u) continue;
85 + const reported = u.cost?.total ?? 0;
86 + if (reported > 0) {
87 + total += reported;
88 + } else {
89 + const provider = (entry.message as { provider?: string }).provider ?? "";
90 + const model = (entry.message as { model?: string }).model ?? "";
91 + total += getTokenCost(provider, model, {
92 + input: u.input ?? 0,
93 + output: u.output ?? 0,
94 + cacheRead: u.cacheRead ?? 0,
95 + cacheWrite: u.cacheWrite ?? 0,
96 + });
97 + }
98 + }
99 + return total;
102 +/** Sum all token usage in a branch (last assistant message after compaction). */
103 +function getLastUsage(branch: ReturnType<ExtensionContext["sessionManager"]["getBranch"]>) {
104 + let input = 0, output = 0, cacheRead = 0, cacheWrite = 0;
105 + for (let i = branch.length - 1; i >= 0; i--) {
106 + const entry = branch[i];
107 + if (entry.type !== "message" || entry.message.role !== "assistant") continue;
108 + const u = entry.message.usage;
109 + if (!u) continue;
110 + input = u.input ?? 0;
111 + output = u.output ?? 0;
112 + cacheRead = u.cacheRead ?? 0;
113 + cacheWrite = u.cacheWrite ?? 0;
114 + break;
116 + return { input, output, cacheRead, cacheWrite };
119 +/** Sum costs from a single session file. */
120 +function sumFileCosts(filePath: string): number {
121 + let total = 0;
122 + try {
123 + const entries = parseSessionEntries(readFileSync(filePath, "utf-8"));
124 + for (const e of entries) {
125 + if (e.type === "message" && e.message?.role === "assistant") {
126 + const u = e.message?.usage;
127 + if (!u) continue;
128 + const reported = u.cost?.total ?? 0;
129 + if (reported > 0) {
130 + total += reported;
131 + } else {
132 + const prov = (e.message as { provider?: string }).provider ?? "";
133 + const mdl = (e.message as { model?: string }).model ?? "";
134 + total += getTokenCost(prov, mdl, {
135 + input: u.input ?? 0, output: u.output ?? 0,
136 + cacheRead: u.cacheRead ?? 0, cacheWrite: u.cacheWrite ?? 0,
137 + });
141 + } catch { /* skip unreadable files */ }
142 + return total;
145 +/** Resolve sessions directory from settings or default. */
146 +function getSessionsDir(): string {
147 + try {
148 + const settingsPath = join(getAgentDir(), "settings.json");
149 + const raw = readFileSync(settingsPath, "utf-8");
150 + const settings = JSON.parse(raw);
151 + if (settings.sessionDir) return settings.sessionDir;
152 + } catch {}
153 + return join(getAgentDir(), "sessions");
156 +/** Async monthly cost - scans session files for current month. Cached per session. */
157 +async function calculateMonthlyCost(): Promise<number> {
158 + const now = new Date();
159 + const ym = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
160 + let total = 0;
161 + const sessionsDir = getSessionsDir();
163 + try {
164 + const entries = readdirSync(sessionsDir, { withFileTypes: true });
165 + for (const entry of entries) {
166 + // Support both layouts:
167 + // New: flat YYYY-MM-DD*.jsonl files
168 + // Old: <cwd-hash>/session-YYYY-MM-DD*.jsonl subdirs
169 + if (entry.isDirectory()) {
170 + try {
171 + for (const file of readdirSync(join(sessionsDir, entry.name), { withFileTypes: true })) {
172 + if (!file.isFile() || !file.name.endsWith(".jsonl")) continue;
173 + const m = file.name.match(/^(\d{4})-(\d{2})/);
174 + if (!m || `${m[1]}-${m[2]}` !== ym) continue;
175 + total += sumFileCosts(join(sessionsDir, entry.name, file.name));
177 + } catch { /* skip */ }
178 + } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
179 + const m = entry.name.match(/^(\d{4})-(\d{2})/);
180 + if (!m || `${m[1]}-${m[2]}` !== ym) continue;
181 + total += sumFileCosts(join(sessionsDir, entry.name));
184 + } catch { /* no sessions dir */ }
185 + return total;
188 +function buildTokenLabel(u: { input: number; output: number; cacheRead: number; cacheWrite: number }): string {
189 + // cache hit ratio = cacheRead / (input + cacheRead)
190 + const totalPrompt = u.input + u.cacheRead;
191 + if (totalPrompt === 0 && u.output === 0) return "↑0";
192 + if (u.input === 0 && u.cacheRead > 0) return `◐ ${fmtCount(u.cacheRead)}`;
193 + if (u.cacheRead > 0) {
194 + const ratio = Math.round((u.cacheRead / totalPrompt) * 100);
195 + return `◐${fmtCount(u.input)} ↓${fmtCount(u.output)} (${ratio}% cached)`;
197 + return `↑${fmtCount(u.input)} ↓${fmtCount(u.output)}`;
200 +export default function costExtension(pi: ExtensionAPI) {
201 + let sessionCost = 0;
202 + let prevSessionCost = 0;
203 + let monthlyCost = 0;
204 + let lastEmitSignature = "";
205 + let hasUI = false;
207 + const sync = async (ctx: ExtensionContext) => {
208 + const branch = ctx.sessionManager.getBranch();
209 + const usage = getLastUsage(branch);
211 + // Cumulative session cost from full branch history
212 + sessionCost = sumBranchCost(branch);
214 + const model = ctx.model;
215 + const provider = fmtProvider(model?.provider);
216 + const modelId = model?.id ?? "no-model";
217 + const modelShort = modelId.split("/").pop() ?? modelId;
218 + const isSub = model && ctx.modelRegistry?.isUsingOAuth(model) ? " (sub)" : "";
220 + const signature = `${provider}|${modelShort}|${usage.input}|${sessionCost}|${monthlyCost}|${isSub}`;
221 + if (signature === lastEmitSignature) return;
222 + lastEmitSignature = signature;
224 + pi.events.emit("footer:segment", {
225 + id: "model",
226 + text: `${provider}/${modelShort}${isSub}`,
227 + color: "syntaxKeyword",
228 + zone: "llm",
229 + order: 0,
230 + });
232 + pi.events.emit("footer:segment", {
233 + id: "tokens",
234 + text: buildTokenLabel(usage),
235 + color: "muted",
236 + zone: "llm",
237 + order: 2,
238 + });
240 + // Turn cost = session cost delta since last sync
241 + const turnCost = Math.max(0, sessionCost - prevSessionCost);
242 + prevSessionCost = sessionCost;
244 + const costParts: string[] = [];
245 + if (turnCost > 0) costParts.push(fmtCost(turnCost));
246 + if (sessionCost > 0) costParts.push(`Σ${fmtCost(sessionCost)}`);
247 + if (monthlyCost > sessionCost) costParts.push(`Mo${fmtCost(monthlyCost)}`);
249 + const costLabel = costParts.length > 0 ? costParts.join(" · ") : "";
251 + if (costLabel) {
252 + pi.events.emit("footer:segment", {
253 + id: "cost",
254 + text: costLabel,
255 + color: "success",
256 + zone: "llm",
257 + order: 3,
258 + });
260 + };
262 + pi.on("session_start", async (_e, ctx) => {
263 + hasUI = ctx.hasUI;
264 + if (!hasUI) return;
265 + sessionCost = 0;
266 + prevSessionCost = 0;
267 + monthlyCost = await calculateMonthlyCost();
268 + lastEmitSignature = "";
269 + await sync(ctx);
270 + });
272 + pi.on("agent_start", async (_e, ctx) => { if (hasUI) try { await sync(ctx); } catch {} });
273 + pi.on("agent_end", async (_e, ctx) => { if (hasUI) try { await sync(ctx); } catch {} });
274 + pi.on("model_select", async (_e, ctx) => { if (!hasUI) return; lastEmitSignature = ""; try { await sync(ctx); } catch {} });
275 + pi.on("tool_execution_end", async (_e, ctx) => { if (hasUI) try { await sync(ctx); } catch {} });
276 + pi.on("session_compact", async (_e, ctx) => { if (!hasUI) return; lastEmitSignature = ""; try { await sync(ctx); } catch {} });

pi/agent/extensions/git-status/index.ts

Added
new file mode 100644
1 +/**
2 + * Git status footer segment producer.
3 + *
4 + * Detects git branch, ahead/behind, and file status via porcelain v2.
5 + * Emits footer:segment with zone "workspace".
6 + */
8 +import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
9 +import { execFile } from "node:child_process";
10 +import { promisify } from "node:util";
12 +const execFileAsync = promisify(execFile);
14 +type GitStatus = {
15 + branch?: string;
16 + ahead: number;
17 + behind: number;
18 + conflicted: number;
19 + untracked: number;
20 + stashed: boolean;
21 + modified: number;
22 + staged: number;
23 + renamed: number;
24 + deleted: number;
25 +};
27 +const ICONS = {
28 + git: "", ahead: "↑", behind: "↓", diverged: "⇕",
29 + conflicted: "=", untracked: "?", stashed: "$",
30 + modified: "!", staged: "+", renamed: "»", deleted: "✘",
31 +};
33 +function parsePorcelain(stdout: string, hasStash: boolean): GitStatus {
34 + const s: GitStatus = { branch: undefined, ahead: 0, behind: 0, conflicted: 0, untracked: 0, stashed: false, modified: 0, staged: 0, renamed: 0, deleted: 0 };
35 + s.stashed = hasStash;
37 + for (const line of stdout.split(/\r?\n/)) {
38 + if (!line) continue;
39 + if (line.startsWith("# branch.head ")) {
40 + const b = line.slice("# branch.head ".length).trim();
41 + s.branch = b && b !== "(detached)" ? b : undefined;
42 + continue;
43 + }
44 + if (line.startsWith("# branch.ab ")) {
45 + const m = line.match(/\+(\d+)\s+-(\d+)/);
46 + if (m) { s.ahead = Number(m[1]); s.behind = Number(m[2]); }
47 + continue;
48 + }
49 + if (line.startsWith("#")) continue;
50 + if (line.startsWith("? ")) { s.untracked++; continue; }
51 + if (line.startsWith("u ")) { s.conflicted++; continue; }
52 + if (!(line.startsWith("1 ") || line.startsWith("2 "))) continue;
53 + const xy = line.split(" ")[1] ?? "..";
54 + const x = xy[0] ?? ".", y = xy[1] ?? ".";
55 + if (x === "R") s.renamed++;
56 + else if (x === "D") s.deleted++;
57 + else if (x !== "." && x !== " ") s.staged++;
58 + if (y === "M") s.modified++;
59 + else if (y === "D") s.deleted++;
60 + }
61 + return s;
64 +async function readGitStatus(cwd: string): Promise<GitStatus> {
65 + const empty: GitStatus = { branch: undefined, ahead: 0, behind: 0, conflicted: 0, untracked: 0, stashed: false, modified: 0, staged: 0, renamed: 0, deleted: 0 };
66 + try {
67 + const [{ stdout }, stash] = await Promise.all([
68 + execFileAsync("git", ["status", "--porcelain=2", "--branch"], { cwd }),
69 + execFileAsync("git", ["rev-parse", "--verify", "--quiet", "refs/stash"], { cwd }).catch(() => ({ stdout: "" })),
70 + ]);
71 + return parsePorcelain(
72 + typeof stdout === "string" ? stdout : String(stdout),
73 + stash.stdout.trim().length > 0,
74 + );
75 + } catch { return empty; }
78 +function emitGit(pi: ExtensionAPI, cwd: string, status: GitStatus) {
79 + const home = process.env.HOME;
80 + const path = home && cwd.startsWith(home) ? `~${cwd.slice(home.length)}` : cwd;
82 + // Cwd segment
83 + pi.events.emit("footer:segment", { id: "cwd", text: path, icon: "󰝰", color: "syntaxOperator", zone: "workspace", order: 0 });
85 + // Branch + status segment
86 + if (status.branch) {
87 + const allStatus = [
88 + status.conflicted > 0 ? ICONS.conflicted : "",
89 + status.stashed ? ICONS.stashed : "",
90 + status.deleted > 0 ? ICONS.deleted : "",
91 + status.renamed > 0 ? ICONS.renamed : "",
92 + status.modified > 0 ? ICONS.modified : "",
93 + status.staged > 0 ? ICONS.staged : "",
94 + status.untracked > 0 ? ICONS.untracked : "",
95 + ].join("");
96 + const ab = status.ahead > 0 && status.behind > 0 ? ICONS.diverged
97 + : status.ahead > 0 ? ICONS.ahead
98 + : status.behind > 0 ? ICONS.behind : "";
99 + const statusBlock = allStatus || ab ? `[${allStatus}${ab}]` : "";
100 + pi.events.emit("footer:segment", {
101 + id: "git-branch",
102 + text: `${status.branch}${statusBlock ? ` ${statusBlock}` : ""}`,
103 + icon: ICONS.git,
104 + color: "syntaxKeyword",
105 + zone: "workspace",
106 + order: 1,
107 + });
108 + } else {
109 + pi.events.emit("footer:segment", { id: "git-branch", text: undefined });
113 +export default function gitStatusExtension(pi: ExtensionAPI) {
114 + let currentCwd = "";
115 + let hasUI = false;
116 + let refreshInFlight = false;
117 + let refreshPending = false;
119 + const refresh = async () => {
120 + if (!hasUI || refreshInFlight) { refreshPending = true; return; }
121 + refreshInFlight = true;
122 + try {
123 + const status = await readGitStatus(currentCwd);
124 + emitGit(pi, currentCwd, status);
125 + } finally {
126 + refreshInFlight = false;
127 + if (refreshPending) { refreshPending = false; refresh(); }
129 + };
131 + pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; currentCwd = ctx.cwd; refresh(); });
132 + pi.on("agent_end", async () => { if (hasUI) refresh(); });
133 + pi.on("tool_execution_end", async () => { if (hasUI) refresh(); });

pi/agent/extensions/pr-status/index.ts

Added
new file mode 100644
1 +/**
2 + * PR/MR status footer segment producer.
3 + *
4 + * Detects open pull/merge requests for the current branch.
5 + * Forge-agnostic: tries gh (GitHub), glab (GitLab), bb (Bitbucket).
6 + * Falls back silently if no forge CLI is available.
7 + * Emits footer:segment with zone "workspace".
8 + */
10 +import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
11 +import { assertArray, assertString, assertHasKeys } from "../../lib/assert.ts";
13 +type ForgeResult = { id: string; url: string; state: string; isDraft?: boolean };
15 +async function execForge(pi: ExtensionAPI, args: string[], cwd: string, timeout = 3000): Promise<string | null> {
16 + try {
17 + const r = await pi.exec(args[0]!, args.slice(1), { cwd, timeout });
18 + return r.code === 0 ? r.stdout.trim() : null;
19 + } catch { return null; }
22 +async function tryGitHub(pi: ExtensionAPI, cwd: string, branch: string): Promise<ForgeResult | null> {
23 + const out = await execForge(pi, [
24 + "gh", "pr", "list", "--head", branch, "--state", "open",
25 + "--limit", "1", "--json", "number,url,state,isDraft",
26 + ], cwd);
27 + if (!out) return null;
28 + try {
29 + const raw = JSON.parse(out);
30 + assertArray(raw, "gh pr list should return array");
31 + if (raw.length === 0) return null;
32 + assertHasKeys(raw[0], ["number", "url", "state"], "gh pr entry shape");
33 + const pr = raw[0];
34 + return { id: `#${pr.number}`, url: pr.url, state: pr.state, isDraft: pr.isDraft };
35 + } catch { return null; }
38 +async function tryGitLab(pi: ExtensionAPI, cwd: string, branch: string): Promise<ForgeResult | null> {
39 + const out = await execForge(pi, [
40 + "glab", "mr", "list", "--source-branch", branch, "--state", "opened",
41 + "--per-page", "1", "--output", "json",
42 + ], cwd);
43 + if (!out) return null;
44 + try {
45 + const raw = JSON.parse(out);
46 + assertArray(raw, "glab mr list should return array");
47 + if (raw.length === 0) return null;
48 + assertHasKeys(raw[0], ["iid", "web_url", "state"], "glab mr entry shape");
49 + const mr = raw[0];
50 + return { id: `!${mr.iid}`, url: mr.web_url, state: mr.state };
51 + } catch { return null; }
54 +async function tryBitbucket(pi: ExtensionAPI, cwd: string, branch: string): Promise<ForgeResult | null> {
55 + const out = await execForge(pi, [
56 + "bb", "pr", "list", "--source-branch", branch, "--state", "OPEN",
57 + "--limit", "1", "--output", "json",
58 + ], cwd);
59 + if (!out) return null;
60 + try {
61 + const raw = JSON.parse(out);
62 + assertArray(raw, "bb pr list should return array");
63 + if (raw.length === 0) return null;
64 + const pr = raw[0];
65 + assertString(pr.id, "bb pr should have id");
66 + return { id: `#${pr.id}`, url: pr.links?.html?.href ?? "", state: pr.state };
67 + } catch { return null; }
70 +async function detectPR(pi: ExtensionAPI, cwd: string): Promise<ForgeResult | null> {
71 + // Get current branch
72 + const branch = await execForge(pi, ["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd, 1500);
73 + if (!branch || branch === "HEAD") return null;
75 + // Try each forge CLI in order
76 + return (
77 + await tryGitHub(pi, cwd, branch) ??
78 + await tryGitLab(pi, cwd, branch) ??
79 + await tryBitbucket(pi, cwd, branch)
80 + );
83 +export default function prStatusExtension(pi: ExtensionAPI) {
84 + let currentCwd = "";
85 + let hasUI = false;
86 + let refreshInFlight = false;
88 + const refresh = async () => {
89 + if (refreshInFlight) return;
90 + refreshInFlight = true;
91 + try {
92 + const pr = await detectPR(pi, currentCwd);
93 + if (pr) {
94 + const draft = pr.isDraft ? " (draft)" : "";
95 + pi.events.emit("footer:segment", {
96 + id: "pr-status",
97 + text: `${pr.id}${draft}`,
98 + icon: "",
99 + color: "accent",
100 + zone: "workspace",
101 + order: 2,
102 + });
103 + } else {
104 + pi.events.emit("footer:segment", { id: "pr-status", text: undefined });
106 + } finally {
107 + refreshInFlight = false;
109 + };
111 + pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; currentCwd = ctx.cwd; refresh(); });
112 + pi.on("agent_end", async () => { if (hasUI) refresh(); });

pi/agent/extensions/runtime/index.ts

Added
new file mode 100644
1 +/**
2 + * Runtime detection footer segment producer.
3 + *
4 + * Detects project language runtime from config files and emits
5 + * a footer:segment with zone "workspace".
6 + */
8 +import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
9 +import { execFile } from "node:child_process";
10 +import { existsSync, readdirSync } from "node:fs";
11 +import { join } from "node:path";
12 +import { promisify } from "node:util";
14 +const execFileAsync = promisify(execFile);
15 +const VERSION_TIMEOUT_MS = 2500;
17 +type RuntimeInfo = { name: string; symbol: string; version?: string };
18 +type Candidate = { name: string; symbol: string; detect: (cwd: string, entries: string[]) => boolean; version: (cwd: string) => Promise<string | undefined> };
20 +const hasFile = (cwd: string, names: string[]) => names.some((n) => existsSync(join(cwd, n)));
21 +const hasEntry = (entries: string[], names: string[]) => names.some((n) => entries.includes(n));
23 +async function runVer(cmd: string, args: string[] = [], cwd?: string): Promise<string | undefined> {
24 + try {
25 + const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, timeout: VERSION_TIMEOUT_MS });
26 + const text = `${stdout}\n${stderr}`.trim();
27 + return text || undefined;
28 + } catch { return undefined; }
31 +function pv(v?: string) { return v?.startsWith("v") ? v : v ? `v${v}` : undefined; }
33 +const runtimes: Candidate[] = [
34 + { name: "bun", symbol: "", detect: (c) => hasFile(c, ["bun.lock", "bun.lockb"]), version: async () => pv(await runVer("bun", ["--version"])) },
35 + { name: "deno", symbol: "", detect: (c) => hasFile(c, ["deno.json", "deno.jsonc", "deno.lock"]), version: async () => pv((await runVer("deno", ["--version"]))?.match(/deno\s+([0-9][^\s]*)/i)?.[1]) },
36 + { name: "lua", symbol: "", detect: (c, e) => hasFile(c, ["stylua.toml", ".stylua.toml", ".luarc.json", ".luarc.jsonc", "init.lua"]) || hasEntry(e, ["lua"]) || e.some((x) => x.endsWith(".lua")),
37 + version: async () => pv((await runVer("lua", ["-v"]))?.match(/Lua\s+([0-9][^\s]*)/i)?.[1] ?? (await runVer("luajit", ["-v"]))?.match(/LuaJIT\s+([0-9][^\s]*)/i)?.[1]) },
38 + { name: "nodejs", symbol: "", detect: (c) => hasFile(c, ["package.json", ".nvmrc", ".node-version"]), version: async () => pv(await runVer("node", ["--version"])) },
39 + { name: "python", symbol: "", detect: (c) => hasFile(c, ["pyproject.toml", "requirements.txt", "setup.py", "setup.cfg", "Pipfile", ".python-version"]),
40 + version: async () => pv((await runVer("python3", ["--version"]))?.match(/Python\s+([0-9][^\s]*)/i)?.[1] ?? (await runVer("python", ["--version"]))?.match(/Python\s+([0-9][^\s]*)/i)?.[1]) },
41 + { name: "golang", symbol: "", detect: (c) => hasFile(c, ["go.mod"]), version: async () => pv((await runVer("go", ["version"]))?.match(/go version go([0-9][^\s]*)/i)?.[1]) },
42 + { name: "rust", symbol: "󱘗", detect: (c) => hasFile(c, ["Cargo.toml"]), version: async () => pv((await runVer("rustc", ["--version"]))?.match(/rustc\s+([0-9][^\s]*)/i)?.[1]) },
43 + { name: "java", symbol: "", detect: (c) => hasFile(c, ["pom.xml", "build.gradle", "build.gradle.kts"]), version: async () => pv((await runVer("java", ["-version"]))?.match(/"([0-9][^"]*)"/)?.[1]) },
44 + { name: "ruby", symbol: "", detect: (c) => hasFile(c, ["Gemfile", ".ruby-version"]), version: async () => pv((await runVer("ruby", ["--version"]))?.match(/ruby\s+([0-9][^\s]*)/i)?.[1]) },
45 + { name: "php", symbol: "", detect: (c) => hasFile(c, ["composer.json"]), version: async () => pv((await runVer("php", ["--version"]))?.match(/PHP\s+([0-9][^\s]*)/i)?.[1]) },
46 +];
48 +const RUNTIME_COLORS: Record<string, string> = {
49 + nodejs: "success", deno: "syntaxType", golang: "syntaxType", bun: "warning", python: "warning", java: "warning",
50 + rust: "error", ruby: "error", lua: "accent", php: "accent",
51 +};
53 +async function detect(cwd: string): Promise<RuntimeInfo | undefined> {
54 + let entries: string[] = [];
55 + try { entries = readdirSync(cwd); } catch { /* not a dir */ }
56 + for (const rt of runtimes) {
57 + if (rt.detect(cwd, entries)) {
58 + return { name: rt.name, symbol: rt.symbol, version: await rt.version(cwd) };
59 + }
60 + }
61 + return undefined;
64 +export default function runtimeExtension(pi: ExtensionAPI) {
65 + let currentCwd = "";
66 + let hasUI = false;
67 + let refreshInFlight = false;
69 + const refresh = async () => {
70 + if (!hasUI || refreshInFlight) return;
71 + refreshInFlight = true;
72 + try {
73 + const rt = await detect(currentCwd);
74 + if (rt) {
75 + const label = rt.version ? `${rt.symbol} ${rt.version}` : rt.symbol;
76 + pi.events.emit("footer:segment", { id: "runtime", text: label, color: RUNTIME_COLORS[rt.name] ?? "text", zone: "workspace", order: 3 });
77 + } else {
78 + pi.events.emit("footer:segment", { id: "runtime", text: undefined });
79 + }
80 + } finally { refreshInFlight = false; }
81 + };
83 + pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; currentCwd = ctx.cwd; refresh(); });
84 + pi.on("agent_end", async () => { if (hasUI) refresh(); });

pi/agent/extensions/thinking/index.ts

Added
new file mode 100644
1 +/**
2 + * Thinking level footer segment producer.
3 + *
4 + * Shows current thinking level with per-level colors.
5 + * Polls at 500ms since thinking level can change mid-turn.
6 + * Emits footer:segment with zone "llm".
7 + */
9 +import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
11 +const LEVEL_COLORS: Record<string, string> = {
12 + off: "thinkingOff",
13 + minimal: "thinkingMinimal",
14 + low: "thinkingLow",
15 + medium: "thinkingMedium",
16 + high: "thinkingHigh",
17 + xhigh: "thinkingXhigh",
18 +};
20 +const LEVEL_LABELS: Record<string, string> = {
21 + off: "think:off",
22 + minimal: "think:min",
23 + low: "think:low",
24 + medium: "think:med",
25 + high: "think:high",
26 + xhigh: "think:xhigh",
27 +};
29 +const POLL_MS = 500;
31 +export default function thinkingExtension(pi: ExtensionAPI) {
32 + let timer: ReturnType<typeof setInterval> | null = null;
33 + let lastLevel = "";
34 + let hasUI = false;
36 + const emit = () => {
37 + const level = pi.getThinkingLevel?.() ?? "off";
38 + if (level === lastLevel) return;
39 + lastLevel = level;
41 + pi.events.emit("footer:segment", {
42 + id: "thinking",
43 + text: LEVEL_LABELS[level] ?? `think:${level}`,
44 + color: LEVEL_COLORS[level] ?? "muted",
45 + zone: "llm",
46 + order: 0.5,
47 + });
48 + };
50 + pi.on("session_start", async (_e, ctx) => {
51 + hasUI = ctx.hasUI;
52 + if (!hasUI) return;
53 + lastLevel = "";
54 + emit();
55 + // Poll for mid-turn changes
56 + timer = setInterval(emit, POLL_MS);
57 + });
59 + pi.on("agent_end", async () => { if (hasUI) try { emit(); } catch {} });
61 + pi.on("session_shutdown", async () => {
62 + if (timer) { clearInterval(timer); timer = null; }
63 + pi.events.emit("footer:segment", { id: "thinking", text: undefined });
64 + });

pi/agent/extensions/timing/index.ts

Added
new file mode 100644
1 +/**
2 + * Wall-clock timing footer segment producer.
3 + *
4 + * Tracks agent time, turn time, and session time with 250ms polling.
5 + * Emits footer:segment with zone "llm".
6 + */
8 +import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
10 +function fmtMin(ms: number | null): string {
11 + if (ms === null) return "--";
12 + const s = Math.round(ms / 1000);
13 + if (s < 60) return `${s}s`;
14 + const m = Math.floor(s / 60);
15 + const rs = s % 60;
16 + return rs > 0 ? `${m}m${rs}s` : `${m}m`;
19 +const POLL_MS = 250;
21 +export default function timingExtension(pi: ExtensionAPI) {
22 + let sessionStart: number | null = null;
23 + let agentStart: number | null = null;
24 + let lastAgentMs: number | null = null;
25 + let turnStart: number | null = null;
26 + let turnAccumMs = 0;
27 + let timer: ReturnType<typeof setInterval> | null = null;
28 + let lastSig = "";
29 + let hasUI = false;
31 + const getAgentMs = (now: number): number | null => {
32 + if (agentStart !== null) return now - agentStart;
33 + return lastAgentMs;
34 + };
36 + const getTurnMs = (now: number): number => {
37 + let total = turnAccumMs;
38 + if (turnStart !== null) total += now - turnStart;
39 + return total;
40 + };
42 + const emit = () => {
43 + if (!sessionStart) return;
44 + const now = Date.now();
45 + const agent = getAgentMs(now);
46 + const turn = getTurnMs(now);
47 + const session = now - sessionStart;
49 + const sig = `${agent}|${turn}|${session}`;
50 + if (sig === lastSig) return;
51 + lastSig = sig;
53 + pi.events.emit("footer:segment", {
54 + id: "timing",
55 + text: `⏱ ${fmtMin(agent)} turn · ${fmtMin(session)} session`,
56 + color: "dim",
57 + zone: "llm",
58 + order: 10,
59 + });
60 + };
62 + const startPoll = () => {
63 + stopPoll();
64 + timer = setInterval(emit, POLL_MS);
65 + };
67 + const stopPoll = () => {
68 + if (timer) { clearInterval(timer); timer = null; }
69 + };
71 + const finalizeTurn = () => {
72 + if (turnStart !== null) {
73 + turnAccumMs += Date.now() - turnStart;
74 + turnStart = null;
75 + }
76 + };
78 + pi.on("session_start", async (_e, ctx) => {
79 + hasUI = ctx.hasUI;
80 + if (!hasUI) return;
81 + sessionStart = Date.now();
82 + agentStart = null;
83 + lastAgentMs = null;
84 + turnStart = null;
85 + turnAccumMs = 0;
86 + lastSig = "";
87 + });
89 + pi.on("agent_start", async () => {
90 + if (!hasUI) return;
91 + finalizeTurn();
92 + agentStart = Date.now();
93 + lastAgentMs = 0;
94 + turnAccumMs = 0;
95 + startPoll();
96 + });
98 + pi.on("turn_start", async () => {
99 + finalizeTurn();
100 + turnStart = Date.now();
101 + });
103 + pi.on("turn_end", async () => finalizeTurn());
105 + pi.on("agent_end", async () => {
106 + if (!hasUI) return;
107 + finalizeTurn();
108 + if (agentStart !== null) {
109 + lastAgentMs = Date.now() - agentStart;
110 + agentStart = null;
112 + emit();
113 + stopPoll();
114 + });
116 + pi.on("session_shutdown", async () => {
117 + stopPoll();
118 + pi.events.emit("footer:segment", { id: "timing", text: undefined });
119 + });