proper-base 0.5.0 → 0.6.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,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
  }
@@ -6,6 +6,10 @@
6
6
  * pi's normal retry budget/backoff apply. Same mechanism the provider
7
7
  * package uses for its own transient patterns; message_end transforms
8
8
  * chain, so both normalizers compose.
9
+ *
10
+ * GPT-6 Astra also returns `server_overloaded` as "Selected model is at
11
+ * capacity. Please try a different model.", which pi-ai's `overloaded`
12
+ * pattern does not match; it gets the same prefix.
9
13
  */
10
14
 
11
15
  /** Structural subset of pi-ai's AssistantMessage used by the normalizer. */
@@ -16,7 +20,7 @@ export interface ErroredMessage {
16
20
  }
17
21
 
18
22
  const CPA_TRANSIENT_ERROR_PATTERN =
19
- /\bempty_stream\b|\bupstream stream closed before first payload\b/i;
23
+ /\bempty_stream\b|\bupstream stream closed before first payload\b|\bat capacity\b/i;
20
24
  const NETWORK_ERROR_PREFIX = "network error:";
21
25
 
22
26
  /** Return a retryable copy of a CPA transient stream error, or the
@@ -0,0 +1,120 @@
1
+ import type { Component, TUI } from "@earendil-works/pi-tui";
2
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
3
+
4
+ const INSTALLED = Symbol.for("pi-proper-base.widget-transcript");
5
+
6
+ type ComponentContainer = Component & {
7
+ children: Component[];
8
+ addChild(component: Component): void;
9
+ removeChild(component: Component): void;
10
+ };
11
+ type InstalledContainer = ComponentContainer & { [INSTALLED]?: () => void };
12
+
13
+ /**
14
+ * Move above-editor extension widgets into the fullscreen transcript.
15
+ *
16
+ * Pi pins `setWidget` output in a dock between the transcript and the prompt,
17
+ * so a widget neither scrolls with the session nor gives rows back when its
18
+ * content shrinks; pi-subagents in particular locks a row budget on first
19
+ * overflow and pads with blank lines afterwards. The dock container keeps
20
+ * rendering its one-row spacer while a mirror appended to the document draws
21
+ * the widgets, minus trailing blank rows, as the transcript's live tail.
22
+ *
23
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Transcript widgets]]
24
+ */
25
+ export function installWidgetTranscript(
26
+ tui: TUI,
27
+ editor: Component,
28
+ ): () => void {
29
+ let restore: (() => void) | undefined;
30
+ let disposed = false;
31
+ const wrap = () => {
32
+ if (disposed) return;
33
+ const root = (tui as TUI & { layoutRoot?: Component }).layoutRoot;
34
+ if (!root) return;
35
+ const document = find(root, isDocument) as ComponentContainer | undefined;
36
+ const editorContainer = find(root, (component) =>
37
+ childrenOf(component).includes(editor),
38
+ );
39
+ const dock = editorContainer
40
+ ? find(root, (component) =>
41
+ childrenOf(component).includes(editorContainer),
42
+ )
43
+ : undefined;
44
+ const siblings = dock ? childrenOf(dock) : [];
45
+ const widgets = editorContainer
46
+ ? (siblings[siblings.indexOf(editorContainer) - 1] as
47
+ | InstalledContainer
48
+ | undefined)
49
+ : undefined;
50
+ if (!document || !widgets || componentName(widgets) !== "Container") {
51
+ return;
52
+ }
53
+ // A reload runs the new factory before the outgoing instance shuts
54
+ // down; take over any wrapper it left.
55
+ widgets[INSTALLED]?.();
56
+
57
+ const render = widgets.render;
58
+ const mirror: Component = {
59
+ render(width) {
60
+ const lines = widgets.children
61
+ .filter((child) => componentName(child) !== "Spacer")
62
+ .flatMap((child) => child.render(width));
63
+ while (
64
+ lines.length &&
65
+ !stripTerminalSequences(lines.at(-1) ?? "").trim()
66
+ ) {
67
+ lines.pop();
68
+ }
69
+ return lines.length ? ["", ...lines] : [];
70
+ },
71
+ invalidate() {},
72
+ };
73
+ // Pi's dock always holds one spacer row here, with or without widgets.
74
+ const gap = () => [""];
75
+ widgets.render = gap;
76
+ document.addChild(mirror);
77
+ restore = () => {
78
+ if (widgets.render === gap) widgets.render = render;
79
+ document.removeChild(mirror);
80
+ delete widgets[INSTALLED];
81
+ restore = undefined;
82
+ };
83
+ widgets[INSTALLED] = restore;
84
+ };
85
+ // The editor mounts into its container right after the factory returns,
86
+ // so the parent walk has to wait a tick.
87
+ queueMicrotask(wrap);
88
+ return () => {
89
+ disposed = true;
90
+ restore?.();
91
+ };
92
+ }
93
+
94
+ function isDocument(component: Component): boolean {
95
+ const children = childrenOf(component);
96
+ return (
97
+ children.length >= 3 &&
98
+ children.slice(0, 3).every((child) => componentName(child) === "Container")
99
+ );
100
+ }
101
+
102
+ function find(
103
+ root: Component,
104
+ matches: (component: Component) => boolean,
105
+ ): Component | undefined {
106
+ if (matches(root)) return root;
107
+ for (const child of childrenOf(root)) {
108
+ const found = find(child, matches);
109
+ if (found) return found;
110
+ }
111
+ return undefined;
112
+ }
113
+
114
+ function childrenOf(component: Component): Component[] {
115
+ return (component as Partial<ComponentContainer>).children ?? [];
116
+ }
117
+
118
+ function componentName(component: Component): string | undefined {
119
+ return (component as { constructor?: { name?: string } }).constructor?.name;
120
+ }