repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi: add extension footer fallbacks

517ba54e1ecdaeb7de9d2d15f96f59e793668960

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (9)

pi/AGENTS.md

Modified
25 25 Prefer `peerDependencies` for Pi packages (`@earendil-works/*`).
26 26 Run `bun install` after any structural change.
28 +## Independence
30 +- Extensions must be standalone packages.
31 +- Never import from another `@bugabinga/pi-ext-*` package.
32 +- Optional integration must be capability/event based and degrade cleanly.
33 +- If behavior is important, provide a native fallback; decorative integration may no-op.
35 +## Publishing
37 +- Source of truth for release gates: `justfile` → `scripts/extensions.py`.
38 +- Run `just check [{name}]` before `npm publish`.
39 +- License is MIT.
41 +## Documentation
43 +- READMEs must be terse.
44 +- Do not duplicate source-of-truth docs/config/API details.
45 +- Link to canonical source files, commands, settings, or upstream docs instead.
46 +- Package README should answer: what, install/load, commands/tools, settings link, optional integrations.
28 48 ## Imports
30 50 | Package | Provides | Use |

pi/agent/extensions/context-size/index.ts

Modified
5 5 ThemeColor,
6 6 } from "@earendil-works/pi-coding-agent";
8 +const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
9 +const STATUS_ID = "context-size";
8 11 const FOOTER_SEGMENT = {
9 12 id: "context-size",
10 13 icon: "",
41 44 color: ThemeColor;
47 +function hasFooter(): boolean {
48 + const footer = (globalThis as any)[FOOTER_KEY];
49 + return footer?.loaded === true && footer.version >= 1;
44 52 function clamp(value: number, min: number, max: number): number {
45 53 return Math.min(max, Math.max(min, value));
98 106 pi.events.emit("footer:segment", { id: FOOTER_SEGMENT.id, text: undefined });
109 + function clearPublished(ctx: ExtensionContext) {
110 + clearSegment();
111 + ctx.ui.setStatus(STATUS_ID, undefined);
101 114 function updateSegment(ctx: ExtensionContext) {
103 116 if (!ctx.hasUI) return;
105 118 const usage = ctx.getContextUsage();
106 119 if (!usage) {
107 - clearSegment();
120 + clearPublished(ctx);
108 121 return;
111 124 const view = buildSegment(ctx, usage);
112 - pi.events.emit("footer:segment", {
113 - ...FOOTER_SEGMENT,
114 - text: view.text,
115 - color: view.color,
116 - });
125 + if (hasFooter()) {
126 + ctx.ui.setStatus(STATUS_ID, undefined);
127 + pi.events.emit("footer:segment", {
128 + ...FOOTER_SEGMENT,
129 + text: view.text,
130 + color: view.color,
131 + });
132 + return;
135 + clearSegment();
136 + ctx.ui.setStatus(STATUS_ID, view.text);
117 137 } catch {
118 138 // Ignore late events during reload/switch/shutdown; Pi marks old ctx/pi stale.
123 143 pi.on(eventName, async (_event, ctx) => updateSegment(ctx));
146 + pi.on("session_shutdown", async (_event, ctx) => {
147 + if (ctx.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
148 + });
126 150 // Footer owns its own teardown. Emitting through `pi.events` during session_shutdown
127 151 // can trip Pi's stale-context guard after reload/switch.

pi/agent/extensions/cost/index.ts

Modified
15 15 // ── Constants ─────────────────────────────────────────────────────────────
17 +const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
18 +const STATUS_ID = "cost";
17 19 const PRICE_UNIT_TOKENS = 1_000_000;
18 20 const COUNT_DECIMAL_THRESHOLD = 1_000;
19 21 const COUNT_ROUND_THRESHOLD = 10_000;
71 73 type SegmentId = "model" | "tokens" | "cost";
75 +// ── Footer capability ─────────────────────────────────────────────────────
77 +function hasFooter(): boolean {
78 + const footer = (globalThis as any)[FOOTER_KEY];
79 + return footer?.loaded === true && footer.version >= 1;
73 82 // ── Pricing ───────────────────────────────────────────────────────────────
75 84 // Prices per 1M tokens. Used only when providers report $0 cost.
270 -function emitSnapshot(pi: ExtensionAPI, snapshot: Snapshot) {
271 - emitSegment(pi, "model", snapshot.modelLabel);
272 - emitSegment(pi, "tokens", tokenLabel(snapshot.usage));
273 - emitSegment(pi, "cost", costLabel(snapshot));
279 +function statusLabel(snapshot: Snapshot): string {
280 + return [snapshot.modelLabel, tokenLabel(snapshot.usage), costLabel(snapshot)]
281 + .filter((part): part is string => !!part)
282 + .join(" · ");
285 +function publishSnapshot(pi: ExtensionAPI, ctx: ExtensionContext, snapshot: Snapshot) {
286 + if (hasFooter()) {
287 + ctx.ui.setStatus(STATUS_ID, undefined);
288 + emitSegment(pi, "model", snapshot.modelLabel);
289 + emitSegment(pi, "tokens", tokenLabel(snapshot.usage));
290 + emitSegment(pi, "cost", costLabel(snapshot));
291 + return;
294 + clearSegments(pi);
295 + ctx.ui.setStatus(STATUS_ID, statusLabel(snapshot));
276 298 function clearSegments(pi: ExtensionAPI) {
279 301 emitSegment(pi, "cost", undefined);
304 +function clearPublished(pi: ExtensionAPI, ctx?: ExtensionContext) {
305 + clearSegments(pi);
306 + if (ctx?.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
282 309 // ── Snapshot ──────────────────────────────────────────────────────────────
284 311 function buildSnapshot(ctx: ExtensionContext, previousSessionCost: number, monthlyCost: number): Snapshot {
325 352 if (nextSignature === lastSignature) return;
326 353 lastSignature = nextSignature;
328 - emitSnapshot(pi, snapshot);
355 + publishSnapshot(pi, ctx, snapshot);
331 358 async function syncBestEffort(ctx: ExtensionContext) {
360 - pi.on("session_shutdown", async () => {
361 - clearSegments(pi);
387 + pi.on("session_shutdown", async (_event, ctx) => {
388 + clearPublished(pi, ctx);

pi/agent/extensions/footer/index.ts

Modified
8 8 * line 3 = extension statuses via ctx.ui.setStatus()
10 10 * Producers use semantic zones ("workspace" | "llm"). Footer decides row mapping.
11 + * Publishes a process-global capability flag so producers can choose footer
12 + * segments over ctx.ui.setStatus() fallbacks without ping events.
11 13 * Uses setFooter() — the single footer owner. Producers are decoupled.
13 15 * /footer or ctrl+alt+f toggles visibility by swapping between
21 23 // ── Constants ─────────────────────────────────────────────────────
25 +const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
23 26 const SEPARATOR_COLOR = "borderMuted" as ThemeColor;
24 27 const DEFAULT_SEGMENT_COLOR = "muted" as ThemeColor;
25 28 const STATUS_COLOR = "dim" as ThemeColor;
29 32 // ── Types ─────────────────────────────────────────────────────────
34 +type FooterGlobal = {
35 + version: 1;
36 + loaded: boolean;
37 +};
31 39 type FooterZone = "workspace" | "llm";
33 41 type Segment = {
67 75 // ── Extension ─────────────────────────────────────────────────────
69 77 export default function footerExtension(pi: ExtensionAPI) {
78 + const state: FooterGlobal = { version: 1, loaded: true };
79 + (globalThis as any)[FOOTER_KEY] = state;
70 81 const segments = new Map<string, Segment>();
71 82 let requestRender: (() => void) | undefined;
72 83 let renderScheduled = false;
281 292 mountFooter();
284 - pi.on("session_shutdown", async () => {
295 + pi.on("session_shutdown", async (event) => {
296 + if (event.reason === "quit" || event.reason === "reload") state.loaded = false;
285 297 segments.clear();
286 298 requestRender = undefined;
287 299 currentCtx = undefined;

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

Modified
10 10 import { promisify } from "node:util";
12 12 const execFileAsync = promisify(execFile);
13 +const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
14 +const CWD_STATUS_ID = "cwd";
15 +const GIT_STATUS_ID = "git";
14 17 type GitStatus = {
15 18 branch?: string;
30 33 modified: "!", staged: "+", renamed: "»", deleted: "✘",
36 +function hasFooter(): boolean {
37 + const footer = (globalThis as any)[FOOTER_KEY];
38 + return footer?.loaded === true && footer.version >= 1;
33 41 function parsePorcelain(stdout: string, hasStash: boolean): GitStatus {
34 42 const s: GitStatus = { branch: undefined, ahead: 0, behind: 0, conflicted: 0, untracked: 0, stashed: false, modified: 0, staged: 0, renamed: 0, deleted: 0 };
35 43 s.stashed = hasStash;
75 83 } catch { return empty; }
78 -function emitGit(pi: ExtensionAPI, cwd: string, status: GitStatus) {
86 +function gitLabel(status: GitStatus): string | undefined {
87 + if (!status.branch) return undefined;
88 + const allStatus = [
89 + status.conflicted > 0 ? ICONS.conflicted : "",
90 + status.stashed ? ICONS.stashed : "",
91 + status.deleted > 0 ? ICONS.deleted : "",
92 + status.renamed > 0 ? ICONS.renamed : "",
93 + status.modified > 0 ? ICONS.modified : "",
94 + status.staged > 0 ? ICONS.staged : "",
95 + status.untracked > 0 ? ICONS.untracked : "",
96 + ].join("");
97 + const ab = status.ahead > 0 && status.behind > 0 ? ICONS.diverged
98 + : status.ahead > 0 ? ICONS.ahead
99 + : status.behind > 0 ? ICONS.behind : "";
100 + const statusBlock = allStatus || ab ? `[${allStatus}${ab}]` : "";
101 + return `${status.branch}${statusBlock ? ` ${statusBlock}` : ""}`;
104 +function clearSegments(pi: ExtensionAPI) {
105 + pi.events.emit("footer:segment", { id: "cwd", text: undefined });
106 + pi.events.emit("footer:segment", { id: "git-branch", text: undefined });
109 +function emitGit(pi: ExtensionAPI, ctx: ExtensionContext, status: GitStatus) {
79 110 const home = process.env.HOME;
80 - const path = home && cwd.startsWith(home) ? `~${cwd.slice(home.length)}` : cwd;
111 + const path = home && ctx.cwd.startsWith(home) ? `~${ctx.cwd.slice(home.length)}` : ctx.cwd;
112 + const branch = gitLabel(status);
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 });
114 + if (hasFooter()) {
115 + ctx.ui.setStatus(CWD_STATUS_ID, undefined);
116 + ctx.ui.setStatus(GIT_STATUS_ID, undefined);
117 + pi.events.emit("footer:segment", { id: "cwd", text: path, icon: "󰝰", color: "syntaxOperator", zone: "workspace", order: 0 });
118 + if (branch) {
119 + pi.events.emit("footer:segment", {
120 + id: "git-branch",
121 + text: branch,
122 + icon: ICONS.git,
123 + color: "syntaxKeyword",
124 + zone: "workspace",
125 + order: 1,
126 + });
127 + } else {
128 + pi.events.emit("footer:segment", { id: "git-branch", text: undefined });
130 + return;
133 + clearSegments(pi);
134 + ctx.ui.setStatus(CWD_STATUS_ID, path);
135 + ctx.ui.setStatus(GIT_STATUS_ID, branch);
113 138 export default function gitStatusExtension(pi: ExtensionAPI) {
114 139 let currentCwd = "";
140 + let currentCtx: ExtensionContext | undefined;
115 141 let hasUI = false;
116 142 let refreshInFlight = false;
117 143 let refreshPending = false;
119 145 const refresh = async () => {
120 - if (!hasUI || refreshInFlight) { refreshPending = true; return; }
146 + if (!hasUI || !currentCtx || refreshInFlight) { refreshPending = true; return; }
147 + const ctx = currentCtx;
121 148 refreshInFlight = true;
123 150 const status = await readGitStatus(currentCwd);
124 - emitGit(pi, currentCwd, status);
151 + emitGit(pi, ctx, status);
125 152 } finally {
126 153 refreshInFlight = false;
127 154 if (refreshPending) { refreshPending = false; refresh(); }
131 - pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; currentCwd = ctx.cwd; refresh(); });
158 + pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; currentCwd = ctx.cwd; currentCtx = ctx; refresh(); });
132 159 pi.on("agent_end", async () => { if (hasUI) refresh(); });
133 160 pi.on("tool_execution_end", async () => { if (hasUI) refresh(); });
161 + pi.on("session_shutdown", async (_e, ctx) => {
162 + clearSegments(pi);
163 + if (ctx.hasUI) {
164 + ctx.ui.setStatus(CWD_STATUS_ID, undefined);
165 + ctx.ui.setStatus(GIT_STATUS_ID, undefined);
167 + currentCtx = undefined;
168 + });

pi/agent/extensions/quota/index.ts

Modified
10 10 import { join } from "node:path";
11 11 import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
13 +const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
14 +const STATUS_ID = "quota";
13 16 // ── Types ─────────────────────────────────────────────────────────────────
15 18 interface MinimaxResponse {
246 249 return used < 50 ? "accent" : used < 80 ? "warning" : "error";
252 +function hasFooter(): boolean {
253 + const footer = (globalThis as any)[FOOTER_KEY];
254 + return footer?.loaded === true && footer.version >= 1;
249 257 // ── Extension ─────────────────────────────────────────────────────────────
251 259 export default function usageExtension(pi: ExtensionAPI) {
347 355 footerIds.clear();
358 + function quotaStatusLabel(ctx: ExtensionContext): string | undefined {
359 + const active = activeProvider(ctx);
360 + const rows = providers
361 + .filter(p => p.fiveH.total > 0)
362 + .filter(p => !active || p.name.startsWith(active))
363 + .map(p => {
364 + const used = Math.round((p.fiveH.used / p.fiveH.total) * 100);
365 + const label = p.name.split(" ")[0];
366 + const reset = fmtReset(p.fiveH.resetAt);
367 + return `${label} ${used}%${reset ? ` ↻${reset}` : ""}`;
368 + });
369 + return rows.length > 0 ? rows.join(" · ") : undefined;
350 372 function updateFooter(ctx: ExtensionContext) {
351 373 const active = activeProvider(ctx);
375 + if (!hasFooter()) {
376 + clearFooter();
377 + ctx.ui.setStatus(STATUS_ID, quotaStatusLabel(ctx));
378 + return;
381 + ctx.ui.setStatus(STATUS_ID, undefined);
352 382 const seen = new Set<string>();
354 384 for (const p of providers.filter(p => p.fiveH.total > 0)) {
444 474 // ── Events ─────────────────────────────────────────────────────────────
446 476 pi.on("session_start", async (_e, ctx) => {
447 - fetchedAt = 0; widgetVisible = false; clearFooter();
477 + fetchedAt = 0; widgetVisible = false; clearFooter(); ctx.ui.setStatus(STATUS_ID, undefined);
448 478 try { await getOrFetch(ctx); updateFooter(ctx); }
449 - catch { if (!providers.length) clearFooter(); }
479 + catch { if (!providers.length) { clearFooter(); ctx.ui.setStatus(STATUS_ID, undefined); } }
452 482 pi.on("agent_start", async (_e, ctx) => updateFooter(ctx));
459 489 stopRefresh();
460 490 widgetVisible = false;
461 491 clearFooter();
492 + ctx.ui.setStatus(STATUS_ID, undefined);
462 493 ctx.ui.setWidget("usage", undefined);

pi/agent/extensions/runtime/index.ts

Modified
5 5 * under $HOME and emits a footer:segment with zone "workspace".
8 -import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8 +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
9 9 import { execFile } from "node:child_process";
10 10 import { readdir, realpath } from "node:fs/promises";
11 11 import { dirname, isAbsolute, relative, resolve } from "node:path";
14 14 const execFileAsync = promisify(execFile);
16 +const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
16 17 const VERSION_TIMEOUT_MS = 2500;
17 18 const SEGMENT_ID = "runtime";
19 +const STATUS_ID = "runtime";
18 20 const SEGMENT_ZONE = "workspace";
19 21 const SEGMENT_ORDER = 3;
43 45 version: () => Promise<string | undefined>;
48 +function hasFooter(): boolean {
49 + const footer = (globalThis as any)[FOOTER_KEY];
50 + return footer?.loaded === true && footer.version >= 1;
46 53 async function commandOutput(cmd: string, args: readonly string[] = []): Promise<string | undefined> {
47 54 try {
48 55 const { stdout, stderr } = await execFileAsync(cmd, [...args], { timeout: VERSION_TIMEOUT_MS });
168 175 export default function runtimeExtension(pi: ExtensionAPI) {
169 176 let currentCwd = "";
177 + let currentCtx: ExtensionContext | undefined;
170 178 let hasUI = false;
171 179 let refreshInFlight = false;
181 + function clearSegment() {
182 + pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
173 185 async function refresh() {
174 - if (!hasUI || refreshInFlight) return;
186 + if (!hasUI || !currentCtx || refreshInFlight) return;
187 + const ctx = currentCtx;
175 188 refreshInFlight = true;
178 191 const rt = await detect(currentCwd);
179 192 if (!rt) {
180 - pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
193 + clearSegment();
194 + ctx.ui.setStatus(STATUS_ID, undefined);
181 195 return;
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 - });
198 + const text = rt.version ?? rt.name;
199 + if (hasFooter()) {
200 + ctx.ui.setStatus(STATUS_ID, undefined);
201 + pi.events.emit("footer:segment", {
202 + id: SEGMENT_ID,
203 + icon: rt.icon,
204 + text,
205 + color: RUNTIME_COLORS[rt.name],
206 + zone: SEGMENT_ZONE,
207 + order: SEGMENT_ORDER,
208 + });
209 + return;
212 + clearSegment();
213 + ctx.ui.setStatus(STATUS_ID, `${rt.icon} ${text}`);
192 214 } finally {
193 215 refreshInFlight = false;
197 219 pi.on("session_start", async (_e, ctx) => {
198 220 hasUI = ctx.hasUI;
199 221 currentCwd = ctx.cwd;
222 + currentCtx = ctx;
200 223 refresh();
203 226 pi.on("agent_end", async () => refresh());
227 + pi.on("session_shutdown", async (_e, ctx) => {
228 + clearSegment();
229 + if (ctx.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
230 + currentCtx = undefined;
231 + });

pi/justfile

Added
new file mode 100644
1 +_default:
2 + python3 scripts/extensions.py list
4 +check ext="":
5 + python3 scripts/extensions.py check {{ ext }}
7 +fmt:
8 + just --fmt

pi/scripts/extensions.py

Added
new file mode 100755
1 +#!/usr/bin/env python3
2 +"""Pi extension package workflow."""
4 +from __future__ import annotations
6 +import argparse
7 +import json
8 +import re
9 +import shutil
10 +import subprocess
11 +import sys
12 +import tempfile
13 +from pathlib import Path
15 +ROOT = Path(__file__).resolve().parents[1]
16 +EXT_ROOT = ROOT / "agent" / "extensions"
17 +PI_PEERS = {
18 + "@earendil-works/pi-ai",
19 + "@earendil-works/pi-agent-core",
20 + "@earendil-works/pi-coding-agent",
21 + "@earendil-works/pi-tui",
22 + "typebox",
24 +IMPORT_RE = re.compile(r"(?:import|export)\s+(?:[^'\"]+?\s+from\s+)?['\"]([^'\"]+)['\"]|import\(['\"]([^'\"]+)['\"]\)")
25 +SECRET_RE = re.compile(r"(api[_-]?key|secret|token|password)\s*[:=]\s*['\"][^'\"]{12,}", re.I)
28 +def pkg_name(spec: str) -> str:
29 + if spec.startswith("@"):
30 + parts = spec.split("/")
31 + return "/".join(parts[:2])
32 + return spec.split("/")[0]
35 +def read_pkg(ext: Path) -> dict:
36 + return json.loads((ext / "package.json").read_text())
39 +def ext_dirs(selected: list[str]) -> list[Path]:
40 + dirs = sorted(p.parent for p in EXT_ROOT.glob("*/package.json"))
41 + if not selected:
42 + return dirs
44 + wanted = set(selected)
45 + result = []
46 + for ext in dirs:
47 + pkg = read_pkg(ext)
48 + if ext.name in wanted or pkg.get("name") in wanted:
49 + result.append(ext)
51 + found = {ext.name for ext in result} | {read_pkg(ext).get("name") for ext in result}
52 + missing = wanted - found
53 + if missing:
54 + raise SystemExit(f"unknown extension(s): {', '.join(sorted(missing))}")
55 + return result
58 +def ts_files(ext: Path) -> list[Path]:
59 + return sorted(p for p in ext.rglob("*.ts") if "node_modules" not in p.parts)
62 +def import_specs(ext: Path) -> set[str]:
63 + specs: set[str] = set()
64 + for file in ts_files(ext):
65 + for match in IMPORT_RE.finditer(file.read_text(errors="ignore")):
66 + spec = match.group(1) or match.group(2)
67 + if spec:
68 + specs.add(spec)
69 + return specs
72 +def err(errors: list[str], ext: Path, msg: str) -> None:
73 + errors.append(f"{ext.name}: {msg}")
76 +def static_check(ext: Path) -> list[str]:
77 + errors: list[str] = []
78 + try:
79 + pkg = read_pkg(ext)
80 + except Exception as e:
81 + return [f"{ext.name}: invalid package.json: {e}"]
83 + expected = f"@bugabinga/pi-ext-{ext.name}"
84 + if pkg.get("name") != expected:
85 + err(errors, ext, f"package name must be {expected!r}")
86 + if pkg.get("type") != "module":
87 + err(errors, ext, "package.json type must be 'module'")
88 + if pkg.get("main") != "index.ts":
89 + err(errors, ext, "package.json main must be 'index.ts'")
90 + if not (ext / "index.ts").exists():
91 + err(errors, ext, "missing index.ts")
93 + if pkg.get("private") is True:
94 + err(errors, ext, "package must not have private:true")
95 + if pkg.get("license") != "MIT":
96 + err(errors, ext, "package license must be MIT")
97 + if not (ext / "README.md").exists():
98 + err(errors, ext, "missing README.md")
100 + deps = pkg.get("dependencies", {}) or {}
101 + peers = pkg.get("peerDependencies", {}) or {}
102 + dev = pkg.get("devDependencies", {}) or {}
104 + for dep in deps:
105 + if dep in PI_PEERS:
106 + err(errors, ext, f"Pi package {dep} belongs in peerDependencies, not dependencies")
107 + if dep.startswith("@bugabinga/pi-ext-"):
108 + err(errors, ext, f"must not depend on sibling extension {dep}")
109 + for dep in peers:
110 + if dep.startswith("@bugabinga/pi-ext-"):
111 + err(errors, ext, f"must not peer-depend on sibling extension {dep}")
113 + specs = import_specs(ext)
114 + packages = {
115 + pkg_name(s)
116 + for s in specs
117 + if not (s.startswith(".") or s.startswith("/") or s.startswith("node:") or s.startswith("bun:"))
120 + for spec in specs:
121 + if spec.startswith("@bugabinga/pi-ext-"):
122 + err(errors, ext, f"must not import sibling extension {spec}")
124 + for file in ts_files(ext):
125 + text = file.read_text(errors="ignore")
126 + for match in IMPORT_RE.finditer(text):
127 + spec = match.group(1) or match.group(2)
128 + if not spec or not spec.startswith("../"):
129 + continue
130 + resolved = (file.parent / spec).resolve()
131 + try:
132 + resolved.relative_to(ext.resolve())
133 + except ValueError:
134 + err(errors, ext, f"cross-extension relative import {spec} in {file.relative_to(ext)}")
135 + if SECRET_RE.search(text):
136 + err(errors, ext, f"possible secret in {file.relative_to(ext)}")
138 + for dep in sorted(packages & PI_PEERS):
139 + if dep not in peers:
140 + err(errors, ext, f"imported {dep} but missing peerDependency")
141 + for dep in sorted(packages - PI_PEERS):
142 + if dep not in deps and dep not in peers and dep not in dev:
143 + err(errors, ext, f"imported external package {dep} but package.json does not declare it")
145 + return errors
148 +def external_deps(pkg: dict) -> list[str]:
149 + deps = set()
150 + for key in ("dependencies", "peerDependencies", "devDependencies"):
151 + deps.update((pkg.get(key) or {}).keys())
152 + return sorted(deps)
155 +def build(ext: Path, out_root: Path) -> None:
156 + pkg = read_pkg(ext)
157 + cmd = ["bun", "build", "index.ts", "--target", "bun", "--outdir", str(out_root / ext.name)]
158 + for dep in external_deps(pkg):
159 + cmd.extend(["--external", dep])
160 + subprocess.run(cmd, cwd=ext, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
163 +def pack_dry(ext: Path) -> None:
164 + proc = subprocess.run(
165 + ["npm", "pack", "--dry-run", "--json"],
166 + cwd=ext,
167 + text=True,
168 + stdout=subprocess.PIPE,
169 + stderr=subprocess.PIPE,
171 + if proc.returncode != 0:
172 + raise subprocess.CalledProcessError(proc.returncode, proc.args, proc.stdout, proc.stderr)
173 + info = json.loads(proc.stdout)[0]
174 + print(f"OK pack {ext.name} ({len(info.get('files', []))} files, {info.get('unpackedSize', 0)} bytes unpacked)")
177 +def cmd_list(selected: list[str]) -> int:
178 + for ext in ext_dirs(selected):
179 + print(f"{ext.name}\t{read_pkg(ext).get('name')}")
180 + return 0
183 +def cmd_check(selected: list[str]) -> int:
184 + dirs = ext_dirs(selected)
185 + errors: list[str] = []
186 + for ext in dirs:
187 + errors.extend(static_check(ext))
188 + if errors:
189 + for e in errors:
190 + print(f"ERROR {e}", file=sys.stderr)
191 + return 1
192 + print(f"OK static {len(dirs)} extension package(s)")
194 + if not shutil.which("bun"):
195 + print("ERROR bun not found", file=sys.stderr)
196 + return 1
197 + if not shutil.which("npm"):
198 + print("ERROR npm not found", file=sys.stderr)
199 + return 1
201 + with tempfile.TemporaryDirectory(prefix="pi-ext-build-") as tmp:
202 + out_root = Path(tmp)
203 + for ext in dirs:
204 + try:
205 + build(ext, out_root)
206 + print(f"OK build {ext.name}")
207 + except subprocess.CalledProcessError as e:
208 + print(f"ERROR build {ext.name}", file=sys.stderr)
209 + if e.stdout:
210 + print(e.stdout, file=sys.stderr)
211 + if e.stderr:
212 + print(e.stderr, file=sys.stderr)
213 + return e.returncode or 1
214 + print(f"OK build {len(dirs)} extension package(s)")
216 + for ext in dirs:
217 + try:
218 + pack_dry(ext)
219 + except subprocess.CalledProcessError as e:
220 + print(f"ERROR pack {ext.name}", file=sys.stderr)
221 + if e.stdout:
222 + print(e.stdout, file=sys.stderr)
223 + if e.stderr:
224 + print(e.stderr, file=sys.stderr)
225 + return e.returncode or 1
226 + print(f"OK pack {len(dirs)} extension package(s)")
227 + return 0
230 +def main() -> int:
231 + parser = argparse.ArgumentParser()
232 + sub = parser.add_subparsers(dest="command", required=True)
233 + list_p = sub.add_parser("list")
234 + list_p.add_argument("extensions", nargs="*")
235 + check_p = sub.add_parser("check")
236 + check_p.add_argument("extensions", nargs="*")
237 + args = parser.parse_args()
239 + if args.command == "list":
240 + return cmd_list(args.extensions)
241 + if args.command == "check":
242 + return cmd_check(args.extensions)
243 + raise AssertionError(args.command)
246 +if __name__ == "__main__":
247 + raise SystemExit(main())