proper-base 0.6.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.
@@ -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
- }
@@ -0,0 +1,199 @@
1
+ import { AgentSession } from "@earendil-works/pi-coding-agent";
2
+ import { stickyDefaultsEnabled } from "./startup-defaults.ts";
3
+
4
+ type ThinkingLevel = Parameters<AgentSession["setThinkingLevel"]>[0];
5
+
6
+ const INSTALLED = Symbol.for("pi-proper-base.sticky-defaults");
7
+ const PLACEHOLDER_PROVIDER = "llm-router";
8
+
9
+ type Model = { provider: string; id: string };
10
+ type MutationOptions = { persist?: boolean };
11
+ type CycleResult = { model: Model } | undefined;
12
+ type SessionPrototype = {
13
+ _buildRuntime(options: unknown): void;
14
+ setModel(model: Model, options?: MutationOptions): Promise<void>;
15
+ cycleModel(
16
+ direction?: "forward" | "backward",
17
+ options?: MutationOptions,
18
+ ): Promise<CycleResult>;
19
+ setThinkingLevel(level: ThinkingLevel, options?: MutationOptions): void;
20
+ [INSTALLED]?: StickyDefaultsController;
21
+ };
22
+ type SessionIdentity = object;
23
+ type LiveSession = {
24
+ sessionManager: SessionIdentity;
25
+ settingsManager: {
26
+ getDefaultProvider(): string | undefined;
27
+ getDefaultModel(): string | undefined;
28
+ setDefaultModelAndProvider(provider: string, modelId: string): void;
29
+ getDefaultThinkingLevel(): ThinkingLevel | undefined;
30
+ setDefaultThinkingLevel(level: ThinkingLevel): void;
31
+ getModelThinkingLevel(
32
+ provider: string,
33
+ modelId: string,
34
+ ): ThinkingLevel | undefined;
35
+ };
36
+ model: Model | undefined;
37
+ thinkingLevel: ThinkingLevel;
38
+ };
39
+
40
+ export type StickyDefaultsController = {
41
+ activate(sessionManager: SessionIdentity): void;
42
+ /** The live AgentSession behind an extension context's session manager. */
43
+ session(sessionManager: SessionIdentity): unknown;
44
+ restore(): void;
45
+ };
46
+
47
+ /**
48
+ * Bridge Pi 0.85.1's missing ExtensionAPI persistence option to the live
49
+ * AgentSession. Remove this adapter once ExtensionAPI forwards `{ persist }`.
50
+ */
51
+ export function installStickyDefaultsAdapter(
52
+ enabled: () => boolean = () => stickyDefaultsEnabled(),
53
+ ): StickyDefaultsController {
54
+ const prototype = AgentSession.prototype as unknown as SessionPrototype;
55
+ prototype[INSTALLED]?.restore();
56
+
57
+ const originalBuildRuntime = prototype._buildRuntime;
58
+ const originalSetModel = prototype.setModel;
59
+ const originalCycleModel = prototype.cycleModel;
60
+ const originalSetThinkingLevel = prototype.setThinkingLevel;
61
+ if (
62
+ typeof originalBuildRuntime !== "function" ||
63
+ typeof originalSetModel !== "function" ||
64
+ typeof originalCycleModel !== "function" ||
65
+ typeof originalSetThinkingLevel !== "function"
66
+ ) {
67
+ return { activate() {}, session: () => undefined, restore() {} };
68
+ }
69
+ let installed = true;
70
+ const sessions = new WeakMap<SessionIdentity, LiveSession>();
71
+ const active = new WeakSet<LiveSession>();
72
+ const modelMutationDepth = new WeakMap<LiveSession, number>();
73
+
74
+ const shouldPersist = (session: LiveSession): boolean =>
75
+ installed && active.has(session) && enabled();
76
+ const beginModelMutation = (session: LiveSession) => {
77
+ modelMutationDepth.set(session, (modelMutationDepth.get(session) ?? 0) + 1);
78
+ };
79
+ const endModelMutation = (session: LiveSession) => {
80
+ modelMutationDepth.set(
81
+ session,
82
+ Math.max(0, (modelMutationDepth.get(session) ?? 1) - 1),
83
+ );
84
+ };
85
+ const persistModel = (session: LiveSession, model: Model | undefined) => {
86
+ if (
87
+ !shouldPersist(session) ||
88
+ !model ||
89
+ model.provider === PLACEHOLDER_PROVIDER
90
+ )
91
+ return;
92
+ const settings = session.settingsManager;
93
+ if (
94
+ settings.getDefaultProvider() === model.provider &&
95
+ settings.getDefaultModel() === model.id
96
+ )
97
+ return;
98
+ settings.setDefaultModelAndProvider(model.provider, model.id);
99
+ };
100
+
101
+ function buildRuntime(this: LiveSession, options: unknown): void {
102
+ originalBuildRuntime.call(this as never, options);
103
+ if (installed) sessions.set(this.sessionManager, this);
104
+ }
105
+ async function setModel(
106
+ this: LiveSession,
107
+ model: Model,
108
+ options: MutationOptions = {},
109
+ ): Promise<void> {
110
+ if (!shouldPersist(this))
111
+ return originalSetModel.call(this as never, model, options);
112
+ beginModelMutation(this);
113
+ try {
114
+ await originalSetModel.call(this as never, model, {
115
+ ...options,
116
+ persist: false,
117
+ });
118
+ } finally {
119
+ endModelMutation(this);
120
+ }
121
+ persistModel(this, this.model);
122
+ }
123
+ async function cycleModel(
124
+ this: LiveSession,
125
+ direction: "forward" | "backward" = "forward",
126
+ options: MutationOptions = {},
127
+ ): Promise<CycleResult> {
128
+ if (!shouldPersist(this))
129
+ return originalCycleModel.call(this as never, direction, options);
130
+ beginModelMutation(this);
131
+ let result: CycleResult;
132
+ try {
133
+ result = await originalCycleModel.call(this as never, direction, {
134
+ ...options,
135
+ persist: false,
136
+ });
137
+ } finally {
138
+ endModelMutation(this);
139
+ }
140
+ if (result) persistModel(this, result.model);
141
+ return result;
142
+ }
143
+ function setThinkingLevel(
144
+ this: LiveSession,
145
+ level: ThinkingLevel,
146
+ options: MutationOptions = {},
147
+ ): void {
148
+ if (!shouldPersist(this)) {
149
+ originalSetThinkingLevel.call(this as never, level, options);
150
+ return;
151
+ }
152
+ originalSetThinkingLevel.call(this as never, level, {
153
+ ...options,
154
+ persist: false,
155
+ });
156
+ if (
157
+ (modelMutationDepth.get(this) ?? 0) > 0 ||
158
+ this.model?.provider === PLACEHOLDER_PROVIDER
159
+ )
160
+ return;
161
+ const effective = this.thinkingLevel;
162
+ const settings = this.settingsManager;
163
+ if (
164
+ this.model &&
165
+ settings.getModelThinkingLevel(this.model.provider, this.model.id) ===
166
+ effective
167
+ )
168
+ return;
169
+ if (settings.getDefaultThinkingLevel() !== effective)
170
+ settings.setDefaultThinkingLevel(effective);
171
+ }
172
+
173
+ const controller: StickyDefaultsController = {
174
+ activate(sessionManager) {
175
+ const session = sessions.get(sessionManager);
176
+ if (session) active.add(session);
177
+ },
178
+ session: (sessionManager) => sessions.get(sessionManager),
179
+ restore() {
180
+ installed = false;
181
+ if (prototype[INSTALLED] !== controller) return;
182
+ if (prototype._buildRuntime === buildRuntime)
183
+ prototype._buildRuntime = originalBuildRuntime;
184
+ if (prototype.setModel === setModel)
185
+ prototype.setModel = originalSetModel;
186
+ if (prototype.cycleModel === cycleModel)
187
+ prototype.cycleModel = originalCycleModel;
188
+ if (prototype.setThinkingLevel === setThinkingLevel)
189
+ prototype.setThinkingLevel = originalSetThinkingLevel;
190
+ delete prototype[INSTALLED];
191
+ },
192
+ };
193
+ prototype._buildRuntime = buildRuntime;
194
+ prototype.setModel = setModel;
195
+ prototype.cycleModel = cycleModel;
196
+ prototype.setThinkingLevel = setThinkingLevel;
197
+ prototype[INSTALLED] = controller;
198
+ return controller;
199
+ }
@@ -256,15 +256,20 @@ function renderActive(
256
256
  base: number,
257
257
  ): string[] {
258
258
  const output: string[][] = Array.from({ length: children.length });
259
+ const hits: DetailHit[][] = Array.from({ length: children.length });
259
260
  let hasTextBelow = false;
260
261
  for (let index = children.length - 1; index >= 0; index--) {
261
262
  const child = children[index];
262
263
  if (!child) continue;
263
- const native = child.render(width);
264
+ const hitStart = state.pendingHits.length;
265
+ const native = isUserBoundary(child)
266
+ ? renderExpandable(child, width, state)
267
+ : child.render(width);
264
268
  output[index] =
265
269
  state.completed.has(child) && hasTextBelow
266
270
  ? renderGroup([child], width, state, [], 0)
267
271
  : native;
272
+ hits[index] = state.pendingHits.splice(hitStart);
268
273
  if (hasSectionText(native)) hasTextBelow = true;
269
274
  }
270
275
  // Outline rows are recorded on a forward pass because the render loop above
@@ -272,6 +277,7 @@ function renderActive(
272
277
  let row = base;
273
278
  for (let index = 0; index < children.length; index++) {
274
279
  const rendered = output[index];
280
+ state.pendingHits.push(...(hits[index] ?? []));
275
281
  const child = children[index];
276
282
  if (child && rendered?.length) {
277
283
  const entry = actionEntry(child);
@@ -358,7 +364,7 @@ function renderGroup(
358
364
  row: base + lines.length,
359
365
  label: "prompt",
360
366
  });
361
- lines.push(...child.render(width));
367
+ lines.push(...renderExpandable(child, width, state));
362
368
  continue;
363
369
  }
364
370
  if (name === "Spacer") {
@@ -1,22 +1,18 @@
1
1
  /**
2
2
  * Pi's fullscreen renderer scrolls its transcript exactly one line per
3
- * mouse-wheel report: the renderer's `wheelScrollLines` option defaults to 1
4
- * and pi passes no override and exposes no setting. Terminals natively
5
- * multiply a wheel notch to about three lines, so fullscreen scrolling feels
6
- * slower than every other terminal surface.
7
- *
8
- * No escape sequence lets an application query the terminal's own wheel
9
- * configuration, so the step defaults to the 3-line application convention
10
- * (vim, less) and honors a per-terminal `PROPER_WHEEL_SCROLL_LINES`
11
- * environment override that each terminal's profile can export.
3
+ * mouse-wheel report. Proper-base raises that to the terminal convention.
12
4
  */
13
5
 
14
6
  const DEFAULT_WHEEL_SCROLL_LINES = 3;
7
+ const INSTALLED = Symbol.for("pi-proper-base.wheel-scroll-lines");
15
8
 
16
- /** Renderer surface carrying the per-wheel-event line count. */
17
- type WheelHost = { wheelScrollLines?: unknown };
9
+ type WheelController = { restore(): void };
10
+ type WheelHost = {
11
+ wheelScrollLines?: unknown;
12
+ [INSTALLED]?: WheelController;
13
+ };
18
14
 
19
- /** Lines per wheel event: a positive integer override, else the 3-line convention. */
15
+ /** Lines per wheel event: a positive integer override, else three. */
20
16
  export function resolveWheelScrollLines(
21
17
  env: Record<string, string | undefined> = process.env,
22
18
  ): number {
@@ -24,23 +20,24 @@ export function resolveWheelScrollLines(
24
20
  return parsed >= 1 ? parsed : DEFAULT_WHEEL_SCROLL_LINES;
25
21
  }
26
22
 
27
- /**
28
- * Raise the fullscreen renderer's wheel step. Only a renderer that already
29
- * exposes a numeric `wheelScrollLines` is touched, so regular mode — where
30
- * the terminal scrolls natively — and a renamed upstream field fail open to
31
- * pi's own behavior.
32
- *
33
- * ponytail: SGR wheel reports cannot distinguish a discrete mouse notch from
34
- * one line of a high-rate trackpad stream, so a terminal emitting one report
35
- * per native line scrolls proportionally faster; exporting
36
- * PROPER_WHEEL_SCROLL_LINES=1 there restores pi's original pace.
37
- */
23
+ /** Patch a fullscreen renderer and return an ownership-checked restoration. */
38
24
  export function installWheelScrollLines(
39
25
  tui: unknown,
40
26
  lines: number = resolveWheelScrollLines(),
41
- ): boolean {
27
+ ): (() => void) | undefined {
42
28
  const host = tui as WheelHost;
43
- if (typeof host.wheelScrollLines !== "number") return false;
44
- host.wheelScrollLines = Math.floor(lines);
45
- return true;
29
+ host[INSTALLED]?.restore();
30
+ if (typeof host.wheelScrollLines !== "number") return undefined;
31
+ const original = host.wheelScrollLines;
32
+ const applied = Math.floor(lines);
33
+ const controller: WheelController = {
34
+ restore() {
35
+ if (host[INSTALLED] !== controller) return;
36
+ if (host.wheelScrollLines === applied) host.wheelScrollLines = original;
37
+ delete host[INSTALLED];
38
+ },
39
+ };
40
+ host.wheelScrollLines = applied;
41
+ host[INSTALLED] = controller;
42
+ return () => controller.restore();
46
43
  }