@bismawy/pi-arnative 0.16.0 → 0.18.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 +25 -16
- package/extensions/index.ts +41 -0
- package/lib/active-clock.ts +91 -0
- package/lib/ansi.ts +40 -78
- package/lib/box.ts +49 -68
- package/lib/chatbox.ts +371 -0
- package/lib/color.ts +3 -31
- package/lib/compat.ts +0 -60
- package/lib/edit-diff.ts +199 -0
- package/{extensions → lib/features}/arnative.ts +96 -423
- package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -325
- package/{extensions → lib/features}/budget.ts +17 -242
- package/lib/features/footer.ts +2232 -0
- package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
- package/{extensions → lib/features}/model-heal.ts +5 -28
- package/lib/features/progress-group.ts +1557 -0
- package/{extensions → lib/features}/render-cache.ts +130 -158
- package/{extensions → lib/features}/timestamps.ts +132 -131
- package/{extensions → lib/features}/todos.ts +44 -158
- package/lib/features/tools.ts +1202 -0
- package/lib/features/ui-render-tweaks.ts +606 -0
- package/lib/features/usage.ts +786 -0
- package/lib/format.ts +22 -4
- package/lib/git-status.ts +164 -0
- package/lib/list-picker.ts +1 -127
- package/lib/model-heal.ts +70 -162
- package/lib/patch.ts +0 -63
- package/lib/preset-store.ts +17 -133
- package/lib/provider-store.ts +573 -0
- package/lib/provider.ts +52 -851
- package/lib/runtime.ts +209 -0
- package/lib/shortcuts.ts +8 -58
- package/lib/spinner.ts +88 -162
- package/lib/status-widget.ts +4 -30
- package/lib/todos.ts +20 -143
- package/lib/usage-pricing.ts +143 -0
- package/lib/usage-store.ts +44 -378
- package/package.json +5 -6
- package/CHANGELOG.md +0 -678
- package/extensions/animations.ts +0 -242
- package/extensions/footer.ts +0 -2580
- package/extensions/tools.ts +0 -2231
- package/extensions/ui-render-tweaks.ts +0 -1005
- package/extensions/usage-export.ts +0 -283
- package/extensions/usage.ts +0 -1406
- package/lib/check.ts +0 -21
- package/themes/gen-themes.mjs +0 -715
|
@@ -0,0 +1,2232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Arnative footer (fixed 3-row grid). Row 1: cwd | active time | branch — model + thinking;
|
|
3
|
+
* rows 2-3: extension status | tok/s · cache · token, each side wrapped in its half of the
|
|
4
|
+
* width. The clock counts active time, not wall-clock age — see {@link ActiveClock}.
|
|
5
|
+
* Preset (`/arnative footers`), live: "Pi (system)", "Pi (color)", "Arnative (Full)" (default),
|
|
6
|
+
* "Arnative (Minimal)", or "Zen".
|
|
7
|
+
*/
|
|
8
|
+
import { isAbsolute, relative, resolve, sep as pathSep } from "node:path";
|
|
9
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
10
|
+
import { CustomEditor, FooterComponent, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { truncateToWidth, visibleWidth, wrapTextWithAnsi, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
12
|
+
import { fgOr, setActiveTheme, softOf, softSecondaryOf, stripAnsi } from "../ansi.ts";
|
|
13
|
+
import { inSpans, textSpans, type TextSpan } from "../box.ts";
|
|
14
|
+
import { capitalize, modelDisplayParts } from "../format.ts";
|
|
15
|
+
import { SHORTCUT_RELOAD, SHORTCUT_TOGGLE_FOOTER } from "../shortcuts.ts";
|
|
16
|
+
import { markPatched, originalOf } from "../patch.ts";
|
|
17
|
+
import { estimateCost, formatTokens, loadPriceTable, TOOL_PROVIDER, type PriceTable } from "../usage-store.ts";
|
|
18
|
+
import { FOOTER_COST_KEY as FOOTER_COST_CONFIG_KEY, FOOTER_PRESET_KEY as FOOTER_PRESET_CONFIG_KEY, choiceSetting, flagSetting, loadSetting } from "../preset-store.ts";
|
|
19
|
+
import { formatCost } from "./usage.ts";
|
|
20
|
+
import { isByteLimitedModel, wireBytesSnapshot } from "./auto-compact.ts";
|
|
21
|
+
import { budgetLevelNow } from "./budget.ts";
|
|
22
|
+
import { activeSpinnerGradient, activeSpinnerPreset, applySpinnerPreset, setWorkingUi, spinnerPainter } from "../spinner.ts";
|
|
23
|
+
import { getRuntime } from "../runtime.ts";
|
|
24
|
+
import {
|
|
25
|
+
ActiveClock,
|
|
26
|
+
IDLE_PAUSE_MS,
|
|
27
|
+
formatDuration,
|
|
28
|
+
isPointerOrFocusInput,
|
|
29
|
+
resolveSessionStartMs,
|
|
30
|
+
seedActiveMs,
|
|
31
|
+
} from "../active-clock.ts";
|
|
32
|
+
import {
|
|
33
|
+
branchFromDisk,
|
|
34
|
+
collectGitInfo,
|
|
35
|
+
formatDiffStat,
|
|
36
|
+
gitParts,
|
|
37
|
+
run,
|
|
38
|
+
shortenCwd,
|
|
39
|
+
sumNumstat,
|
|
40
|
+
type GitInfo,
|
|
41
|
+
} from "../git-status.ts";
|
|
42
|
+
import {
|
|
43
|
+
CHATBOX_DIALOG_KEY,
|
|
44
|
+
CHATBOX_DIALOGS,
|
|
45
|
+
CHATBOX_PRESET_KEY,
|
|
46
|
+
CHATBOX_PRESETS,
|
|
47
|
+
CHATBOX_PROMPT_KEY,
|
|
48
|
+
CHATBOX_PROMPTS,
|
|
49
|
+
DEFAULT_CHATBOX_DIALOG,
|
|
50
|
+
DEFAULT_CHATBOX_PRESET,
|
|
51
|
+
DEFAULT_CHATBOX_PROMPT,
|
|
52
|
+
PROMPT_IDLE_MS,
|
|
53
|
+
activeChatboxDialog,
|
|
54
|
+
activeChatboxPreset,
|
|
55
|
+
activeChatboxPrompt,
|
|
56
|
+
applyChatboxDialog,
|
|
57
|
+
bindChatboxPoke,
|
|
58
|
+
boxEditorLines,
|
|
59
|
+
chatboxPrimaryPaint,
|
|
60
|
+
isPromptActive,
|
|
61
|
+
isWideNerdPrompt,
|
|
62
|
+
markPromptTyped,
|
|
63
|
+
nextChatboxDialog,
|
|
64
|
+
nextChatboxPrompt,
|
|
65
|
+
overlayOutsideDialogOnWidgetLines,
|
|
66
|
+
paintChatboxPrompt,
|
|
67
|
+
renderChatboxLines,
|
|
68
|
+
renderChatboxScrollBorder,
|
|
69
|
+
setChatboxDialog,
|
|
70
|
+
setChatboxPreset,
|
|
71
|
+
setChatboxPrompt,
|
|
72
|
+
stopPromptIdle,
|
|
73
|
+
type ChatboxDialog,
|
|
74
|
+
type ChatboxPreset,
|
|
75
|
+
type ChatboxPrompt,
|
|
76
|
+
} from "../chatbox.ts";
|
|
77
|
+
|
|
78
|
+
export {
|
|
79
|
+
ActiveClock,
|
|
80
|
+
CHATBOX_DIALOGS,
|
|
81
|
+
CHATBOX_PRESETS,
|
|
82
|
+
CHATBOX_PROMPTS,
|
|
83
|
+
DEFAULT_CHATBOX_DIALOG,
|
|
84
|
+
DEFAULT_CHATBOX_PRESET,
|
|
85
|
+
DEFAULT_CHATBOX_PROMPT,
|
|
86
|
+
IDLE_PAUSE_MS,
|
|
87
|
+
PROMPT_IDLE_MS,
|
|
88
|
+
activeChatboxDialog,
|
|
89
|
+
activeChatboxPreset,
|
|
90
|
+
activeChatboxPrompt,
|
|
91
|
+
applyChatboxDialog,
|
|
92
|
+
boxEditorLines,
|
|
93
|
+
chatboxPrimaryPaint,
|
|
94
|
+
formatDiffStat,
|
|
95
|
+
formatDuration,
|
|
96
|
+
gitParts,
|
|
97
|
+
isPointerOrFocusInput,
|
|
98
|
+
isPromptActive,
|
|
99
|
+
isWideNerdPrompt,
|
|
100
|
+
markPromptTyped,
|
|
101
|
+
nextChatboxDialog,
|
|
102
|
+
nextChatboxPrompt,
|
|
103
|
+
overlayOutsideDialogOnWidgetLines,
|
|
104
|
+
paintChatboxPrompt,
|
|
105
|
+
renderChatboxLines,
|
|
106
|
+
renderChatboxScrollBorder,
|
|
107
|
+
resolveSessionStartMs,
|
|
108
|
+
seedActiveMs,
|
|
109
|
+
setChatboxDialog,
|
|
110
|
+
setChatboxPreset,
|
|
111
|
+
setChatboxPrompt,
|
|
112
|
+
shortenCwd,
|
|
113
|
+
stopPromptIdle,
|
|
114
|
+
sumNumstat,
|
|
115
|
+
type ChatboxDialog,
|
|
116
|
+
type ChatboxPreset,
|
|
117
|
+
type ChatboxPrompt,
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// Footer preset chosen through `/arnative footers`. "Arnative (Full)" = this extension's
|
|
121
|
+
// 3-row grid footer; "Pi (system)" = pi's built-in footer (the boxed editor stays arnative
|
|
122
|
+
// in both — pi's `setEditorComponent()` would close the picker mid-preview).
|
|
123
|
+
// Listed built-in-first: the `(Full)` suffix is rendered dim, so the plain row reads cleaner on top.
|
|
124
|
+
export const FOOTER_PRESETS = ["Pi (system)", "Pi (color)", "Arnative (Full)", "Arnative (Minimal)", "Zen"] as const;
|
|
125
|
+
export type FooterPreset = (typeof FOOTER_PRESETS)[number];
|
|
126
|
+
export const DEFAULT_FOOTER_PRESET: FooterPreset = "Arnative (Full)";
|
|
127
|
+
/** Presets that this extension's registrar draws (everything but pi's built-in footer). */
|
|
128
|
+
const ARNATIVE_PRESETS: readonly FooterPreset[] = ["Pi (color)", "Arnative (Full)", "Arnative (Minimal)", "Zen"];
|
|
129
|
+
/** Collapse state of the minimal footer: one flag per side, so a click on the left
|
|
130
|
+
* head does not open the right metrics. Session-scoped, not persisted. */
|
|
131
|
+
export function minimalExpanded(): { left: boolean; right: boolean } {
|
|
132
|
+
const rt = getRuntime();
|
|
133
|
+
rt.minimalFooterExpanded ??= { left: false, right: false };
|
|
134
|
+
return rt.minimalFooterExpanded;
|
|
135
|
+
}
|
|
136
|
+
/** Collapse state of the Zen footer: `git` toggles inline git expansion after `···`,
|
|
137
|
+
* and `detail` opens one centered second row at a time (`left` statuses or `right` metrics). */
|
|
138
|
+
export function zenExpanded(): { git: boolean; detail: "left" | "right" | null } {
|
|
139
|
+
const rt = getRuntime();
|
|
140
|
+
rt.zenFooterExpanded ??= { git: false, detail: null };
|
|
141
|
+
return rt.zenFooterExpanded;
|
|
142
|
+
}
|
|
143
|
+
const footerPreset = choiceSetting(FOOTER_PRESET_CONFIG_KEY, FOOTER_PRESETS, DEFAULT_FOOTER_PRESET);
|
|
144
|
+
const FOOTER_PRESET_KEY = footerPreset.slot;
|
|
145
|
+
const footerCost = flagSetting(FOOTER_COST_CONFIG_KEY);
|
|
146
|
+
|
|
147
|
+
/** Is the session cost cell on? */
|
|
148
|
+
export const activeFooterCost = (): boolean => footerCost.get();
|
|
149
|
+
|
|
150
|
+
/** Flip the cost cell, persist it, and repaint the footer at once. */
|
|
151
|
+
export function setFooterCost(on: boolean): void {
|
|
152
|
+
footerCost.set(on);
|
|
153
|
+
poke();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export const activeFooterPreset = (): FooterPreset => {
|
|
157
|
+
const raw = (globalThis as Record<symbol, unknown>)[FOOTER_PRESET_KEY] ?? loadSetting(FOOTER_PRESET_CONFIG_KEY);
|
|
158
|
+
if (raw === "Argon" || raw === "Arnative (Zen)") return "Zen";
|
|
159
|
+
return footerPreset.get();
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Hand the footer slot to the active preset: arnative's grid, or pi's built-in footer.
|
|
164
|
+
* The editor is deliberately never touched here — pi's `setEditorComponent()` calls
|
|
165
|
+
* `disposeActiveSelector()`, which would close the `/arnative` picker mid-preview.
|
|
166
|
+
*/
|
|
167
|
+
function applyFooterPreset(ctx: ExtensionContext): void {
|
|
168
|
+
if (activeFooterPreset() === "Pi (system)") {
|
|
169
|
+
ctx.ui?.setFooter?.(undefined);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const register = getRuntime().footerRegistrar;
|
|
173
|
+
register?.(ctx);
|
|
174
|
+
}
|
|
175
|
+
/** Select a preset and apply it immediately (the footer swaps on the spot). */
|
|
176
|
+
export function setFooterPreset(name: FooterPreset, ctx: ExtensionContext): void {
|
|
177
|
+
footerPreset.set(name);
|
|
178
|
+
applyFooterPreset(ctx);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
interface FooterComponentProto {
|
|
182
|
+
render(width: number): string[];
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
interface WorkingUiSurface {
|
|
186
|
+
setWorkingMessage?: (message?: string) => void;
|
|
187
|
+
setWorkingIndicator?: (options?: unknown) => void;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
interface WorkingIndicatorLike {
|
|
191
|
+
renderIndicatorVerbatim?: boolean;
|
|
192
|
+
spinnerColorFn?: (text: string) => string;
|
|
193
|
+
messageColorFn?: (text: string) => string;
|
|
194
|
+
updateDisplay?: () => void;
|
|
195
|
+
renderInBorder?(width: number): string;
|
|
196
|
+
renderSpinnerInBorder?(width: number): string;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
interface OutsideDialogModeLike {
|
|
200
|
+
editor?: unknown;
|
|
201
|
+
editorContainer?: { children?: unknown[] };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Intercept the built-in FooterComponent to force a pure 2-line footer.
|
|
205
|
+
// Reinstalled on every load (lib/patch.ts): `/reload` must pick up a footer change.
|
|
206
|
+
if (FooterComponent?.prototype?.render) {
|
|
207
|
+
const proto = FooterComponent.prototype as unknown as FooterComponentProto;
|
|
208
|
+
const origRender = originalOf<(this: FooterComponentProto, width: number) => string[]>(proto, "render");
|
|
209
|
+
proto.render = markPatched(function (this: FooterComponentProto, width: number): string[] {
|
|
210
|
+
// "Pi (system)" preset = pi's own footer, so keep its stock line count.
|
|
211
|
+
if (activeFooterPreset() === "Pi (system)") return origRender.call(this, width);
|
|
212
|
+
const lines = origRender.call(this, width);
|
|
213
|
+
return lines.length > 2 ? lines.slice(0, 2) : lines;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
let activeThemeProxy: { fg(color: string, text: string): string; bg?(color: string, text: string): string } | null = null;
|
|
218
|
+
|
|
219
|
+
/** Painters for the footer's current theme, rebuilt only when pi hands over a new theme. */
|
|
220
|
+
let themeCache: {
|
|
221
|
+
theme: unknown;
|
|
222
|
+
acc: (t: string) => string;
|
|
223
|
+
dim: (t: string) => string;
|
|
224
|
+
soft: (t: string) => string;
|
|
225
|
+
colorOr: (name: string, fallback: (t: string) => string) => (t: string) => string;
|
|
226
|
+
primary: (t: string) => string;
|
|
227
|
+
secondarySoft: (t: string) => string;
|
|
228
|
+
diffAdd: (t: string) => string;
|
|
229
|
+
diffDel: (t: string) => string;
|
|
230
|
+
sep: string;
|
|
231
|
+
} | null = null;
|
|
232
|
+
/** The cwd cell and git segment, rebuilt only when theme, cwd, or collected git info changes. */
|
|
233
|
+
let gitCache: { theme: unknown; git: GitInfo; cwd: string; cwdCell: string; gitItems: string[]; gitSeg: string } | null = null;
|
|
234
|
+
|
|
235
|
+
let gitRefreshInFlight = false;
|
|
236
|
+
let git: GitInfo = null;
|
|
237
|
+
let currentThinkingLevel: string | undefined = undefined;
|
|
238
|
+
let currentModel: { id: string; name?: string; provider?: string } | undefined = undefined;
|
|
239
|
+
let rerender: (() => void) | null = null;
|
|
240
|
+
let lastPokeMs = 0;
|
|
241
|
+
/** Column ranges of the minimal footer's head cells and disclosure arrows, recorded per render
|
|
242
|
+
* (mouse coordinates are component-local, so they must come from the same frame). */
|
|
243
|
+
interface MinimalSpan {
|
|
244
|
+
y: number;
|
|
245
|
+
x0: number;
|
|
246
|
+
x1: number;
|
|
247
|
+
}
|
|
248
|
+
let minimalRanges: {
|
|
249
|
+
left: MinimalSpan[];
|
|
250
|
+
right: MinimalSpan[];
|
|
251
|
+
leftArrow: MinimalSpan | null;
|
|
252
|
+
rightArrow: MinimalSpan | null;
|
|
253
|
+
} | null = null;
|
|
254
|
+
let zenRanges: {
|
|
255
|
+
left: MinimalSpan[];
|
|
256
|
+
right: MinimalSpan[];
|
|
257
|
+
dots: MinimalSpan | null;
|
|
258
|
+
} | null = null;
|
|
259
|
+
|
|
260
|
+
// One shared clock: a /reload re-imports this module, so a fresh instance would restart
|
|
261
|
+
// a session that is already hours old. Exported so a test can drive the render path.
|
|
262
|
+
export let clock = new ActiveClock(Date.now());
|
|
263
|
+
|
|
264
|
+
let footerGen = getRuntime().footerGen || 0;
|
|
265
|
+
|
|
266
|
+
let assistantStartMs: number | null = null;
|
|
267
|
+
let assistantChars = 0;
|
|
268
|
+
let latestSpeed: number | null = null;
|
|
269
|
+
|
|
270
|
+
// Live elapsed clock for the working loader: "⠴ Working (50s)".
|
|
271
|
+
const WORK_LABEL = "Working";
|
|
272
|
+
let workVerb = WORK_LABEL;
|
|
273
|
+
let workStartMs: number | null = null;
|
|
274
|
+
let workUI: { setWorkingMessage?: (message?: string) => void; setWorkingIndicator?: (options?: unknown) => void } | null =
|
|
275
|
+
null;
|
|
276
|
+
// Verbs of tools still running (toolCallId -> verb): the label must not reset to "Working"
|
|
277
|
+
// while a sibling tool is still going (pi executes tools in parallel).
|
|
278
|
+
const activeToolVerbs = new Map<string, string>();
|
|
279
|
+
|
|
280
|
+
/** Label while `active` tools remain: last started wins, empty -> default. */
|
|
281
|
+
export function currentToolVerb(active: ReadonlyMap<string, string>): string {
|
|
282
|
+
let verb = WORK_LABEL;
|
|
283
|
+
for (const v of active.values()) verb = v;
|
|
284
|
+
return verb;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Is this status value pi-jev-eye's own cell? It is matched on the LABEL the value carries (`Eye:`), not on
|
|
289
|
+
* the internal key name: the value is `Eye: ● ON (Clef Flash)` and contains no `jev-eye` anywhere, so the
|
|
290
|
+
* old `value.includes("jev-eye")` test went false and the whole cell fell through to the generic path —
|
|
291
|
+
* which is exactly how it silently lost its icon and its dim backend suffix.
|
|
292
|
+
*
|
|
293
|
+
* Recognising the label keeps the rule honest: if pi-jev-eye renames its label, this test fails loudly in
|
|
294
|
+
* the self-check below instead of degrading to a plain grey cell.
|
|
295
|
+
*/
|
|
296
|
+
export const isJevEyeStatus = (status: string): boolean => /^(?:(?:\uf21b|\ueb1b|\u{1F440})\s*)?Eye\s*:/iu.test(stripAnsi(status));
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The pi-jev-eye / pi-decision-eye status cell: `[icon] Eye: ● MODE (Backend)`.
|
|
300
|
+
*
|
|
301
|
+
* The trailing parenthesised backend is a modifier, so it takes `dim` while the `Eye:` label and the state
|
|
302
|
+
* keep the soft and state tiers — that is what makes `(Clef Flash)` / `(mercury-decide)` recede and
|
|
303
|
+
* `Eye: ● ON` / `Eye: ● BALANCED` stay readable at a glance. The backend name itself is read out of the value,
|
|
304
|
+
* never hardcoded here.
|
|
305
|
+
*/
|
|
306
|
+
export function jevEyeStatusLine(
|
|
307
|
+
status: string,
|
|
308
|
+
acc: (text: string) => string,
|
|
309
|
+
dim: (text: string) => string,
|
|
310
|
+
soft: (text: string) => string,
|
|
311
|
+
theme?: { fg?: (color: string, text: string) => string },
|
|
312
|
+
): string {
|
|
313
|
+
const clean = stripAnsi(status).replace(/^(?:\uf21b|\ueb1b|\u{1F440})\s*/u, "");
|
|
314
|
+
const isOff = /\bOFF\b/i.test(clean) || clean.includes("\u25CB");
|
|
315
|
+
const isReview = /\bREVIEW\b/i.test(clean);
|
|
316
|
+
const isStrict = /\bSTRICT\b/i.test(clean);
|
|
317
|
+
const isLight = /\bLIGHT\b/i.test(clean);
|
|
318
|
+
const isBalanced = /\bBALANCED\b/i.test(clean);
|
|
319
|
+
const fgToken = (token: string, fallback: (t: string) => string) => {
|
|
320
|
+
if (typeof theme?.fg !== "function") return fallback("\u25CF");
|
|
321
|
+
try {
|
|
322
|
+
return theme.fg(token, "\u25CF");
|
|
323
|
+
} catch {
|
|
324
|
+
return fallback("\u25CF");
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
let bullet = isOff ? dim("\u25CB") : acc("\u25CF");
|
|
328
|
+
if (isReview) bullet = fgToken("warning", acc);
|
|
329
|
+
else if (isStrict) bullet = fgToken("mdHeading", acc);
|
|
330
|
+
else if (isLight) bullet = fgToken("borderAccent", acc);
|
|
331
|
+
const label = isOff
|
|
332
|
+
? "OFF"
|
|
333
|
+
: isReview
|
|
334
|
+
? "REVIEW"
|
|
335
|
+
: isStrict
|
|
336
|
+
? "STRICT"
|
|
337
|
+
: isLight
|
|
338
|
+
? "LIGHT"
|
|
339
|
+
: isBalanced
|
|
340
|
+
? "BALANCED"
|
|
341
|
+
: "ON";
|
|
342
|
+
// `Eye: ● ON (Clef Flash)` -> the base before the first colon, the backend in the trailing parentheses.
|
|
343
|
+
const base = clean.split(":")[0]!.trim() || "Eye";
|
|
344
|
+
const at = clean.lastIndexOf("(");
|
|
345
|
+
const backend = at >= 0 && clean.trimEnd().endsWith(")") ? clean.slice(at, clean.lastIndexOf(")") + 1).trim() : "";
|
|
346
|
+
// One space, not the two the previous glyph needed: \uf21b's ink fits its own cell, so the label sits
|
|
347
|
+
// right after it. The space before the backend stays outside the dim run, so the modifier does not
|
|
348
|
+
// start with a painted blank.
|
|
349
|
+
return `${acc("\uf21b")} ${soft(`${base}:`)} ${bullet} ${soft(label)}${backend ? ` ${dim(backend)}` : ""}`;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* The ponytail status cell. The horse lives at U+EF04 (fa-horse). U+EF51
|
|
354
|
+
* (fa-circle_radiation) carries no outline in the Windows Nerd Font build, so it
|
|
355
|
+
* renders as a blank cell there and the status silently loses its icon; U+EF04 does
|
|
356
|
+
* draw. Kept out of the render closure so the self-check drives this exact path.
|
|
357
|
+
*/
|
|
358
|
+
export function ponytailStatusLine(
|
|
359
|
+
status: string,
|
|
360
|
+
acc: (text: string) => string,
|
|
361
|
+
dim: (text: string) => string,
|
|
362
|
+
soft: (text: string) => string,
|
|
363
|
+
): string {
|
|
364
|
+
const bullet = status.includes("\u25CF") ? acc("\u25CF") : dim("\u25CB");
|
|
365
|
+
let mode = "FULL";
|
|
366
|
+
if (/LITE/i.test(status)) mode = "LITE";
|
|
367
|
+
else if (/ULTRA/i.test(status)) mode = "ULTRA";
|
|
368
|
+
return `${acc("\uef04")} ${soft("ponytail:")} ${bullet} ${soft(mode)}`;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// A refresh arriving while one is in flight is queued (last requested cwd wins) and
|
|
372
|
+
// re-run afterwards — it used to be dropped, leaving the footer's git state stale
|
|
373
|
+
// until the next trigger.
|
|
374
|
+
let gitRefreshQueuedCwd: string | null = null;
|
|
375
|
+
let lastGitRefreshMs = 0;
|
|
376
|
+
/** Tool bursts (a turn with ten edits) would otherwise run two git processes per tool;
|
|
377
|
+
* coalesce them into one refresh per window, with a trailing run so the final state lands. */
|
|
378
|
+
const GIT_REFRESH_MIN_INTERVAL_MS = 2500;
|
|
379
|
+
let gitRefreshTrailing: ReturnType<typeof setTimeout> | null = null;
|
|
380
|
+
|
|
381
|
+
/** Tools that cannot mutate the git worktree — skip spawning git status/diff after them. */
|
|
382
|
+
const READ_ONLY_GIT_TOOLS = new Set([
|
|
383
|
+
"read",
|
|
384
|
+
"grep",
|
|
385
|
+
"ffgrep",
|
|
386
|
+
"find",
|
|
387
|
+
"fffind",
|
|
388
|
+
"ls",
|
|
389
|
+
"lsp_diagnostics",
|
|
390
|
+
"web_search",
|
|
391
|
+
"fetch_content",
|
|
392
|
+
"get_search_content",
|
|
393
|
+
"source_check",
|
|
394
|
+
"todo",
|
|
395
|
+
"scratchpad",
|
|
396
|
+
"ask_user_question",
|
|
397
|
+
"plan_mode_question",
|
|
398
|
+
"memory_read",
|
|
399
|
+
"memory_search",
|
|
400
|
+
"memory_status",
|
|
401
|
+
]);
|
|
402
|
+
|
|
403
|
+
function toolMayChangeGit(toolName: string | undefined): boolean {
|
|
404
|
+
if (!toolName) return true;
|
|
405
|
+
const n = toolName.toLowerCase();
|
|
406
|
+
return !READ_ONLY_GIT_TOOLS.has(n);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async function refreshGit(cwd: string, opts: { force?: boolean } = {}): Promise<void> {
|
|
410
|
+
if (!opts.force) {
|
|
411
|
+
const since = Date.now() - lastGitRefreshMs;
|
|
412
|
+
if (since < GIT_REFRESH_MIN_INTERVAL_MS) {
|
|
413
|
+
if (gitRefreshTrailing) clearTimeout(gitRefreshTrailing);
|
|
414
|
+
gitRefreshTrailing = setTimeout(() => {
|
|
415
|
+
gitRefreshTrailing = null;
|
|
416
|
+
void refreshGit(cwd, { force: true }).then(() => poke());
|
|
417
|
+
}, GIT_REFRESH_MIN_INTERVAL_MS - since);
|
|
418
|
+
gitRefreshTrailing.unref?.();
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (gitRefreshInFlight) {
|
|
423
|
+
gitRefreshQueuedCwd = cwd;
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
lastGitRefreshMs = Date.now();
|
|
427
|
+
gitRefreshInFlight = true;
|
|
428
|
+
try {
|
|
429
|
+
git = await collectGitInfo(cwd);
|
|
430
|
+
getRuntime().lastGit = git;
|
|
431
|
+
} finally {
|
|
432
|
+
gitRefreshInFlight = false;
|
|
433
|
+
if (gitRefreshQueuedCwd !== null) {
|
|
434
|
+
const queued = gitRefreshQueuedCwd;
|
|
435
|
+
gitRefreshQueuedCwd = null;
|
|
436
|
+
void refreshGit(queued, { force: true }).then(() => poke());
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Head row for the minimal footer, plus the exact click zones (0-based, inclusive
|
|
443
|
+
* columns) of its two heads. Placing the row here instead of guessing at `pairRow`'s
|
|
444
|
+
* arithmetic is deliberate: `pairRow` truncates with an ellipsis, which shifts columns,
|
|
445
|
+
* and a mirror of that logic silently drifts at narrow widths — the bug where a click on
|
|
446
|
+
* blank space toggled a side. Measuring the placed cells cannot drift. The blank gap and
|
|
447
|
+
* any padding stay inert; a head the row cannot fit gets `[-1, -1]`.
|
|
448
|
+
*/
|
|
449
|
+
export function placeMinimalHead(
|
|
450
|
+
left: string,
|
|
451
|
+
right: string,
|
|
452
|
+
width: number,
|
|
453
|
+
): {
|
|
454
|
+
row: string;
|
|
455
|
+
left: [number, number];
|
|
456
|
+
right: [number, number];
|
|
457
|
+
leftTruncated: boolean;
|
|
458
|
+
rightTruncated: boolean;
|
|
459
|
+
} {
|
|
460
|
+
const lw = visibleWidth(left);
|
|
461
|
+
const rw = visibleWidth(right);
|
|
462
|
+
if (lw + 1 + rw <= width) {
|
|
463
|
+
const rightStart = width - rw;
|
|
464
|
+
return {
|
|
465
|
+
row: left + " ".repeat(rightStart - lw) + right,
|
|
466
|
+
left: lw > 0 ? [0, lw - 1] : [-1, -1],
|
|
467
|
+
right: rw > 0 ? [rightStart, width - 1] : [-1, -1],
|
|
468
|
+
leftTruncated: false,
|
|
469
|
+
rightTruncated: false,
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
// Too wide: the left head is cut, the right one keeps its edge column like pairRow.
|
|
473
|
+
const room = Math.max(1, width - Math.min(rw, width) - 1);
|
|
474
|
+
const lCut = truncateToWidth(left, room);
|
|
475
|
+
const rCut = truncateToWidth(right, width - room - 1);
|
|
476
|
+
const lCutW = visibleWidth(lCut);
|
|
477
|
+
const rCutW = visibleWidth(rCut);
|
|
478
|
+
const rightStart = lCutW + 1;
|
|
479
|
+
return {
|
|
480
|
+
row: lCut + " " + rCut,
|
|
481
|
+
left: lCutW > 0 ? [0, lCutW - 1] : [-1, -1],
|
|
482
|
+
right: rCutW > 0 ? [rightStart, rightStart + rCutW - 1] : [-1, -1],
|
|
483
|
+
leftTruncated: lCut !== left,
|
|
484
|
+
rightTruncated: rCut !== right,
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function centerLine(text: string, width: number): { line: string; pad: number; textW: number } {
|
|
489
|
+
const textW = visibleWidth(text);
|
|
490
|
+
const pad = Math.max(0, Math.floor((width - textW) / 2));
|
|
491
|
+
return { line: pad > 0 ? " ".repeat(pad) + text : text, pad, textW };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Centered head row(s) for the Zen footer, plus exact 0-based inclusive hit zones for
|
|
496
|
+
* `left` (cwd + clock), `right` (model), and `dots` (`···` git toggle). Measured directly
|
|
497
|
+
* from the placed strings so click zones never drift across widths or narrow wraps.
|
|
498
|
+
*/
|
|
499
|
+
export function placeZenHead(
|
|
500
|
+
left: string,
|
|
501
|
+
right: string,
|
|
502
|
+
sep: string,
|
|
503
|
+
dots: string,
|
|
504
|
+
gitText: string,
|
|
505
|
+
width: number,
|
|
506
|
+
): {
|
|
507
|
+
rows: string[];
|
|
508
|
+
left: MinimalSpan[];
|
|
509
|
+
right: MinimalSpan[];
|
|
510
|
+
dots: MinimalSpan | null;
|
|
511
|
+
} {
|
|
512
|
+
const w = Math.max(1, width);
|
|
513
|
+
const leftW = visibleWidth(left);
|
|
514
|
+
const sepW = visibleWidth(sep);
|
|
515
|
+
const rightW = visibleWidth(right);
|
|
516
|
+
const dotsW = dots ? visibleWidth(dots) : 0;
|
|
517
|
+
const gitW = gitText ? visibleWidth(gitText) : 0;
|
|
518
|
+
const base = `${left}${sep}${right}${dotsW > 0 ? ` ${dots}` : ""}`;
|
|
519
|
+
const baseW = leftW + sepW + rightW + (dotsW > 0 ? 1 + dotsW : 0);
|
|
520
|
+
const fullW = baseW + (gitW > 0 ? 1 + gitW : 0);
|
|
521
|
+
|
|
522
|
+
if (fullW <= w) {
|
|
523
|
+
const rowText = gitW > 0 ? `${base} ${gitText}` : base;
|
|
524
|
+
const pad = Math.max(0, Math.floor((w - fullW) / 2));
|
|
525
|
+
const rightStart = pad + leftW + sepW;
|
|
526
|
+
const dotsStart = rightStart + rightW + 1;
|
|
527
|
+
return {
|
|
528
|
+
rows: [pad > 0 ? " ".repeat(pad) + rowText : rowText],
|
|
529
|
+
left: leftW > 0 ? [{ y: 0, x0: pad, x1: pad + leftW - 1 }] : [],
|
|
530
|
+
right: rightW > 0 ? [{ y: 0, x0: rightStart, x1: rightStart + rightW - 1 }] : [],
|
|
531
|
+
dots: dotsW > 0 ? { y: 0, x0: dotsStart, x1: dotsStart + dotsW - 1 } : null,
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
if (baseW <= w && gitW > 0) {
|
|
536
|
+
const pad = Math.max(0, Math.floor((w - baseW) / 2));
|
|
537
|
+
const rightStart = pad + leftW + sepW;
|
|
538
|
+
const dotsStart = rightStart + rightW + 1;
|
|
539
|
+
const gitRows = wrapTextWithAnsi(gitText, w).map((l) => centerLine(l, w).line);
|
|
540
|
+
return {
|
|
541
|
+
rows: [pad > 0 ? " ".repeat(pad) + base : base, ...gitRows],
|
|
542
|
+
left: leftW > 0 ? [{ y: 0, x0: pad, x1: pad + leftW - 1 }] : [],
|
|
543
|
+
right: rightW > 0 ? [{ y: 0, x0: rightStart, x1: rightStart + rightW - 1 }] : [],
|
|
544
|
+
dots: dotsW > 0 ? { y: 0, x0: dotsStart, x1: dotsStart + dotsW - 1 } : null,
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// Narrow viewport: wrap each head centered so nothing clips and zones stay exact.
|
|
549
|
+
const rows: string[] = [];
|
|
550
|
+
const leftSpans: MinimalSpan[] = [];
|
|
551
|
+
for (const seg of wrapTextWithAnsi(left, w)) {
|
|
552
|
+
const { line, pad, textW } = centerLine(seg, w);
|
|
553
|
+
if (textW > 0) leftSpans.push({ y: rows.length, x0: pad, x1: pad + textW - 1 });
|
|
554
|
+
rows.push(line);
|
|
555
|
+
}
|
|
556
|
+
const rightSpans: MinimalSpan[] = [];
|
|
557
|
+
let dotsSpan: MinimalSpan | null = null;
|
|
558
|
+
const rightWrapped = wrapTextWithAnsi(dotsW > 0 ? `${right} ${dots}` : right, w);
|
|
559
|
+
for (let i = 0; i < rightWrapped.length; i++) {
|
|
560
|
+
const { line, pad, textW } = centerLine(rightWrapped[i]!, w);
|
|
561
|
+
const y = rows.length;
|
|
562
|
+
const isLast = i === rightWrapped.length - 1;
|
|
563
|
+
if (isLast && dotsW > 0 && textW >= dotsW) {
|
|
564
|
+
const dotsStart = pad + textW - dotsW;
|
|
565
|
+
dotsSpan = { y, x0: dotsStart, x1: pad + textW - 1 };
|
|
566
|
+
// Exclude the trailing ` ···` from the right-text zone so clicks on `···` stay distinct.
|
|
567
|
+
const rightEnd = dotsStart - 2;
|
|
568
|
+
if (rightEnd >= pad) rightSpans.push({ y, x0: pad, x1: rightEnd });
|
|
569
|
+
} else if (textW > 0) {
|
|
570
|
+
rightSpans.push({ y, x0: pad, x1: pad + textW - 1 });
|
|
571
|
+
}
|
|
572
|
+
rows.push(line);
|
|
573
|
+
}
|
|
574
|
+
if (gitW > 0) {
|
|
575
|
+
for (const seg of wrapTextWithAnsi(gitText, w)) rows.push(centerLine(seg, w).line);
|
|
576
|
+
}
|
|
577
|
+
return { rows, left: leftSpans, right: rightSpans, dots: dotsSpan };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function formatModelName(
|
|
581
|
+
model: { id: string; name?: string; provider?: string } | undefined,
|
|
582
|
+
thinkingLevel: string | undefined,
|
|
583
|
+
acc: (t: string) => string,
|
|
584
|
+
soft: (t: string) => string,
|
|
585
|
+
primary: (t: string) => string,
|
|
586
|
+
dim: (t: string) => string,
|
|
587
|
+
): string {
|
|
588
|
+
if (!model) return dim("No Model");
|
|
589
|
+
const { name, provider } = modelDisplayParts({ id: model.id, name: model.name, provider: model.provider });
|
|
590
|
+
const provStr = provider ? ` ${dim(`(${provider})`)}` : "";
|
|
591
|
+
const capThinking = thinkingLevel && thinkingLevel !== "off" ? capitalize(thinkingLevel) : "";
|
|
592
|
+
const thinkStr = capThinking ? `${acc("\uee9c")} ${soft(capThinking)} ${dim("·")} ` : "";
|
|
593
|
+
return `${thinkStr}${primary(name)}${provStr}`;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** Format `cwd` the same way Pi's built-in footer does (replace home prefix with `~`). */
|
|
597
|
+
export function formatPiCwd(cwd: string, home: string | undefined = process.env.HOME || process.env.USERPROFILE): string {
|
|
598
|
+
if (!home) return cwd;
|
|
599
|
+
const resolvedCwd = resolve(cwd);
|
|
600
|
+
const resolvedHome = resolve(home);
|
|
601
|
+
const rel = relative(resolvedHome, resolvedCwd);
|
|
602
|
+
const inside = rel === "" || (rel !== ".." && !rel.startsWith(`..${pathSep}`) && !isAbsolute(rel));
|
|
603
|
+
if (!inside) return cwd;
|
|
604
|
+
return rel === "" ? "~" : `~${pathSep}${rel}`;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
export interface PiColorStats {
|
|
608
|
+
input: number;
|
|
609
|
+
output: number;
|
|
610
|
+
cacheRead: number;
|
|
611
|
+
cacheWrite: number;
|
|
612
|
+
cost: number;
|
|
613
|
+
latestCacheHitRate: number | undefined;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
export interface PiColorPainters {
|
|
617
|
+
acc: (t: string) => string;
|
|
618
|
+
dim: (t: string) => string;
|
|
619
|
+
primary: (t: string) => string;
|
|
620
|
+
secondarySoft: (t: string) => string;
|
|
621
|
+
warning: (t: string) => string;
|
|
622
|
+
error: (t: string) => string;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** Format token counts identically to Pi's built-in FooterComponent. */
|
|
626
|
+
export function formatPiTokens(count: number): string {
|
|
627
|
+
if (count < 1000) return count.toString();
|
|
628
|
+
if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
|
|
629
|
+
if (count < 1000000) return `${Math.round(count / 1000)}k`;
|
|
630
|
+
if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;
|
|
631
|
+
return `${Math.round(count / 1000000)}M`;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export interface PiColorFooterInput {
|
|
635
|
+
cwd: string;
|
|
636
|
+
home?: string;
|
|
637
|
+
branch: string | null;
|
|
638
|
+
sessionName?: string;
|
|
639
|
+
stats: PiColorStats;
|
|
640
|
+
usingSubscription?: boolean;
|
|
641
|
+
budgetBand?: "ok" | "warn" | "over";
|
|
642
|
+
contextPercent: number | null;
|
|
643
|
+
contextWindow: number;
|
|
644
|
+
autoCompactEnabled?: boolean;
|
|
645
|
+
experimental?: boolean;
|
|
646
|
+
model?: { id: string; provider?: string; reasoning?: boolean };
|
|
647
|
+
thinkingLevel?: string;
|
|
648
|
+
availableProviderCount: number;
|
|
649
|
+
extensionStatuses: ReadonlyMap<string, string>;
|
|
650
|
+
width: number;
|
|
651
|
+
painters: PiColorPainters;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
let piStatsCache: {
|
|
655
|
+
manager: unknown;
|
|
656
|
+
sessionId: string | undefined;
|
|
657
|
+
entryCount: number;
|
|
658
|
+
leafId: string | null | undefined;
|
|
659
|
+
stats: PiColorStats;
|
|
660
|
+
} | null = null;
|
|
661
|
+
|
|
662
|
+
function collectPiSessionStats(sessionManager: {
|
|
663
|
+
getEntries(): readonly unknown[];
|
|
664
|
+
getLeafId?: () => string | null;
|
|
665
|
+
getSessionId?: () => string;
|
|
666
|
+
}): PiColorStats {
|
|
667
|
+
const entries = sessionManager.getEntries();
|
|
668
|
+
const entryCount = entries.length;
|
|
669
|
+
const leafId = sessionManager.getLeafId?.();
|
|
670
|
+
const sessionId = sessionManager.getSessionId?.();
|
|
671
|
+
if (
|
|
672
|
+
piStatsCache &&
|
|
673
|
+
piStatsCache.manager === sessionManager &&
|
|
674
|
+
piStatsCache.sessionId === sessionId &&
|
|
675
|
+
piStatsCache.entryCount === entryCount &&
|
|
676
|
+
piStatsCache.leafId === leafId
|
|
677
|
+
) {
|
|
678
|
+
return piStatsCache.stats;
|
|
679
|
+
}
|
|
680
|
+
const stats: PiColorStats = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, latestCacheHitRate: undefined };
|
|
681
|
+
const addUsage = (u: MessageUsage | undefined) => {
|
|
682
|
+
if (!u) return;
|
|
683
|
+
stats.input += u.input || 0;
|
|
684
|
+
stats.output += u.output || 0;
|
|
685
|
+
stats.cacheRead += u.cacheRead || 0;
|
|
686
|
+
stats.cacheWrite += u.cacheWrite || 0;
|
|
687
|
+
stats.cost += u.cost?.total || 0;
|
|
688
|
+
};
|
|
689
|
+
for (const entry of entries) {
|
|
690
|
+
if (!entry || typeof entry !== "object" || !("type" in entry)) continue;
|
|
691
|
+
const e = entry as {
|
|
692
|
+
type?: string;
|
|
693
|
+
usage?: MessageUsage;
|
|
694
|
+
message?: { role?: string; usage?: MessageUsage };
|
|
695
|
+
};
|
|
696
|
+
if (e.type === "usage") {
|
|
697
|
+
addUsage(e.usage);
|
|
698
|
+
} else if (e.type === "message" && e.message?.role === "assistant") {
|
|
699
|
+
addUsage(e.message.usage);
|
|
700
|
+
const u = e.message.usage;
|
|
701
|
+
if (u) {
|
|
702
|
+
const prompt = (u.input || 0) + (u.cacheRead || 0) + (u.cacheWrite || 0);
|
|
703
|
+
stats.latestCacheHitRate = prompt > 0 ? ((u.cacheRead || 0) / prompt) * 100 : undefined;
|
|
704
|
+
}
|
|
705
|
+
} else if (e.type === "message" && e.message?.role === "toolResult" && e.message.usage) {
|
|
706
|
+
addUsage(e.message.usage);
|
|
707
|
+
} else if ((e.type === "branch_summary" || e.type === "compaction") && e.usage) {
|
|
708
|
+
addUsage(e.usage);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
piStatsCache = { manager: sessionManager, sessionId, entryCount, leafId, stats };
|
|
712
|
+
return stats;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function sanitizePiStatus(text: string): string {
|
|
716
|
+
return text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim();
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* Pi's built-in footer layout (row 1: pwd/branch/session, row 2: token stats + model/thinking,
|
|
721
|
+
* row 3: extension statuses) colored with Arnative's two-toned accent + secondarySoft palette.
|
|
722
|
+
*/
|
|
723
|
+
export function renderPiColorFooter(input: PiColorFooterInput): string[] {
|
|
724
|
+
const { acc, dim, primary, secondarySoft, warning, error } = input.painters;
|
|
725
|
+
const width = Math.max(1, input.width);
|
|
726
|
+
|
|
727
|
+
// Row 1: pwd (branch) • sessionName
|
|
728
|
+
let pwdLine = dim(formatPiCwd(input.cwd, input.home));
|
|
729
|
+
if (input.branch) {
|
|
730
|
+
pwdLine += ` ${acc(`(${input.branch})`)}`;
|
|
731
|
+
}
|
|
732
|
+
if (input.sessionName) {
|
|
733
|
+
pwdLine += `${dim(" \u2022 ")}${secondarySoft(input.sessionName)}`;
|
|
734
|
+
}
|
|
735
|
+
pwdLine = truncateToWidth(pwdLine, width, dim("..."));
|
|
736
|
+
|
|
737
|
+
// Row 2 left: ↑in ↓out Rread Wwrite CHrate% $cost pct%/win (auto)
|
|
738
|
+
const { stats } = input;
|
|
739
|
+
const statsParts: string[] = [];
|
|
740
|
+
if (stats.input) statsParts.push(`${acc("\u2191")}${secondarySoft(formatPiTokens(stats.input))}`);
|
|
741
|
+
if (stats.output) statsParts.push(`${acc("\u2193")}${secondarySoft(formatPiTokens(stats.output))}`);
|
|
742
|
+
if (stats.cacheRead) statsParts.push(`${acc("R")}${secondarySoft(formatPiTokens(stats.cacheRead))}`);
|
|
743
|
+
if (stats.cacheWrite) statsParts.push(`${acc("W")}${secondarySoft(formatPiTokens(stats.cacheWrite))}`);
|
|
744
|
+
if ((stats.cacheRead > 0 || stats.cacheWrite > 0) && stats.latestCacheHitRate !== undefined) {
|
|
745
|
+
const chPaint = stats.latestCacheHitRate < 40 ? error : stats.latestCacheHitRate < 70 ? warning : null;
|
|
746
|
+
statsParts.push(`${(chPaint ?? acc)("CH")}${(chPaint ?? secondarySoft)(`${stats.latestCacheHitRate.toFixed(1)}%`)}`);
|
|
747
|
+
}
|
|
748
|
+
if (stats.cost || input.usingSubscription) {
|
|
749
|
+
const costPaint = input.budgetBand === "over" ? error : input.budgetBand === "warn" ? warning : null;
|
|
750
|
+
const sub = input.usingSubscription ? dim(" (sub)") : "";
|
|
751
|
+
statsParts.push(`${(costPaint ?? acc)("$")}${(costPaint ?? secondarySoft)(stats.cost.toFixed(3))}${sub}`);
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
const autoIndicator = input.autoCompactEnabled ? " (auto)" : "";
|
|
755
|
+
const winStr = formatPiTokens(input.contextWindow);
|
|
756
|
+
const pctValue = input.contextPercent ?? 0;
|
|
757
|
+
const pctStr = input.contextPercent !== null ? `${pctValue.toFixed(1)}%` : "?";
|
|
758
|
+
if (pctValue > 90) {
|
|
759
|
+
statsParts.push(`${error(`${pctStr}/${winStr}`)}${dim(autoIndicator)}`);
|
|
760
|
+
} else if (pctValue > 70) {
|
|
761
|
+
statsParts.push(`${warning(`${pctStr}/${winStr}`)}${dim(autoIndicator)}`);
|
|
762
|
+
} else {
|
|
763
|
+
statsParts.push(`${secondarySoft(pctStr)}${dim(`/${winStr}${autoIndicator}`)}`);
|
|
764
|
+
}
|
|
765
|
+
if (input.experimental) {
|
|
766
|
+
statsParts.push(`${dim("\u2022")} ${warning("xp")}`);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
let statsLeft = statsParts.join(" ");
|
|
770
|
+
let statsLeftWidth = visibleWidth(statsLeft);
|
|
771
|
+
if (statsLeftWidth > width) {
|
|
772
|
+
statsLeft = truncateToWidth(statsLeft, width, dim("..."));
|
|
773
|
+
statsLeftWidth = visibleWidth(statsLeft);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// Row 2 right: (provider) model.id • thinkingLevel
|
|
777
|
+
const minPadding = 2;
|
|
778
|
+
let rightWithoutProvider = input.model ? primary(input.model.id) : dim("no-model");
|
|
779
|
+
if (input.model?.reasoning) {
|
|
780
|
+
const level = input.thinkingLevel || "off";
|
|
781
|
+
rightWithoutProvider += level === "off"
|
|
782
|
+
? dim(" \u2022 thinking off")
|
|
783
|
+
: `${dim(" \u2022 ")}${acc(level)}`;
|
|
784
|
+
}
|
|
785
|
+
let rightSide = rightWithoutProvider;
|
|
786
|
+
if (input.availableProviderCount > 1 && input.model?.provider) {
|
|
787
|
+
const withProvider = `${dim(`(${input.model.provider}) `)}${rightWithoutProvider}`;
|
|
788
|
+
if (statsLeftWidth + minPadding + visibleWidth(withProvider) <= width) {
|
|
789
|
+
rightSide = withProvider;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const rightSideWidth = visibleWidth(rightSide);
|
|
794
|
+
let statsLine: string;
|
|
795
|
+
if (statsLeftWidth + minPadding + rightSideWidth <= width) {
|
|
796
|
+
statsLine = statsLeft + " ".repeat(width - statsLeftWidth - rightSideWidth) + rightSide;
|
|
797
|
+
} else {
|
|
798
|
+
const availableForRight = width - statsLeftWidth - minPadding;
|
|
799
|
+
if (availableForRight > 0) {
|
|
800
|
+
const truncatedRight = truncateToWidth(rightSide, availableForRight, "");
|
|
801
|
+
const truncatedRightWidth = visibleWidth(truncatedRight);
|
|
802
|
+
statsLine = statsLeft + " ".repeat(Math.max(0, width - statsLeftWidth - truncatedRightWidth)) + truncatedRight;
|
|
803
|
+
} else {
|
|
804
|
+
statsLine = statsLeft;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
const lines = [pwdLine, statsLine];
|
|
809
|
+
if (input.extensionStatuses.size > 0) {
|
|
810
|
+
const sorted = Array.from(input.extensionStatuses.entries())
|
|
811
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
812
|
+
.map(([, text]) => {
|
|
813
|
+
const clean = sanitizePiStatus(text);
|
|
814
|
+
return clean.includes("\x1b[") ? clean : secondarySoft(clean);
|
|
815
|
+
});
|
|
816
|
+
lines.push(truncateToWidth(sorted.join(" "), width, dim("...")));
|
|
817
|
+
}
|
|
818
|
+
return lines;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* The footer as a fixed 3-row grid. Row 1 pairs the head cells (cwd line, model);
|
|
823
|
+
* rows 2-3 pair the wrapped left cells (extension status, mcp first) with the
|
|
824
|
+
* wrapped right cells (tok/s · cache · token), each side wrapping inside its half
|
|
825
|
+
* of the terminal so the columns never collide. Right cells stay right-aligned.
|
|
826
|
+
* A side that runs out of cells leaves its half blank, and a row where both sides
|
|
827
|
+
* ran out is dropped, so a quiet footer stays 1-3 rows tall.
|
|
828
|
+
*/
|
|
829
|
+
export function layoutFooterGrid(
|
|
830
|
+
headLeft: string,
|
|
831
|
+
headRight: string,
|
|
832
|
+
left: readonly string[],
|
|
833
|
+
right: readonly string[],
|
|
834
|
+
leftSep: string,
|
|
835
|
+
rightSep: string,
|
|
836
|
+
width: number,
|
|
837
|
+
vw: (s: string) => number = visibleWidth,
|
|
838
|
+
): string[] {
|
|
839
|
+
const headLeftW = headLeft ? vw(headLeft) : 0;
|
|
840
|
+
const headRightW = headRight ? vw(headRight) : 0;
|
|
841
|
+
// Narrow / mobile viewport: when the two head cells cannot share one row,
|
|
842
|
+
// stack left layout (head + statuses, auto-wrapped) above right layout (head + metrics, auto-wrapped).
|
|
843
|
+
if (headLeft && headRight && headLeftW + 1 + headRightW > width) {
|
|
844
|
+
const w = Math.max(1, width);
|
|
845
|
+
const out: string[] = [...wrapTextWithAnsi(headLeft, w)];
|
|
846
|
+
if (left.length > 0) out.push(...wrapTextWithAnsi(left.join(leftSep), w));
|
|
847
|
+
out.push(...wrapTextWithAnsi(headRight, w));
|
|
848
|
+
if (right.length > 0) out.push(...wrapTextWithAnsi(right.join(rightSep), w));
|
|
849
|
+
return out;
|
|
850
|
+
}
|
|
851
|
+
const half = Math.max(1, Math.floor(width / 2) - 1);
|
|
852
|
+
// Every cell's width is measured once up front: visibleWidth parses ANSI and
|
|
853
|
+
// clusters graphemes, and wrap()/pairRow() used to re-measure the same cell 3x.
|
|
854
|
+
const leftW = left.map(vw);
|
|
855
|
+
const rightW = right.map(vw);
|
|
856
|
+
const sepWL = vw(leftSep);
|
|
857
|
+
const sepWR = vw(rightSep);
|
|
858
|
+
// Wrap each side at half width; the first break happens at most once (rows 2-3),
|
|
859
|
+
// after that the rest stays on the last row and the pairing truncates it.
|
|
860
|
+
const wrap = (cells: readonly string[], widths: readonly number[], sep: string, sepW: number): { text: string; width: number }[] => {
|
|
861
|
+
const rows: { text: string; width: number }[] = [];
|
|
862
|
+
let line = "";
|
|
863
|
+
let lineW = 0;
|
|
864
|
+
for (let i = 0; i < cells.length; i++) {
|
|
865
|
+
const cell = cells[i]!;
|
|
866
|
+
const cellW = widths[i]!;
|
|
867
|
+
if (line && rows.length === 0 && lineW + sepW + cellW > half) {
|
|
868
|
+
rows.push({ text: line, width: lineW });
|
|
869
|
+
line = cell;
|
|
870
|
+
lineW = cellW;
|
|
871
|
+
} else if (line) {
|
|
872
|
+
line += sep + cell;
|
|
873
|
+
lineW += sepW + cellW;
|
|
874
|
+
} else {
|
|
875
|
+
line = cell;
|
|
876
|
+
lineW = cellW;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
if (line) rows.push({ text: line, width: lineW });
|
|
880
|
+
return rows;
|
|
881
|
+
};
|
|
882
|
+
const leftRows = wrap(left, leftW, leftSep, sepWL);
|
|
883
|
+
const rightRows = wrap(right, rightW, rightSep, sepWR);
|
|
884
|
+
const out = [pairRow(headLeft, headRight, width, vw, headLeftW, headRightW)];
|
|
885
|
+
for (let i = 0; i < Math.max(leftRows.length, rightRows.length); i++) {
|
|
886
|
+
const l = leftRows[i];
|
|
887
|
+
const r = rightRows[i];
|
|
888
|
+
if (l === undefined && r === undefined) break;
|
|
889
|
+
out.push(pairRow(l?.text ?? "", r?.text ?? "", width, vw, l?.width ?? 0, r?.width ?? 0));
|
|
890
|
+
}
|
|
891
|
+
return out;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/** One grid row: `left` at the start, `right` flush to the right edge. `leftW`/`rightW`
|
|
895
|
+
* are the caller's measured widths when it already has them, so the row costs no extra pass. */
|
|
896
|
+
function pairRow(left: string, right: string, width: number, vw: (s: string) => number, leftW?: number, rightW?: number): string {
|
|
897
|
+
const lw = leftW ?? vw(left);
|
|
898
|
+
if (!right) return lw <= width ? left : truncateToWidth(left, width);
|
|
899
|
+
const rawRw = rightW ?? vw(right);
|
|
900
|
+
const rw = Math.min(rawRw, width);
|
|
901
|
+
if (!left) return " ".repeat(width - rw) + (rawRw <= width ? right : truncateToWidth(right, width));
|
|
902
|
+
if (lw + 1 + rw <= width) {
|
|
903
|
+
return left + " ".repeat(width - lw - rw) + (rawRw <= width ? right : truncateToWidth(right, width));
|
|
904
|
+
}
|
|
905
|
+
// Too wide together: the right cell keeps its columns, the left one is cut.
|
|
906
|
+
const room = Math.max(1, width - rw - 1);
|
|
907
|
+
const lCut = lw <= room ? left : truncateToWidth(left, room);
|
|
908
|
+
const rRoom = width - room - 1;
|
|
909
|
+
const rCut = rawRw <= rRoom ? right : truncateToWidth(right, rRoom);
|
|
910
|
+
return lCut + " " + rCut;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function parseOptimizer(raw: string | undefined): string | null {
|
|
914
|
+
|
|
915
|
+
if (!raw) return null;
|
|
916
|
+
const m = raw.match(/([A-Za-z0-9_-]+)\s+cache\s+(\d+\/\d+)·[^\s]+\s+([\d.]+%)/);
|
|
917
|
+
return m ? `${m[1]} ${m[2]} (${m[3]})` : null;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// Pi's own per-message usage: shown when pi-cache-optimizer has no adapter for the
|
|
921
|
+
// provider (a custom one like mytool.ts publishes no pi-cache-stats status).
|
|
922
|
+
// The denominator (`input + cacheRead`) includes tool-result (child) tokens, because the ↑
|
|
923
|
+
// cell above is total spend — the hit rate is measured against the same total, so do not
|
|
924
|
+
// "fix" the denominator back to assistant messages only.
|
|
925
|
+
let usageTotals = { inp: 0, read: 0 };
|
|
926
|
+
export function piCacheHit(): string | null {
|
|
927
|
+
const total = usageTotals.inp + usageTotals.read;
|
|
928
|
+
return total > 0 ? "pi " + ((usageTotals.read / total) * 100).toFixed(1) + "%" : null;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// The cache cell's COLOUR comes from a recent window, not the session-wide rate above: the
|
|
932
|
+
// last CACHE_WINDOW_MSGS assistant messages, with the session's first two always skipped
|
|
933
|
+
// (turn 1 is a cold cache, so colouring it would cry wolf on every session). The `pi …%`
|
|
934
|
+
// text stays session-wide; only the colour is windowed.
|
|
935
|
+
export const CACHE_WINDOW_MSGS = 10;
|
|
936
|
+
/** Windowed (input, cacheRead) sums of the last scan — read by the render for the colour. */
|
|
937
|
+
let usageWindow = { inp: 0, read: 0 };
|
|
938
|
+
|
|
939
|
+
export type CacheHitBand = "soft" | "warning" | "error";
|
|
940
|
+
/** Colour band of a windowed cache-hit rate: ≥70% keeps the current soft tier, 40–70% is
|
|
941
|
+
* amber (the theme's `warning` slot), below 40% is red (`error`). No rate yet (fewer than
|
|
942
|
+
* 3 assistant messages, so an empty window) stays soft. */
|
|
943
|
+
export function cacheHitBand(winInp: number, winRead: number): CacheHitBand {
|
|
944
|
+
const total = winInp + winRead;
|
|
945
|
+
if (total <= 0) return "soft";
|
|
946
|
+
const rate = winRead / total;
|
|
947
|
+
if (rate >= 0.7) return "soft";
|
|
948
|
+
if (rate >= 0.4) return "warning";
|
|
949
|
+
return "error";
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
let usageScanAt = 0;
|
|
953
|
+
let usageScanLen = -1;
|
|
954
|
+
interface UsageTotals {
|
|
955
|
+
inp: number;
|
|
956
|
+
out: number;
|
|
957
|
+
read: number;
|
|
958
|
+
/** Sum of `cost.total` over the messages the provider billed (`totalFromProvider`). */
|
|
959
|
+
costBilled: number;
|
|
960
|
+
/** Everything else: catalog totals, plus a price-table reconstruction for messages that
|
|
961
|
+
* carried no cost at all. Never blended into `costBilled`. */
|
|
962
|
+
costEstimated: number;
|
|
963
|
+
/** Only set on the branch-last snapshot (`lastUsageOf`): that entry is an assistant message. */
|
|
964
|
+
assistant?: boolean;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
let usageScanManager: object | undefined;
|
|
968
|
+
let usageScanLeaf: unknown;
|
|
969
|
+
let usageScanPriceTable: PriceTable | null = null;
|
|
970
|
+
// A stream mutates the same leaf, so its delta updates the cached prefix. A different
|
|
971
|
+
// manager or leaf must rescan: equal-length /tree branches can have different usage.
|
|
972
|
+
|
|
973
|
+
let usageScanNums: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
|
|
974
|
+
// Usage of the branch's last entry at scan time (assistant or tool result): a stream tick
|
|
975
|
+
// mutates that entry in place (branch length unchanged), so the delta is applied on top of
|
|
976
|
+
// the cached sums — O(1) per frame, numbers always fresh, still no O(N) rescan per frame.
|
|
977
|
+
let usageScanLast: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
|
|
978
|
+
// Windowed sums at scan time, plus the window contribution of the branch's last entry
|
|
979
|
+
// (`null` when that entry is not an assistant message inside the window): the in-place
|
|
980
|
+
// delta of a stream tick lands in the window exactly when the last entry is one.
|
|
981
|
+
let usageScanWin = { inp: 0, read: 0 };
|
|
982
|
+
let usageScanWinLast: { inp: number; read: number } | null = null;
|
|
983
|
+
|
|
984
|
+
type MessageUsage = {
|
|
985
|
+
input?: number;
|
|
986
|
+
output?: number;
|
|
987
|
+
cacheRead?: number;
|
|
988
|
+
cacheWrite?: number;
|
|
989
|
+
cost?: { total?: number; totalFromProvider?: boolean };
|
|
990
|
+
/** Only set by a tool that names what produced its own usage; absent on the main LLM calls. */
|
|
991
|
+
provider?: string;
|
|
992
|
+
model?: string;
|
|
993
|
+
};
|
|
994
|
+
|
|
995
|
+
/** True when a usage object carries any countable field: a tool result without usage (or with
|
|
996
|
+
* an all-zero one) adds nothing to the sums. */
|
|
997
|
+
const hasUsage = (u: MessageUsage | undefined): u is MessageUsage =>
|
|
998
|
+
!!u && !!((u.input || 0) || (u.output || 0) || (u.cacheRead || 0) || (u.cacheWrite || 0) || (u.cost?.total || 0));
|
|
999
|
+
|
|
1000
|
+
/** Attribution of one branch message's usage: a tool result's usage names no provider/model,
|
|
1001
|
+
* so it is attributed to the tool itself (`tool` · toolName), never to the parent's model. */
|
|
1002
|
+
/** A tool result names no provider/model: it is attributed to the tool itself, never to the
|
|
1003
|
+
* parent's model. pi-subagents does not set `totalFromProvider` on that usage, so child spend
|
|
1004
|
+
* always lands in the estimated part of the cell (`~`) even when the children were billed. */
|
|
1005
|
+
const attributionOf = (
|
|
1006
|
+
m: { role: string; provider?: string; model?: string; toolName?: string },
|
|
1007
|
+
u: MessageUsage,
|
|
1008
|
+
): { provider: string | undefined; model: string | undefined } =>
|
|
1009
|
+
m.role === "toolResult"
|
|
1010
|
+
? { provider: u.provider ?? TOOL_PROVIDER, model: u.model ?? m.toolName ?? TOOL_PROVIDER }
|
|
1011
|
+
: { provider: m.provider, model: m.model };
|
|
1012
|
+
|
|
1013
|
+
/** Billed vs estimated split of one message's usage: a provider-billed total goes to
|
|
1014
|
+
* `costBilled`, a catalog total (pi's own estimate) to `costEstimated`, and a message that
|
|
1015
|
+
* carried no cost at all is recomputed from the price table, cache writes included. */
|
|
1016
|
+
const costSplitOf = (
|
|
1017
|
+
u: MessageUsage,
|
|
1018
|
+
provider: string | undefined,
|
|
1019
|
+
model: string | undefined,
|
|
1020
|
+
table: PriceTable,
|
|
1021
|
+
): { costBilled: number; costEstimated: number } => {
|
|
1022
|
+
const total = u.cost?.total || 0;
|
|
1023
|
+
if (u.cost?.totalFromProvider === true) return { costBilled: total, costEstimated: 0 };
|
|
1024
|
+
if (total > 0) return { costBilled: 0, costEstimated: total };
|
|
1025
|
+
const est = provider && model ? estimateCost(u.input || 0, u.output || 0, u.cacheRead || 0, u.cacheWrite || 0, model, provider, table) : null;
|
|
1026
|
+
return { costBilled: 0, costEstimated: est ?? 0 };
|
|
1027
|
+
};
|
|
1028
|
+
|
|
1029
|
+
const lastUsageOf = (branch: readonly unknown[], table: PriceTable): UsageTotals => {
|
|
1030
|
+
const zeros: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
|
|
1031
|
+
const last = branch[branch.length - 1] as
|
|
1032
|
+
| {
|
|
1033
|
+
type?: string;
|
|
1034
|
+
message?: { role?: string; provider?: string; model?: string; toolName?: string; usage?: MessageUsage };
|
|
1035
|
+
}
|
|
1036
|
+
| undefined;
|
|
1037
|
+
const m = last?.type === "message" ? last.message : undefined;
|
|
1038
|
+
const role = m?.role;
|
|
1039
|
+
const assistant = role === "assistant";
|
|
1040
|
+
const u = role === "assistant" || role === "toolResult" ? m!.usage : undefined;
|
|
1041
|
+
if (!hasUsage(u)) {
|
|
1042
|
+
zeros.assistant = assistant;
|
|
1043
|
+
return zeros;
|
|
1044
|
+
}
|
|
1045
|
+
const { provider, model } = attributionOf(m!, u);
|
|
1046
|
+
const { costBilled, costEstimated } = costSplitOf(u, provider, model, table);
|
|
1047
|
+
return { inp: u.input || 0, out: u.output || 0, read: u.cacheRead || 0, costBilled, costEstimated, assistant };
|
|
1048
|
+
};
|
|
1049
|
+
|
|
1050
|
+
/** No burn rate below five minutes of active time: dividing a two-minute clock prints nonsense. */
|
|
1051
|
+
export const RATE_MIN_ACTIVE_MS = 5 * 60_000;
|
|
1052
|
+
/** Terminals narrower than this drop the rate — the cost alone still fits. */
|
|
1053
|
+
export const RATE_MIN_WIDTH = 80;
|
|
1054
|
+
|
|
1055
|
+
/** The session cost cell, with the burn rate appended in parentheses (one cell, not two): `$0.42 ($1.80/h)`.
|
|
1056
|
+
* Billed and estimated never blend: `$0.42` when only the provider billed, `~$0.42` when only
|
|
1057
|
+
* an estimate exists, `$0.30 + ~$0.12` when the branch has both, and no cell at all when there
|
|
1058
|
+
* is no cost — the same promise `/usage` makes. The rate is cost per ACTIVE hour — the clock
|
|
1059
|
+
* counts active time (idle pauses excluded), not wall-clock — so it is labelled `$/h`; it
|
|
1060
|
+
* carries the `~` whenever estimated cost feeds it, like the estimated part of the cell, and
|
|
1061
|
+
* is hidden below RATE_MIN_ACTIVE_MS of active time and below RATE_MIN_WIDTH columns.
|
|
1062
|
+
* `bandPaint` paints the whole cell (icon and text) when a budget cap is near or over —
|
|
1063
|
+
* amber at `warn`, red at `over` (see `budgetLevelNow`); without it the icon keeps `acc` and
|
|
1064
|
+
* the text `soft`. The rate suffix is secondary information, so it renders `dim` (or the band
|
|
1065
|
+
* paint when a cap is active, keeping the alert one colour). */
|
|
1066
|
+
export function costCell(
|
|
1067
|
+
costBilled: number,
|
|
1068
|
+
costEstimated: number,
|
|
1069
|
+
acc: (t: string) => string,
|
|
1070
|
+
soft: (t: string) => string,
|
|
1071
|
+
width: number = RATE_MIN_WIDTH,
|
|
1072
|
+
bandPaint?: (t: string) => string,
|
|
1073
|
+
dim?: (t: string) => string,
|
|
1074
|
+
): string {
|
|
1075
|
+
if (!(costBilled > 0) && !(costEstimated > 0)) return "";
|
|
1076
|
+
const parts: string[] = [];
|
|
1077
|
+
if (costBilled > 0) parts.push(formatCost(costBilled));
|
|
1078
|
+
if (costEstimated > 0) parts.push(`~${formatCost(costEstimated)}`);
|
|
1079
|
+
const text = parts.join(" + ");
|
|
1080
|
+
let rate = "";
|
|
1081
|
+
const activeMs = clock.total();
|
|
1082
|
+
if (activeMs >= RATE_MIN_ACTIVE_MS && width >= RATE_MIN_WIDTH) {
|
|
1083
|
+
const perHour = (costBilled + costEstimated) / (activeMs / 3_600_000);
|
|
1084
|
+
rate = `(${costEstimated > 0 ? "~" : ""}${formatCost(perHour)}/h)`;
|
|
1085
|
+
}
|
|
1086
|
+
const cell = `${(bandPaint ?? acc)("\uf155")} ${(bandPaint ?? soft)(text)}`;
|
|
1087
|
+
return rate ? `${cell} ${(bandPaint ?? dim ?? soft)(rate)}` : cell;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
// 2s cache + branch length: the footer renders on every poke/stream tick, so
|
|
1091
|
+
// without this every frame rescans the whole branch (O(N) per frame).
|
|
1092
|
+
export function getUsage(
|
|
1093
|
+
ctx: {
|
|
1094
|
+
sessionManager: { getBranch(): readonly unknown[] };
|
|
1095
|
+
getContextUsage(): { tokens: number | null; contextWindow: number; percent: number | null } | undefined;
|
|
1096
|
+
model?: { id?: string; provider?: string };
|
|
1097
|
+
},
|
|
1098
|
+
acc: (t: string) => string,
|
|
1099
|
+
soft: (t: string) => string,
|
|
1100
|
+
/** Off by default: the cost cell is opt-in (`/arnative` → Footers → `[c]`). */
|
|
1101
|
+
showCost: boolean = activeFooterCost(),
|
|
1102
|
+
/** Terminal width: the burn rate is dropped below RATE_MIN_WIDTH columns. */
|
|
1103
|
+
width: number = RATE_MIN_WIDTH,
|
|
1104
|
+
/** Budget band painter for the cost cell (amber at `warn`, red at `over`); absent keeps acc/soft. */
|
|
1105
|
+
bandPaint?: (t: string) => string,
|
|
1106
|
+
/** Painter for the divider that opens the cost group; the caller passes the footer `dim`. */
|
|
1107
|
+
dim: (t: string) => string = soft,
|
|
1108
|
+
): string {
|
|
1109
|
+
const branch = ctx.sessionManager.getBranch();
|
|
1110
|
+
const leaf = branch[branch.length - 1];
|
|
1111
|
+
const cacheFresh = Date.now() - usageScanAt < 2000 && branch.length === usageScanLen && ctx.sessionManager === usageScanManager && leaf === usageScanLeaf;
|
|
1112
|
+
// Memoized on models.json's stat; reuse the cached table during the 2s window to avoid statSync per frame.
|
|
1113
|
+
const priceTable = cacheFresh && usageScanPriceTable ? usageScanPriceTable : loadPriceTable();
|
|
1114
|
+
const last = lastUsageOf(branch, priceTable);
|
|
1115
|
+
let inp = 0;
|
|
1116
|
+
let out = 0;
|
|
1117
|
+
let read = 0;
|
|
1118
|
+
let costBilled = 0;
|
|
1119
|
+
let costEstimated = 0;
|
|
1120
|
+
let winInp = 0;
|
|
1121
|
+
let winRead = 0;
|
|
1122
|
+
if (cacheFresh) {
|
|
1123
|
+
// Cached sums + the streaming delta of the last message (mutated in place).
|
|
1124
|
+
inp = usageScanNums.inp + last.inp - usageScanLast.inp;
|
|
1125
|
+
out = usageScanNums.out + last.out - usageScanLast.out;
|
|
1126
|
+
read = usageScanNums.read + last.read - usageScanLast.read;
|
|
1127
|
+
costBilled = usageScanNums.costBilled + last.costBilled - usageScanLast.costBilled;
|
|
1128
|
+
costEstimated = usageScanNums.costEstimated + last.costEstimated - usageScanLast.costEstimated;
|
|
1129
|
+
// The window covers assistant messages only, so the in-place delta of the last
|
|
1130
|
+
// entry lands in it exactly when that entry is an assistant message in the window.
|
|
1131
|
+
winInp = usageScanWin.inp + (usageScanWinLast ? last.inp - usageScanWinLast.inp : 0);
|
|
1132
|
+
winRead = usageScanWin.read + (usageScanWinLast ? last.read - usageScanWinLast.read : 0);
|
|
1133
|
+
} else {
|
|
1134
|
+
// (input, cacheRead) of the trailing assistant messages, capped so the window below
|
|
1135
|
+
// is the last CACHE_WINDOW_MSGS of them once the first two are skipped.
|
|
1136
|
+
const assist: [number, number][] = [];
|
|
1137
|
+
for (const e of branch) {
|
|
1138
|
+
if (!e || typeof e !== "object" || !("type" in e) || e.type !== "message") continue;
|
|
1139
|
+
const m = (e as { message?: unknown }).message as
|
|
1140
|
+
| { role?: string; provider?: string; model?: string; toolName?: string; usage?: MessageUsage }
|
|
1141
|
+
| undefined;
|
|
1142
|
+
// Assistant messages carry their own call's usage; a tool result carries the child
|
|
1143
|
+
// (subagent / nested tool) spend — pi puts that nowhere else, so summing both roles
|
|
1144
|
+
// counts every token once, never twice.
|
|
1145
|
+
if (!m || (m.role !== "assistant" && m.role !== "toolResult")) continue;
|
|
1146
|
+
const u = m.usage;
|
|
1147
|
+
if (m.role === "assistant") {
|
|
1148
|
+
assist.push([u?.input || 0, u?.cacheRead || 0]);
|
|
1149
|
+
if (assist.length > CACHE_WINDOW_MSGS + 2) assist.shift();
|
|
1150
|
+
}
|
|
1151
|
+
if (!hasUsage(u)) continue;
|
|
1152
|
+
inp += u.input || 0;
|
|
1153
|
+
out += u.output || 0;
|
|
1154
|
+
read += u.cacheRead || 0;
|
|
1155
|
+
const { provider, model } = attributionOf(m, u);
|
|
1156
|
+
const split = costSplitOf(u, provider, model, priceTable);
|
|
1157
|
+
costBilled += split.costBilled;
|
|
1158
|
+
costEstimated += split.costEstimated;
|
|
1159
|
+
}
|
|
1160
|
+
usageScanNums = { inp, out, read, costBilled, costEstimated };
|
|
1161
|
+
usageScanLast = last;
|
|
1162
|
+
usageScanAt = Date.now();
|
|
1163
|
+
usageScanLen = branch.length;
|
|
1164
|
+
// Windowed cache rate, computed in this same pass: the last CACHE_WINDOW_MSGS
|
|
1165
|
+
// assistant messages, the session's first two skipped (turn 1 is always cold).
|
|
1166
|
+
const win = assist.slice(Math.max(2, assist.length - CACHE_WINDOW_MSGS));
|
|
1167
|
+
for (const [wi, wr] of win) {
|
|
1168
|
+
winInp += wi;
|
|
1169
|
+
winRead += wr;
|
|
1170
|
+
}
|
|
1171
|
+
usageScanWin = { inp: winInp, read: winRead };
|
|
1172
|
+
usageScanWinLast = last.assistant === true && assist.length > 2 ? { inp: last.inp, read: last.read } : null;
|
|
1173
|
+
usageScanManager = ctx.sessionManager;
|
|
1174
|
+
usageScanLeaf = leaf;
|
|
1175
|
+
usageScanPriceTable = priceTable;
|
|
1176
|
+
}
|
|
1177
|
+
usageTotals = { inp, read };
|
|
1178
|
+
usageWindow = { inp: winInp, read: winRead };
|
|
1179
|
+
const parts: string[] = [];
|
|
1180
|
+
if (inp > 0) parts.push(`${acc("↑")}${soft(formatTokens(inp))}`);
|
|
1181
|
+
if (out > 0) parts.push(`${acc("↓")}${soft(formatTokens(out))}`);
|
|
1182
|
+
if (read > 0) parts.push(`${acc("\uf49b")} ${soft(formatTokens(read))}`);
|
|
1183
|
+
const u = ctx.getContextUsage();
|
|
1184
|
+
if (u && u.percent !== null && u.tokens !== null) {
|
|
1185
|
+
parts.push(`${acc("\ueb85")} ${soft(`${u.percent.toFixed(1)}%/${formatTokens(u.contextWindow)}`)}`);
|
|
1186
|
+
}
|
|
1187
|
+
if (showCost) {
|
|
1188
|
+
const cell = costCell(costBilled, costEstimated, acc, soft, width, bandPaint, dim);
|
|
1189
|
+
// The dollar icon opens a new group, so it takes the same divider the footer uses
|
|
1190
|
+
// between cells; the token and context parts stay a space apart.
|
|
1191
|
+
if (cell) parts.push(parts.length > 0 ? `${dim("·")} ${cell}` : cell);
|
|
1192
|
+
}
|
|
1193
|
+
return parts.join(" ");
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
let editorTui: { requestRender?: () => void } | null = null;
|
|
1197
|
+
|
|
1198
|
+
function poke(): void {
|
|
1199
|
+
try {
|
|
1200
|
+
if (rerender) rerender();
|
|
1201
|
+
else editorTui?.requestRender?.();
|
|
1202
|
+
} catch {
|
|
1203
|
+
// ignore
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
bindChatboxPoke(poke);
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* Tool name → active progress text (gerund).
|
|
1210
|
+
* Fallback when unregistered: "Working".
|
|
1211
|
+
*/
|
|
1212
|
+
// Verb for an MCP sub-action (shared by the `mcp` and `mcp__*` tool names).
|
|
1213
|
+
function mcpStatusOf(sub: string): string {
|
|
1214
|
+
if (sub.includes("search") || sub.includes("find")) return "Searching";
|
|
1215
|
+
if (sub.includes("fetch") || sub.includes("get") || sub.includes("read")) return "Fetching";
|
|
1216
|
+
if (sub.includes("edit") || sub.includes("write") || sub.includes("patch")) return "Editing";
|
|
1217
|
+
return "Executing";
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
/**
|
|
1221
|
+
* The spinner is one preset out of `lib/spinner.ts`, chosen through `/arnative` →
|
|
1222
|
+
* **Animations** and persisted in `arnative-config.json`. `Pi (system)` hands the slot back
|
|
1223
|
+
* to pi's own Braille indicator; every other preset installs its own frames and painter.
|
|
1224
|
+
* The frames are read fresh on each `session_start`, so a preset picked mid-session applies
|
|
1225
|
+
* on the next reload without re-registering the handler.
|
|
1226
|
+
*/
|
|
1227
|
+
/** Loader label with the elapsed suffix; no suffix below 1s (avoids a "(0s)" flicker). */
|
|
1228
|
+
export function workingLabel(verb: string, elapsedMs: number): string {
|
|
1229
|
+
return elapsedMs >= 1000 ? `${verb} (${formatDuration(elapsedMs)})` : verb;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
function paintWorking(): void {
|
|
1233
|
+
if (!workUI || workStartMs === null) return;
|
|
1234
|
+
try {
|
|
1235
|
+
workUI.setWorkingMessage?.(workingLabel(workVerb, Date.now() - workStartMs));
|
|
1236
|
+
} catch {
|
|
1237
|
+
// ignore
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
function stopWorkingClock(): void {
|
|
1242
|
+
workStartMs = null;
|
|
1243
|
+
workUI = null;
|
|
1244
|
+
activeToolVerbs.clear();
|
|
1245
|
+
const rt = getRuntime();
|
|
1246
|
+
if (rt.idleTimer === null || clock.idle()) stopClockTick();
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
let idlePauseShown = false;
|
|
1250
|
+
|
|
1251
|
+
/** Single 1s ticker shared by the active footer clock and the working-indicator elapsed label. */
|
|
1252
|
+
function startClockTick(): void {
|
|
1253
|
+
const rt = getRuntime();
|
|
1254
|
+
if (rt.clockTimer !== null) return;
|
|
1255
|
+
rt.clockTimer = setInterval(() => {
|
|
1256
|
+
const working = workStartMs !== null;
|
|
1257
|
+
const idle = clock.idle();
|
|
1258
|
+
if (working) paintWorking();
|
|
1259
|
+
if (!idle) poke();
|
|
1260
|
+
if (!working && (getRuntime().idleTimer === null || idle)) stopClockTick();
|
|
1261
|
+
}, 1000);
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
function stopClockTick(): void {
|
|
1265
|
+
const rt = getRuntime();
|
|
1266
|
+
if (rt.clockTimer) clearInterval(rt.clockTimer);
|
|
1267
|
+
rt.clockTimer = null;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
/** Repaint a frozen clock on the first activity, instead of waiting for the next tick. */
|
|
1271
|
+
export function repaintIdle(now: number = Date.now()): void {
|
|
1272
|
+
if (!clock.idle(now) || idlePauseShown) return;
|
|
1273
|
+
poke();
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/** Intercepts terminal input on TuiBase to register keystroke activity. */
|
|
1277
|
+
export function wrapInputListener(tui: unknown): () => void {
|
|
1278
|
+
const rt = getRuntime();
|
|
1279
|
+
rt.activityHook = (data: string) => {
|
|
1280
|
+
if (isPointerOrFocusInput(data)) return;
|
|
1281
|
+
clock.tick();
|
|
1282
|
+
repaintIdle();
|
|
1283
|
+
armIdleProbe();
|
|
1284
|
+
};
|
|
1285
|
+
const target = tui as { handleTerminalInput?: (data: string) => void };
|
|
1286
|
+
if (!target || typeof target.handleTerminalInput !== "function") return () => {};
|
|
1287
|
+
const wrapped = rt.wrappedTuis;
|
|
1288
|
+
if (!wrapped.has(target)) {
|
|
1289
|
+
wrapped.add(target);
|
|
1290
|
+
const original = target.handleTerminalInput;
|
|
1291
|
+
target.handleTerminalInput = function (this: unknown, data: string): void {
|
|
1292
|
+
// One keystroke, one activity. The wrapper runs before `original`, and `pi-tui`
|
|
1293
|
+
// has a single caller for it (`terminal.start`), so there is nothing to dedupe.
|
|
1294
|
+
try {
|
|
1295
|
+
getRuntime().activityHook?.(data);
|
|
1296
|
+
} catch {
|
|
1297
|
+
// activity bookkeeping must never break input
|
|
1298
|
+
}
|
|
1299
|
+
original.call(this, data);
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
return () => {
|
|
1303
|
+
// Only the hook is torn down; the wrapper stays, since a reload re-registers it.
|
|
1304
|
+
getRuntime().activityHook = null;
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
/** Past the boundary, where `idle()` is still false because it is a strict `>` (~one frame). */
|
|
1309
|
+
const IDLE_PROBE_EPSILON_MS = 25;
|
|
1310
|
+
|
|
1311
|
+
let lastIdleArmMs = 0;
|
|
1312
|
+
|
|
1313
|
+
export function armIdleProbe(now: number = Date.now(), opts?: { repaint?: boolean }): void {
|
|
1314
|
+
const rt = getRuntime();
|
|
1315
|
+
const shouldRepaint = opts?.repaint ?? true;
|
|
1316
|
+
const shouldRearm = !rt.idleTimer || shouldRepaint || now - lastIdleArmMs >= 1000;
|
|
1317
|
+
if (shouldRearm) {
|
|
1318
|
+
if (rt.idleTimer) clearTimeout(rt.idleTimer);
|
|
1319
|
+
lastIdleArmMs = now;
|
|
1320
|
+
const wait = Math.max(0, clock.pauseMs - (now - clock.lastSeen)) + IDLE_PROBE_EPSILON_MS;
|
|
1321
|
+
const timer = setTimeout(() => {
|
|
1322
|
+
getRuntime().idleTimer = null;
|
|
1323
|
+
if (!clock.idle()) {
|
|
1324
|
+
armIdleProbe(Date.now(), { repaint: false });
|
|
1325
|
+
return;
|
|
1326
|
+
}
|
|
1327
|
+
idlePauseShown = true;
|
|
1328
|
+
if (workStartMs === null) stopClockTick();
|
|
1329
|
+
poke();
|
|
1330
|
+
}, wait);
|
|
1331
|
+
timer.unref?.();
|
|
1332
|
+
rt.idleTimer = timer;
|
|
1333
|
+
}
|
|
1334
|
+
startClockTick();
|
|
1335
|
+
if (shouldRepaint || idlePauseShown) poke();
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/** Stop the idle machinery: the one-shot probe and the moving clock tick. */
|
|
1339
|
+
export function stopIdleProbe(): void {
|
|
1340
|
+
const rt = getRuntime();
|
|
1341
|
+
if (rt.idleTimer) clearTimeout(rt.idleTimer);
|
|
1342
|
+
rt.idleTimer = null;
|
|
1343
|
+
if (workStartMs === null) stopClockTick();
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
/** Start (or restart) the 1s tick from a fresh turn, reusing the shared clock ticker. */
|
|
1347
|
+
function startWorkingClock(ctx: { ui?: WorkingUiSurface }): void {
|
|
1348
|
+
stopWorkingClock();
|
|
1349
|
+
workUI = ctx.ui ?? null;
|
|
1350
|
+
workVerb = WORK_LABEL;
|
|
1351
|
+
workStartMs = Date.now();
|
|
1352
|
+
startClockTick();
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
/** Swap the verb (tool change) without resetting the turn clock. */
|
|
1356
|
+
function setWorkingVerb(ctx: { ui?: WorkingUiSurface }, verb: string): void {
|
|
1357
|
+
workUI = ctx.ui ?? null;
|
|
1358
|
+
workVerb = verb;
|
|
1359
|
+
if (workStartMs === null) workStartMs = Date.now();
|
|
1360
|
+
paintWorking();
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
export function getToolWorkingMessage(toolName: string, args?: Record<string, unknown>): string {
|
|
1364
|
+
const n = (toolName ?? "").trim();
|
|
1365
|
+
if (!n) return WORK_LABEL;
|
|
1366
|
+
|
|
1367
|
+
// Standard / file tools
|
|
1368
|
+
if (n === "edit") return "Editing";
|
|
1369
|
+
if (n === "write") return "Writing";
|
|
1370
|
+
if (n === "read") return "Reading";
|
|
1371
|
+
if (n === "grep" || n === "find" || n === "web_search" || n === "source_check") return "Searching";
|
|
1372
|
+
if (n === "bash") return "Executing";
|
|
1373
|
+
if (n === "fetch_content") return "Fetching";
|
|
1374
|
+
if (n === "get_search_content") return "Reading";
|
|
1375
|
+
if (n === "generate_image") return "Generating image";
|
|
1376
|
+
if (n === "todo" || n === "scratchpad") return "Updating tasks";
|
|
1377
|
+
if (n.startsWith("memory_")) return "Accessing memory";
|
|
1378
|
+
if (n.startsWith("lsp_")) return "Checking code";
|
|
1379
|
+
if (n.startsWith("chrome_devtools_")) return "Browsing";
|
|
1380
|
+
if (n === "ask_user_question" || n === "plan_mode_question") return "Waiting for input";
|
|
1381
|
+
|
|
1382
|
+
// MCP tools (mcp / mcpScript / mcp__*)
|
|
1383
|
+
if (n === "mcpScript") return "Running script";
|
|
1384
|
+
if (n === "mcp") {
|
|
1385
|
+
const sub = typeof args === "object" && args ? (args.tool || args.search || args.describe || args.action) : "";
|
|
1386
|
+
return sub ? mcpStatusOf(String(sub).toLowerCase()) : "Executing";
|
|
1387
|
+
}
|
|
1388
|
+
if (n.startsWith("mcp__")) {
|
|
1389
|
+
const sub = typeof args === "object" && args?.tool ? String(args.tool).toLowerCase() : "";
|
|
1390
|
+
return mcpStatusOf(sub);
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
return WORK_LABEL;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
export default function (pi: ExtensionAPI) {
|
|
1397
|
+
let runtimeGen = 0;
|
|
1398
|
+
|
|
1399
|
+
// Keyboard path for the minimal footer's disclosure: mouse clicks only exist in
|
|
1400
|
+
// fullscreen mode, so pi's own rule ("always design a keyboard path") needs this.
|
|
1401
|
+
// One key toggles both sides: expand all unless everything is already open.
|
|
1402
|
+
const toggleMinimal = () => {
|
|
1403
|
+
if (activeFooterPreset() === "Zen") {
|
|
1404
|
+
const state = zenExpanded();
|
|
1405
|
+
if (state.detail === null && !state.git) {
|
|
1406
|
+
state.detail = "left";
|
|
1407
|
+
state.git = true;
|
|
1408
|
+
} else if (state.detail === "left") {
|
|
1409
|
+
state.detail = "right";
|
|
1410
|
+
} else {
|
|
1411
|
+
state.detail = null;
|
|
1412
|
+
state.git = false;
|
|
1413
|
+
}
|
|
1414
|
+
poke();
|
|
1415
|
+
return;
|
|
1416
|
+
}
|
|
1417
|
+
const state = minimalExpanded();
|
|
1418
|
+
const allOpen = state.left && state.right;
|
|
1419
|
+
state.left = !allOpen;
|
|
1420
|
+
state.right = !allOpen;
|
|
1421
|
+
poke();
|
|
1422
|
+
};
|
|
1423
|
+
for (const key of SHORTCUT_TOGGLE_FOOTER.keys) {
|
|
1424
|
+
pi.registerShortcut(key, { description: "Expand/collapse the minimal footer", handler: toggleMinimal });
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
// Assistant speed timer (user message timestamps come from lib/features/timestamps.ts).
|
|
1428
|
+
// Reset for every role: a user or tool message between two assistant runs must not
|
|
1429
|
+
// leave the previous run's start time behind, or the next speed reads a stale elapsed.
|
|
1430
|
+
pi.on("message_start", async (event) => {
|
|
1431
|
+
if (event.message.role === "assistant") {
|
|
1432
|
+
assistantStartMs = Date.now();
|
|
1433
|
+
assistantChars = 0;
|
|
1434
|
+
} else {
|
|
1435
|
+
assistantStartMs = null;
|
|
1436
|
+
assistantChars = 0;
|
|
1437
|
+
}
|
|
1438
|
+
});
|
|
1439
|
+
|
|
1440
|
+
pi.on("session_start", async (event, ctx) => {
|
|
1441
|
+
// A /reload re-imports this module while the old instance's timers (and its
|
|
1442
|
+
// ctx.ui closures) may still be alive; clear every RuntimeState timer handle first.
|
|
1443
|
+
const rt = getRuntime();
|
|
1444
|
+
stopWorkingClock();
|
|
1445
|
+
stopIdleProbe();
|
|
1446
|
+
if (event.reason !== "reload") {
|
|
1447
|
+
rt.activeClock = null;
|
|
1448
|
+
clock = new ActiveClock(resolveSessionStartMs(event.reason, ctx.sessionManager.getHeader()?.timestamp, Date.now()));
|
|
1449
|
+
try {
|
|
1450
|
+
const now = Date.now();
|
|
1451
|
+
clock.active = seedActiveMs(ctx.sessionManager.getEntries(), IDLE_PAUSE_MS, now);
|
|
1452
|
+
clock.runStarted = now;
|
|
1453
|
+
clock.lastSeen = now;
|
|
1454
|
+
} catch {
|
|
1455
|
+
// unreadable log -> start from now
|
|
1456
|
+
}
|
|
1457
|
+
idlePauseShown = false;
|
|
1458
|
+
currentModel = ctx.model;
|
|
1459
|
+
currentThinkingLevel = ctx.thinkingLevel;
|
|
1460
|
+
git = null;
|
|
1461
|
+
// A new session reuses this module (no re-import), so the 2s cache would serve the
|
|
1462
|
+
// previous session's sums whenever the fresh branch happens to be the same length.
|
|
1463
|
+
usageScanAt = 0;
|
|
1464
|
+
usageScanLen = -1;
|
|
1465
|
+
usageScanManager = undefined;
|
|
1466
|
+
usageScanLeaf = undefined;
|
|
1467
|
+
usageScanPriceTable = null;
|
|
1468
|
+
piStatsCache = null;
|
|
1469
|
+
} else {
|
|
1470
|
+
currentModel = (rt.currentModel as typeof currentModel) ?? ctx.model;
|
|
1471
|
+
currentThinkingLevel = (rt.currentThinking as typeof currentThinkingLevel) ?? ctx.thinkingLevel;
|
|
1472
|
+
git = (rt.lastGit as GitInfo) ?? null;
|
|
1473
|
+
}
|
|
1474
|
+
rt.currentModel = currentModel;
|
|
1475
|
+
rt.currentThinking = currentThinkingLevel;
|
|
1476
|
+
rt.lastGit = git;
|
|
1477
|
+
activeThemeProxy = ((ctx as unknown as { ui?: { theme?: typeof activeThemeProxy } }).ui?.theme) ?? activeThemeProxy;
|
|
1478
|
+
if (activeThemeProxy) setActiveTheme(activeThemeProxy);
|
|
1479
|
+
setWorkingUi(ctx.ui);
|
|
1480
|
+
|
|
1481
|
+
const cwd = (event.reason === "reload" && rt.lastCwd) ? rt.lastCwd : ctx.cwd;
|
|
1482
|
+
rt.lastCwd = cwd;
|
|
1483
|
+
|
|
1484
|
+
runtimeGen = ++footerGen;
|
|
1485
|
+
rt.footerGen = footerGen;
|
|
1486
|
+
|
|
1487
|
+
try {
|
|
1488
|
+
armIdleProbe();
|
|
1489
|
+
const registerArnative = (c: ExtensionContext) => {
|
|
1490
|
+
c.ui.setFooter((tui, theme, footerData) => {
|
|
1491
|
+
activeThemeProxy = theme;
|
|
1492
|
+
// Wraps the dispatch (see `wrapInputListener`): the TUI's own viewport
|
|
1493
|
+
// listener runs first and would swallow the keys an `addInputListener` waits for.
|
|
1494
|
+
const dot = wrapInputListener(tui);
|
|
1495
|
+
rerender = () => tui.requestRender();
|
|
1496
|
+
const unsub = footerData.onBranchChange(() => {
|
|
1497
|
+
void refreshGit(cwd, { force: true }).then(() => tui.requestRender());
|
|
1498
|
+
});
|
|
1499
|
+
// Swallows the follow-up release/click after a press on the ▲/▼ arrow so it never toggles twice.
|
|
1500
|
+
let swallowMinimalClick = false;
|
|
1501
|
+
return {
|
|
1502
|
+
dispose() {
|
|
1503
|
+
rerender = null;
|
|
1504
|
+
dot();
|
|
1505
|
+
unsub();
|
|
1506
|
+
if (gitRefreshTrailing) {
|
|
1507
|
+
clearTimeout(gitRefreshTrailing);
|
|
1508
|
+
gitRefreshTrailing = null;
|
|
1509
|
+
}
|
|
1510
|
+
themeCache = null;
|
|
1511
|
+
gitCache = null;
|
|
1512
|
+
},
|
|
1513
|
+
invalidate() {},
|
|
1514
|
+
render(width: number): string[] {
|
|
1515
|
+
// Painters and the cwd/model/git segments only change when their inputs do
|
|
1516
|
+
// (theme, cwd, model, thinking level, git info). The footer re-renders on every
|
|
1517
|
+
// stream tick and clock tick, so rebuilding them per frame was pure waste.
|
|
1518
|
+
if (themeCache?.theme !== theme) {
|
|
1519
|
+
const acc = (text: string) => theme.fg("accent", text);
|
|
1520
|
+
const dim = (text: string) => theme.fg("dim", text);
|
|
1521
|
+
// `accentSoft`/`secondarySoft` are vars-only tokens on Pi 1.2+, so both soft tiers
|
|
1522
|
+
// are resolved through the shared painters instead of a raw fg() probe. Icons keep
|
|
1523
|
+
// `accent`; the cwd/branch/clock/status text takes the border-accent tier, so the
|
|
1524
|
+
// footer stays two-toned instead of the text inheriting the accent hue.
|
|
1525
|
+
const soft = softOf(theme as never);
|
|
1526
|
+
const softLabel = softSecondaryOf(theme as never);
|
|
1527
|
+
// Diff colors: the same theme slots pi uses for a diff body, with the
|
|
1528
|
+
// plain soft color as fallback for a theme that omits them. Optional tokens are
|
|
1529
|
+
// probed once per theme (fgOr), not thrown-and-caught on every frame.
|
|
1530
|
+
const colorOr = (name: string, fallback: (t: string) => string) => fgOr(theme, name, fallback);
|
|
1531
|
+
themeCache = {
|
|
1532
|
+
theme,
|
|
1533
|
+
acc,
|
|
1534
|
+
dim,
|
|
1535
|
+
soft,
|
|
1536
|
+
colorOr,
|
|
1537
|
+
primary: colorOr("mdHeading", acc),
|
|
1538
|
+
secondarySoft: softLabel,
|
|
1539
|
+
diffAdd: colorOr("toolDiffAdded", soft),
|
|
1540
|
+
diffDel: colorOr("toolDiffRemoved", soft),
|
|
1541
|
+
sep: ` ${dim("·")} `,
|
|
1542
|
+
};
|
|
1543
|
+
}
|
|
1544
|
+
const { acc, dim, soft, colorOr, primary, secondarySoft, diffAdd, diffDel, sep } = themeCache!;
|
|
1545
|
+
const preset = activeFooterPreset();
|
|
1546
|
+
|
|
1547
|
+
if (preset === "Pi (color)") {
|
|
1548
|
+
minimalRanges = null;
|
|
1549
|
+
zenRanges = null;
|
|
1550
|
+
const statuses: ReadonlyMap<string, string> = (() => {
|
|
1551
|
+
try {
|
|
1552
|
+
return footerData.getExtensionStatuses();
|
|
1553
|
+
} catch {
|
|
1554
|
+
return new Map<string, string>();
|
|
1555
|
+
}
|
|
1556
|
+
})();
|
|
1557
|
+
const branch = (() => {
|
|
1558
|
+
try {
|
|
1559
|
+
return footerData.getGitBranch();
|
|
1560
|
+
} catch {
|
|
1561
|
+
return null;
|
|
1562
|
+
}
|
|
1563
|
+
})();
|
|
1564
|
+
const availableProviderCount = (() => {
|
|
1565
|
+
try {
|
|
1566
|
+
return footerData.getAvailableProviderCount();
|
|
1567
|
+
} catch {
|
|
1568
|
+
return 0;
|
|
1569
|
+
}
|
|
1570
|
+
})();
|
|
1571
|
+
const sessionMgr = ctx.sessionManager as unknown as {
|
|
1572
|
+
getEntries(): readonly unknown[];
|
|
1573
|
+
getLeafId?: () => string | null;
|
|
1574
|
+
getSessionId?: () => string;
|
|
1575
|
+
getCwd?: () => string;
|
|
1576
|
+
getSessionName?: () => string | undefined;
|
|
1577
|
+
};
|
|
1578
|
+
const stats = collectPiSessionStats(sessionMgr);
|
|
1579
|
+
const contextUsage = (() => {
|
|
1580
|
+
try {
|
|
1581
|
+
return ctx.getContextUsage();
|
|
1582
|
+
} catch {
|
|
1583
|
+
return undefined;
|
|
1584
|
+
}
|
|
1585
|
+
})();
|
|
1586
|
+
const model = (ctx.model ?? currentModel) as { id: string; provider?: string; reasoning?: boolean; contextWindow?: number } | undefined;
|
|
1587
|
+
const liveThinkingLevel = (() => {
|
|
1588
|
+
try {
|
|
1589
|
+
return (pi as unknown as { getThinkingLevel?: () => string | undefined }).getThinkingLevel?.();
|
|
1590
|
+
} catch {
|
|
1591
|
+
return undefined;
|
|
1592
|
+
}
|
|
1593
|
+
})() ?? ctx.thinkingLevel ?? currentThinkingLevel;
|
|
1594
|
+
const autoCompactEnabled = (() => {
|
|
1595
|
+
try {
|
|
1596
|
+
const s = (pi as unknown as { getSettings?: () => { compaction?: { enabled?: boolean } } }).getSettings?.();
|
|
1597
|
+
return s?.compaction?.enabled !== false;
|
|
1598
|
+
} catch {
|
|
1599
|
+
return true;
|
|
1600
|
+
}
|
|
1601
|
+
})();
|
|
1602
|
+
const usingSubscription = Boolean(
|
|
1603
|
+
model && (
|
|
1604
|
+
model.provider === "kimi-coding" ||
|
|
1605
|
+
(ctx as unknown as { modelRegistry?: { isUsingOAuth?: (m: unknown) => boolean } }).modelRegistry?.isUsingOAuth?.(model)
|
|
1606
|
+
),
|
|
1607
|
+
);
|
|
1608
|
+
return renderPiColorFooter({
|
|
1609
|
+
cwd: sessionMgr.getCwd?.() ?? cwd,
|
|
1610
|
+
branch,
|
|
1611
|
+
sessionName: sessionMgr.getSessionName?.(),
|
|
1612
|
+
stats,
|
|
1613
|
+
usingSubscription,
|
|
1614
|
+
budgetBand: budgetLevelNow(),
|
|
1615
|
+
contextPercent: contextUsage?.percent ?? null,
|
|
1616
|
+
contextWindow: contextUsage?.contextWindow ?? model?.contextWindow ?? 0,
|
|
1617
|
+
autoCompactEnabled,
|
|
1618
|
+
experimental: process.env.PI_EXPERIMENTAL === "1",
|
|
1619
|
+
model,
|
|
1620
|
+
thinkingLevel: liveThinkingLevel,
|
|
1621
|
+
availableProviderCount,
|
|
1622
|
+
extensionStatuses: statuses,
|
|
1623
|
+
width,
|
|
1624
|
+
painters: {
|
|
1625
|
+
acc,
|
|
1626
|
+
dim,
|
|
1627
|
+
primary,
|
|
1628
|
+
secondarySoft,
|
|
1629
|
+
warning: colorOr("warning", acc),
|
|
1630
|
+
error: colorOr("error", acc),
|
|
1631
|
+
},
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
const durationStr = formatDuration(clock.total());
|
|
1636
|
+
const diffStat = formatDiffStat(git, acc, diffAdd, diffDel);
|
|
1637
|
+
const paused = clock.idle();
|
|
1638
|
+
idlePauseShown = paused;
|
|
1639
|
+
const clockIcon = paused ? dim("\uf017") : acc("\uf017");
|
|
1640
|
+
const clockText = paused ? dim(durationStr) : secondarySoft(durationStr);
|
|
1641
|
+
const clockCell = `${clockIcon} ${clockText}`;
|
|
1642
|
+
const pDuration = `${clockCell}${diffStat ? `${sep}${diffStat}` : ""}`;
|
|
1643
|
+
// The git segment (branch, sync, tag, dirty count) is rebuilt only when theme,
|
|
1644
|
+
// git info, or cwd changes (refreshGit replaces the git object).
|
|
1645
|
+
if (gitCache?.theme !== theme || gitCache?.git !== git || gitCache?.cwd !== cwd) {
|
|
1646
|
+
const cwdCell = `${acc("\uf07b")} ${dim(shortenCwd(cwd))}`;
|
|
1647
|
+
const gitItems = git ? gitParts(git, acc, secondarySoft) : [];
|
|
1648
|
+
const gitSeg = gitItems.map((p) => `${sep}${p}`).join("");
|
|
1649
|
+
gitCache = { theme, git, cwd, cwdCell, gitItems, gitSeg };
|
|
1650
|
+
}
|
|
1651
|
+
const isMinimal = preset === "Arnative (Minimal)";
|
|
1652
|
+
const isZen = preset === "Zen";
|
|
1653
|
+
const open = minimalExpanded();
|
|
1654
|
+
const arrow = (expanded: boolean) => dim(expanded ? " ▼" : " ▲");
|
|
1655
|
+
let left1 = `${gitCache.cwdCell}${sep}${pDuration}${gitCache.gitSeg}`;
|
|
1656
|
+
if (isMinimal) left1 += arrow(open.left);
|
|
1657
|
+
const modelText = formatModelName(currentModel, currentThinkingLevel, acc, secondarySoft, primary, dim);
|
|
1658
|
+
const right1 = modelText + (isMinimal ? arrow(open.right) : "");
|
|
1659
|
+
|
|
1660
|
+
const statuses: ReadonlyMap<string, string> = (() => {
|
|
1661
|
+
try {
|
|
1662
|
+
return footerData.getExtensionStatuses();
|
|
1663
|
+
} catch {
|
|
1664
|
+
return new Map<string, string>();
|
|
1665
|
+
}
|
|
1666
|
+
})();
|
|
1667
|
+
const rawCache = statuses.get("pi-cache-stats");
|
|
1668
|
+
const cleanStatus = (s: string) => {
|
|
1669
|
+
if (s.includes("MCP:")) {
|
|
1670
|
+
let clean = stripAnsi(s);
|
|
1671
|
+
const idx = clean.indexOf("MCP:");
|
|
1672
|
+
let rest = (idx >= 0 ? clean.slice(idx) : clean).replace(/\uFFFD/g, "").trim();
|
|
1673
|
+
rest = rest.replace(/[\p{Extended_Pictographic}\uFE0F\u200D\u2800-\u28FF]/gu, "").replace(/\s{2,}/g, " ").trim();
|
|
1674
|
+
const m = rest.match(/MCP:\s*\d+\s*servers?\s*enabled/i);
|
|
1675
|
+
return `${acc("\uf233")} ${secondarySoft(m ? m[0] : rest || "MCP")}`;
|
|
1676
|
+
}
|
|
1677
|
+
if (s.includes("ponytail")) return ponytailStatusLine(s, acc, dim, secondarySoft);
|
|
1678
|
+
if (isJevEyeStatus(s)) return jevEyeStatusLine(s, acc, dim, secondarySoft, theme);
|
|
1679
|
+
let clean = stripAnsi(s);
|
|
1680
|
+
clean = clean.replace(/\uFFFD/g, "").replace(/\?{1,2}\s*/g, "");
|
|
1681
|
+
return secondarySoft(clean.trim());
|
|
1682
|
+
};
|
|
1683
|
+
|
|
1684
|
+
const groups: string[] = [];
|
|
1685
|
+
const mcp = statuses.get("mcp");
|
|
1686
|
+
if (mcp !== undefined) groups.push(cleanStatus(mcp));
|
|
1687
|
+
for (const [k, s] of statuses) {
|
|
1688
|
+
if (k !== "mcp" && k !== "pi-cache-stats") groups.push(cleanStatus(s));
|
|
1689
|
+
}
|
|
1690
|
+
// Payload pressure sits beside the extension statuses: the right rows
|
|
1691
|
+
// already carry speed, cache, tokens and cost. The denominator is the shed
|
|
1692
|
+
// trigger from the snapshot (900KB), not the 1MB proxy wall: showing /1MB
|
|
1693
|
+
// understated pressure by 10 points right before the trim starts.
|
|
1694
|
+
const wire = wireBytesSnapshot();
|
|
1695
|
+
if (wire && wire.bytes > 0 && isByteLimitedModel(ctx.model)) {
|
|
1696
|
+
// Under a 1 MB wall the label keeps the approved shape `0.74MB/900KB`: the
|
|
1697
|
+
// payload in MB, the ceiling in KB. A bigger wall scales both to MB so the
|
|
1698
|
+
// ceiling stays readable instead of printing 14336KB.
|
|
1699
|
+
const label = wire.limit >= 1024 * 1024
|
|
1700
|
+
? `${(wire.bytes / 1024 / 1024).toFixed(2)}MB/${(wire.limit / 1024 / 1024).toFixed(2)}MB`
|
|
1701
|
+
: `${(wire.bytes / 1024 / 1024).toFixed(2)}MB/${Math.round(wire.limit / 1024)}KB`;
|
|
1702
|
+
groups.push(`${acc("\udb80\udd93")} ${secondarySoft(label)}`);
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
let usageStr = "";
|
|
1706
|
+
try {
|
|
1707
|
+
// The cost cell's colour follows the budget band — amber at ≥80% of a
|
|
1708
|
+
// cap, red at ≥100% — read from the memoized usage summary, so the
|
|
1709
|
+
// render path scans at most once per 5s memo expiry, never per frame.
|
|
1710
|
+
// Nothing is read at all while the cell is off.
|
|
1711
|
+
const band = activeFooterCost() ? budgetLevelNow() : "ok";
|
|
1712
|
+
const bandPaint = band === "warn" ? colorOr("warning", acc) : band === "over" ? colorOr("error", acc) : undefined;
|
|
1713
|
+
usageStr = getUsage(ctx, acc, secondarySoft, activeFooterCost(), width, bandPaint, dim);
|
|
1714
|
+
} catch {
|
|
1715
|
+
// fallback
|
|
1716
|
+
}
|
|
1717
|
+
const opt = parseOptimizer(rawCache) ?? piCacheHit();
|
|
1718
|
+
const speedStr = latestSpeed !== null && latestSpeed > 0 ? `${acc("\udb81\udcc5")} ${secondarySoft(`${latestSpeed.toFixed(1)} tok/s`)}` : "";
|
|
1719
|
+
// The cache cell's colour follows the recent window (the last 10 assistant
|
|
1720
|
+
// messages, the first two skipped): soft ≥70%, amber 40–70% (`warning`
|
|
1721
|
+
// slot, accent when the theme has none), red below 40% (`error`). A passive
|
|
1722
|
+
// colour only — never a notify. The `pi …%` text itself stays as is.
|
|
1723
|
+
// Only pi's own number may be coloured by pi's window: a cache-stats plugin
|
|
1724
|
+
// publishes its own rate (often per request, not per token), and painting it
|
|
1725
|
+
// with our band would contradict the number printed next to it.
|
|
1726
|
+
const fromPi = !parseOptimizer(rawCache);
|
|
1727
|
+
const band = fromPi ? cacheHitBand(usageWindow.inp, usageWindow.read) : null;
|
|
1728
|
+
const bandPaint = band === "warning" ? colorOr("warning", acc) : band === "error" ? colorOr("error", acc) : null;
|
|
1729
|
+
const cacheCell = opt ? `${(bandPaint ?? acc)("\udb80\udf5b")} ${(bandPaint ?? secondarySoft)(opt)}` : "";
|
|
1730
|
+
const metricCells = [speedStr, cacheCell, usageStr].filter(Boolean);
|
|
1731
|
+
|
|
1732
|
+
if (isZen) {
|
|
1733
|
+
minimalRanges = null;
|
|
1734
|
+
const zen = zenExpanded();
|
|
1735
|
+
const zenLeft = `${gitCache.cwdCell}${sep}${clockCell}`;
|
|
1736
|
+
const zenGitCells = [diffStat, ...gitCache.gitItems].filter(Boolean);
|
|
1737
|
+
const hasGit = zenGitCells.length > 0;
|
|
1738
|
+
const dots = hasGit ? (zen.git ? acc("···") : dim("···")) : "";
|
|
1739
|
+
const gitText = hasGit && zen.git ? zenGitCells.join(sep) : "";
|
|
1740
|
+
const placed = placeZenHead(zenLeft, modelText, ` ${dim("|")} `, dots, gitText, width);
|
|
1741
|
+
zenRanges = { left: placed.left, right: placed.right, dots: placed.dots };
|
|
1742
|
+
const detailCells = zen.detail === "left" ? groups : zen.detail === "right" ? metricCells : [];
|
|
1743
|
+
const w = Math.max(1, width);
|
|
1744
|
+
const detailLines = detailCells.length > 0
|
|
1745
|
+
? wrapTextWithAnsi(detailCells.join(sep), w).map((l) => centerLine(l, w).line)
|
|
1746
|
+
: [];
|
|
1747
|
+
return [...placed.rows, ...detailLines];
|
|
1748
|
+
}
|
|
1749
|
+
zenRanges = null;
|
|
1750
|
+
// Fixed 3-row grid: head (cwd/model), then statuses and metrics each
|
|
1751
|
+
// wrapped inside their half of the width. Arnative (Minimal) starts collapsed
|
|
1752
|
+
// and reveals the same rows on click/keypress, one side at a time.
|
|
1753
|
+
const leftRows = isMinimal && !open.left ? [] : groups;
|
|
1754
|
+
const rightRows = isMinimal && !open.right ? [] : metricCells;
|
|
1755
|
+
if (isMinimal) {
|
|
1756
|
+
const rightSep = ` ${dim("·")} `;
|
|
1757
|
+
if (visibleWidth(left1) + 1 + visibleWidth(right1) > width) {
|
|
1758
|
+
// Narrow / mobile viewport: stack left layout (head + expanded statuses)
|
|
1759
|
+
// then right layout (head + expanded metrics), each auto-wrapped to full width.
|
|
1760
|
+
const w = Math.max(1, width);
|
|
1761
|
+
const leftHeadLines = wrapTextWithAnsi(left1, w);
|
|
1762
|
+
const leftDetailLines = leftRows.length > 0 ? wrapTextWithAnsi(leftRows.join(sep), w) : [];
|
|
1763
|
+
const rightHeadY = leftHeadLines.length + leftDetailLines.length;
|
|
1764
|
+
const rightHeadLines = wrapTextWithAnsi(right1, w);
|
|
1765
|
+
const rightDetailLines = rightRows.length > 0 ? wrapTextWithAnsi(rightRows.join(rightSep), w) : [];
|
|
1766
|
+
const spansOf = (lines: string[], startY: number): MinimalSpan[] => {
|
|
1767
|
+
const spans: MinimalSpan[] = [];
|
|
1768
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1769
|
+
const lw = visibleWidth(lines[i]!);
|
|
1770
|
+
if (lw > 0) spans.push({ y: startY + i, x0: 0, x1: lw - 1 });
|
|
1771
|
+
}
|
|
1772
|
+
return spans;
|
|
1773
|
+
};
|
|
1774
|
+
const arrowOf = (spans: MinimalSpan[]): MinimalSpan | null => {
|
|
1775
|
+
const last = spans[spans.length - 1];
|
|
1776
|
+
return last ? { y: last.y, x0: Math.max(last.x0, last.x1 - 1), x1: last.x1 } : null;
|
|
1777
|
+
};
|
|
1778
|
+
const leftSpans = spansOf(leftHeadLines, 0);
|
|
1779
|
+
const rightSpans = spansOf(rightHeadLines, rightHeadY);
|
|
1780
|
+
minimalRanges = {
|
|
1781
|
+
left: leftSpans,
|
|
1782
|
+
right: rightSpans,
|
|
1783
|
+
leftArrow: arrowOf(leftSpans),
|
|
1784
|
+
rightArrow: arrowOf(rightSpans),
|
|
1785
|
+
};
|
|
1786
|
+
return [...leftHeadLines, ...leftDetailLines, ...rightHeadLines, ...rightDetailLines];
|
|
1787
|
+
}
|
|
1788
|
+
// Wide viewport: single head row with measured click zones.
|
|
1789
|
+
const placed = placeMinimalHead(left1, right1, width);
|
|
1790
|
+
const leftSpans: MinimalSpan[] = placed.left[0] >= 0 ? [{ y: 0, x0: placed.left[0], x1: placed.left[1] }] : [];
|
|
1791
|
+
const rightSpans: MinimalSpan[] = placed.right[0] >= 0 ? [{ y: 0, x0: placed.right[0], x1: placed.right[1] }] : [];
|
|
1792
|
+
const leftArrow: MinimalSpan | null = !placed.leftTruncated && placed.left[0] >= 0 && placed.left[1] >= placed.left[0]
|
|
1793
|
+
? { y: 0, x0: Math.max(placed.left[0], placed.left[1] - 1), x1: placed.left[1] }
|
|
1794
|
+
: null;
|
|
1795
|
+
const rightArrow: MinimalSpan | null = !placed.rightTruncated && placed.right[0] >= 0 && placed.right[1] >= placed.right[0]
|
|
1796
|
+
? { y: 0, x0: Math.max(placed.right[0], placed.right[1] - 1), x1: placed.right[1] }
|
|
1797
|
+
: null;
|
|
1798
|
+
minimalRanges = { left: leftSpans, right: rightSpans, leftArrow, rightArrow };
|
|
1799
|
+
const rest = layoutFooterGrid("", "", leftRows, rightRows, sep, rightSep, width).slice(1);
|
|
1800
|
+
return [placed.row, ...rest];
|
|
1801
|
+
}
|
|
1802
|
+
minimalRanges = null;
|
|
1803
|
+
return layoutFooterGrid(left1, right1, leftRows, rightRows, sep, ` ${dim("·")} `, width);
|
|
1804
|
+
},
|
|
1805
|
+
handleMouse(event: TuiMouseEvent) {
|
|
1806
|
+
// Matches arnative-box (tools.ts / todos.ts):
|
|
1807
|
+
// - Press on the ▲/▼ arrow toggles immediately and swallows the follow-up
|
|
1808
|
+
// release/click so a 1-cell drift still works without double-toggling.
|
|
1809
|
+
// - Press on head text returns undefined so pi handles text selection
|
|
1810
|
+
// (drag-select, double-click word, triple-click line).
|
|
1811
|
+
// - Single-click without drag on either head (clickCount === 1) toggles
|
|
1812
|
+
// that side; double/triple clicks stay with pi's selection.
|
|
1813
|
+
if (event.button !== "left") return undefined;
|
|
1814
|
+
if (event.type === "press") swallowMinimalClick = false;
|
|
1815
|
+
if (swallowMinimalClick && (event.type === "release" || event.type === "click")) {
|
|
1816
|
+
if (event.type === "click") swallowMinimalClick = false;
|
|
1817
|
+
return { handled: true, render: false };
|
|
1818
|
+
}
|
|
1819
|
+
const hitSpan = (s: MinimalSpan | null) => !!s && event.y === s.y && event.x >= s.x0 && event.x <= s.x1;
|
|
1820
|
+
const hitAny = (spans: readonly MinimalSpan[]) => spans.some((s) => hitSpan(s));
|
|
1821
|
+
if (zenRanges) {
|
|
1822
|
+
const toggleGit = () => {
|
|
1823
|
+
const state = zenExpanded();
|
|
1824
|
+
state.git = !state.git;
|
|
1825
|
+
poke();
|
|
1826
|
+
return { handled: true, render: true };
|
|
1827
|
+
};
|
|
1828
|
+
const toggleDetail = (side: "left" | "right") => {
|
|
1829
|
+
const state = zenExpanded();
|
|
1830
|
+
state.detail = state.detail === side ? null : side;
|
|
1831
|
+
poke();
|
|
1832
|
+
return { handled: true, render: true };
|
|
1833
|
+
};
|
|
1834
|
+
if (event.type === "press") {
|
|
1835
|
+
if (!hitSpan(zenRanges.dots)) return undefined;
|
|
1836
|
+
swallowMinimalClick = true;
|
|
1837
|
+
return toggleGit();
|
|
1838
|
+
}
|
|
1839
|
+
if (event.type !== "click" || (event.clickCount ?? 1) !== 1) return undefined;
|
|
1840
|
+
if (hitSpan(zenRanges.dots)) return toggleGit();
|
|
1841
|
+
const hit = hitAny(zenRanges.left) ? "left" : hitAny(zenRanges.right) ? "right" : null;
|
|
1842
|
+
if (!hit) return undefined;
|
|
1843
|
+
return toggleDetail(hit);
|
|
1844
|
+
}
|
|
1845
|
+
const ranges = minimalRanges;
|
|
1846
|
+
if (!ranges) return undefined;
|
|
1847
|
+
const toggle = (side: "left" | "right") => {
|
|
1848
|
+
const state = minimalExpanded();
|
|
1849
|
+
state[side] = !state[side];
|
|
1850
|
+
poke();
|
|
1851
|
+
return { handled: true, render: true };
|
|
1852
|
+
};
|
|
1853
|
+
if (event.type === "press") {
|
|
1854
|
+
const arrowHit = hitSpan(ranges.leftArrow) ? "left" : hitSpan(ranges.rightArrow) ? "right" : null;
|
|
1855
|
+
if (!arrowHit) return undefined;
|
|
1856
|
+
swallowMinimalClick = true;
|
|
1857
|
+
return toggle(arrowHit);
|
|
1858
|
+
}
|
|
1859
|
+
if (event.type !== "click" || (event.clickCount ?? 1) !== 1) return undefined;
|
|
1860
|
+
const hit = hitAny(ranges.left) ? "left" : hitAny(ranges.right) ? "right" : null;
|
|
1861
|
+
if (!hit) return undefined;
|
|
1862
|
+
return toggle(hit);
|
|
1863
|
+
},
|
|
1864
|
+
};
|
|
1865
|
+
});
|
|
1866
|
+
|
|
1867
|
+
};
|
|
1868
|
+
rt.footerRegistrar = registerArnative;
|
|
1869
|
+
applyFooterPreset(ctx);
|
|
1870
|
+
class ArnativeEditor extends CustomEditor {
|
|
1871
|
+
private lastHiddenLineCount = 0;
|
|
1872
|
+
private lastBottomHiddenCount = 0;
|
|
1873
|
+
private topMoreSpans: TextSpan[] = [];
|
|
1874
|
+
private bottomMoreSpans: TextSpan[] = [];
|
|
1875
|
+
|
|
1876
|
+
constructor(
|
|
1877
|
+
tui: ConstructorParameters<typeof CustomEditor>[0],
|
|
1878
|
+
editorTheme: ConstructorParameters<typeof CustomEditor>[1],
|
|
1879
|
+
keybindings: ConstructorParameters<typeof CustomEditor>[2],
|
|
1880
|
+
options?: ConstructorParameters<typeof CustomEditor>[3],
|
|
1881
|
+
) {
|
|
1882
|
+
super(tui, editorTheme, keybindings, { ...options, embedWorkingStatus: true });
|
|
1883
|
+
editorTui = tui;
|
|
1884
|
+
// Published so `/arnative` → Animations can repaint the live spinner without
|
|
1885
|
+
// waiting for the next session, and so workUI has a handle to the Loader.
|
|
1886
|
+
getRuntime().editor = this;
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
private getActiveTheme() {
|
|
1890
|
+
return ctx.ui?.theme ?? activeThemeProxy;
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
private applyFixedIndicatorColors(indicator: WorkingIndicatorLike | undefined) {
|
|
1894
|
+
if (!indicator) return;
|
|
1895
|
+
// Clear renderIndicatorVerbatim so custom frames pass through spinnerColorFn.
|
|
1896
|
+
indicator.renderIndicatorVerbatim = false;
|
|
1897
|
+
indicator.spinnerColorFn = spinnerPainter(activeSpinnerPreset(), this.getActiveTheme(), activeSpinnerGradient());
|
|
1898
|
+
indicator.messageColorFn = (text: string) => {
|
|
1899
|
+
try {
|
|
1900
|
+
const th = this.getActiveTheme();
|
|
1901
|
+
if (!th) return text;
|
|
1902
|
+
return softSecondaryOf(th as never)(text);
|
|
1903
|
+
} catch {
|
|
1904
|
+
return text;
|
|
1905
|
+
}
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
setWorkingStatusIndicator(indicator: WorkingIndicatorLike | undefined) {
|
|
1910
|
+
this.applyFixedIndicatorColors(indicator);
|
|
1911
|
+
indicator?.updateDisplay?.();
|
|
1912
|
+
super.setWorkingStatusIndicator(indicator as Parameters<CustomEditor["setWorkingStatusIndicator"]>[0]);
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
renderTopBorder(width: number, hiddenLineCount: number): string {
|
|
1916
|
+
this.lastHiddenLineCount = hiddenLineCount;
|
|
1917
|
+
this.applyFixedIndicatorColors((this as unknown as { workingStatusIndicator?: WorkingIndicatorLike }).workingStatusIndicator);
|
|
1918
|
+
if (activeChatboxPreset() === "Arnative") {
|
|
1919
|
+
return renderChatboxScrollBorder(
|
|
1920
|
+
"\u2191",
|
|
1921
|
+
hiddenLineCount,
|
|
1922
|
+
width,
|
|
1923
|
+
(t) => this.borderColor(t),
|
|
1924
|
+
chatboxPrimaryPaint(this.getActiveTheme()),
|
|
1925
|
+
);
|
|
1926
|
+
}
|
|
1927
|
+
// Plain/scroll border only; render() positions the status dialog after boxing.
|
|
1928
|
+
const editorProto = Object.getPrototypeOf(CustomEditor.prototype) as {
|
|
1929
|
+
renderTopBorder?: (w: number, h: number) => string;
|
|
1930
|
+
};
|
|
1931
|
+
if (typeof editorProto?.renderTopBorder === "function") {
|
|
1932
|
+
return editorProto.renderTopBorder.call(this, width, hiddenLineCount);
|
|
1933
|
+
}
|
|
1934
|
+
return this.borderColor("\u2500".repeat(width));
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
renderBottomBorder(width: number, hiddenLineCount: number): string {
|
|
1938
|
+
this.lastBottomHiddenCount = hiddenLineCount;
|
|
1939
|
+
if (activeChatboxPreset() === "Arnative") {
|
|
1940
|
+
return renderChatboxScrollBorder(
|
|
1941
|
+
"\u2193",
|
|
1942
|
+
hiddenLineCount,
|
|
1943
|
+
width,
|
|
1944
|
+
(t) => this.borderColor(t),
|
|
1945
|
+
chatboxPrimaryPaint(this.getActiveTheme()),
|
|
1946
|
+
);
|
|
1947
|
+
}
|
|
1948
|
+
const editorProto = Object.getPrototypeOf(CustomEditor.prototype) as {
|
|
1949
|
+
renderBottomBorder?: (w: number, h: number) => string;
|
|
1950
|
+
};
|
|
1951
|
+
if (typeof editorProto?.renderBottomBorder === "function") {
|
|
1952
|
+
return editorProto.renderBottomBorder.call(this, width, hiddenLineCount);
|
|
1953
|
+
}
|
|
1954
|
+
return this.borderColor("\u2500".repeat(width));
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
private scrollByBorderClick(direction: -1 | 1): void {
|
|
1958
|
+
const ed = this as unknown as {
|
|
1959
|
+
lastWidth?: number;
|
|
1960
|
+
scrollOffset?: number;
|
|
1961
|
+
renderedVisibleLineCount?: number;
|
|
1962
|
+
buildVisualLineMap?(w: number): unknown[];
|
|
1963
|
+
findCurrentVisualLine?(vls: unknown[]): number;
|
|
1964
|
+
moveToVisualLine?(vls: unknown[], cur: number, target: number): void;
|
|
1965
|
+
pageScroll?(dir: number): void;
|
|
1966
|
+
};
|
|
1967
|
+
if (
|
|
1968
|
+
typeof ed.buildVisualLineMap === "function" &&
|
|
1969
|
+
typeof ed.findCurrentVisualLine === "function" &&
|
|
1970
|
+
typeof ed.moveToVisualLine === "function"
|
|
1971
|
+
) {
|
|
1972
|
+
const vls = ed.buildVisualLineMap(ed.lastWidth ?? 80);
|
|
1973
|
+
if (vls.length > 0) {
|
|
1974
|
+
const cur = ed.findCurrentVisualLine(vls);
|
|
1975
|
+
const vis = Math.max(1, ed.renderedVisibleLineCount ?? 5);
|
|
1976
|
+
const step = Math.max(1, Math.floor(vis / 2));
|
|
1977
|
+
const scrollOff = Math.max(0, ed.scrollOffset ?? 0);
|
|
1978
|
+
const target =
|
|
1979
|
+
direction < 0
|
|
1980
|
+
? Math.max(0, scrollOff - step)
|
|
1981
|
+
: Math.min(vls.length - 1, scrollOff + vis - 1 + step);
|
|
1982
|
+
ed.moveToVisualLine(vls, cur, target);
|
|
1983
|
+
return;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
ed.pageScroll?.(direction);
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
handleMouse(event: TuiMouseEvent) {
|
|
1990
|
+
if (activeChatboxPreset() === "Arnative" && event.type === "click" && event.button === "left") {
|
|
1991
|
+
if (inSpans(this.topMoreSpans, event.y, event.x)) {
|
|
1992
|
+
this.scrollByBorderClick(-1);
|
|
1993
|
+
return { handled: true, focus: true };
|
|
1994
|
+
}
|
|
1995
|
+
if (inSpans(this.bottomMoreSpans, event.y, event.x)) {
|
|
1996
|
+
this.scrollByBorderClick(1);
|
|
1997
|
+
return { handled: true, focus: true };
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
return super.handleMouse(event);
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
handleInput(data: string) {
|
|
2004
|
+
if (SHORTCUT_RELOAD.matches(data)) {
|
|
2005
|
+
this.setText("");
|
|
2006
|
+
if (this.onSubmit) {
|
|
2007
|
+
this.onSubmit("/reload");
|
|
2008
|
+
}
|
|
2009
|
+
return;
|
|
2010
|
+
}
|
|
2011
|
+
if (!isPointerOrFocusInput(data)) markPromptTyped();
|
|
2012
|
+
super.handleInput(data);
|
|
2013
|
+
}
|
|
2014
|
+
|
|
2015
|
+
render(width: number): string[] {
|
|
2016
|
+
const preset = activeChatboxPreset();
|
|
2017
|
+
const dialog = activeChatboxDialog();
|
|
2018
|
+
const indicator = (this as unknown as { workingStatusIndicator?: WorkingIndicatorLike }).workingStatusIndicator;
|
|
2019
|
+
this.applyFixedIndicatorColors(indicator);
|
|
2020
|
+
// The box eats 5 columns: 2 sides + the 3-column prompt, so the
|
|
2021
|
+
// content is rendered 5 columns narrower.
|
|
2022
|
+
const visible = (this as unknown as { renderedVisibleLineCount?: number }).renderedVisibleLineCount;
|
|
2023
|
+
const prompt = paintChatboxPrompt(activeChatboxPrompt(), this.getActiveTheme(), isPromptActive());
|
|
2024
|
+
const promptW = visibleWidth(prompt);
|
|
2025
|
+
const lines = renderChatboxLines(preset, (w) => super.render(w), width, visible, (t) => this.borderColor(t), prompt);
|
|
2026
|
+
const boxed = preset === "Arnative" && typeof visible === "number" && width >= promptW + 8 && lines.length >= visible + 2;
|
|
2027
|
+
const statusMax = Math.max(1, width - (boxed ? promptW + 4 : 5));
|
|
2028
|
+
const status = indicator?.renderInBorder?.(statusMax) ?? "";
|
|
2029
|
+
const spinnerOnly = status ? (indicator?.renderSpinnerInBorder?.(width) ?? "") : "";
|
|
2030
|
+
const primary = chatboxPrimaryPaint(this.getActiveTheme());
|
|
2031
|
+
const out = applyChatboxDialog(lines, boxed, width, this.lastHiddenLineCount, dialog, status, spinnerOnly, (t) => this.borderColor(t), primary);
|
|
2032
|
+
const visNow = (this as unknown as { renderedVisibleLineCount?: number }).renderedVisibleLineCount ?? 0;
|
|
2033
|
+
this.topMoreSpans =
|
|
2034
|
+
this.lastHiddenLineCount > 0 && out.length > 0
|
|
2035
|
+
? textSpans([out[0]!], `\u2191 ${this.lastHiddenLineCount} more`)
|
|
2036
|
+
: [];
|
|
2037
|
+
const botRow = visNow + 1;
|
|
2038
|
+
this.bottomMoreSpans =
|
|
2039
|
+
this.lastBottomHiddenCount > 0 && botRow < out.length
|
|
2040
|
+
? textSpans([out[botRow]!], `\u2193 ${this.lastBottomHiddenCount} more`).map((s) => ({ ...s, row: botRow }))
|
|
2041
|
+
: [];
|
|
2042
|
+
return out;
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
ctx.ui.setEditorComponent((tui, editorTheme, keybindings) => new ArnativeEditor(tui, editorTheme, keybindings));
|
|
2046
|
+
applySpinnerPreset(ctx.ui, activeThemeProxy);
|
|
2047
|
+
rt.outsideDialogHook = (lines: string[], width: number, modeRaw: unknown): string[] => {
|
|
2048
|
+
if (activeChatboxDialog() !== "Outside") return lines;
|
|
2049
|
+
const mode = modeRaw as OutsideDialogModeLike | null | undefined;
|
|
2050
|
+
const editor = getRuntime().editor as
|
|
2051
|
+
| { workingStatusIndicator?: WorkingIndicatorLike; applyFixedIndicatorColors?: (ind: WorkingIndicatorLike) => void }
|
|
2052
|
+
| null;
|
|
2053
|
+
if (!editor || mode?.editor !== editor) return lines;
|
|
2054
|
+
const children = mode?.editorContainer?.children;
|
|
2055
|
+
if (Array.isArray(children) && !children.includes(editor)) return lines;
|
|
2056
|
+
const indicator = editor.workingStatusIndicator;
|
|
2057
|
+
if (!indicator) return lines;
|
|
2058
|
+
editor.applyFixedIndicatorColors?.(indicator);
|
|
2059
|
+
const status = indicator.renderInBorder?.(Math.max(1, width - 5)) ?? "";
|
|
2060
|
+
if (!status || visibleWidth(status) === 0) return lines;
|
|
2061
|
+
return overlayOutsideDialogOnWidgetLines(lines, width, status);
|
|
2062
|
+
};
|
|
2063
|
+
} catch {
|
|
2064
|
+
// fallback
|
|
2065
|
+
}
|
|
2066
|
+
void refreshGit(cwd, { force: true }).then(() => poke());
|
|
2067
|
+
});
|
|
2068
|
+
|
|
2069
|
+
pi.on("turn_start", async (_event, ctx) => {
|
|
2070
|
+
const rt = getRuntime();
|
|
2071
|
+
clock.tick();
|
|
2072
|
+
armIdleProbe();
|
|
2073
|
+
currentModel = ctx.model;
|
|
2074
|
+
currentThinkingLevel = ctx.thinkingLevel;
|
|
2075
|
+
rt.currentModel = currentModel;
|
|
2076
|
+
rt.currentThinking = currentThinkingLevel;
|
|
2077
|
+
rt.lastCwd = ctx.cwd;
|
|
2078
|
+
startWorkingClock(ctx);
|
|
2079
|
+
void refreshGit(ctx.cwd, { force: true }).then(() => poke());
|
|
2080
|
+
});
|
|
2081
|
+
|
|
2082
|
+
pi.on("tool_execution_start", async (event, ctx) => {
|
|
2083
|
+
clock.tick();
|
|
2084
|
+
armIdleProbe(Date.now(), { repaint: false });
|
|
2085
|
+
const verb = getToolWorkingMessage(event.toolName, event.args);
|
|
2086
|
+
activeToolVerbs.set(event.toolCallId, verb);
|
|
2087
|
+
setWorkingVerb(ctx, verb);
|
|
2088
|
+
});
|
|
2089
|
+
|
|
2090
|
+
pi.on("tool_execution_end", async (event, ctx) => {
|
|
2091
|
+
clock.tick();
|
|
2092
|
+
armIdleProbe(Date.now(), { repaint: false });
|
|
2093
|
+
activeToolVerbs.delete(event.toolCallId);
|
|
2094
|
+
setWorkingVerb(ctx, currentToolVerb(activeToolVerbs));
|
|
2095
|
+
// Only refresh git status for tools that can modify the worktree or git state.
|
|
2096
|
+
if (toolMayChangeGit(event.toolName)) {
|
|
2097
|
+
void refreshGit(ctx.cwd).then(() => poke());
|
|
2098
|
+
}
|
|
2099
|
+
});
|
|
2100
|
+
|
|
2101
|
+
pi.on("message_update", async (event) => {
|
|
2102
|
+
clock.tick();
|
|
2103
|
+
armIdleProbe(Date.now(), { repaint: false });
|
|
2104
|
+
if (event.message.role === "assistant") {
|
|
2105
|
+
// Timer starts lazily if message_start never fired (fragile event pairing)
|
|
2106
|
+
if (assistantStartMs === null) assistantStartMs = Date.now();
|
|
2107
|
+
const streamEvent = (event as { assistantMessageEvent?: { type?: string; delta?: string } }).assistantMessageEvent;
|
|
2108
|
+
if (streamEvent?.delta) {
|
|
2109
|
+
assistantChars += streamEvent.delta.length;
|
|
2110
|
+
}
|
|
2111
|
+
const elapsed = (Date.now() - assistantStartMs) / 1000;
|
|
2112
|
+
if (elapsed >= 0.3) {
|
|
2113
|
+
const usageOut = (event.message as AssistantMessage).usage?.output;
|
|
2114
|
+
const currentTokens = typeof usageOut === "number" && usageOut > 0 ? usageOut : Math.ceil(assistantChars / 3.8);
|
|
2115
|
+
if (currentTokens > 0) {
|
|
2116
|
+
latestSpeed = currentTokens / elapsed;
|
|
2117
|
+
const now = Date.now();
|
|
2118
|
+
if (now - lastPokeMs >= 500) {
|
|
2119
|
+
lastPokeMs = now;
|
|
2120
|
+
poke();
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
});
|
|
2126
|
+
|
|
2127
|
+
pi.on("message_end", async (event) => {
|
|
2128
|
+
clock.tick();
|
|
2129
|
+
armIdleProbe();
|
|
2130
|
+
if (event.message.role === "assistant") {
|
|
2131
|
+
const start = assistantStartMs ?? Date.now();
|
|
2132
|
+
const elapsed = (Date.now() - start) / 1000;
|
|
2133
|
+
assistantStartMs = null;
|
|
2134
|
+
const usageOut = (event.message as AssistantMessage).usage?.output;
|
|
2135
|
+
const finalTokens = typeof usageOut === "number" && usageOut > 0 ? usageOut : Math.ceil(assistantChars / 3.8);
|
|
2136
|
+
if (finalTokens > 0 && elapsed > 0.2) {
|
|
2137
|
+
latestSpeed = finalTokens / elapsed;
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
poke();
|
|
2141
|
+
});
|
|
2142
|
+
|
|
2143
|
+
pi.on("turn_end", async (_event, ctx) => {
|
|
2144
|
+
clock.tick();
|
|
2145
|
+
armIdleProbe();
|
|
2146
|
+
stopWorkingClock();
|
|
2147
|
+
try {
|
|
2148
|
+
ctx.ui?.setWorkingMessage?.();
|
|
2149
|
+
} catch {
|
|
2150
|
+
// ignore
|
|
2151
|
+
}
|
|
2152
|
+
poke();
|
|
2153
|
+
});
|
|
2154
|
+
|
|
2155
|
+
pi.on("model_select", async (event) => {
|
|
2156
|
+
currentModel = event.model;
|
|
2157
|
+
getRuntime().currentModel = currentModel;
|
|
2158
|
+
poke();
|
|
2159
|
+
});
|
|
2160
|
+
|
|
2161
|
+
pi.on("thinking_level_select", async (event) => {
|
|
2162
|
+
currentThinkingLevel = event.level;
|
|
2163
|
+
getRuntime().currentThinking = currentThinkingLevel;
|
|
2164
|
+
poke();
|
|
2165
|
+
});
|
|
2166
|
+
|
|
2167
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
2168
|
+
const rt = getRuntime();
|
|
2169
|
+
usageScanManager = undefined;
|
|
2170
|
+
usageScanLeaf = undefined;
|
|
2171
|
+
usageScanPriceTable = null;
|
|
2172
|
+
piStatsCache = null;
|
|
2173
|
+
stopWorkingClock();
|
|
2174
|
+
stopIdleProbe();
|
|
2175
|
+
stopPromptIdle();
|
|
2176
|
+
stopClockTick();
|
|
2177
|
+
editorTui = null;
|
|
2178
|
+
rt.outsideDialogHook = null;
|
|
2179
|
+
try {
|
|
2180
|
+
ctx.ui?.setWorkingIndicator?.();
|
|
2181
|
+
} catch {
|
|
2182
|
+
// ignore
|
|
2183
|
+
}
|
|
2184
|
+
rerender = null;
|
|
2185
|
+
const cur = rt.footerGen ?? 0;
|
|
2186
|
+
if (cur !== runtimeGen) return;
|
|
2187
|
+
footerGen++;
|
|
2188
|
+
rt.footerGen = footerGen;
|
|
2189
|
+
try {
|
|
2190
|
+
(ctx as unknown as { ui?: { setFooter?: (f?: undefined) => void } }).ui?.setFooter?.(undefined);
|
|
2191
|
+
} catch {
|
|
2192
|
+
// ignore
|
|
2193
|
+
}
|
|
2194
|
+
});
|
|
2195
|
+
}
|
|
2196
|
+
|
|
2197
|
+
export const __test = {
|
|
2198
|
+
CHATBOX_PRESET_KEY,
|
|
2199
|
+
CHATBOX_PROMPT_KEY,
|
|
2200
|
+
CHATBOX_DIALOG_KEY,
|
|
2201
|
+
ARNATIVE_PRESETS,
|
|
2202
|
+
FOOTER_PRESET_KEY,
|
|
2203
|
+
get git() {
|
|
2204
|
+
return git;
|
|
2205
|
+
},
|
|
2206
|
+
set git(v) {
|
|
2207
|
+
git = v;
|
|
2208
|
+
},
|
|
2209
|
+
WORK_LABEL,
|
|
2210
|
+
run,
|
|
2211
|
+
branchFromDisk,
|
|
2212
|
+
refreshGit,
|
|
2213
|
+
formatModelName,
|
|
2214
|
+
get usageWindow() {
|
|
2215
|
+
return usageWindow;
|
|
2216
|
+
},
|
|
2217
|
+
get usageScanAt() {
|
|
2218
|
+
return usageScanAt;
|
|
2219
|
+
},
|
|
2220
|
+
set usageScanAt(v) {
|
|
2221
|
+
usageScanAt = v;
|
|
2222
|
+
},
|
|
2223
|
+
get usageScanLen() {
|
|
2224
|
+
return usageScanLen;
|
|
2225
|
+
},
|
|
2226
|
+
set usageScanLen(v) {
|
|
2227
|
+
usageScanLen = v;
|
|
2228
|
+
},
|
|
2229
|
+
stopWorkingClock,
|
|
2230
|
+
IDLE_PROBE_EPSILON_MS,
|
|
2231
|
+
startWorkingClock,
|
|
2232
|
+
};
|