repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

feat: add horst extension for per-host data and tool deltas

025546d594fdbd8abd1b0dc5ace5a6447c899c06

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (8)

extensions/horst/README.md

Added
new file mode 100644
1 +# horst
3 +Per-host environment data and tool defaults for Pi.
5 +## Install / load
7 +Loaded through the root pi-ext package.
8 +See [root README](../../README.md).
10 +## Commands / tools / settings
12 +- Commands:
13 + none
14 +- Tools:
15 + none
16 +- Settings:
17 + `horst` block in `~/.pi/agent/settings.json` (global) or `.pi/settings.json`
18 + (project); project wins per key
19 +- Hooks:
20 + `session_start`, `before_agent_start`
22 +## Settings
24 +```json
26 + "horst": {
27 + "os": {
28 + "win32": { "tools": { "add": ["powershell"], "remove": ["bash"] } }
29 + },
30 + "hosts": {
31 + "winbox": { "tools": { "remove": ["read"] } }
32 + }
33 + }
35 +```
37 +- `os` keys: `win32`, `lnx`, `mac`
38 +- `hosts` keys: hostname, lowercased
39 +- both maps optional, unknown names ignored with a warning
40 +- fold order: `os` first, then `hosts`; `hosts` wins per field
41 +- no match: no change
43 +## Behavior
45 +- Injects a stable host data section (`<horst>`) into the system prompt:
46 + hostname, os, kernel, arch, cpu, memory, shell, editor.
47 +- Loads the snapshot lazily exactly once per process:
48 + `node:os` getters plus one `/etc/os-release` read on Linux.
49 +- Only stable facts enter the prompt, so the section produces one prompt patch
50 + and then stays cache-stable.
51 +- Applies the configured tool delta once per session start on top of the
52 + active tools.

extensions/horst/__tests__/harness.test.ts

Added
new file mode 100644
1 +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 +import os, { tmpdir } from "node:os";
3 +import path from "node:path";
4 +import { afterEach, describe, expect, it } from "vitest";
5 +import { createTestSession, type TestSession } from "../../../test/harness";
6 +import {
7 + getHostSection,
8 + type HostSnapshot,
9 + renderHostSection,
10 +} from "../host.ts";
11 +import {
12 + EMPTY_HORST_SETTINGS,
13 + mergeHorst,
14 + pickHorst,
15 + resolveHorstTools,
16 +} from "../settings.ts";
18 +const horstPath = () => path.resolve(import.meta.dirname, "../index.ts");
20 +describe("pickHorst", () => {
21 + it("keeps well-formed tool deltas and lowercases keys", () => {
22 + const settings = pickHorst({
23 + os: { WIN32: { tools: { add: ["powershell"], remove: ["bash"] } } },
24 + hosts: { WinBox: { tools: { remove: ["write"] } } },
25 + });
26 + expect(settings).toEqual({
27 + os: { win32: { add: ["powershell"], remove: ["bash"] } },
28 + hosts: { winbox: { remove: ["write"] } },
29 + });
30 + });
32 + it("drops malformed entries and keeps empty results empty", () => {
33 + expect(
34 + pickHorst({
35 + os: {
36 + lnx: { tools: { add: [42] }, flat: { add: ["ls"] } },
37 + },
38 + hosts: "nope",
39 + default: { tools: { add: ["bash"] } },
40 + }),
41 + ).toEqual(EMPTY_HORST_SETTINGS);
42 + expect(pickHorst(undefined)).toEqual(EMPTY_HORST_SETTINGS);
43 + });
44 +});
46 +describe("mergeHorst", () => {
47 + it("lets later partials win per key", () => {
48 + const merged = mergeHorst(
49 + {
50 + os: { win32: { add: ["powershell"] } },
51 + hosts: { a: { remove: ["read"] } },
52 + },
53 + { os: { win32: { remove: ["bash"] } }, hosts: { b: { add: ["grep"] } } },
54 + );
55 + expect(merged).toEqual({
56 + os: { win32: { remove: ["bash"] } },
57 + hosts: { a: { remove: ["read"] }, b: { add: ["grep"] } },
58 + });
59 + });
60 +});
62 +describe("resolveHorstTools", () => {
63 + it("maps platform names to os keys", () => {
64 + expect(
65 + resolveHorstTools(
66 + { os: { lnx: { add: ["grep"] } }, hosts: {} },
67 + "linux",
68 + "x",
69 + ),
70 + ).toEqual({ add: ["grep"] });
71 + expect(
72 + resolveHorstTools(
73 + { os: { mac: { add: ["grep"] } }, hosts: {} },
74 + "darwin",
75 + "x",
76 + ),
77 + ).toEqual({ add: ["grep"] });
78 + expect(
79 + resolveHorstTools(
80 + { os: { win32: { add: ["powershell"] } }, hosts: {} },
81 + "win32",
82 + "x",
83 + ),
84 + ).toEqual({ add: ["powershell"] });
85 + });
87 + it("matches hostnames case-insensitively and wins per field over os", () => {
88 + const settings = {
89 + os: { win32: { add: ["powershell"], remove: ["bash"] } },
90 + hosts: { winbox: { remove: ["write"] } },
91 + };
92 + expect(resolveHorstTools(settings, "win32", "WinBox")).toEqual({
93 + add: ["powershell"],
94 + remove: ["write"],
95 + });
96 + });
98 + it("returns undefined without a match", () => {
99 + expect(
100 + resolveHorstTools(EMPTY_HORST_SETTINGS, "linux", "x"),
101 + ).toBeUndefined();
102 + });
103 +});
105 +describe("renderHostSection", () => {
106 + it("renders stable facts and omits absent shell/editor", () => {
107 + const host: HostSnapshot = {
108 + hostname: "winbox",
109 + osLabel: "Fedora Linux 42",
110 + kernel: "6.14.0",
111 + arch: "x64",
112 + cpuModel: "AMD Ryzen 9",
113 + cpuCount: 24,
114 + memGiB: 32,
115 + };
116 + const section = renderHostSection(host);
117 + expect(section).toContain("hostname: winbox");
118 + expect(section).toContain("os: Fedora Linux 42");
119 + expect(section).toContain("cpu: AMD Ryzen 9 × 24");
120 + expect(section).toContain("mem: 32 GiB");
121 + expect(section).not.toContain("shell:");
122 + expect(section).not.toContain("editor:");
123 + });
124 +});
126 +describe("horst pi-test-harness", () => {
127 + let t: TestSession | undefined;
129 + afterEach(() => {
130 + t?.dispose();
131 + t = undefined;
132 + });
134 + it("loads in real Pi extension runtime", async () => {
135 + t = await createTestSession({ extensions: [horstPath()] });
136 + expect(
137 + t.session.extensionRunner.extensions.map((extension) => extension.path),
138 + ).toContain(horstPath());
139 + });
141 + it("applies the host tool delta from project settings", async () => {
142 + const root = mkdtempSync(path.join(tmpdir(), "horst-delta-"));
143 + try {
144 + mkdirSync(path.join(root, ".pi"), { recursive: true });
145 + writeFileSync(
146 + path.join(root, ".pi", "settings.json"),
147 + JSON.stringify({
148 + horst: {
149 + hosts: {
150 + [os.hostname().toLowerCase()]: {
151 + tools: { add: ["grep", "find"], remove: ["write"] },
152 + },
153 + },
154 + },
155 + }),
156 + );
157 + t = await createTestSession({ cwd: root, extensions: [horstPath()] });
158 + const active = t.session.getActiveToolNames();
159 + expect(active).toContain("grep");
160 + expect(active).toContain("find");
161 + expect(active).not.toContain("write");
162 + } finally {
163 + t?.dispose();
164 + t = undefined;
165 + rmSync(root, { recursive: true, force: true });
167 + });
169 + it("injects the stable host section each turn", async () => {
170 + t = await createTestSession({ extensions: [horstPath()] });
171 + const runner = t.session.extensionRunner;
172 + const first = await runner.emitBeforeAgentStart("prompt", undefined, {
173 + cwd: t.cwd,
174 + });
175 + const second = await runner.emitBeforeAgentStart("prompt", undefined, {
176 + cwd: t.cwd,
177 + });
178 + const { horst } = first.systemPromptOptions.sections;
179 + expect(horst).toBe(second.systemPromptOptions.sections.horst);
180 + expect(horst).toContain(`hostname: ${os.hostname()}`);
181 + expect(getHostSection()).resolves.toBe(horst);
182 + });
183 +});

extensions/horst/host.ts

Added
new file mode 100644
1 +// horst — stable host snapshot.
2 +//
3 +// One-time lazy load: node:os getters plus a single /etc/os-release read,
4 +// memoized for the whole process so the rendered section never changes.
6 +import { readFile } from "node:fs/promises";
7 +import os from "node:os";
9 +export interface HostSnapshot {
10 + hostname: string;
11 + osLabel: string;
12 + kernel: string;
13 + arch: string;
14 + cpuModel?: string;
15 + cpuCount: number;
16 + memGiB: number;
17 + shell?: string;
18 + editor?: string;
21 +function osTypeLabel(): string {
22 + if (process.platform === "win32") return "Windows";
23 + if (process.platform === "darwin") return "macOS";
24 + return os.type();
27 +/** Read PRETTY_NAME from /etc/os-release; absent on other platforms. */
28 +async function readPrettyName(): Promise<string | undefined> {
29 + if (process.platform !== "linux") return undefined;
30 + try {
31 + const content = await readFile("/etc/os-release", "utf8");
32 + const match = /^PRETTY_NAME=(?:"([^"]*)"|(.*?))\s*$/m.exec(content);
33 + return match?.[1] ?? match?.[2] ?? undefined;
34 + } catch {
35 + return undefined;
36 + }
39 +async function loadHostSnapshot(): Promise<HostSnapshot> {
40 + const cpus = os.cpus();
41 + return {
42 + hostname: os.hostname(),
43 + osLabel: (await readPrettyName()) ?? osTypeLabel(),
44 + kernel: os.release(),
45 + arch: os.arch(),
46 + cpuModel: cpus[0]?.model.trim() || undefined,
47 + cpuCount: cpus.length,
48 + memGiB: Math.round(os.totalmem() / 2 ** 30),
49 + shell: process.env.SHELL,
50 + editor: process.env.VISUAL ?? process.env.EDITOR,
51 + };
54 +let snapshot: Promise<HostSnapshot> | undefined;
56 +/** Lazy process-wide snapshot; loaded at most once. */
57 +export function getHostSnapshot(): Promise<HostSnapshot> {
58 + if (!snapshot) snapshot = loadHostSnapshot();
59 + return snapshot;
62 +export function renderHostSection(host: HostSnapshot): string {
63 + const lines = [
64 + "Stable host environment facts:",
65 + `hostname: ${host.hostname}`,
66 + `os: ${host.osLabel}`,
67 + `kernel: ${host.kernel}`,
68 + `arch: ${host.arch}`,
69 + host.cpuModel
70 + ? `cpu: ${host.cpuModel} × ${host.cpuCount}`
71 + : `cpu: ${host.cpuCount} cores`,
72 + `mem: ${host.memGiB} GiB`,
73 + ];
74 + if (host.shell) lines.push(`shell: ${host.shell}`);
75 + if (host.editor) lines.push(`editor: ${host.editor}`);
76 + return lines.join("\n");
79 +let section: Promise<string> | undefined;
81 +/** Lazy process-wide section text; rendered at most once. */
82 +export function getHostSection(): Promise<string> {
83 + if (!section) section = getHostSnapshot().then(renderHostSection);
84 + return section;

extensions/horst/index.ts

Added
new file mode 100644
1 +// horst — per-host environment data and tool defaults.
3 +import os from "node:os";
4 +import type {
5 + ExtensionAPI,
6 + ExtensionContext,
7 +} from "@earendil-works/pi-coding-agent";
8 +import { SettingsManager } from "@earendil-works/pi-coding-agent";
9 +import { getHostSection } from "./host.ts";
10 +import {
11 + type HorstSettings,
12 + mergeHorst,
13 + pickHorst,
14 + resolveHorstTools,
15 +} from "./settings.ts";
17 +const SETTINGS_KEY = "horst";
19 +function readHorstSettings(ctx: ExtensionContext): HorstSettings {
20 + const manager = SettingsManager.create(ctx.cwd, undefined, {
21 + projectTrusted: ctx.isProjectTrusted(),
22 + });
23 + const raw = (settings: Record<string, unknown>) =>
24 + pickHorst(settings[SETTINGS_KEY]);
25 + return mergeHorst(
26 + raw(manager.getGlobalSettings() as Record<string, unknown>),
27 + raw(manager.getProjectSettings() as Record<string, unknown>),
28 + );
31 +export default function horstExtension(pi: ExtensionAPI) {
32 + pi.on("session_start", async (_event, ctx) => {
33 + const delta = resolveHorstTools(
34 + readHorstSettings(ctx),
35 + process.platform,
36 + os.hostname(),
37 + );
38 + if (!delta) return;
39 + const known = new Set(pi.getAllTools().map((tool) => tool.name));
40 + const unknown = [...(delta.add ?? []), ...(delta.remove ?? [])].filter(
41 + (name) => !known.has(name),
42 + );
43 + if (unknown.length > 0)
44 + ctx.ui.notify(`horst: unknown tools: ${unknown.join(", ")}`, "warning");
45 + const next = pi
46 + .getActiveTools()
47 + .filter((name) => !delta.remove?.includes(name));
48 + for (const name of delta.add ?? []) {
49 + if (known.has(name) && !next.includes(name)) next.push(name);
50 + }
51 + pi.setActiveTools(next);
52 + });
54 + pi.on("before_agent_start", async (event) => {
55 + event.systemPromptOptions.sections.horst = await getHostSection();
56 + });

extensions/horst/mise.toml

Added
new file mode 100644
1 +[tasks.lint]
2 +description = "Lint horst extension"
3 +depends = ["//:install"]
4 +run = [
5 + "biome ci --config-path ../.. .",
6 + "rumdl check --config ../../.rumdl.toml .",
7 + "taplo format --check --config ../../.taplo.toml mise.toml",
8 +]
10 +[tasks.test]
11 +description = "Test horst extension"
12 +depends = ["//:install"]
13 +run = [
14 + { task = "//:test", args = ["extensions/horst"] },
17 +[tasks.check]
18 +description = "Check horst extension"
19 +depends = ["//:install"]
20 +run = [
21 + { task = "//:build", args = ["horst"] },

extensions/horst/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-horst",
3 + "type": "module",
4 + "main": "index.ts",
5 + "peerDependencies": {
6 + "@earendil-works/pi-coding-agent": "*"
7 + },
8 + "license": "MIT",
9 + "description": "Per-host environment data and tool defaults for Pi.",
10 + "keywords": [
11 + "pi",
12 + "pi-extension"
13 + ],
14 + "devDependencies": {
15 + "@marcfargas/pi-test-harness": "^0.6.1",
16 + "vitest": "^4.1.9"
17 + },
18 + "private": true

extensions/horst/settings.ts

Added
new file mode 100644
1 +// horst — settings.
2 +//
3 +// Reads the `horst` block from Pi's global and project settings.
5 +export interface HorstToolDelta {
6 + add?: string[];
7 + remove?: string[];
8 +}
10 +export interface HorstSettings {
11 + os: Record<string, HorstToolDelta>;
12 + hosts: Record<string, HorstToolDelta>;
15 +export const EMPTY_HORST_SETTINGS: HorstSettings = { os: {}, hosts: {} };
17 +export function horstOsKey(platform: string): string | undefined {
18 + if (platform === "linux") return "lnx";
19 + if (platform === "darwin") return "mac";
20 + if (platform === "win32") return "win32";
21 + return undefined;
24 +function toolNames(value: unknown): string[] | undefined {
25 + const names = Array.isArray(value)
26 + ? value.filter(
27 + (name): name is string =>
28 + typeof name === "string" && name.trim().length > 0,
29 + )
30 + : [];
31 + return names.length > 0 ? names : undefined;
34 +function pickMap(value: unknown): Record<string, HorstToolDelta> {
35 + if (typeof value !== "object" || value === null) return {};
36 + const map: Record<string, HorstToolDelta> = {};
37 + for (const [key, entry] of Object.entries(value)) {
38 + const tools = (entry as { tools?: unknown } | null)?.tools;
39 + if (typeof tools !== "object" || tools === null) continue;
40 + const { add, remove } = tools as { add?: unknown; remove?: unknown };
41 + const delta: HorstToolDelta = {};
42 + const addNames = toolNames(add);
43 + const removeNames = toolNames(remove);
44 + if (addNames) delta.add = addNames;
45 + if (removeNames) delta.remove = removeNames;
46 + if (delta.add || delta.remove) map[key.toLowerCase()] = delta;
47 + }
48 + return map;
51 +/** Extract the `horst` block, keeping only well-formed `os`/`hosts` tool deltas. */
52 +export function pickHorst(raw: unknown): HorstSettings {
53 + if (typeof raw !== "object" || raw === null) return EMPTY_HORST_SETTINGS;
54 + const block = raw as { os?: unknown; hosts?: unknown };
55 + return { os: pickMap(block.os), hosts: pickMap(block.hosts) };
58 +/** Fold partial settings over defaults; project keys win over global keys. */
59 +export function mergeHorst(...partials: HorstSettings[]): HorstSettings {
60 + const merged: HorstSettings = { os: {}, hosts: {} };
61 + for (const partial of partials) {
62 + Object.assign(merged.os, partial.os);
63 + Object.assign(merged.hosts, partial.hosts);
64 + }
65 + return merged;
68 +/**
69 + * Resolve the tool delta for this machine.
70 + * `os` deltas apply first, a matching `hosts` entry wins per field.
71 + */
72 +export function resolveHorstTools(
73 + settings: HorstSettings,
74 + platform: string,
75 + hostname: string,
76 +): HorstToolDelta | undefined {
77 + const osDelta = settings.os[horstOsKey(platform) ?? ""];
78 + const hostDelta = settings.hosts[hostname.toLowerCase()];
79 + if (!osDelta && !hostDelta) return undefined;
80 + return {
81 + add: hostDelta?.add ?? osDelta?.add,
82 + remove: hostDelta?.remove ?? osDelta?.remove,
83 + };

package-lock.json

Modified
165 165 "typebox": "*"
168 + "extensions/horst": {
169 + "name": "@bugabinga/pi-ext-horst",
170 + "license": "MIT",
171 + "devDependencies": {
172 + "@marcfargas/pi-test-harness": "^0.6.1",
173 + "vitest": "^4.1.9"
174 + },
175 + "peerDependencies": {
176 + "@earendil-works/pi-coding-agent": "*"
178 + },
168 179 "extensions/intellij": {
169 180 "name": "@bugabinga/pi-ext-intellij",
170 181 "license": "MIT",
1292 1303 "resolved": "extensions/good-job",
1293 1304 "link": true
1306 + "node_modules/@bugabinga/pi-ext-horst": {
1307 + "resolved": "extensions/horst",
1308 + "link": true
1309 + },
1295 1310 "node_modules/@bugabinga/pi-ext-intellij": {
1296 1311 "resolved": "extensions/intellij",
1297 1312 "link": true