proper-base 0.7.0 → 0.8.0

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,340 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import type { Component } from "@earendil-works/pi-tui";
5
+
6
+ const CONFIG_FILE_NAME = "proper-base.json";
7
+ const GLOBAL_KEY = "contextTokens";
8
+
9
+ /**
10
+ * The hard input cap of OpenAI's 1,050,000-token models: the window minus
11
+ * the 128,000 reserved output tokens. Probing the Codex backend through
12
+ * CLIProxyAPI on 2026-09-22 rejected every listed model one token past it
13
+ * (usage-counted 921,858 accepted, 921,859 refused; the rest is hidden
14
+ * request framing), just as gpt-5.5 there stops at Pi's registered 272,000.
15
+ * Codex's own catalog budgets 872,000, keeping 50,000 of headroom that Pi's
16
+ * `reserveTokens` provides instead.
17
+ */
18
+ const MAX_INPUT = 922_000;
19
+ const CODEX_MODELS = new Set([
20
+ "gpt-6-astra",
21
+ "gpt-6.1-sol",
22
+ "gpt-6-sol",
23
+ "gpt-6-luna",
24
+ "gpt-5.6-sol",
25
+ "gpt-5.6-terra",
26
+ "gpt-5.6-luna",
27
+ ]);
28
+ /** The API also serves GPT-5.5 and GPT-5.4 at 1,050,000 (Codex keeps GPT-5.5 at 272,000). */
29
+ const API_MODELS = new Set([...CODEX_MODELS, "gpt-5.5", "gpt-5.4"]);
30
+
31
+ export const CONTEXT_TOKENS_ENTRY = "proper-base-context-tokens";
32
+ export const TOKENS_USAGE = "Usage: /tokens [max|default] [global]";
33
+
34
+ export type ContextTokensMode = "max" | "default";
35
+ export type TokenLimits = { default: number; max: number };
36
+ export type TokensModel = {
37
+ provider: string;
38
+ id: string;
39
+ contextWindow: number;
40
+ };
41
+ type CompactionSettings = { enabled: boolean; reserveTokens: number };
42
+ type BranchEntry = { type: string; customType?: string; data?: unknown };
43
+
44
+ /** The live AgentSession fields this module reads and writes. */
45
+ export type TokensSession = {
46
+ agent: { state: { model: TokensModel | undefined } };
47
+ settingsManager: {
48
+ getCompactionSettings(model?: TokensModel): CompactionSettings;
49
+ };
50
+ sessionManager: { getBranch(): readonly BranchEntry[] };
51
+ };
52
+
53
+ /** The ModelRegistry call this module needs. */
54
+ export type TokensRegistry = {
55
+ find(provider: string, id: string): TokensModel | undefined;
56
+ };
57
+
58
+ type JsonObject = Record<string, unknown>;
59
+
60
+ function readJsonObject(path: string): JsonObject | undefined {
61
+ try {
62
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
63
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
64
+ ? (parsed as JsonObject)
65
+ : undefined;
66
+ } catch {
67
+ return undefined;
68
+ }
69
+ }
70
+
71
+ function isMode(value: unknown): value is ContextTokensMode {
72
+ return value === "max" || value === "default";
73
+ }
74
+
75
+ /** Feature-detect the private AgentSession shape; a renamed field disables the command. */
76
+ export function asTokensSession(value: unknown): TokensSession | undefined {
77
+ const session = value as Partial<TokensSession> | undefined;
78
+ return session?.agent?.state &&
79
+ typeof session.settingsManager?.getCompactionSettings === "function" &&
80
+ typeof session.sessionManager?.getBranch === "function"
81
+ ? (session as TokensSession)
82
+ : undefined;
83
+ }
84
+
85
+ /** `""` shows the state; otherwise `max|default` with an optional `global`. */
86
+ export function parseTokensArgs(
87
+ args: string,
88
+ ): { mode?: ContextTokensMode; global: boolean } | undefined {
89
+ const words = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
90
+ if (words.length === 0) return { global: false };
91
+ const [mode, scope, ...rest] = words;
92
+ if (!isMode(mode) || rest.length || (scope && scope !== "global")) {
93
+ return undefined;
94
+ }
95
+ return { mode, global: scope === "global" };
96
+ }
97
+
98
+ const COMPLETIONS = [
99
+ { value: "max", description: "Largest window for this session" },
100
+ { value: "default", description: "Standard window for this session" },
101
+ { value: "max global", description: "Largest window for every session" },
102
+ { value: "default global", description: "Standard window for every session" },
103
+ ];
104
+
105
+ export function tokensArgumentCompletions(prefix: string) {
106
+ const needle = prefix.trimStart().toLowerCase();
107
+ // After a completed mode, list its scopes. The session scope leads and its
108
+ // value equals the typed text, so Pi preselects it and Enter or Tab keeps
109
+ // the choice session-only instead of turning it global.
110
+ const mode = /^(max|default) $/.exec(needle)?.[1];
111
+ const items = mode
112
+ ? COMPLETIONS.filter(({ value }) => value.startsWith(mode)).map((item) => ({
113
+ ...item,
114
+ value: item.value === mode ? needle : item.value,
115
+ label: item.value,
116
+ }))
117
+ : COMPLETIONS.filter(({ value }) => value.startsWith(needle)).map(
118
+ (item) => ({ ...item, label: item.value }),
119
+ );
120
+ return items.length ? items : null;
121
+ }
122
+
123
+ const SCOPE_INSTALLED = Symbol.for("pi-proper-base.tokens-scope-completion");
124
+ const MODE_TEXT = /^\/tokens (?:max|default)$/;
125
+ const SCOPE_TEXT = /^\/tokens (?:max|default) $/;
126
+
127
+ type ScopeEditor = Component & {
128
+ getText?(): string;
129
+ handleInput?(data: string): void;
130
+ isShowingAutocomplete?(): boolean;
131
+ tryTriggerAutocomplete?(): void;
132
+ [SCOPE_INSTALLED]?: boolean;
133
+ };
134
+
135
+ /**
136
+ * Offer the `global` scope after a `/tokens` mode. Pi reopens suggestions
137
+ * only from typed letters and digits, and the separator is a space, so Tab
138
+ * on a mode stops there, adds the space, and opens the scope menu, and a
139
+ * typed space opens it too. Tab on a scope completes it and closes.
140
+ */
141
+ export function installTokensScopeCompletion(
142
+ editor: Component,
143
+ keybindings: { matches(data: string, action: string): boolean },
144
+ ): void {
145
+ const target = editor as ScopeEditor;
146
+ if (target[SCOPE_INSTALLED] || !target.handleInput || !target.getText) return;
147
+ const handleInput = target.handleInput.bind(target);
148
+ target.handleInput = (data: string) => {
149
+ handleInput(data);
150
+ if (target.isShowingAutocomplete?.()) return;
151
+ const tab = keybindings.matches(data, "tui.input.tab");
152
+ if (tab && MODE_TEXT.test(target.getText?.() ?? "")) handleInput(" ");
153
+ else if (data !== " ") return;
154
+ if (SCOPE_TEXT.test(target.getText?.() ?? ""))
155
+ target.tryTriggerAutocomplete?.();
156
+ };
157
+ target[SCOPE_INSTALLED] = true;
158
+ }
159
+
160
+ const format = (tokens: number) => tokens.toLocaleString("en-US");
161
+
162
+ /**
163
+ * Session and global context-window choices for OpenAI models.
164
+ *
165
+ * Pi registers these models at their standard window (272,000) although
166
+ * the backend accepts more, so the choice only changes Pi's budgeting: the
167
+ * session model is swapped for a copy carrying the chosen `contextWindow`,
168
+ * which every compaction, overflow, and footer check reads live. The
169
+ * provider/id identity is unchanged, so per-model compaction overrides keep
170
+ * applying. The session choice is a branch entry; the global choice is
171
+ * `contextTokens` in `proper-base.json`, re-read on every apply.
172
+ */
173
+ export class ContextTokens {
174
+ private readonly agentDir: string;
175
+ private readonly cliproxyProviderId: () => string;
176
+
177
+ constructor(agentDir: string, cliproxyProviderId: () => string) {
178
+ this.agentDir = agentDir;
179
+ this.cliproxyProviderId = cliproxyProviderId;
180
+ }
181
+
182
+ private configPath(): string {
183
+ return join(this.agentDir, CONFIG_FILE_NAME);
184
+ }
185
+
186
+ globalMode(): ContextTokensMode | undefined {
187
+ const value = readJsonObject(this.configPath())?.[GLOBAL_KEY];
188
+ return isMode(value) ? value : undefined;
189
+ }
190
+
191
+ /** Preserves every other key. Write failures propagate to the caller. */
192
+ setGlobalMode(mode: ContextTokensMode): void {
193
+ const existing = readJsonObject(this.configPath()) ?? {};
194
+ writeFileSync(
195
+ this.configPath(),
196
+ `${JSON.stringify({ ...existing, [GLOBAL_KEY]: mode }, null, "\t")}\n`,
197
+ );
198
+ }
199
+
200
+ /** The latest session choice on this branch; `null` data follows global. */
201
+ sessionMode(branch: readonly BranchEntry[]): ContextTokensMode | undefined {
202
+ for (let index = branch.length - 1; index >= 0; index--) {
203
+ const entry = branch[index];
204
+ if (entry?.type !== "custom" || entry.customType !== CONTEXT_TOKENS_ENTRY)
205
+ continue;
206
+ const mode = (entry.data as { mode?: unknown } | undefined)?.mode;
207
+ return isMode(mode) ? mode : undefined;
208
+ }
209
+ return undefined;
210
+ }
211
+
212
+ effectiveMode(branch: readonly BranchEntry[]): ContextTokensMode {
213
+ return this.sessionMode(branch) ?? this.globalMode() ?? "default";
214
+ }
215
+
216
+ /**
217
+ * Limits for a registry model, or `undefined` when it has no larger
218
+ * window. The default is the registry's own value, including any
219
+ * `models.json` override.
220
+ */
221
+ limitsFor(model: TokensModel): TokenLimits | undefined {
222
+ const models =
223
+ model.provider === "openai"
224
+ ? API_MODELS
225
+ : model.provider === "openai-codex" ||
226
+ model.provider === this.cliproxyProviderId()
227
+ ? CODEX_MODELS
228
+ : undefined;
229
+ return models?.has(model.id) && MAX_INPUT > model.contextWindow
230
+ ? { default: model.contextWindow, max: MAX_INPUT }
231
+ : undefined;
232
+ }
233
+
234
+ /** The model carrying the effective window, or the model unchanged. */
235
+ private windowed(
236
+ model: TokensModel | undefined,
237
+ session: TokensSession,
238
+ registry: TokensRegistry,
239
+ ): TokensModel | undefined {
240
+ if (!model) return model;
241
+ const base = registry.find(model.provider, model.id) ?? model;
242
+ const limits = this.limitsFor(base);
243
+ if (!limits) return model;
244
+ const mode = this.effectiveMode(session.sessionManager.getBranch());
245
+ const window = mode === "max" ? limits.max : limits.default;
246
+ if (model.contextWindow === window) return model;
247
+ return window === base.contextWindow
248
+ ? base
249
+ : { ...base, contextWindow: window };
250
+ }
251
+
252
+ /**
253
+ * Swap the session model for one carrying the effective window. Returns
254
+ * the applied window, or `undefined` when the model is ineligible.
255
+ */
256
+ apply(
257
+ session: TokensSession,
258
+ registry: TokensRegistry,
259
+ ): { window: number; limits: TokenLimits } | undefined {
260
+ const state = session.agent.state;
261
+ const next = this.windowed(state.model, session, registry);
262
+ if (next !== state.model) state.model = next;
263
+ if (!next) return undefined;
264
+ const limits = this.limitsFor(
265
+ registry.find(next.provider, next.id) ?? next,
266
+ );
267
+ return limits && { window: next.contextWindow, limits };
268
+ }
269
+
270
+ /**
271
+ * Keep the effective window across every write to the session model.
272
+ * Model switches, session restore, and any extension's provider
273
+ * (re)registration put the registry object back without an event, so the
274
+ * setter windows each model as it lands. Global changes made by another
275
+ * process still need `apply`. Returns the uninstaller.
276
+ */
277
+ guard(session: TokensSession, registry: TokensRegistry): () => void {
278
+ const state = session.agent.state;
279
+ let model = state.model;
280
+ const get = () => model;
281
+ Object.defineProperty(state, "model", {
282
+ configurable: true,
283
+ enumerable: true,
284
+ get,
285
+ set: (next: TokensModel | undefined) => {
286
+ model = this.windowed(next, session, registry);
287
+ },
288
+ });
289
+ return () => {
290
+ if (Object.getOwnPropertyDescriptor(state, "model")?.get !== get) return;
291
+ Object.defineProperty(state, "model", {
292
+ configurable: true,
293
+ enumerable: true,
294
+ writable: true,
295
+ value: model,
296
+ });
297
+ };
298
+ }
299
+ }
300
+
301
+ /** Feedback for `/tokens`, including where compaction will now trigger. */
302
+ export function tokensNotice(options: {
303
+ modelId: string;
304
+ /** The chosen mode, or for status its label and source. */
305
+ mode: string;
306
+ scope: "session" | "global" | "status";
307
+ window: number;
308
+ limits: TokenLimits;
309
+ compaction: CompactionSettings;
310
+ contextTokens: number | null | undefined;
311
+ }): { message: string; level: "info" | "warning" } {
312
+ const { modelId, mode, scope, window, limits, compaction, contextTokens } =
313
+ options;
314
+ const where =
315
+ scope === "global"
316
+ ? " for all sessions"
317
+ : scope === "session"
318
+ ? " for this session"
319
+ : "";
320
+ const lead =
321
+ scope === "status"
322
+ ? `${modelId}: ${format(window)}-token context window (${mode}; default ${format(limits.default)}, max ${format(limits.max)}).`
323
+ : `Context window ${mode}${where}: ${modelId} now uses ${format(window)} tokens.`;
324
+ if (!compaction.enabled) {
325
+ const over = contextTokens != null && contextTokens > window;
326
+ return {
327
+ message: `${lead} Auto-compaction is off${over ? `; the current ${format(contextTokens)}-token context already exceeds the window.` : "."}`,
328
+ level: over ? "warning" : "info",
329
+ };
330
+ }
331
+ const threshold = window - compaction.reserveTokens;
332
+ const trigger = `Compaction triggers above ${format(Math.max(0, threshold))} tokens (reserve ${format(compaction.reserveTokens)}).`;
333
+ if (contextTokens != null && contextTokens > threshold) {
334
+ return {
335
+ message: `${lead} ${trigger} The current ${format(contextTokens)}-token context is past it, so the next request compacts first.`,
336
+ level: "warning",
337
+ };
338
+ }
339
+ return { message: `${lead} ${trigger}`, level: "info" };
340
+ }
package/src/fast-mode.ts CHANGED
@@ -81,7 +81,7 @@ export class FastOverlay {
81
81
  return join(this.agentDir, CONFIG_FILE_NAME);
82
82
  }
83
83
 
84
- /** Session Fast is never persisted; a new session always starts off. */
84
+ /** Session Fast starts off; /clear restores its captured flag after startup. */
85
85
  resetSession(): void {
86
86
  this.sessionEnabled = false;
87
87
  }
@@ -166,9 +166,10 @@ export function installFooterColors(
166
166
  typeof state.ctx.sessionManager?.getLeafId === "function"
167
167
  ? (state.ctx.sessionManager.getLeafId() ?? "")
168
168
  : "";
169
- const key = `${leafId}\u0000${model ?? ""}\u0000${level}\u0000${
170
- isFast ? "1" : "0"
171
- }`;
169
+ // /tokens swaps the window without a new entry or model id.
170
+ const key = `${leafId}\u0000${model ?? ""}\u0000${
171
+ state.ctx.model?.contextWindow ?? ""
172
+ }\u0000${level}\u0000${isFast ? "1" : "0"}`;
172
173
  const base = (at: number) => {
173
174
  const lines = baseLines(at, key, theme, now);
174
175
  return model && isFast ? tagFast(lines, at, model, theme) : lines;
@@ -8,9 +8,11 @@ import { appendPromptSection } from "./prompt-sections.ts";
8
8
  * effort: a developer message telling the model to delegate whenever work
9
9
  * parallelizes. Pi's subagent policy is the opposite, set by two sentences
10
10
  * pi-subagents puts in the system prompt: a tool guideline and a line in
11
- * the `<advertised_subagents>` catalog. This rewrites exactly those two
12
- * sentences and appends the Codex paragraph; the preflight instructions
13
- * around them and the tool description's safety guidance stay as they are.
11
+ * the `<advertised_subagents>` catalog. Since 0.71 a fresh session starts
12
+ * with only the `subagents_enable` loader active, whose tool-list line
13
+ * repeats the ask-first rule. This rewrites exactly those sentences and
14
+ * appends the Codex paragraph; the preflight instructions around them and
15
+ * the tool descriptions' safety guidance stay as they are.
14
16
  *
15
17
  * Codex's Ultra also picks each subagent's model. pi-subagents' `models`
16
18
  * action lists the whole registry and the tool description says to copy
@@ -22,10 +24,15 @@ const GUIDELINE = "Use subagent only when delegation is needed.";
22
24
  const CATALOG_SENTENCE =
23
25
  "Their descriptions indicate available specializations, not instructions to delegate. Use subagent only when delegation is needed.";
24
26
 
27
+ const LOADER_SENTENCES =
28
+ "For authorized specialist, independent-review, or parallel work, call subagents_enable, then subagent. Authorization must come from the current request or applicable instructions; complexity alone is not authorization.";
29
+
25
30
  const PROACTIVE_GUIDELINE =
26
31
  "Delegate to subagents proactively whenever work parallelizes; see Multi-agent mode below.";
27
32
  const PROACTIVE_CATALOG_SENTENCE =
28
33
  "Their descriptions indicate available specializations; delegate to them proactively whenever work parallelizes.";
34
+ const PROACTIVE_LOADER_SENTENCES =
35
+ "To delegate, call subagents_enable, then subagent; see Multi-agent mode below.";
29
36
 
30
37
  /**
31
38
  * Codex's `PROACTIVE_MULTI_AGENT_MODE_TEXT` retargeted at pi's tool, plus
@@ -89,8 +96,12 @@ export function applyProactiveDelegation(
89
96
  const rewrite = (text: string) =>
90
97
  text
91
98
  .replace(CATALOG_SENTENCE, PROACTIVE_CATALOG_SENTENCE)
92
- .replace(GUIDELINE, PROACTIVE_GUIDELINE);
99
+ .replace(GUIDELINE, PROACTIVE_GUIDELINE)
100
+ .replace(LOADER_SENTENCES, PROACTIVE_LOADER_SENTENCES);
93
101
  options.promptGuidelines = options.promptGuidelines.map(rewrite);
102
+ for (const [name, text] of Object.entries(options.toolSnippets)) {
103
+ options.toolSnippets[name] = rewrite(text);
104
+ }
94
105
  for (const [name, rules] of Object.entries(options.toolGuidelines)) {
95
106
  options.toolGuidelines[name] = rules.map(rewrite);
96
107
  }
@@ -7,6 +7,7 @@ import {
7
7
  } from "@earendil-works/pi-coding-agent";
8
8
  import { installWrapper, originalInput } from "./host-interop.ts";
9
9
  import type { PromptDisplayController } from "./prompt-display.ts";
10
+ import { splitSkillText } from "./skill-context.ts";
10
11
 
11
12
  type Message = Parameters<SessionManager["appendMessage"]>[0];
12
13
  type Manager = Pick<SessionManager, "getBranch">;
@@ -103,6 +104,11 @@ export function installPromptDisplayHost(
103
104
  session: AgentSession;
104
105
  getUserMessageText(message: Message): string;
105
106
  getMarkdownTransformers(): MarkdownTransformer[];
107
+ addMessageToChat(
108
+ message: Message,
109
+ options?: { populateHistory?: boolean },
110
+ ): void;
111
+ editor: { addToHistory?(text: string): void };
106
112
  };
107
113
  const prototype = InteractiveMode.prototype as unknown as InteractiveHost;
108
114
  const original = prototype.getUserMessageText;
@@ -118,6 +124,30 @@ export function installPromptDisplayHost(
118
124
  };
119
125
  restorers.push(installWrapper(prototype, "getUserMessageText", wrapped));
120
126
 
127
+ // Pi collapses only the first skill block, rendering the rest as user text.
128
+ // Feed each block through its native renderer without changing the message.
129
+ const addMessage = prototype.addMessageToChat;
130
+ const addSkills: typeof addMessage = function (
131
+ this: InteractiveHost,
132
+ message,
133
+ options,
134
+ ) {
135
+ if (
136
+ !active ||
137
+ message.role !== "user" ||
138
+ !this.getMarkdownTransformers().includes(marker)
139
+ )
140
+ return addMessage.call(this, message, options);
141
+ const text = this.getUserMessageText(message);
142
+ const { skills, request } = splitSkillText(text);
143
+ if (skills.length < 2) return addMessage.call(this, message, options);
144
+ for (const skill of skills)
145
+ addMessage.call(this, { ...message, content: skill.block });
146
+ if (request) addMessage.call(this, { ...message, content: request });
147
+ if (options?.populateHistory) this.editor.addToHistory?.(text);
148
+ };
149
+ restorers.push(installWrapper(prototype, "addMessageToChat", addSkills));
150
+
121
151
  const controller: Controller = {
122
152
  activate(next) {
123
153
  manager = next;
package/src/settings.ts CHANGED
@@ -1,4 +1,11 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ mkdirSync,
4
+ readFileSync,
5
+ renameSync,
6
+ rmSync,
7
+ writeFileSync,
8
+ } from "node:fs";
2
9
  import { join } from "node:path";
3
10
 
4
11
  import type { Component, TUI } from "@earendil-works/pi-tui";
@@ -23,6 +30,13 @@ const TOGGLES = [
23
30
  description:
24
31
  "proper-base: clicking the prompt moves the cursor; off leaves the cursor where typing put it",
25
32
  },
33
+ {
34
+ id: "proper-base-skill-context",
35
+ key: "skillContext",
36
+ label: "Skill context management",
37
+ description:
38
+ "proper-base: load multiple skills, manage snapshots and restore full instructions after compaction; applies to the next run",
39
+ },
26
40
  ] as const;
27
41
  type ToggleKey = (typeof TOGGLES)[number]["key"];
28
42
 
@@ -64,8 +78,13 @@ function readToggle(agentDir: string, key: ToggleKey): boolean {
64
78
  readFileSync(configPath(agentDir), "utf8"),
65
79
  ) as unknown;
66
80
  return (parsed as Record<string, unknown> | null)?.[key] !== false;
67
- } catch {
68
- return true;
81
+ } catch (error) {
82
+ if (
83
+ error instanceof SyntaxError ||
84
+ typeof (error as NodeJS.ErrnoException).code === "string"
85
+ )
86
+ return true;
87
+ throw error;
69
88
  }
70
89
  }
71
90
 
@@ -77,28 +96,59 @@ export function readEditorMouseEnabled(agentDir: string): boolean {
77
96
  return readToggle(agentDir, "editorMouse");
78
97
  }
79
98
 
80
- /** Fail-open like the history store: a read-only agent dir only costs
81
- * persistence, never the session. Other keys in the file are preserved. */
99
+ export function readSkillContextEnabled(agentDir: string): boolean {
100
+ try {
101
+ const parsed: unknown = JSON.parse(
102
+ readFileSync(configPath(agentDir), "utf8"),
103
+ );
104
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
105
+ return false;
106
+ const value = (parsed as Record<string, unknown>).skillContext;
107
+ return value === undefined || value === true;
108
+ } catch (error) {
109
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return true;
110
+ if (
111
+ error instanceof SyntaxError ||
112
+ typeof (error as NodeJS.ErrnoException).code === "string"
113
+ )
114
+ return false;
115
+ throw error;
116
+ }
117
+ }
118
+
119
+ export function writeSkillContextEnabled(
120
+ agentDir: string,
121
+ enabled: boolean,
122
+ ): void {
123
+ writeToggle(agentDir, "skillContext", enabled);
124
+ }
125
+
126
+ /** Fresh-disk merge and atomic replacement; failed saves keep the live value. */
82
127
  function writeToggle(agentDir: string, key: ToggleKey, enabled: boolean): void {
128
+ let parsed: Record<string, unknown> = {};
83
129
  try {
84
- let parsed: Record<string, unknown> = {};
85
- try {
86
- const existing = JSON.parse(
87
- readFileSync(configPath(agentDir), "utf8"),
88
- ) as unknown;
89
- if (existing && typeof existing === "object") {
90
- parsed = existing as Record<string, unknown>;
91
- }
92
- } catch {
93
- // Damaged or absent config starts fresh.
94
- }
95
- parsed[key] = enabled;
96
- writeFileSync(
97
- configPath(agentDir),
98
- `${JSON.stringify(parsed, null, "\t")}\n`,
130
+ const existing: unknown = JSON.parse(
131
+ readFileSync(configPath(agentDir), "utf8"),
99
132
  );
100
- } catch {
101
- // Persistence is best-effort.
133
+ if (!existing || typeof existing !== "object" || Array.isArray(existing))
134
+ throw new SyntaxError(
135
+ "proper-base.json must contain an object; preference was not saved.",
136
+ );
137
+ parsed = existing as Record<string, unknown>;
138
+ } catch (error) {
139
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
140
+ }
141
+ parsed[key] = enabled;
142
+ mkdirSync(agentDir, { recursive: true });
143
+ const temporary = `${configPath(agentDir)}.${randomUUID()}.tmp`;
144
+ try {
145
+ writeFileSync(temporary, `${JSON.stringify(parsed, null, "\t")}\n`, {
146
+ flag: "wx",
147
+ mode: 0o600,
148
+ });
149
+ renameSync(temporary, configPath(agentDir));
150
+ } finally {
151
+ rmSync(temporary, { force: true });
102
152
  }
103
153
  }
104
154
 
@@ -139,8 +189,7 @@ function findEditorContainer(
139
189
  }
140
190
 
141
191
  /**
142
- * Add proper-base's toggles to Pi's native `/settings` menu: the session
143
- * action rail and prompt mouse clicks.
192
+ * Add proper-base's toggles to Pi's native `/settings` menu.
144
193
  *
145
194
  * Pi has no extension hook into that menu, so this is a guarded
146
195
  * compatibility layer in the house style: the container Pi mounts selectors
@@ -148,11 +197,11 @@ function findEditorContainer(
148
197
  * settings selector that mounts receives the extra items spliced into its
149
198
  * `SettingsList`, whose instance-held `onChange` is wrapped to keep the
150
199
  * toggles out of Pi's own switch. A renamed component or list shape installs
151
- * or injects nothing and both features simply stay enabled.
200
+ * or injects nothing; config-file and command controls remain available.
152
201
  *
153
- * Choices persist as `sessionRail` and `editorMouse` in the agent
154
- * directory's `proper-base.json`; other sessions pick a change up at their
155
- * next start.
202
+ * Choices persist as `sessionRail`, `editorMouse` and `skillContext` in the
203
+ * agent directory's `proper-base.json`. Skill management reads its preference
204
+ * at the next run; the editor toggles remain cached for the session.
156
205
  *
157
206
  * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
158
207
  * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt mouse clicks]]
@@ -161,15 +210,18 @@ export function installSettings(
161
210
  tui: TUI,
162
211
  editor: Component,
163
212
  agentDir: string,
213
+ onError?: (error: Error) => void,
164
214
  ): SettingsController {
165
215
  const state: Record<ToggleKey, boolean> = {
166
216
  sessionRail: readToggle(agentDir, "sessionRail"),
167
217
  editorMouse: readToggle(agentDir, "editorMouse"),
218
+ skillContext: readSkillContextEnabled(agentDir),
168
219
  };
169
220
  let disposed = false;
170
221
  let uninstall: (() => void) | undefined;
171
222
 
172
223
  const inject = (selector: SettingsHost): void => {
224
+ state.skillContext = readSkillContextEnabled(agentDir);
173
225
  const list = selector.settingsList;
174
226
  const items = list?.items;
175
227
  if (!list || !Array.isArray(items) || typeof list.onChange !== "function")
@@ -188,8 +240,20 @@ export function installSettings(
188
240
  list.onChange = (id, value) => {
189
241
  const toggle = TOGGLES.find((entry) => entry.id === id);
190
242
  if (toggle) {
191
- state[toggle.key] = value === "true";
192
- writeToggle(agentDir, toggle.key, state[toggle.key]);
243
+ if (disposed || (value !== "true" && value !== "false")) return;
244
+ try {
245
+ writeToggle(agentDir, toggle.key, value === "true");
246
+ state[toggle.key] = value === "true";
247
+ } catch (error) {
248
+ if (
249
+ !(error instanceof SyntaxError) &&
250
+ typeof (error as NodeJS.ErrnoException).code !== "string"
251
+ )
252
+ throw error;
253
+ onError?.(error as Error);
254
+ }
255
+ const item = items.find((entry) => entry.id === id);
256
+ if (item) item.currentValue = String(state[toggle.key]);
193
257
  return;
194
258
  }
195
259
  native(id, value);