repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi(ext/runtime): update runtime extension

0bf9702ca05e1c1727c8874d976c5e1d4542f9ef

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

pi/agent/extensions/TODO.md

Modified
3 3 # TODO
5 5 ## Extensions
7 7 - [ ] Port vibeguard plugin from opencode — extend with env var support
8 -- [ ] Port agent identity plugin from opencode
9 -- [ ] Port model announcer plugin from opencode
10 -- [ ] Allow starting pi with a predefined list of extensions
11 -- [ ] Define a directory for optional, on-demand extensions
12 -- [ ] thinking: look for ways, to render useful stuff from think stream into thinking label
14 -## Configuration
16 -- [x] Move all settings into `settings.json`
17 - - `ui.json` → `settings.ui`
18 - - `animations.json` → `settings.animations`
19 - - `ghost.json` → `settings.ghost` (global); project-level `<cwd>/.pi/ghost.json` still overrides
20 - - `costs.json` → removed (cost tracking simplified to live session data)
21 -- [x] State persistence utility — `state.ts` (loadState/saveState under `~/.pi/agent/state/`)
22 - - Not yet adopted by any extension (animation state not prioritized)
23 -- [x] taint-guard allowlist — uses `settings.ts` utility, reads from `settings.taint.taintAllowlist`
8 +- [ ] Port agent identity plugin from opencode?
9 +- [ ] Port model announcer plugin from opencode?
10 +- [ ] Implement extensions from optional/, by default off.
11 + can enable in config or flag
12 +- [ ] simplify remember and enhance:
13 + pipe to model, when creating new, amend by default, merge actions into widget
14 +- [ ] fix todo.ts:
15 + widget not in sync
16 +- [ ] fix cost.ts:
17 + monthly cost not shown
25 19 ## TUI
27 21 - [ ] More emphasized user messages in the TUI
28 -- [x] Remove monkey patching from ui/ (patchUserMessageComponent deleted)
29 -- [x] Remove StyledEditor (was fragile, editor padding available via settings.editorPaddingX)
30 -- [x] Remove monthly cost accumulation (session cost computed live from message.usage.cost.total)
32 -## Notify Events
34 -- [x] `notify:send` event — payload: `{ message, severity?, source? }`
35 -- [x] `notify.ts` — clean listener, emits native terminal notification + `notify:ui` relay
36 -- [x] `permissions.ts` — emits `notify:send` for all bash commands
37 -- [x] `taint-guard.ts` — emits `notify:send` on block/warn; fixed "Allow all" stale-flag bug
38 -- [x] Fixed typo: `bugabinga:notify` → `notify:send`

pi/agent/extensions/runtime/index.ts

Modified
2 2 * Runtime detection footer segment producer.
4 - * Detects project language runtime from config files and emits
5 - * a footer:segment with zone "workspace".
4 + * Detects project language runtime from config files in cwd or parents
5 + * under $HOME and emits a footer:segment with zone "workspace".
8 8 import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
9 9 import { execFile } from "node:child_process";
10 -import { existsSync, readdirSync } from "node:fs";
11 -import { join } from "node:path";
10 +import { readdir, realpath } from "node:fs/promises";
11 +import { dirname, isAbsolute, relative, resolve } from "node:path";
12 12 import { promisify } from "node:util";
14 14 const execFileAsync = promisify(execFile);
15 16 const VERSION_TIMEOUT_MS = 2500;
17 +const SEGMENT_ID = "runtime";
18 +const SEGMENT_ZONE = "workspace";
19 +const SEGMENT_ORDER = 3;
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> };
21 +const RUNTIME_FILES = {
22 + bun: ["bun.lock", "bun.lockb"],
23 + deno: ["deno.json", "deno.jsonc", "deno.lock"],
24 + lua: ["stylua.toml", ".stylua.toml", ".luarc.json", ".luarc.jsonc", "init.lua"],
25 + nodejs: ["package.json", ".nvmrc", ".node-version"],
26 + python: ["pyproject.toml", "requirements.txt", "setup.py", "setup.cfg", "Pipfile", ".python-version"],
27 + golang: ["go.mod"],
28 + rust: ["Cargo.toml"],
29 + java: ["pom.xml", "build.gradle", "build.gradle.kts"],
30 + ruby: ["Gemfile", ".ruby-version"],
31 + php: ["composer.json"],
32 +} as const;
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));
34 +type RuntimeName = keyof typeof RUNTIME_FILES;
35 +type DirEntries = { names: readonly string[]; set: ReadonlySet<string> };
36 +type RuntimeInfo = { name: RuntimeName; icon: string; version?: string };
37 +type RuntimeDef = {
38 + name: RuntimeName;
39 + icon: string;
40 + files: readonly string[];
41 + entries?: readonly string[];
42 + suffixes?: readonly string[];
43 + version: () => Promise<string | undefined>;
44 +};
23 -async function runVer(cmd: string, args: string[] = [], cwd?: string): Promise<string | undefined> {
46 +async function commandOutput(cmd: string, args: readonly string[] = []): Promise<string | undefined> {
24 47 try {
25 - const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, timeout: VERSION_TIMEOUT_MS });
48 + const { stdout, stderr } = await execFileAsync(cmd, [...args], { timeout: VERSION_TIMEOUT_MS });
26 49 const text = `${stdout}\n${stderr}`.trim();
27 50 return text || undefined;
28 51 } catch { return undefined; }
31 -function pv(v?: string) { return v?.startsWith("v") ? v : v ? `v${v}` : undefined; }
54 +function prefixedVersion(version?: string): string | undefined {
55 + if (!version) return undefined;
56 + return version.startsWith("v") ? version : `v${version}`;
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]) },
59 +async function exactVersion(cmd: string, args: readonly string[] = []): Promise<string | undefined> {
60 + return prefixedVersion(await commandOutput(cmd, args));
63 +async function matchedVersion(cmd: string, args: readonly string[], regex: RegExp): Promise<string | undefined> {
64 + return prefixedVersion((await commandOutput(cmd, args))?.match(regex)?.[1]);
67 +async function firstMatchedVersion(commands: readonly [string, readonly string[], RegExp][]): Promise<string | undefined> {
68 + for (const [cmd, args, regex] of commands) {
69 + const version = await matchedVersion(cmd, args, regex);
70 + if (version) return version;
71 + }
72 + return undefined;
75 +async function canonicalPath(path: string): Promise<string> {
76 + try { return await realpath(path); } catch { return resolve(path); }
79 +function isInside(path: string, root: string): boolean {
80 + const rel = relative(root, path);
81 + return rel === "" || (!!rel && !rel.startsWith("..") && !isAbsolute(rel));
84 +async function searchDirs(cwd: string): Promise<string[]> {
85 + const start = await canonicalPath(cwd);
86 + const homeRaw = process.env.HOME;
87 + if (!homeRaw) return [start];
89 + const home = await canonicalPath(homeRaw);
90 + if (!isInside(start, home)) return [start];
92 + const dirs: string[] = [];
93 + let dir = start;
95 + while (true) {
96 + dirs.push(dir);
97 + if (dir === home) return dirs;
99 + const parent = dirname(dir);
100 + if (parent === dir || !isInside(parent, home)) return dirs;
101 + dir = parent;
105 +const runtimes: readonly RuntimeDef[] = [
106 + { name: "bun", icon: "", files: RUNTIME_FILES.bun, version: () => exactVersion("bun", ["--version"]) },
107 + { name: "deno", icon: "", files: RUNTIME_FILES.deno, version: () => matchedVersion("deno", ["--version"], /deno\s+([0-9][^\s]*)/i) },
108 + { name: "lua", icon: "", files: RUNTIME_FILES.lua, entries: ["lua"], suffixes: [".lua"], version: () => firstMatchedVersion([
109 + ["lua", ["-v"], /Lua\s+([0-9][^\s]*)/i],
110 + ["luajit", ["-v"], /LuaJIT\s+([0-9][^\s]*)/i],
111 + ]) },
112 + { name: "nodejs", icon: "", files: RUNTIME_FILES.nodejs, version: () => exactVersion("node", ["--version"]) },
113 + { name: "python", icon: "", files: RUNTIME_FILES.python, version: () => firstMatchedVersion([
114 + ["python3", ["--version"], /Python\s+([0-9][^\s]*)/i],
115 + ["python", ["--version"], /Python\s+([0-9][^\s]*)/i],
116 + ]) },
117 + { name: "golang", icon: "", files: RUNTIME_FILES.golang, version: () => matchedVersion("go", ["version"], /go version go([0-9][^\s]*)/i) },
118 + { name: "rust", icon: "", files: RUNTIME_FILES.rust, version: () => matchedVersion("rustc", ["--version"], /rustc\s+([0-9][^\s]*)/i) },
119 + { name: "java", icon: "", files: RUNTIME_FILES.java, version: () => matchedVersion("java", ["-version"], /"([0-9][^"]*)"/) },
120 + { name: "ruby", icon: "", files: RUNTIME_FILES.ruby, version: () => matchedVersion("ruby", ["--version"], /ruby\s+([0-9][^\s]*)/i) },
121 + { name: "php", icon: "", files: RUNTIME_FILES.php, version: () => matchedVersion("php", ["--version"], /PHP\s+([0-9][^\s]*)/i) },
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",
124 +const RUNTIME_COLORS: Record<RuntimeName, string> = {
125 + nodejs: "success",
126 + deno: "syntaxType",
127 + golang: "syntaxType",
128 + bun: "warning",
129 + python: "warning",
130 + java: "warning",
131 + rust: "error",
132 + ruby: "error",
133 + lua: "accent",
134 + php: "accent",
53 -async function detect(cwd: string): Promise<RuntimeInfo | undefined> {
54 - let entries: string[] = [];
55 - try { entries = readdirSync(cwd); } catch { /* not a dir */ }
137 +async function entriesFor(dir: string): Promise<DirEntries> {
138 + try {
139 + const names = await readdir(dir);
140 + return { names, set: new Set(names) };
141 + } catch { return { names: [], set: new Set() }; }
144 +function matchesRuntime(rt: RuntimeDef, entries: DirEntries): boolean {
145 + if (rt.files.some((file) => entries.set.has(file))) return true;
146 + if (rt.entries?.some((entry) => entries.set.has(entry))) return true;
147 + if (rt.suffixes?.some((suffix) => entries.names.some((entry) => entry.endsWith(suffix)))) return true;
148 + return false;
151 +async function detectInDir(dir: string): Promise<RuntimeInfo | undefined> {
152 + const entries = await entriesFor(dir);
56 153 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 - }
154 + if (!matchesRuntime(rt, entries)) continue;
155 + return { name: rt.name, icon: rt.icon, version: await rt.version() };
157 + return undefined;
160 +async function detect(cwd: string): Promise<RuntimeInfo | undefined> {
161 + for (const dir of await searchDirs(cwd)) {
162 + const rt = await detectInDir(dir);
163 + if (rt) return rt;
61 165 return undefined;
66 170 let hasUI = false;
67 171 let refreshInFlight = false;
69 - const refresh = async () => {
173 + async function refresh() {
70 174 if (!hasUI || refreshInFlight) return;
71 175 refreshInFlight = true;
72 177 try {
73 178 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 });
179 + if (!rt) {
180 + pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
181 + return;
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(); });
184 + pi.events.emit("footer:segment", {
185 + id: SEGMENT_ID,
186 + icon: rt.icon,
187 + text: rt.version ?? rt.name,
188 + color: RUNTIME_COLORS[rt.name],
189 + zone: SEGMENT_ZONE,
190 + order: SEGMENT_ORDER,
191 + });
192 + } finally {
193 + refreshInFlight = false;
197 + pi.on("session_start", async (_e, ctx) => {
198 + hasUI = ctx.hasUI;
199 + currentCwd = ctx.cwd;
200 + refresh();
201 + });
203 + pi.on("agent_end", async () => refresh());