repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(horst): distinguish login and preferred shells

265b9468e31a25ae011b66e2e75e0383f4be8d41

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (5)

extensions/horst/README.md

Modified
24 24 ```json
26 26 "horst": {
27 + "preferredShell": "nu",
27 28 "os": {
28 29 "win32": { "tools": { "add": ["powershell"], "remove": ["bash"] } }
38 +- `preferredShell`: optional declared interactive shell; independent of Pi's tool execution shells
37 39 - `os` keys: `win32`, `lnx`, `mac`
38 40 - `hosts` keys: hostname, lowercased
39 41 - both maps optional, unknown names ignored with a warning
43 45 ## 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:
47 +- Injects host facts (`<horst>`) into the system prompt:
48 + hostname, os, kernel, arch, cpu, memory, available account login shell, and configured preferred shell.
49 +- The login shell comes from the effective user's OS account record on Unix; Windows has no equivalent field.
50 +- The preferred shell is explicitly declared, not inferred from `$SHELL` or Pi's tool configuration.
51 +- Loads host facts lazily exactly once per process:
48 52 `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.
53 +- Shell preference is read at session start; reload Pi after changing settings.
51 54 - Applies the configured tool delta once per session start on top of the
52 55 active tools.

extensions/horst/__tests__/harness.test.ts

Modified
1 1 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2 2 import os, { tmpdir } from "node:os";
3 3 import path from "node:path";
4 -import { afterEach, describe, expect, it } from "vitest";
4 +import { afterEach, describe, expect, it, vi } from "vitest";
5 5 import { createTestSession, type TestSession } from "../../../test/harness";
6 6 import {
7 7 getHostSection,
20 20 describe("pickHorst", () => {
21 21 it("keeps well-formed tool deltas and lowercases keys", () => {
22 22 const settings = pickHorst({
23 + preferredShell: " nu ",
23 24 os: { WIN32: { tools: { add: ["powershell"], remove: ["bash"] } } },
24 25 hosts: { WinBox: { tools: { remove: ["write"] } } },
26 27 expect(settings).toEqual({
27 28 os: { win32: { add: ["powershell"], remove: ["bash"] } },
28 29 hosts: { winbox: { remove: ["write"] } },
30 + preferredShell: "nu",
38 40 hosts: "nope",
39 41 default: { tools: { add: ["bash"] } },
42 + preferredShell: " ",
41 44 ).toEqual(EMPTY_HORST_SETTINGS);
42 45 expect(pickHorst(undefined)).toEqual(EMPTY_HORST_SETTINGS);
46 + for (const value of [null, 42, [], {}]) {
47 + expect(pickHorst({ preferredShell: value })).toEqual(
48 + EMPTY_HORST_SETTINGS,
49 + );
50 + }
50 58 os: { win32: { add: ["powershell"] } },
51 59 hosts: { a: { remove: ["read"] } },
60 + preferredShell: "nu",
53 62 { os: { win32: { remove: ["bash"] } }, hosts: { b: { add: ["grep"] } } },
55 64 expect(merged).toEqual({
56 65 os: { win32: { remove: ["bash"] } },
57 66 hosts: { a: { remove: ["read"] }, b: { add: ["grep"] } },
67 + preferredShell: "nu",
69 + expect(
70 + mergeHorst(
71 + pickHorst({ preferredShell: "nu" }),
72 + pickHorst({ preferredShell: "fish" }),
73 + ).preferredShell,
74 + ).toBe("fish");
105 121 describe("renderHostSection", () => {
106 - it("renders stable facts and omits absent shell/editor", () => {
122 + it("renders host facts without a misleading environment shell or editor", () => {
107 123 const host: HostSnapshot = {
108 124 hostname: "winbox",
109 125 osLabel: "Fedora Linux 42",
118 134 expect(section).toContain("os: Fedora Linux 42");
119 135 expect(section).toContain("cpu: AMD Ryzen 9 × 24");
120 136 expect(section).toContain("mem: 32 GiB");
137 + expect(section).not.toContain("Stable host environment facts:");
121 138 expect(section).not.toContain("shell:");
122 139 expect(section).not.toContain("editor:");
140 + expect(
141 + renderHostSection({ ...host, loginShell: "/bin/bash" }, "nu"),
142 + ).toContain("login shell: /bin/bash\npreferred shell: nu");
143 + });
145 + it("reads account login shell independently of inherited SHELL", async () => {
146 + vi.resetModules();
147 + const userInfo = vi.spyOn(os, "userInfo").mockReturnValue({
148 + ...os.userInfo(),
149 + shell: "/bin/zsh",
150 + });
151 + try {
152 + const { getHostSection: freshSection } = await import("../host.ts");
153 + expect(await freshSection()).toContain("login shell: /bin/zsh");
154 + expect(await freshSection()).not.toContain("preferred shell:");
155 + } finally {
156 + userInfo.mockRestore();
158 + });
160 + it("omits unavailable account shell", async () => {
161 + for (const shell of [null, "", "throws"] as const) {
162 + vi.resetModules();
163 + const userInfo = vi.spyOn(os, "userInfo");
164 + if (shell === "throws")
165 + userInfo.mockImplementation(() => {
166 + throw new Error("unavailable");
167 + });
168 + else userInfo.mockReturnValue({ ...os.userInfo(), shell });
169 + try {
170 + const { getHostSection: freshSection } = await import("../host.ts");
171 + expect(await freshSection()).not.toContain("login shell:");
172 + } finally {
173 + userInfo.mockRestore();
180 233 expect(horst).toContain(`hostname: ${os.hostname()}`);
181 234 expect(getHostSection()).resolves.toBe(horst);
237 + it("injects project shell preference even without a tool delta", async () => {
238 + const root = mkdtempSync(path.join(tmpdir(), "horst-shell-"));
239 + try {
240 + mkdirSync(path.join(root, ".pi"), { recursive: true });
241 + writeFileSync(
242 + path.join(root, ".pi", "settings.json"),
243 + JSON.stringify({ horst: { preferredShell: " fish " } }),
244 + );
245 + t = await createTestSession({ cwd: root, extensions: [horstPath()] });
246 + const runner = t.session.extensionRunner;
247 + const first = await runner.emitBeforeAgentStart("prompt", undefined, {
248 + cwd: t.cwd,
249 + });
250 + const second = await runner.emitBeforeAgentStart("prompt", undefined, {
251 + cwd: t.cwd,
252 + });
253 + expect(first.systemPromptOptions.sections.horst).toContain(
254 + "preferred shell: fish",
255 + );
256 + expect(second.systemPromptOptions.sections.horst).toBe(
257 + first.systemPromptOptions.sections.horst,
258 + );
259 + } finally {
260 + t?.dispose();
261 + t = undefined;
262 + rmSync(root, { recursive: true, force: true });
264 + });

extensions/horst/host.ts

Modified
14 14 cpuModel?: string;
15 15 cpuCount: number;
16 16 memGiB: number;
17 - shell?: string;
18 - editor?: string;
17 + loginShell?: string;
21 20 function osTypeLabel(): string {
38 +function loginShell(): string | undefined {
39 + try {
40 + return os.userInfo().shell?.trim() || undefined;
41 + } catch {
42 + return undefined;
43 + }
39 46 async function loadHostSnapshot(): Promise<HostSnapshot> {
40 47 const cpus = os.cpus();
41 48 return {
46 53 cpuModel: cpus[0]?.model.trim() || undefined,
47 54 cpuCount: cpus.length,
48 55 memGiB: Math.round(os.totalmem() / 2 ** 30),
49 - shell: process.env.SHELL,
50 - editor: process.env.VISUAL ?? process.env.EDITOR,
56 + loginShell: loginShell(),
59 65 return snapshot;
62 -export function renderHostSection(host: HostSnapshot): string {
68 +export function renderHostSection(
69 + host: HostSnapshot,
70 + preferredShell?: string,
71 +): string {
63 72 const lines = [
64 - "Stable host environment facts:",
65 73 `hostname: ${host.hostname}`,
66 74 `os: ${host.osLabel}`,
67 75 `kernel: ${host.kernel}`,
71 79 : `cpu: ${host.cpuCount} cores`,
72 80 `mem: ${host.memGiB} GiB`,
74 - if (host.shell) lines.push(`shell: ${host.shell}`);
75 - if (host.editor) lines.push(`editor: ${host.editor}`);
82 + if (host.loginShell) lines.push(`login shell: ${host.loginShell}`);
83 + if (preferredShell) lines.push(`preferred shell: ${preferredShell}`);
76 84 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;
87 +/** Render the cached host facts with the current session's shell preference. */
88 +export async function getHostSection(preferredShell?: string): Promise<string> {
89 + return renderHostSection(await getHostSnapshot(), preferredShell);

extensions/horst/index.ts

Modified
31 31 export default function horstExtension(pi: ExtensionAPI) {
32 + let preferredShell: string | undefined;
32 33 pi.on("session_start", async (_event, ctx) => {
33 - const delta = resolveHorstTools(
34 - readHorstSettings(ctx),
35 - process.platform,
36 - os.hostname(),
37 - );
34 + const settings = readHorstSettings(ctx);
35 + preferredShell = settings.preferredShell;
36 + const delta = resolveHorstTools(settings, process.platform, os.hostname());
38 37 if (!delta) return;
39 38 const known = new Set(pi.getAllTools().map((tool) => tool.name));
40 39 const unknown = [...(delta.add ?? []), ...(delta.remove ?? [])].filter(
54 53 pi.on("before_agent_start", async (event) => {
55 - event.systemPromptOptions.sections.horst = await getHostSection();
54 + event.systemPromptOptions.sections.horst =
55 + await getHostSection(preferredShell);

extensions/horst/settings.ts

Modified
10 10 export interface HorstSettings {
11 11 os: Record<string, HorstToolDelta>;
12 12 hosts: Record<string, HorstToolDelta>;
13 + preferredShell?: string;
15 16 export const EMPTY_HORST_SETTINGS: HorstSettings = { os: {}, hosts: {} };
48 49 return map;
51 -/** Extract the `horst` block, keeping only well-formed `os`/`hosts` tool deltas. */
52 +/** Extract well-formed tool deltas and a declared shell preference. */
52 53 export function pickHorst(raw: unknown): HorstSettings {
53 54 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) };
55 + const block = raw as {
56 + os?: unknown;
57 + hosts?: unknown;
58 + preferredShell?: unknown;
59 + };
60 + const preferredShell =
61 + typeof block.preferredShell === "string"
62 + ? block.preferredShell.trim() || undefined
63 + : undefined;
64 + return {
65 + os: pickMap(block.os),
66 + hosts: pickMap(block.hosts),
67 + ...(preferredShell ? { preferredShell } : {}),
68 + };
58 71 /** Fold partial settings over defaults; project keys win over global keys. */
61 74 for (const partial of partials) {
62 75 Object.assign(merged.os, partial.os);
63 76 Object.assign(merged.hosts, partial.hosts);
77 + if (partial.preferredShell) merged.preferredShell = partial.preferredShell;
65 79 return merged;