@arhen/pi-senja 1.2.7 → 1.3.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 +7 -3
- package/package.json +1 -1
- package/src/index.ts +104 -48
- package/src/tool-groups.ts +680 -0
package/README.md
CHANGED
|
@@ -9,8 +9,12 @@ Forked from [pi-haiku](https://github.com/nnocte/pi-haiku) **0.2.0** by **nocte*
|
|
|
9
9
|
- **Gruvbox Material dark/medium/material** — exact colors captured from Neovim, matching the Ghostty Senja theme. Background `#282828`, foreground `#d4be98`, orange accent `#e78a4e`. All 56 Pi roles and HTML export backgrounds use palette variables.
|
|
10
10
|
- **A header** with shortcuts grouped by control, models, view, and input.
|
|
11
11
|
- **A footer** with location, Git branch, session name, provider, model, thinking effort (including `max`), context bar, token usage, latest cache-hit rate, cost, OAuth subscription marker, and extension statuses.
|
|
12
|
-
- **
|
|
13
|
-
- **
|
|
12
|
+
- **Flat tool output** — image captions, command results, and errors sit on the terminal background. Only source and diff lines get a quiet editor surface (Senja warm grey `#32302f`). Status dots and failure labels carry the state; user messages retain their own background.
|
|
13
|
+
- **Grouped tool calls** — a single call stays on one line, e.g. `• write example.ts ▸`. Tool-call summaries can use the full pane width. Long titles truncate on one line, leaving room for the status and arrow. For runs longer than ten, the heading counts every call and failure, but only the latest ten calls are listed. Click **Show all** to reveal earlier calls above those ten, or **Show less** to fold history again. The control briefly brightens without scrolling through intermediate layouts (`REDUCE_MOTION=1` disables the feedback). Image reads keep Pi’s native inline image or text fallback, without a code gutter. Two or more consecutive calls to the same tool share a fixed heading, e.g. `• Ran codemode ×4 · 1 failed`. Each call occupies one tree line: `├─ script ▸` or `└─ script · failed ▸`. Click the line to open its indented native panel. The muted trailing icon changes to `▾`. Calls start collapsed by default. While running, the label has a subtle moving highlight without changing the row height (`REDUCE_MOTION=1` or `NO_COLOR=1` disables it). Click a call to open or close it at any time; partial output, success, and failure update its status without changing your choice. Expanded panels omit repeated titles and number script or file source lines (read offsets and native diff numbering are preserved). A text read opens to five wrapped lines; click its “more lines” hint to see the full read result. Image reads are not clipped. Opening a codemode row shows Pi’s native preview: at most five wrapped output lines. Click the result to see it in full; click it again to return to the preview. The row arrow closes the panel. Numbered source has a shaded row of padding above and below. Nested calls, output, and timing align with the script text, without an inner border. Pi’s tool expansion shortcut (default `Ctrl+O`) toggles all calls. Collapsed thinking is marked with a single-cell outline bulb (Nerd Font) beside `Thinking…` while streaming and `Thought` afterward. Inside a tool group, the bulb sits after the tree guide. Click the label to replace it with Pi’s thinking text without an icon, or the text to fold it back. A thinking-only turn between matching tools stays above the next call’s tree branch; elsewhere it stays in transcript order. Final replies have no marker. Parallel calls share the row once. Thinking follows its call through **Show all / Show less** and does not count toward the ten calls. A different tool or assistant prose starts a new group.
|
|
14
|
+
- **Tool activity** — An unnamed call shows `preparing…`. As soon as Pi names it, the row shows `running`, even while the model writes the script. The timer starts at the first named call update and keeps counting through execution (`running 1m 30s`). Confirmed interruptions freeze that total (`cancelled · 8s`) without counting as failures.
|
|
15
|
+
- **Codemode intent titles** — Senja asks the agent to put a short plan in a leading `// @title: Find the goal notice renderer` comment (after an optional `// @options:` line). The row displays that plan; expand it for the actual script and results. Untitled calls keep their script preview.
|
|
16
|
+
- **Goal notices** — a `goal-ui` status starts as one clickable row. Open it for the original notice, including its objective, usage and commands.
|
|
17
|
+
- **Quiet tool text** — action labels such as `Ran` use muted teal (`#7daea3`) to distinguish tools from assistant prose. Tool names following a verb and tool output use the foreground beige (`fg0`) rather than loud accents, keeping panels calm against their tint.
|
|
14
18
|
- **Editor-style code colors** — pink keywords, olive strings, aqua function names, amber types, warm beige identifiers and punctuation, readable muted comments. Applies to code in tool calls/results and Markdown code blocks through Pi's syntax roles.
|
|
15
19
|
- **A live timer** while Pi works, plus elapsed-time completion message and notification. Preserves the active mode label and colour from `@arhen/pi-add-mode` (`review is working... 8s`).
|
|
16
20
|
- **Fast / Ultrafast mode** — `/fast on|off` and `/ultrafast on|off` set a paid speed preference per OpenAI provider and model. With `openai-codex` and ChatGPT sign-in, Senja checks the account catalog and retries a saved tier after a temporary lookup failure on the next turn or model selection. With the public `openai` Responses provider, Senja checks known model support and OpenAI handles account eligibility. The footer shows the selected preference as `fast` or `ultrafast`. Preferences persist under `<agent-dir>/fast-mode/`. An explicit `samplingParams.service_tier` takes precedence.
|
|
@@ -28,7 +32,7 @@ Disable/remove `pi-haiku` or other header/footer replacements to avoid competing
|
|
|
28
32
|
|
|
29
33
|
## Toggle
|
|
30
34
|
|
|
31
|
-
Type `/senja` to turn the header and
|
|
35
|
+
Type `/senja` to turn the header, footer, and tool grouping on or off. The theme stays selected. Terminal session startup selects `senja`; selecting another theme afterward still works.
|
|
32
36
|
|
|
33
37
|
## Development
|
|
34
38
|
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -21,6 +21,8 @@ import type { ExtensionAPI, ExtensionContext, Theme, ThemeColor } from "@earendi
|
|
|
21
21
|
import { VERSION } from "@earendil-works/pi-coding-agent";
|
|
22
22
|
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
23
23
|
|
|
24
|
+
import { formatDuration, installToolGroups } from "./tool-groups.ts";
|
|
25
|
+
|
|
24
26
|
// ── Visual primitives ────────────────────────────────────────────────────────
|
|
25
27
|
|
|
26
28
|
const GLYPH = {
|
|
@@ -129,20 +131,6 @@ function fmtTokens(n: number): string {
|
|
|
129
131
|
return `${Math.round(n / 1_000_000)}M`;
|
|
130
132
|
}
|
|
131
133
|
|
|
132
|
-
/** Format milliseconds as a human-readable duration. */
|
|
133
|
-
function formatDuration(ms: number): string {
|
|
134
|
-
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
|
|
135
|
-
if (totalSeconds < 60) return `${totalSeconds}s`;
|
|
136
|
-
|
|
137
|
-
const s = totalSeconds % 60;
|
|
138
|
-
const totalMinutes = Math.floor(totalSeconds / 60);
|
|
139
|
-
if (totalMinutes < 60) return `${totalMinutes}m ${s}s`;
|
|
140
|
-
|
|
141
|
-
const m = totalMinutes % 60;
|
|
142
|
-
const h = Math.floor(totalMinutes / 60);
|
|
143
|
-
return `${h}h ${m}m ${s}s`;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
134
|
/** Right-align two text blocks, truncating left if they don't both fit. */
|
|
147
135
|
function alignRight(left: string, right: string, width: number, theme: Theme): string {
|
|
148
136
|
const rightW = visibleWidth(right);
|
|
@@ -332,13 +320,44 @@ function renderHeader(theme: Theme, width: number): string[] {
|
|
|
332
320
|
return lines.map((line) => truncateToWidth(line, width, ellipsis));
|
|
333
321
|
}
|
|
334
322
|
|
|
335
|
-
function
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
323
|
+
function readUsage(ctx: ExtensionContext) {
|
|
324
|
+
let totalInput = 0;
|
|
325
|
+
let totalOutput = 0;
|
|
326
|
+
let totalCost = 0;
|
|
327
|
+
let latestCacheHitRate: number | undefined;
|
|
328
|
+
|
|
329
|
+
for (const entry of ctx.sessionManager.getEntries()) {
|
|
330
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
331
|
+
const m = entry.message;
|
|
332
|
+
totalInput += m.usage.input;
|
|
333
|
+
totalOutput += m.usage.output;
|
|
334
|
+
totalCost += m.usage.cost.total;
|
|
335
|
+
|
|
336
|
+
const promptTokens = m.usage.input + m.usage.cacheRead + m.usage.cacheWrite;
|
|
337
|
+
latestCacheHitRate = promptTokens > 0 ? (m.usage.cacheRead / promptTokens) * 100 : undefined;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return { totalInput, totalOutput, totalCost, latestCacheHitRate, contextUsage: ctx.getContextUsage() };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function applyHeader(
|
|
344
|
+
ctx: ExtensionContext,
|
|
345
|
+
starts: ReadonlyMap<string, number>,
|
|
346
|
+
cancelled: ReadonlyMap<string, number | undefined>,
|
|
347
|
+
): void {
|
|
348
|
+
ctx.ui.setHeader((tui, theme) => {
|
|
349
|
+
let cached: { width: number; lines: string[] } | undefined;
|
|
350
|
+
return {
|
|
351
|
+
...installToolGroups(tui, theme, starts, cancelled),
|
|
352
|
+
render(width: number) {
|
|
353
|
+
if (cached?.width !== width) cached = { width, lines: renderHeader(theme, width) };
|
|
354
|
+
return cached.lines;
|
|
355
|
+
},
|
|
356
|
+
invalidate() {
|
|
357
|
+
cached = undefined;
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
});
|
|
342
361
|
}
|
|
343
362
|
|
|
344
363
|
function restoreHeader(ctx: ExtensionContext): void {
|
|
@@ -363,6 +382,37 @@ export default function (pi: ExtensionAPI) {
|
|
|
363
382
|
let renderHandle: RenderHandle | undefined;
|
|
364
383
|
let disposeFooter: (() => void) | undefined;
|
|
365
384
|
let enabled = true;
|
|
385
|
+
const starts = new Map<string, number>();
|
|
386
|
+
const cancelled = new Map<string, number | undefined>();
|
|
387
|
+
function startCall(id: string) {
|
|
388
|
+
if (!starts.has(id)) starts.set(id, performance.now());
|
|
389
|
+
}
|
|
390
|
+
function cancelCall(id: string) {
|
|
391
|
+
if (cancelled.has(id)) return;
|
|
392
|
+
const start = starts.get(id);
|
|
393
|
+
cancelled.set(id, start === undefined ? undefined : performance.now() - start);
|
|
394
|
+
starts.delete(id);
|
|
395
|
+
}
|
|
396
|
+
pi.on("message_update", ({ assistantMessageEvent: update }, ctx) => {
|
|
397
|
+
if (ctx.mode !== "tui" || !("contentIndex" in update)) return;
|
|
398
|
+
const block = update.partial.content[update.contentIndex];
|
|
399
|
+
if (block?.type === "toolCall" && block.name && block.id) startCall(block.id);
|
|
400
|
+
});
|
|
401
|
+
pi.on("message_end", ({ message }, ctx) => {
|
|
402
|
+
if (ctx.mode !== "tui" || message.role !== "assistant" || message.stopReason !== "aborted") return;
|
|
403
|
+
for (const block of message.content) {
|
|
404
|
+
if (block.type === "toolCall") cancelCall(block.id);
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
pi.on("tool_execution_start", (event, ctx) => {
|
|
408
|
+
if (ctx.mode === "tui" && !event.parentToolCallId) startCall(event.toolCallId);
|
|
409
|
+
});
|
|
410
|
+
pi.on("tool_execution_end", (event, ctx) => {
|
|
411
|
+
if (!event.parentToolCallId && event.isError && ctx.signal?.aborted && starts.has(event.toolCallId)) {
|
|
412
|
+
cancelCall(event.toolCallId);
|
|
413
|
+
}
|
|
414
|
+
starts.delete(event.toolCallId);
|
|
415
|
+
});
|
|
366
416
|
let workingSince: number | undefined;
|
|
367
417
|
let workingTimer: ReturnType<typeof setInterval> | undefined;
|
|
368
418
|
let lastDoneIn: number | undefined;
|
|
@@ -370,6 +420,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
370
420
|
const speedTiers = new Map<string, SpeedTier | null>();
|
|
371
421
|
const unverifiedTiers = new Set<string>();
|
|
372
422
|
|
|
423
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
424
|
+
if (!enabled || ctx.mode !== "tui" || !event.systemPromptOptions?.selectedTools.includes("codemode")) return;
|
|
425
|
+
const guide =
|
|
426
|
+
"Start each codemode script with a // @title: comment describing its planned action in a short verb phrase (e.g. // @title: Find the goal notice renderer). If using // @options:, put the title on the next line.";
|
|
427
|
+
const { promptGuidelines } = event.systemPromptOptions;
|
|
428
|
+
if (!promptGuidelines.includes(guide)) promptGuidelines.push(guide);
|
|
429
|
+
});
|
|
430
|
+
|
|
373
431
|
const unsubscribeMode = pi.events.on("pi-mode:working-message", (message) => {
|
|
374
432
|
if (message === undefined || typeof message === "string") modeWorkingMessage = message || undefined;
|
|
375
433
|
});
|
|
@@ -473,11 +531,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
473
531
|
|
|
474
532
|
if (ctx.mode !== "tui") return;
|
|
475
533
|
|
|
534
|
+
let lastMessage: string | undefined;
|
|
476
535
|
const tick = () => {
|
|
477
536
|
if (workingSince === undefined) return;
|
|
478
537
|
const elapsed = formatDuration(Date.now() - workingSince);
|
|
538
|
+
const message = `${modeWorkingMessage ?? "Working…"} ${elapsed}`;
|
|
539
|
+
if (message === lastMessage) return;
|
|
479
540
|
try {
|
|
480
|
-
ctx.ui.setWorkingMessage(
|
|
541
|
+
ctx.ui.setWorkingMessage(message);
|
|
542
|
+
lastMessage = message;
|
|
481
543
|
} catch {
|
|
482
544
|
// Ignore if the UI is already torn down.
|
|
483
545
|
}
|
|
@@ -497,6 +559,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
497
559
|
|
|
498
560
|
// Report final duration and clean up timers.
|
|
499
561
|
pi.on("agent_end", (_event, ctx) => {
|
|
562
|
+
starts.clear();
|
|
500
563
|
clearWorkingTimers();
|
|
501
564
|
|
|
502
565
|
if (workingSince !== undefined) {
|
|
@@ -537,34 +600,25 @@ export default function (pi: ExtensionAPI) {
|
|
|
537
600
|
}
|
|
538
601
|
};
|
|
539
602
|
disposeFooter = dispose;
|
|
603
|
+
let cached: { key: string; model: ExtensionContext["model"]; usage: ReturnType<typeof readUsage> } | undefined;
|
|
540
604
|
|
|
541
605
|
return {
|
|
542
606
|
dispose,
|
|
543
607
|
invalidate() {
|
|
544
|
-
|
|
608
|
+
cached = undefined;
|
|
545
609
|
},
|
|
546
610
|
render(width: number): string[] {
|
|
547
611
|
if (width <= 0) return [];
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
const m = entry.message as AssistantMessage;
|
|
557
|
-
totalInput += m.usage.input;
|
|
558
|
-
totalOutput += m.usage.output;
|
|
559
|
-
totalCost += m.usage.cost.total;
|
|
560
|
-
|
|
561
|
-
const promptTokens = m.usage.input + m.usage.cacheRead + m.usage.cacheWrite;
|
|
562
|
-
latestCacheHitRate = promptTokens > 0 ? (m.usage.cacheRead / promptTokens) * 100 : undefined;
|
|
563
|
-
}
|
|
612
|
+
const manager = ctx.sessionManager;
|
|
613
|
+
// Pi's session is append-only; older hosts without the cheap entry count use the uncached path.
|
|
614
|
+
const key =
|
|
615
|
+
"getEntryCount" in manager && typeof manager.getEntryCount === "function"
|
|
616
|
+
? `${manager.getSessionId()}:${manager.getLeafId()}:${manager.getEntryCount()}`
|
|
617
|
+
: "";
|
|
618
|
+
if (!cached || !key || cached.key !== key || cached.model !== ctx.model) {
|
|
619
|
+
cached = { key, model: ctx.model, usage: readUsage(ctx) };
|
|
564
620
|
}
|
|
565
|
-
|
|
566
|
-
// ── Context usage for the active model ───────────────────────────
|
|
567
|
-
const contextUsage = ctx.getContextUsage();
|
|
621
|
+
const { totalInput, totalOutput, totalCost, latestCacheHitRate, contextUsage } = cached.usage;
|
|
568
622
|
const contextWindow = contextUsage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
|
|
569
623
|
const contextTokens = contextUsage?.tokens ?? null;
|
|
570
624
|
const contextPercent = contextUsage?.percent ?? null;
|
|
@@ -590,13 +644,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
590
644
|
locationBlock += ` ${theme.fg("dim", "session")} ${theme.fg("text", sessionName)}`;
|
|
591
645
|
}
|
|
592
646
|
|
|
593
|
-
let modelBlock = `${theme.fg(providerColor(provider),
|
|
647
|
+
let modelBlock = `${theme.fg(providerColor(provider), provider)} ${theme.fg("dim", GLYPH.square)} ${theme.fg("text", modelId)}`;
|
|
594
648
|
if (reasoning) {
|
|
595
649
|
const level = pi.getThinkingLevel();
|
|
596
650
|
modelBlock += ` ${theme.fg("dim", GLYPH.square)} ${theme.fg(effortColor(level), level)}`;
|
|
597
651
|
}
|
|
598
|
-
const
|
|
599
|
-
const tier =
|
|
652
|
+
const modelKey = speedKey(ctx.model);
|
|
653
|
+
const tier = modelKey && speedTiers.get(modelKey);
|
|
600
654
|
if (tier) {
|
|
601
655
|
modelBlock += ` ${theme.fg("dim", GLYPH.square)} ${theme.fg("warning", tier)}`;
|
|
602
656
|
}
|
|
@@ -693,7 +747,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
693
747
|
|
|
694
748
|
// Toggle command.
|
|
695
749
|
pi.registerCommand("senja", {
|
|
696
|
-
description: "Toggle the Senja header and
|
|
750
|
+
description: "Toggle the Senja header, footer, and tool groups",
|
|
697
751
|
handler: async (_args, ctx) => {
|
|
698
752
|
if (ctx.mode !== "tui") {
|
|
699
753
|
if (ctx.hasUI) ctx.ui.notify("Senja requires terminal UI mode", "info");
|
|
@@ -702,7 +756,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
702
756
|
enabled = !enabled;
|
|
703
757
|
if (enabled) {
|
|
704
758
|
applyFooter(ctx);
|
|
705
|
-
applyHeader(ctx);
|
|
759
|
+
applyHeader(ctx, starts, cancelled);
|
|
706
760
|
ctx.ui.notify("Senja enabled", "info");
|
|
707
761
|
} else {
|
|
708
762
|
restoreFooter(ctx);
|
|
@@ -787,7 +841,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
787
841
|
|
|
788
842
|
if (enabled) {
|
|
789
843
|
applyFooter(ctx);
|
|
790
|
-
applyHeader(ctx);
|
|
844
|
+
applyHeader(ctx, starts, cancelled);
|
|
791
845
|
} else {
|
|
792
846
|
restoreFooter(ctx);
|
|
793
847
|
restoreHeader(ctx);
|
|
@@ -795,6 +849,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
795
849
|
});
|
|
796
850
|
|
|
797
851
|
pi.on("session_shutdown", () => {
|
|
852
|
+
starts.clear();
|
|
853
|
+
cancelled.clear();
|
|
798
854
|
unsubscribeMode();
|
|
799
855
|
modeWorkingMessage = undefined;
|
|
800
856
|
clearWorkingTimers();
|
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AssistantMessageComponent,
|
|
3
|
+
CustomMessageComponent,
|
|
4
|
+
type Theme,
|
|
5
|
+
ToolExecutionComponent,
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import {
|
|
8
|
+
type Component,
|
|
9
|
+
Container,
|
|
10
|
+
foregroundAnsi,
|
|
11
|
+
indexedColor,
|
|
12
|
+
Markdown,
|
|
13
|
+
MouseRegion,
|
|
14
|
+
mixColors,
|
|
15
|
+
rgbColor,
|
|
16
|
+
Spacer,
|
|
17
|
+
sliceByColumn,
|
|
18
|
+
stripTerminalSequences,
|
|
19
|
+
Text,
|
|
20
|
+
type TUI,
|
|
21
|
+
truncateToWidth,
|
|
22
|
+
visibleWidth,
|
|
23
|
+
wrapTextWithAnsi,
|
|
24
|
+
} from "@earendil-works/pi-tui";
|
|
25
|
+
|
|
26
|
+
type ToolRow = Component & {
|
|
27
|
+
toolName: string;
|
|
28
|
+
toolCallId: string;
|
|
29
|
+
args?: Record<string, unknown>;
|
|
30
|
+
isPartial: boolean;
|
|
31
|
+
expanded: boolean;
|
|
32
|
+
outputPad?: number;
|
|
33
|
+
result?: { isError: boolean; durationMs?: number; content?: { type: string; text?: string }[] };
|
|
34
|
+
setExpanded(value: boolean): void;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function summary(value: unknown): string {
|
|
38
|
+
if (typeof value !== "string") return "";
|
|
39
|
+
return stripTerminalSequences(value.slice(0, 2048))
|
|
40
|
+
.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]+/gu, " ")
|
|
41
|
+
.replace(/\s+/gu, " ")
|
|
42
|
+
.trim();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const graphemes = new Intl.Segmenter();
|
|
46
|
+
const colorSpan = /(\x1b\[38;(?:2;\d+;\d+;\d+|5;\d+)m)([^\x1b]+)/g;
|
|
47
|
+
|
|
48
|
+
function createShimmer(theme: Theme) {
|
|
49
|
+
const ramps = new Map<string, string[]>();
|
|
50
|
+
const target = theme.appearance === "light" ? rgbColor(0, 0, 0) : rgbColor(255, 255, 255);
|
|
51
|
+
return (line: string, frame: number) => {
|
|
52
|
+
const width = visibleWidth(line);
|
|
53
|
+
if (width < 2) return line;
|
|
54
|
+
const center = (frame * 2) % width;
|
|
55
|
+
const radius = Math.min(9, width / 2);
|
|
56
|
+
let column = 0;
|
|
57
|
+
let cursor = 0;
|
|
58
|
+
// Only tint foreground spans. Leave bold, resets, tree guides and unstyled text intact.
|
|
59
|
+
return line.replace(colorSpan, (span, ansi: string, text: string, offset) => {
|
|
60
|
+
column += visibleWidth(line.slice(cursor, offset));
|
|
61
|
+
cursor = offset + span.length;
|
|
62
|
+
let ramp = ramps.get(ansi);
|
|
63
|
+
if (!ramp) {
|
|
64
|
+
const [mode, r, g, b] = ansi.slice(5, -1).split(";").map(Number);
|
|
65
|
+
const base = mode === 5 ? indexedColor(r!) : rgbColor(r!, g!, b!);
|
|
66
|
+
ramp = Array.from({ length: 9 }, (_, i) =>
|
|
67
|
+
i ? foregroundAnsi(mixColors(base, target, i / 24, "srgb"), mode === 5 ? "256color" : "truecolor") : ansi,
|
|
68
|
+
);
|
|
69
|
+
ramps.set(ansi, ramp);
|
|
70
|
+
}
|
|
71
|
+
let result = ansi;
|
|
72
|
+
let previous = 0;
|
|
73
|
+
for (const { segment } of graphemes.segment(text)) {
|
|
74
|
+
const dx = Math.abs(column - center);
|
|
75
|
+
const distance = Math.min(dx, width - dx);
|
|
76
|
+
const level = distance >= radius ? 0 : Math.round(4 * (1 + Math.cos((Math.PI * distance) / radius)));
|
|
77
|
+
if (level !== previous) result += ramp[level];
|
|
78
|
+
result += segment;
|
|
79
|
+
previous = level;
|
|
80
|
+
column += visibleWidth(segment);
|
|
81
|
+
}
|
|
82
|
+
return previous ? result + ansi : result;
|
|
83
|
+
});
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function describe(tool: ToolRow): [string, string] {
|
|
88
|
+
const a = tool.args ?? {};
|
|
89
|
+
switch (tool.toolName) {
|
|
90
|
+
case "read": {
|
|
91
|
+
const path = summary(a.file_path ?? a.path) || ".";
|
|
92
|
+
if (typeof a.offset !== "number" && typeof a.limit !== "number") return ["Explored", path];
|
|
93
|
+
const start = typeof a.offset === "number" ? a.offset : 1;
|
|
94
|
+
return ["Explored", `${path}:${start}${typeof a.limit === "number" ? `-${start + a.limit - 1}` : ""}`];
|
|
95
|
+
}
|
|
96
|
+
case "ls":
|
|
97
|
+
return ["Explored", summary(a.path) || "."];
|
|
98
|
+
case "find":
|
|
99
|
+
case "grep":
|
|
100
|
+
return ["Searched", summary(a.pattern)];
|
|
101
|
+
case "web_search":
|
|
102
|
+
return ["Searched the web", summary(a.query)];
|
|
103
|
+
case "edit":
|
|
104
|
+
case "write":
|
|
105
|
+
return ["", summary(a.path ?? a.file_path)];
|
|
106
|
+
case "bash":
|
|
107
|
+
return ["Ran", summary(a.command)];
|
|
108
|
+
case "codemode": {
|
|
109
|
+
const code = a.code ?? a.input ?? a.source ?? a.script;
|
|
110
|
+
const title =
|
|
111
|
+
typeof code === "string"
|
|
112
|
+
? /^(?:\/\/ @options:[^\n]*\n)?\/\/ @title:[ \t]*([^\r\n]+)/.exec(code.slice(0, 2048))
|
|
113
|
+
: undefined;
|
|
114
|
+
return ["Ran", summary(title?.[1]) || summary(code)];
|
|
115
|
+
}
|
|
116
|
+
default:
|
|
117
|
+
return ["Called", summary(a.path ?? a.query)];
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function sourceText(tool: ToolRow) {
|
|
122
|
+
const args = tool.args ?? {};
|
|
123
|
+
let raw: unknown;
|
|
124
|
+
let first = 1;
|
|
125
|
+
if (tool.toolName === "codemode") raw = args.code;
|
|
126
|
+
else if (tool.toolName === "write") raw = args.content;
|
|
127
|
+
else if (tool.toolName === "read" && !tool.result?.isError) {
|
|
128
|
+
raw = tool.result?.content?.find((block) => block.type === "text")?.text;
|
|
129
|
+
if (typeof args.offset === "number" && Number.isSafeInteger(args.offset)) first = Math.max(1, args.offset);
|
|
130
|
+
}
|
|
131
|
+
if (typeof raw !== "string" || !raw) return;
|
|
132
|
+
return { raw, first };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function indentedDetails(
|
|
136
|
+
tool: ToolRow,
|
|
137
|
+
theme: Theme,
|
|
138
|
+
previews: WeakSet<Component>,
|
|
139
|
+
tui: TUI,
|
|
140
|
+
): Component & { guide: string; revision: number } {
|
|
141
|
+
let inset = 0;
|
|
142
|
+
let top = 0;
|
|
143
|
+
let padTop = 0;
|
|
144
|
+
let editorRows = 0;
|
|
145
|
+
let padBottom = 0;
|
|
146
|
+
let hiddenReadRows = 0;
|
|
147
|
+
let height = 0;
|
|
148
|
+
let contentWidth = 0;
|
|
149
|
+
let gutter = 0;
|
|
150
|
+
let outputGutter = 0;
|
|
151
|
+
let codeEnd = 0;
|
|
152
|
+
let previousSource: string | undefined;
|
|
153
|
+
let logicalLines: string[] = [];
|
|
154
|
+
let cached:
|
|
155
|
+
| { lines: readonly string[]; width: number; guide: string; revision: number; first?: number; body: string[] }
|
|
156
|
+
| undefined;
|
|
157
|
+
const blank = /^(?:\s|\x1b\[[\d;:]*m)*$/;
|
|
158
|
+
return {
|
|
159
|
+
guide: "",
|
|
160
|
+
revision: 0,
|
|
161
|
+
invalidate: () => tool.invalidate(),
|
|
162
|
+
render(width) {
|
|
163
|
+
const image = tool.result?.content?.some((block) => block.type === "image");
|
|
164
|
+
const source = image ? undefined : sourceText(tool);
|
|
165
|
+
if (source?.raw !== previousSource) {
|
|
166
|
+
previousSource = source?.raw;
|
|
167
|
+
logicalLines = previousSource?.replace(/\r/g, "").replace(/\t/g, " ").trimEnd().split("\n") ?? [];
|
|
168
|
+
cached = undefined;
|
|
169
|
+
}
|
|
170
|
+
const digits = source ? Math.max(2, String(source.first + logicalLines.length - 1).length) : 0;
|
|
171
|
+
gutter = digits && width >= 16 ? digits + 2 : 0;
|
|
172
|
+
const innerPad = image ? 0 : gutter ? 2 : (tool.outputPad ?? 1);
|
|
173
|
+
inset = Math.max(0, visibleWidth(this.guide) - innerPad);
|
|
174
|
+
const guide = sliceByColumn(this.guide, 0, inset);
|
|
175
|
+
contentWidth = Math.max(1, width - inset - gutter - (width >= 16 ? 2 : 0));
|
|
176
|
+
const lines = tool.render(contentWidth);
|
|
177
|
+
if (
|
|
178
|
+
cached?.width === width &&
|
|
179
|
+
cached.guide === this.guide &&
|
|
180
|
+
cached.revision === this.revision &&
|
|
181
|
+
cached.first === source?.first &&
|
|
182
|
+
cached.lines.length === lines.length &&
|
|
183
|
+
lines.every((line, i) => line === cached!.lines[i])
|
|
184
|
+
) {
|
|
185
|
+
return cached.body;
|
|
186
|
+
}
|
|
187
|
+
height = lines.length;
|
|
188
|
+
top = 0;
|
|
189
|
+
while (top < height && blank.test(lines[top]!)) top++;
|
|
190
|
+
const plain = (line: string) => stripTerminalSequences(line).trim();
|
|
191
|
+
const innerWidth = Math.max(1, contentWidth - 2 * (tool.outputPad ?? 1));
|
|
192
|
+
const [, subject] = describe(tool);
|
|
193
|
+
const titles = [`${tool.toolName} ${subject}`, tool.toolName];
|
|
194
|
+
if (process.env.HOME && subject.startsWith(`${process.env.HOME}/`)) {
|
|
195
|
+
titles.unshift(`${tool.toolName} ~${subject.slice(process.env.HOME.length)}`);
|
|
196
|
+
}
|
|
197
|
+
const headerStart = top;
|
|
198
|
+
if (tool.toolName === "bash" && visibleWidth(subject) <= innerWidth - 2) titles.unshift(`$ ${subject}`);
|
|
199
|
+
for (const title of titles) {
|
|
200
|
+
const parts = wrapTextWithAnsi(title, innerWidth);
|
|
201
|
+
if (!parts.every((part, i) => top + i < height && plain(lines[top + i]!) === part.trim())) continue;
|
|
202
|
+
top += parts.length;
|
|
203
|
+
while (!image && top < height && blank.test(lines[top]!)) top++;
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
let end = height;
|
|
207
|
+
while (!image && end > top && blank.test(lines[end - 1]!)) end--;
|
|
208
|
+
hiddenReadRows = tool.toolName === "read" && source ? Math.max(0, end - top - 5) : 0;
|
|
209
|
+
if (end === top) return [];
|
|
210
|
+
const clipped = previews.has(tool) ? hiddenReadRows : 0;
|
|
211
|
+
const displayEnd = end - clipped;
|
|
212
|
+
// Keep non-redundant renderer metadata (ranges, limits, invalid arguments).
|
|
213
|
+
const firstLine = stripTerminalSequences(lines[top]!);
|
|
214
|
+
const redundant = top === headerStart && firstLine.trimStart().startsWith(`${tool.toolName} `);
|
|
215
|
+
const labelEnd = redundant
|
|
216
|
+
? firstLine.length - firstLine.trimStart().length + visibleWidth(tool.toolName) + 1
|
|
217
|
+
: 0;
|
|
218
|
+
const numbers = new Map<number, string>();
|
|
219
|
+
codeEnd = top;
|
|
220
|
+
if (source) {
|
|
221
|
+
let row = top;
|
|
222
|
+
let started = false;
|
|
223
|
+
for (const [i, logical] of logicalLines.entries()) {
|
|
224
|
+
if (row >= displayEnd) break;
|
|
225
|
+
if (!started && !logical.trim()) continue;
|
|
226
|
+
const parts = wrapTextWithAnsi(logical, innerWidth);
|
|
227
|
+
if (!parts.every((part, j) => row + j < end && plain(lines[row + j]!) === part.trim())) break;
|
|
228
|
+
numbers.set(row, String(source.first + i));
|
|
229
|
+
row += parts.length;
|
|
230
|
+
codeEnd = Math.min(row, displayEnd);
|
|
231
|
+
started = true;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
outputGutter =
|
|
235
|
+
tool.toolName === "codemode" && codeEnd > top ? gutter : Math.max(0, innerPad - (tool.outputPad ?? 1));
|
|
236
|
+
const resultIndent = " ".repeat(outputGutter);
|
|
237
|
+
const fills = (["toolPendingBg", "toolSuccessBg", "toolErrorBg"] as const).map((role) => theme.getBgAnsi(role));
|
|
238
|
+
const body = lines.slice(top, displayEnd).map((line, i) => {
|
|
239
|
+
// Graphics sequences and their reserved rows belong to Pi's image renderer.
|
|
240
|
+
if (image && (!line.trim() || line.includes("\x1b_G") || line.includes("\x1b]1337;File="))) return guide + line;
|
|
241
|
+
let content = i === 0 && labelEnd ? sliceByColumn(line, labelEnd, contentWidth) : line;
|
|
242
|
+
for (const fill of fills) if (fill) content = content.replaceAll(fill, "");
|
|
243
|
+
const code = top + i < codeEnd;
|
|
244
|
+
const diff = tool.toolName === "edit" && !tool.result?.isError && /^\s*[+-]?\s*\d+\s/.test(plain(content));
|
|
245
|
+
if (!code && !diff) return guide + resultIndent + content;
|
|
246
|
+
const number = numbers.get(top + i);
|
|
247
|
+
const cell = number && gutter ? ` ${theme.fg("dim", number.padStart(digits))} ` : " ".repeat(gutter);
|
|
248
|
+
return guide + theme.bg("toolSuccessBg", cell + content);
|
|
249
|
+
});
|
|
250
|
+
editorRows = codeEnd - top;
|
|
251
|
+
padTop = !image && (editorRows || body.length > 1) ? 1 : 0;
|
|
252
|
+
padBottom = !image && body.length > 1 && editorRows !== body.length ? 1 : 0;
|
|
253
|
+
if (padBottom) body.push(guide);
|
|
254
|
+
if (editorRows) {
|
|
255
|
+
const pad = guide + theme.bg("toolSuccessBg", " ".repeat(gutter + contentWidth));
|
|
256
|
+
body.splice(editorRows, 0, pad);
|
|
257
|
+
body.unshift(pad);
|
|
258
|
+
} else if (padTop) body.unshift(guide);
|
|
259
|
+
if (clipped) {
|
|
260
|
+
body.push(truncateToWidth(this.guide + theme.fg("muted", `… ${clipped} more lines · click to expand`), width));
|
|
261
|
+
}
|
|
262
|
+
cached = { lines, width, guide: this.guide, revision: this.revision, first: source?.first, body };
|
|
263
|
+
return body;
|
|
264
|
+
},
|
|
265
|
+
handleMouse(event) {
|
|
266
|
+
if (hiddenReadRows && event.type === "click" && event.button === "left") {
|
|
267
|
+
if (previews.has(tool)) previews.delete(tool);
|
|
268
|
+
else previews.add(tool);
|
|
269
|
+
cached = undefined;
|
|
270
|
+
tui.requestRender();
|
|
271
|
+
return { handled: true };
|
|
272
|
+
}
|
|
273
|
+
const row = event.y - padTop;
|
|
274
|
+
if (row < 0 || (editorRows && row === editorRows) || event.y >= event.height - padBottom) return;
|
|
275
|
+
const y = row + top - (editorRows && row > editorRows ? 1 : 0);
|
|
276
|
+
const x = event.x - inset - (y < codeEnd ? gutter : outputGutter);
|
|
277
|
+
if (x < 0 || x >= contentWidth) return;
|
|
278
|
+
const full = tool.expanded;
|
|
279
|
+
const result = tool.handleMouse?.({ ...event, x, y, width: contentWidth, height });
|
|
280
|
+
if (tool.toolName === "codemode" && full && !tool.expanded) previews.add(tool);
|
|
281
|
+
return result;
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function isToolRow(row: Component): row is ToolRow {
|
|
287
|
+
return row instanceof ToolExecutionComponent && typeof Reflect.get(row, "toolName") === "string";
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function thinkingRow(region: MouseRegion, theme: Theme, tui: TUI): Component & { guide?: string; live: boolean } {
|
|
291
|
+
const child = Reflect.get(region, "child");
|
|
292
|
+
const open = child instanceof Markdown;
|
|
293
|
+
const padding = open ? (Reflect.get(child, "paddingX") ?? 0) : 0;
|
|
294
|
+
const margin = " ".repeat(padding);
|
|
295
|
+
const bulb = theme.fg("dim", "\uEA61 ");
|
|
296
|
+
const indent = " ".repeat(visibleWidth(bulb));
|
|
297
|
+
return {
|
|
298
|
+
live: false,
|
|
299
|
+
render(width) {
|
|
300
|
+
const label = theme.italic(theme.fg("thinkingText", this.live ? "Thinking…" : "Thought"));
|
|
301
|
+
const guide = this.guide ?? " ";
|
|
302
|
+
if (!open) return [truncateToWidth(guide + bulb + label, width)];
|
|
303
|
+
const prefix = guide + indent;
|
|
304
|
+
const inner = Math.max(1, width - visibleWidth(prefix));
|
|
305
|
+
const lines = region.render(inner + padding).map((line) => {
|
|
306
|
+
const text = line.startsWith(margin) ? line.slice(padding) : line;
|
|
307
|
+
return truncateToWidth(prefix + text, width, "");
|
|
308
|
+
});
|
|
309
|
+
return [this.guide ?? "", ...lines, this.guide ?? ""];
|
|
310
|
+
},
|
|
311
|
+
handleMouse(event) {
|
|
312
|
+
if (event.type !== "click" || event.button !== "left") return;
|
|
313
|
+
if (open && (event.y === 0 || event.y === event.height - 1)) return;
|
|
314
|
+
const inset = visibleWidth(this.guide ?? " ") + indent.length;
|
|
315
|
+
const result = region.handleMouse({
|
|
316
|
+
...event,
|
|
317
|
+
x: Math.max(0, event.x - inset) + padding,
|
|
318
|
+
y: event.y - (open ? 1 : 0),
|
|
319
|
+
width: Math.max(1, event.width - inset) + padding,
|
|
320
|
+
height: event.height - (open ? 2 : 0),
|
|
321
|
+
});
|
|
322
|
+
if (result?.handled) tui.requestRender();
|
|
323
|
+
return result;
|
|
324
|
+
},
|
|
325
|
+
invalidate: () => region.invalidate(),
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Format milliseconds as a human-readable duration. */
|
|
330
|
+
export function formatDuration(ms: number): string {
|
|
331
|
+
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
|
|
332
|
+
if (totalSeconds < 60) return `${totalSeconds}s`;
|
|
333
|
+
|
|
334
|
+
const s = totalSeconds % 60;
|
|
335
|
+
const totalMinutes = Math.floor(totalSeconds / 60);
|
|
336
|
+
if (totalMinutes < 60) return `${totalMinutes}m ${s}s`;
|
|
337
|
+
|
|
338
|
+
const m = totalMinutes % 60;
|
|
339
|
+
const h = Math.floor(totalMinutes / 60);
|
|
340
|
+
return `${h}h ${m}m ${s}s`;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export function installToolGroups(
|
|
344
|
+
tui: TUI,
|
|
345
|
+
theme: Theme,
|
|
346
|
+
starts?: ReadonlyMap<string, number>,
|
|
347
|
+
cancelled?: ReadonlyMap<string, number | undefined>,
|
|
348
|
+
) {
|
|
349
|
+
// ponytail: Pi 1.x exposes per-tool renderers, not transcript grouping; leave unknown layouts alone until Pi ships a group hook.
|
|
350
|
+
const document = tui.children?.[0];
|
|
351
|
+
if (!(document instanceof Container) || document.children.length !== 3) return;
|
|
352
|
+
const [header, resources, chat] = document.children;
|
|
353
|
+
if (!(header instanceof Container && resources instanceof Container && chat instanceof Container)) return;
|
|
354
|
+
|
|
355
|
+
const blockGap = new Spacer(1);
|
|
356
|
+
const branchGap: Component = {
|
|
357
|
+
render: (width) => [width >= 8 ? theme.fg("dim", " │") : ""],
|
|
358
|
+
invalidate() {},
|
|
359
|
+
};
|
|
360
|
+
const goalRows = new WeakMap<CustomMessageComponent, MouseRegion>();
|
|
361
|
+
function goalRow(card: CustomMessageComponent) {
|
|
362
|
+
const message = Reflect.get(card, "message");
|
|
363
|
+
if (
|
|
364
|
+
message?.customType !== "goal-ui" ||
|
|
365
|
+
typeof message.content !== "string" ||
|
|
366
|
+
Reflect.get(card, "customRenderer")
|
|
367
|
+
) {
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
let row = goalRows.get(card);
|
|
371
|
+
if (!row) {
|
|
372
|
+
const title = summary(message.content.split("\n", 1)[0]) || "Goal";
|
|
373
|
+
row = new MouseRegion(
|
|
374
|
+
{
|
|
375
|
+
render(width) {
|
|
376
|
+
const limit = Math.max(1, Math.floor(width / 2));
|
|
377
|
+
const icon = theme.fg("muted", Reflect.get(card, "_expanded") ? "▾" : "▸");
|
|
378
|
+
const label = ` ${theme.fg("dim", "•")} ${theme.fg("customMessageLabel", title)}`;
|
|
379
|
+
return [limit <= 2 ? icon : `${truncateToWidth(label, limit - 2, "…")} ${icon}`];
|
|
380
|
+
},
|
|
381
|
+
invalidate() {},
|
|
382
|
+
},
|
|
383
|
+
(event) => {
|
|
384
|
+
if (event.type !== "click" || event.button !== "left") return;
|
|
385
|
+
card.setExpanded(!Reflect.get(card, "_expanded"));
|
|
386
|
+
tui.requestRender();
|
|
387
|
+
return { handled: true };
|
|
388
|
+
},
|
|
389
|
+
);
|
|
390
|
+
goalRows.set(card, row);
|
|
391
|
+
}
|
|
392
|
+
return row;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const titles = new WeakMap<Component, Text>();
|
|
396
|
+
const controls = new WeakMap<Component, MouseRegion>();
|
|
397
|
+
const showAll = new WeakSet<Component>();
|
|
398
|
+
const previews = new WeakSet<Component>();
|
|
399
|
+
type Thought = ReturnType<typeof thinkingRow>;
|
|
400
|
+
const originals = new WeakMap<Component, MouseRegion>();
|
|
401
|
+
function styleThoughts(message: AssistantMessageComponent): Thought[] | undefined {
|
|
402
|
+
const [content] = message.children;
|
|
403
|
+
if (message.children.length !== 1 || !(content instanceof Container)) return;
|
|
404
|
+
const thoughts: Thought[] = [];
|
|
405
|
+
let onlyThoughts = true;
|
|
406
|
+
for (const [i, part] of content.children.entries()) {
|
|
407
|
+
if (part instanceof Spacer) continue;
|
|
408
|
+
const region = originals.get(part) ?? part;
|
|
409
|
+
const child = region instanceof MouseRegion ? Reflect.get(region, "child") : undefined;
|
|
410
|
+
if (!(region instanceof MouseRegion) || !(child instanceof Text || child instanceof Markdown)) {
|
|
411
|
+
onlyThoughts = false;
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
if (child instanceof Text && Reflect.get(message, "hiddenThinkingLabel") === "") continue;
|
|
415
|
+
const row = region === part ? thinkingRow(region, theme, tui) : (part as Thought);
|
|
416
|
+
if (region === part) {
|
|
417
|
+
originals.set(row, region);
|
|
418
|
+
content.children[i] = row;
|
|
419
|
+
}
|
|
420
|
+
row.guide = undefined;
|
|
421
|
+
row.live =
|
|
422
|
+
i === content.children.length - 1 &&
|
|
423
|
+
Reflect.get(message, "isStreaming") === true &&
|
|
424
|
+
Reflect.get(message, "lastMessage")?.content.at(-1)?.type === "thinking";
|
|
425
|
+
thoughts.push(row);
|
|
426
|
+
}
|
|
427
|
+
return onlyThoughts ? thoughts : undefined;
|
|
428
|
+
}
|
|
429
|
+
const motion = !process.env.REDUCE_MOTION && !process.env.NO_COLOR;
|
|
430
|
+
const shimmer = createShimmer(theme);
|
|
431
|
+
let frame = 0;
|
|
432
|
+
let animation: ReturnType<typeof setInterval> | undefined;
|
|
433
|
+
let pressed: Component | undefined;
|
|
434
|
+
let settle: ReturnType<typeof setTimeout> | undefined;
|
|
435
|
+
const calls = new WeakMap<
|
|
436
|
+
Component,
|
|
437
|
+
{
|
|
438
|
+
label: Text;
|
|
439
|
+
row: MouseRegion;
|
|
440
|
+
details?: ReturnType<typeof indentedDetails>;
|
|
441
|
+
labelKey?: string;
|
|
442
|
+
}
|
|
443
|
+
>();
|
|
444
|
+
function historyControl(first: ToolRow, title: Text) {
|
|
445
|
+
return new MouseRegion(title, (event) => {
|
|
446
|
+
if (event.type !== "click" || event.button !== "left") return;
|
|
447
|
+
if (showAll.has(first)) showAll.delete(first);
|
|
448
|
+
else {
|
|
449
|
+
showAll.add(first);
|
|
450
|
+
if ("getPrimaryScrollView" in tui && typeof tui.getPrimaryScrollView === "function") {
|
|
451
|
+
const viewport = tui.getPrimaryScrollView();
|
|
452
|
+
viewport?.scrollTo(viewport.scrollTop, { disableFollow: true });
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (motion) {
|
|
456
|
+
clearTimeout(settle);
|
|
457
|
+
pressed = first;
|
|
458
|
+
settle = setTimeout(() => {
|
|
459
|
+
pressed = undefined;
|
|
460
|
+
tui.requestRender();
|
|
461
|
+
}, 150);
|
|
462
|
+
}
|
|
463
|
+
tui.requestRender();
|
|
464
|
+
return { handled: true };
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function createCall(tool: ToolRow) {
|
|
469
|
+
const label = new Text("", 0, 0);
|
|
470
|
+
const row = new MouseRegion(label, (event) => {
|
|
471
|
+
if (event.type !== "click" || event.button !== "left") return;
|
|
472
|
+
if (tool.toolName === "read") {
|
|
473
|
+
if (tool.expanded) previews.delete(tool);
|
|
474
|
+
else previews.add(tool);
|
|
475
|
+
tool.setExpanded(!tool.expanded);
|
|
476
|
+
} else if (tool.toolName !== "codemode") tool.setExpanded(!tool.expanded);
|
|
477
|
+
else if (tool.expanded || previews.has(tool)) {
|
|
478
|
+
previews.delete(tool);
|
|
479
|
+
if (tool.expanded) tool.setExpanded(false);
|
|
480
|
+
} else previews.add(tool);
|
|
481
|
+
tui.requestRender();
|
|
482
|
+
return { handled: true };
|
|
483
|
+
});
|
|
484
|
+
return { label, row };
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const view = new Container();
|
|
488
|
+
const render = view.render.bind(view);
|
|
489
|
+
let revision = 0;
|
|
490
|
+
view.invalidate = () => {
|
|
491
|
+
revision++;
|
|
492
|
+
chat.invalidate();
|
|
493
|
+
};
|
|
494
|
+
view.render = (width) => {
|
|
495
|
+
let animating = false;
|
|
496
|
+
const rows: Component[] = [];
|
|
497
|
+
let run: ToolRow[] = [];
|
|
498
|
+
let name = "";
|
|
499
|
+
const before = new Map<ToolRow, Thought[]>();
|
|
500
|
+
let pending: { message: AssistantMessageComponent; regions: Thought[] }[] = [];
|
|
501
|
+
const flush = () => {
|
|
502
|
+
const first = run[0];
|
|
503
|
+
if (!first) return;
|
|
504
|
+
const grouped = run.length > 1;
|
|
505
|
+
let failed = 0;
|
|
506
|
+
let interrupted = 0;
|
|
507
|
+
for (const tool of run) {
|
|
508
|
+
if (!tool.result?.isError) continue;
|
|
509
|
+
if (cancelled?.has(tool.toolCallId)) interrupted++;
|
|
510
|
+
else failed++;
|
|
511
|
+
}
|
|
512
|
+
const heading = () => {
|
|
513
|
+
const [verb] = describe(first);
|
|
514
|
+
const settled = interrupted ? "muted" : "success";
|
|
515
|
+
const role = failed ? "error" : run.some((tool) => tool.isPartial) ? "warning" : settled;
|
|
516
|
+
const dot = theme.fg(role, "•");
|
|
517
|
+
const action = theme.bold(theme.fg("customMessageLabel", verb || summary(name)));
|
|
518
|
+
return ` ${dot} ${action}${verb ? ` ${theme.fg("toolTitle", summary(name))}` : ""}`;
|
|
519
|
+
};
|
|
520
|
+
rows.push(blockGap);
|
|
521
|
+
if (grouped) {
|
|
522
|
+
let title = titles.get(first);
|
|
523
|
+
if (!title) {
|
|
524
|
+
title = new Text("", 0, 0);
|
|
525
|
+
titles.set(first, title);
|
|
526
|
+
}
|
|
527
|
+
const status = failed ? theme.fg("error", ` · ${failed} failed`) : "";
|
|
528
|
+
const caption = `${heading()} ×${run.length}${status}`;
|
|
529
|
+
if (run.length <= 10) {
|
|
530
|
+
title.setText(truncateToWidth(caption, width));
|
|
531
|
+
rows.push(title);
|
|
532
|
+
} else {
|
|
533
|
+
let control = controls.get(first);
|
|
534
|
+
if (!control) {
|
|
535
|
+
control = historyControl(first, title);
|
|
536
|
+
controls.set(first, control);
|
|
537
|
+
}
|
|
538
|
+
const action = theme.fg(
|
|
539
|
+
pressed === first ? "toolTitle" : "muted",
|
|
540
|
+
showAll.has(first) ? "Show less" : "Show all",
|
|
541
|
+
);
|
|
542
|
+
const titleLine = truncateToWidth(caption, width);
|
|
543
|
+
title.setText(
|
|
544
|
+
visibleWidth(titleLine) + 3 + visibleWidth(action) <= width
|
|
545
|
+
? `${titleLine} · ${action}`
|
|
546
|
+
: `${titleLine}\n${truncateToWidth(action, width)}`,
|
|
547
|
+
);
|
|
548
|
+
rows.push(control);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
for (let i = showAll.has(first) ? 0 : Math.max(0, run.length - 10); i < run.length; i++) {
|
|
553
|
+
const tool = run[i]!;
|
|
554
|
+
let call = calls.get(tool);
|
|
555
|
+
if (!call) {
|
|
556
|
+
call = createCall(tool);
|
|
557
|
+
calls.set(tool, call);
|
|
558
|
+
}
|
|
559
|
+
if (tool.toolName === "read" ? !tool.expanded : tool.expanded) previews.delete(tool);
|
|
560
|
+
const open = tool.expanded || previews.has(tool);
|
|
561
|
+
const last = i === run.length - 1;
|
|
562
|
+
const [, subject] = describe(tool);
|
|
563
|
+
const start = tool.isPartial ? starts?.get(tool.toolCallId) : undefined;
|
|
564
|
+
const error = tool.result?.isError && (cancelled?.has(tool.toolCallId) ? "cancelled" : "failed");
|
|
565
|
+
const state = error || (!tool.isPartial ? "" : name ? "running" : "preparing…");
|
|
566
|
+
const duration =
|
|
567
|
+
state === "cancelled" ? (cancelled?.get(tool.toolCallId) ?? tool.result?.durationMs) : undefined;
|
|
568
|
+
const elapsed = start === undefined ? "" : formatDuration(performance.now() - start);
|
|
569
|
+
const regions = before.get(tool);
|
|
570
|
+
const branch = grouped && width >= 9 ? (last ? " └─ " : " ├─ ") : "";
|
|
571
|
+
const guide = width < 8 ? "" : !grouped ? " " : last ? " " : " │ ";
|
|
572
|
+
if (regions) {
|
|
573
|
+
for (const row of regions) {
|
|
574
|
+
row.live = false;
|
|
575
|
+
row.guide = width >= 8 ? theme.fg("dim", " │ ") : "";
|
|
576
|
+
rows.push(row);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
const active = motion && tool.isPartial && !error && width > 1;
|
|
580
|
+
animating ||= active || !!elapsed;
|
|
581
|
+
const labelKey = `${revision}:${width}:${grouped}:${last}:${open}:${state}:${elapsed}:${duration ?? ""}:${active ? frame : 0}:${subject}`;
|
|
582
|
+
if (labelKey !== call.labelKey) {
|
|
583
|
+
call.labelKey = labelKey;
|
|
584
|
+
const available = width - branch.length - 2;
|
|
585
|
+
let suffix = state ? ` · ${state}` : "";
|
|
586
|
+
if (duration !== undefined) {
|
|
587
|
+
const timed = `${suffix} · ${formatDuration(duration)}`;
|
|
588
|
+
if (timed.length < available) suffix = timed;
|
|
589
|
+
} else if (elapsed) {
|
|
590
|
+
const full = `${suffix} ${elapsed}`;
|
|
591
|
+
suffix = full.length < available ? full : ` · ${elapsed}`;
|
|
592
|
+
}
|
|
593
|
+
const icon = theme.fg("muted", open ? "▾" : "▸");
|
|
594
|
+
const status = suffix.length < available ? theme.fg(state === "failed" ? "error" : "muted", suffix) : "";
|
|
595
|
+
const label = theme.fg("dim", subject || summary(name));
|
|
596
|
+
const caption = grouped ? label : !name ? " •" : subject ? `${heading()} ${label}` : heading();
|
|
597
|
+
const script = truncateToWidth(caption, Math.max(0, available - visibleWidth(status)), "…");
|
|
598
|
+
const line = `${script}${status} ${icon}`;
|
|
599
|
+
call.label.setText(width <= 1 ? icon : theme.fg("dim", branch) + (active ? shimmer(line, frame) : line));
|
|
600
|
+
}
|
|
601
|
+
rows.push(call.row);
|
|
602
|
+
if (open) {
|
|
603
|
+
call.details ??= indentedDetails(tool, theme, previews, tui);
|
|
604
|
+
const details = call.details;
|
|
605
|
+
details.revision = revision;
|
|
606
|
+
details.guide = guide.includes("│") ? theme.fg("dim", guide) : guide;
|
|
607
|
+
rows.push(details);
|
|
608
|
+
if (!last) rows.push(branchGap);
|
|
609
|
+
} else call.details = undefined;
|
|
610
|
+
}
|
|
611
|
+
run = [];
|
|
612
|
+
for (const { message } of pending) rows.push(message);
|
|
613
|
+
pending = [];
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
for (const child of chat.children) {
|
|
617
|
+
if (isToolRow(child)) {
|
|
618
|
+
if (child.toolName !== name) flush();
|
|
619
|
+
else if (pending.length) {
|
|
620
|
+
before.set(
|
|
621
|
+
child,
|
|
622
|
+
pending.flatMap(({ regions }) => regions),
|
|
623
|
+
);
|
|
624
|
+
pending = [];
|
|
625
|
+
}
|
|
626
|
+
name = child.toolName;
|
|
627
|
+
run.push(child);
|
|
628
|
+
} else {
|
|
629
|
+
if (child instanceof AssistantMessageComponent) {
|
|
630
|
+
const regions = styleThoughts(child);
|
|
631
|
+
if (run.length && regions) {
|
|
632
|
+
if (regions.length) pending.push({ message: child, regions });
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
flush();
|
|
637
|
+
const notice = child instanceof CustomMessageComponent && goalRow(child);
|
|
638
|
+
if (notice) {
|
|
639
|
+
rows.push(blockGap, notice);
|
|
640
|
+
if (Reflect.get(child, "_expanded")) rows.push(child);
|
|
641
|
+
} else rows.push(child);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
flush();
|
|
645
|
+
if (animating && !animation) {
|
|
646
|
+
animation = setInterval(
|
|
647
|
+
() => {
|
|
648
|
+
frame++;
|
|
649
|
+
tui.requestRender();
|
|
650
|
+
},
|
|
651
|
+
motion ? 25 : 1000,
|
|
652
|
+
);
|
|
653
|
+
animation.unref();
|
|
654
|
+
} else if (!animating && animation) {
|
|
655
|
+
clearInterval(animation);
|
|
656
|
+
animation = undefined;
|
|
657
|
+
frame = 0;
|
|
658
|
+
}
|
|
659
|
+
view.children = rows;
|
|
660
|
+
return render(width);
|
|
661
|
+
};
|
|
662
|
+
document.children[2] = view;
|
|
663
|
+
return {
|
|
664
|
+
dispose() {
|
|
665
|
+
clearInterval(animation);
|
|
666
|
+
clearTimeout(settle);
|
|
667
|
+
for (const message of chat.children) {
|
|
668
|
+
if (!(message instanceof AssistantMessageComponent)) continue;
|
|
669
|
+
const [content] = message.children;
|
|
670
|
+
if (content instanceof Container) {
|
|
671
|
+
for (const [i, part] of content.children.entries()) {
|
|
672
|
+
const original = originals.get(part);
|
|
673
|
+
if (original) content.children[i] = original;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
if (document.children[2] === view) document.children[2] = chat;
|
|
678
|
+
},
|
|
679
|
+
};
|
|
680
|
+
}
|