pi: add extension footer fallbacks
b639e94737c9a6f087c8db0531c7a8457c40356d
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: acd5c8e4b447
bugabingas dorkfiles
b639e94737c9a6f087c8db0531c7a8457c40356d
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+492 / −60 text lines
+20 / −0 text lines
## Independence- Extensions must be standalone packages.- Never import from another `@bugabinga/pi-ext-*` package.- Optional integration must be capability/event based and degrade cleanly.- If behavior is important, provide a native fallback; decorative integration may no-op.## Publishing- Source of truth for release gates: `justfile` → `scripts/extensions.py`.- Run `just check [{name}]` before `npm publish`.- License is MIT.## Documentation- READMEs must be terse.- Do not duplicate source-of-truth docs/config/API details.- Link to canonical source files, commands, settings, or upstream docs instead.- Package README should answer: what, install/load, commands/tools, settings link, optional integrations.+30 / −6 text lines
+34 / −7 text lines
function emitSnapshot(pi: ExtensionAPI, snapshot: Snapshot) { emitSegment(pi, "model", snapshot.modelLabel); emitSegment(pi, "tokens", tokenLabel(snapshot.usage)); emitSegment(pi, "cost", costLabel(snapshot));function statusLabel(snapshot: Snapshot): string { return [snapshot.modelLabel, tokenLabel(snapshot.usage), costLabel(snapshot)] .filter((part): part is string => !!part) .join(" · ");}function publishSnapshot(pi: ExtensionAPI, ctx: ExtensionContext, snapshot: Snapshot) { if (hasFooter()) { ctx.ui.setStatus(STATUS_ID, undefined); emitSegment(pi, "model", snapshot.modelLabel); emitSegment(pi, "tokens", tokenLabel(snapshot.usage)); emitSegment(pi, "cost", costLabel(snapshot)); return; } clearSegments(pi); ctx.ui.setStatus(STATUS_ID, statusLabel(snapshot));function buildSnapshot(ctx: ExtensionContext, previousSessionCost: number, monthlyCost: number): Snapshot {+13 / −1 text lines
+68 / −33 text lines
const s: GitStatus = { branch: undefined, ahead: 0, behind: 0, conflicted: 0, untracked: 0, stashed: false, modified: 0, staged: 0, renamed: 0, deleted: 0 };function emitGit(pi: ExtensionAPI, cwd: string, status: GitStatus) {function gitLabel(status: GitStatus): string | undefined { if (!status.branch) return undefined; const allStatus = [ status.conflicted > 0 ? ICONS.conflicted : "", status.stashed ? ICONS.stashed : "", status.deleted > 0 ? ICONS.deleted : "", status.renamed > 0 ? ICONS.renamed : "", status.modified > 0 ? ICONS.modified : "", status.staged > 0 ? ICONS.staged : "", status.untracked > 0 ? ICONS.untracked : "", ].join(""); const ab = status.ahead > 0 && status.behind > 0 ? ICONS.diverged : status.ahead > 0 ? ICONS.ahead : status.behind > 0 ? ICONS.behind : ""; const statusBlock = allStatus || ab ? `[${allStatus}${ab}]` : ""; return `${status.branch}${statusBlock ? ` ${statusBlock}` : ""}`;}function clearSegments(pi: ExtensionAPI) { pi.events.emit("footer:segment", { id: "cwd", text: undefined }); pi.events.emit("footer:segment", { id: "git-branch", text: undefined });}function emitGit(pi: ExtensionAPI, ctx: ExtensionContext, status: GitStatus) { const path = home && cwd.startsWith(home) ? `~${cwd.slice(home.length)}` : cwd; // Cwd segment pi.events.emit("footer:segment", { id: "cwd", text: path, icon: "", color: "syntaxOperator", zone: "workspace", order: 0 }); // Branch + status segment if (status.branch) { const allStatus = [ status.conflicted > 0 ? ICONS.conflicted : "", status.stashed ? ICONS.stashed : "", status.deleted > 0 ? ICONS.deleted : "", status.renamed > 0 ? ICONS.renamed : "", status.modified > 0 ? ICONS.modified : "", status.staged > 0 ? ICONS.staged : "", status.untracked > 0 ? ICONS.untracked : "", ].join(""); const ab = status.ahead > 0 && status.behind > 0 ? ICONS.diverged : status.ahead > 0 ? ICONS.ahead : status.behind > 0 ? ICONS.behind : ""; const statusBlock = allStatus || ab ? `[${allStatus}${ab}]` : ""; pi.events.emit("footer:segment", { id: "git-branch", text: `${status.branch}${statusBlock ? ` ${statusBlock}` : ""}`, icon: ICONS.git, color: "syntaxKeyword", zone: "workspace", order: 1, }); } else { pi.events.emit("footer:segment", { id: "git-branch", text: undefined }); if (hasFooter()) { ctx.ui.setStatus(CWD_STATUS_ID, undefined); ctx.ui.setStatus(GIT_STATUS_ID, undefined); pi.events.emit("footer:segment", { id: "cwd", text: path, icon: "", color: "syntaxOperator", zone: "workspace", order: 0 }); if (branch) { pi.events.emit("footer:segment", { id: "git-branch", text: branch, icon: ICONS.git, color: "syntaxKeyword", zone: "workspace", order: 1, }); } else { pi.events.emit("footer:segment", { id: "git-branch", text: undefined }); } return; let currentCtx: ExtensionContext | undefined; if (!hasUI || refreshInFlight) { refreshPending = true; return; } pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; currentCwd = ctx.cwd; refresh(); }); pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; currentCwd = ctx.cwd; currentCtx = ctx; refresh(); });+33 / −2 text lines
function quotaStatusLabel(ctx: ExtensionContext): string | undefined { const active = activeProvider(ctx); const rows = providers .filter(p => p.fiveH.total > 0) .filter(p => !active || p.name.startsWith(active)) .map(p => { const used = Math.round((p.fiveH.used / p.fiveH.total) * 100); const label = p.name.split(" ")[0]; const reset = fmtReset(p.fiveH.resetAt); return `${label} ${used}%${reset ? ` ↻${reset}` : ""}`; }); return rows.length > 0 ? rows.join(" · ") : undefined; } fetchedAt = 0; widgetVisible = false; clearFooter(); fetchedAt = 0; widgetVisible = false; clearFooter(); ctx.ui.setStatus(STATUS_ID, undefined); catch { if (!providers.length) clearFooter(); } catch { if (!providers.length) { clearFooter(); ctx.ui.setStatus(STATUS_ID, undefined); } } ctx.ui.setStatus(STATUS_ID, undefined);+39 / −11 text lines
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");const STATUS_ID = "runtime";async function commandOutput(cmd: string, args: readonly string[] = []): Promise<string | undefined> { const { stdout, stderr } = await execFileAsync(cmd, [...args], { timeout: VERSION_TIMEOUT_MS }); let currentCtx: ExtensionContext | undefined; if (!hasUI || refreshInFlight) return; pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined }); pi.events.emit("footer:segment", { id: SEGMENT_ID, icon: rt.icon, text: rt.version ?? rt.name, color: RUNTIME_COLORS[rt.name], zone: SEGMENT_ZONE, order: SEGMENT_ORDER, }); const text = rt.version ?? rt.name; if (hasFooter()) { ctx.ui.setStatus(STATUS_ID, undefined); pi.events.emit("footer:segment", { id: SEGMENT_ID, icon: rt.icon, text, color: RUNTIME_COLORS[rt.name], zone: SEGMENT_ZONE, order: SEGMENT_ORDER, }); return; } clearSegment(); ctx.ui.setStatus(STATUS_ID, `${rt.icon} ${text}`); currentCtx = ctx;new file mode 100644+8 / −0 text lines
new file mode 100755+247 / −0 text lines
#!/usr/bin/env python3"""Pi extension package workflow."""from __future__ import annotationsimport argparseimport jsonimport reimport shutilimport subprocessimport sysimport tempfilefrom pathlib import PathROOT = Path(__file__).resolve().parents[1]EXT_ROOT = ROOT / "agent" / "extensions"PI_PEERS = { "@earendil-works/pi-ai", "@earendil-works/pi-agent-core", "@earendil-works/pi-coding-agent", "@earendil-works/pi-tui", "typebox",}IMPORT_RE = re.compile(r"(?:import|export)\s+(?:[^'\"]+?\s+from\s+)?['\"]([^'\"]+)['\"]|import\(['\"]([^'\"]+)['\"]\)")SECRET_RE = re.compile(r"(api[_-]?key|secret|token|password)\s*[:=]\s*['\"][^'\"]{12,}", re.I)def pkg_name(spec: str) -> str: if spec.startswith("@"): parts = spec.split("/") return "/".join(parts[:2]) return spec.split("/")[0]def read_pkg(ext: Path) -> dict: return json.loads((ext / "package.json").read_text())def ext_dirs(selected: list[str]) -> list[Path]: dirs = sorted(p.parent for p in EXT_ROOT.glob("*/package.json")) if not selected: return dirs wanted = set(selected) result = [] for ext in dirs: pkg = read_pkg(ext) if ext.name in wanted or pkg.get("name") in wanted: result.append(ext) found = {ext.name for ext in result} | {read_pkg(ext).get("name") for ext in result} missing = wanted - found if missing: raise SystemExit(f"unknown extension(s): {', '.join(sorted(missing))}") return resultdef ts_files(ext: Path) -> list[Path]: return sorted(p for p in ext.rglob("*.ts") if "node_modules" not in p.parts)def import_specs(ext: Path) -> set[str]: specs: set[str] = set() for file in ts_files(ext): for match in IMPORT_RE.finditer(file.read_text(errors="ignore")): spec = match.group(1) or match.group(2) if spec: specs.add(spec) return specsdef err(errors: list[str], ext: Path, msg: str) -> None: errors.append(f"{ext.name}: {msg}")def static_check(ext: Path) -> list[str]: errors: list[str] = [] try: pkg = read_pkg(ext) except Exception as e: return [f"{ext.name}: invalid package.json: {e}"] expected = f"@bugabinga/pi-ext-{ext.name}" if pkg.get("name") != expected: err(errors, ext, f"package name must be {expected!r}") if pkg.get("type") != "module": err(errors, ext, "package.json type must be 'module'") if pkg.get("main") != "index.ts": err(errors, ext, "package.json main must be 'index.ts'") if not (ext / "index.ts").exists(): err(errors, ext, "missing index.ts") if pkg.get("private") is True: err(errors, ext, "package must not have private:true") if pkg.get("license") != "MIT": err(errors, ext, "package license must be MIT") if not (ext / "README.md").exists(): err(errors, ext, "missing README.md") deps = pkg.get("dependencies", {}) or {} peers = pkg.get("peerDependencies", {}) or {} dev = pkg.get("devDependencies", {}) or {} for dep in deps: if dep in PI_PEERS: err(errors, ext, f"Pi package {dep} belongs in peerDependencies, not dependencies") if dep.startswith("@bugabinga/pi-ext-"): err(errors, ext, f"must not depend on sibling extension {dep}") for dep in peers: if dep.startswith("@bugabinga/pi-ext-"): err(errors, ext, f"must not peer-depend on sibling extension {dep}") specs = import_specs(ext) packages = { pkg_name(s) for s in specs if not (s.startswith(".") or s.startswith("/") or s.startswith("node:") or s.startswith("bun:")) } for spec in specs: if spec.startswith("@bugabinga/pi-ext-"): err(errors, ext, f"must not import sibling extension {spec}") for file in ts_files(ext): text = file.read_text(errors="ignore") for match in IMPORT_RE.finditer(text): spec = match.group(1) or match.group(2) if not spec or not spec.startswith("../"): continue resolved = (file.parent / spec).resolve() try: resolved.relative_to(ext.resolve()) except ValueError: err(errors, ext, f"cross-extension relative import {spec} in {file.relative_to(ext)}") if SECRET_RE.search(text): err(errors, ext, f"possible secret in {file.relative_to(ext)}") for dep in sorted(packages & PI_PEERS): if dep not in peers: err(errors, ext, f"imported {dep} but missing peerDependency") for dep in sorted(packages - PI_PEERS): if dep not in deps and dep not in peers and dep not in dev: err(errors, ext, f"imported external package {dep} but package.json does not declare it") return errorsdef external_deps(pkg: dict) -> list[str]: deps = set() for key in ("dependencies", "peerDependencies", "devDependencies"): deps.update((pkg.get(key) or {}).keys()) return sorted(deps)def build(ext: Path, out_root: Path) -> None: pkg = read_pkg(ext) cmd = ["bun", "build", "index.ts", "--target", "bun", "--outdir", str(out_root / ext.name)] for dep in external_deps(pkg): cmd.extend(["--external", dep]) subprocess.run(cmd, cwd=ext, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)def pack_dry(ext: Path) -> None: proc = subprocess.run( ["npm", "pack", "--dry-run", "--json"], cwd=ext, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) if proc.returncode != 0: raise subprocess.CalledProcessError(proc.returncode, proc.args, proc.stdout, proc.stderr) info = json.loads(proc.stdout)[0] print(f"OK pack {ext.name} ({len(info.get('files', []))} files, {info.get('unpackedSize', 0)} bytes unpacked)")def cmd_list(selected: list[str]) -> int: for ext in ext_dirs(selected): print(f"{ext.name}\t{read_pkg(ext).get('name')}") return 0def cmd_check(selected: list[str]) -> int: dirs = ext_dirs(selected) errors: list[str] = [] for ext in dirs: errors.extend(static_check(ext)) if errors: for e in errors: print(f"ERROR {e}", file=sys.stderr) return 1 print(f"OK static {len(dirs)} extension package(s)") if not shutil.which("bun"): print("ERROR bun not found", file=sys.stderr) return 1 if not shutil.which("npm"): print("ERROR npm not found", file=sys.stderr) return 1 with tempfile.TemporaryDirectory(prefix="pi-ext-build-") as tmp: out_root = Path(tmp) for ext in dirs: try: build(ext, out_root) print(f"OK build {ext.name}") except subprocess.CalledProcessError as e: print(f"ERROR build {ext.name}", file=sys.stderr) if e.stdout: print(e.stdout, file=sys.stderr) if e.stderr: print(e.stderr, file=sys.stderr) return e.returncode or 1 print(f"OK build {len(dirs)} extension package(s)") for ext in dirs: try: pack_dry(ext) except subprocess.CalledProcessError as e: print(f"ERROR pack {ext.name}", file=sys.stderr) if e.stdout: print(e.stdout, file=sys.stderr) if e.stderr: print(e.stderr, file=sys.stderr) return e.returncode or 1 print(f"OK pack {len(dirs)} extension package(s)") return 0def main() -> int: parser = argparse.ArgumentParser() sub = parser.add_subparsers(dest="command", required=True) list_p = sub.add_parser("list") list_p.add_argument("extensions", nargs="*") check_p = sub.add_parser("check") check_p.add_argument("extensions", nargs="*") args = parser.parse_args() if args.command == "list": return cmd_list(args.extensions) if args.command == "check": return cmd_check(args.extensions) raise AssertionError(args.command)if __name__ == "__main__": raise SystemExit(main())