pi-famulus 0.2.1 → 0.2.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,343 @@
1
+ /**
2
+ * The settings pages of /famulus: every documented config.json key, grouped
3
+ * by who reads it, edited one value at a time (docs/config.md).
4
+ */
5
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { hostname } from "node:os";
7
+ import { dirname } from "node:path";
8
+ import type { PiTuiInteractive, PiTuiModule, PiTuiSettingItem, PiTuiSettingsListTheme } from "./pi-tui-load";
9
+
10
+ type Kind = "int" | "text" | "secret" | "bool" | "enum" | "duration";
11
+
12
+ export interface SettingSpec {
13
+ /** Key path inside config.json. */
14
+ path: string[];
15
+ kind: Kind;
16
+ /** What an unset key means, as shown in the list. */
17
+ default: string;
18
+ description: string;
19
+ values?: string[];
20
+ }
21
+
22
+ export interface SettingsSection {
23
+ id: string;
24
+ label: string;
25
+ /** When a change takes effect, unless a key says otherwise. */
26
+ applies: string;
27
+ specs: Array<SettingSpec & { applies?: string }>;
28
+ }
29
+
30
+ const RELOAD = "reload the extension to apply";
31
+ const LIVE = "applies immediately";
32
+ const RESTART = "restart the manager daemon to apply";
33
+
34
+ const int = (path: string[], def: string, description: string, applies?: string) => ({
35
+ path,
36
+ kind: "int" as const,
37
+ default: def,
38
+ description,
39
+ ...(applies ? { applies } : {}),
40
+ });
41
+
42
+ export const SETTINGS_SECTIONS: SettingsSection[] = [
43
+ {
44
+ id: "extension",
45
+ label: "Extension",
46
+ applies: RELOAD,
47
+ specs: [
48
+ int(["foregroundBudgetMs"], "20000", "How long bash waits before moving a command to the background (ms)."),
49
+ int(["subagentBudgetMs"], "45000", "Default wait before a subagent call runs in the background (ms); subagent.budgetMs overrides it."),
50
+ { path: ["managerPath"], kind: "text", default: "auto", description: "Explicit pi-famulus executable; empty resolves it automatically." },
51
+ { path: ["logLevel"], kind: "enum", values: ["debug", "info", "warn", "error"], default: "info", description: "Log level." },
52
+ ],
53
+ },
54
+ {
55
+ id: "subagent",
56
+ label: "Subagents",
57
+ applies: RELOAD,
58
+ specs: [
59
+ int(["subagent", "budgetMs"], "45000", "Per-call backgrounding budget (ms)."),
60
+ int(["subagent", "timeoutMs"], "1800000", "Soft per-turn budget (ms); reaching it does not stop the child."),
61
+ int(["subagent", "overrunRepeatMs"], "600000", "Interval between repeated overrun notifications (ms)."),
62
+ int(["subagent", "hardTimeoutMs"], "0", "Per-turn abort limit (ms); 0 disables it."),
63
+ int(["subagent", "stallMs"], "300000", "Abort a child with no events for this long (ms)."),
64
+ int(["subagent", "stallRetries"], "1", "Automatic retries after a stall."),
65
+ int(["subagent", "stallRetryDelayMs"], "5000", "Delay before retrying a stalled child (ms)."),
66
+ int(["subagent", "decisionTimeoutMs"], "600000", "Maximum wait for the parent to answer a decision request (ms)."),
67
+ int(["subagent", "concurrency"], "4", "Default concurrency within one subagent call."),
68
+ int(["subagent", "maxConcurrentChildren"], "8", "Concurrent children allowed in this pi session."),
69
+ int(["subagent", "spawnBudgetPerHour"], "32", "Child sessions started per hour in this session."),
70
+ { path: ["subagent", "piCommand"], kind: "text", default: "pi", description: "Pi executable, shell command, or JSON argv array for hosted children." },
71
+ int(["subagent", "idleMinMs"], "120000", "Minimum warm idle lifetime before parking (ms). Read by the daemon.", LIVE),
72
+ int(["subagent", "idleGraceMs"], "15000", "Grace period after the estimated prompt-cache expiry (ms). Read by the daemon.", LIVE),
73
+ int(["subagent", "idleMaxMs"], "3600000", "Maximum warm idle lifetime (ms). Read by the daemon.", LIVE),
74
+ ],
75
+ },
76
+ {
77
+ id: "daemon",
78
+ label: "Manager daemon",
79
+ applies: LIVE,
80
+ specs: [
81
+ int(["maxAgents"], "8", "Machine-wide concurrent subagent limit."),
82
+ int(["maxTestSuite"], "2", "Concurrent test-suite subagents."),
83
+ int(["maxTest"], "2", "Concurrent test subagents."),
84
+ int(["maxBuild"], "maxAgents", "Concurrent build subagents."),
85
+ int(["maxLintType"], "maxAgents", "Concurrent lint/type subagents."),
86
+ int(["maxOther"], "maxAgents", "Concurrent general subagents."),
87
+ int(["maxGit"], "maxAgents", "Concurrent git subagents."),
88
+ int(["maxReadSearch"], "maxAgents", "Concurrent read/search subagents."),
89
+ int(["maxWarmAgents"], "4", "Maximum warm hosted agents."),
90
+ { path: ["goneSessionRetention"], kind: "duration", default: "24h", description: "How long files of disconnected sessions are kept (30m, 24h, 7d, 0s).", applies: RESTART },
91
+ { path: ["finishedTaskRetention"], kind: "duration", default: "24h", description: "How long finished task records and output are kept.", applies: RESTART },
92
+ ],
93
+ },
94
+ {
95
+ id: "messaging",
96
+ label: "Messaging",
97
+ applies: RESTART,
98
+ specs: [
99
+ { path: ["messaging", "name"], kind: "text", default: hostname(), description: "Device name shown to peers; the hostname when unset." },
100
+ { path: ["messaging", "server"], kind: "text", default: "https://127.0.0.1:8443", description: "Relay server URL." },
101
+ { path: ["messaging", "token"], kind: "secret", default: "not set", description: "Relay or enrollment token." },
102
+ { path: ["messaging", "localOnly"], kind: "bool", default: "false", description: "Only local sessions, no relay. On automatically without a token or device identity." },
103
+ { path: ["messaging", "remoteMessages"], kind: "enum", values: ["allow", "refuse"], default: "allow", description: "Whether messages from other machines are accepted." },
104
+ { path: ["messaging", "tlsInsecure"], kind: "bool", default: "false", description: "Skip relay TLS certificate verification." },
105
+ { path: ["messaging", "mcpListen"], kind: "text", default: "off", description: "MCP listener address; empty disables it." },
106
+ { path: ["messaging", "mcpToken"], kind: "secret", default: "generated", description: "MCP bearer token; generated and stored privately when unset." },
107
+ { path: ["messaging", "mcpAllowNonLoopback"], kind: "bool", default: "false", description: "Permit a non-loopback MCP listener (needs mcpToken)." },
108
+ { path: ["messaging", "sock"], kind: "text", default: "default", description: "Local bridge socket path." },
109
+ { path: ["messaging", "stateDir"], kind: "text", default: "~/.pi/agent/pi-famulus/messaging", description: "Device identity and bridge state directory." },
110
+ int(["messaging", "eventLogSize"], "4096", "Maximum retained bridge event-log entries."),
111
+ ],
112
+ },
113
+ ];
114
+
115
+ type Json = Record<string, unknown>;
116
+
117
+ export function readConfigText(path: string): string {
118
+ try {
119
+ return readFileSync(path, "utf8");
120
+ } catch (error) {
121
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "{}\n";
122
+ throw error;
123
+ }
124
+ }
125
+
126
+ function parseConfig(text: string): Json {
127
+ const parsed: unknown = JSON.parse(text);
128
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
129
+ throw new Error("config.json must contain a JSON object");
130
+ }
131
+ return parsed as Json;
132
+ }
133
+
134
+ export function readConfig(path: string): Json {
135
+ return parseConfig(readConfigText(path));
136
+ }
137
+
138
+ function writeConfigObject(path: string, config: Json): void {
139
+ mkdirSync(dirname(path), { recursive: true });
140
+ const temporary = `${path}.${process.pid}.tmp`;
141
+ try {
142
+ writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, "utf8");
143
+ renameSync(temporary, path);
144
+ } finally {
145
+ rmSync(temporary, { force: true });
146
+ }
147
+ }
148
+
149
+ /** Validate a whole edited file and write it. */
150
+ export function writeConfigText(path: string, text: string): void {
151
+ writeConfigObject(path, parseConfig(text));
152
+ }
153
+
154
+ function lookup(config: Json, path: string[]): unknown {
155
+ let node: unknown = config;
156
+ for (const key of path) {
157
+ if (typeof node !== "object" || node === null || Array.isArray(node)) return undefined;
158
+ node = (node as Json)[key];
159
+ }
160
+ return node;
161
+ }
162
+
163
+ /**
164
+ * Set one key (undefined removes it), re-reading the file first so edits
165
+ * made elsewhere since the page opened survive.
166
+ */
167
+ export function setConfigValue(path: string, keyPath: string[], value: unknown): void {
168
+ const config = readConfig(path);
169
+ let node = config;
170
+ for (const key of keyPath.slice(0, -1)) {
171
+ const next = node[key];
172
+ if (next === undefined && value === undefined) return;
173
+ if (next === undefined) node[key] = {};
174
+ else if (typeof next !== "object" || next === null || Array.isArray(next)) {
175
+ throw new Error(`${key} in config.json is not an object`);
176
+ }
177
+ node = node[key] as Json;
178
+ }
179
+ const leaf = keyPath[keyPath.length - 1];
180
+ if (value === undefined) delete node[leaf];
181
+ else node[leaf] = value;
182
+ writeConfigObject(path, config);
183
+ }
184
+
185
+ /** The value shown in the list for a key's current setting. */
186
+ export function displayValue(spec: SettingSpec, raw: unknown): string {
187
+ if (raw === undefined || raw === null || raw === "") return spec.default;
188
+ if (spec.kind === "secret") return "set";
189
+ return typeof raw === "string" ? raw : JSON.stringify(raw);
190
+ }
191
+
192
+ /** Parse typed text into the stored value; undefined removes the key. */
193
+ export function parseInput(spec: SettingSpec, text: string): { value: unknown } | { error: string } {
194
+ const trimmed = text.trim();
195
+ if (trimmed === "") return { value: undefined };
196
+ switch (spec.kind) {
197
+ case "int":
198
+ return /^\d+$/.test(trimmed) ? { value: Number(trimmed) } : { error: "Enter a whole number, or nothing for the default." };
199
+ case "duration":
200
+ return /^\d+[smhd]$/.test(trimmed) ? { value: trimmed } : { error: "Enter a duration such as 30m, 24h, 7d or 0s." };
201
+ case "bool":
202
+ return trimmed === "true" || trimmed === "false" ? { value: trimmed === "true" } : { error: "Enter true or false." };
203
+ case "enum":
204
+ return spec.values?.includes(trimmed) ? { value: trimmed } : { error: `Enter one of: ${spec.values?.join(", ")}.` };
205
+ default:
206
+ return { value: trimmed };
207
+ }
208
+ }
209
+
210
+ export interface SettingsPageDeps {
211
+ tui: PiTuiModule;
212
+ theme: { fg(color: string, text: string): string };
213
+ configPath: string;
214
+ requestRender(): void;
215
+ /** Report a save or its failure under the list. */
216
+ notice(text: string, error?: boolean): void;
217
+ }
218
+
219
+ export function listTheme(theme: SettingsPageDeps["theme"]): PiTuiSettingsListTheme {
220
+ return {
221
+ label: (text, selected) => (selected ? theme.fg("accent", text) : text),
222
+ value: (text, selected) => (selected ? theme.fg("accent", text) : theme.fg("muted", text)),
223
+ description: (text) => theme.fg("dim", text),
224
+ cursor: theme.fg("accent", "→ "),
225
+ hint: (text) => theme.fg("dim", text),
226
+ };
227
+ }
228
+
229
+ const keyOf = (spec: SettingSpec) => spec.path.join(".");
230
+
231
+ function describe(spec: SettingSpec & { applies?: string }, section: SettingsSection, raw: unknown): string {
232
+ const state = raw === undefined ? `not set (default ${spec.default})` : `default ${spec.default}`;
233
+ return `${spec.description} · ${state} · ${spec.applies ?? section.applies}`;
234
+ }
235
+
236
+ /** One-line text editor for a single key. */
237
+ function valueEditor(
238
+ deps: SettingsPageDeps,
239
+ spec: SettingSpec,
240
+ raw: unknown,
241
+ save: (value: unknown) => boolean,
242
+ done: (shown?: string) => void,
243
+ ): PiTuiInteractive {
244
+ const input = new deps.tui.Input();
245
+ input.focused = true;
246
+ if (spec.kind !== "secret" && raw !== undefined && raw !== null) {
247
+ // A paste leaves the cursor after the text; setValue would leave it at 0.
248
+ input.handleInput(`\x1b[200~${typeof raw === "string" ? raw : JSON.stringify(raw)}\x1b[201~`);
249
+ }
250
+ const hint =
251
+ spec.kind === "secret"
252
+ ? "enter save · empty keeps the current value · esc cancel"
253
+ : `enter save · empty resets to ${spec.default} · esc cancel`;
254
+ let error = "";
255
+ input.onSubmit = (text) => {
256
+ if (spec.kind === "secret" && text.trim() === "") return done();
257
+ const parsed = parseInput(spec, text);
258
+ if ("error" in parsed) {
259
+ error = parsed.error;
260
+ deps.requestRender();
261
+ return;
262
+ }
263
+ if (save(parsed.value)) done(displayValue(spec, parsed.value));
264
+ };
265
+ input.onEscape = () => done();
266
+ return {
267
+ render: (width) => [
268
+ deps.theme.fg("accent", keyOf(spec)),
269
+ deps.theme.fg("dim", spec.description),
270
+ "",
271
+ ...input.render(width),
272
+ "",
273
+ error ? deps.theme.fg("error", error) : deps.theme.fg("dim", hint),
274
+ ],
275
+ invalidate: () => input.invalidate(),
276
+ handleInput: (data) => input.handleInput(data),
277
+ };
278
+ }
279
+
280
+ /** The list of one section's keys; esc returns to the overview. */
281
+ export function sectionPage(deps: SettingsPageDeps, section: SettingsSection, close: () => void): PiTuiInteractive {
282
+ let config: Json;
283
+ try {
284
+ config = readConfig(deps.configPath);
285
+ } catch (error) {
286
+ deps.notice(`Cannot read ${deps.configPath}: ${(error as Error).message}`, true);
287
+ config = {};
288
+ }
289
+ const specs = new Map(section.specs.map((spec) => [keyOf(spec), spec]));
290
+ const save = (spec: SettingSpec & { applies?: string }, value: unknown): boolean => {
291
+ try {
292
+ setConfigValue(deps.configPath, spec.path, value);
293
+ } catch (error) {
294
+ deps.notice(`${keyOf(spec)} was not saved: ${(error as Error).message}`, true);
295
+ return false;
296
+ }
297
+ deps.notice(`Saved ${keyOf(spec)}; ${spec.applies ?? section.applies}.`);
298
+ return true;
299
+ };
300
+ const items: PiTuiSettingItem[] = section.specs.map((spec) => {
301
+ const raw = lookup(config, spec.path);
302
+ const item: PiTuiSettingItem = {
303
+ id: keyOf(spec),
304
+ label: spec.path[spec.path.length - 1],
305
+ description: describe(spec, section, raw),
306
+ currentValue: displayValue(spec, raw),
307
+ };
308
+ if (spec.kind === "bool") item.values = ["true", "false"];
309
+ else if (spec.kind === "enum") item.values = spec.values;
310
+ else {
311
+ item.submenu = (_current, done) =>
312
+ valueEditor(deps, spec, lookup(readConfigOrEmpty(deps.configPath), spec.path), (value) => save(spec, value), done);
313
+ }
314
+ return item;
315
+ });
316
+ const list = new deps.tui.SettingsList(
317
+ items,
318
+ 12,
319
+ listTheme(deps.theme),
320
+ (id, value) => {
321
+ const spec = specs.get(id);
322
+ if (!spec || (!spec.values && spec.kind !== "bool")) return;
323
+ const parsed = parseInput(spec, value);
324
+ if ("value" in parsed && !save(spec, parsed.value)) {
325
+ list.updateValue(id, displayValue(spec, lookup(readConfigOrEmpty(deps.configPath), spec.path)));
326
+ }
327
+ },
328
+ close,
329
+ );
330
+ return {
331
+ render: (width) => [deps.theme.fg("accent", section.label), "", ...list.render(width)],
332
+ invalidate: () => list.invalidate(),
333
+ handleInput: (data) => list.handleInput(data),
334
+ };
335
+ }
336
+
337
+ function readConfigOrEmpty(path: string): Json {
338
+ try {
339
+ return readConfig(path);
340
+ } catch {
341
+ return {};
342
+ }
343
+ }
@@ -46,6 +46,20 @@ export interface PiTuiModule {
46
46
  options?: { gap?: number },
47
47
  ) => PiTuiComponent;
48
48
  matchesKey(data: string, key: string): boolean;
49
+ SettingsList: new (
50
+ items: PiTuiSettingItem[],
51
+ maxVisible: number,
52
+ theme: PiTuiSettingsListTheme,
53
+ onChange: (id: string, newValue: string) => void,
54
+ onCancel: () => void,
55
+ ) => PiTuiInteractive & { updateValue(id: string, newValue: string): void };
56
+ Input: new () => PiTuiInteractive & {
57
+ focused: boolean;
58
+ onSubmit?: (value: string) => void;
59
+ onEscape?: () => void;
60
+ getValue(): string;
61
+ setValue(value: string): void;
62
+ };
49
63
  Box: new (
50
64
  paddingX?: number,
51
65
  paddingY?: number,
@@ -53,6 +67,29 @@ export interface PiTuiModule {
53
67
  ) => { addChild(component: unknown): void };
54
68
  }
55
69
 
70
+ export interface PiTuiInteractive extends PiTuiComponent {
71
+ handleInput(data: string): void;
72
+ }
73
+
74
+ export interface PiTuiSettingItem {
75
+ id: string;
76
+ label: string;
77
+ description?: string;
78
+ currentValue: string;
79
+ /** Enter cycles through these. */
80
+ values?: string[];
81
+ /** Enter opens this; `done(value)` sets the shown value, `done()` cancels. */
82
+ submenu?: (currentValue: string, done: (selectedValue?: string) => void) => PiTuiInteractive;
83
+ }
84
+
85
+ export interface PiTuiSettingsListTheme {
86
+ label: (text: string, selected: boolean) => string;
87
+ value: (text: string, selected: boolean) => string;
88
+ description: (text: string) => string;
89
+ cursor: string;
90
+ hint: (text: string) => string;
91
+ }
92
+
56
93
  export interface PiTuiWidth {
57
94
  visibleWidth(text: string): number;
58
95
  truncateToWidth(text: string, maxWidth: number, ellipsis?: string): string;