repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

build: generate self-contained extension packages under dist/<name>

199a37cbca0306cc8b04d12f4f13008a4914c6bf

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Pi now loads one Rolldown-built package per extension instead of the source workspace (PX-PLAN-RMJ8BIOX, PX-SPEC-DZLVGRW4).

- root manifest is empty; extensions declare entries, resources, assets, and justified externals under pi-ext
- builds stage, then publish atomically; previous chunks survive one generation for in-flight lazy imports
- ultra worker resolves Pi from the running installation; sibling lookups accept generated index.js
- the-system ships mermaid and minisearch as package assets
- //:build-ext, //:build-all, //:verify-packages [--collection], //:settings-entries, per-extension verify-package
- relocation probe loads every package outside the checkout and rejects registration conflicts

Changed files (78)

.gitignore

Modified
1 1 node_modules/
2 2 **/node_modules/
3 +/dist/
3 4 .worktrees/
4 5 .research/
5 6 .safe-clones/

.rumdl.toml

Modified
61 61 include = ["**/*.md"]
62 62 exclude = [
63 63 "**/node_modules/**",
64 + "dist/**",
64 65 ".research/**",
65 66 "skills/*/references/**",
66 67 "skills/*/_research/**",

README.md

Modified
8 8 Never `pi ext install`.
9 9 That corpse stays buried.
11 -All extensions, pinned to repo tag:
11 +The repository root is a development workspace, not a Pi package.
12 +Every extension builds into its own self-contained package under `dist/<extension>`, and Pi loads those packages.
14 +Build the packages:
13 16 ```bash
14 -pi install git:github.com/bugabinga/pi-ext@v0.0.3
17 +mise run //:build-all
17 -Default branch:
20 +Build one:
19 22 ```bash
20 -pi install git:github.com/bugabinga/pi-ext
23 +mise run //:build-ext ultra
23 -Local checkout, absolute path:
26 +Print the explicit package list for `~/.pi/agent/settings.json`:
25 28 ```bash
26 -pi install /home/me/Workspace/pi-ext
29 +mise run //:settings-entries
29 -Local checkout, `~` path:
32 +Each entry is one local package path, e.g. `~/Workspace/pi-ext/dist/ultra`.
33 +After a rebuild, run `/reload` in Pi.
31 -```bash
32 -pi install ~/Workspace/pi-ext
33 -```
35 +Published npm and Git packages of the generated output are planned; until then, install from a local build.
35 37 ### Filtering
37 -Load one extension via `~/.pi/agent/settings.json`:
39 +A generated package exposes exactly one extension entry plus its declared skills.
40 +Load a subset by listing only the wanted `dist/<extension>` packages.
41 +Resource filters still apply per package:
39 43 ```json
41 45 "packages": [
43 - "source": "git:github.com/bugabinga/pi-ext@v0.0.3",
44 - "extensions": ["extensions/web/index.ts"],
45 - "skills": [],
46 - "prompts": [],
47 - "themes": []
47 + "source": "~/Workspace/pi-ext/dist/web",
48 + "skills": []

biome.jsonc

Modified
12 12 "**/*.css",
13 13 "**/*.html",
14 14 "!**/node_modules",
15 + "!dist",
15 16 "!.research",
16 17 "!.safe-clones",
17 18 "!.rumdl_cache",

extensions/AGENTS.md

Modified
26 26 - `license: "MIT"`
27 27 - development dependencies on `@marcfargas/pi-test-harness` and Vitest
29 +Declare what the generated package needs under `pi-ext`:
31 +- `entries`: extra bundled entrypoints such as worker scripts spawned by path
32 +- `resources`: files or directories copied verbatim, such as skills, prompts, templates, or executable helpers
33 +- `assets`: package-relative destination to `<dependency>/<file>` for browser assets copied out of a bundled dependency
34 +- `externals`: third-party packages kept external, each with its demonstrated bundling incompatibility; they install into the generated package
36 +Portable third-party JavaScript is bundled by default; Node built-ins, Pi modules, and TypeBox stay external.
37 +Resolve runtime files relative to `import.meta.url` or `import.meta.dirname`; generated packages keep every chunk flat in the package root so those lookups work from any chunk.
38 +When a path depends on the file extension, derive it from `import.meta.url` (`.ts` in source, `.js` generated).
29 40 Do not declare a per-extension version.
30 41 The root package owns the repository version.
31 42 Do not declare package scripts.
173 184 Link to canonical source files, commands, settings, or upstream documentation.
174 185 A package README should explain purpose, installation or loading, commands and tools, settings, and optional integrations.
187 +## Generated packages
189 +Pi loads `dist/<name>`, never the source workspace; the root manifest is intentionally empty.
190 +Build with `mise run //:build-ext <name>` or `//:build-all`, then `/reload` in Pi.
191 +Verify relocation with `mise run //extensions/<name>:verify-package`; verify the whole collection with `mise run //:verify-packages --collection`.
192 +Print the user settings package list with `mise run //:settings-entries`.
176 194 ## Publishing
178 196 Use the root `//:publish` task.

extensions/angel/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["angel"] },
31 + { task = "//:build-ext", args = ["angel"] },
34 +[tasks.verify-package]
35 +description = "Build angel and load the generated package relocated outside the checkout"
36 +depends = ["//:install"]
37 +run = [
38 + { task = "//:build-ext", args = ["angel"] },
39 + { task = "//:verify-packages", args = ["angel"] },

extensions/ask/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["ask"] },
31 + { task = "//:build-ext", args = ["ask"] },
34 +[tasks.verify-package]
35 +description = "Build ask and load the generated package relocated outside the checkout"
36 +depends = ["//:install"]
37 +run = [
38 + { task = "//:build-ext", args = ["ask"] },
39 + { task = "//:verify-packages", args = ["ask"] },

extensions/bak/mise.toml

Modified
34 34 depends = ["//:install"]
35 35 run = [
36 36 { task = "//:build", args = ["bak"] },
37 + { task = "//:build-ext", args = ["bak"] },
40 +[tasks.verify-package]
41 +description = "Build bak and load the generated package relocated outside the checkout"
42 +depends = ["//:install"]
43 +run = [
44 + { task = "//:build-ext", args = ["bak"] },
45 + { task = "//:verify-packages", args = ["bak"] },

extensions/chrome-cdp/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["chrome-cdp"] },
31 + { task = "//:build-ext", args = ["chrome-cdp"] },
33 34 [tasks.e2e]
48 49 description = "Profile large CDP response spooling with Node CPU profiler"
49 50 depends = ["//:install"]
50 51 run = "node --cpu-prof --cpu-prof-dir ../../.pi/tmp/chrome-cdp-bench/profiles --no-warnings --experimental-strip-types __bench__/spool.bench.ts 80"
53 +[tasks.verify-package]
54 +description = "Build chrome-cdp and load the generated package relocated outside the checkout"
55 +depends = ["//:install"]
56 +run = [
57 + { task = "//:build-ext", args = ["chrome-cdp"] },
58 + { task = "//:verify-packages", args = ["chrome-cdp"] },

extensions/context-size/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["context-size"] },
22 + { task = "//:build-ext", args = ["context-size"] },
25 +[tasks.verify-package]
26 +description = "Build context-size and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["context-size"] },
30 + { task = "//:verify-packages", args = ["context-size"] },

extensions/continuity/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["continuity"] },
22 + { task = "//:build-ext", args = ["continuity"] },
25 +[tasks.verify-package]
26 +description = "Build continuity and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["continuity"] },
30 + { task = "//:verify-packages", args = ["continuity"] },

extensions/cost/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["cost"] },
22 + { task = "//:build-ext", args = ["cost"] },
25 +[tasks.verify-package]
26 +description = "Build cost and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["cost"] },
30 + { task = "//:verify-packages", args = ["cost"] },

extensions/decay/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["decay"] },
31 + { task = "//:build-ext", args = ["decay"] },
34 +[tasks.verify-package]
35 +description = "Build decay and load the generated package relocated outside the checkout"
36 +depends = ["//:install"]
37 +run = [
38 + { task = "//:build-ext", args = ["decay"] },
39 + { task = "//:verify-packages", args = ["decay"] },

extensions/fast/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["fast"] },
22 + { task = "//:build-ext", args = ["fast"] },
25 +[tasks.verify-package]
26 +description = "Build fast and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["fast"] },
30 + { task = "//:verify-packages", args = ["fast"] },

extensions/firefox-bidi/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["firefox-bidi"] },
31 + { task = "//:build-ext", args = ["firefox-bidi"] },
33 34 [tasks.bench]
42 43 arg "[pairs]" default="12"
44 45 run = "node --no-warnings --experimental-strip-types __bench__/e2e.mts {{ usage.pairs }}"
47 +[tasks.verify-package]
48 +description = "Build firefox-bidi and load the generated package relocated outside the checkout"
49 +depends = ["//:install"]
50 +run = [
51 + { task = "//:build-ext", args = ["firefox-bidi"] },
52 + { task = "//:verify-packages", args = ["firefox-bidi"] },

extensions/firefox-bidi/package.json

Modified
24 24 "extensions": [
25 25 "index.ts"
27 + },
28 + "pi-ext": {
29 + "resources": [
30 + "skills"
31 + ]

extensions/footer/mise.toml

Modified
47 47 depends = ["//:install"]
48 48 run = [
49 49 { task = "//:build", args = ["footer"] },
50 + { task = "//:build-ext", args = ["footer"] },
53 +[tasks.verify-package]
54 +description = "Build footer and load the generated package relocated outside the checkout"
55 +depends = ["//:install"]
56 +run = [
57 + { task = "//:build-ext", args = ["footer"] },
58 + { task = "//:verify-packages", args = ["footer"] },

extensions/git-safe/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["git-safe"] },
31 + { task = "//:build-ext", args = ["git-safe"] },
34 +[tasks.verify-package]
35 +description = "Build git-safe and load the generated package relocated outside the checkout"
36 +depends = ["//:install"]
37 +run = [
38 + { task = "//:build-ext", args = ["git-safe"] },
39 + { task = "//:verify-packages", args = ["git-safe"] },

extensions/git-safe/package.json

Modified
17 17 "@marcfargas/pi-test-harness": "^0.6.1",
18 18 "vitest": "^4.1.9"
20 - "private": true
20 + "private": true,
21 + "pi-ext": {
22 + "resources": [
23 + "git-wrapper.cjs"
24 + ]
25 + }

extensions/good-job/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["good-job"] },
31 + { task = "//:build-ext", args = ["good-job"] },
33 34 [tasks.bench]
34 35 description = "Benchmark loading persisted good-job records"
35 36 depends = ["//:install"]
36 37 run = "node --no-warnings --experimental-strip-types --experimental-loader ../../scripts/ts-js-loader.mjs __benches__/storage.bench.ts"
39 +[tasks.verify-package]
40 +description = "Build good-job and load the generated package relocated outside the checkout"
41 +depends = ["//:install"]
42 +run = [
43 + { task = "//:build-ext", args = ["good-job"] },
44 + { task = "//:verify-packages", args = ["good-job"] },

extensions/gratis/mise.toml

Modified
43 43 depends = ["//:install"]
44 44 run = [
45 45 { task = "//:build", args = ["gratis"] },
46 + { task = "//:build-ext", args = ["gratis"] },
49 +[tasks.verify-package]
50 +description = "Build gratis and load the generated package relocated outside the checkout"
51 +depends = ["//:install"]
52 +run = [
53 + { task = "//:build-ext", args = ["gratis"] },
54 + { task = "//:verify-packages", args = ["gratis"] },

extensions/horst/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["horst"] },
22 + { task = "//:build-ext", args = ["horst"] },
25 +[tasks.verify-package]
26 +description = "Build horst and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["horst"] },
30 + { task = "//:verify-packages", args = ["horst"] },

extensions/intellij/mise.toml

Modified
20 20 run = [
21 21 "npm exec -- tsc --noEmit --project tsconfig.json",
22 22 "node ../../scripts/extensions.mjs check intellij",
23 + { task = "//:build-ext", args = ["intellij"] },
25 26 [tasks.bench]
26 27 description = "Benchmark IntelliJ catalog preparation"
27 28 depends = ["//:install"]
28 29 run = "node --no-warnings --experimental-strip-types --experimental-loader ../../scripts/ts-js-loader.mjs __bench__/catalog.bench.ts"
31 +[tasks.verify-package]
32 +description = "Build intellij and load the generated package relocated outside the checkout"
33 +depends = ["//:install"]
34 +run = [
35 + { task = "//:build-ext", args = ["intellij"] },
36 + { task = "//:verify-packages", args = ["intellij"] },

extensions/klaus/mise.toml

Modified
30 30 depends = ["//:install"]
31 31 run = [
32 32 { task = "//:build", args = ["klaus"] },
33 + { task = "//:build-ext", args = ["klaus"] },
36 +[tasks.verify-package]
37 +description = "Build klaus and load the generated package relocated outside the checkout"
38 +depends = ["//:install"]
39 +run = [
40 + { task = "//:build-ext", args = ["klaus"] },
41 + { task = "//:verify-packages", args = ["klaus"] },

extensions/klaus/package.json

Modified
22 22 "@marcfargas/pi-test-harness": "^0.6.1",
23 23 "vitest": "^4.1.9"
25 - "private": true
25 + "private": true,
26 + "pi-ext": {
27 + "externals": {
28 + "@anthropic-ai/claude-agent-sdk": "ships per-platform binaries and a manifest located through require.resolve on the installed package"
29 + }
30 + }

extensions/masks/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["masks"] },
31 + { task = "//:build-ext", args = ["masks"] },
34 +[tasks.verify-package]
35 +description = "Build masks and load the generated package relocated outside the checkout"
36 +depends = ["//:install"]
37 +run = [
38 + { task = "//:build-ext", args = ["masks"] },
39 + { task = "//:verify-packages", args = ["masks"] },

extensions/mockup/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["mockup"] },
31 + { task = "//:build-ext", args = ["mockup"] },
33 34 [tasks.e2e]
35 36 depends = ["//:install"]
36 37 env = { NODE_ENV = "test" }
37 38 run = "npm exec -- playwright test --config playwright.config.ts"
40 +[tasks.verify-package]
41 +description = "Build mockup and load the generated package relocated outside the checkout"
42 +depends = ["//:install"]
43 +run = [
44 + { task = "//:build-ext", args = ["mockup"] },
45 + { task = "//:verify-packages", args = ["mockup"] },

extensions/mockup/package.json

Modified
27 27 "extensions": [
28 28 "index.ts"
30 + },
31 + "pi-ext": {
32 + "resources": [
33 + "guidance"
34 + ],
35 + "externals": {
36 + "playwright": "resolves its driver and browser registry relative to the installed package; bundling breaks browser launch"
37 + }

extensions/model-info/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["model-info"] },
22 + { task = "//:build-ext", args = ["model-info"] },
25 +[tasks.verify-package]
26 +description = "Build model-info and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["model-info"] },
30 + { task = "//:verify-packages", args = ["model-info"] },

extensions/notes/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["notes"] },
31 + { task = "//:build-ext", args = ["notes"] },
34 +[tasks.verify-package]
35 +description = "Build notes and load the generated package relocated outside the checkout"
36 +depends = ["//:install"]
37 +run = [
38 + { task = "//:build-ext", args = ["notes"] },
39 + { task = "//:verify-packages", args = ["notes"] },

extensions/nu-bang/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["nu-bang"] },
22 + { task = "//:build-ext", args = ["nu-bang"] },
25 +[tasks.verify-package]
26 +description = "Build nu-bang and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["nu-bang"] },
30 + { task = "//:verify-packages", args = ["nu-bang"] },

extensions/nushell/mise.toml

Modified
38 38 depends = ["//:install"]
39 39 run = [
40 40 { task = "//:build", args = ["nushell"] },
41 + { task = "//:build-ext", args = ["nushell"] },
44 +[tasks.verify-package]
45 +description = "Build nushell and load the generated package relocated outside the checkout"
46 +depends = ["//:install"]
47 +run = [
48 + { task = "//:build-ext", args = ["nushell"] },
49 + { task = "//:verify-packages", args = ["nushell"] },

extensions/open/mise.toml

Modified
28 28 depends = ["//:install"]
29 29 run = [
30 30 { task = "//:build", args = ["open"] },
31 + { task = "//:build-ext", args = ["open"] },
34 +[tasks.verify-package]
35 +description = "Build open and load the generated package relocated outside the checkout"
36 +depends = ["//:install"]
37 +run = [
38 + { task = "//:build-ext", args = ["open"] },
39 + { task = "//:verify-packages", args = ["open"] },

extensions/os-notifier/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["os-notifier"] },
22 + { task = "//:build-ext", args = ["os-notifier"] },
25 +[tasks.verify-package]
26 +description = "Build os-notifier and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["os-notifier"] },
30 + { task = "//:verify-packages", args = ["os-notifier"] },

extensions/pfui/__tests__/harness.test.ts

Modified
1 +import { execFileSync } from "node:child_process";
1 2 import {
2 3 cpSync,
3 4 mkdirSync,
198 - it("loads through Pi and resolves once at position one from the root manifest", async () => {
199 + it("loads through Pi once, first in the generated package list, while the workspace root exposes nothing", async () => {
199 200 t = await createPfuiSession();
201 202 expect(t.session.extensionRunner.extensions).toHaveLength(1);
202 203 const manifest = JSON.parse(
203 204 readFileSync(path.join(repositoryRoot, "package.json"), "utf8"),
204 - ) as { pi?: { extensions?: string[] } };
205 - expect(manifest.pi?.extensions).toEqual([
206 - "extensions/pfui/index.ts",
207 - "extensions/footer/index.ts",
208 - "extensions/*/index.ts",
209 - ]);
205 + ) as { pi?: unknown };
206 + expect(manifest.pi).toEqual({});
211 208 const packageManager = new DefaultPackageManager({
212 209 cwd: t.cwd,
217 214 [repositoryRoot],
218 215 { temporary: true },
220 - const pfuiPath = path.join(extensionRoot, "index.ts");
221 - const footerPath = path.join(repositoryRoot, "extensions/footer/index.ts");
222 - expect(resolved.extensions[0]?.path).toBe(pfuiPath);
223 - expect(resolved.extensions[1]?.path).toBe(footerPath);
217 + expect(resolved.extensions).toEqual([]);
219 + // Pi loads one generated package per extension; pfui must come first so it
220 + // owns the system prompt before other extensions contribute sections.
221 + const entries = JSON.parse(
222 + execFileSync(
223 + process.execPath,
224 + ["--no-warnings", "scripts/build/settings-entries.ts"],
225 + { cwd: repositoryRoot, encoding: "utf8" },
226 + ),
227 + ) as string[];
228 + const suffix = (entry: string) => entry.split(path.sep).slice(-2).join("/");
229 + expect(suffix(entries[0] ?? "")).toBe("dist/pfui");
230 + expect(suffix(entries[1] ?? "")).toBe("dist/footer");
224 231 expect(
225 - resolved.extensions.filter((extension) => extension.path === pfuiPath),
226 - ).toHaveLength(1);
227 - expect(
228 - resolved.extensions.filter((extension) => extension.path === footerPath),
232 + entries.filter((entry) => suffix(entry) === "dist/pfui"),
229 233 ).toHaveLength(1);
234 + expect(new Set(entries).size).toBe(entries.length);
232 237 it("composes the fallback with dynamic tools and deduplicated guidelines", async () => {

extensions/pfui/mise.toml

Modified
29 29 depends = ["//:install"]
30 30 run = [
31 31 { task = "//:build", args = ["pfui"] },
32 + { task = "//:build-ext", args = ["pfui"] },
35 +[tasks.verify-package]
36 +description = "Build pfui and load the generated package relocated outside the checkout"
37 +depends = ["//:install"]
38 +run = [
39 + { task = "//:build-ext", args = ["pfui"] },
40 + { task = "//:verify-packages", args = ["pfui"] },

extensions/pfui/package.json

Modified
20 20 "extensions": [
21 21 "index.ts"
23 + },
24 + "pi-ext": {
25 + "resources": [
26 + "skills",
27 + "SYSTEM.md"
28 + ]

extensions/prompt-autopsy/mise.toml

Modified
24 24 depends = ["//:install"]
25 25 run = [
26 26 { task = "//:build", args = ["prompt-autopsy"] },
27 + { task = "//:build-ext", args = ["prompt-autopsy"] },
30 +[tasks.verify-package]
31 +description = "Build prompt-autopsy and load the generated package relocated outside the checkout"
32 +depends = ["//:install"]
33 +run = [
34 + { task = "//:build-ext", args = ["prompt-autopsy"] },
35 + { task = "//:verify-packages", args = ["prompt-autopsy"] },

extensions/quota/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["quota"] },
22 + { task = "//:build-ext", args = ["quota"] },
25 +[tasks.verify-package]
26 +description = "Build quota and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["quota"] },
30 + { task = "//:verify-packages", args = ["quota"] },

extensions/rtk/mise.toml

Modified
38 38 depends = ["//:install"]
39 39 run = [
40 40 { task = "//:build", args = ["rtk"] },
41 + { task = "//:build-ext", args = ["rtk"] },
44 +[tasks.verify-package]
45 +description = "Build rtk and load the generated package relocated outside the checkout"
46 +depends = ["//:install"]
47 +run = [
48 + { task = "//:build-ext", args = ["rtk"] },
49 + { task = "//:verify-packages", args = ["rtk"] },

extensions/runtime/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["runtime"] },
22 + { task = "//:build-ext", args = ["runtime"] },
25 +[tasks.verify-package]
26 +description = "Build runtime and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["runtime"] },
30 + { task = "//:verify-packages", args = ["runtime"] },

extensions/session-rename/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["session-rename"] },
22 + { task = "//:build-ext", args = ["session-rename"] },
25 +[tasks.verify-package]
26 +description = "Build session-rename and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["session-rename"] },
30 + { task = "//:verify-packages", args = ["session-rename"] },

extensions/skillz/mise.toml

Modified
50 50 depends = ["//:install"]
51 51 run = [
52 52 { task = "//:build", args = ["skillz"] },
53 + { task = "//:build-ext", args = ["skillz"] },
56 +[tasks.verify-package]
57 +description = "Build skillz and load the generated package relocated outside the checkout"
58 +depends = ["//:install"]
59 +run = [
60 + { task = "//:build-ext", args = ["skillz"] },
61 + { task = "//:verify-packages", args = ["skillz"] },

extensions/strata/mise.toml

Modified
24 24 [tasks.check]
25 25 description = "Check Strata"
26 26 depends = ["//:install"]
27 -run = [{ task = "//:build", args = ["strata"] }]
27 +run = [
28 + { task = "//:build", args = ["strata"] },
29 + { task = "//:build-ext", args = ["strata"] },
29 32 [tasks.live]
30 33 description = "Open Pi's TUI with Strata and a live model (pass Pi CLI options)"
37 40 description = "Run Strata browser end-to-end tests"
38 41 depends = ["//:install"]
39 42 run = "npm exec -- playwright test --config playwright.config.ts"
44 +[tasks.verify-package]
45 +description = "Build strata and load the generated package relocated outside the checkout"
46 +depends = ["//:install"]
47 +run = [
48 + { task = "//:build-ext", args = ["strata"] },
49 + { task = "//:verify-packages", args = ["strata"] },

extensions/strata/package.json

Modified
19 19 "extensions": [
20 20 "index.ts"
22 + },
23 + "pi-ext": {
24 + "resources": [
25 + "assets"
26 + ]

extensions/the-system/mise.toml

Modified
43 43 depends = ["//:install"]
44 44 run = [
45 45 { task = "//:build", args = ["the-system"] },
46 + { task = "//:build-ext", args = ["the-system"] },
48 49 [tasks.doctor]
55 56 depends = ["//:install"]
56 57 env = { NODE_ENV = "test" }
57 58 run = "npm exec -- playwright test --config playwright.config.ts"
60 +[tasks.verify-package]
61 +description = "Build the-system and load the generated package relocated outside the checkout"
62 +depends = ["//:install"]
63 +run = [
64 + { task = "//:build-ext", args = ["the-system"] },
65 + { task = "//:verify-packages", args = ["the-system"] },

extensions/the-system/package.json

Modified
47 47 "extensions": [
48 48 "index.ts"
50 + },
51 + "pi-ext": {
52 + "resources": [
53 + "skills"
54 + ],
55 + "assets": {
56 + "assets/mermaid.min.js": "mermaid/dist/mermaid.min.js",
57 + "assets/minisearch.js": "minisearch/dist/umd/index.js"
58 + }

extensions/the-system/system-renderer.ts

Modified
1057 1057 mkdirSync(path.join(outputRoot, ".system"), { recursive: true });
1060 -const copyMermaid = (outputRoot: string) => {
1061 - const mermaid = path.join(
1062 - path.dirname(fileURLToPath(import.meta.resolve("mermaid/package.json"))),
1063 - "dist/mermaid.min.js",
1064 - );
1065 - if (!existsSync(mermaid)) return;
1066 - mkdirSync(path.join(outputRoot, "assets"), { recursive: true });
1067 - copyFileSync(mermaid, path.join(outputRoot, "assets/mermaid.min.js"));
1060 +// Browser assets ship inside the generated package under `assets/`; the source
1061 +// checkout falls back to the installed dependency.
1062 +const browserAsset = (
1063 + name: string,
1064 + specifier: string,
1065 + file: string,
1066 +): string | undefined => {
1067 + const packaged = fileURLToPath(new URL(`./assets/${name}`, import.meta.url));
1068 + if (existsSync(packaged)) return packaged;
1069 + try {
1070 + const installed = path.join(
1071 + path.dirname(fileURLToPath(import.meta.resolve(specifier))),
1072 + file,
1073 + );
1074 + return existsSync(installed) ? installed : undefined;
1075 + } catch {
1076 + return undefined;
1070 -const copyMiniSearch = (outputRoot: string) => {
1071 - const miniSearch = path.join(
1072 - path.dirname(fileURLToPath(import.meta.resolve("minisearch"))),
1073 - "../umd/index.js",
1074 - );
1075 - if (!existsSync(miniSearch)) return;
1080 +const copyBrowserAsset = (
1081 + outputRoot: string,
1082 + name: string,
1083 + source?: string,
1084 +) => {
1085 + if (!source) return;
1076 1086 mkdirSync(path.join(outputRoot, "assets"), { recursive: true });
1077 - copyFileSync(miniSearch, path.join(outputRoot, "assets/minisearch.js"));
1087 + copyFileSync(source, path.join(outputRoot, "assets", name));
1090 +const copyMermaid = (outputRoot: string) =>
1091 + copyBrowserAsset(
1092 + outputRoot,
1093 + "mermaid.min.js",
1094 + browserAsset(
1095 + "mermaid.min.js",
1096 + "mermaid/package.json",
1097 + "dist/mermaid.min.js",
1098 + ),
1099 + );
1101 +const copyMiniSearch = (outputRoot: string) =>
1102 + copyBrowserAsset(
1103 + outputRoot,
1104 + "minisearch.js",
1105 + browserAsset("minisearch.js", "minisearch", "../umd/index.js"),
1106 + );
1080 1108 const rel = (from: string, to: string) =>
1081 1109 path.relative(path.dirname(from), to).split(path.sep).join("/") || ".";

extensions/tps/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["tps"] },
22 + { task = "//:build-ext", args = ["tps"] },
25 +[tasks.verify-package]
26 +description = "Build tps and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["tps"] },
30 + { task = "//:verify-packages", args = ["tps"] },

extensions/ultra/dynamic-catalog.ts

Modified
1 1 import { spawn } from "node:child_process";
2 2 import { createHash, randomUUID } from "node:crypto";
3 -import { existsSync } from "node:fs";
3 +import { existsSync, readFileSync } from "node:fs";
4 4 import {
5 5 access,
6 6 copyFile,
14 14 writeFile,
15 15 } from "node:fs/promises";
16 16 import { homedir } from "node:os";
17 -import { dirname, join, posix, relative, resolve, sep, win32 } from "node:path";
17 +import {
18 + dirname,
19 + extname,
20 + join,
21 + posix,
22 + relative,
23 + resolve,
24 + sep,
25 + win32,
26 +} from "node:path";
18 27 import { fileURLToPath } from "node:url";
19 28 import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
20 29 import { Type } from "typebox";
34 43 import { DYNAMIC_EXTENSION_TOOL_NAMES } from "./spec.ts";
36 45 const MAX_TOOL_OUTPUT = 12_000;
46 +const PI_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
48 +/**
49 + * The validator worker ships next to this module with the same file extension:
50 + * `.ts` in the source checkout, `.js` inside a generated package.
51 + */
52 +export function defaultWorkerPath(): string {
53 + const here = fileURLToPath(import.meta.url);
54 + return join(dirname(here), `dynamic-validator-worker${extname(here)}`);
57 +let piPackageRootCache: string | undefined | null = null;
59 +/**
60 + * Locate the running Pi installation so a standalone worker process can import
61 + * Pi modules without a repository `node_modules` ancestor.
62 + */
63 +export function piPackageRoot(
64 + env: NodeJS.ProcessEnv = process.env,
65 + mainScript: string | undefined = process.argv[1],
66 +): string | undefined {
67 + if (env.ULTRA_PI_PACKAGE_ROOT) return env.ULTRA_PI_PACKAGE_ROOT;
68 + if (piPackageRootCache !== null) return piPackageRootCache;
69 + let dir = mainScript ? dirname(resolve(mainScript)) : undefined;
70 + while (dir) {
71 + try {
72 + const pkg = JSON.parse(
73 + readFileSync(join(dir, "package.json"), "utf8"),
74 + ) as { name?: unknown };
75 + if (pkg.name === PI_PACKAGE_NAME) break;
76 + } catch {
77 + // Not a package boundary.
78 + }
79 + const parent = dirname(dir);
80 + dir = parent === dir ? undefined : parent;
81 + }
82 + piPackageRootCache = dir;
83 + return dir;
37 85 const NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
39 87 export interface DynamicCatalogPaths {
138 186 safeSegment(options.parentSessionId),
139 187 safeSegment(options.workflowRunId),
141 - this.workerPath =
142 - options.workerPath ??
143 - fileURLToPath(new URL("./dynamic-validator-worker.ts", import.meta.url));
189 + this.workerPath = options.workerPath ?? defaultWorkerPath();
146 192 private init(): Promise<void> {
975 1021 cwd: args.draftPath,
977 1023 ...process.env,
1024 + ...(piPackageRoot() ? { ULTRA_PI_PACKAGE_ROOT: piPackageRoot() } : {}),
978 1025 CI: "true",
979 1026 ULTRA_VALIDATOR_TEMP: dirname(args.draftPath),
980 1027 ULTRA_VALIDATOR_RESULT_PATH: resultPath,

extensions/ultra/dynamic-validator-worker.ts

Modified
1 1 import { once } from "node:events";
2 2 import { lstatSync, readFileSync } from "node:fs";
3 3 import { mkdtemp, rm, writeFile } from "node:fs/promises";
4 +import { registerHooks } from "node:module";
4 5 import { tmpdir } from "node:os";
5 6 import { join, resolve } from "node:path";
6 -import { fileURLToPath } from "node:url";
7 -import { getModels } from "@earendil-works/pi-ai/compat";
8 -import {
9 - createAgentSession,
10 - DefaultResourceLoader,
11 - SessionManager,
12 -} from "@earendil-works/pi-coding-agent";
7 +import { fileURLToPath, pathToFileURL } from "node:url";
13 8 import {
14 9 artifactFiles,
15 10 hashArtifacts as hashArtifactTree,
38 33 manifest?: DynamicManifest;
36 +type PiCodingAgent = typeof import("@earendil-works/pi-coding-agent");
37 +type PiAiCompat = typeof import("@earendil-works/pi-ai/compat");
39 +const PI_SPECIFIER = /^(?:@earendil-works\/|typebox(?:\/|$))/u;
41 +/**
42 + * A generated package has no `node_modules` ancestor, so the parent passes the
43 + * running Pi installation and this worker resolves Pi modules from there.
44 + * Static imports would hoist above the hook, hence dynamic imports.
45 + */
46 +function anchorPiModules(packageRoot: string | undefined): void {
47 + if (!packageRoot) return;
48 + const here = new URL("./", import.meta.url).href;
49 + const anchor = pathToFileURL(join(packageRoot, "package.json")).href;
50 + registerHooks({
51 + resolve(specifier, context, next) {
52 + if (PI_SPECIFIER.test(specifier) && context.parentURL?.startsWith(here))
53 + return next(specifier, { ...context, parentURL: anchor });
54 + return next(specifier, context);
55 + },
56 + });
59 +let piModulesPromise: Promise<[PiCodingAgent, PiAiCompat]> | undefined;
61 +function piModules(): Promise<[PiCodingAgent, PiAiCompat]> {
62 + if (!piModulesPromise) {
63 + anchorPiModules(process.env.ULTRA_PI_PACKAGE_ROOT);
64 + piModulesPromise = Promise.all([
65 + import("@earendil-works/pi-coding-agent"),
66 + import("@earendil-works/pi-ai/compat"),
67 + ]);
68 + }
69 + return piModulesPromise;
41 72 function diagnostic(
42 73 state: ValidationState,
43 74 value: Omit<ValidationDiagnostic, "workingCopyPath">,
155 186 const indexPath = join(state.draftPath, "index.ts");
156 187 const agentDir = await mkdtemp(join(tmpdir(), "ultra-validator-agent-"));
157 188 let session:
158 - | Awaited<ReturnType<typeof createAgentSession>>["session"]
189 + | Awaited<ReturnType<PiCodingAgent["createAgentSession"]>>["session"]
159 190 | undefined;
192 + const [
193 + { createAgentSession, DefaultResourceLoader, SessionManager },
194 + { getModels },
195 + ] = await piModules();
161 196 const loader = new DefaultResourceLoader({
162 197 cwd: state.draftPath,
163 198 agentDir,

extensions/ultra/implementation.ts

Modified
107 107 const paths = setting.map((name) => {
108 108 if (!/^[a-z0-9][a-z0-9-]*$/u.test(name))
109 109 throw new Error(`ultra: invalid sub-agent extension name: ${name}`);
110 - const path = fileURLToPath(new URL(`../${name}/index.ts`, import.meta.url));
111 - if (!existsSync(path))
112 - throw new Error(`ultra: unknown sub-agent extension: ${name}`);
110 + // Sibling packages sit next to this one: `index.js` when generated, `index.ts` in source.
111 + const path = ["index.js", "index.ts"]
112 + .map((entry) =>
113 + fileURLToPath(new URL(`../${name}/${entry}`, import.meta.url)),
115 + .find((candidate) => existsSync(candidate));
116 + if (!path) throw new Error(`ultra: unknown sub-agent extension: ${name}`);
113 117 return path;
115 119 return { all: false, paths, pathKeys: new Set(paths.map(pathKey)) };

extensions/ultra/mise.toml

Modified
89 89 depends = ["//:install"]
90 90 run = [
91 91 { task = "//:build", args = ["ultra"] },
92 + { task = "//:build-ext", args = ["ultra"] },
95 +[tasks.verify-package]
96 +description = "Build ultra and load the generated package relocated outside the checkout"
97 +depends = ["//:install"]
98 +run = [
99 + { task = "//:build-ext", args = ["ultra"] },
100 + { task = "//:verify-packages", args = ["ultra"] },

extensions/ultra/package.json

Modified
24 24 "extensions": [
25 25 "index.ts"
27 + },
28 + "pi-ext": {
29 + "entries": [
30 + "dynamic-validator-worker.ts"
31 + ],
32 + "resources": [
33 + "prompts",
34 + "workflows"
35 + ]

extensions/usage/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["usage"] },
22 + { task = "//:build-ext", args = ["usage"] },
25 +[tasks.verify-package]
26 +description = "Build usage and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["usage"] },
30 + { task = "//:verify-packages", args = ["usage"] },

extensions/uv/mise.toml

Modified
38 38 depends = ["//:install"]
39 39 run = [
40 40 { task = "//:build", args = ["uv"] },
41 + { task = "//:build-ext", args = ["uv"] },
44 +[tasks.verify-package]
45 +description = "Build uv and load the generated package relocated outside the checkout"
46 +depends = ["//:install"]
47 +run = [
48 + { task = "//:build-ext", args = ["uv"] },
49 + { task = "//:verify-packages", args = ["uv"] },

extensions/uv/package.json

Modified
15 15 "devDependencies": {
16 16 "@marcfargas/pi-test-harness": "^0.6.1",
17 17 "vitest": "^4.1.9"
18 + },
19 + "pi-ext": {
20 + "resources": [
21 + "intercepted-commands"
22 + ]

extensions/vcs-status/mise.toml

Modified
19 19 depends = ["//:install"]
20 20 run = [
21 21 { task = "//:build", args = ["vcs-status"] },
22 + { task = "//:build-ext", args = ["vcs-status"] },
25 +[tasks.verify-package]
26 +description = "Build vcs-status and load the generated package relocated outside the checkout"
27 +depends = ["//:install"]
28 +run = [
29 + { task = "//:build-ext", args = ["vcs-status"] },
30 + { task = "//:verify-packages", args = ["vcs-status"] },

extensions/web/mise.toml

Modified
38 38 depends = ["//:install"]
39 39 run = [
40 40 { task = "//:build", args = ["web"] },
41 + { task = "//:build-ext", args = ["web"] },
44 +[tasks.verify-package]
45 +description = "Build web and load the generated package relocated outside the checkout"
46 +depends = ["//:install"]
47 +run = [
48 + { task = "//:build-ext", args = ["web"] },
49 + { task = "//:verify-packages", args = ["web"] },

extensions/web/package.json

Modified
18 18 "pi",
19 19 "pi-extension"
21 - "private": true
21 + "private": true,
22 + "pi-ext": {
23 + "resources": [
24 + "llm-extract.lua"
25 + ]
26 + }

mise.toml

Modified
188 188 depends = ["install"]
189 189 run = "node scripts/e2e.mjs //extensions/chrome-cdp:e2e //extensions/klaus:e2e //extensions/mockup:e2e //extensions/strata:e2e //extensions/the-system:e2e"
191 +[tasks.build-ext]
192 +description = "Build selected extension packages into dist/<name> (--release for the release variant)"
193 +depends = ["install"]
194 +usage = '''
195 +arg "<extensions>" var=#true
196 +flag "--release" help="Minified release variant without sourcemaps"
197 +'''
198 +run = '''
199 +node --no-warnings scripts/build/cli.ts{% if usage.release %} --release{% endif %}{% for extension in usage.extensions %} "{{ extension }}"{% endfor %}
200 +'''
202 +[tasks.build-all]
203 +description = "Build every extension package into dist/ (--release for the release variant)"
204 +depends = ["install"]
205 +usage = '''
206 +flag "--release" help="Minified release variant without sourcemaps"
207 +'''
208 +run = '''
209 +node --no-warnings scripts/build/cli.ts --all{% if usage.release %} --release{% endif %}
210 +'''
212 +[tasks.settings-entries]
213 +description = "Print the explicit dist/<name> package list for ~/.pi/agent/settings.json packages"
214 +run = "node --no-warnings scripts/build/settings-entries.ts"
216 +[tasks.verify-packages]
217 +description = "Load generated packages relocated outside the checkout through Pi (all built packages when none given)"
218 +depends = ["install"]
219 +usage = '''
220 +arg "[extensions]" var=#true
221 +flag "--collection" help="Load the selected packages together and fail on identity, tool, command, flag, or skill conflicts"
222 +'''
223 +run = '''
224 +node --no-warnings scripts/build/verify-cli.ts{% if usage.collection %} --collection{% endif %}{% for extension in usage.extensions %} "{{ extension }}"{% endfor %}
225 +'''
191 227 [tasks.build]
192 228 description = "Typecheck and statically validate extensions"
193 229 depends = ["install"]

package-lock.json

Modified
21 21 "@earendil-works/pi-tui": "0.87.0",
22 22 "@playwright/test": "^1.61.0",
23 23 "@vitest/coverage-istanbul": "^4.1.11",
24 + "rolldown": "^1.2.11",
24 25 "typescript": "^6.0.3",
25 26 "vitest": "^4.1.11"
4120 4121 "node_modules/@oxc-project/types": {
4121 - "version": "0.149.0",
4122 - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.149.0.tgz",
4123 - "integrity": "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==",
4122 + "version": "0.151.0",
4123 + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.151.0.tgz",
4124 + "integrity": "sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==",
4124 4125 "dev": true,
4125 4126 "license": "MIT",
4126 4127 "funding": {
4201 4202 "license": "BSD-3-Clause"
4203 4204 "node_modules/@rolldown/binding-android-arm-eabi": {
4204 - "version": "1.2.8",
4205 - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz",
4206 - "integrity": "sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==",
4205 + "version": "1.2.11",
4206 + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.11.tgz",
4207 + "integrity": "sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==",
4207 4208 "cpu": [
4220 4221 "node_modules/@rolldown/binding-android-arm64": {
4221 - "version": "1.2.8",
4222 - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.8.tgz",
4223 - "integrity": "sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==",
4222 + "version": "1.2.11",
4223 + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.11.tgz",
4224 + "integrity": "sha512-z6cTycz+iJ4PVkuL4HHW4DfTfoeU/2nqYYuSOrTmH7yHK5Y0LCOnA03V4ZNxavyVaU1oOqUgIg2klN/s+USGOA==",
4224 4225 "cpu": [
4237 4238 "node_modules/@rolldown/binding-darwin-arm64": {
4238 - "version": "1.2.8",
4239 - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.8.tgz",
4240 - "integrity": "sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==",
4239 + "version": "1.2.11",
4240 + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.11.tgz",
4241 + "integrity": "sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==",
4241 4242 "cpu": [
4254 4255 "node_modules/@rolldown/binding-darwin-x64": {
4255 - "version": "1.2.8",
4256 - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.8.tgz",
4257 - "integrity": "sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==",
4256 + "version": "1.2.11",
4257 + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.11.tgz",
4258 + "integrity": "sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==",
4258 4259 "cpu": [
4271 4272 "node_modules/@rolldown/binding-freebsd-x64": {
4272 - "version": "1.2.8",
4273 - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.8.tgz",
4274 - "integrity": "sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==",
4273 + "version": "1.2.11",
4274 + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.11.tgz",
4275 + "integrity": "sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==",
4275 4276 "cpu": [
4288 4289 "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
4289 - "version": "1.2.8",
4290 - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.8.tgz",
4291 - "integrity": "sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==",
4290 + "version": "1.2.11",
4291 + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.11.tgz",
4292 + "integrity": "sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==",
4292 4293 "cpu": [
4305 4306 "node_modules/@rolldown/binding-linux-arm64-gnu": {
4306 - "version": "1.2.8",
4307 - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.8.tgz",
4308 - "integrity": "sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==",
4307 + "version": "1.2.11",
4308 + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.11.tgz",
4309 + "integrity": "sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==",
4309 4310 "cpu": [
4325 4326 "node_modules/@rolldown/binding-linux-arm64-musl": {
4326 - "version": "1.2.8",
4327 - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.8.tgz",
4328 - "integrity": "sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==",
4327 + "version": "1.2.11",
4328 + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.11.tgz",
4329 + "integrity": "sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==",
4329 4330 "cpu": [
4345 4346 "node_modules/@rolldown/binding-linux-ppc64-gnu": {
4346 - "version": "1.2.8",
4347 - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.8.tgz",
4348 - "integrity": "sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==",
4347 + "version": "1.2.11",
4348 + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.11.tgz",
4349 + "integrity": "sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==",
4349 4350 "cpu": [
4365 4366 "node_modules/@rolldown/binding-linux-s390x-gnu": {
4366 - "version": "1.2.8",
4367 - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.8.tgz",
4368 - "integrity": "sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==",
4367 + "version": "1.2.11",
4368 + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.11.tgz",
4369 + "integrity": "sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==",
4369 4370 "cpu": [
4385 4386 "node_modules/@rolldown/binding-linux-x64-gnu": {
4386 - "version": "1.2.8",
4387 - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.8.tgz",
4388 - "integrity": "sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==",
4387 + "version": "1.2.11",
4388 + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.11.tgz",
4389 + "integrity": "sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==",
4389 4390 "cpu": [
4405 4406 "node_modules/@rolldown/binding-linux-x64-musl": {
4406 - "version": "1.2.8",
4407 - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.8.tgz",
4408 - "integrity": "sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==",
4407 + "version": "1.2.11",
4408 + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.11.tgz",
4409 + "integrity": "sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==",
4409 4410 "cpu": [
4425 4426 "node_modules/@rolldown/binding-openharmony-arm64": {
4426 - "version": "1.2.8",
4427 - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.8.tgz",
4428 - "integrity": "sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==",
4427 + "version": "1.2.11",
4428 + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.11.tgz",
4429 + "integrity": "sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==",
4429 4430 "cpu": [
4442 4443 "node_modules/@rolldown/binding-win32-arm64-msvc": {
4443 - "version": "1.2.8",
4444 - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.8.tgz",
4445 - "integrity": "sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==",
4444 + "version": "1.2.11",
4445 + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.11.tgz",
4446 + "integrity": "sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==",
4446 4447 "cpu": [
4459 4460 "node_modules/@rolldown/binding-win32-x64-msvc": {
4460 - "version": "1.2.8",
4461 - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.8.tgz",
4462 - "integrity": "sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==",
4461 + "version": "1.2.11",
4462 + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.11.tgz",
4463 + "integrity": "sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==",
4463 4464 "cpu": [
9578 9579 "license": "Unlicense"
9580 9581 "node_modules/rolldown": {
9581 - "version": "1.2.8",
9582 - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz",
9583 - "integrity": "sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==",
9582 + "version": "1.2.11",
9583 + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.11.tgz",
9584 + "integrity": "sha512-qpSwIyz0jHQq5qXBTNxFmE6664rJ7O+4TvPFOiOaBSrz8IOHc1koKKSqTM2H6u1UG1+TveuC6vaDHKXFOvb1Kw==",
9584 9585 "dev": true,
9585 9586 "license": "MIT",
9586 9587 "dependencies": {
9587 - "@oxc-project/types": "=0.149.0",
9588 + "@oxc-project/types": "=0.151.0",
9588 9589 "@rolldown/pluginutils": "^1.0.0"
9590 9591 "bin": {
9594 9595 "node": "^20.19.0 || >=22.12.0"
9596 9597 "optionalDependencies": {
9597 - "@rolldown/binding-android-arm-eabi": "1.2.8",
9598 - "@rolldown/binding-android-arm64": "1.2.8",
9599 - "@rolldown/binding-darwin-arm64": "1.2.8",
9600 - "@rolldown/binding-darwin-x64": "1.2.8",
9601 - "@rolldown/binding-freebsd-x64": "1.2.8",
9602 - "@rolldown/binding-linux-arm-gnueabihf": "1.2.8",
9603 - "@rolldown/binding-linux-arm64-gnu": "1.2.8",
9604 - "@rolldown/binding-linux-arm64-musl": "1.2.8",
9605 - "@rolldown/binding-linux-ppc64-gnu": "1.2.8",
9606 - "@rolldown/binding-linux-s390x-gnu": "1.2.8",
9607 - "@rolldown/binding-linux-x64-gnu": "1.2.8",
9608 - "@rolldown/binding-linux-x64-musl": "1.2.8",
9609 - "@rolldown/binding-openharmony-arm64": "1.2.8",
9610 - "@rolldown/binding-win32-arm64-msvc": "1.2.8",
9611 - "@rolldown/binding-win32-x64-msvc": "1.2.8"
9598 + "@rolldown/binding-android-arm-eabi": "1.2.11",
9599 + "@rolldown/binding-android-arm64": "1.2.11",
9600 + "@rolldown/binding-darwin-arm64": "1.2.11",
9601 + "@rolldown/binding-darwin-x64": "1.2.11",
9602 + "@rolldown/binding-freebsd-x64": "1.2.11",
9603 + "@rolldown/binding-linux-arm-gnueabihf": "1.2.11",
9604 + "@rolldown/binding-linux-arm64-gnu": "1.2.11",
9605 + "@rolldown/binding-linux-arm64-musl": "1.2.11",
9606 + "@rolldown/binding-linux-ppc64-gnu": "1.2.11",
9607 + "@rolldown/binding-linux-s390x-gnu": "1.2.11",
9608 + "@rolldown/binding-linux-x64-gnu": "1.2.11",
9609 + "@rolldown/binding-linux-x64-musl": "1.2.11",
9610 + "@rolldown/binding-openharmony-arm64": "1.2.11",
9611 + "@rolldown/binding-win32-arm64-msvc": "1.2.11",
9612 + "@rolldown/binding-win32-x64-msvc": "1.2.11"
9614 9615 "node_modules/roughjs": {

package.json

Modified
24 24 "@earendil-works/pi-tui": "0.87.0",
25 25 "@playwright/test": "^1.61.0",
26 26 "@vitest/coverage-istanbul": "^4.1.11",
27 + "rolldown": "^1.2.11",
27 28 "typescript": "^6.0.3",
28 29 "vitest": "^4.1.11"
30 - "pi": {
31 - "extensions": [
32 - "extensions/pfui/index.ts",
33 - "extensions/footer/index.ts",
34 - "extensions/*/index.ts"
35 - ]
36 - },
31 + "pi": {},
37 32 "allowScripts": {
38 33 "protobufjs": false,
39 34 "@google/genai": false,

scripts/build/build.test.ts

Added
new file mode 100644
1 +import { spawnSync } from "node:child_process";
2 +import {
3 + existsSync,
4 + mkdirSync,
5 + mkdtempSync,
6 + readdirSync,
7 + readFileSync,
8 + rmSync,
9 + writeFileSync,
10 +} from "node:fs";
11 +import { tmpdir } from "node:os";
12 +import { join } from "node:path";
13 +import { afterAll, beforeAll, describe, expect, it } from "vitest";
14 +import { buildExtension, ROOT, rootVersion } from "./build.ts";
15 +import { registrationConflicts } from "./conflicts.ts";
16 +import { BUILD_MANIFEST, listFiles, publishPackage } from "./publish.ts";
17 +import { readBuildSpec } from "./spec.ts";
18 +import {
19 + forbiddenImports,
20 + moduleImports,
21 + verifyCollection,
22 + verifyPackage,
23 +} from "./verify.ts";
25 +const PI_PACKAGE_ROOT = join(
26 + ROOT,
27 + "node_modules",
28 + "@earendil-works",
29 + "pi-coding-agent",
30 +);
32 +function temp(prefix: string): string {
33 + return mkdtempSync(join(tmpdir(), prefix));
36 +describe("ultra package", () => {
37 + let distRoot: string;
38 + let pkg: string;
40 + beforeAll(async () => {
41 + distRoot = temp("pi-ext-dist-");
42 + pkg = (await buildExtension("ultra", { distRoot })).dir;
43 + }, 60_000);
45 + afterAll(() => {
46 + rmSync(distRoot, { recursive: true, force: true });
47 + });
49 + it("emits a complete self-contained package with declared resources", () => {
50 + const files = listFiles(pkg);
51 + expect(files).toContain("index.js");
52 + expect(files).toContain("dynamic-validator-worker.js");
53 + expect(files).toContain("package.json");
54 + expect(files).toContain("prompts/ultra-authoring/SKILL.md");
55 + expect(files).toContain("workflows/feature.json");
56 + expect(files.some((f) => /^implementation-[a-z0-9]+\.js$/u.test(f))).toBe(
57 + true,
58 + );
59 + expect(files.some((f) => f.includes("/node_modules/"))).toBe(false);
60 + expect(existsSync(join(distRoot, ".staging"))).toBe(false);
62 + const manifest = JSON.parse(
63 + readFileSync(join(pkg, "package.json"), "utf8"),
64 + );
65 + expect(manifest).toMatchObject({
66 + name: "@bugabinga/pi-ext-ultra",
67 + version: rootVersion(),
68 + private: true,
69 + type: "module",
70 + main: "index.js",
71 + pi: { extensions: ["index.js"] },
72 + });
73 + expect(manifest.scripts).toBeUndefined();
74 + expect(manifest.dependencies).toBeUndefined();
75 + expect(Object.keys(manifest.peerDependencies)).toEqual(
76 + expect.arrayContaining(["@earendil-works/pi-coding-agent", "typebox"]),
77 + );
78 + });
80 + it("keeps the lazy runtime out of the entry chunk", () => {
81 + const entry = readFileSync(join(pkg, "index.js"), "utf8");
82 + expect(entry).not.toContain("unknown sub-agent extension");
83 + expect(moduleImports("index.js", entry)).toEqual(
84 + expect.arrayContaining([
85 + expect.stringMatching(/^\.\/implementation-[a-z0-9]+\.js$/u),
86 + ]),
87 + );
88 + });
90 + it("imports only Node built-ins, Pi modules, and package-private chunks", () => {
91 + expect(forbiddenImports(pkg)).toEqual([]);
92 + });
94 + it("loads relocated outside the checkout, activates the lazy runtime, and exposes the authoring skill", async () => {
95 + const report = await verifyPackage(pkg, {
96 + userSettings: { ultra: { autoEnable: true } },
97 + });
98 + expect(report.errors).toEqual([]);
99 + expect(report.ok).toBe(true);
100 + expect(report.extensions).toHaveLength(1);
101 + const [ultra] = report.extensions;
102 + expect(ultra.path).not.toContain(ROOT);
103 + expect(ultra.commands).toContain("ultra");
104 + expect(ultra.tools).toContain("run_workflow");
105 + expect(ultra.activeTools).toContain("run_workflow");
106 + expect(report.skills).toEqual([
107 + expect.stringMatching(/\/prompts\/ultra-authoring\/SKILL\.md$/u),
108 + ]);
109 + expect(report.skills[0]).not.toContain(ROOT);
110 + }, 120_000);
112 + it("runs the validator worker from a relocated package against the running Pi", () => {
113 + const root = temp("pi-ext-worker-");
114 + try {
115 + const relocated = join(root, "ultra");
116 + spawnSync("cp", ["-r", pkg, relocated]);
117 + const draft = join(root, "draft");
118 + mkdirSync(draft);
119 + writeFileSync(
120 + join(draft, "manifest.json"),
121 + JSON.stringify({ name: "hello-tool", description: "says hello" }),
122 + );
123 + writeFileSync(
124 + join(draft, "index.ts"),
125 + `export default function (pi) {
126 + pi.registerTool({
127 + name: "hello_tool",
128 + label: "Hello",
129 + description: "hello",
130 + parameters: { type: "object", properties: {} },
131 + async execute() {
132 + return { content: [{ type: "text", text: "hi" }], details: {} };
133 + },
134 + });
137 + );
138 + const result = spawnSync(
139 + process.execPath,
141 + "--no-warnings",
142 + join(relocated, "dynamic-validator-worker.js"),
143 + draft,
144 + ],
146 + encoding: "utf8",
147 + env: {
148 + ...process.env,
149 + ULTRA_PI_PACKAGE_ROOT: PI_PACKAGE_ROOT,
150 + PI_CODING_AGENT_DIR: join(root, "agent"),
151 + },
152 + timeout: 60_000,
153 + },
154 + );
155 + const line = result.stdout
156 + .split("\n")
157 + .find((candidate) => candidate.startsWith("ULTRA_VALIDATION_RESULT="));
158 + expect(line, result.stdout + result.stderr).toBeDefined();
159 + const report = JSON.parse(
160 + (line ?? "").slice("ULTRA_VALIDATION_RESULT=".length),
161 + );
162 + expect(report.diagnostics).toEqual([]);
163 + expect(report.ok).toBe(true);
164 + } finally {
165 + rmSync(root, { recursive: true, force: true });
167 + }, 90_000);
168 +});
170 +describe("the-system package", () => {
171 + let distRoot: string;
172 + let pkg: string;
174 + beforeAll(async () => {
175 + distRoot = temp("pi-ext-dist-");
176 + pkg = (await buildExtension("the-system", { distRoot })).dir;
177 + }, 60_000);
179 + afterAll(() => {
180 + rmSync(distRoot, { recursive: true, force: true });
181 + });
183 + it("bundles every third-party dependency and ships skills plus browser assets", () => {
184 + const files = listFiles(pkg);
185 + expect(files).toContain("skills/vertical-slices/SKILL.md");
186 + expect(files).toContain("skills/the-system-mermaid/SKILL.md");
187 + expect(files).toContain("assets/mermaid.min.js");
188 + expect(files).toContain("assets/minisearch.js");
189 + expect(files.some((f) => f.startsWith("node_modules/"))).toBe(false);
190 + expect(forbiddenImports(pkg)).toEqual([]);
191 + const manifest = JSON.parse(
192 + readFileSync(join(pkg, "package.json"), "utf8"),
193 + );
194 + expect(manifest.dependencies).toBeUndefined();
195 + const renderer = files.find((f) =>
196 + /^system-renderer-[a-z0-9]+\.js$/u.test(f),
197 + );
198 + expect(renderer).toBeDefined();
199 + expect(readFileSync(join(pkg, renderer ?? ""), "utf8")).toContain(
200 + "./assets/",
201 + );
202 + });
204 + it("loads relocated with its skills served from the package", async () => {
205 + const report = await verifyPackage(pkg);
206 + expect(report.errors).toEqual([]);
207 + expect(report.ok).toBe(true);
208 + expect(report.extensions[0]?.commands).toContain("system");
209 + expect(report.skills).toEqual([
210 + expect.stringMatching(/\/skills\/vertical-slices\/SKILL\.md$/u),
211 + ]);
212 + expect(report.skills[0]).not.toContain(ROOT);
213 + }, 120_000);
214 +});
216 +describe("collection", () => {
217 + it("reports identity, tool, command, flag, and skill conflicts", () => {
218 + expect(
219 + registrationConflicts(
221 + { path: "/a/index.js", tools: ["x"], commands: ["go"], flags: [] },
222 + { path: "/b/index.js", tools: ["x"], commands: [], flags: ["f"] },
223 + { path: "/c/index.js", tools: [], commands: ["go"], flags: ["f"] },
224 + ],
225 + ["@p/one", "@p/two", "@p/one"],
226 + ["/a/skills/s/SKILL.md", "/b/skills/s/SKILL.md"],
227 + ),
228 + ).toEqual([
229 + "command go registered by /a/index.js, /c/index.js",
230 + "flag f registered by /b/index.js, /c/index.js",
231 + "package @p/one registered by @p/one, @p/one",
232 + "skill s registered by /a/skills/s/SKILL.md, /b/skills/s/SKILL.md",
233 + "tool x registered by /a/index.js, /b/index.js",
234 + ]);
235 + expect(
236 + registrationConflicts(
237 + [{ path: "/a/index.js", tools: ["x"], commands: ["go"], flags: [] }],
238 + ["@p/one"],
239 + ["/a/skills/s/SKILL.md"],
240 + ),
241 + ).toEqual([]);
242 + });
244 + it("loads several generated packages together without conflicts", async () => {
245 + const distRoot = temp("pi-ext-dist-");
246 + try {
247 + const dirs: string[] = [];
248 + for (const name of ["pfui", "footer", "ultra", "nushell"])
249 + dirs.push((await buildExtension(name, { distRoot })).dir);
250 + const report = await verifyCollection(dirs);
251 + expect(report.errors).toEqual([]);
252 + expect(report.conflicts).toEqual([]);
253 + expect(report.ok).toBe(true);
254 + expect(report.extensions.map((e) => e.path.split("/").at(-2))).toEqual([
255 + "pfui",
256 + "footer",
257 + "ultra",
258 + "nushell",
259 + ]);
260 + } finally {
261 + rmSync(distRoot, { recursive: true, force: true });
263 + }, 180_000);
264 +});
266 +describe("publishPackage", () => {
267 + function stage(root: string, files: Record<string, string>): string {
268 + const staging = join(
269 + root,
270 + `staging-${Math.random().toString(36).slice(2)}`,
271 + );
272 + for (const [name, content] of Object.entries(files)) {
273 + mkdirSync(join(staging, name, ".."), { recursive: true });
274 + writeFileSync(join(staging, name), content);
276 + return staging;
279 + it("keeps previous chunks for one generation and switches entries last", () => {
280 + const root = temp("pi-ext-publish-");
281 + try {
282 + const target = join(root, "dist", "demo");
283 + publishPackage(
284 + stage(root, {
285 + "index.js": "import './chunk-a.js'",
286 + "chunk-a.js": "a",
287 + "prompts/one.md": "one",
288 + "package.json": "{}",
289 + }),
290 + target,
291 + ["index.js"],
292 + );
293 + expect(listFiles(target)).toEqual([
294 + BUILD_MANIFEST,
295 + "chunk-a.js",
296 + "index.js",
297 + "package.json",
298 + "prompts/one.md",
299 + ]);
301 + publishPackage(
302 + stage(root, {
303 + "index.js": "import './chunk-b.js'",
304 + "chunk-b.js": "b",
305 + "package.json": "{}",
306 + }),
307 + target,
308 + ["index.js"],
309 + );
310 + expect(listFiles(target)).toEqual([
311 + BUILD_MANIFEST,
312 + "chunk-a.js",
313 + "chunk-b.js",
314 + "index.js",
315 + "package.json",
316 + "prompts/one.md",
317 + ]);
318 + expect(readFileSync(join(target, "index.js"), "utf8")).toBe(
319 + "import './chunk-b.js'",
320 + );
322 + publishPackage(
323 + stage(root, {
324 + "index.js": "import './chunk-c.js'",
325 + "chunk-c.js": "c",
326 + "package.json": "{}",
327 + }),
328 + target,
329 + ["index.js"],
330 + );
331 + expect(listFiles(target)).toEqual([
332 + BUILD_MANIFEST,
333 + "chunk-b.js",
334 + "chunk-c.js",
335 + "index.js",
336 + "package.json",
337 + ]);
338 + expect(readdirSync(root).filter((n) => n.startsWith("staging-"))).toEqual(
339 + [],
340 + );
341 + } finally {
342 + rmSync(root, { recursive: true, force: true });
344 + });
345 +});
347 +describe("buildExtension", () => {
348 + function fakeRepo(): { root: string; ext: string } {
349 + const root = temp("pi-ext-repo-");
350 + writeFileSync(
351 + join(root, "package.json"),
352 + JSON.stringify({ name: "fake", version: "9.9.9" }),
353 + );
354 + const ext = join(root, "extensions", "demo");
355 + mkdirSync(ext, { recursive: true });
356 + writeFileSync(
357 + join(ext, "package.json"),
358 + JSON.stringify({
359 + name: "@bugabinga/pi-ext-demo",
360 + description: "demo",
361 + license: "MIT",
362 + peerDependencies: { "@earendil-works/pi-coding-agent": "*" },
363 + }),
364 + );
365 + writeFileSync(
366 + join(ext, "index.ts"),
367 + 'import { join } from "node:path";\nexport default function demo() { return join("a", "b"); }\n',
368 + );
369 + return { root, ext };
372 + it("leaves the previous package intact when a rebuild fails", async () => {
373 + const { root, ext } = fakeRepo();
374 + try {
375 + const built = await buildExtension("demo", { root });
376 + const before = listFiles(built.dir).map((f) => [
377 + f,
378 + readFileSync(join(built.dir, f), "utf8"),
379 + ]);
380 + expect(
381 + JSON.parse(readFileSync(join(built.dir, "package.json"), "utf8")),
382 + ).toMatchObject({ version: "9.9.9", pi: { extensions: ["index.js"] } });
384 + writeFileSync(join(ext, "index.ts"), 'import "./missing.ts";\n');
385 + await expect(buildExtension("demo", { root })).rejects.toThrow();
387 + const after = listFiles(built.dir).map((f) => [
388 + f,
389 + readFileSync(join(built.dir, f), "utf8"),
390 + ]);
391 + expect(after).toEqual(before);
392 + expect(existsSync(join(root, "dist", ".staging"))).toBe(false);
393 + } finally {
394 + rmSync(root, { recursive: true, force: true });
396 + });
398 + it("rejects undeclared or missing build declarations", () => {
399 + const { root, ext } = fakeRepo();
400 + try {
401 + writeFileSync(
402 + join(ext, "package.json"),
403 + JSON.stringify({
404 + name: "@bugabinga/pi-ext-demo",
405 + "pi-ext": { resources: ["missing"] },
406 + }),
407 + );
408 + expect(() => readBuildSpec(ext)).toThrow(/missing does not exist/u);
409 + writeFileSync(
410 + join(ext, "package.json"),
411 + JSON.stringify({
412 + name: "@bugabinga/pi-ext-demo",
413 + "pi-ext": { externals: { left: "" } },
414 + }),
415 + );
416 + expect(() => readBuildSpec(ext)).toThrow(/incompatibility reason/u);
417 + writeFileSync(
418 + join(ext, "package.json"),
419 + JSON.stringify({
420 + name: "@bugabinga/pi-ext-demo",
421 + dependencies: { left: "^1" },
422 + "pi-ext": { externals: { left: "native addon" } },
423 + }),
424 + );
425 + expect(readBuildSpec(ext).externals).toEqual({ left: "native addon" });
426 + } finally {
427 + rmSync(root, { recursive: true, force: true });
429 + });
430 +});

scripts/build/build.ts

Added
new file mode 100644
1 +import { spawnSync } from "node:child_process";
2 +import { randomUUID } from "node:crypto";
3 +import {
4 + copyFileSync,
5 + cpSync,
6 + existsSync,
7 + mkdirSync,
8 + readdirSync,
9 + readFileSync,
10 + rmdirSync,
11 + rmSync,
12 + writeFileSync,
13 +} from "node:fs";
14 +import { dirname, join, resolve } from "node:path";
15 +import { fileURLToPath } from "node:url";
16 +import { bundleExtension } from "./bundle.ts";
17 +import { generatePackageJson } from "./manifest.ts";
18 +import { publishPackage } from "./publish.ts";
19 +import { readBuildSpec } from "./spec.ts";
21 +export const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
22 +export const DIST_ROOT = join(ROOT, "dist");
24 +export interface BuildExtensionOptions {
25 + /** Repository root; defaults to this checkout. */
26 + root?: string;
27 + /** Canonical package parent; defaults to `<root>/dist`. */
28 + distRoot?: string;
29 + release?: boolean;
32 +export interface BuiltPackage {
33 + name: string;
34 + dir: string;
35 + entries: string[];
38 +export function allExtensionNames(root = ROOT): string[] {
39 + return readdirSync(join(root, "extensions"), { withFileTypes: true })
40 + .filter(
41 + (entry) =>
42 + entry.isDirectory() &&
43 + existsSync(join(root, "extensions", entry.name, "package.json")),
44 + )
45 + .map((entry) => entry.name)
46 + .sort();
49 +export function rootVersion(root = ROOT): string {
50 + const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as {
51 + version?: string;
52 + };
53 + if (!pkg.version) throw new Error("root package.json has no version");
54 + return pkg.version;
57 +/**
58 + * Externals declared with an incompatibility reason ship as a real dependency
59 + * tree inside the package, so a relocated copy resolves them without the
60 + * workspace. Peer dependencies stay Pi-provided and are never installed.
61 + */
62 +function installExternals(packageDir: string): void {
63 + const result = spawnSync(
64 + process.platform === "win32" ? "npm.cmd" : "npm",
65 + [
66 + "install",
67 + "--omit=dev",
68 + "--legacy-peer-deps",
69 + "--ignore-scripts",
70 + "--no-audit",
71 + "--no-fund",
72 + "--no-package-lock",
73 + "--prefer-offline",
74 + "--loglevel=error",
75 + ],
76 + { cwd: packageDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },
77 + );
78 + if (result.status !== 0)
79 + throw new Error(
80 + `npm install of external dependencies failed:\n${result.stderr || result.stdout}`,
81 + );
84 +/**
85 + * Build one extension into `<distRoot>/<name>`.
86 + * Everything is produced in a staging directory first; the canonical package is
87 + * touched only once the staging content is complete.
88 + */
89 +export async function buildExtension(
90 + name: string,
91 + options: BuildExtensionOptions = {},
92 +): Promise<BuiltPackage> {
93 + const root = options.root ?? ROOT;
94 + const distRoot = options.distRoot ?? join(root, "dist");
95 + const spec = readBuildSpec(join(root, "extensions", name));
96 + const staging = join(distRoot, ".staging", `${name}-${randomUUID()}`);
97 + mkdirSync(staging, { recursive: true });
98 + try {
99 + const bundled = await bundleExtension(spec, staging, {
100 + release: options.release,
101 + });
102 + for (const resource of spec.resources) {
103 + const destination = join(staging, resource);
104 + mkdirSync(dirname(destination), { recursive: true });
105 + cpSync(join(spec.dir, resource), destination, {
106 + recursive: true,
107 + dereference: true,
108 + });
110 + for (const [destination, source] of Object.entries(spec.assets)) {
111 + const target = join(staging, destination);
112 + mkdirSync(dirname(target), { recursive: true });
113 + copyFileSync(source, target);
115 + writeFileSync(
116 + join(staging, "package.json"),
117 + `${JSON.stringify(generatePackageJson(spec, rootVersion(root)), null, "\t")}\n`,
118 + );
119 + if (Object.keys(spec.externals).length) installExternals(staging);
120 + const target = join(distRoot, name);
121 + publishPackage(staging, target, bundled.entries);
122 + return { name, dir: target, entries: bundled.entries };
123 + } catch (error) {
124 + rmSync(staging, { recursive: true, force: true });
125 + throw error;
126 + } finally {
127 + const stagingRoot = join(distRoot, ".staging");
128 + if (existsSync(stagingRoot)) {
129 + try {
130 + rmdirSync(stagingRoot);
131 + } catch {
132 + // Another build is still staging.

scripts/build/bundle.ts

Added
new file mode 100644
1 +import { build } from "rolldown";
2 +import { type ExtensionBuildSpec, isExternal } from "./spec.ts";
4 +export interface BundleOptions {
5 + release?: boolean;
6 +}
8 +export interface BundleResult {
9 + /** Entry output files relative to the output directory. */
10 + entries: string[];
11 + /** Every emitted file relative to the output directory. */
12 + files: string[];
15 +/**
16 + * Bundle one extension into `outDir`.
17 + * Chunks stay flat in the package root so `import.meta.url` relative resource
18 + * lookups resolve identically from the entry and from any chunk.
19 + */
20 +export async function bundleExtension(
21 + spec: ExtensionBuildSpec,
22 + outDir: string,
23 + options: BundleOptions = {},
24 +): Promise<BundleResult> {
25 + const result = await build({
26 + input: spec.entries,
27 + cwd: spec.dir,
28 + platform: "node",
29 + // Source imports sibling modules as `./x.js`; the file on disk is `x.ts`.
30 + resolve: { extensionAlias: { ".js": [".ts", ".js"] } },
31 + external: (id, _parent, isResolved) =>
32 + isResolved ? false : isExternal(id, spec.externals),
33 + logLevel: "warn",
34 + onLog(level, log, defaultHandler) {
35 + if (level === "warn" && /import\.meta|circular/iu.test(log.message))
36 + return;
37 + defaultHandler(level, log);
38 + },
39 + output: {
40 + dir: outDir,
41 + format: "esm",
42 + entryFileNames: "[name].js",
43 + chunkFileNames: "[name]-[hash].js",
44 + hashCharacters: "base36",
45 + sourcemap: !options.release,
46 + minify: Boolean(options.release),
47 + },
48 + });
49 + const files: string[] = [];
50 + const entries: string[] = [];
51 + for (const output of result.output) {
52 + files.push(output.fileName);
53 + if (output.type === "chunk" && output.isEntry)
54 + entries.push(output.fileName);
55 + if (output.type === "chunk" && output.sourcemapFileName)
56 + files.push(output.sourcemapFileName);
57 + }
58 + return { entries, files };

scripts/build/cli.ts

Added
new file mode 100644
1 +import { allExtensionNames, buildExtension } from "./build.ts";
3 +function usage(): never {
4 + console.error(
5 + "usage: node scripts/build/cli.ts [--release] [--all] <extension>...",
6 + );
7 + process.exit(2);
8 +}
10 +export async function main(argv = process.argv.slice(2)): Promise<number> {
11 + let release = false;
12 + let all = false;
13 + const names: string[] = [];
14 + for (const arg of argv) {
15 + if (arg === "--release") release = true;
16 + else if (arg === "--all") all = true;
17 + else if (arg.startsWith("-")) usage();
18 + else names.push(arg);
19 + }
20 + const selected = all ? allExtensionNames() : names;
21 + if (!selected.length) usage();
22 + let failed = 0;
23 + for (const name of selected) {
24 + const started = performance.now();
25 + try {
26 + const built = await buildExtension(name, { release });
27 + console.log(
28 + `OK ${name} → ${built.dir} (${built.entries.join(", ")}) ${Math.round(performance.now() - started)}ms`,
29 + );
30 + } catch (error) {
31 + failed += 1;
32 + console.error(
33 + `ERROR ${name}: ${error instanceof Error ? error.message : String(error)}`,
34 + );
35 + }
36 + }
37 + return failed ? 1 : 0;
40 +process.exitCode = await main();

scripts/build/conflicts.ts

Added
new file mode 100644
1 +export interface ProbeExtension {
2 + path: string;
3 + tools: string[];
4 + commands: string[];
5 + flags: string[];
6 + activeTools: string[];
7 +}
9 +export interface ProbeReport {
10 + errors: string[];
11 + extensions: ProbeExtension[];
12 + skills: string[];
13 + /** Registrations claimed by more than one package in the probed set. */
14 + conflicts: string[];
17 +/** Identity, tool, command, flag, and skill names claimed more than once. */
18 +export function registrationConflicts(
19 + extensions: readonly Pick<
20 + ProbeExtension,
21 + "path" | "tools" | "commands" | "flags"
22 + >[],
23 + packageNames: readonly string[],
24 + skills: readonly string[],
25 +): string[] {
26 + const conflicts: string[] = [];
27 + const owners = (
28 + kind: string,
29 + items: readonly (readonly [string, string])[],
30 + ) => {
31 + const byName = new Map<string, string[]>();
32 + for (const [name, owner] of items)
33 + byName.set(name, [...(byName.get(name) ?? []), owner]);
34 + for (const [name, list] of byName)
35 + if (list.length > 1)
36 + conflicts.push(`${kind} ${name} registered by ${list.join(", ")}`);
37 + };
38 + owners(
39 + "package",
40 + packageNames.map((name) => [name, name] as const),
41 + );
42 + for (const kind of ["tools", "commands", "flags"] as const)
43 + owners(
44 + kind.slice(0, -1),
45 + extensions.flatMap((extension) =>
46 + extension[kind].map((name) => [name, extension.path] as const),
47 + ),
48 + );
49 + owners(
50 + "skill",
51 + skills.map(
52 + (path) => [path.split("/").slice(-2, -1)[0] ?? path, path] as const,
53 + ),
54 + );
55 + return conflicts.sort();

scripts/build/load-probe.ts

Added
new file mode 100644
1 +// Loads a generated extension package through Pi's real loader and a print-mode
2 +// session, then reports registrations as JSON on the last stdout line.
3 +// Runs as a child process so the probed package sees a clean module graph.
4 +import {
5 + mkdirSync,
6 + mkdtempSync,
7 + readFileSync,
8 + rmSync,
9 + writeFileSync,
10 +} from "node:fs";
11 +import { tmpdir } from "node:os";
12 +import { join, resolve } from "node:path";
13 +import { getModels } from "@earendil-works/pi-ai/compat";
14 +import {
15 + createAgentSession,
16 + DefaultResourceLoader,
17 + SessionManager,
18 +} from "@earendil-works/pi-coding-agent";
19 +import { type ProbeReport, registrationConflicts } from "./conflicts.ts";
21 +async function probe(packageRoots: string[]): Promise<ProbeReport> {
22 + const cwd = mkdtempSync(join(tmpdir(), "pi-ext-probe-cwd-"));
23 + const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(cwd, "agent");
24 + if (process.env.PI_EXT_PROBE_USER_SETTINGS) {
25 + mkdirSync(agentDir, { recursive: true });
26 + writeFileSync(
27 + join(agentDir, "settings.json"),
28 + process.env.PI_EXT_PROBE_USER_SETTINGS,
29 + );
30 + }
31 + const errors: string[] = [];
32 + const packageNames: string[] = [];
33 + const entries = packageRoots.flatMap((root) => {
34 + const pkg = JSON.parse(
35 + readFileSync(join(root, "package.json"), "utf8"),
36 + ) as {
37 + name?: string;
38 + pi?: { extensions?: string[] };
39 + };
40 + packageNames.push(pkg.name ?? root);
41 + return (pkg.pi?.extensions ?? ["index.js"]).map((entry) =>
42 + resolve(root, entry),
43 + );
44 + });
45 + let session:
46 + | Awaited<ReturnType<typeof createAgentSession>>["session"]
47 + | undefined;
48 + try {
49 + const loader = new DefaultResourceLoader({
50 + cwd,
51 + agentDir,
52 + noExtensions: true,
53 + noSkills: true,
54 + noPromptTemplates: true,
55 + noThemes: true,
56 + noContextFiles: true,
57 + additionalExtensionPaths: entries,
58 + });
59 + await loader.reload();
60 + const loaded = loader.getExtensions();
61 + errors.push(...loaded.errors.map((error) => String(error)));
62 + const model = getModels("openai")[0] ?? getModels("anthropic")[0];
63 + if (!model)
64 + throw new Error("Pi has no built-in model for an in-memory session.");
65 + ({ session } = await createAgentSession({
66 + cwd,
67 + agentDir,
68 + model,
69 + resourceLoader: loader,
70 + sessionManager: SessionManager.inMemory(cwd),
71 + }));
72 + await session.bindExtensions({
73 + mode: "print",
74 + onError: (error) => errors.push(String(error)),
75 + });
76 + const activeTools = session.getActiveToolNames();
77 + const extensions = loaded.extensions.map((extension) => ({
78 + path: extension.path,
79 + tools: [...extension.tools.keys()].sort(),
80 + commands: [...extension.commands.keys()].sort(),
81 + flags: [...extension.flags.keys()].sort(),
82 + activeTools: [...extension.tools.keys()]
83 + .filter((name) => activeTools.includes(name))
84 + .sort(),
85 + }));
86 + const skills = session.resourceLoader
87 + .getSkills()
88 + .skills.map((skill) => skill.filePath)
89 + .sort();
90 + await session.extensionRunner.emit({
91 + type: "session_shutdown",
92 + reason: "quit",
93 + });
94 + return {
95 + errors,
96 + extensions,
97 + skills,
98 + conflicts: registrationConflicts(extensions, packageNames, skills),
99 + };
100 + } finally {
101 + session?.dispose();
102 + rmSync(cwd, { recursive: true, force: true });
106 +const roots = process.argv.slice(2);
107 +if (!roots.length) {
108 + console.error("usage: node scripts/build/load-probe.ts <package-root>...");
109 + process.exit(2);
111 +const report = await probe(roots).catch((error: unknown) => ({
112 + errors: [
113 + error instanceof Error ? (error.stack ?? error.message) : String(error),
114 + ],
115 + extensions: [],
116 + skills: [],
117 + conflicts: [],
118 +}));
119 +console.log(`PI_EXT_PROBE=${JSON.stringify(report)}`);
120 +process.exit(0);

scripts/build/manifest.ts

Added
new file mode 100644
1 +import type { ExtensionBuildSpec } from "./spec.ts";
3 +/** Generated `package.json` for a built extension package. */
4 +export interface GeneratedPackageJson {
5 + name: string;
6 + version: string;
7 + private: true;
8 + type: "module";
9 + main: string;
10 + license?: string;
11 + description?: string;
12 + keywords?: string[];
13 + peerDependencies?: Record<string, string>;
14 + dependencies?: Record<string, string>;
15 + pi: Partial<Record<"extensions" | "skills" | "prompts" | "themes", string[]>>;
18 +function toOutput(entry: string): string {
19 + return entry.replace(/\.[cm]?ts$/u, ".js");
22 +export function generatePackageJson(
23 + spec: ExtensionBuildSpec,
24 + version: string,
25 +): GeneratedPackageJson {
26 + const source = spec.pkg;
27 + const extensions = (
28 + source.pi?.extensions?.length ? source.pi.extensions : ["index.ts"]
29 + ).map(toOutput);
30 + const pi: GeneratedPackageJson["pi"] = { extensions };
31 + for (const field of ["skills", "prompts", "themes"] as const)
32 + if (source.pi?.[field]) pi[field] = [...(source.pi[field] ?? [])];
33 + const dependencies = Object.fromEntries(
34 + Object.keys(spec.externals)
35 + .sort()
36 + .map((dep) => [dep, source.dependencies?.[dep] ?? "*"]),
37 + );
38 + const generated: GeneratedPackageJson = {
39 + name: source.name,
40 + version,
41 + private: true,
42 + type: "module",
43 + main: extensions[0] ?? "index.js",
44 + pi,
45 + };
46 + if (source.license) generated.license = source.license;
47 + if (source.description) generated.description = source.description;
48 + if (source.keywords) generated.keywords = [...source.keywords];
49 + if (source.peerDependencies)
50 + generated.peerDependencies = { ...source.peerDependencies };
51 + if (Object.keys(dependencies).length) generated.dependencies = dependencies;
52 + return generated;

scripts/build/publish.ts

Added
new file mode 100644
1 +import {
2 + copyFileSync,
3 + existsSync,
4 + mkdirSync,
5 + readdirSync,
6 + readFileSync,
7 + renameSync,
8 + rmSync,
9 + statSync,
10 + writeFileSync,
11 +} from "node:fs";
12 +import { dirname, join, relative, sep } from "node:path";
14 +export const BUILD_MANIFEST = ".pi-ext-build.json";
16 +interface BuildManifest {
17 + files: string[];
20 +export function listFiles(dir: string, base = dir): string[] {
21 + const out: string[] = [];
22 + if (!existsSync(dir)) return out;
23 + for (const entry of readdirSync(dir, { withFileTypes: true })) {
24 + const path = join(dir, entry.name);
25 + if (entry.isDirectory()) out.push(...listFiles(path, base));
26 + else out.push(relative(base, path).split(sep).join("/"));
27 + }
28 + return out.sort();
31 +function readManifest(target: string): BuildManifest | undefined {
32 + try {
33 + const parsed = JSON.parse(
34 + readFileSync(join(target, BUILD_MANIFEST), "utf8"),
35 + ) as Partial<BuildManifest>;
36 + return Array.isArray(parsed.files)
37 + ? { files: parsed.files.filter((f) => typeof f === "string") }
38 + : undefined;
39 + } catch {
40 + return undefined;
41 + }
44 +function replaceFile(source: string, destination: string): void {
45 + mkdirSync(dirname(destination), { recursive: true });
46 + const temp = `${destination}.tmp-${process.pid}`;
47 + copyFileSync(source, temp);
48 + renameSync(temp, destination);
51 +function pruneEmptyDirs(dir: string, root: string): void {
52 + if (dir === root || !existsSync(dir)) return;
53 + if (readdirSync(dir).length === 0) {
54 + rmSync(dir, { recursive: true, force: true });
55 + pruneEmptyDirs(dirname(dir), root);
56 + }
59 +/**
60 + * Publish a complete staging directory into the canonical package directory.
61 + *
62 + * Non-entry files land first, then entry files replace the previous entries
63 + * atomically, so a loaded extension keeps a consistent package until the
64 + * new entrypoint appears. Files from the previous build survive one more
65 + * generation so in-flight lazy imports can still resolve their chunks; anything
66 + * older is pruned.
67 + */
68 +export function publishPackage(
69 + staging: string,
70 + target: string,
71 + entries: readonly string[],
72 +): void {
73 + const files = listFiles(staging);
74 + if (!files.length) throw new Error(`nothing staged in ${staging}`);
75 + if (!existsSync(target)) {
76 + mkdirSync(dirname(target), { recursive: true });
77 + writeFileSync(
78 + join(staging, BUILD_MANIFEST),
79 + `${JSON.stringify({ files } satisfies BuildManifest, null, "\t")}\n`,
80 + );
81 + renameSync(staging, target);
82 + return;
83 + }
84 + if (!statSync(target).isDirectory())
85 + throw new Error(`${target} is not a directory`);
86 + const previous = new Set(readManifest(target)?.files ?? listFiles(target));
87 + const entrySet = new Set(entries);
88 + const late = files.filter((f) => entrySet.has(f) || f === "package.json");
89 + const early = files.filter((f) => !late.includes(f));
90 + for (const file of early)
91 + replaceFile(join(staging, file), join(target, file));
92 + for (const file of late.filter((f) => f === "package.json"))
93 + replaceFile(join(staging, file), join(target, file));
94 + for (const file of late.filter((f) => f !== "package.json"))
95 + replaceFile(join(staging, file), join(target, file));
96 + const keep = new Set([...files, ...previous, BUILD_MANIFEST]);
97 + for (const file of listFiles(target)) {
98 + if (keep.has(file)) continue;
99 + rmSync(join(target, file), { force: true });
100 + pruneEmptyDirs(dirname(join(target, file)), target);
102 + writeFileSync(
103 + join(target, BUILD_MANIFEST),
104 + `${JSON.stringify({ files } satisfies BuildManifest, null, "\t")}\n`,
105 + );
106 + rmSync(staging, { recursive: true, force: true });

scripts/build/settings-entries.ts

Added
new file mode 100644
1 +// Print the explicit Pi package list for ~/.pi/agent/settings.json: one
2 +// generated package per extension, pfui and footer first so they own prompt
3 +// sections and footer slots before the rest register.
4 +import { join } from "node:path";
5 +import { allExtensionNames, DIST_ROOT } from "./build.ts";
7 +const FIRST = ["pfui", "footer"];
9 +export function settingsEntries(
10 + names = allExtensionNames(),
11 + distRoot = DIST_ROOT,
12 +): string[] {
13 + const ordered = [
14 + ...FIRST.filter((name) => names.includes(name)),
15 + ...names.filter((name) => !FIRST.includes(name)),
16 + ];
17 + return ordered.map((name) => join(distRoot, name));
20 +console.log(JSON.stringify(settingsEntries(), null, "\t"));

scripts/build/spec.ts

Added
new file mode 100644
1 +import { existsSync, readFileSync, statSync } from "node:fs";
2 +import { builtinModules } from "node:module";
3 +import { basename, isAbsolute, join, relative } from "node:path";
5 +/** Bare specifiers that stay external in every generated package. */
6 +export const PI_EXTERNAL_PATTERNS: readonly RegExp[] = [
7 + /^node:/,
8 + /^@earendil-works\//,
9 + /^@mariozechner\//,
10 + /^typebox(?:\/|$)/,
11 + /^@sinclair\/typebox(?:\/|$)/,
12 +];
14 +const BUILTINS = new Set(builtinModules);
16 +export interface ExtensionPackageJson {
17 + name: string;
18 + description?: string;
19 + license?: string;
20 + keywords?: string[];
21 + dependencies?: Record<string, string>;
22 + peerDependencies?: Record<string, string>;
23 + pi?: Partial<
24 + Record<"extensions" | "skills" | "prompts" | "themes", string[]>
25 + >;
26 + "pi-ext"?: {
27 + entries?: string[];
28 + resources?: string[];
29 + /** Package-relative destination → `<dependency>/<file>` copied from a bundled dependency. */
30 + assets?: Record<string, string>;
31 + externals?: Record<string, string>;
32 + };
35 +export interface ExtensionBuildSpec {
36 + /** Directory name under `extensions/`. */
37 + name: string;
38 + /** Absolute source directory. */
39 + dir: string;
40 + pkg: ExtensionPackageJson;
41 + /** Rolldown entry name → source file relative to `dir`. */
42 + entries: Record<string, string>;
43 + /** Files or directories copied verbatim into the package, relative to `dir`. */
44 + resources: string[];
45 + /** Package-relative destination → absolute source file taken from a dependency. */
46 + assets: Record<string, string>;
47 + /** Third-party packages kept external with a recorded incompatibility reason. */
48 + externals: Record<string, string>;
51 +function fail(name: string, message: string): never {
52 + throw new Error(`${name}: ${message}`);
55 +function safeRelative(
56 + name: string,
57 + dir: string,
58 + value: unknown,
59 + label: string,
60 +) {
61 + if (typeof value !== "string" || !value)
62 + fail(name, `${label} must be a relative path`);
63 + if (isAbsolute(value) || value.includes("\\") || value.includes("\0"))
64 + fail(name, `${label} must be a relative slash-separated path`);
65 + const path = join(dir, value);
66 + const rel = relative(dir, path);
67 + if (rel === "" || rel.startsWith("..") || isAbsolute(rel))
68 + fail(name, `${label} must stay inside the extension`);
69 + if (!existsSync(path)) fail(name, `${label} ${value} does not exist`);
70 + return value
71 + .split("/")
72 + .filter((part) => part !== ".")
73 + .join("/");
76 +function findDependencyFile(
77 + name: string,
78 + dir: string,
79 + specifier: string,
80 +): string {
81 + const [scopeOrName, ...rest] = specifier.split("/");
82 + const packageName = specifier.startsWith("@")
83 + ? `${scopeOrName}/${rest.shift() ?? ""}`
84 + : (scopeOrName ?? "");
85 + const file = rest.join("/");
86 + if (!packageName || !file)
87 + fail(name, `pi-ext.assets source ${specifier} must be <package>/<file>`);
88 + let current = dir;
89 + while (true) {
90 + const candidate = join(current, "node_modules", packageName, file);
91 + if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
92 + const parent = join(current, "..");
93 + if (relative(parent, current) === "" || parent === current) break;
94 + current = parent;
95 + if (current === "/" || /^[A-Za-z]:\\?$/u.test(current)) {
96 + const last = join(current, "node_modules", packageName, file);
97 + if (existsSync(last) && statSync(last).isFile()) return last;
98 + break;
99 + }
101 + return fail(name, `pi-ext.assets source ${specifier} is not installed`);
104 +function entryName(file: string): string {
105 + return file.replace(/\.[cm]?[jt]s$/u, "");
108 +export function readBuildSpec(dir: string): ExtensionBuildSpec {
109 + const name = basename(dir);
110 + const pkgPath = join(dir, "package.json");
111 + if (!existsSync(pkgPath)) fail(name, "missing package.json");
112 + const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as ExtensionPackageJson;
113 + const declared = pkg["pi-ext"] ?? {};
114 + const entries: Record<string, string> = {};
115 + const piEntries = pkg.pi?.extensions?.length
116 + ? pkg.pi.extensions
117 + : ["index.ts"];
118 + for (const entry of piEntries) {
119 + const file = safeRelative(name, dir, entry, "pi.extensions entry");
120 + if (!statSync(join(dir, file)).isFile())
121 + fail(name, `pi.extensions entry ${file} must be a file`);
122 + entries[entryName(file)] = file;
124 + for (const entry of declared.entries ?? []) {
125 + const file = safeRelative(name, dir, entry, "pi-ext.entries entry");
126 + if (!statSync(join(dir, file)).isFile())
127 + fail(name, `pi-ext.entries entry ${file} must be a file`);
128 + const key = entryName(file);
129 + if (key in entries) fail(name, `duplicate entry ${file}`);
130 + entries[key] = file;
132 + const resources = (declared.resources ?? []).map((resource) =>
133 + safeRelative(name, dir, resource, "pi-ext.resources entry"),
134 + );
135 + const assets: Record<string, string> = {};
136 + for (const [destination, source] of Object.entries(declared.assets ?? {})) {
137 + if (
138 + typeof destination !== "string" ||
139 + !destination ||
140 + isAbsolute(destination) ||
141 + destination.split("/").some((part) => !part || part === "..")
143 + fail(
144 + name,
145 + `pi-ext.assets destination ${destination} must be a relative path`,
146 + );
147 + if (typeof source !== "string")
148 + fail(name, `pi-ext.assets.${destination} must name <package>/<file>`);
149 + assets[destination] = findDependencyFile(name, dir, source);
151 + const externals = declared.externals ?? {};
152 + for (const [dep, reason] of Object.entries(externals)) {
153 + if (typeof reason !== "string" || !reason.trim())
154 + fail(name, `pi-ext.externals.${dep} needs an incompatibility reason`);
155 + if (!pkg.dependencies?.[dep])
156 + fail(name, `pi-ext.externals.${dep} is not a declared dependency`);
158 + return { name, dir, pkg, entries, resources, assets, externals };
161 +export function packageOf(specifier: string): string {
162 + return specifier.startsWith("@")
163 + ? specifier.split("/").slice(0, 2).join("/")
164 + : (specifier.split("/")[0] ?? specifier);
167 +/** True when a bare specifier stays outside the generated bundle. */
168 +export function isExternal(
169 + specifier: string,
170 + externals: Record<string, string>,
171 +): boolean {
172 + if (specifier.startsWith(".") || isAbsolute(specifier)) return false;
173 + if (BUILTINS.has(specifier)) return true;
174 + if (PI_EXTERNAL_PATTERNS.some((pattern) => pattern.test(specifier)))
175 + return true;
176 + return packageOf(specifier) in externals;

scripts/build/verify-cli.ts

Added
new file mode 100644
1 +import { existsSync, readFileSync } from "node:fs";
2 +import { join } from "node:path";
3 +import { allExtensionNames, DIST_ROOT, ROOT } from "./build.ts";
4 +import { verifyCollection, verifyPackage } from "./verify.ts";
6 +export async function main(argv = process.argv.slice(2)): Promise<number> {
7 + const collection = argv.includes("--collection");
8 + const selected = argv.filter((arg) => arg !== "--collection");
9 + const names = selected.length
10 + ? selected
11 + : allExtensionNames().filter((name) =>
12 + existsSync(join(DIST_ROOT, name, "package.json")),
13 + );
14 + if (!names.length) {
15 + console.error("no generated packages under dist/; run //:build-ext first");
16 + return 1;
17 + }
18 + if (collection) {
19 + const report = await verifyCollection(
20 + names.map((name) => join(DIST_ROOT, name)),
21 + );
22 + for (const error of report.errors)
23 + console.error(`ERROR collection: ${error}`);
24 + for (const conflict of report.conflicts)
25 + console.error(`ERROR collection: ${conflict}`);
26 + if (report.ok)
27 + console.log(
28 + `OK collection: ${report.extensions.length} extensions, ${report.skills.length} skills, no conflicts`,
29 + );
30 + return report.ok ? 0 : 1;
31 + }
32 + let failed = 0;
33 + for (const name of names) {
34 + const dir = join(DIST_ROOT, name);
35 + if (!existsSync(join(dir, "package.json"))) {
36 + failed += 1;
37 + console.error(`ERROR ${name}: no generated package at ${dir}`);
38 + continue;
39 + }
40 + const source = JSON.parse(
41 + readFileSync(join(ROOT, "extensions", name, "package.json"), "utf8"),
42 + ) as { "pi-ext"?: { externals?: Record<string, string> } };
43 + const report = await verifyPackage(dir, {
44 + externals: source["pi-ext"]?.externals,
45 + });
46 + if (report.ok) {
47 + const registered = report.extensions
48 + .map((e) => `${e.tools.length} tools, ${e.commands.length} commands`)
49 + .join("; ");
50 + console.log(`OK ${name}: loads relocated (${registered})`);
51 + continue;
52 + }
53 + failed += 1;
54 + for (const error of report.errors) console.error(`ERROR ${name}: ${error}`);
55 + for (const spec of report.forbiddenImports)
56 + console.error(`ERROR ${name}: forbidden import ${spec}`);
57 + }
58 + return failed ? 1 : 0;
61 +process.exitCode = await main();

scripts/build/verify.ts

Added
new file mode 100644
1 +import { spawn } from "node:child_process";
2 +import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
3 +import { tmpdir } from "node:os";
4 +import { basename, dirname, join, resolve } from "node:path";
5 +import { fileURLToPath } from "node:url";
6 +import ts from "typescript";
7 +import type { ProbeReport } from "./conflicts.ts";
8 +import { listFiles } from "./publish.ts";
9 +import { isExternal, packageOf } from "./spec.ts";
11 +const HERE = dirname(fileURLToPath(import.meta.url));
12 +const PROBE = join(HERE, "load-probe.ts");
14 +export interface VerifyOptions {
15 + /** Extra bare packages this package may legitimately import. */
16 + externals?: Record<string, string>;
17 + /** User settings written into the probe's isolated agent directory. */
18 + userSettings?: Record<string, unknown>;
19 + timeoutMs?: number;
22 +export interface VerifyReport extends ProbeReport {
23 + package: string;
24 + /** Bare specifiers found in emitted JavaScript that violate the external policy. */
25 + forbiddenImports: string[];
26 + ok: boolean;
29 +/** Static and dynamic import specifiers of one JavaScript module. */
30 +export function moduleImports(file: string, text: string): string[] {
31 + const specifiers = new Set<string>();
32 + const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
33 + const visit = (node: ts.Node): void => {
34 + if (
35 + (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
36 + node.moduleSpecifier &&
37 + ts.isStringLiteral(node.moduleSpecifier)
38 + )
39 + specifiers.add(node.moduleSpecifier.text);
40 + if (
41 + ts.isCallExpression(node) &&
42 + node.expression.kind === ts.SyntaxKind.ImportKeyword &&
43 + node.arguments[0] &&
44 + ts.isStringLiteralLike(node.arguments[0])
45 + )
46 + specifiers.add(node.arguments[0].text);
47 + ts.forEachChild(node, visit);
48 + };
49 + visit(source);
50 + return [...specifiers].sort();
53 +export function scanImports(packageDir: string): string[] {
54 + const specifiers = new Set<string>();
55 + for (const file of listFiles(packageDir)) {
56 + // Installed external dependency trees own their internal imports.
57 + if (file.startsWith("node_modules/") || !/\.[cm]?js$/u.test(file)) continue;
58 + for (const specifier of moduleImports(
59 + file,
60 + readFileSync(join(packageDir, file), "utf8"),
61 + ))
62 + specifiers.add(specifier);
63 + }
64 + return [...specifiers].sort();
67 +export function forbiddenImports(
68 + packageDir: string,
69 + externals: Record<string, string> = {},
70 +): string[] {
71 + return scanImports(packageDir).filter((specifier) => {
72 + if (specifier.startsWith("./") || specifier.startsWith("../")) {
73 + return specifier.startsWith("../") || /\.[cm]?ts$/u.test(specifier);
74 + }
75 + if (specifier.startsWith("/") || specifier.startsWith("file:")) return true;
76 + return (
77 + !isExternal(specifier, externals) && !(packageOf(specifier) in externals)
78 + );
79 + });
82 +/** Run the Pi load probe over relocated package copies. */
83 +export async function probePackages(
84 + packageDirs: string[],
85 + options: Pick<VerifyOptions, "userSettings" | "timeoutMs"> = {},
86 +): Promise<ProbeReport> {
87 + const timeoutMs = options.timeoutMs ?? 120_000;
88 + const root = mkdtempSync(join(tmpdir(), "pi-ext-verify-"));
89 + try {
90 + const relocated = packageDirs.map((dir) => {
91 + const copy = join(root, "packages", basename(dir));
92 + cpSync(dir, copy, { recursive: true });
93 + return copy;
94 + });
95 + const agentDir = join(root, "agent");
96 + const output = await new Promise<string>((resolveOutput, reject) => {
97 + const child = spawn(
98 + process.execPath,
99 + ["--no-warnings", PROBE, ...relocated],
101 + cwd: root,
102 + env: {
103 + ...process.env,
104 + PI_CODING_AGENT_DIR: agentDir,
105 + PI_OFFLINE: "1",
106 + ...(options.userSettings
107 + ? {
108 + PI_EXT_PROBE_USER_SETTINGS: JSON.stringify(
109 + options.userSettings,
110 + ),
112 + : {}),
113 + },
114 + stdio: ["ignore", "pipe", "pipe"],
115 + },
116 + );
117 + let text = "";
118 + const append = (chunk: Buffer) => {
119 + text += chunk.toString("utf8");
120 + };
121 + child.stdout.on("data", append);
122 + child.stderr.on("data", append);
123 + const timer = setTimeout(() => {
124 + child.kill("SIGKILL");
125 + reject(new Error(`load probe timed out after ${timeoutMs}ms\n${text}`));
126 + }, timeoutMs);
127 + child.once("error", (error) => {
128 + clearTimeout(timer);
129 + reject(error);
130 + });
131 + child.once("close", () => {
132 + clearTimeout(timer);
133 + resolveOutput(text);
134 + });
135 + });
136 + const line = output
137 + .split("\n")
138 + .reverse()
139 + .find((candidate) => candidate.startsWith("PI_EXT_PROBE="));
140 + if (!line) throw new Error(`load probe produced no report\n${output}`);
141 + return JSON.parse(line.slice("PI_EXT_PROBE=".length)) as ProbeReport;
142 + } finally {
143 + rmSync(root, { recursive: true, force: true });
147 +/**
148 + * Verify the complete configured collection relocated together: every package
149 + * loads and no two packages claim the same identity, tool, command, flag, or skill.
150 + */
151 +export async function verifyCollection(
152 + packageDirs: string[],
153 + options: Pick<VerifyOptions, "userSettings" | "timeoutMs"> = {},
154 +): Promise<ProbeReport & { ok: boolean }> {
155 + const report = await probePackages(
156 + packageDirs.map((dir) => resolve(dir)),
157 + options,
158 + );
159 + return {
160 + ...report,
161 + ok: report.errors.length === 0 && report.conflicts.length === 0,
162 + };
165 +/** Verify one generated package relocated outside the checkout. */
166 +export async function verifyPackage(
167 + packageDir: string,
168 + options: VerifyOptions = {},
169 +): Promise<VerifyReport> {
170 + const dir = resolve(packageDir);
171 + const forbidden = forbiddenImports(dir, options.externals);
172 + const report = await probePackages([dir], options);
173 + return {
174 + package: dir,
175 + ...report,
176 + forbiddenImports: forbidden,
177 + ok: report.errors.length === 0 && forbidden.length === 0,
178 + };

scripts/extensions.mjs

Modified
12 12 import { dirname, join, relative, resolve } from "node:path";
13 13 import { pathToFileURL } from "node:url";
14 14 import ts from "typescript";
15 +import { readBuildSpec } from "./build/spec.ts";
15 16 import { CONFIG_PATH, checkGenerated } from "./codegen.mjs";
16 17 import {
477 478 if (pkg.license !== "MIT") err(errors, ext, "package license must be MIT");
478 479 if (!existsSync(join(ext, "README.md")))
479 480 err(errors, ext, "missing README.md");
481 + try {
482 + readBuildSpec(ext);
483 + } catch (e) {
484 + err(errors, ext, `invalid package build declaration: ${e.message}`);
480 486 errors.push(...checkGenerated(ext, root));
481 487 const debugPath = join(ext, "src", "debug.ts");
482 488 if (!existsSync(debugPath))
1061 1067 if (pkg.private !== true) errors.push("root: package must have private:true");
1062 1068 if (JSON.stringify(pkg.workspaces) !== JSON.stringify(["extensions/*"]))
1063 1069 errors.push("root: workspaces must be ['extensions/*']");
1064 - if (
1065 - JSON.stringify(pkg.pi?.extensions) !==
1066 - JSON.stringify([
1067 - "extensions/pfui/index.ts",
1068 - "extensions/footer/index.ts",
1069 - "extensions/*/index.ts",
1070 - ])
1070 + // The root is a development workspace, never a Pi package: an empty manifest
1071 + // stops Pi from discovering `extensions/` by convention. Pi loads generated
1072 + // packages from dist/<name> instead.
1073 + if (JSON.stringify(pkg.pi) !== "{}")
1072 1074 errors.push(
1073 - "root: pi.extensions must load pfui and footer explicitly before the extension glob",
1075 + "root: pi must be an empty manifest; Pi loads generated dist/<name> packages, not the workspace",
1075 - if ("skills" in (pkg.pi ?? {})) errors.push("root: pi.skills must be absent");
1076 - if ("prompts" in (pkg.pi ?? {}))
1077 - errors.push("root: pi.prompts must be absent");
1078 - if ("themes" in (pkg.pi ?? {})) errors.push("root: pi.themes must be absent");
1079 1077 if (errors.length) {
1080 1078 for (const e of errors) console.error(`ERROR ${e}`);
1081 1079 return 1;

scripts/test_extensions_static_check.mjs

Modified
289 -assert.deepEqual(rootPkg().pi, {
290 - extensions: [
291 - "extensions/pfui/index.ts",
292 - "extensions/footer/index.ts",
293 - "extensions/*/index.ts",
294 - ],
295 -});
289 +// The workspace root exports nothing; Pi loads generated dist/<name> packages.
290 +assert.deepEqual(rootPkg().pi, {});
297 292 const cliFailure = spawnSync(
298 293 process.execPath,

tsconfig.json

Modified
14 14 "include": [
15 15 "extensions/**/*.ts",
16 + "scripts/build/**/*.ts",
16 17 "skills/**/*.ts",
17 18 "prompts/**/*.ts",
18 19 "themes/**/*.ts"
20 21 "exclude": [
21 22 "node_modules",
23 + "dist",
24 + "scripts/build/**/*.test.ts",
22 25 "extensions/*/node_modules",
23 26 "extensions/**/__tests__/**",
24 27 "extensions/**/*.test.ts",