proper-base 0.5.0 → 0.5.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.
package/README.md CHANGED
@@ -20,6 +20,14 @@ and footer layout.
20
20
  keep their names.
21
21
  - `/clear` starts an empty session but restores the exact provider and model
22
22
  selected in the previous one. No messages, name, or branch state carry over.
23
+ - The model you pick in `/model` and the level you pick in `/thinking` become
24
+ Pi's startup defaults, so the next session opens on them. Pi otherwise saves
25
+ those only when you press Ctrl+S in the picker, and because Pi re-derives the
26
+ thinking level from the saved default on every model switch, an unsaved level
27
+ is otherwise lost mid-session at the next `/model`, Ctrl+P, or `/clear`.
28
+ Switching to a model that cannot reach the current level records the level
29
+ you actually get. Resuming a session does not redefine the model. Set
30
+ `"stickyDefaults": false` in `~/.pi/agent/proper-base.json` to turn this off.
23
31
  - Prompt-template expansions remain model-facing, while the transcript shows
24
32
  the slash command you typed, such as `/implement-ready epic-1 4`.
25
33
  - CLIProxyAPI `empty_stream` failures become normal retryable network errors, so
@@ -47,7 +55,9 @@ proper-base records eligible editor submissions on a best-effort basis, not
47
55
  transformed Pi session messages. History uses an encoded key derived from the
48
56
  current working directory.
49
57
 
50
- - Up and Down recall prompts from previous sessions in the same project.
58
+ - Up and Down recall prompts from previous sessions in the same project. Up
59
+ recalls only from an empty prompt; with a draft it only moves the cursor,
60
+ so Home then Up can no longer replace what you typed.
51
61
  - Ctrl+R starts case-sensitive reverse substring search. Press Ctrl+R again for
52
62
  an older match, Backspace or Shift+Backspace to broaden the query, Enter to
53
63
  submit, Esc to keep the match for editing, or Ctrl+G to restore the original
@@ -75,9 +85,18 @@ directory to forget all proper-base history.
75
85
  and URLs.
76
86
  - `/model ` results sort by displayed model ID in descending numeric-aware
77
87
  order. Typed terms must all match when strict matches exist.
78
- - Enter or Tab switches immediately only when the complete prompt is a
79
- single-line `/model ...` command. Inline and multiline slash segments only
80
- receive the completion. Tab keeps its normal behavior elsewhere.
88
+ - `/model` takes an optional thinking level after the model name, as in
89
+ `/model anthropic/claude-opus-4 high`. Once the model name carries a
90
+ provider slash, the next word completes against Pi's thinking levels; a
91
+ word naming no level keeps searching models.
92
+ - Tab-completing a model name submits nothing. It leaves the name, a
93
+ trailing space, and an open level menu led by the level already in
94
+ effect, so you can type a level straight away or press Enter to keep the
95
+ current one.
96
+ - Tab or Enter on a level completion switches immediately: the level is
97
+ the last argument, so `/model gp<Tab>lo<Tab>` picks the model and `low`
98
+ without a further Enter. Either key switches only when the complete
99
+ prompt is a single-line `/model ...` command.
81
100
 
82
101
  ### Fullscreen navigation and selection
83
102
 
@@ -109,6 +128,13 @@ to the bottom. While you are scrolled up, a dimmer `position/total` reading sits
109
128
  centred under the arrows and counts the prompts in the session; it disappears
110
129
  once the viewport is following output again.
111
130
 
131
+ Pi 0.85.0 moves the prompt cursor to wherever you click in the prompt. If you
132
+ click the prompt area to focus the terminal or to select text, turn off
133
+ `Prompt mouse clicks` in `/settings`: clicks on the prompt text then leave the
134
+ cursor alone while drag-to-select keeps working. The same menu holds the
135
+ `Session action rail` toggle. Both persist in `~/.pi/agent/proper-base.json`
136
+ as `editorMouse` and `sessionRail`.
137
+
112
138
  ### Clipboard and model image context
113
139
 
114
140
  Ctrl+V and Ctrl+Shift+V both use Pi's image-or-text clipboard action. Readable
@@ -158,7 +184,7 @@ highlight. Custom replacement footers are not changed.
158
184
 
159
185
  ## Install
160
186
 
161
- Node 22.19 or newer is required. The package is tested against Pi 0.84.4.
187
+ Node 22.19 or newer is required. The package is tested against Pi 0.85.0.
162
188
 
163
189
  From npm:
164
190
 
package/index.ts CHANGED
@@ -23,10 +23,12 @@ import {
23
23
  installAutocompleteDetails,
24
24
  installInlineSlashAutocomplete,
25
25
  installModelAutocompleteSubmit,
26
+ modelThinkingCommand,
26
27
  sortModelAutocompleteDescending,
27
28
  } from "./src/autocomplete-details.ts";
28
29
  import { installClipboardLeakGuard } from "./src/clipboard-guard.ts";
29
30
  import { commitGuardReason } from "./src/commit-guard.ts";
31
+ import { installEditorMouseGuard } from "./src/editor-mouse.ts";
30
32
  import {
31
33
  installEditorNavigation,
32
34
  installPromptClear,
@@ -59,15 +61,16 @@ import {
59
61
  PROMPT_DISPLAY_ENTRY,
60
62
  } from "./src/prompt-display.ts";
61
63
  import { installPromptJump } from "./src/prompt-jump.ts";
62
- import {
63
- installRailSetting,
64
- type RailSettingController,
65
- } from "./src/rail-setting.ts";
66
64
  import { installRecorder } from "./src/recorder.ts";
67
65
  import { installSelectionDismiss } from "./src/selection-dismiss.ts";
68
66
  import { installFastSessionList } from "./src/session-list.ts";
67
+ import { installSettings, type SettingsController } from "./src/settings.ts";
69
68
  import { pinSkillContext } from "./src/skill-context.ts";
70
69
  import { installSmartSelection } from "./src/smart-selection.ts";
70
+ import {
71
+ persistDefaultModel,
72
+ persistDefaultThinkingLevel,
73
+ } from "./src/startup-defaults.ts";
71
74
  import {
72
75
  appendPrompt,
73
76
  compactIfNeeded,
@@ -294,7 +297,8 @@ export default function (pi: ExtensionAPI) {
294
297
  let removeFooterColors: (() => void) | undefined;
295
298
  let removeJumpToBottom: (() => void) | undefined;
296
299
  let removePromptJump: (() => void) | undefined;
297
- let railSetting: RailSettingController | undefined;
300
+ let settings: SettingsController | undefined;
301
+ let removeEditorMouseGuard: (() => void) | undefined;
298
302
  let removePromptClear: (() => void) | undefined;
299
303
  let removeSmartSelection: (() => void) | undefined;
300
304
  let removeSelectionDismiss: (() => void) | undefined;
@@ -331,6 +335,43 @@ export default function (pi: ExtensionAPI) {
331
335
  );
332
336
  };
333
337
 
338
+ /**
339
+ * Run a `/model <reference> <level>` submission, if that is the shape.
340
+ *
341
+ * Pi reads a `/model` argument as one model search term, so a thinking level
342
+ * appended to it only widens that search and opens the picker. The command is
343
+ * taken over at the editor instead, and the level is applied after the model:
344
+ * every `setModel` recomputes the level from settings, so setting it first
345
+ * would be discarded. A reference matching no model is left to Pi, whose
346
+ * picker still opens on the raw text.
347
+ */
348
+ const applyModelThinking = (ctx: ExtensionContext, text: string): boolean => {
349
+ const request = modelThinkingCommand(text);
350
+ if (!request) return false;
351
+ const available =
352
+ ctx.scopedModels.length > 0
353
+ ? ctx.scopedModels.map((scoped) => scoped.model)
354
+ : ctx.modelRegistry.getAvailable();
355
+ const model = available.find(
356
+ (candidate) =>
357
+ `${candidate.provider}/${candidate.id}` === request.reference ||
358
+ candidate.id === request.reference,
359
+ );
360
+ if (!model) return false;
361
+ void (async () => {
362
+ if (!(await pi.setModel(model))) {
363
+ ctx.ui.notify(
364
+ `Could not switch to ${model.provider}/${model.id}`,
365
+ "error",
366
+ );
367
+ return;
368
+ }
369
+ pi.setThinkingLevel(request.level);
370
+ ctx.ui.notify(`Model: ${model.id} (thinking: ${request.level})`, "info");
371
+ })();
372
+ return true;
373
+ };
374
+
334
375
  pi.registerCommand?.(RESTORE_MODEL_COMMAND, {
335
376
  description: "Internal: restore the model after /clear",
336
377
  handler: async (args, ctx) => {
@@ -394,6 +435,20 @@ export default function (pi: ExtensionAPI) {
394
435
  },
395
436
  });
396
437
 
438
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Sticky startup defaults]]
439
+ pi.on("model_select", (event) => {
440
+ if (event.source === "restore") return;
441
+ persistDefaultModel(getAgentDir(), event.model);
442
+ });
443
+
444
+ pi.on("thinking_level_select", (event, ctx) => {
445
+ persistDefaultThinkingLevel(
446
+ getAgentDir(),
447
+ event.level,
448
+ ctx.model ?? undefined,
449
+ );
450
+ });
451
+
397
452
  pi.on("input", (event) => {
398
453
  if (event.source === "interactive") {
399
454
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Pinned transcript scrolling]]
@@ -573,8 +628,10 @@ export default function (pi: ExtensionAPI) {
573
628
  removeJumpToBottom = undefined;
574
629
  removePromptJump?.();
575
630
  removePromptJump = undefined;
576
- railSetting?.dispose();
577
- railSetting = undefined;
631
+ settings?.dispose();
632
+ settings = undefined;
633
+ removeEditorMouseGuard?.();
634
+ removeEditorMouseGuard = undefined;
578
635
  removePromptClear?.();
579
636
  removePromptClear = undefined;
580
637
  removeSmartSelection?.();
@@ -642,7 +699,9 @@ export default function (pi: ExtensionAPI) {
642
699
  ctx.ui.setEditorText(promptText);
643
700
  return undefined;
644
701
  });
645
- ctx.ui.addAutocompleteProvider?.(sortModelAutocompleteDescending);
702
+ ctx.ui.addAutocompleteProvider?.((current) =>
703
+ sortModelAutocompleteDescending(current, () => pi.getThinkingLevel?.()),
704
+ );
646
705
 
647
706
  const store = storePath(getAgentDir(), ctx.cwd);
648
707
  compactIfNeeded(store);
@@ -704,14 +763,20 @@ export default function (pi: ExtensionAPI) {
704
763
  removeJumpToBottom?.();
705
764
  removeJumpToBottom = installJumpToBottom(editor, tui);
706
765
  removePromptJump?.();
707
- railSetting?.dispose();
708
- railSetting = installRailSetting(tui, editor, getAgentDir());
766
+ settings?.dispose();
767
+ settings = installSettings(tui, editor, getAgentDir());
768
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt mouse clicks]]
769
+ removeEditorMouseGuard?.();
770
+ removeEditorMouseGuard = installEditorMouseGuard(
771
+ editor,
772
+ () => settings?.editorMouse() !== false,
773
+ );
709
774
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
710
775
  removePromptJump = installPromptJump(tui, {
711
776
  color: (value) => ctx.ui.theme.fg("muted", value),
712
777
  subtle: (value) => ctx.ui.theme.fg("dim", value),
713
778
  outline: () =>
714
- railSetting?.enabled() !== false
779
+ settings?.enabled() !== false
715
780
  ? (transcriptCleanup?.outline() ?? [])
716
781
  : [],
717
782
  });
@@ -730,15 +795,18 @@ export default function (pi: ExtensionAPI) {
730
795
  // provider's global `/fast` can only be repurposed as a session
731
796
  // toggle by consuming it at the editor before pi ever parses it.
732
797
  (text) => {
733
- if (!isFastToggle(text)) return false;
734
- const notice = fastToggleNotice({
735
- scope: "session",
736
- enabled: fastOverlay.toggleSession(),
737
- otherEnabled: fastOverlay.isGlobalEnabled(),
738
- modelSupported: fastOverlay.supportsModel(ctx.model ?? undefined),
739
- });
740
- ctx.ui.notify(notice.message, notice.level);
741
- return true;
798
+ if (isFastToggle(text)) {
799
+ const notice = fastToggleNotice({
800
+ scope: "session",
801
+ enabled: fastOverlay.toggleSession(),
802
+ otherEnabled: fastOverlay.isGlobalEnabled(),
803
+ modelSupported: fastOverlay.supportsModel(ctx.model ?? undefined),
804
+ });
805
+ ctx.ui.notify(notice.message, notice.level);
806
+ return true;
807
+ }
808
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Model thinking argument]]
809
+ return applyModelThinking(ctx, text);
742
810
  },
743
811
  );
744
812
  installModelAutocompleteSubmit(editor, keybindings);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Baseline Pi behavior for session naming, history, prompt editing, fullscreen navigation, and footer styling",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -53,8 +53,9 @@
53
53
  "@earendil-works/pi-tui": "*"
54
54
  },
55
55
  "devDependencies": {
56
- "@earendil-works/pi-coding-agent": "0.84.4",
57
- "@earendil-works/pi-tui": "0.84.4",
56
+ "@earendil-works/pi-coding-agent": "0.85.0",
57
+ "@earendil-works/pi-server": "0.85.0",
58
+ "@earendil-works/pi-tui": "0.85.0",
58
59
  "@types/node": "25.9.5",
59
60
  "typescript": "6.0.2"
60
61
  },
@@ -1,5 +1,7 @@
1
1
  import {
2
+ type AutocompleteItem,
2
3
  type AutocompleteProvider,
4
+ type AutocompleteSuggestions,
3
5
  type Component,
4
6
  type OverlayHandle,
5
7
  type OverlayMargin,
@@ -29,6 +31,67 @@ const MODEL_ORDER = new Intl.Collator("en", {
29
31
  sensitivity: "base",
30
32
  });
31
33
 
34
+ /**
35
+ * Pi's thinking levels, weakest first. The extension API exports neither the
36
+ * list nor the per-model subset, and Pi clamps an unsupported level when it
37
+ * applies one, so restating the full list here costs nothing.
38
+ */
39
+ const THINKING_LEVELS = [
40
+ "off",
41
+ "minimal",
42
+ "low",
43
+ "medium",
44
+ "high",
45
+ "xhigh",
46
+ "max",
47
+ ] as const;
48
+
49
+ export type ThinkingArgument = (typeof THINKING_LEVELS)[number];
50
+
51
+ /**
52
+ * `/model <provider>/<id> <level>` before the cursor.
53
+ *
54
+ * The first argument must carry a provider slash, the exact shape a model
55
+ * completion produces, so a multi-term model search such as `/model opus 4`
56
+ * keeps filtering models instead of being read as a level.
57
+ */
58
+ const MODEL_THINKING_ARGUMENT = /^\/model\s+(\S*\/\S*)\s+(\S*)$/;
59
+
60
+ /** Level suggestions for a second `/model` argument, or nothing for any other shape. */
61
+ function thinkingSuggestions(
62
+ activeLine: string,
63
+ current: string | undefined,
64
+ ): AutocompleteSuggestions | undefined {
65
+ const prefix = MODEL_THINKING_ARGUMENT.exec(activeLine)?.[2];
66
+ if (prefix === undefined) return undefined;
67
+ const query = prefix.toLowerCase();
68
+ const matches = THINKING_LEVELS.filter((level) => level.startsWith(query));
69
+ // The level already in effect leads the list, so accepting the menu's
70
+ // default selection keeps the current level instead of the weakest one.
71
+ const items: AutocompleteItem[] = [
72
+ ...matches.filter((level) => level === current),
73
+ ...matches.filter((level) => level !== current),
74
+ ].map((level) => ({ value: level, label: level }));
75
+ return items.length > 0 ? { items, prefix } : undefined;
76
+ }
77
+
78
+ /**
79
+ * A submitted `/model <reference> <level>`, if that is the shape.
80
+ *
81
+ * Pi's own `/model` treats everything after the command as one model search
82
+ * term, so the extra argument has to be split off before Pi ever sees it.
83
+ */
84
+ export function modelThinkingCommand(
85
+ text: string,
86
+ ): { reference: string; level: ThinkingArgument } | undefined {
87
+ const match = /^\/model\s+(\S+)\s+(\S+)$/.exec(text.trim());
88
+ const reference = match?.[1];
89
+ const level = THINKING_LEVELS.find(
90
+ (candidate) => candidate === match?.[2]?.toLowerCase(),
91
+ );
92
+ return reference && level ? { reference, level } : undefined;
93
+ }
94
+
32
95
  type AutocompleteEditor = Component & {
33
96
  autocompleteList?: {
34
97
  getSelectedItem(): { description?: string } | null;
@@ -55,7 +118,7 @@ type ModelAutocompleteEditor = Component & {
55
118
  };
56
119
  getText?(): string;
57
120
  handleInput?(data: string): void;
58
- submitValue?(): void;
121
+ tryTriggerAutocomplete?(): void;
59
122
  [MODEL_SUBMIT_INSTALLED]?: boolean;
60
123
  };
61
124
 
@@ -201,6 +264,7 @@ function createAutocompleteDetailBox(theme: DetailTheme) {
201
264
 
202
265
  export function sortModelAutocompleteDescending(
203
266
  current: AutocompleteProvider,
267
+ thinkingLevel?: () => string | undefined,
204
268
  ): AutocompleteProvider {
205
269
  return {
206
270
  ...(current.triggerCharacters
@@ -208,6 +272,13 @@ export function sortModelAutocompleteDescending(
208
272
  : {}),
209
273
  async getSuggestions(lines, cursorLine, cursorCol, options) {
210
274
  const inline = inlineSlashContext(lines, cursorLine, cursorCol);
275
+ const activeLine =
276
+ inline?.prefix ?? (lines[cursorLine] ?? "").slice(0, cursorCol);
277
+ // Checked before delegating so an explicit Tab, which asks Pi for
278
+ // forced file completion once the argument holds a space, still lists
279
+ // levels rather than paths.
280
+ const thinking = thinkingSuggestions(activeLine, thinkingLevel?.());
281
+ if (thinking) return thinking;
211
282
  const requestLines = inline ? [...lines] : lines;
212
283
  if (inline) requestLines[cursorLine] = inline.prefix;
213
284
  const suggestions = await current.getSuggestions(
@@ -216,8 +287,6 @@ export function sortModelAutocompleteDescending(
216
287
  inline ? inline.prefix.length : cursorCol,
217
288
  inline ? { ...options, force: false } : options,
218
289
  );
219
- const line = lines[cursorLine] ?? "";
220
- const activeLine = inline?.prefix ?? line.slice(0, cursorCol);
221
290
  if (!suggestions || !activeLine.startsWith("/model ")) {
222
291
  return suggestions;
223
292
  }
@@ -285,6 +354,13 @@ export function sortModelAutocompleteDescending(
285
354
  };
286
355
  }
287
356
 
357
+ /** Whether an accepted completion left a runnable `/model` command behind. */
358
+ function completedModelCommand(text: string, value: string): boolean {
359
+ if (!/^\/model [^\n]*$/.test(text)) return false;
360
+ const argument = text.slice("/model ".length);
361
+ return argument === value || argument.endsWith(` ${value}`);
362
+ }
363
+
288
364
  export function installModelAutocompleteSubmit(
289
365
  editor: Component,
290
366
  keybindings: EditorKeybindings,
@@ -299,28 +375,47 @@ export function installModelAutocompleteSubmit(
299
375
  }
300
376
 
301
377
  const handleInput = target.handleInput.bind(target);
378
+ const openThinkingMenu = () => {
379
+ if (
380
+ target.autocompleteList === undefined &&
381
+ MODEL_THINKING_ARGUMENT.test(target.getText?.() ?? "")
382
+ ) {
383
+ target.tryTriggerAutocomplete?.();
384
+ }
385
+ };
302
386
  target.handleInput = (data: string) => {
303
- const selected = target.autocompleteList?.getSelectedItem();
304
- const selectedValue = selected?.value;
387
+ const selectedValue = target.autocompleteList?.getSelectedItem()?.value;
388
+ const accepted =
389
+ typeof selectedValue === "string" &&
390
+ /^\/model [^\n]*$/.test(target.getText?.() ?? "")
391
+ ? selectedValue
392
+ : undefined;
305
393
  const confirm = keybindings.matches(data, "tui.select.confirm");
306
394
  const tab = keybindings.matches(data, "tui.input.tab");
307
- const shouldSubmit =
308
- (confirm || tab) &&
309
- typeof selectedValue === "string" &&
310
- /^\/model [^\n]*$/.test(target.getText?.() ?? "");
311
395
 
312
396
  handleInput(data);
397
+ // Pi reopens suggestions only from typed characters, and the separator
398
+ // before a thinking level is a space, which is not one of them.
399
+ if (data === " ") {
400
+ openThinkingMenu();
401
+ return;
402
+ }
313
403
  if (
314
- shouldSubmit &&
315
- target.autocompleteList === undefined &&
316
- target.getText?.() === `/model ${selectedValue}`
404
+ accepted === undefined ||
405
+ target.autocompleteList !== undefined ||
406
+ !completedModelCommand(target.getText?.() ?? "", accepted)
317
407
  ) {
318
- if (tab) {
319
- if (target.submitValue) target.submitValue();
320
- else handleInput("\r");
321
- } else {
322
- handleInput(data);
323
- }
408
+ return;
409
+ }
410
+ // Tab stops at the model name so a level can follow, and Pi's argument
411
+ // completion appends no separator, so the space and the menu it cannot
412
+ // trigger on its own are supplied here. Tab on the level itself has
413
+ // nothing left to complete, so it submits like Enter.
414
+ if (tab && accepted.includes("/")) {
415
+ handleInput(" ");
416
+ openThinkingMenu();
417
+ } else if (confirm || tab) {
418
+ handleInput("\r");
324
419
  }
325
420
  };
326
421
  target[MODEL_SUBMIT_INSTALLED] = true;
@@ -0,0 +1,69 @@
1
+ import type {
2
+ Component,
3
+ TuiMouseEvent,
4
+ TuiMouseEventResult,
5
+ } from "@earendil-works/pi-tui";
6
+
7
+ const INSTALLED = Symbol.for("pi-proper-base.editor-mouse");
8
+
9
+ type MouseHandler = (event: TuiMouseEvent) => TuiMouseEventResult | undefined;
10
+ type MouseEditor = Component & {
11
+ handleMouse?: MouseHandler;
12
+ renderedVisibleLineCount?: number;
13
+ [INSTALLED]?: () => void;
14
+ };
15
+
16
+ /**
17
+ * Keep prompt clicks from moving the editor cursor while the setting is off.
18
+ *
19
+ * Since Pi 0.85.0 the fullscreen renderer routes mouse input through
20
+ * component `handleMouse` methods, and the editor's own handler turns a left
21
+ * click on a prompt row into a cursor move. That is the wrong default for
22
+ * anyone who clicks the prompt area to focus the terminal or to select text:
23
+ * the cursor jumps away from where typing left it. This wraps the editor
24
+ * instance's `handleMouse` and, while `enabled()` is false, swallows left
25
+ * clicks that land on the prompt's text rows. The event is still reported
26
+ * handled so the click neither falls through to the renderer's selection
27
+ * path nor moves focus, and the drag-to-select gesture is untouched because
28
+ * the editor already leaves press, drag, and release to the renderer.
29
+ *
30
+ * Clicks on the autocomplete rows below the prompt, and on the border rows,
31
+ * keep Pi's native behavior: the guard only covers the text rows Pi itself
32
+ * bounds with `renderedVisibleLineCount`. Editors without a `handleMouse`
33
+ * (Pi before 0.85.0, or a renderer without mouse dispatch) install nothing.
34
+ *
35
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt mouse clicks]]
36
+ */
37
+ export function installEditorMouseGuard(
38
+ editor: Component,
39
+ enabled: () => boolean,
40
+ ): (() => void) | undefined {
41
+ const target = editor as MouseEditor;
42
+ target[INSTALLED]?.();
43
+ if (typeof target.handleMouse !== "function") return undefined;
44
+
45
+ const hadOwnMethod = Object.hasOwn(target, "handleMouse");
46
+ const original = target.handleMouse;
47
+ const wrapped: MouseHandler = function (this: MouseEditor, event) {
48
+ if (
49
+ !enabled() &&
50
+ event.type === "click" &&
51
+ event.button === "left" &&
52
+ event.y > 0 &&
53
+ event.y <= (target.renderedVisibleLineCount ?? 0)
54
+ ) {
55
+ return { handled: true };
56
+ }
57
+ return original.call(this, event);
58
+ };
59
+ target.handleMouse = wrapped;
60
+
61
+ const dispose = () => {
62
+ if (target.handleMouse !== wrapped) return;
63
+ if (hadOwnMethod) target.handleMouse = original;
64
+ else delete target.handleMouse;
65
+ delete target[INSTALLED];
66
+ };
67
+ target[INSTALLED] = dispose;
68
+ return dispose;
69
+ }
@@ -50,6 +50,7 @@ type NavigableEditor = Component & {
50
50
  isShowingAutocomplete?(): boolean;
51
51
  onChange?(text: string): void;
52
52
  setText?(text: string): void;
53
+ historyIndex?: number;
53
54
  state?: {
54
55
  lines: string[];
55
56
  cursorLine: number;
@@ -226,6 +227,25 @@ export function installEditorNavigation(
226
227
  }
227
228
  }
228
229
  if (previous) {
230
+ // Pi recalls history on Up from the first visual row whenever the
231
+ // cursor sits at column 0, so Home followed by Up, or Up pressed
232
+ // twice from a short first line, replaces a draft with an older
233
+ // prompt. Recall is only for an empty prompt: with a draft and no
234
+ // recall in progress, Up at that position is already at the line
235
+ // start Pi would otherwise jump to, so it does nothing. The dedicated
236
+ // history binding is left alone; it is opt-in and explicit.
237
+ if (
238
+ keybindings.matches(data, "tui.editor.cursorUp") &&
239
+ (target.historyIndex ?? -1) < 0 &&
240
+ target.getCursor?.().col === 0 &&
241
+ target.getLines?.().some((line) => line !== "")
242
+ ) {
243
+ const visualLines = target.buildVisualLineMap?.(target.lastWidth ?? 80);
244
+ const visualIndex = visualLines
245
+ ? target.findCurrentVisualLine?.(visualLines)
246
+ : undefined;
247
+ if (visualIndex === 0) return;
248
+ }
229
249
  const before = target.getLines?.().join("\n");
230
250
  handleInput(data);
231
251
  const state = target.state;
@@ -3,8 +3,28 @@ import { join } from "node:path";
3
3
 
4
4
  import type { Component, TUI } from "@earendil-works/pi-tui";
5
5
 
6
+ // Keyed by its original name: a /reload of a build that still runs the
7
+ // rail-only module must find and hand over the wrapper it installed.
6
8
  const INSTALLED = Symbol.for("pi-proper-base.rail-setting");
7
- const ITEM_ID = "proper-base-session-rail";
9
+
10
+ /** Each toggle proper-base splices into Pi's `/settings` menu. */
11
+ const TOGGLES = [
12
+ {
13
+ id: "proper-base-session-rail",
14
+ key: "sessionRail",
15
+ label: "Session action rail",
16
+ description:
17
+ "proper-base: colored per-action jump symbols along the transcript's right edge",
18
+ },
19
+ {
20
+ id: "proper-base-editor-mouse",
21
+ key: "editorMouse",
22
+ label: "Prompt mouse clicks",
23
+ description:
24
+ "proper-base: clicking the prompt moves the cursor; off leaves the cursor where typing put it",
25
+ },
26
+ ] as const;
27
+ type ToggleKey = (typeof TOGGLES)[number]["key"];
8
28
 
9
29
  type SettingItem = {
10
30
  id: string;
@@ -26,9 +46,11 @@ type ComponentContainer = Component & {
26
46
  };
27
47
  type InstalledContainer = ComponentContainer & { [INSTALLED]?: () => void };
28
48
 
29
- export type RailSettingController = {
49
+ export type SettingsController = {
30
50
  /** Whether the session action rail is enabled. Cached per session. */
31
51
  enabled(): boolean;
52
+ /** Whether prompt clicks may move the editor cursor. Cached per session. */
53
+ editorMouse(): boolean;
32
54
  dispose(): void;
33
55
  };
34
56
 
@@ -36,20 +58,28 @@ function configPath(agentDir: string): string {
36
58
  return join(agentDir, "proper-base.json");
37
59
  }
38
60
 
39
- export function readRailEnabled(agentDir: string): boolean {
61
+ function readToggle(agentDir: string, key: ToggleKey): boolean {
40
62
  try {
41
63
  const parsed = JSON.parse(
42
64
  readFileSync(configPath(agentDir), "utf8"),
43
65
  ) as unknown;
44
- return (parsed as { sessionRail?: unknown } | null)?.sessionRail !== false;
66
+ return (parsed as Record<string, unknown> | null)?.[key] !== false;
45
67
  } catch {
46
68
  return true;
47
69
  }
48
70
  }
49
71
 
72
+ export function readRailEnabled(agentDir: string): boolean {
73
+ return readToggle(agentDir, "sessionRail");
74
+ }
75
+
76
+ export function readEditorMouseEnabled(agentDir: string): boolean {
77
+ return readToggle(agentDir, "editorMouse");
78
+ }
79
+
50
80
  /** Fail-open like the history store: a read-only agent dir only costs
51
81
  * persistence, never the session. Other keys in the file are preserved. */
52
- function writeRailEnabled(agentDir: string, enabled: boolean): void {
82
+ function writeToggle(agentDir: string, key: ToggleKey, enabled: boolean): void {
53
83
  try {
54
84
  let parsed: Record<string, unknown> = {};
55
85
  try {
@@ -62,7 +92,7 @@ function writeRailEnabled(agentDir: string, enabled: boolean): void {
62
92
  } catch {
63
93
  // Damaged or absent config starts fresh.
64
94
  }
65
- parsed.sessionRail = enabled;
95
+ parsed[key] = enabled;
66
96
  writeFileSync(
67
97
  configPath(agentDir),
68
98
  `${JSON.stringify(parsed, null, "\t")}\n`,
@@ -109,27 +139,33 @@ function findEditorContainer(
109
139
  }
110
140
 
111
141
  /**
112
- * Add a "Session action rail" toggle to Pi's native `/settings` menu.
142
+ * Add proper-base's toggles to Pi's native `/settings` menu: the session
143
+ * action rail and prompt mouse clicks.
113
144
  *
114
145
  * Pi has no extension hook into that menu, so this is a guarded
115
146
  * compatibility layer in the house style: the container Pi mounts selectors
116
147
  * into is the editor's own parent, its `addChild` is wrapped once, and every
117
- * settings selector that mounts receives one extra item spliced into its
148
+ * settings selector that mounts receives the extra items spliced into its
118
149
  * `SettingsList`, whose instance-held `onChange` is wrapped to keep the
119
- * toggle out of Pi's own switch. A renamed component or list shape installs
120
- * or injects nothing and the rail simply stays enabled.
150
+ * toggles out of Pi's own switch. A renamed component or list shape installs
151
+ * or injects nothing and both features simply stay enabled.
121
152
  *
122
- * The choice persists as `sessionRail` in the agent directory's
123
- * `proper-base.json`; other sessions pick a change up at their next start.
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.
124
156
  *
125
157
  * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Session action rail]]
158
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt mouse clicks]]
126
159
  */
127
- export function installRailSetting(
160
+ export function installSettings(
128
161
  tui: TUI,
129
162
  editor: Component,
130
163
  agentDir: string,
131
- ): RailSettingController {
132
- let enabled = readRailEnabled(agentDir);
164
+ ): SettingsController {
165
+ const state: Record<ToggleKey, boolean> = {
166
+ sessionRail: readToggle(agentDir, "sessionRail"),
167
+ editorMouse: readToggle(agentDir, "editorMouse"),
168
+ };
133
169
  let disposed = false;
134
170
  let uninstall: (() => void) | undefined;
135
171
 
@@ -138,20 +174,22 @@ export function installRailSetting(
138
174
  const items = list?.items;
139
175
  if (!list || !Array.isArray(items) || typeof list.onChange !== "function")
140
176
  return;
141
- if (items.some((item) => item?.id === ITEM_ID)) return;
142
- items.push({
143
- id: ITEM_ID,
144
- label: "Session action rail",
145
- description:
146
- "proper-base: colored per-action jump symbols along the transcript's right edge",
147
- currentValue: enabled ? "true" : "false",
148
- values: ["true", "false"],
149
- });
177
+ if (items.some((item) => item?.id === TOGGLES[0].id)) return;
178
+ for (const toggle of TOGGLES) {
179
+ items.push({
180
+ id: toggle.id,
181
+ label: toggle.label,
182
+ description: toggle.description,
183
+ currentValue: state[toggle.key] ? "true" : "false",
184
+ values: ["true", "false"],
185
+ });
186
+ }
150
187
  const native = list.onChange;
151
188
  list.onChange = (id, value) => {
152
- if (id === ITEM_ID) {
153
- enabled = value === "true";
154
- writeRailEnabled(agentDir, enabled);
189
+ const toggle = TOGGLES.find((entry) => entry.id === id);
190
+ if (toggle) {
191
+ state[toggle.key] = value === "true";
192
+ writeToggle(agentDir, toggle.key, state[toggle.key]);
155
193
  return;
156
194
  }
157
195
  native(id, value);
@@ -190,7 +228,8 @@ export function installRailSetting(
190
228
  queueMicrotask(wrap);
191
229
 
192
230
  return {
193
- enabled: () => enabled,
231
+ enabled: () => state.sessionRail,
232
+ editorMouse: () => state.editorMouse,
194
233
  dispose() {
195
234
  disposed = true;
196
235
  uninstall?.();
@@ -0,0 +1,143 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ const SETTINGS_FILE_NAME = "settings.json";
5
+ 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
+
16
+ type JsonObject = Record<string, unknown>;
17
+
18
+ function readJsonObject(path: string): JsonObject | undefined {
19
+ try {
20
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
21
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
22
+ ? (parsed as JsonObject)
23
+ : undefined;
24
+ } catch {
25
+ return undefined;
26
+ }
27
+ }
28
+
29
+ /** Whether the session's model and effort follow into Pi's startup defaults. */
30
+ export function stickyDefaultsEnabled(agentDir: string): boolean {
31
+ return (
32
+ readJsonObject(join(agentDir, CONFIG_FILE_NAME))?.stickyDefaults !== false
33
+ );
34
+ }
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
+ }
@@ -533,7 +533,8 @@ function hasSectionText(lines: string[]): boolean {
533
533
  const text = stripTerminalSequences(line).trim();
534
534
  return (
535
535
  text.length > 0 &&
536
- !/(?:^|\s)Working(?:\.\.\.|…)(?:\s+\([^)]*\))?$/.test(text)
536
+ // Pi 0.85.0 dropped the ellipsis from its default working label.
537
+ !/(?:^|\s)Working(?:\.\.\.|…)?(?:\s+\([^)]*\))?$/.test(text)
537
538
  );
538
539
  });
539
540
  }