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
Addednew file mode 100644 9 +import type { AgentMessage }
from "@mariozechner/pi-ai";
11 + buildSessionContext,
15 + type ExtensionContext,
17 +}
from "@mariozechner/pi-coding-agent";
27 + approximate
: boolean;
31 + tokens
: number | null;
32 + contextWindow
: number | null;
33 + percent
: number | null;
34 + breakdown
: Breakdown;
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";
54 +export default function contextExtension(pi
: ExtensionAPI) {
55 + let lastSignature
= "";
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 });
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;
78 + ? `S${fmtCount(b.system)} U${fmtCount(b.user)} A${fmtCount(b.agent)} T${fmtCount(b.tools)} C${fmtCount(b.carried)}` 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", {
88 + color:
getColor(pct),
95 + pi.events.
emit(
"footer:segment", {
103 + pi.events.
emit(
"footer:segment", { id:
"context-mix", text:
undefined });
107 + const safeSync = (ctx
: ExtensionContext, liveMessages
?: AgentMessage[])
=> {
108 + if (
!hasUI
&& !ctx.hasUI)
return;
109 + try {
sync(ctx, liveMessages); }
catch {}
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 142 + ...scaleBreakdownToTotal(estimated, tokens),
143 + approximate:
!canTrustUsage,
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[];
153 + messages
= buildSessionContext(entries, ctx.sessionManager.
getLeafId(), byId).messages;
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),
177 + approximate:
false,
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;
186 + case "bashExecution":
187 + breakdown.tools
+= tokens;
189 + case "compactionSummary":
190 + case "branchSummary":
193 + breakdown.carried
+= tokens;
198 + breakdown.total
= breakdown.system
+ breakdown.user
+ breakdown.agent
+ breakdown.tools
+ breakdown.carried;
202 +function scaleBreakdownToTotal(breakdown
: Breakdown, targetTotal
: number | null)
: Breakdown {
203 + if (targetTotal
=== null || targetTotal
< 0 || breakdown.total
<= 0 || breakdown.total
=== targetTotal) {
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 },
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) };
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;
227 + const next
= {
...breakdown, total: targetTotal };
228 + for (
const field
of scaled) {
229 + next[field.key]
= field.
value;
234 +function countAssistantMessages(entries
: SessionEntry[])
: number {
236 + for (
const entry
of entries) {
237 + if (entry.
type === "message" && entry.message.role
=== "assistant") count
+= 1;
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 {
249 + return Math.
max(
0,
estimateTokens(message));
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
Addednew file mode 100644 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";
21 +type PriceRow = { input
: number; cacheRead
: number; output
: number };
23 +const PRICING
: Record<
string,
Record<
string,
PriceRow>>
= {
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 },
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 },
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;
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",
74 + return known[p]
?? p.
replace(
/[-_]/g,
" ").
replace(
/\b\w/g, (c)
=> c.
toUpperCase());
78 +function sumBranchCost(branch
: ReturnType<
ExtensionContext[
"sessionManager"][
"getBranch"]>)
: number {
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;
85 + const reported
= u.cost?.total
?? 0;
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,
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;
110 + input
= u.
input ?? 0;
111 + output
= u.output
?? 0;
112 + cacheRead
= u.cacheRead
?? 0;
113 + cacheWrite
= u.cacheWrite
?? 0;
116 + return { input, output, cacheRead, cacheWrite };
120 +function sumFileCosts(filePath
: string)
: number {
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;
128 + const reported
= u.cost?.total
?? 0;
129 + if (reported
> 0) {
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,
146 +function getSessionsDir()
: string {
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;
153 + return join(
getAgentDir(),
"sessions");
157 +async function calculateMonthlyCost()
: Promise<
number> {
158 + const now
= new Date();
159 + const ym
= `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
161 + const sessionsDir
= getSessionsDir();
164 + const entries
= readdirSync(sessionsDir, { withFileTypes:
true });
165 + for (
const entry
of entries) {
169 + if (entry.
isDirectory()) {
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));
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));
188 +function buildTokenLabel(u
: { input
: number; output
: number; cacheRead
: number; cacheWrite
: number })
: string {
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
= "";
207 + const sync = async (ctx
: ExtensionContext)
=> {
208 + const branch
= ctx.sessionManager.
getBranch();
209 + const usage
= getLastUsage(branch);
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", {
226 + text:
`${provider}/${modelShort}${isSub}`,
227 + color:
"syntaxKeyword",
232 + pi.events.
emit(
"footer:segment", {
234 + text:
buildTokenLabel(usage),
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(
" · ")
: "";
252 + pi.events.
emit(
"footer:segment", {
262 + pi.
on(
"session_start",
async (_e, ctx)
=> {
264 + if (
!hasUI)
return;
266 + prevSessionCost
= 0;
267 + monthlyCost
= await calculateMonthlyCost();
268 + lastEmitSignature
= "";
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
Addednew file mode 100644 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);
28 + git:
"", ahead:
"↑", behind:
"↓", diverged:
"⇕",
29 + conflicted:
"=", untracked:
"?", stashed:
"$",
30 + modified:
"!", staged:
"+", renamed:
"»", deleted:
"✘",
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;
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]); }
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
++;
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 };
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:
"" })),
71 + return parsePorcelain(
72 + typeof stdout
=== "string" ? stdout
: String(stdout),
73 + stash.stdout.
trim().
length > 0,
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;
83 + pi.events.
emit(
"footer:segment", { id:
"cwd", text: path, icon:
"", color:
"syntaxOperator", zone:
"workspace", order:
0 });
86 + if (status.branch) {
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
: "",
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", {
102 + text:
`${status.branch}${statusBlock ? ` ${statusBlock}` : ""}`,
104 + color:
"syntaxKeyword",
109 + pi.events.
emit(
"footer:segment", { id:
"git-branch", text:
undefined });
113 +export default function gitStatusExtension(pi
: ExtensionAPI) {
114 + let currentCwd
= "";
116 + let refreshInFlight
= false;
117 + let refreshPending
= false;
119 + const refresh = async ()
=> {
120 + if (
!hasUI
|| refreshInFlight) { refreshPending
= true;
return; }
121 + refreshInFlight
= true;
123 + const status
= await readGitStatus(currentCwd);
124 + emitGit(pi, currentCwd, status);
126 + refreshInFlight
= false;
127 + if (refreshPending) { refreshPending
= false;
refresh(); }
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
Addednew file mode 100644 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> {
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",
27 + if (
!out)
return null;
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");
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",
43 + if (
!out)
return null;
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");
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",
59 + if (
!out)
return null;
61 + const raw
= JSON.
parse(out);
62 + assertArray(raw,
"bb pr list should return array");
63 + if (raw.
length === 0)
return null;
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> {
72 + const branch
= await execForge(pi, [
"git",
"rev-parse",
"--abbrev-ref",
"HEAD"], cwd,
1500);
73 + if (
!branch
|| branch
=== "HEAD")
return null;
77 + await tryGitHub(pi, cwd, branch)
?? 78 + await tryGitLab(pi, cwd, branch)
?? 79 + await tryBitbucket(pi, cwd, branch)
83 +export default function prStatusExtension(pi
: ExtensionAPI) {
84 + let currentCwd
= "";
86 + let refreshInFlight
= false;
88 + const refresh = async ()
=> {
89 + if (refreshInFlight)
return;
90 + refreshInFlight
= true;
92 + const pr
= await detectPR(pi, currentCwd);
94 + const draft
= pr.isDraft
? " (draft)" : "";
95 + pi.events.
emit(
"footer:segment", {
97 + text:
`${pr.id}${draft}`,
104 + pi.events.
emit(
"footer:segment", { id:
"pr-status", text:
undefined });
107 + refreshInFlight
= false;
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
Addednew file mode 100644 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> {
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]) },
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",
53 +async function detect(cwd
: string)
: Promise<
RuntimeInfo | undefined> {
54 + let entries
: string[]
= [];
55 + try { entries
= readdirSync(cwd); }
catch { }
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) };
64 +export default function runtimeExtension(pi
: ExtensionAPI) {
65 + let currentCwd
= "";
67 + let refreshInFlight
= false;
69 + const refresh = async ()
=> {
70 + if (
!hasUI
|| refreshInFlight)
return;
71 + refreshInFlight
= true;
73 + const rt
= await detect(currentCwd);
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 });
78 + pi.events.
emit(
"footer:segment", { id:
"runtime", text:
undefined });
80 + }
finally { refreshInFlight
= false; }
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
Addednew file mode 100644 9 +import type { ExtensionAPI, ExtensionContext }
from "@mariozechner/pi-coding-agent";
11 +const LEVEL_COLORS
: Record<
string,
string>
= {
13 + minimal:
"thinkingMinimal",
15 + medium:
"thinkingMedium",
16 + high:
"thinkingHigh",
17 + xhigh:
"thinkingXhigh",
20 +const LEVEL_LABELS
: Record<
string,
string>
= {
22 + minimal:
"think:min",
24 + medium:
"think:med",
26 + xhigh:
"think:xhigh",
31 +export default function thinkingExtension(pi
: ExtensionAPI) {
32 + let timer
: ReturnType<
typeof setInterval>
| null = null;
36 + const emit = ()
=> {
37 + const level
= pi.
getThinkingLevel?.()
?? "off";
38 + if (level
=== lastLevel)
return;
41 + pi.events.
emit(
"footer:segment", {
43 + text: LEVEL_LABELS[level]
?? `think:${level}`,
44 + color: LEVEL_COLORS[level]
?? "muted",
50 + pi.
on(
"session_start",
async (_e, ctx)
=> {
56 + timer
= setInterval(emit, POLL_MS);
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 });
pi/agent/extensions/timing/index.ts
Addednew file mode 100644 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);
16 + return rs
> 0 ? `${m}m${rs}s` : `${m}m`;
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;
31 + const getAgentMs = (now
: number)
: number | null => {
32 + if (agentStart
!== null)
return now
- agentStart;
36 + const getTurnMs = (now
: number)
: number => {
37 + let total
= turnAccumMs;
38 + if (turnStart
!== null) total
+= now
- turnStart;
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;
53 + pi.events.
emit(
"footer:segment", {
55 + text:
`⏱ ${fmtMin(agent)} turn · ${fmtMin(session)} session`,
62 + const startPoll = ()
=> {
64 + timer
= setInterval(emit, POLL_MS);
67 + const stopPoll = ()
=> {
68 + if (timer) {
clearInterval(timer); timer
= null; }
71 + const finalizeTurn = ()
=> {
72 + if (turnStart
!== null) {
73 + turnAccumMs
+= Date.
now()
- turnStart;
78 + pi.
on(
"session_start",
async (_e, ctx)
=> {
81 + sessionStart
= Date.
now();
89 + pi.
on(
"agent_start",
async ()
=> {
92 + agentStart
= Date.
now();
98 + pi.
on(
"turn_start",
async ()
=> {
100 + turnStart
= Date.
now();
103 + pi.
on(
"turn_end",
async ()
=> finalizeTurn());
105 + pi.
on(
"agent_end",
async ()
=> {
106 + if (
!hasUI)
return;
108 + if (agentStart
!== null) {
109 + lastAgentMs
= Date.
now()
- agentStart;
116 + pi.
on(
"session_shutdown",
async ()
=> {
118 + pi.events.
emit(
"footer:segment", { id:
"timing", text:
undefined });