proper-base 0.7.0 → 0.8.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.
@@ -0,0 +1,340 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import type { Component } from "@earendil-works/pi-tui";
5
+
6
+ const CONFIG_FILE_NAME = "proper-base.json";
7
+ const GLOBAL_KEY = "contextTokens";
8
+
9
+ /**
10
+ * The hard input cap of OpenAI's 1,050,000-token models: the window minus
11
+ * the 128,000 reserved output tokens. Probing the Codex backend through
12
+ * CLIProxyAPI on 2026-09-22 rejected every listed model one token past it
13
+ * (usage-counted 921,858 accepted, 921,859 refused; the rest is hidden
14
+ * request framing), just as gpt-5.5 there stops at Pi's registered 272,000.
15
+ * Codex's own catalog budgets 872,000, keeping 50,000 of headroom that Pi's
16
+ * `reserveTokens` provides instead.
17
+ */
18
+ const MAX_INPUT = 922_000;
19
+ const CODEX_MODELS = new Set([
20
+ "gpt-6-astra",
21
+ "gpt-6.1-sol",
22
+ "gpt-6-sol",
23
+ "gpt-6-luna",
24
+ "gpt-5.6-sol",
25
+ "gpt-5.6-terra",
26
+ "gpt-5.6-luna",
27
+ ]);
28
+ /** The API also serves GPT-5.5 and GPT-5.4 at 1,050,000 (Codex keeps GPT-5.5 at 272,000). */
29
+ const API_MODELS = new Set([...CODEX_MODELS, "gpt-5.5", "gpt-5.4"]);
30
+
31
+ export const CONTEXT_TOKENS_ENTRY = "proper-base-context-tokens";
32
+ export const TOKENS_USAGE = "Usage: /tokens [max|default] [global]";
33
+
34
+ export type ContextTokensMode = "max" | "default";
35
+ export type TokenLimits = { default: number; max: number };
36
+ export type TokensModel = {
37
+ provider: string;
38
+ id: string;
39
+ contextWindow: number;
40
+ };
41
+ type CompactionSettings = { enabled: boolean; reserveTokens: number };
42
+ type BranchEntry = { type: string; customType?: string; data?: unknown };
43
+
44
+ /** The live AgentSession fields this module reads and writes. */
45
+ export type TokensSession = {
46
+ agent: { state: { model: TokensModel | undefined } };
47
+ settingsManager: {
48
+ getCompactionSettings(model?: TokensModel): CompactionSettings;
49
+ };
50
+ sessionManager: { getBranch(): readonly BranchEntry[] };
51
+ };
52
+
53
+ /** The ModelRegistry call this module needs. */
54
+ export type TokensRegistry = {
55
+ find(provider: string, id: string): TokensModel | undefined;
56
+ };
57
+
58
+ type JsonObject = Record<string, unknown>;
59
+
60
+ function readJsonObject(path: string): JsonObject | undefined {
61
+ try {
62
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
63
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
64
+ ? (parsed as JsonObject)
65
+ : undefined;
66
+ } catch {
67
+ return undefined;
68
+ }
69
+ }
70
+
71
+ function isMode(value: unknown): value is ContextTokensMode {
72
+ return value === "max" || value === "default";
73
+ }
74
+
75
+ /** Feature-detect the private AgentSession shape; a renamed field disables the command. */
76
+ export function asTokensSession(value: unknown): TokensSession | undefined {
77
+ const session = value as Partial<TokensSession> | undefined;
78
+ return session?.agent?.state &&
79
+ typeof session.settingsManager?.getCompactionSettings === "function" &&
80
+ typeof session.sessionManager?.getBranch === "function"
81
+ ? (session as TokensSession)
82
+ : undefined;
83
+ }
84
+
85
+ /** `""` shows the state; otherwise `max|default` with an optional `global`. */
86
+ export function parseTokensArgs(
87
+ args: string,
88
+ ): { mode?: ContextTokensMode; global: boolean } | undefined {
89
+ const words = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
90
+ if (words.length === 0) return { global: false };
91
+ const [mode, scope, ...rest] = words;
92
+ if (!isMode(mode) || rest.length || (scope && scope !== "global")) {
93
+ return undefined;
94
+ }
95
+ return { mode, global: scope === "global" };
96
+ }
97
+
98
+ const COMPLETIONS = [
99
+ { value: "max", description: "Largest window for this session" },
100
+ { value: "default", description: "Standard window for this session" },
101
+ { value: "max global", description: "Largest window for every session" },
102
+ { value: "default global", description: "Standard window for every session" },
103
+ ];
104
+
105
+ export function tokensArgumentCompletions(prefix: string) {
106
+ const needle = prefix.trimStart().toLowerCase();
107
+ // After a completed mode, list its scopes. The session scope leads and its
108
+ // value equals the typed text, so Pi preselects it and Enter or Tab keeps
109
+ // the choice session-only instead of turning it global.
110
+ const mode = /^(max|default) $/.exec(needle)?.[1];
111
+ const items = mode
112
+ ? COMPLETIONS.filter(({ value }) => value.startsWith(mode)).map((item) => ({
113
+ ...item,
114
+ value: item.value === mode ? needle : item.value,
115
+ label: item.value,
116
+ }))
117
+ : COMPLETIONS.filter(({ value }) => value.startsWith(needle)).map(
118
+ (item) => ({ ...item, label: item.value }),
119
+ );
120
+ return items.length ? items : null;
121
+ }
122
+
123
+ const SCOPE_INSTALLED = Symbol.for("pi-proper-base.tokens-scope-completion");
124
+ const MODE_TEXT = /^\/tokens (?:max|default)$/;
125
+ const SCOPE_TEXT = /^\/tokens (?:max|default) $/;
126
+
127
+ type ScopeEditor = Component & {
128
+ getText?(): string;
129
+ handleInput?(data: string): void;
130
+ isShowingAutocomplete?(): boolean;
131
+ tryTriggerAutocomplete?(): void;
132
+ [SCOPE_INSTALLED]?: boolean;
133
+ };
134
+
135
+ /**
136
+ * Offer the `global` scope after a `/tokens` mode. Pi reopens suggestions
137
+ * only from typed letters and digits, and the separator is a space, so Tab
138
+ * on a mode stops there, adds the space, and opens the scope menu, and a
139
+ * typed space opens it too. Tab on a scope completes it and closes.
140
+ */
141
+ export function installTokensScopeCompletion(
142
+ editor: Component,
143
+ keybindings: { matches(data: string, action: string): boolean },
144
+ ): void {
145
+ const target = editor as ScopeEditor;
146
+ if (target[SCOPE_INSTALLED] || !target.handleInput || !target.getText) return;
147
+ const handleInput = target.handleInput.bind(target);
148
+ target.handleInput = (data: string) => {
149
+ handleInput(data);
150
+ if (target.isShowingAutocomplete?.()) return;
151
+ const tab = keybindings.matches(data, "tui.input.tab");
152
+ if (tab && MODE_TEXT.test(target.getText?.() ?? "")) handleInput(" ");
153
+ else if (data !== " ") return;
154
+ if (SCOPE_TEXT.test(target.getText?.() ?? ""))
155
+ target.tryTriggerAutocomplete?.();
156
+ };
157
+ target[SCOPE_INSTALLED] = true;
158
+ }
159
+
160
+ const format = (tokens: number) => tokens.toLocaleString("en-US");
161
+
162
+ /**
163
+ * Session and global context-window choices for OpenAI models.
164
+ *
165
+ * Pi registers these models at their standard window (272,000) although
166
+ * the backend accepts more, so the choice only changes Pi's budgeting: the
167
+ * session model is swapped for a copy carrying the chosen `contextWindow`,
168
+ * which every compaction, overflow, and footer check reads live. The
169
+ * provider/id identity is unchanged, so per-model compaction overrides keep
170
+ * applying. The session choice is a branch entry; the global choice is
171
+ * `contextTokens` in `proper-base.json`, re-read on every apply.
172
+ */
173
+ export class ContextTokens {
174
+ private readonly agentDir: string;
175
+ private readonly cliproxyProviderId: () => string;
176
+
177
+ constructor(agentDir: string, cliproxyProviderId: () => string) {
178
+ this.agentDir = agentDir;
179
+ this.cliproxyProviderId = cliproxyProviderId;
180
+ }
181
+
182
+ private configPath(): string {
183
+ return join(this.agentDir, CONFIG_FILE_NAME);
184
+ }
185
+
186
+ globalMode(): ContextTokensMode | undefined {
187
+ const value = readJsonObject(this.configPath())?.[GLOBAL_KEY];
188
+ return isMode(value) ? value : undefined;
189
+ }
190
+
191
+ /** Preserves every other key. Write failures propagate to the caller. */
192
+ setGlobalMode(mode: ContextTokensMode): void {
193
+ const existing = readJsonObject(this.configPath()) ?? {};
194
+ writeFileSync(
195
+ this.configPath(),
196
+ `${JSON.stringify({ ...existing, [GLOBAL_KEY]: mode }, null, "\t")}\n`,
197
+ );
198
+ }
199
+
200
+ /** The latest session choice on this branch; `null` data follows global. */
201
+ sessionMode(branch: readonly BranchEntry[]): ContextTokensMode | undefined {
202
+ for (let index = branch.length - 1; index >= 0; index--) {
203
+ const entry = branch[index];
204
+ if (entry?.type !== "custom" || entry.customType !== CONTEXT_TOKENS_ENTRY)
205
+ continue;
206
+ const mode = (entry.data as { mode?: unknown } | undefined)?.mode;
207
+ return isMode(mode) ? mode : undefined;
208
+ }
209
+ return undefined;
210
+ }
211
+
212
+ effectiveMode(branch: readonly BranchEntry[]): ContextTokensMode {
213
+ return this.sessionMode(branch) ?? this.globalMode() ?? "default";
214
+ }
215
+
216
+ /**
217
+ * Limits for a registry model, or `undefined` when it has no larger
218
+ * window. The default is the registry's own value, including any
219
+ * `models.json` override.
220
+ */
221
+ limitsFor(model: TokensModel): TokenLimits | undefined {
222
+ const models =
223
+ model.provider === "openai"
224
+ ? API_MODELS
225
+ : model.provider === "openai-codex" ||
226
+ model.provider === this.cliproxyProviderId()
227
+ ? CODEX_MODELS
228
+ : undefined;
229
+ return models?.has(model.id) && MAX_INPUT > model.contextWindow
230
+ ? { default: model.contextWindow, max: MAX_INPUT }
231
+ : undefined;
232
+ }
233
+
234
+ /** The model carrying the effective window, or the model unchanged. */
235
+ private windowed(
236
+ model: TokensModel | undefined,
237
+ session: TokensSession,
238
+ registry: TokensRegistry,
239
+ ): TokensModel | undefined {
240
+ if (!model) return model;
241
+ const base = registry.find(model.provider, model.id) ?? model;
242
+ const limits = this.limitsFor(base);
243
+ if (!limits) return model;
244
+ const mode = this.effectiveMode(session.sessionManager.getBranch());
245
+ const window = mode === "max" ? limits.max : limits.default;
246
+ if (model.contextWindow === window) return model;
247
+ return window === base.contextWindow
248
+ ? base
249
+ : { ...base, contextWindow: window };
250
+ }
251
+
252
+ /**
253
+ * Swap the session model for one carrying the effective window. Returns
254
+ * the applied window, or `undefined` when the model is ineligible.
255
+ */
256
+ apply(
257
+ session: TokensSession,
258
+ registry: TokensRegistry,
259
+ ): { window: number; limits: TokenLimits } | undefined {
260
+ const state = session.agent.state;
261
+ const next = this.windowed(state.model, session, registry);
262
+ if (next !== state.model) state.model = next;
263
+ if (!next) return undefined;
264
+ const limits = this.limitsFor(
265
+ registry.find(next.provider, next.id) ?? next,
266
+ );
267
+ return limits && { window: next.contextWindow, limits };
268
+ }
269
+
270
+ /**
271
+ * Keep the effective window across every write to the session model.
272
+ * Model switches, session restore, and any extension's provider
273
+ * (re)registration put the registry object back without an event, so the
274
+ * setter windows each model as it lands. Global changes made by another
275
+ * process still need `apply`. Returns the uninstaller.
276
+ */
277
+ guard(session: TokensSession, registry: TokensRegistry): () => void {
278
+ const state = session.agent.state;
279
+ let model = state.model;
280
+ const get = () => model;
281
+ Object.defineProperty(state, "model", {
282
+ configurable: true,
283
+ enumerable: true,
284
+ get,
285
+ set: (next: TokensModel | undefined) => {
286
+ model = this.windowed(next, session, registry);
287
+ },
288
+ });
289
+ return () => {
290
+ if (Object.getOwnPropertyDescriptor(state, "model")?.get !== get) return;
291
+ Object.defineProperty(state, "model", {
292
+ configurable: true,
293
+ enumerable: true,
294
+ writable: true,
295
+ value: model,
296
+ });
297
+ };
298
+ }
299
+ }
300
+
301
+ /** Feedback for `/tokens`, including where compaction will now trigger. */
302
+ export function tokensNotice(options: {
303
+ modelId: string;
304
+ /** The chosen mode, or for status its label and source. */
305
+ mode: string;
306
+ scope: "session" | "global" | "status";
307
+ window: number;
308
+ limits: TokenLimits;
309
+ compaction: CompactionSettings;
310
+ contextTokens: number | null | undefined;
311
+ }): { message: string; level: "info" | "warning" } {
312
+ const { modelId, mode, scope, window, limits, compaction, contextTokens } =
313
+ options;
314
+ const where =
315
+ scope === "global"
316
+ ? " for all sessions"
317
+ : scope === "session"
318
+ ? " for this session"
319
+ : "";
320
+ const lead =
321
+ scope === "status"
322
+ ? `${modelId}: ${format(window)}-token context window (${mode}; default ${format(limits.default)}, max ${format(limits.max)}).`
323
+ : `Context window ${mode}${where}: ${modelId} now uses ${format(window)} tokens.`;
324
+ if (!compaction.enabled) {
325
+ const over = contextTokens != null && contextTokens > window;
326
+ return {
327
+ message: `${lead} Auto-compaction is off${over ? `; the current ${format(contextTokens)}-token context already exceeds the window.` : "."}`,
328
+ level: over ? "warning" : "info",
329
+ };
330
+ }
331
+ const threshold = window - compaction.reserveTokens;
332
+ const trigger = `Compaction triggers above ${format(Math.max(0, threshold))} tokens (reserve ${format(compaction.reserveTokens)}).`;
333
+ if (contextTokens != null && contextTokens > threshold) {
334
+ return {
335
+ message: `${lead} ${trigger} The current ${format(contextTokens)}-token context is past it, so the next request compacts first.`,
336
+ level: "warning",
337
+ };
338
+ }
339
+ return { message: `${lead} ${trigger}`, level: "info" };
340
+ }
package/src/fast-mode.ts CHANGED
@@ -81,7 +81,7 @@ export class FastOverlay {
81
81
  return join(this.agentDir, CONFIG_FILE_NAME);
82
82
  }
83
83
 
84
- /** Session Fast is never persisted; a new session always starts off. */
84
+ /** Session Fast starts off; /clear restores its captured flag after startup. */
85
85
  resetSession(): void {
86
86
  this.sessionEnabled = false;
87
87
  }
@@ -166,9 +166,10 @@ export function installFooterColors(
166
166
  typeof state.ctx.sessionManager?.getLeafId === "function"
167
167
  ? (state.ctx.sessionManager.getLeafId() ?? "")
168
168
  : "";
169
- const key = `${leafId}\u0000${model ?? ""}\u0000${level}\u0000${
170
- isFast ? "1" : "0"
171
- }`;
169
+ // /tokens swaps the window without a new entry or model id.
170
+ const key = `${leafId}\u0000${model ?? ""}\u0000${
171
+ state.ctx.model?.contextWindow ?? ""
172
+ }\u0000${level}\u0000${isFast ? "1" : "0"}`;
172
173
  const base = (at: number) => {
173
174
  const lines = baseLines(at, key, theme, now);
174
175
  return model && isFast ? tagFast(lines, at, model, theme) : lines;
@@ -6,9 +6,6 @@ import {
6
6
  } from "@earendil-works/pi-tui";
7
7
 
8
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
9
  /** Mirrors pi-tui's private PAGE_SCROLL_OVERLAP. */
13
10
  const PAGE_OVERLAP = 4;
14
11
 
@@ -19,49 +16,24 @@ type ScrollHost = TUI & {
19
16
  scrollToBottom(): void;
20
17
  isOverlayFocused?(): boolean;
21
18
  getPrimaryScrollView?(): { viewportHeight: number };
22
- routeWheel?(event: {
23
- direction: number;
24
- x: number;
25
- y: number;
26
- button: number;
27
- }): void;
28
- wheelScrollLines?: number;
29
19
  [INSTALLED]?: () => void;
30
20
  };
31
21
 
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
22
  /**
50
- * Keep the fullscreen transcript scrollable while an overlay owns focus.
23
+ * Keep the fullscreen transcript scrollable by key while an overlay owns
24
+ * focus.
51
25
  *
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.
26
+ * Pi's viewport listener declines every `tui.altScreen` scroll key as soon as
27
+ * a capturing overlay is focused, so an `ask_user_question` questionnaire
28
+ * freezes the transcript behind it. (Pi 1.2.0 routes wheel events itself in
29
+ * that state, so only keys need help.) This listener registers after the
30
+ * renderer's own, so it only ever sees input the viewport already passed on,
31
+ * and routes that to the same scroll methods the renderer would have used.
32
+ * Keys are consumed so the overlay never receives a scroll chord.
61
33
  *
62
34
  * 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.
35
+ * nothing; a renamed private field only loses the page size, not scrolling
36
+ * itself.
65
37
  *
66
38
  * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Overlay transcript scrolling]]
67
39
  */
@@ -89,12 +61,6 @@ export function installOverlayScroll(tui: TUI): (() => void) | undefined {
89
61
 
90
62
  const listener: TuiInputListener = (data) => {
91
63
  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
64
  if (!data.startsWith("\x1b")) return undefined;
99
65
  const kb = getKeybindings();
100
66
  const action = kb.matches(data, "tui.altScreen.pageUp")
@@ -8,9 +8,11 @@ import { appendPromptSection } from "./prompt-sections.ts";
8
8
  * effort: a developer message telling the model to delegate whenever work
9
9
  * parallelizes. Pi's subagent policy is the opposite, set by two sentences
10
10
  * pi-subagents puts in the system prompt: a tool guideline and a line in
11
- * the `<advertised_subagents>` catalog. This rewrites exactly those two
12
- * sentences and appends the Codex paragraph; the preflight instructions
13
- * around them and the tool description's safety guidance stay as they are.
11
+ * the `<advertised_subagents>` catalog. Since 0.71 a fresh session starts
12
+ * with only the `subagents_enable` loader active, whose tool-list line
13
+ * repeats the ask-first rule. This rewrites exactly those sentences and
14
+ * appends the Codex paragraph; the preflight instructions around them and
15
+ * the tool descriptions' safety guidance stay as they are.
14
16
  *
15
17
  * Codex's Ultra also picks each subagent's model. pi-subagents' `models`
16
18
  * action lists the whole registry and the tool description says to copy
@@ -22,10 +24,15 @@ const GUIDELINE = "Use subagent only when delegation is needed.";
22
24
  const CATALOG_SENTENCE =
23
25
  "Their descriptions indicate available specializations, not instructions to delegate. Use subagent only when delegation is needed.";
24
26
 
27
+ const LOADER_SENTENCES =
28
+ "For authorized specialist, independent-review, or parallel work, call subagents_enable, then subagent. Authorization must come from the current request or applicable instructions; complexity alone is not authorization.";
29
+
25
30
  const PROACTIVE_GUIDELINE =
26
31
  "Delegate to subagents proactively whenever work parallelizes; see Multi-agent mode below.";
27
32
  const PROACTIVE_CATALOG_SENTENCE =
28
33
  "Their descriptions indicate available specializations; delegate to them proactively whenever work parallelizes.";
34
+ const PROACTIVE_LOADER_SENTENCES =
35
+ "To delegate, call subagents_enable, then subagent; see Multi-agent mode below.";
29
36
 
30
37
  /**
31
38
  * Codex's `PROACTIVE_MULTI_AGENT_MODE_TEXT` retargeted at pi's tool, plus
@@ -89,8 +96,12 @@ export function applyProactiveDelegation(
89
96
  const rewrite = (text: string) =>
90
97
  text
91
98
  .replace(CATALOG_SENTENCE, PROACTIVE_CATALOG_SENTENCE)
92
- .replace(GUIDELINE, PROACTIVE_GUIDELINE);
99
+ .replace(GUIDELINE, PROACTIVE_GUIDELINE)
100
+ .replace(LOADER_SENTENCES, PROACTIVE_LOADER_SENTENCES);
93
101
  options.promptGuidelines = options.promptGuidelines.map(rewrite);
102
+ for (const [name, text] of Object.entries(options.toolSnippets)) {
103
+ options.toolSnippets[name] = rewrite(text);
104
+ }
94
105
  for (const [name, rules] of Object.entries(options.toolGuidelines)) {
95
106
  options.toolGuidelines[name] = rules.map(rewrite);
96
107
  }
@@ -7,6 +7,7 @@ import {
7
7
  } from "@earendil-works/pi-coding-agent";
8
8
  import { installWrapper, originalInput } from "./host-interop.ts";
9
9
  import type { PromptDisplayController } from "./prompt-display.ts";
10
+ import { splitSkillText } from "./skill-context.ts";
10
11
 
11
12
  type Message = Parameters<SessionManager["appendMessage"]>[0];
12
13
  type Manager = Pick<SessionManager, "getBranch">;
@@ -103,6 +104,11 @@ export function installPromptDisplayHost(
103
104
  session: AgentSession;
104
105
  getUserMessageText(message: Message): string;
105
106
  getMarkdownTransformers(): MarkdownTransformer[];
107
+ addMessageToChat(
108
+ message: Message,
109
+ options?: { populateHistory?: boolean },
110
+ ): void;
111
+ editor: { addToHistory?(text: string): void };
106
112
  };
107
113
  const prototype = InteractiveMode.prototype as unknown as InteractiveHost;
108
114
  const original = prototype.getUserMessageText;
@@ -118,6 +124,30 @@ export function installPromptDisplayHost(
118
124
  };
119
125
  restorers.push(installWrapper(prototype, "getUserMessageText", wrapped));
120
126
 
127
+ // Pi collapses only the first skill block, rendering the rest as user text.
128
+ // Feed each block through its native renderer without changing the message.
129
+ const addMessage = prototype.addMessageToChat;
130
+ const addSkills: typeof addMessage = function (
131
+ this: InteractiveHost,
132
+ message,
133
+ options,
134
+ ) {
135
+ if (
136
+ !active ||
137
+ message.role !== "user" ||
138
+ !this.getMarkdownTransformers().includes(marker)
139
+ )
140
+ return addMessage.call(this, message, options);
141
+ const text = this.getUserMessageText(message);
142
+ const { skills, request } = splitSkillText(text);
143
+ if (skills.length < 2) return addMessage.call(this, message, options);
144
+ for (const skill of skills)
145
+ addMessage.call(this, { ...message, content: skill.block });
146
+ if (request) addMessage.call(this, { ...message, content: request });
147
+ if (options?.populateHistory) this.editor.addToHistory?.(text);
148
+ };
149
+ restorers.push(installWrapper(prototype, "addMessageToChat", addSkills));
150
+
121
151
  const controller: Controller = {
122
152
  activate(next) {
123
153
  manager = next;