@arhen/pi-senja 1.5.2 → 1.5.4
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 +1 -1
- package/package.json +1 -1
- package/src/diff-counts.ts +69 -0
- package/src/index.ts +4 -1
- package/src/tool-groups.ts +27 -8
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Forked from [pi-haiku](https://github.com/nnocte/pi-haiku) **0.2.0** by **nocte*
|
|
|
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
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 ▸`.
|
|
13
|
+
- **Grouped tool calls** — a single call stays on one line, e.g. `• Write example.ts ▸`. Titled codemode summaries can use the full pane width. Untitled script previews and other tool summaries use at most 60%. 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
14
|
- **Shared transcript renderer** — compatible subagent views use the same renderer as the leader when Senja is enabled. Other Pi extensions can synchronously discover it via `pi.events.emit("pi:transcript-renderer", provider => { … })`. Mount with `provider.mount(chatContainer, tui, theme, starts?, cancelled?)`, render and send clicks to its `root`, and call `dispose()` when the view closes. The optional maps use tool call IDs and monotonic milliseconds (starts or frozen durations). With no provider, render the native container. This is opt-in for custom views; non-transcript panels are unchanged.
|
|
15
15
|
- **Tool activity** — A call shows `preparing…` without a timer while Pi receives its arguments. Pi’s execution-start event switches the row to `running 0s`; writing the script does not count. Expanded results keep Pi’s own reported duration. Confirmed interruptions show `cancelled` before execution, or `cancelled · 8s` after it starts, without counting as failures.
|
|
16
16
|
- **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.
|
package/package.json
CHANGED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { open } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { type ExtensionAPI, generateDiffString } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
|
|
8
|
+
export function countDiff(diff: string) {
|
|
9
|
+
return { added: diff.match(/(?:^|\n)\+/g)?.length ?? 0, removed: diff.match(/(?:^|\n)-/g)?.length ?? 0 };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const lines = (s: string) => (s.match(/\n/g)?.length ?? 0) + Number(!!s && !s.endsWith("\n"));
|
|
13
|
+
|
|
14
|
+
export function trackWrites(pi: ExtensionAPI, enabled = () => true) {
|
|
15
|
+
type Entry = { path: string; overlap?: boolean; counts?: ReturnType<typeof countDiff> };
|
|
16
|
+
const pending = new Map<string, Entry>();
|
|
17
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
18
|
+
if (!enabled() || event.toolName !== "write" || event.parentToolCallId) return;
|
|
19
|
+
const { path, content } = event.input;
|
|
20
|
+
if (typeof path !== "string" || typeof content !== "string" || content.includes("\0")) return;
|
|
21
|
+
if (!pi.getAllTools().some((tool) => tool.name === "write" && tool.sourceInfo?.path === "builtin:write")) return;
|
|
22
|
+
try {
|
|
23
|
+
const raw = path.replace(/^@/, "").replace(/[\u00a0\u2000-\u200a\u202f\u205f\u3000]/g, " ");
|
|
24
|
+
const target = resolve(
|
|
25
|
+
ctx.cwd,
|
|
26
|
+
raw.startsWith("file://") ? fileURLToPath(raw) : raw.replace(/^~(?=\/|$)/, homedir()),
|
|
27
|
+
);
|
|
28
|
+
const entry: Entry = { path: target };
|
|
29
|
+
for (const other of pending.values()) {
|
|
30
|
+
if (other.path === target) other.overlap = entry.overlap = true;
|
|
31
|
+
}
|
|
32
|
+
pending.set(event.toolCallId, entry);
|
|
33
|
+
if (entry.overlap) return;
|
|
34
|
+
let before = "";
|
|
35
|
+
try {
|
|
36
|
+
const file = await open(target, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
37
|
+
try {
|
|
38
|
+
const stat = await file.stat();
|
|
39
|
+
if (!stat.isFile() || stat.size > 512 * 1024) return;
|
|
40
|
+
const bytes = Buffer.alloc(stat.size + 1);
|
|
41
|
+
const { bytesRead } = await file.read(bytes);
|
|
42
|
+
if (bytesRead !== stat.size) return;
|
|
43
|
+
before = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, bytesRead));
|
|
44
|
+
} finally {
|
|
45
|
+
await file.close();
|
|
46
|
+
}
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") return;
|
|
49
|
+
}
|
|
50
|
+
if (before.includes("\0")) return;
|
|
51
|
+
if (before === content) entry.counts = { added: 0, removed: 0 };
|
|
52
|
+
else if (!before || !content) entry.counts = { added: lines(content), removed: lines(before) };
|
|
53
|
+
else {
|
|
54
|
+
// ponytail: skip expensive whole-file rewrites; move larger diffs to a worker if needed.
|
|
55
|
+
if (content.length > 512 * 1024 || (before + content).split("\n", 2049).length > 2048) return;
|
|
56
|
+
entry.counts = countDiff(generateDiffString(before, content).diff);
|
|
57
|
+
}
|
|
58
|
+
} catch {
|
|
59
|
+
// Optional display metadata must never block the write.
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
pi.on("tool_result", (event) => {
|
|
63
|
+
const entry = pending.get(event.toolCallId);
|
|
64
|
+
pending.delete(event.toolCallId);
|
|
65
|
+
if (event.toolName === "write" && !event.isError && entry?.counts && !entry.overlap && event.details == null)
|
|
66
|
+
return { details: { senjaCounts: entry.counts } };
|
|
67
|
+
});
|
|
68
|
+
pi.on("agent_end", () => pending.clear());
|
|
69
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -21,6 +21,7 @@ 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 { trackWrites } from "./diff-counts.ts";
|
|
24
25
|
import { createTranscriptView, formatDuration, installToolGroups } from "./tool-groups.ts";
|
|
25
26
|
|
|
26
27
|
// ── Visual primitives ────────────────────────────────────────────────────────
|
|
@@ -382,6 +383,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
382
383
|
let renderHandle: RenderHandle | undefined;
|
|
383
384
|
let disposeFooter: (() => void) | undefined;
|
|
384
385
|
let enabled = true;
|
|
386
|
+
trackWrites(pi, () => enabled);
|
|
385
387
|
const starts = new Map<string, number>();
|
|
386
388
|
const cancelled = new Map<string, number | undefined>();
|
|
387
389
|
function startCall(id: string) {
|
|
@@ -418,7 +420,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
418
420
|
const guide =
|
|
419
421
|
"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.";
|
|
420
422
|
const unsubscribeTranscript = pi.events.on("pi:transcript-renderer", (accept) => {
|
|
421
|
-
if (enabled && typeof accept === "function")
|
|
423
|
+
if (enabled && typeof accept === "function")
|
|
424
|
+
accept({ mount: createTranscriptView, codemodeGuide: guide, trackWrites });
|
|
422
425
|
});
|
|
423
426
|
pi.on("before_agent_start", (event, ctx) => {
|
|
424
427
|
if (!enabled || ctx.mode !== "tui" || !event.systemPromptOptions?.selectedTools.includes("codemode")) return;
|
package/src/tool-groups.ts
CHANGED
|
@@ -23,6 +23,8 @@ import {
|
|
|
23
23
|
wrapTextWithAnsi,
|
|
24
24
|
} from "@earendil-works/pi-tui";
|
|
25
25
|
|
|
26
|
+
import { countDiff } from "./diff-counts.ts";
|
|
27
|
+
|
|
26
28
|
type ToolRow = Component & {
|
|
27
29
|
toolName: string;
|
|
28
30
|
toolCallId: string;
|
|
@@ -34,7 +36,7 @@ type ToolRow = Component & {
|
|
|
34
36
|
result?: {
|
|
35
37
|
isError: boolean;
|
|
36
38
|
durationMs?: number;
|
|
37
|
-
details?: { diff?: string };
|
|
39
|
+
details?: { diff?: string; senjaCounts?: ReturnType<typeof countDiff> };
|
|
38
40
|
content?: { type: string; text?: string }[];
|
|
39
41
|
};
|
|
40
42
|
setExpanded(value: boolean): void;
|
|
@@ -90,7 +92,7 @@ function createShimmer(theme: Theme) {
|
|
|
90
92
|
};
|
|
91
93
|
}
|
|
92
94
|
|
|
93
|
-
function describe(tool: ToolRow): [string, string] {
|
|
95
|
+
function describe(tool: ToolRow): [verb: string, subject: string, hasTitle?: boolean] {
|
|
94
96
|
const a = tool.args ?? {};
|
|
95
97
|
switch (tool.toolName) {
|
|
96
98
|
case "read": {
|
|
@@ -117,7 +119,8 @@ function describe(tool: ToolRow): [string, string] {
|
|
|
117
119
|
typeof code === "string"
|
|
118
120
|
? /^(?:\/\/ @options:[^\n]*\n)?\/\/ @title:[ \t]*([^\r\n]+)/.exec(code.slice(0, 2048))
|
|
119
121
|
: undefined;
|
|
120
|
-
|
|
122
|
+
const plan = summary(title?.[1]);
|
|
123
|
+
return ["Ran", plan || summary(code), !!plan];
|
|
121
124
|
}
|
|
122
125
|
default:
|
|
123
126
|
return ["Called", summary(a.path ?? a.query)];
|
|
@@ -498,6 +501,7 @@ export function createTranscriptView(
|
|
|
498
501
|
let animation: ReturnType<typeof setInterval> | undefined;
|
|
499
502
|
let pressed: Component | undefined;
|
|
500
503
|
let settle: ReturnType<typeof setTimeout> | undefined;
|
|
504
|
+
const editCounts = new WeakMap<object, ReturnType<typeof countDiff>>();
|
|
501
505
|
const calls = new WeakMap<
|
|
502
506
|
Component,
|
|
503
507
|
{
|
|
@@ -622,7 +626,7 @@ export function createTranscriptView(
|
|
|
622
626
|
if (tool.toolName === "read" ? !tool.expanded : tool.expanded) previews.delete(tool);
|
|
623
627
|
const open = tool.expanded || previews.has(tool);
|
|
624
628
|
const last = i === run.length - 1;
|
|
625
|
-
const [, subject] = describe(tool);
|
|
629
|
+
const [, subject, hasTitle] = describe(tool);
|
|
626
630
|
const start = tool.isPartial ? starts?.get(tool.toolCallId) : undefined;
|
|
627
631
|
const error = tool.result?.isError && (cancelled?.has(tool.toolCallId) ? "cancelled" : "failed");
|
|
628
632
|
const running = start !== undefined || tool.executionStarted;
|
|
@@ -631,7 +635,7 @@ export function createTranscriptView(
|
|
|
631
635
|
state === "cancelled" ? (tool.result?.durationMs ?? cancelled?.get(tool.toolCallId)) : undefined;
|
|
632
636
|
const elapsed = start === undefined ? "" : formatDuration(performance.now() - start);
|
|
633
637
|
const regions = before.get(tool);
|
|
634
|
-
const rowWidth =
|
|
638
|
+
const rowWidth = hasTitle ? width : Math.max(1, Math.floor(width * 0.6));
|
|
635
639
|
const branch = grouped && rowWidth >= 9 ? (last ? " └─ " : " ├─ ") : "";
|
|
636
640
|
const guide = width < 8 ? "" : !grouped ? " " : last ? " " : " │ ";
|
|
637
641
|
if (regions) {
|
|
@@ -643,7 +647,13 @@ export function createTranscriptView(
|
|
|
643
647
|
}
|
|
644
648
|
const active = motion && tool.isPartial && !error && width > 1;
|
|
645
649
|
animating ||= active || !!elapsed;
|
|
646
|
-
const
|
|
650
|
+
const result = !tool.isPartial && !error ? tool.result : undefined;
|
|
651
|
+
let counts = name === "write" ? result?.details?.senjaCounts : undefined;
|
|
652
|
+
if (name === "edit" && result && typeof result.details?.diff === "string") {
|
|
653
|
+
counts = editCounts.get(result) ?? countDiff(result.details.diff);
|
|
654
|
+
editCounts.set(result, counts);
|
|
655
|
+
}
|
|
656
|
+
const labelKey = `${counts?.added}:${counts?.removed}:${revision}:${rowWidth}:${grouped}:${last}:${open}:${state}:${elapsed}:${duration ?? ""}:${active ? frame : 0}:${subject}`;
|
|
647
657
|
if (labelKey !== call.labelKey) {
|
|
648
658
|
call.labelKey = labelKey;
|
|
649
659
|
const available = rowWidth - branch.length - 2;
|
|
@@ -661,8 +671,17 @@ export function createTranscriptView(
|
|
|
661
671
|
const title = () =>
|
|
662
672
|
state === "preparing…" ? ` ${theme.fg("warning", "•")} ${theme.fg("toolTitle", summary(name))}` : heading();
|
|
663
673
|
const caption = grouped ? label : !name ? " •" : subject ? `${title()} ${label}` : title();
|
|
664
|
-
const
|
|
665
|
-
|
|
674
|
+
const stats =
|
|
675
|
+
counts &&
|
|
676
|
+
Number.isSafeInteger(counts.added) &&
|
|
677
|
+
counts.added >= 0 &&
|
|
678
|
+
Number.isSafeInteger(counts.removed) &&
|
|
679
|
+
counts.removed >= 0
|
|
680
|
+
? ` ${theme.fg("toolDiffAdded", `+${counts.added}`)} ${theme.fg("toolDiffRemoved", `-${counts.removed}`)}`
|
|
681
|
+
: "";
|
|
682
|
+
const tail = stats && visibleWidth(stats) + (grouped ? 1 : 9) <= available ? stats : status;
|
|
683
|
+
const script = truncateToWidth(caption, Math.max(0, available - visibleWidth(tail)), "…");
|
|
684
|
+
const line = `${script}${tail} ${icon}`;
|
|
666
685
|
call.label.setText(rowWidth <= 1 ? icon : theme.fg("dim", branch) + (active ? shimmer(line, frame) : line));
|
|
667
686
|
}
|
|
668
687
|
rows.push(call.row);
|