proper-base 0.5.1 → 0.7.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.
@@ -1,101 +1,63 @@
1
- import { createHash } from "node:crypto";
1
+ import type { SessionManager } from "@earendil-works/pi-coding-agent";
2
2
 
3
3
  export const PROMPT_DISPLAY_ENTRY = "proper-prompt-display";
4
-
5
- type Command = { name: string; source: string };
6
- type Message = { content: string | Array<{ type: string; text?: string }> };
7
- type Entry = {
8
- type: string;
9
- customType?: string;
10
- data?: unknown;
11
- };
12
- export type PromptDisplayRecord = { hash: string; raw: string };
13
-
14
- export type PromptDisplayController = {
15
- captureInput(text: string, commands: Command[]): void;
16
- captureUser(message: Message): void;
17
- transform(markdown: string): string;
18
- drain(): PromptDisplayRecord[];
19
- restore(entries: Entry[]): void;
20
- clear(): void;
21
- };
22
-
23
- export function createPromptDisplay(): PromptDisplayController {
24
- const display = new Map<string, string>();
25
- const pending = new Map<string, string>();
26
- const inputs: Array<string | undefined> = [];
27
-
4
+ type Message = Parameters<SessionManager["appendMessage"]>[0];
5
+ type Entry = ReturnType<SessionManager["getBranch"]>[number];
6
+ export type PromptDisplayRecord = { messageEntryId: string; raw: string };
7
+
8
+ /** Display metadata belongs to a message, never to its text or submission order. */
9
+ export function createPromptDisplay() {
10
+ let display = new WeakMap<Message, string>();
11
+ const pending: PromptDisplayRecord[] = [];
28
12
  return {
29
- captureInput(text, commands) {
30
- const name = /^\/([^\s]+)/.exec(text)?.[1];
31
- const prompt = name
32
- ? commands.some(
33
- (command) => command.name === name && command.source === "prompt",
34
- )
35
- : false;
36
- inputs.push(prompt ? text : undefined);
13
+ bind(message: Message, raw: string) {
14
+ display.set(message, raw);
37
15
  },
38
- captureUser(message) {
39
- const raw = inputs.shift();
40
- if (!raw) return;
41
- const expanded = messageText(message);
42
- if (!expanded) return;
43
- const key = hash(expanded);
44
- display.set(key, raw);
45
- pending.set(key, raw);
16
+ rawFor(message: Message): string | undefined {
17
+ return display.get(message);
46
18
  },
47
- transform(markdown) {
48
- return display.get(hash(markdown)) ?? markdown;
19
+ persist(message: Message, messageEntryId: string) {
20
+ const raw = display.get(message);
21
+ if (raw !== undefined) pending.push({ messageEntryId, raw });
49
22
  },
50
- drain() {
51
- const records = [...pending].map(([hash, raw]) => ({ hash, raw }));
52
- pending.clear();
53
- return records;
23
+ drain(): PromptDisplayRecord[] {
24
+ return pending.splice(0);
54
25
  },
55
- restore(entries) {
56
- display.clear();
57
- pending.clear();
58
- inputs.length = 0;
26
+ restore(entries: Entry[]) {
27
+ display = new WeakMap();
28
+ pending.length = 0;
29
+ const messages = new Map(
30
+ entries.flatMap((entry) =>
31
+ entry.type === "message" && entry.message.role === "user"
32
+ ? [[entry.id, entry.message] as const]
33
+ : [],
34
+ ),
35
+ );
59
36
  for (const entry of entries) {
60
37
  if (
61
38
  entry.type !== "custom" ||
62
39
  entry.customType !== PROMPT_DISPLAY_ENTRY
63
- ) {
40
+ )
64
41
  continue;
42
+ const data = entry.data as { prompts?: unknown } | undefined;
43
+ if (!data || !Array.isArray(data.prompts)) continue;
44
+ for (const record of data.prompts) {
45
+ if (
46
+ !record ||
47
+ typeof record !== "object" ||
48
+ typeof record.messageEntryId !== "string" ||
49
+ typeof record.raw !== "string"
50
+ )
51
+ continue;
52
+ const message = messages.get(record.messageEntryId);
53
+ if (message) display.set(message, record.raw);
65
54
  }
66
- const records = asRecords(entry.data);
67
- for (const record of records) display.set(record.hash, record.raw);
68
55
  }
69
56
  },
70
57
  clear() {
71
- display.clear();
72
- pending.clear();
73
- inputs.length = 0;
58
+ display = new WeakMap();
59
+ pending.length = 0;
74
60
  },
75
61
  };
76
62
  }
77
-
78
- function messageText(message: Message): string {
79
- if (typeof message.content === "string") return message.content;
80
- return message.content
81
- .filter((part) => part.type === "text" && typeof part.text === "string")
82
- .map((part) => part.text ?? "")
83
- .join("");
84
- }
85
-
86
- function hash(text: string): string {
87
- return createHash("sha256").update(text.trim()).digest("hex");
88
- }
89
-
90
- function asRecords(data: unknown): PromptDisplayRecord[] {
91
- if (typeof data !== "object" || data === null) return [];
92
- const prompts = (data as { prompts?: unknown }).prompts;
93
- if (!Array.isArray(prompts)) return [];
94
- return prompts.flatMap((record) => {
95
- if (typeof record !== "object" || record === null) return [];
96
- const { hash, raw } = record as { hash?: unknown; raw?: unknown };
97
- return typeof hash === "string" && typeof raw === "string"
98
- ? [{ hash, raw }]
99
- : [];
100
- });
101
- }
63
+ export type PromptDisplayController = ReturnType<typeof createPromptDisplay>;
@@ -0,0 +1,16 @@
1
+ import type { NormalizedBuildSystemPromptOptions } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Compose normally; never turn structured input into an opaque replacement. */
4
+ export function appendPromptSection(
5
+ options: NormalizedBuildSystemPromptOptions,
6
+ name: string,
7
+ text: string,
8
+ ): void {
9
+ if (options.forceSystemPrompt !== undefined) {
10
+ // A prior extension explicitly replaced the prompt. Preserve that choice;
11
+ // Pi ignores structured sections in this mode, so append to its text.
12
+ options.forceSystemPrompt += `\n\n<${name}>\n${text}\n</${name}>`;
13
+ } else {
14
+ options.sections[name] = text;
15
+ }
16
+ }
@@ -20,6 +20,8 @@ import { open, readdir, stat } from "node:fs/promises";
20
20
  import { join, resolve } from "node:path";
21
21
  import { createInterface } from "node:readline";
22
22
 
23
+ import { SessionSelectorComponent } from "@earendil-works/pi-coding-agent";
24
+
23
25
  import { projectKey } from "./store.ts";
24
26
 
25
27
  /** Structurally compatible with pi's `SessionInfo`. */
@@ -448,12 +450,18 @@ export function createSessionListers(agentDir: string) {
448
450
  * was handed restores full-text search without the loader ever waiting for it.
449
451
  * Sessions arrive newest-first, which is the order the picker shows them in.
450
452
  */
451
- export function backfillSearchText(sessions: SessionInfo[]): () => void {
453
+ export function backfillSearchText(
454
+ sessions: SessionInfo[],
455
+ onUpdate?: (session: SessionInfo) => void,
456
+ ): () => void {
452
457
  let cancelled = false;
453
458
  void (async () => {
454
459
  for (const session of sessions) {
455
460
  if (cancelled) return;
456
- session.allMessagesText = await readSearchText(session.path);
461
+ const text = await readSearchText(session.path);
462
+ if (cancelled) return;
463
+ session.allMessagesText = text;
464
+ onUpdate?.(session);
457
465
  }
458
466
  })();
459
467
  return () => {
@@ -461,37 +469,140 @@ export function backfillSearchText(sessions: SessionInfo[]): () => void {
461
469
  };
462
470
  }
463
471
 
464
- type Listers = { list: unknown; listAll: unknown };
472
+ type Lister = (...args: never[]) => unknown;
473
+ type Listers = { list: Lister; listAll: Lister };
474
+ type SessionListSurface = {
475
+ allSessions: SessionInfo[];
476
+ showCwd: boolean;
477
+ filteredSessions: Array<{ session: SessionInfo }>;
478
+ selectedIndex: number;
479
+ getSelectedSessionPath(): string | undefined;
480
+ setSessions(sessions: SessionInfo[], showCwd: boolean): void;
481
+ };
482
+ type SelectorSurface = {
483
+ sessionList: SessionListSurface;
484
+ requestRender(): void;
485
+ };
486
+ type SessionListController = { restore(): void };
465
487
 
466
488
  const FAST_SESSION_LIST = Symbol.for("pi-proper-base.fast-session-list");
489
+ const SELECTOR_REFRESH = Symbol.for("pi-proper-base.session-selector-refresh");
490
+ type TaggedListers = Listers & {
491
+ [FAST_SESSION_LIST]?: SessionListController | true;
492
+ };
493
+ type TaggedSelectorPrototype = {
494
+ handleInput(data: string): void;
495
+ [SELECTOR_REFRESH]?: SessionListController;
496
+ };
467
497
 
468
- /**
469
- * Point pi's session listing at the fast readers.
470
- *
471
- * Pi's `SessionManager` is a module singleton reached through static property
472
- * lookups, so replacing the two listing methods covers `/resume` without
473
- * touching the picker. Installation is idempotent: the class outlives every
474
- * session, so a reload must not stack wrappers.
475
- */
476
- export function installFastSessionList(target: object, agentDir: string): void {
477
- const tagged = target as Listers & { [FAST_SESSION_LIST]?: true };
478
- if (tagged[FAST_SESSION_LIST]) return;
498
+ /** Install fast listers plus live query refresh, with reload-safe ownership. */
499
+ export function installFastSessionList(
500
+ target: object,
501
+ agentDir: string,
502
+ ): () => void {
503
+ const tagged = target as TaggedListers;
504
+ const previous = tagged[FAST_SESSION_LIST];
505
+ if (previous && previous !== true) previous.restore();
506
+ const selectorPrototype =
507
+ SessionSelectorComponent.prototype as unknown as TaggedSelectorPrototype;
508
+ selectorPrototype[SELECTOR_REFRESH]?.restore();
509
+ const originalList = tagged.list;
510
+ const originalListAll = tagged.listAll;
511
+ const originalHandleInput = selectorPrototype.handleInput;
479
512
  const fast = createSessionListers(agentDir);
513
+ const selectors = new Set<WeakRef<SelectorSurface>>();
514
+ const seen = new WeakSet<SelectorSurface>();
515
+ const pending = new Set<SessionInfo>();
516
+ let installed = true;
517
+ let refreshTimer: ReturnType<typeof setTimeout> | undefined;
480
518
  let cancelBackfill: (() => void) | undefined;
519
+
520
+ const refreshMatchingQueries = () => {
521
+ refreshTimer = undefined;
522
+ for (const reference of selectors) {
523
+ const selector = reference.deref();
524
+ if (!selector) {
525
+ selectors.delete(reference);
526
+ continue;
527
+ }
528
+ const list = selector.sessionList;
529
+ if (
530
+ !list ||
531
+ !Array.isArray(list.allSessions) ||
532
+ !list.allSessions.some((session) => pending.has(session)) ||
533
+ typeof list.setSessions !== "function"
534
+ )
535
+ continue;
536
+ const selectedPath = list.getSelectedSessionPath?.();
537
+ list.setSessions(list.allSessions, list.showCwd);
538
+ if (selectedPath && Array.isArray(list.filteredSessions)) {
539
+ const selectedIndex = list.filteredSessions.findIndex(
540
+ (item) => item.session.path === selectedPath,
541
+ );
542
+ if (selectedIndex >= 0) list.selectedIndex = selectedIndex;
543
+ }
544
+ selector.requestRender?.();
545
+ }
546
+ pending.clear();
547
+ };
548
+ const scheduleRefresh = (updated: SessionInfo) => {
549
+ pending.add(updated);
550
+ refreshTimer ??= setTimeout(refreshMatchingQueries, 16);
551
+ refreshTimer.unref();
552
+ };
481
553
  const served = (sessions: SessionInfo[]): SessionInfo[] => {
482
- // Only the newest listing is worth completing; a rescan replaces it.
554
+ if (!installed) return sessions;
483
555
  cancelBackfill?.();
484
- cancelBackfill = backfillSearchText(sessions);
556
+ cancelBackfill = backfillSearchText(sessions, scheduleRefresh);
485
557
  return sessions;
486
558
  };
487
- tagged.list = (
559
+ const list = (
488
560
  cwd: string,
489
561
  sessionDir?: string,
490
562
  onProgress?: ProgressCallback,
491
- ) => fast.list(cwd, sessionDir, onProgress).then(served);
492
- tagged.listAll = (
563
+ ) =>
564
+ installed
565
+ ? fast.list(cwd, sessionDir, onProgress).then(served)
566
+ : Reflect.apply(originalList, target, [cwd, sessionDir, onProgress]);
567
+ const listAll = (
493
568
  sessionDirOrProgress?: string | ProgressCallback,
494
569
  onProgress?: ProgressCallback,
495
- ) => fast.listAll(sessionDirOrProgress, onProgress).then(served);
496
- tagged[FAST_SESSION_LIST] = true;
570
+ ) =>
571
+ installed
572
+ ? fast.listAll(sessionDirOrProgress, onProgress).then(served)
573
+ : Reflect.apply(originalListAll, target, [
574
+ sessionDirOrProgress,
575
+ onProgress,
576
+ ]);
577
+ function handleInput(this: SelectorSurface, data: string): void {
578
+ if (installed && !seen.has(this)) {
579
+ seen.add(this);
580
+ selectors.add(new WeakRef(this));
581
+ }
582
+ originalHandleInput.call(this, data);
583
+ }
584
+ const controller: SessionListController = {
585
+ restore() {
586
+ installed = false;
587
+ cancelBackfill?.();
588
+ clearTimeout(refreshTimer);
589
+ pending.clear();
590
+ selectors.clear();
591
+ if (tagged[FAST_SESSION_LIST] !== controller) return;
592
+ if (tagged.list === (list as Lister)) tagged.list = originalList;
593
+ if (tagged.listAll === (listAll as Lister))
594
+ tagged.listAll = originalListAll;
595
+ if (selectorPrototype.handleInput === handleInput)
596
+ selectorPrototype.handleInput = originalHandleInput;
597
+ delete tagged[FAST_SESSION_LIST];
598
+ if (selectorPrototype[SELECTOR_REFRESH] === controller)
599
+ delete selectorPrototype[SELECTOR_REFRESH];
600
+ },
601
+ };
602
+ tagged.list = list as Lister;
603
+ tagged.listAll = listAll as Lister;
604
+ selectorPrototype.handleInput = handleInput;
605
+ tagged[FAST_SESSION_LIST] = controller;
606
+ selectorPrototype[SELECTOR_REFRESH] = controller;
607
+ return () => controller.restore();
497
608
  }
@@ -1,7 +1,10 @@
1
- import { parseSkillBlock } from "@earendil-works/pi-coding-agent";
1
+ import {
2
+ type ContextEditEntry,
3
+ parseSkillBlock,
4
+ } from "@earendil-works/pi-coding-agent";
2
5
 
3
6
  /**
4
- * Characters kept from a single skill body when it is carried across a
7
+ * Characters kept from a complete skill block when it is carried across a
5
8
  * compaction. Roughly four characters per token, matching the estimate Pi's
6
9
  * own compaction uses.
7
10
  */
@@ -15,8 +18,11 @@ type ContextMessage = {
15
18
  content?: unknown;
16
19
  };
17
20
  type TextPart = { type: "text"; text: string };
18
- type SessionEntry = {
21
+ type BranchEntry = {
19
22
  type: string;
23
+ id?: string;
24
+ targetId?: string;
25
+ replacement?: ContextEditEntry["replacement"];
20
26
  message?: { role?: string; content?: unknown };
21
27
  };
22
28
  type Invocation = { name: string; block: string };
@@ -47,7 +53,7 @@ function readInvocation(
47
53
  }
48
54
 
49
55
  function messageInvocation(
50
- message: ContextMessage | SessionEntry["message"],
56
+ message: ContextMessage | BranchEntry["message"],
51
57
  ): ReturnType<typeof readInvocation> {
52
58
  const content = message?.content;
53
59
  if (typeof content === "string") return readInvocation(content);
@@ -97,8 +103,37 @@ function prependText(message: ContextMessage, prefix: string): ContextMessage {
97
103
  return { ...message, content: next };
98
104
  }
99
105
 
100
- function truncate(block: string, limit: number): string {
101
- return block.length <= limit ? block : block.slice(0, limit) + TRUNCATED;
106
+ function truncate(block: string, limit: number): string | undefined {
107
+ if (block.length <= limit) return block;
108
+ const suffix = `${TRUNCATED}\n</skill>`;
109
+ // Never cut the opening tag or omit the closing tag. An oversized header
110
+ // cannot fit safely, so leave that skill out rather than emit broken markup.
111
+ if (block.indexOf("\n") + 1 + suffix.length > limit) return undefined;
112
+ return block.slice(0, limit - suffix.length) + suffix;
113
+ }
114
+
115
+ function contextEdits(
116
+ branch: BranchEntry[],
117
+ ): Map<string, ContextEditEntry["replacement"]> {
118
+ const edits = new Map<string, ContextEditEntry["replacement"]>();
119
+ for (const entry of branch) {
120
+ if (entry.type !== "context_edit" || typeof entry.targetId !== "string")
121
+ continue;
122
+ edits.set(entry.targetId, entry.replacement ?? null);
123
+ }
124
+ return edits;
125
+ }
126
+
127
+ function visibleBranchMessage(
128
+ entry: BranchEntry,
129
+ edits: Map<string, ContextEditEntry["replacement"]>,
130
+ ): BranchEntry["message"] | undefined {
131
+ if (entry.type !== "message" || entry.message?.role !== "user")
132
+ return undefined;
133
+ if (!entry.id || !edits.has(entry.id)) return entry.message;
134
+ const replacement = edits.get(entry.id);
135
+ if (replacement === null || !replacement) return undefined;
136
+ return { ...entry.message, content: replacement.content };
102
137
  }
103
138
 
104
139
  /**
@@ -117,7 +152,7 @@ function truncate(block: string, limit: number): string {
117
152
  */
118
153
  export function pinSkillContext<T extends ContextMessage>(
119
154
  messages: T[],
120
- branch: SessionEntry[],
155
+ branch: BranchEntry[],
121
156
  ): T[] {
122
157
  const seen = new Set<string>();
123
158
  let changed = false;
@@ -154,21 +189,24 @@ export function pinSkillContext<T extends ContextMessage>(
154
189
  */
155
190
  function carryAcrossCompaction(
156
191
  messages: ContextMessage[],
157
- branch: SessionEntry[],
192
+ branch: BranchEntry[],
158
193
  present: Set<string>,
159
194
  ): string | undefined {
160
195
  if (!messages.some((message) => message.role === "compactionSummary")) {
161
196
  return undefined;
162
197
  }
198
+ const edits = contextEdits(branch);
163
199
  const missing = new Map<string, Invocation>();
164
200
  for (const entry of branch) {
165
- if (entry.type !== "message" || entry.message?.role !== "user") continue;
166
- const invocation = messageInvocation(entry.message);
201
+ const message = visibleBranchMessage(entry, edits);
202
+ if (!message) continue;
203
+ const invocation = messageInvocation(message);
167
204
  if (!invocation) continue;
168
205
  // A skill file edited mid-session yields a new body, so the newest state
169
206
  // of each name decides: a present body cancels an earlier missing one.
170
- if (present.has(invocation.block)) missing.delete(invocation.name);
171
- else missing.set(invocation.name, invocation);
207
+ missing.delete(invocation.name);
208
+ if (!present.has(invocation.block))
209
+ missing.set(invocation.name, invocation);
172
210
  }
173
211
  if (!missing.size) return undefined;
174
212
 
@@ -176,8 +214,8 @@ function carryAcrossCompaction(
176
214
  let used = 0;
177
215
  for (const invocation of [...missing.values()].reverse()) {
178
216
  const block = truncate(invocation.block, MAX_SKILL_CHARS);
179
- if (used + block.length > MAX_CARRY_CHARS) continue;
180
- used += block.length;
217
+ if (!block || used + block.length + 2 > MAX_CARRY_CHARS) continue;
218
+ used += block.length + 2;
181
219
  blocks.unshift(block);
182
220
  }
183
221
  return blocks.length ? `${blocks.join("\n\n")}\n\n` : undefined;
@@ -1,17 +1,7 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
 
4
- const SETTINGS_FILE_NAME = "settings.json";
5
4
  const CONFIG_FILE_NAME = "proper-base.json";
6
- /**
7
- * proper-llm-router's routing placeholder. Its provider is registered by an
8
- * extension and carries no credentials, so Pi's startup resolver skips it and
9
- * silently falls back; the router re-selects it at every session start anyway.
10
- */
11
- const PLACEHOLDER_PROVIDER = "llm-router";
12
-
13
- /** The model identity Pi's startup defaults are keyed by. */
14
- export type DefaultModel = { provider: string; id: string };
15
5
 
16
6
  type JsonObject = Record<string, unknown>;
17
7
 
@@ -26,118 +16,10 @@ function readJsonObject(path: string): JsonObject | undefined {
26
16
  }
27
17
  }
28
18
 
29
- /** Whether the session's model and effort follow into Pi's startup defaults. */
30
- export function stickyDefaultsEnabled(agentDir: string): boolean {
19
+ /** Whether model and effort selections follow into Pi's startup defaults. */
20
+ export function stickyDefaultsEnabled(agentDir?: string): boolean {
21
+ if (!agentDir) return true;
31
22
  return (
32
23
  readJsonObject(join(agentDir, CONFIG_FILE_NAME))?.stickyDefaults !== false
33
24
  );
34
25
  }
35
-
36
- function settingsPath(agentDir: string): string {
37
- return join(agentDir, SETTINGS_FILE_NAME);
38
- }
39
-
40
- /**
41
- * Pi's settings, or nothing when persistence is off or the file is absent or
42
- * damaged. A damaged file is never replaced with a defaults-only one.
43
- */
44
- function openSettings(agentDir: string): JsonObject | undefined {
45
- if (!stickyDefaultsEnabled(agentDir)) return undefined;
46
- return readJsonObject(settingsPath(agentDir));
47
- }
48
-
49
- /**
50
- * Replace Pi's settings file, preserving every other key and its two-space
51
- * format. Writing from outside is safe against Pi's own saves: its settings
52
- * writer re-reads the file under a lock and merges back only the fields it
53
- * marked modified, so keys written here survive.
54
- *
55
- * ponytail: read-modify-write without Pi's lock. A Pi settings write landing
56
- * inside one of these read/write pairs would be overwritten; take the lock if
57
- * extensions ever get access to it.
58
- */
59
- function writeSettings(agentDir: string, settings: JsonObject): boolean {
60
- try {
61
- writeFileSync(
62
- settingsPath(agentDir),
63
- `${JSON.stringify(settings, null, 2)}\n`,
64
- "utf8",
65
- );
66
- return true;
67
- } catch {
68
- return false;
69
- }
70
- }
71
-
72
- function perModelLevel(
73
- settings: JsonObject,
74
- model: DefaultModel,
75
- ): unknown | undefined {
76
- const levels = settings.modelThinkingLevels;
77
- if (!levels || typeof levels !== "object") return undefined;
78
- return (levels as JsonObject)[`${model.provider}/${model.id}`];
79
- }
80
-
81
- /**
82
- * Record the active model as Pi's startup default.
83
- *
84
- * Pi writes `defaultProvider`/`defaultModel` only when Ctrl+S is pressed in the
85
- * `/model` picker; a plain selection lives and dies with the session, so a new
86
- * session silently reopens on whichever model was saved last. Extensions get no
87
- * access to Pi's settings manager, so the two keys are rewritten directly.
88
- *
89
- * An unchanged selection writes nothing, so restores and repeated cycling
90
- * through the same model cause no churn. The routing placeholder is never
91
- * stored, because Pi cannot start on it.
92
- */
93
- export function persistDefaultModel(
94
- agentDir: string,
95
- model: DefaultModel,
96
- ): boolean {
97
- if (model.provider === PLACEHOLDER_PROVIDER) return false;
98
- const settings = openSettings(agentDir);
99
- if (!settings) return false;
100
- if (
101
- settings.defaultProvider === model.provider &&
102
- settings.defaultModel === model.id
103
- ) {
104
- return false;
105
- }
106
- return writeSettings(agentDir, {
107
- ...settings,
108
- defaultProvider: model.provider,
109
- defaultModel: model.id,
110
- });
111
- }
112
-
113
- /**
114
- * Record the active thinking level as Pi's startup default.
115
- *
116
- * Persisting the level is what makes it hold, not merely what makes it
117
- * reappear. Pi recomputes the level on every model switch from
118
- * `modelThinkingLevels`, then `defaultThinkingLevel`, and only then the level
119
- * in effect, so a session-only choice does not survive the next `/model`,
120
- * `Ctrl+P`, `/clear`, or routed prompt: the saved default overwrites it mid
121
- * session. Writing the same key the resolver reads keeps the current choice
122
- * both durable and stable across switches.
123
- *
124
- * The event carries the level after Pi clamps it to the model, so moving to a
125
- * model that cannot reach the current level records the level actually in
126
- * effect. A level matching a `modelThinkingLevels` entry for the current model
127
- * is not stored: that rule is per model, and promoting it to the global default
128
- * would hand it to every model without one.
129
- */
130
- export function persistDefaultThinkingLevel(
131
- agentDir: string,
132
- level: string,
133
- model: DefaultModel | undefined,
134
- ): boolean {
135
- const settings = openSettings(agentDir);
136
- if (!settings) return false;
137
- if (settings.defaultThinkingLevel === level) return false;
138
- if (model && perModelLevel(settings, model) === level) return false;
139
- return writeSettings(agentDir, {
140
- ...settings,
141
- defaultThinkingLevel: level,
142
- });
143
- }