repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix: load extension settings through Pi API

0054ab149fc0521c211249aff4e28f746881b3d7

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (23)

extensions/angel/__tests__/settings.test.ts

Modified
1 +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
2 +import { tmpdir } from "node:os";
3 +import path from "node:path";
1 4 import { describe, expect, it } from "vitest";
2 5 import { __test } from "../index.ts";
7 +function project(settings?: unknown): { cwd: string; agentDir: string } {
8 + const cwd = mkdtempSync(path.join(tmpdir(), "angel-settings-project-"));
9 + const agentDir = mkdtempSync(path.join(tmpdir(), "angel-settings-agent-"));
10 + if (settings !== undefined) {
11 + mkdirSync(path.join(cwd, ".pi"));
12 + writeFileSync(
13 + path.join(cwd, ".pi", "settings.json"),
14 + JSON.stringify(settings),
15 + );
16 + }
17 + return { cwd, agentDir };
4 20 describe("angel settings", () => {
5 - it("loads only the merged Pi settings angel block", () => {
6 - expect(
7 - __test.loadSettings({
8 - settingsManager: {
9 - getSettings: () => ({
10 - angel: { enabled: false, maxCallsPerTask: 4 },
11 - }),
12 - },
13 - } as never),
14 - ).toMatchObject({ enabled: false, maxCallsPerTask: 4 });
21 + it("loads the project Pi settings angel block", () => {
22 + const { cwd, agentDir } = project({
23 + angel: { enabled: false, maxCallsPerTask: 4 },
24 + });
25 + expect(__test.loadSettings(cwd, agentDir)).toMatchObject({
26 + enabled: false,
27 + maxCallsPerTask: 4,
28 + });
17 - it("defaults when runtime settings are missing", () => {
18 - expect(__test.loadSettings({} as never)).toEqual({});
31 + it("defaults when settings are missing", () => {
32 + const { cwd, agentDir } = project();
33 + expect(__test.loadSettings(cwd, agentDir)).toEqual({});

extensions/angel/index.ts

Modified
21 21 } from "@earendil-works/pi-coding-agent";
22 22 import {
23 23 convertToLlm,
24 + SettingsManager,
24 25 serializeConversation,
25 26 } from "@earendil-works/pi-coding-agent";
26 27 import type { AutocompleteItem } from "@earendil-works/pi-tui";
74 75 policyGate?: "off" | "block";
77 -interface SettingsAPI extends ExtensionAPI {
78 - settingsManager?: { getSettings(): Record<string, unknown> | undefined };
81 78 interface Advice {
82 79 summary: string;
83 80 nextAction: string;
174 171 return v !== null && typeof v === "object" && !Array.isArray(v);
177 -function loadSettings(pi: ExtensionAPI): Settings {
178 - const allSettings = (pi as SettingsAPI).settingsManager?.getSettings();
179 - return isPlainObject(allSettings?.angel)
180 - ? (allSettings.angel as Settings)
181 - : {};
174 +function loadSettings(cwd = process.cwd(), agentDir?: string): Settings {
175 + const manager = SettingsManager.create(cwd, agentDir);
176 + const global = manager.getGlobalSettings() as Record<string, unknown>;
177 + const project = manager.getProjectSettings() as Record<string, unknown>;
178 + return {
179 + ...(isPlainObject(global.angel) ? global.angel : {}),
180 + ...(isPlainObject(project.angel) ? project.angel : {}),
181 + };
184 184 // ── model resolution ───────────────────────────────────────────────────
479 479 // ── extension entry ────────────────────────────────────────────────────
481 481 export default function (pi: ExtensionAPI) {
482 - const settings = loadSettings(pi);
482 + const settings = loadSettings();
483 483 const maxCalls = settings.maxCallsPerTask ?? DEFAULT_MAX_CALLS;
484 484 const autoOnErrors = settings.autoOnErrors ?? DEFAULT_AUTO_ON_ERRORS;
485 485 const policyGate = settings.policyGate ?? "block";

extensions/cmprss/index.ts

Modified
1 1 import { createHash } from "node:crypto";
2 2 import { readFileSync } from "node:fs";
3 -import type {
4 - ContextUsage,
5 - ExtensionAPI,
3 +import {
4 + type ContextUsage,
5 + type ExtensionAPI,
6 + SettingsManager,
6 7 } from "@earendil-works/pi-coding-agent";
7 8 import { Type } from "typebox";
321 -function settingsFrom(pi: unknown): CmprssConfig {
322 - const raw = (
323 - pi as {
324 - settingsManager?: {
325 - getSettings?: () => Record<string, unknown> | undefined;
326 - };
327 - }
328 - ).settingsManager?.getSettings?.();
329 - return normalizeConfig(isRecord(raw?.cmprss) ? raw.cmprss : {});
322 +function settingsFrom(cwd = process.cwd()): CmprssConfig {
323 + const manager = SettingsManager.create(cwd);
324 + const global = manager.getGlobalSettings() as Record<string, unknown>;
325 + const project = manager.getProjectSettings() as Record<string, unknown>;
326 + return normalizeConfig({
327 + ...(isRecord(global.cmprss) ? global.cmprss : {}),
328 + ...(isRecord(project.cmprss) ? project.cmprss : {}),
329 + });
332 332 export function createRuntime(
537 537 export default function cmprssExtension(pi: ExtensionAPI) {
538 - let runtime = createRuntime(settingsFrom(pi), (event) =>
538 + let runtime = createRuntime(settingsFrom(), (event) =>
539 539 pi.appendEntry(ENTRY_TYPE, event),
542 542 pi.on("session_start", (_event, ctx) => {
543 - runtime = createRuntime(settingsFrom(pi), (event) =>
543 + runtime = createRuntime(settingsFrom(ctx.cwd), (event) =>
544 544 pi.appendEntry(ENTRY_TYPE, event),
546 546 replayState(

extensions/devil/index.ts

Modified
178 178 onBlocking?: "surface" | "escalate" | "ignore";
181 -interface SettingsAPI extends ExtensionAPI {
182 - settingsManager?: { getSettings(): Record<string, unknown> | undefined };
181 +function devilBlock(settings: unknown): DevilSettings {
182 + if (!settings || typeof settings !== "object" || Array.isArray(settings))
183 + return {};
184 + const devil = (settings as Record<string, unknown>).devil;
185 + return devil && typeof devil === "object" && !Array.isArray(devil)
186 + ? (devil as DevilSettings)
187 + : {};
190 +function readDevilSettings(cwd = process.cwd()): DevilSettings {
191 + const manager = SettingsManager.create(cwd);
192 + return {
193 + ...devilBlock(manager.getGlobalSettings()),
194 + ...devilBlock(manager.getProjectSettings()),
195 + };
185 198 interface SynthesisResult {
922 935 export default async function (pi: ExtensionAPI) {
923 936 gcEphemeralForks();
924 - const settings = (pi as SettingsAPI).settingsManager?.getSettings();
925 - const devilSettings: DevilSettings = (settings?.devil ?? {}) as DevilSettings;
937 + const devilSettings = readDevilSettings();
926 938 const activeControllers = new Set<AbortController>();
928 940 // ── Flags ─────────────────────────────────────────────────────────

extensions/goal/__tests__/unit.test.ts

Modified
109 109 setActiveTools: (next: string[]) => {
110 110 activeTools = next;
112 - settingsManager: {
113 - getSettings: () => ({ goal: { judgeModel: "test/judge" } }),
114 - },
115 112 events: { emit: () => {} },
117 114 const ctx = {
610 607 it("loads settings with clamped integers and trimmed judge model", () => {
611 608 expect(
612 609 __goalTest.loadSettings({
613 - settingsManager: {
614 - getSettings: () => ({
615 - goal: {
616 - tailBytes: 1_000_000,
617 - judgeModel: " test/model ",
618 - tokenBudget: "100k",
619 - timeBudget: "2h",
620 - },
621 - }),
610 + goal: {
611 + tailBytes: 1_000_000,
612 + judgeModel: " test/model ",
613 + tokenBudget: "100k",
614 + timeBudget: "2h",
623 - } as never),
616 + }),
624 617 ).toEqual({
625 618 judgeModel: "test/model",
626 619 plannerModel: undefined,
632 625 expect(
633 626 __goalTest.loadSettings({
634 - settingsManager: {
635 - getSettings: () => ({
636 - goal: { tailBytes: "bad", judgeModel: " " },
637 - }),
638 - },
639 - } as never),
627 + goal: { tailBytes: "bad", judgeModel: " " },
628 + }),
640 629 ).toEqual({
641 630 judgeModel: undefined,
642 631 plannerModel: undefined,
928 917 expect(() =>
929 918 __goalTest.createGoalState(
930 919 "x".repeat(4_001),
931 - __goalTest.loadSettings({
932 - settingsManager: { getSettings: () => ({}) },
933 - } as never),
920 + __goalTest.loadSettings({}),
934 921 "session-1",
936 923 ).toThrow("Goal objective is too long");
2179 2166 describe("loadSettings edge cases", () => {
2180 2167 it("returns defaults when settings missing", () => {
2181 - expect(
2182 - __goalTest.loadSettings({
2183 - settingsManager: { getSettings: () => ({}) },
2184 - } as never),
2185 - ).toEqual({
2168 + expect(__goalTest.loadSettings({})).toEqual({
2186 2169 judgeModel: undefined,
2187 2170 plannerModel: undefined,
2188 2171 plannerThinkingLevel: "high",
2192 2175 it("returns defaults when goal settings missing", () => {
2193 - expect(
2194 - __goalTest.loadSettings({
2195 - settingsManager: { getSettings: () => ({ other: true }) },
2196 - } as never),
2197 - ).toEqual({
2176 + expect(__goalTest.loadSettings({ other: true })).toEqual({
2198 2177 judgeModel: undefined,
2199 2178 plannerModel: undefined,
2200 2179 plannerThinkingLevel: "high",
2204 2183 it("ignores non-string judgeModel", () => {
2205 2184 expect(
2206 - __goalTest.loadSettings({
2207 - settingsManager: {
2208 - getSettings: () => ({ goal: { judgeModel: 123 } }),
2209 - },
2210 - } as never).judgeModel,
2185 + __goalTest.loadSettings({ goal: { judgeModel: 123 } }).judgeModel,
2211 2186 ).toBeUndefined();

extensions/goal/index.ts

Modified
259 259 type GoalUiMode = "normal" | "judging" | "queued";
260 260 type GoalWidgetMode = "compact" | "expanded";
262 -type SettingsAPI = ExtensionAPI & {
263 - settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
266 262 function isRecord(value: unknown): value is Record<string, unknown> {
267 263 return value !== null && typeof value === "object" && !Array.isArray(value);
323 319 : DEFAULT_PLANNER_THINKING_LEVEL;
326 -function loadSettings(pi: ExtensionAPI): GoalSettings {
327 - const all = (pi as SettingsAPI).settingsManager?.getSettings?.();
328 - const raw = isRecord(all?.goal) ? all.goal : {};
322 +function loadSettings(all: unknown): GoalSettings {
323 + const raw = isRecord(all) && isRecord(all.goal) ? all.goal : {};
329 324 const settings: GoalSettings = {
330 325 judgeModel:
331 326 typeof raw.judgeModel === "string" && raw.judgeModel.trim()
347 342 return settings;
345 +function settingsForCwd(cwd: string): GoalSettings {
346 + const manager = SettingsManager.create(cwd);
347 + const global = manager.getGlobalSettings() as Record<string, unknown>;
348 + const project = manager.getProjectSettings() as Record<string, unknown>;
349 + return loadSettings({
350 + goal: {
351 + ...(isRecord(global.goal) ? global.goal : {}),
352 + ...(isRecord(project.goal) ? project.goal : {}),
353 + },
354 + });
350 357 function textFromContent(content: unknown): string {
351 358 if (typeof content === "string") return content;
352 359 if (!Array.isArray(content)) return "";
2081 2088 !globals[PLANNER_FOR_TEST]
2083 2090 return;
2084 - void runPlanner(ctx, state, dossier, loadSettings(pi), trigger)
2091 + void runPlanner(ctx, state, dossier, settingsForCwd(ctx.cwd), trigger)
2085 2092 .then((next) => {
2087 2094 const latest = latestGoalDossier(ctx, state.id) ?? dossier;
2809 2816 if (!state) {
2810 2817 const objective = extractStandingGoalObjective(event.prompt);
2811 2818 if (objective) {
2812 - const settings = loadSettings(pi);
2819 + const settings = settingsForCwd(ctx.cwd);
2814 2821 state = createGoalState(objective, settings, currentSessionId(ctx));
2815 2822 } catch (error) {
2920 2927 return;
2922 2929 piRetryDeferrals = 0;
2923 - const settings = loadSettings(pi);
2930 + const settings = settingsForCwd(ctx.cwd);
2924 2931 let dossier = ensureDossier(pi, ctx, state);
2925 2932 dossier = appendTurnEvidenceToDossier(
3331 3338 `Prompt template not found: ${input.split(/\s+/, 1)[0]}`,
3332 3339 "warning",
3334 - const settings = loadSettings(pi);
3341 + const settings = settingsForCwd(ctx.cwd);
3336 3343 state = createGoalState(objective, settings, currentSessionId(ctx));
3337 3344 } catch (error) {

extensions/lazy/__tests__/harness.test.ts

Modified
1 1 import { execFileSync } from "node:child_process";
2 2 import { mkdirSync, writeFileSync } from "node:fs";
3 +import path from "node:path";
3 4 import { fileURLToPath } from "node:url";
4 5 import { afterEach, describe, expect, it } from "vitest";
5 6 import { createTestSession, type TestSession } from "../../../test/harness";
157 158 it("status gracefully does nothing when disabled", async () => {
158 - t = await createTestSession({
159 - extensionFactories: [
160 - (pi) =>
161 - lazyExtension({
162 - ...pi,
163 - settingsManager: {
164 - getSettings: () => ({ lazy: { status: false } }),
165 - },
166 - } as never),
167 - ],
168 - });
159 + t = await createTestSession({ extensionFactories: [lazyExtension] });
160 + mkdirSync(path.join(t.cwd, ".pi"), { recursive: true });
161 + writeFileSync(
162 + path.join(t.cwd, ".pi", "settings.json"),
163 + JSON.stringify({ lazy: { status: false } }),
164 + );
169 165 t.events.ui.length = 0;
170 166 await runCommand("lazy", "ultra");
171 167 expect(uiArgs("setStatus")).toEqual([]);

extensions/lazy/__tests__/unit.test.ts

Modified
91 91 JSON.stringify({ lazy: { defaultMode: "lite" } }),
94 - expect(
95 - loadLazySettingsForCwd(dir, {
96 - settingsManager: {
97 - getSettings: () => ({ lazy: { defaultMode: "ultra" } }),
98 - },
99 - }).defaultMode,
100 - ).toBe("ultra");
94 + mkdirSync(path.join(dir, ".pi"));
95 + writeFileSync(
96 + path.join(dir, ".pi", "settings.json"),
97 + JSON.stringify({ lazy: { defaultMode: "ultra" } }),
98 + );
99 + expect(loadLazySettingsForCwd(dir).defaultMode).toBe("ultra");
102 - expect(
103 - loadLazySettingsForCwd(dir, {
104 - settingsManager: { getSettings: () => ({}) },
105 - }).defaultMode,
106 - ).toBe("full");
101 + writeFileSync(path.join(dir, ".pi", "settings.json"), "{}");
102 + expect(loadLazySettingsForCwd(dir).defaultMode).toBe("full");
109 105 it("prints settings snippet", () => {

extensions/lazy/index.ts

Modified
81 81 ): void {
82 82 state.mode = mode;
83 83 pi.appendEntry(ENTRY_TYPE, { mode, at: Date.now() });
84 - updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd, pi).status);
84 + updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd).status);
87 87 function sendSkill(
114 114 return COMPLETIONS.filter((item) => item.value.startsWith(clean));
116 116 handler: async (args, ctx) => {
117 - const settings = loadLazySettingsForCwd(ctx.cwd, pi);
117 + const settings = loadLazySettingsForCwd(ctx.cwd);
118 118 const command = parseLazyCommand(args, settings.defaultMode);
119 119 if (command.kind === "invalid") {
120 120 notify(ctx, command.message);
162 162 pi.on("session_start", (_event, ctx) => {
163 - const settings = loadLazySettingsForCwd(ctx.cwd, pi);
163 + const settings = loadLazySettingsForCwd(ctx.cwd);
164 164 state.mode = replayMode(
165 165 ctx.sessionManager.getBranch() as EntryLike[],
166 166 settings.defaultMode,
195 195 pi.on("agent_start", (_event, ctx) => {
196 196 state.activeGeneration = true;
197 - updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd, pi).status);
197 + updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd).status);
200 200 pi.on("agent_end", async (_event, ctx) => {
201 201 state.activeGeneration = false;
202 - updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd, pi).status);
202 + updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd).status);
204 204 const root = await pi.exec("git", ["rev-parse", "--show-toplevel"], {
205 205 cwd: ctx.cwd,

extensions/lazy/src/config.ts

Modified
1 +import { SettingsManager } from "@earendil-works/pi-coding-agent";
1 2 import { type LazyMode, normalizeMode } from "./modes.ts";
3 4 export interface LazySettings {
10 11 status: true,
13 -type SettingsAPI = {
14 - settingsManager?: { getSettings(): unknown };
15 -};
17 -function settingsApi(value: unknown): SettingsAPI {
18 - return value && typeof value === "object" ? (value as SettingsAPI) : {};
19 -}
21 14 function isPlainObject(value: unknown): value is Record<string, unknown> {
22 15 return value !== null && typeof value === "object" && !Array.isArray(value);
48 41 return mergeLazySettings(pickLazy(runtime));
51 -export function loadLazySettingsForCwd(
52 - _cwd: string,
53 - pi: unknown,
54 -): LazySettings {
55 - return loadLazySettings(settingsApi(pi).settingsManager?.getSettings());
44 +export function loadLazySettingsForCwd(cwd: string): LazySettings {
45 + const manager = SettingsManager.create(cwd);
46 + return mergeLazySettings(
47 + pickLazy(manager.getGlobalSettings()),
48 + pickLazy(manager.getProjectSettings()),
49 + );
58 52 export function settingsSnippet(mode: LazyMode): string {

extensions/leaks/__tests__/pi-direct.test.ts

Modified
17 17 handlers,
18 18 commands,
19 19 pi: {
20 - settingsManager: {
21 - getSettings: () => ({
22 - leaks: { regex: [{ pattern: "TOKEN_[0-9]+", label: "TOKEN" }] },
23 - }),
24 - },
25 20 on(name: string, handler: Handler) {
26 21 handlers.set(name, handler);
52 47 function ui(confirm = true) {
53 48 const notices: string[] = [];
54 49 const statuses: string[] = [];
50 + const cwd = temp();
51 + mkdirSync(path.join(cwd, ".pi"));
52 + writeFileSync(
53 + path.join(cwd, ".pi", "settings.json"),
54 + JSON.stringify({
55 + leaks: { regex: [{ pattern: "TOKEN_[0-9]+", label: "TOKEN" }] },
56 + }),
57 + );
55 58 return {
56 59 notices,
57 60 statuses,
58 61 ctx: {
59 62 hasUI: true,
60 - cwd: temp(),
63 + cwd,
61 64 ui: {
62 65 setStatus(_key: string, text: string) {
63 66 statuses.push(text);
79 82 leaks(runtime.pi as never);
80 83 const secret = "sk-or-v1-" + "9".repeat(64);
81 84 const view = ui(false);
82 - mkdirSync(path.join(view.ctx.cwd, ".pi"));
83 - writeFileSync(path.join(view.ctx.cwd, ".pi", "settings.json"), "{", "utf8");
85 86 await runtime.handlers.get("session_start")?.({}, view.ctx);
86 87 expect(view.statuses.at(-1)).toContain("leaks on");
91 92 await runtime.handlers.get("session_start")?.(
93 - { ...view.ctx, cwd: temp() },
94 + { ...ui(false).ctx, hasUI: false },
96 97 const custom = await runtime.handlers.get("before_provider_request")?.(

extensions/leaks/src/pi.ts

Modified
1 1 import path from "node:path";
2 -import type {
3 - ExtensionAPI,
4 - ExtensionContext,
2 +import {
3 + type ExtensionAPI,
4 + type ExtensionContext,
5 + SettingsManager,
5 6 } from "@earendil-works/pi-coding-agent";
6 7 import { LeaksEngine } from "./engine.ts";
7 8 import { isPlainObject, sanitizeTag } from "./safety.ts";
8 9 import { loadLeaksSettings } from "./settings.ts";
10 -type SettingsAPI = ExtensionAPI & {
11 - settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
12 -};
14 11 export default function leaks(pi: ExtensionAPI) {
15 12 const engine = new LeaksEngine();
17 14 pi.on("session_start", async (_event, ctx) => {
18 - engine.reload(ctx.cwd, readSettings(pi), process.env);
15 + engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
19 16 if (ctx.hasUI) ctx.ui.setStatus("leaks", "leaks on | last 0");
83 80 return;
85 82 if (command === "reload") {
86 - engine.reload(ctx.cwd, readSettings(pi), process.env);
83 + engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
87 84 ctx.ui.notify("leaks reloaded", "info");
88 85 return;
260 -function readSettings(pi: ExtensionAPI) {
261 - return loadLeaksSettings((pi as SettingsAPI).settingsManager?.getSettings?.())
262 - .settings;
257 +function readSettings(cwd: string) {
258 + const manager = SettingsManager.create(cwd);
259 + const global = manager.getGlobalSettings() as Record<string, unknown>;
260 + const project = manager.getProjectSettings() as Record<string, unknown>;
261 + return loadLeaksSettings({
262 + leaks: {
263 + ...(isPlainObject(global.leaks) ? global.leaks : {}),
264 + ...(isPlainObject(project.leaks) ? project.leaks : {}),
265 + },
266 + }).settings;
265 269 function formatNotice(result: {

extensions/neko/__tests__/lifecycle.test.ts

Modified
76 76 editorPaddingX: 1,
79 + writeSettings(runtimeSettings);
79 80 const handlers = new Map<string, Handler[]>();
80 81 const commands = new Map<string, any>();
81 82 const uiCalls: Array<{ method: string; args: any[] }> = [];
95 96 list.push(handler);
96 97 handlers.set(event, list);
98 - settingsManager: {
99 - getSettings: () => runtimeSettings,
100 - },
101 99 registerCommand(name: string, options: any) {
102 100 commands.set(name, options);

extensions/neko/index.ts

Modified
7 7 type ExtensionAPI,
8 8 type ExtensionContext,
9 9 getAgentDir,
10 + SettingsManager,
10 11 } from "@earendil-works/pi-coding-agent";
11 12 import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
384 -type SettingsAPI = ExtensionAPI & {
385 - settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
386 -};
388 385 interface NekoSettings {
389 386 enabled?: boolean;
392 -function mergedSettings(pi: ExtensionAPI): Record<string, unknown> {
393 - return (pi as SettingsAPI).settingsManager?.getSettings?.() ?? {};
389 +function settingsRecord(value: unknown): Record<string, unknown> {
390 + return value && typeof value === "object" && !Array.isArray(value)
391 + ? (value as Record<string, unknown>)
392 + : {};
396 -function resolveEditorPaddingX(pi: ExtensionAPI): number {
397 - const value = mergedSettings(pi).editorPaddingX;
395 +function mergedSettings(cwd: string): Record<string, unknown> {
396 + const manager = SettingsManager.create(cwd);
397 + const global = manager.getGlobalSettings() as Record<string, unknown>;
398 + const project = manager.getProjectSettings() as Record<string, unknown>;
399 + return {
400 + ...global,
401 + ...project,
402 + neko: {
403 + ...settingsRecord(global.neko),
404 + ...settingsRecord(project.neko),
405 + },
406 + };
409 +function resolveEditorPaddingX(cwd: string): number {
410 + const value = mergedSettings(cwd).editorPaddingX;
398 411 return typeof value === "number" && value > 0 ? value : 0;
401 -function isNekoEnabled(pi: ExtensionAPI, override?: boolean): boolean {
414 +function isNekoEnabled(cwd: string, override?: boolean): boolean {
402 415 if (override !== undefined) return override;
403 - const raw = mergedSettings(pi).neko;
416 + const raw = mergedSettings(cwd).neko;
404 417 return !(
405 418 raw &&
406 419 typeof raw === "object" &&
466 479 disposeEditors();
468 - if (!isNekoEnabled(pi, enabledOverride)) {
481 + if (!isNekoEnabled(ctx.cwd, enabledOverride)) {
469 482 ctx.ui.setWorkingVisible?.(true);
470 483 ctx.ui.setEditorComponent?.(undefined);
471 484 return;
474 487 ctx.ui.setWorkingVisible?.(false);
476 - const paddingX = resolveEditorPaddingX(pi);
489 + const paddingX = resolveEditorPaddingX(ctx.cwd);
477 490 ctx.ui.setEditorComponent?.((tui, theme, keybindings) => {
478 491 const editor = new NekoEditor(
479 492 paddingX,
538 551 handler: async (args, ctx) => {
539 552 const arg = args.trim().toLowerCase();
540 - const enabled = isNekoEnabled(pi, enabledOverride);
553 + const enabled = isNekoEnabled(ctx.cwd, enabledOverride);
542 555 switch (arg) {
543 556 case "":

extensions/q/index.ts

Modified
4 4 import { randomUUID } from "node:crypto";
5 5 import {
6 6 BorderedLoader,
7 7 type ExtensionAPI,
8 8 type ExtensionCommandContext,
9 9 type ExtensionContext,
10 + SettingsManager,
10 11 } from "@earendil-works/pi-coding-agent";
11 12 import { truncateToWidth } from "@earendil-works/pi-tui";
12 13 import { DISCUSSION_WIDGET_ID, RETURN_FAILURE_CHOICES } from "./constants.js";
31 32 } from "./types.js";
32 33 import { runWizard } from "./wizard-ui.js";
34 -type SettingsAPI = ExtensionAPI & {
35 - settingsManager?: { getSettings(): Record<string, unknown> | undefined };
36 -};
38 35 type ExtractionOutcome =
39 36 | { status: "ok"; questions: QuestionItem[] }
40 37 | { status: "cancelled" }
41 38 | { status: "error"; message: string };
43 -function readSettings(pi: ExtensionAPI): { model: string | undefined } {
44 - const raw = (pi as SettingsAPI).settingsManager?.getSettings?.();
45 - const q =
46 - raw &&
47 - typeof raw === "object" &&
48 - !Array.isArray(raw) &&
49 - "q" in raw &&
50 - typeof raw.q === "object" &&
51 - raw.q !== null &&
52 - !Array.isArray(raw.q)
53 - ? (raw.q as Record<string, unknown>)
54 - : {};
40 +function readSettings(cwd = process.cwd()): { model: string | undefined } {
41 + const manager = SettingsManager.create(cwd);
42 + const global = manager.getGlobalSettings() as Record<string, unknown>;
43 + const project = manager.getProjectSettings() as Record<string, unknown>;
44 + const q = {
45 + ...(global.q && typeof global.q === "object" && !Array.isArray(global.q)
46 + ? (global.q as Record<string, unknown>)
47 + : {}),
48 + ...(project.q && typeof project.q === "object" && !Array.isArray(project.q)
49 + ? (project.q as Record<string, unknown>)
50 + : {}),
51 + };
55 52 return {
56 53 model:
57 54 typeof q.model === "string" && q.model.trim()
427 424 return { systemPrompt: event.systemPrompt + discussionPrompt(meta) };
430 - const settings = readSettings(pi);
427 + const settings = readSettings();
432 429 pi.on("message_end", (event, ctx) => {
433 430 const text = textOfAssistantMessage(event.message);

extensions/tldr/index.ts

Modified
1 1 import type { Model, UserMessage } from "@earendil-works/pi-ai";
2 2 import { complete } from "@earendil-works/pi-ai";
3 -import type {
4 - ExtensionAPI,
5 - ExtensionContext,
3 +import {
4 + type ExtensionAPI,
5 + type ExtensionContext,
6 + SettingsManager,
6 7 } from "@earendil-works/pi-coding-agent";
8 -type SettingsAPI = ExtensionAPI & {
9 - settingsManager?: { getSettings(): Record<string, unknown> | undefined };
10 -};
12 9 type TldrSettings = {
13 10 model?: string;
212 209 ctx.ui.setWidget(WIDGET_KEY, undefined);
215 -function settingsFrom(pi: ExtensionAPI): TldrSettings {
216 - const raw = (pi as SettingsAPI).settingsManager?.getSettings?.();
217 - const tldr = isRecord(raw?.tldr) ? raw.tldr : {};
212 +function settingsFrom(cwd = process.cwd()): TldrSettings {
213 + const manager = SettingsManager.create(cwd);
214 + const global = manager.getGlobalSettings() as Record<string, unknown>;
215 + const project = manager.getProjectSettings() as Record<string, unknown>;
216 + const tldr = {
217 + ...(isRecord(global.tldr) ? global.tldr : {}),
218 + ...(isRecord(project.tldr) ? project.tldr : {}),
219 + };
218 220 return {
219 221 model:
220 222 typeof tldr.model === "string" && tldr.model.trim()
632 634 return function tldrExtension(pi: ExtensionAPI) {
633 635 const facts = new FactCollector();
634 - const settings = settingsFrom(pi);
636 + const settings = settingsFrom();
635 637 const engine = new TldrEngine({
636 638 facts,
637 639 generate: deps.generate,

extensions/tune/__tests__/unit.test.ts

Modified
1 1 import * as fs from "node:fs";
2 +import * as os from "node:os";
2 3 import * as path from "node:path";
3 4 import { DEFAULT_MAX_LINES } from "@earendil-works/pi-coding-agent";
4 5 import { describe, expect, it } from "vitest";
81 82 // ── Tune config ───────────────────────────────────────────────────────────
83 84 describe("tune settings", () => {
85 + function project(tune: Record<string, unknown>): string {
86 + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "tune-settings-"));
87 + fs.mkdirSync(path.join(cwd, ".pi"));
88 + fs.writeFileSync(
89 + path.join(cwd, ".pi", "settings.json"),
90 + JSON.stringify({ tune }),
91 + );
92 + return cwd;
93 + }
84 95 it("reads positive numeric limits from settings.tune", () => {
85 96 expect(
86 - __test.readTuneSettings({
87 - settingsManager: {
88 - getSettings: () => ({
89 - tune: { maxIterations: 9.8, autoResumeLimit: 12.9 },
90 - }),
91 - },
92 - } as never),
97 + __test.readTuneSettings(
98 + project({ maxIterations: 9.8, autoResumeLimit: 12.9 }),
99 + ),
93 100 ).toMatchObject({ maxIterations: 9, autoResumeLimit: 12 });
100 107 { maxIterations: -1, autoResumeLimit: -1 },
101 108 { maxIterations: "20", autoResumeLimit: "20" },
103 - expect(
104 - __test.readTuneSettings({
105 - settingsManager: { getSettings: () => ({ tune }) },
106 - } as never),
107 - ).toMatchObject({ maxIterations: null, autoResumeLimit: null });
110 + expect(__test.readTuneSettings(project(tune))).toMatchObject({
111 + maxIterations: null,
112 + autoResumeLimit: null,
113 + });

extensions/tune/index.ts

Modified
25 25 DEFAULT_MAX_BYTES,
26 26 DEFAULT_MAX_LINES,
27 27 formatSize,
28 + SettingsManager,
28 29 truncateTail,
29 30 } from "@earendil-works/pi-coding-agent";
30 31 import {
478 479 return base;
481 -type SettingsAPI = ExtensionAPI & {
482 - settingsManager?: { getSettings?(): Record<string, unknown> | undefined };
485 482 interface TuneSettings {
486 483 maxIterations: number | null;
487 484 autoResumeLimit: number | null;
494 491 : null;
497 -function readTuneSettings(pi: ExtensionAPI): TuneSettings {
498 - const settings = (pi as SettingsAPI).settingsManager?.getSettings?.() ?? {};
499 - const tune =
500 - settings.tune &&
501 - typeof settings.tune === "object" &&
502 - !Array.isArray(settings.tune)
503 - ? (settings.tune as Record<string, unknown>)
494 +function readTuneSettings(cwd = process.cwd()): TuneSettings {
495 + const manager = SettingsManager.create(cwd);
496 + const global = manager.getGlobalSettings() as Record<string, unknown>;
497 + const project = manager.getProjectSettings() as Record<string, unknown>;
498 + const globalTune =
499 + global.tune &&
500 + typeof global.tune === "object" &&
501 + !Array.isArray(global.tune)
502 + ? (global.tune as Record<string, unknown>)
504 + const projectTune =
505 + project.tune &&
506 + typeof project.tune === "object" &&
507 + !Array.isArray(project.tune)
508 + ? (project.tune as Record<string, unknown>)
509 + : {};
510 + const tune: Record<string, unknown> = {
511 + ...globalTune,
512 + ...projectTune,
513 + shortcuts: {
514 + ...(globalTune.shortcuts &&
515 + typeof globalTune.shortcuts === "object" &&
516 + !Array.isArray(globalTune.shortcuts)
517 + ? globalTune.shortcuts
518 + : {}),
519 + ...(projectTune.shortcuts &&
520 + typeof projectTune.shortcuts === "object" &&
521 + !Array.isArray(projectTune.shortcuts)
522 + ? projectTune.shortcuts
523 + : {}),
524 + },
525 + };
526 + const settings = { ...global, ...project, tune };
505 527 return {
506 528 maxIterations: positiveIntOrNull(tune.maxIterations),
507 529 autoResumeLimit: positiveIntOrNull(tune.autoResumeLimit),
1173 1195 const BENCHMARK_GUARDRAIL =
1174 1196 "Be careful not to overfit to the benchmarks and do not cheat on the benchmarks.";
1175 1197 const SETTLED_WINDOW_MS = 800;
1176 - const tuneSettings = (): TuneSettings => readTuneSettings(pi);
1198 + let settingsCwd = process.cwd();
1199 + const tuneSettings = (): TuneSettings => readTuneSettings(settingsCwd);
1177 1200 const shortcuts = tuneSettings().shortcuts;
1179 1202 const dashboardHintVariants = (
1691 1714 // ── Lifecycle hooks ─────────────────────────────────────────────────
1693 1716 pi.on("session_start", async (_e, ctx) => {
1717 + settingsCwd = ctx.cwd;
1694 1718 reconstructState(ctx);
1695 1719 setTuneToolsActive(pi, getRuntime(ctx).tuneMode);

extensions/ultra/__tests__/settings.test.ts

Modified
116 116 concurrency: 9,
117 117 maxRetries: 4,
118 118 subagentExtensions: "all",
119 - modelTiers: { big: "openai/gpt-5" },
119 + modelTiers: {
120 + small: "openai/gpt-5-mini",
121 + big: "openai/gpt-5",
122 + },
133 136 describe("loadUltraSettings", () => {
134 - it("uses runtime Pi settings over defaults", () => {
137 + it("merges global and project Pi settings over defaults", () => {
135 138 const merged = loadUltraSettings({
136 - runtime: { ultra: { concurrency: 10, maxRetries: 9 } },
139 + global: {
140 + ultra: {
141 + concurrency: 10,
142 + modelTiers: { small: "openai/gpt-5-mini" },
143 + },
144 + },
145 + project: {
146 + ultra: {
147 + maxRetries: 9,
148 + modelTiers: { big: "openai/gpt-5" },
149 + },
150 + },
139 153 expect(merged).toEqual({
141 155 concurrency: 10,
142 156 maxRetries: 9,
143 157 subagentExtensions: "all",
144 - modelTiers: {},
158 + modelTiers: {
159 + small: "openai/gpt-5-mini",
160 + big: "openai/gpt-5",
161 + },

extensions/ultra/index.ts

Modified
19 19 getAgentDir,
20 20 getMarkdownTheme,
21 21 SessionManager,
22 + SettingsManager,
22 23 } from "@earendil-works/pi-coding-agent";
23 24 import { Markdown } from "@earendil-works/pi-tui";
24 25 import { Type } from "typebox";
88 - // Settings: resolved per-invocation so the runtime `settingsManager` (which
89 - // can change mid-session) always wins. The angel precedence pattern.
90 - const settings = (): UltraSettings =>
91 - loadUltraSettings({
92 - runtime: (
93 - pi as { settingsManager?: { getSettings(): unknown } }
94 - ).settingsManager?.getSettings(),
89 + const settings = (cwd: string): UltraSettings => {
90 + const manager = SettingsManager.create(cwd);
91 + return loadUltraSettings({
92 + global: manager.getGlobalSettings(),
93 + project: manager.getProjectSettings(),
95 + };
97 97 // Discovery is lazy — NEVER run in `session_start` (extensions/AGENTS.md). The
98 98 // first tool/command/completion use pays for it once, then it's cached.
270 270 renderResult: renderUltraResult,
271 271 async execute(_toolCallId, params, signal, onUpdate, ctx) {
272 - const cfg = settings();
272 + const cfg = settings(ctx.cwd);
273 273 if (!cfg.enabled) {
274 274 return {
275 275 content: [
349 349 return;
351 351 if (action === "Resume" && run.spec) {
352 - startBackground(ctx, run.spec, run.args, settings(), run.id);
352 + startBackground(ctx, run.spec, run.args, settings(ctx.cwd), run.id);
353 353 ctx.ui.notify(`Resumed ultra run ${run.id}.`, "info");
354 354 return;
389 389 getArgumentCompletions: (prefix) =>
390 390 completeWorkflowNames(discover(process.cwd()), prefix),
391 391 handler: async (argString, ctx) => {
392 - const cfg = settings();
392 + const cfg = settings(ctx.cwd);
393 393 if (!cfg.enabled) {
394 394 if (ctx.hasUI)
395 395 ctx.ui.notify(

extensions/ultra/settings.ts

Modified
1 1 // ultra — settings (Task 9, offline-testable half).
3 -// Reads the `ultra.*` block from Pi settings via runtime `settingsManager`.
3 +// Reads the `ultra.*` block from Pi's global and project settings.
5 5 /** Resolved `ultra` configuration (design §Settings). */
6 6 export type ModelTierName = "small" | "medium" | "big";
81 81 p.subagentExtensions === "none" || p.subagentExtensions === "all"
82 82 ? p.subagentExtensions
83 83 : into.subagentExtensions,
84 - modelTiers: isPlainObject(p.modelTiers) ? p.modelTiers : into.modelTiers,
84 + modelTiers: isPlainObject(p.modelTiers)
85 + ? { ...into.modelTiers, ...p.modelTiers }
86 + : into.modelTiers,
86 88 { ...ULTRA_DEFAULTS },
90 -/** Settings source; `runtime` is the raw `settingsManager.getSettings()` object. */
91 92 export interface SettingsSources {
92 - runtime?: unknown;
93 + global?: unknown;
94 + project?: unknown;
95 -/** Resolve effective settings: defaults < runtime. */
97 +/** Resolve effective settings: defaults < global < project. */
96 98 export function loadUltraSettings(sources: SettingsSources): UltraSettings {
97 - return mergeUltraSettings(pickUltra(sources.runtime));
99 + return mergeUltraSettings(
100 + pickUltra(sources.global),
101 + pickUltra(sources.project),
102 + );

scripts/extensions.mjs

Modified
53 53 message:
54 54 "agent extension config file is forbidden; use settings.tune in Pi settings",
56 + {
57 + re: /\.settingsManager(?:\?\.)?\.?getSettings/,
58 + message:
59 + "private settingsManager access is forbidden; use SettingsManager.create()",
60 + },
58 63 const CHANGELOG_STYLE = `Voice:

scripts/test_extensions_static_check.mjs

Modified
106 106 'const a = path.join(process.cwd(), "settings.json");',
107 107 'const b = path.join(process.cwd(), ".pi", "tune", "config.json");',
108 108 'const c = "tune.json";',
109 - "void [a, b, c];",
109 + "const d = (pi as SettingsAPI).settingsManager?.getSettings?.();",
110 + "void [a, b, c, d];",
110 111 ].join("\n"),
112 113 const errors = staticCheck(join(root, "bad-config"), { root });
113 114 assert(errors.some((e) => e.includes("workspace-root settings.json")));
114 115 assert(errors.some((e) => e.includes("custom tune config file")));
115 116 assert(errors.some((e) => e.includes("agent extension config file")));
117 + assert(errors.some((e) => e.includes("private settingsManager access")));
118 120 withTemp((root) => {