proper-base 0.5.1 → 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.
package/README.md CHANGED
@@ -116,12 +116,20 @@ pinned while Pi scrolls the transcript above them.
116
116
  | Home, End, PageUp, PageDown | Stay assigned to the prompt editor. |
117
117
  | Ctrl+Shift+Home or End | Jump the transcript to its top or bottom. |
118
118
  | Ctrl+Shift+PageUp or PageDown | Scroll the transcript by one page. |
119
+
120
+ Wheel and transcript scroll keys keep working while an `ask_user_question`
121
+ questionnaire or other overlay has focus, so earlier context stays reachable.
119
122
  | Double-click | Select a complete one-line URL, path, flag, qualified identifier, or quoted value when possible. |
120
123
 
121
124
  Scrolling away from current output adds a `↓ jump to bottom` row above the
122
125
  prompt. Clicking it returns to the newest output without disabling scrollbar
123
126
  dragging.
124
127
 
128
+ Extension widgets that Pi would pin above the prompt (for example the
129
+ pi-subagents async-agents card) render at the end of the transcript instead, so
130
+ they scroll with the session and shrink as their content does rather than
131
+ holding rows they no longer need.
132
+
125
133
  The transcript's top-right corner carries muted `↑` and `↓` arrows that walk
126
134
  the viewport between your own prompts. Clicking `↓` past the last prompt scrolls
127
135
  to the bottom. While you are scrolled up, a dimmer `position/total` reading sits
@@ -184,7 +192,7 @@ highlight. Custom replacement footers are not changed.
184
192
 
185
193
  ## Install
186
194
 
187
- Node 22.19 or newer is required. The package is tested against Pi 0.85.0.
195
+ Node 22.19 or newer is required. The package is tested against Pi 0.85.1.
188
196
 
189
197
  From npm:
190
198
 
package/index.ts CHANGED
@@ -56,6 +56,11 @@ import {
56
56
  } from "./src/image-preview.ts";
57
57
  import { installJumpToBottom } from "./src/jump-to-bottom.ts";
58
58
  import { installOsc8LinkIds } from "./src/osc8-link-ids.ts";
59
+ import { installOverlayScroll } from "./src/overlay-scroll.ts";
60
+ import {
61
+ applyProactiveDelegation,
62
+ readProactiveDelegationEnabled,
63
+ } from "./src/proactive-delegation.ts";
59
64
  import {
60
65
  createPromptDisplay,
61
66
  PROMPT_DISPLAY_ENTRY,
@@ -83,6 +88,7 @@ import {
83
88
  } from "./src/transcript-cleanup.ts";
84
89
  import { normalizeCpaTransientError } from "./src/transient-retry.ts";
85
90
  import { installWheelScrollLines } from "./src/wheel-scroll.ts";
91
+ import { installWidgetTranscript } from "./src/widget-transcript.ts";
86
92
 
87
93
  /** Prompts seeded into the editor. Older prompts past this point are dropped. */
88
94
  const MAX_ENTRIES = 200;
@@ -302,10 +308,12 @@ export default function (pi: ExtensionAPI) {
302
308
  let removePromptClear: (() => void) | undefined;
303
309
  let removeSmartSelection: (() => void) | undefined;
304
310
  let removeSelectionDismiss: (() => void) | undefined;
311
+ let removeOverlayScroll: (() => void) | undefined;
305
312
  let removeOsc8LinkIds: (() => void) | undefined;
306
313
  let imagePreview: ImagePreviewController | undefined;
307
314
  let removeTerminalInput: (() => void) | undefined;
308
315
  let transcriptCleanup: TranscriptCleanupController | undefined;
316
+ let removeWidgetTranscript: (() => void) | undefined;
309
317
  let activeEditor: PromptEditor | undefined;
310
318
  let activeTui: EditorTui | undefined;
311
319
  let submittedPrompt: string | undefined;
@@ -510,6 +518,19 @@ export default function (pi: ExtensionAPI) {
510
518
  if (messages !== event.messages) return { messages };
511
519
  });
512
520
 
521
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Proactive delegation]]
522
+ pi.on("before_agent_start", (event, ctx) => {
523
+ if (!readProactiveDelegationEnabled(getAgentDir())) return;
524
+ const tools =
525
+ event.systemPromptOptions?.selectedTools ?? pi.getActiveTools?.() ?? [];
526
+ const systemPrompt = applyProactiveDelegation(
527
+ event.systemPrompt,
528
+ tools.includes("subagent"),
529
+ ctx.scopedModels.map((scoped) => scoped.model),
530
+ );
531
+ if (systemPrompt !== undefined) return { systemPrompt };
532
+ });
533
+
513
534
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Automatic session title]]
514
535
  pi.on("before_agent_start", (event) => {
515
536
  if (!sessionTitlePending || pi.getSessionName?.()) {
@@ -638,12 +659,16 @@ export default function (pi: ExtensionAPI) {
638
659
  removeSmartSelection = undefined;
639
660
  removeSelectionDismiss?.();
640
661
  removeSelectionDismiss = undefined;
662
+ removeOverlayScroll?.();
663
+ removeOverlayScroll = undefined;
641
664
  removeOsc8LinkIds?.();
642
665
  removeOsc8LinkIds = undefined;
643
666
  imagePreview?.dispose();
644
667
  imagePreview = undefined;
645
668
  removeTerminalInput?.();
646
669
  removeTerminalInput = undefined;
670
+ removeWidgetTranscript?.();
671
+ removeWidgetTranscript = undefined;
647
672
  transcriptCleanup?.uninstall();
648
673
  transcriptCleanup = undefined;
649
674
  activeEditor = undefined;
@@ -746,6 +771,9 @@ export default function (pi: ExtensionAPI) {
746
771
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Settled transcript]]
747
772
  transcriptCleanup?.uninstall();
748
773
  transcriptCleanup = installTranscriptCleanup(tui, ctx);
774
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Transcript widgets]]
775
+ removeWidgetTranscript?.();
776
+ removeWidgetTranscript = installWidgetTranscript(tui, editor);
749
777
  removeSmartSelection?.();
750
778
  removeSmartSelection = installSmartSelection(tui);
751
779
  removeSelectionDismiss?.();
@@ -756,6 +784,9 @@ export default function (pi: ExtensionAPI) {
756
784
  .getKeys("app.message.copy")
757
785
  .some((key) => matchesKey(data, key)),
758
786
  );
787
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Overlay transcript scrolling]]
788
+ removeOverlayScroll?.();
789
+ removeOverlayScroll = installOverlayScroll(tui);
759
790
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Hyperlink identity]]
760
791
  removeOsc8LinkIds?.();
761
792
  removeOsc8LinkIds = installOsc8LinkIds(tui);
@@ -803,6 +834,7 @@ export default function (pi: ExtensionAPI) {
803
834
  modelSupported: fastOverlay.supportsModel(ctx.model ?? undefined),
804
835
  });
805
836
  ctx.ui.notify(notice.message, notice.level);
837
+ tui.requestRender();
806
838
  return true;
807
839
  }
808
840
  // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Model thinking argument]]
@@ -821,7 +853,9 @@ export default function (pi: ExtensionAPI) {
821
853
  );
822
854
  installAutocompleteDetails(editor, tui, theme);
823
855
  removeFooterColors?.();
824
- removeFooterColors = installFooterColors(tui, ctx);
856
+ removeFooterColors = installFooterColors(tui, ctx, () =>
857
+ fastOverlay.isEffectiveFor(ctx.model ?? undefined),
858
+ );
825
859
  for (const prompt of seeded) historyGuard?.add(prompt);
826
860
  return editor;
827
861
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proper-base",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
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,9 +53,8 @@
53
53
  "@earendil-works/pi-tui": "*"
54
54
  },
55
55
  "devDependencies": {
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",
56
+ "@earendil-works/pi-coding-agent": "0.85.1",
57
+ "@earendil-works/pi-tui": "0.85.1",
59
58
  "@types/node": "25.9.5",
60
59
  "typescript": "6.0.2"
61
60
  },
@@ -65,6 +64,6 @@
65
64
  ]
66
65
  },
67
66
  "dependencies": {
68
- "sharp": "0.35.3"
67
+ "sharp": "0.35.4"
69
68
  }
70
69
  }
package/src/fast-mode.ts CHANGED
@@ -153,6 +153,14 @@ export class FastOverlay {
153
153
  return this.modelsCache.ids.has(model.id);
154
154
  }
155
155
 
156
+ /** Whether requests for this model currently carry the priority tier. */
157
+ isEffectiveFor(model: FastModel | undefined): boolean {
158
+ return (
159
+ (this.sessionEnabled || this.isGlobalEnabled()) &&
160
+ this.supportsModel(model)
161
+ );
162
+ }
163
+
156
164
  /**
157
165
  * The replacement payload for pi's `before_provider_request`, or
158
166
  * `undefined` to keep it. Adds `service_tier` when Fast is on for a
@@ -166,11 +174,11 @@ export class FastOverlay {
166
174
  return undefined;
167
175
  }
168
176
  const record = payload as JsonObject;
169
- const effective = this.sessionEnabled || this.isGlobalEnabled();
170
- if (effective && this.supportsModel(model)) {
177
+ if (this.isEffectiveFor(model)) {
171
178
  if (record.service_tier === PRIORITY_TIER) return undefined;
172
179
  return { ...record, service_tier: PRIORITY_TIER };
173
180
  }
181
+ const effective = this.sessionEnabled || this.isGlobalEnabled();
174
182
  if (!effective && record.service_tier === PRIORITY_TIER) {
175
183
  const { service_tier: _dropped, ...rest } = record;
176
184
  return rest;
@@ -42,6 +42,7 @@ type FooterTheme = ExtensionContext["ui"]["theme"];
42
42
  type FooterState = {
43
43
  ctx: ExtensionContext;
44
44
  tui: TUI;
45
+ fast: (() => boolean) | undefined;
45
46
  };
46
47
  type FooterController = {
47
48
  update(state: FooterState): void;
@@ -63,17 +64,18 @@ type FooterColorState = {
63
64
  export function installFooterColors(
64
65
  tui: TUI,
65
66
  ctx: ExtensionContext,
67
+ fast?: () => boolean,
66
68
  ): (() => void) | undefined {
67
69
  const footer = findFooter(tui);
68
70
  if (!footer) return undefined;
69
71
 
70
72
  const existing = footer[INSTALLED];
71
73
  if (existing) {
72
- existing.update({ ctx, tui });
74
+ existing.update({ ctx, tui, fast });
73
75
  return existing.uninstall;
74
76
  }
75
77
 
76
- let state = { ctx, tui };
78
+ let state: FooterState = { ctx, tui, fast };
77
79
  let timer: ReturnType<typeof setInterval> | undefined;
78
80
  const ownsRender = Object.hasOwn(footer, "render");
79
81
  const render = footer.render;
@@ -114,17 +116,17 @@ export function installFooterColors(
114
116
  if (level === "max" || level === "ultra") startAnimation();
115
117
  else stopAnimation();
116
118
  const theme = state.ctx.ui.theme;
117
- return colorFooter(
118
- layoutFooter(render.call(footer, width), width, theme, (wide) =>
119
- render.call(footer, wide),
120
- ),
121
- {
122
- level,
123
- model: state.ctx.model?.id,
124
- now: Date.now(),
125
- theme,
126
- },
127
- );
119
+ const model = state.ctx.model?.id;
120
+ const base = (at: number) => {
121
+ const lines = render.call(footer, at);
122
+ return model && state.fast?.() ? tagFast(lines, at, model, theme) : lines;
123
+ };
124
+ return colorFooter(layoutFooter(base(width), width, theme, base), {
125
+ level,
126
+ model,
127
+ now: Date.now(),
128
+ theme,
129
+ });
128
130
  };
129
131
  footer.dispose = () => {
130
132
  controller.uninstall();
@@ -134,6 +136,53 @@ export function installFooterColors(
134
136
  return controller.uninstall;
135
137
  }
136
138
 
139
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Fast tier scopes]]
140
+ /**
141
+ * Append the provider's `fast` chip when the session overlay makes Fast
142
+ * effective but the provider's own global flag is off. Pads are trimmed so
143
+ * the line keeps its width, matching how the provider's label would sit.
144
+ */
145
+ function tagFast(
146
+ lines: string[],
147
+ width: number,
148
+ model: string,
149
+ theme: FooterTheme,
150
+ ): string[] {
151
+ const index = lines.findIndex((line) =>
152
+ stripTerminalSequences(line).includes(model),
153
+ );
154
+ const line = lines[index];
155
+ if (line === undefined) return lines;
156
+ const plain = stripTerminalSequences(line);
157
+ if (/ • fast(?: • |$)/.test(plain)) return lines;
158
+
159
+ const tag = ` • ${theme.fg("warning", "fast")}`;
160
+ const tagWidth = 7;
161
+ const total = visibleWidth(line);
162
+ const pausedAt = plain.lastIndexOf(" • paused");
163
+ const cut = pausedAt >= 0 ? pausedAt : total;
164
+ let head = sliceByColumn(line, 0, cut, true);
165
+ const tail = sliceByColumn(line, cut, total - cut, true);
166
+ const gap = [...plain.slice(0, cut).matchAll(/ {2,}/g)].at(-1);
167
+ if (gap?.index !== undefined) {
168
+ const trim = Math.min(
169
+ gap[0].length - 2,
170
+ Math.max(0, total + tagWidth - width),
171
+ );
172
+ if (trim > 0) {
173
+ head = `${sliceByColumn(head, 0, gap.index, true)}${sliceByColumn(
174
+ head,
175
+ gap.index + trim,
176
+ cut - gap.index - trim,
177
+ true,
178
+ )}`;
179
+ }
180
+ }
181
+ const result = [...lines];
182
+ result[index] = `${head}${tag}${tail}`;
183
+ return result;
184
+ }
185
+
137
186
  function layoutFooter(
138
187
  lines: string[],
139
188
  width: number,
@@ -0,0 +1,130 @@
1
+ import {
2
+ getKeybindings,
3
+ isKeyRelease,
4
+ type TUI,
5
+ type TuiInputListener,
6
+ } from "@earendil-works/pi-tui";
7
+
8
+ const INSTALLED = Symbol.for("pi-proper-base.overlay-scroll");
9
+ // ESC prefix is matched separately: biome bans control characters in
10
+ // regexes, and string literals carry it fine.
11
+ const SGR_MOUSE_TAIL = /^\[<(\d+);(\d+);(\d+)[Mm]$/;
12
+ /** Mirrors pi-tui's private PAGE_SCROLL_OVERLAP. */
13
+ const PAGE_OVERLAP = 4;
14
+
15
+ /** Alternate-screen renderer surface, duck-typed since most of it is private. */
16
+ type ScrollHost = TUI & {
17
+ scrollBy(lines: number): void;
18
+ scrollToTop(): void;
19
+ scrollToBottom(): void;
20
+ isOverlayFocused?(): boolean;
21
+ getPrimaryScrollView?(): { viewportHeight: number };
22
+ routeWheel?(event: {
23
+ direction: number;
24
+ x: number;
25
+ y: number;
26
+ button: number;
27
+ }): void;
28
+ wheelScrollLines?: number;
29
+ [INSTALLED]?: () => void;
30
+ };
31
+
32
+ /** Same shape pi-tui's parseWheelEvent produces. */
33
+ export function parseWheel(data: string) {
34
+ if (!data.startsWith("\x1b")) return undefined;
35
+ const match = SGR_MOUSE_TAIL.exec(data.slice(1));
36
+ if (!match) return undefined;
37
+ const button = Number.parseInt(match[1] ?? "", 10);
38
+ if ((button & 64) === 0) return undefined;
39
+ const direction = button & 3;
40
+ if (direction !== 0 && direction !== 1) return undefined;
41
+ return {
42
+ direction: direction === 0 ? -1 : 1,
43
+ x: Number.parseInt(match[2] ?? "", 10) - 1,
44
+ y: Number.parseInt(match[3] ?? "", 10) - 1,
45
+ button,
46
+ };
47
+ }
48
+
49
+ /**
50
+ * Keep the fullscreen transcript scrollable while an overlay owns focus.
51
+ *
52
+ * Pi's viewport listener declines wheel events and every `tui.altScreen`
53
+ * scroll key as soon as a capturing overlay is focused, so an
54
+ * `ask_user_question` questionnaire freezes the transcript behind it. This
55
+ * listener registers after the renderer's own, so it only ever sees input the
56
+ * viewport (or an overlay's own mouse handler) already passed on, and routes
57
+ * that to the same scroll methods the renderer would have used. Keys are
58
+ * consumed so the overlay never receives a scroll chord; wheel events fall
59
+ * through untouched when no overlay is focused because the renderer already
60
+ * consumed them.
61
+ *
62
+ * Regular mode and renderer shapes without the scroll surface install
63
+ * nothing; a renamed private field only loses the wheel step or page size,
64
+ * not scrolling itself.
65
+ *
66
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Overlay transcript scrolling]]
67
+ */
68
+ export function installOverlayScroll(tui: TUI): (() => void) | undefined {
69
+ const host = tui as ScrollHost;
70
+ if (
71
+ typeof host.scrollBy !== "function" ||
72
+ typeof host.scrollToTop !== "function" ||
73
+ typeof host.scrollToBottom !== "function"
74
+ ) {
75
+ return undefined;
76
+ }
77
+ host[INSTALLED]?.();
78
+
79
+ const page = () =>
80
+ Math.max(
81
+ 1,
82
+ (host.getPrimaryScrollView?.().viewportHeight ?? 1) - PAGE_OVERLAP,
83
+ );
84
+ const half = () =>
85
+ Math.max(
86
+ 1,
87
+ Math.floor((host.getPrimaryScrollView?.().viewportHeight ?? 1) / 2),
88
+ );
89
+
90
+ const listener: TuiInputListener = (data) => {
91
+ if (host.isOverlayFocused?.() !== true) return undefined;
92
+ const wheel = parseWheel(data);
93
+ if (wheel) {
94
+ if (typeof host.routeWheel === "function") host.routeWheel(wheel);
95
+ else host.scrollBy(wheel.direction * (host.wheelScrollLines ?? 1));
96
+ return { consume: true };
97
+ }
98
+ if (!data.startsWith("\x1b")) return undefined;
99
+ const kb = getKeybindings();
100
+ const action = kb.matches(data, "tui.altScreen.pageUp")
101
+ ? () => host.scrollBy(-page())
102
+ : kb.matches(data, "tui.altScreen.pageDown")
103
+ ? () => host.scrollBy(page())
104
+ : kb.matches(data, "tui.altScreen.halfPageUp")
105
+ ? () => host.scrollBy(-half())
106
+ : kb.matches(data, "tui.altScreen.halfPageDown")
107
+ ? () => host.scrollBy(half())
108
+ : kb.matches(data, "tui.altScreen.lineUp")
109
+ ? () => host.scrollBy(-1)
110
+ : kb.matches(data, "tui.altScreen.lineDown")
111
+ ? () => host.scrollBy(1)
112
+ : kb.matches(data, "tui.altScreen.top")
113
+ ? () => host.scrollToTop()
114
+ : kb.matches(data, "tui.altScreen.bottom")
115
+ ? () => host.scrollToBottom()
116
+ : undefined;
117
+ if (!action) return undefined;
118
+ if (!isKeyRelease(data)) action();
119
+ return { consume: true };
120
+ };
121
+ const unsubscribe = tui.addInputListener(listener);
122
+
123
+ const dispose = () => {
124
+ if (host[INSTALLED] !== dispose) return;
125
+ unsubscribe();
126
+ delete host[INSTALLED];
127
+ };
128
+ host[INSTALLED] = dispose;
129
+ return dispose;
130
+ }
@@ -0,0 +1,91 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ /**
5
+ * Codex switches GPT-6 Astra into `MultiAgentMode::Proactive` at the Ultra
6
+ * effort: a developer message telling the model to delegate whenever work
7
+ * parallelizes. Pi's subagent policy is the opposite, set by two sentences
8
+ * pi-subagents puts in the system prompt: a tool guideline and a line in
9
+ * the `<advertised_subagents>` catalog. This rewrites exactly those two
10
+ * sentences and appends the Codex paragraph; the preflight instructions
11
+ * around them and the tool description's safety guidance stay as they are.
12
+ *
13
+ * Codex's Ultra also picks each subagent's model. pi-subagents' `models`
14
+ * action lists the whole registry and the tool description says to copy
15
+ * one, so the paragraph also carries the session's scoped models (the same
16
+ * set `/model` shows) and tells the model to choose the best fit per task.
17
+ */
18
+
19
+ const GUIDELINE = "Use subagent only when delegation is needed.";
20
+ const CATALOG_SENTENCE =
21
+ "Their descriptions indicate available specializations, not instructions to delegate. Use subagent only when delegation is needed.";
22
+
23
+ const PROACTIVE_GUIDELINE =
24
+ "Delegate to subagents proactively whenever work parallelizes; see Multi-agent mode below.";
25
+ const PROACTIVE_CATALOG_SENTENCE =
26
+ "Their descriptions indicate available specializations; delegate to them proactively whenever work parallelizes.";
27
+
28
+ /**
29
+ * Codex's `PROACTIVE_MULTI_AGENT_MODE_TEXT` retargeted at pi's tool, plus
30
+ * the boundaries and legibility line OpenAI's GPT-6 Astra model guide pairs
31
+ * with it: delegate independent, sizeable work; keep sequential, small, and
32
+ * same-area edits local; own synthesis; keep inter-agent messages readable.
33
+ */
34
+ export const PROACTIVE_DELEGATION_TEXT = `# Multi-agent mode
35
+
36
+ Proactive multi-agent delegation is active. Any earlier instruction requiring an explicit user request before spawning subagents no longer applies. User requests override this mode.
37
+
38
+ If at any point you can parallelize work by delegating tasks to another agent (no matter if you are root or a subagent), you should do so with the subagent tool if it could save time or improve quality.
39
+
40
+ Delegate work that is independent and large enough to justify a fresh context; keep tightly sequential steps, small tasks where coordination costs more than it saves, and edits to the same area in this session. You own synthesis and the final answer: read every result and decide yourself, never hand a child "based on the findings, do X". Messages you send to other agents may be read by a human, so ensure they are legible and always put proper spaces between words and numbers.`;
41
+
42
+ const MODEL_CHOICE_HEADER =
43
+ "For every delegation choose the model best suited to that task's difficulty and cost, passing it as the subagent tool's exact provider/id model argument. Bounded, well-specified subtasks suit cheaper or faster models; reserve the strongest models for decomposition, review, and hard reasoning. Only these models are enabled in this session; a model the subagent models action lists that is missing here must not be used:";
44
+
45
+ /** A scoped model as the delegation text names it. */
46
+ export type ScopedModelRef = { provider: string; id: string };
47
+
48
+ /** proper-llm-router's placeholder routes the parent, never a child. */
49
+ const PLACEHOLDER_PROVIDER = "llm-router";
50
+
51
+ function modelChoiceText(models: readonly ScopedModelRef[]): string {
52
+ const ids = [
53
+ ...new Set(
54
+ models
55
+ .filter((m) => m.provider !== PLACEHOLDER_PROVIDER)
56
+ .map((m) => `${m.provider}/${m.id}`),
57
+ ),
58
+ ];
59
+ if (ids.length === 0) return "";
60
+ return `\n\n${MODEL_CHOICE_HEADER}\n${ids.map((id) => `- ${id}`).join("\n")}`;
61
+ }
62
+
63
+ /** `"proactiveDelegation": false` in the agent directory's `proper-base.json` turns it off. */
64
+ export function readProactiveDelegationEnabled(agentDir: string): boolean {
65
+ try {
66
+ const parsed = JSON.parse(
67
+ readFileSync(join(agentDir, "proper-base.json"), "utf8"),
68
+ ) as Record<string, unknown> | null;
69
+ return parsed?.proactiveDelegation !== false;
70
+ } catch {
71
+ return true;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * The rewritten system prompt, or `undefined` when nothing changes: the
77
+ * subagent tool is absent, the mode is off, or the paragraph is already in.
78
+ */
79
+ export function applyProactiveDelegation(
80
+ systemPrompt: string,
81
+ hasSubagentTool: boolean,
82
+ scopedModels: readonly ScopedModelRef[] = [],
83
+ ): string | undefined {
84
+ if (!hasSubagentTool || systemPrompt.includes(PROACTIVE_DELEGATION_TEXT)) {
85
+ return undefined;
86
+ }
87
+ const rewritten = systemPrompt
88
+ .replace(CATALOG_SENTENCE, PROACTIVE_CATALOG_SENTENCE)
89
+ .replace(GUIDELINE, PROACTIVE_GUIDELINE);
90
+ return `${rewritten}\n\n${PROACTIVE_DELEGATION_TEXT}${modelChoiceText(scopedModels)}`;
91
+ }
@@ -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
+ }