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.
@@ -0,0 +1,196 @@
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
+ restore(): void;
43
+ };
44
+
45
+ /**
46
+ * Bridge Pi 0.85.1's missing ExtensionAPI persistence option to the live
47
+ * AgentSession. Remove this adapter once ExtensionAPI forwards `{ persist }`.
48
+ */
49
+ export function installStickyDefaultsAdapter(
50
+ enabled: () => boolean = () => stickyDefaultsEnabled(),
51
+ ): StickyDefaultsController {
52
+ const prototype = AgentSession.prototype as unknown as SessionPrototype;
53
+ prototype[INSTALLED]?.restore();
54
+
55
+ const originalBuildRuntime = prototype._buildRuntime;
56
+ const originalSetModel = prototype.setModel;
57
+ const originalCycleModel = prototype.cycleModel;
58
+ const originalSetThinkingLevel = prototype.setThinkingLevel;
59
+ if (
60
+ typeof originalBuildRuntime !== "function" ||
61
+ typeof originalSetModel !== "function" ||
62
+ typeof originalCycleModel !== "function" ||
63
+ typeof originalSetThinkingLevel !== "function"
64
+ ) {
65
+ return { activate() {}, restore() {} };
66
+ }
67
+ let installed = true;
68
+ const sessions = new WeakMap<SessionIdentity, LiveSession>();
69
+ const active = new WeakSet<LiveSession>();
70
+ const modelMutationDepth = new WeakMap<LiveSession, number>();
71
+
72
+ const shouldPersist = (session: LiveSession): boolean =>
73
+ installed && active.has(session) && enabled();
74
+ const beginModelMutation = (session: LiveSession) => {
75
+ modelMutationDepth.set(session, (modelMutationDepth.get(session) ?? 0) + 1);
76
+ };
77
+ const endModelMutation = (session: LiveSession) => {
78
+ modelMutationDepth.set(
79
+ session,
80
+ Math.max(0, (modelMutationDepth.get(session) ?? 1) - 1),
81
+ );
82
+ };
83
+ const persistModel = (session: LiveSession, model: Model | undefined) => {
84
+ if (
85
+ !shouldPersist(session) ||
86
+ !model ||
87
+ model.provider === PLACEHOLDER_PROVIDER
88
+ )
89
+ return;
90
+ const settings = session.settingsManager;
91
+ if (
92
+ settings.getDefaultProvider() === model.provider &&
93
+ settings.getDefaultModel() === model.id
94
+ )
95
+ return;
96
+ settings.setDefaultModelAndProvider(model.provider, model.id);
97
+ };
98
+
99
+ function buildRuntime(this: LiveSession, options: unknown): void {
100
+ originalBuildRuntime.call(this as never, options);
101
+ if (installed) sessions.set(this.sessionManager, this);
102
+ }
103
+ async function setModel(
104
+ this: LiveSession,
105
+ model: Model,
106
+ options: MutationOptions = {},
107
+ ): Promise<void> {
108
+ if (!shouldPersist(this))
109
+ return originalSetModel.call(this as never, model, options);
110
+ beginModelMutation(this);
111
+ try {
112
+ await originalSetModel.call(this as never, model, {
113
+ ...options,
114
+ persist: false,
115
+ });
116
+ } finally {
117
+ endModelMutation(this);
118
+ }
119
+ persistModel(this, this.model);
120
+ }
121
+ async function cycleModel(
122
+ this: LiveSession,
123
+ direction: "forward" | "backward" = "forward",
124
+ options: MutationOptions = {},
125
+ ): Promise<CycleResult> {
126
+ if (!shouldPersist(this))
127
+ return originalCycleModel.call(this as never, direction, options);
128
+ beginModelMutation(this);
129
+ let result: CycleResult;
130
+ try {
131
+ result = await originalCycleModel.call(this as never, direction, {
132
+ ...options,
133
+ persist: false,
134
+ });
135
+ } finally {
136
+ endModelMutation(this);
137
+ }
138
+ if (result) persistModel(this, result.model);
139
+ return result;
140
+ }
141
+ function setThinkingLevel(
142
+ this: LiveSession,
143
+ level: ThinkingLevel,
144
+ options: MutationOptions = {},
145
+ ): void {
146
+ if (!shouldPersist(this)) {
147
+ originalSetThinkingLevel.call(this as never, level, options);
148
+ return;
149
+ }
150
+ originalSetThinkingLevel.call(this as never, level, {
151
+ ...options,
152
+ persist: false,
153
+ });
154
+ if (
155
+ (modelMutationDepth.get(this) ?? 0) > 0 ||
156
+ this.model?.provider === PLACEHOLDER_PROVIDER
157
+ )
158
+ return;
159
+ const effective = this.thinkingLevel;
160
+ const settings = this.settingsManager;
161
+ if (
162
+ this.model &&
163
+ settings.getModelThinkingLevel(this.model.provider, this.model.id) ===
164
+ effective
165
+ )
166
+ return;
167
+ if (settings.getDefaultThinkingLevel() !== effective)
168
+ settings.setDefaultThinkingLevel(effective);
169
+ }
170
+
171
+ const controller: StickyDefaultsController = {
172
+ activate(sessionManager) {
173
+ const session = sessions.get(sessionManager);
174
+ if (session) active.add(session);
175
+ },
176
+ restore() {
177
+ installed = false;
178
+ if (prototype[INSTALLED] !== controller) return;
179
+ if (prototype._buildRuntime === buildRuntime)
180
+ prototype._buildRuntime = originalBuildRuntime;
181
+ if (prototype.setModel === setModel)
182
+ prototype.setModel = originalSetModel;
183
+ if (prototype.cycleModel === cycleModel)
184
+ prototype.cycleModel = originalCycleModel;
185
+ if (prototype.setThinkingLevel === setThinkingLevel)
186
+ prototype.setThinkingLevel = originalSetThinkingLevel;
187
+ delete prototype[INSTALLED];
188
+ },
189
+ };
190
+ prototype._buildRuntime = buildRuntime;
191
+ prototype.setModel = setModel;
192
+ prototype.cycleModel = cycleModel;
193
+ prototype.setThinkingLevel = setThinkingLevel;
194
+ prototype[INSTALLED] = controller;
195
+ return controller;
196
+ }
@@ -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
@@ -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
  }
@@ -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
+ }