repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi: add extension footer fallbacks

b639e94737c9a6f087c8db0531c7a8457c40356d

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (9)

+492 / −60 text lines

Diff layout

pi/AGENTS.md

Modified

+20 / −0 text lines

2525Prefer `peerDependencies` for Pi packages (`@earendil-works/*`).
2626Run `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.
2848## Imports
3050| Package | Provides | Use |

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

Modified

+30 / −6 text lines

55 ThemeColor,
66} from "@earendil-works/pi-coding-agent";
8const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
9const STATUS_ID = "context-size";
811const FOOTER_SEGMENT = {
912 id: "context-size",
1013 icon: "",
4144 color: ThemeColor;
4245};
47function hasFooter(): boolean {
48 const footer = (globalThis as any)[FOOTER_KEY];
49 return footer?.loaded === true && footer.version >= 1;
50}
4452function clamp(value: number, min: number, max: number): number {
4553 return Math.min(max, Math.max(min, value));
98106 pi.events.emit("footer:segment", { id: FOOTER_SEGMENT.id, text: undefined });
99107 }
109 function clearPublished(ctx: ExtensionContext) {
110 clearSegment();
111 ctx.ui.setStatus(STATUS_ID, undefined);
112 }
101114 function updateSegment(ctx: ExtensionContext) {
102115 try {
103116 if (!ctx.hasUI) return;
105118 const usage = ctx.getContextUsage();
106119 if (!usage) {
107 clearSegment();
120 clearPublished(ctx);
108121 return;
109122 }
111124 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;
133 }
135 clearSegment();
136 ctx.ui.setStatus(STATUS_ID, view.text);
117137 } catch {
118138 // Ignore late events during reload/switch/shutdown; Pi marks old ctx/pi stale.
119139 }
123143 pi.on(eventName, async (_event, ctx) => updateSegment(ctx));
124144 }
146 pi.on("session_shutdown", async (_event, ctx) => {
147 if (ctx.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
148 });
126150 // Footer owns its own teardown. Emitting through `pi.events` during session_shutdown
127151 // can trip Pi's stale-context guard after reload/switch.

pi/agent/extensions/cost/index.ts

Modified

+34 / −7 text lines

1515// ── Constants ─────────────────────────────────────────────────────────────
17const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
18const STATUS_ID = "cost";
1719const PRICE_UNIT_TOKENS = 1_000_000;
1820const COUNT_DECIMAL_THRESHOLD = 1_000;
1921const COUNT_ROUND_THRESHOLD = 10_000;
7173type SegmentId = "model" | "tokens" | "cost";
75// ── Footer capability ─────────────────────────────────────────────────────
77function hasFooter(): boolean {
78 const footer = (globalThis as any)[FOOTER_KEY];
79 return footer?.loaded === true && footer.version >= 1;
80}
7382// ── Pricing ───────────────────────────────────────────────────────────────
7584// Prices per 1M tokens. Used only when providers report $0 cost.
267276 });
270function emitSnapshot(pi: ExtensionAPI, snapshot: Snapshot) {
271 emitSegment(pi, "model", snapshot.modelLabel);
272 emitSegment(pi, "tokens", tokenLabel(snapshot.usage));
273 emitSegment(pi, "cost", costLabel(snapshot));
279function statusLabel(snapshot: Snapshot): string {
280 return [snapshot.modelLabel, tokenLabel(snapshot.usage), costLabel(snapshot)]
281 .filter((part): part is string => !!part)
282 .join(" · ");
283}
285function 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;
292 }
294 clearSegments(pi);
295 ctx.ui.setStatus(STATUS_ID, statusLabel(snapshot));
276298function clearSegments(pi: ExtensionAPI) {
279301 emitSegment(pi, "cost", undefined);
304function clearPublished(pi: ExtensionAPI, ctx?: ExtensionContext) {
305 clearSegments(pi);
306 if (ctx?.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
307}
282309// ── Snapshot ──────────────────────────────────────────────────────────────
284311function buildSnapshot(ctx: ExtensionContext, previousSessionCost: number, monthlyCost: number): Snapshot {
325352 if (nextSignature === lastSignature) return;
326353 lastSignature = nextSignature;
328 emitSnapshot(pi, snapshot);
355 publishSnapshot(pi, ctx, snapshot);
329356 }
331358 async function syncBestEffort(ctx: ExtensionContext) {
357384 });
358385 }
360 pi.on("session_shutdown", async () => {
361 clearSegments(pi);
387 pi.on("session_shutdown", async (_event, ctx) => {
388 clearPublished(pi, ctx);
362389 });

pi/agent/extensions/footer/index.ts

Modified

+13 / −1 text lines

88 * line 3 = extension statuses via ctx.ui.setStatus()
99 *
1010 * 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.
1113 * Uses setFooter() — the single footer owner. Producers are decoupled.
1214 *
1315 * /footer or ctrl+alt+f toggles visibility by swapping between
2123// ── Constants ─────────────────────────────────────────────────────
25const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
2326const SEPARATOR_COLOR = "borderMuted" as ThemeColor;
2427const DEFAULT_SEGMENT_COLOR = "muted" as ThemeColor;
2528const STATUS_COLOR = "dim" as ThemeColor;
2932// ── Types ─────────────────────────────────────────────────────────
34type FooterGlobal = {
35 version: 1;
36 loaded: boolean;
37};
3139type FooterZone = "workspace" | "llm";
3341type Segment = {
6775// ── Extension ─────────────────────────────────────────────────────
6977export default function footerExtension(pi: ExtensionAPI) {
78 const state: FooterGlobal = { version: 1, loaded: true };
79 (globalThis as any)[FOOTER_KEY] = state;
7081 const segments = new Map<string, Segment>();
7182 let requestRender: (() => void) | undefined;
7283 let renderScheduled = false;
281292 mountFooter();
282293 });
284 pi.on("session_shutdown", async () => {
295 pi.on("session_shutdown", async (event) => {
296 if (event.reason === "quit" || event.reason === "reload") state.loaded = false;
285297 segments.clear();
286298 requestRender = undefined;
287299 currentCtx = undefined;

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

Modified

+68 / −33 text lines

1010import { promisify } from "node:util";
1212const execFileAsync = promisify(execFile);
13const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
14const CWD_STATUS_ID = "cwd";
15const GIT_STATUS_ID = "git";
1417type GitStatus = {
1518 branch?: string;
3033 modified: "!", staged: "+", renamed: "»", deleted: "✘",
3134};
36function hasFooter(): boolean {
37 const footer = (globalThis as any)[FOOTER_KEY];
38 return footer?.loaded === true && footer.version >= 1;
39}
3341function parsePorcelain(stdout: string, hasStash: boolean): GitStatus {
3442 const s: GitStatus = { branch: undefined, ahead: 0, behind: 0, conflicted: 0, untracked: 0, stashed: false, modified: 0, staged: 0, renamed: 0, deleted: 0 };
3543 s.stashed = hasStash;
7583 } catch { return empty; }
78function emitGit(pi: ExtensionAPI, cwd: string, status: GitStatus) {
86function 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}` : ""}`;
102}
104function clearSegments(pi: ExtensionAPI) {
105 pi.events.emit("footer:segment", { id: "cwd", text: undefined });
106 pi.events.emit("footer:segment", { id: "git-branch", text: undefined });
107}
109function emitGit(pi: ExtensionAPI, ctx: ExtensionContext, status: GitStatus) {
79110 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 });
129 }
130 return;
110131 }
133 clearSegments(pi);
134 ctx.ui.setStatus(CWD_STATUS_ID, path);
135 ctx.ui.setStatus(GIT_STATUS_ID, branch);
113138export default function gitStatusExtension(pi: ExtensionAPI) {
114139 let currentCwd = "";
140 let currentCtx: ExtensionContext | undefined;
115141 let hasUI = false;
116142 let refreshInFlight = false;
117143 let refreshPending = false;
119145 const refresh = async () => {
120 if (!hasUI || refreshInFlight) { refreshPending = true; return; }
146 if (!hasUI || !currentCtx || refreshInFlight) { refreshPending = true; return; }
147 const ctx = currentCtx;
121148 refreshInFlight = true;
122149 try {
123150 const status = await readGitStatus(currentCwd);
124 emitGit(pi, currentCwd, status);
151 emitGit(pi, ctx, status);
125152 } finally {
126153 refreshInFlight = false;
127154 if (refreshPending) { refreshPending = false; refresh(); }
128155 }
129156 };
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(); });
132159 pi.on("agent_end", async () => { if (hasUI) refresh(); });
133160 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);
166 }
167 currentCtx = undefined;
168 });

pi/agent/extensions/quota/index.ts

Modified

+33 / −2 text lines

1010import { join } from "node:path";
1111import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
13const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
14const STATUS_ID = "quota";
1316// ── Types ─────────────────────────────────────────────────────────────────
1518interface MinimaxResponse {
246249 return used < 50 ? "accent" : used < 80 ? "warning" : "error";
252function hasFooter(): boolean {
253 const footer = (globalThis as any)[FOOTER_KEY];
254 return footer?.loaded === true && footer.version >= 1;
255}
249257// ── Extension ─────────────────────────────────────────────────────────────
251259export default function usageExtension(pi: ExtensionAPI) {
347355 footerIds.clear();
348356 }
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;
370 }
350372 function updateFooter(ctx: ExtensionContext) {
351373 const active = activeProvider(ctx);
375 if (!hasFooter()) {
376 clearFooter();
377 ctx.ui.setStatus(STATUS_ID, quotaStatusLabel(ctx));
378 return;
379 }
381 ctx.ui.setStatus(STATUS_ID, undefined);
352382 const seen = new Set<string>();
354384 for (const p of providers.filter(p => p.fiveH.total > 0)) {
444474 // ── Events ─────────────────────────────────────────────────────────────
446476 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);
448478 try { await getOrFetch(ctx); updateFooter(ctx); }
449 catch { if (!providers.length) clearFooter(); }
479 catch { if (!providers.length) { clearFooter(); ctx.ui.setStatus(STATUS_ID, undefined); } }
450480 });
452482 pi.on("agent_start", async (_e, ctx) => updateFooter(ctx));
459489 stopRefresh();
460490 widgetVisible = false;
461491 clearFooter();
492 ctx.ui.setStatus(STATUS_ID, undefined);
462493 ctx.ui.setWidget("usage", undefined);
463494 });

pi/agent/extensions/runtime/index.ts

Modified

+39 / −11 text lines

55 * under $HOME and emits a footer:segment with zone "workspace".
66 */
8import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
99import { execFile } from "node:child_process";
1010import { readdir, realpath } from "node:fs/promises";
1111import { dirname, isAbsolute, relative, resolve } from "node:path";
1414const execFileAsync = promisify(execFile);
16const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
1617const VERSION_TIMEOUT_MS = 2500;
1718const SEGMENT_ID = "runtime";
19const STATUS_ID = "runtime";
1820const SEGMENT_ZONE = "workspace";
1921const SEGMENT_ORDER = 3;
4345 version: () => Promise<string | undefined>;
4446};
48function hasFooter(): boolean {
49 const footer = (globalThis as any)[FOOTER_KEY];
50 return footer?.loaded === true && footer.version >= 1;
51}
4653async function commandOutput(cmd: string, args: readonly string[] = []): Promise<string | undefined> {
4754 try {
4855 const { stdout, stderr } = await execFileAsync(cmd, [...args], { timeout: VERSION_TIMEOUT_MS });
168175export default function runtimeExtension(pi: ExtensionAPI) {
169176 let currentCwd = "";
177 let currentCtx: ExtensionContext | undefined;
170178 let hasUI = false;
171179 let refreshInFlight = false;
181 function clearSegment() {
182 pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
183 }
173185 async function refresh() {
174 if (!hasUI || refreshInFlight) return;
186 if (!hasUI || !currentCtx || refreshInFlight) return;
187 const ctx = currentCtx;
175188 refreshInFlight = true;
177190 try {
178191 const rt = await detect(currentCwd);
179192 if (!rt) {
180 pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
193 clearSegment();
194 ctx.ui.setStatus(STATUS_ID, undefined);
181195 return;
182196 }
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;
210 }
212 clearSegment();
213 ctx.ui.setStatus(STATUS_ID, `${rt.icon} ${text}`);
192214 } finally {
193215 refreshInFlight = false;
194216 }
197219 pi.on("session_start", async (_e, ctx) => {
198220 hasUI = ctx.hasUI;
199221 currentCwd = ctx.cwd;
222 currentCtx = ctx;
200223 refresh();
201224 });
203226 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

+8 / −0 text lines

1_default:
2 python3 scripts/extensions.py list
3
4check ext="":
5 python3 scripts/extensions.py check {{ ext }}
6
7fmt:
8 just --fmt

pi/scripts/extensions.py

Added
new file mode 100755

+247 / −0 text lines

1#!/usr/bin/env python3
2"""Pi extension package workflow."""
3
4from __future__ import annotations
5
6import argparse
7import json
8import re
9import shutil
10import subprocess
11import sys
12import tempfile
13from pathlib import Path
15ROOT = Path(__file__).resolve().parents[1]
16EXT_ROOT = ROOT / "agent" / "extensions"
17PI_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",
23}
24IMPORT_RE = re.compile(r"(?:import|export)\s+(?:[^'\"]+?\s+from\s+)?['\"]([^'\"]+)['\"]|import\(['\"]([^'\"]+)['\"]\)")
25SECRET_RE = re.compile(r"(api[_-]?key|secret|token|password)\s*[:=]\s*['\"][^'\"]{12,}", re.I)
28def pkg_name(spec: str) -> str:
29 if spec.startswith("@"):
30 parts = spec.split("/")
31 return "/".join(parts[:2])
32 return spec.split("/")[0]
35def read_pkg(ext: Path) -> dict:
36 return json.loads((ext / "package.json").read_text())
39def 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
58def ts_files(ext: Path) -> list[Path]:
59 return sorted(p for p in ext.rglob("*.ts") if "node_modules" not in p.parts)
62def 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
72def err(errors: list[str], ext: Path, msg: str) -> None:
73 errors.append(f"{ext.name}: {msg}")
76def 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:"))
118 }
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
148def 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)
155def 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)
163def 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,
170 )
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)")
177def 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
183def 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
230def 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)
246if __name__ == "__main__":
247 raise SystemExit(main())