@bismawy/pi-arnative 0.13.0 → 0.15.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/CHANGELOG.md +20 -0
- package/README.md +2 -2
- package/extensions/arnative.ts +353 -59
- package/extensions/autocompact.ts +142 -30
- package/extensions/budget.ts +4 -3
- package/extensions/tools.ts +228 -15
- package/extensions/ui-render-tweaks.ts +23 -7
- package/extensions/usage.ts +3 -4
- package/lib/color.ts +34 -0
- package/lib/list-picker.ts +11 -11
- package/lib/preset-store.ts +10 -1
- package/lib/usage-store.ts +4 -5
- package/package.json +49 -49
- package/themes/arnative-blossom.json +9 -9
- package/themes/arnative-crimson.json +10 -10
- package/themes/arnative-cyberpunk.json +9 -9
- package/themes/arnative-dracula.json +9 -9
- package/themes/arnative-earthy.json +10 -10
- package/themes/arnative-garden.json +10 -10
- package/themes/arnative-gruvbox.json +10 -10
- package/themes/arnative-lemonade.json +9 -9
- package/themes/arnative-magical.json +9 -9
- package/themes/arnative-matrix.json +9 -9
- package/themes/arnative-neutral.json +9 -9
- package/themes/arnative-nord.json +8 -8
- package/themes/arnative-zinc.json +9 -9
- package/themes/arnative.json +9 -9
- package/themes/gen-themes.mjs +43 -15
|
@@ -21,7 +21,7 @@ import { mkdtempSync, rmSync } from "node:fs";
|
|
|
21
21
|
import { tmpdir } from "node:os";
|
|
22
22
|
import { join } from "node:path";
|
|
23
23
|
import { assert, isMain } from "../lib/check.ts";
|
|
24
|
-
import { loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
|
|
24
|
+
import { PAYLOAD_LIMIT_KEY, loadChoice, loadSetting, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
|
|
25
25
|
import { activeRenderCache, setRenderCache } from "./render-cache.ts";
|
|
26
26
|
|
|
27
27
|
/** Stored exactly as the picker shows them; `Off` disables the trigger entirely. */
|
|
@@ -30,24 +30,106 @@ export type AutoCompactChoice = (typeof AUTO_COMPACT_CHOICES)[number];
|
|
|
30
30
|
export const DEFAULT_AUTO_COMPACT: AutoCompactChoice = "Off";
|
|
31
31
|
export const AUTO_COMPACT_KEY = "autoCompact";
|
|
32
32
|
|
|
33
|
-
/**
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
33
|
+
/** Proxy payload limit presets shown in `/arnative` → Payload limit. */
|
|
34
|
+
export const PAYLOAD_LIMIT_PRESETS = ["Off", "1 MB", "4 MB", "8 MB", "16 MB", "32 MB"] as const;
|
|
35
|
+
export type PayloadLimitPreset = (typeof PAYLOAD_LIMIT_PRESETS)[number];
|
|
36
|
+
export const DEFAULT_PAYLOAD_LIMIT: PayloadLimitPreset = "1 MB";
|
|
37
|
+
export const PAYLOAD_LIMIT_MB_RANGE = { min: 1, max: 1024 } as const;
|
|
38
|
+
export const PAYLOAD_LIMIT_CONFIG_KEY = Symbol.for("pi-arnative.payloadLimit");
|
|
39
|
+
|
|
40
|
+
export interface ByteCeilings {
|
|
41
|
+
mb: number;
|
|
42
|
+
shedTriggerBytes: number;
|
|
43
|
+
shedTargetBytes: number;
|
|
44
|
+
compactInputBytes: number;
|
|
45
|
+
shedTriggerAfter413Bytes: number;
|
|
46
|
+
shedTargetAfter413Bytes: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function formatMb(mb: number): string {
|
|
50
|
+
return Number.isInteger(mb) ? String(mb) : String(Number(mb.toFixed(2)));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Parse `"Off"`, a number, or `"16 MB"` / `"16m"` into normalized storage form (`"Off"` or `"<N> MB"`). */
|
|
54
|
+
export function parsePayloadLimit(raw: unknown): string | undefined {
|
|
55
|
+
if (typeof raw === "number") {
|
|
56
|
+
if (!Number.isFinite(raw) || raw < PAYLOAD_LIMIT_MB_RANGE.min || raw > PAYLOAD_LIMIT_MB_RANGE.max) return undefined;
|
|
57
|
+
return `${formatMb(raw)} MB`;
|
|
58
|
+
}
|
|
59
|
+
if (typeof raw !== "string") return undefined;
|
|
60
|
+
const trimmed = raw.trim();
|
|
61
|
+
if (/^off$/i.test(trimmed)) return "Off";
|
|
62
|
+
const m = /^(\d+(?:\.\d+)?)\s*(?:mb|m)?$/i.exec(trimmed);
|
|
63
|
+
if (!m) return undefined;
|
|
64
|
+
const mb = Number(m[1]);
|
|
65
|
+
if (!Number.isFinite(mb) || mb < PAYLOAD_LIMIT_MB_RANGE.min || mb > PAYLOAD_LIMIT_MB_RANGE.max) return undefined;
|
|
66
|
+
return `${formatMb(mb)} MB`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Numeric MB limit for a parsed payload limit string, or `null` when `"Off"`. */
|
|
70
|
+
export function payloadLimitMb(choice: string): number | null {
|
|
71
|
+
if (choice === "Off") return null;
|
|
72
|
+
const n = Number.parseFloat(choice);
|
|
73
|
+
return Number.isFinite(n) && n > 0 ? n : 1;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Shell override via `PI_ARNATIVE_BYTE_WALL_MB`, when set to a valid positive number. */
|
|
77
|
+
export function envByteWallOverride(): string | undefined {
|
|
78
|
+
const raw = process.env.PI_ARNATIVE_BYTE_WALL_MB;
|
|
79
|
+
if (typeof raw !== "string" || raw.trim() === "") return undefined;
|
|
80
|
+
const mb = Number(raw);
|
|
81
|
+
return Number.isFinite(mb) && mb > 0 ? `${formatMb(mb)} MB` : undefined;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Stored `config.json` choice (`"Off"` or `"<N> MB"`), ignoring process env overrides. */
|
|
85
|
+
export function savedPayloadLimit(): string {
|
|
86
|
+
return parsePayloadLimit(loadSetting(PAYLOAD_LIMIT_KEY)) ?? DEFAULT_PAYLOAD_LIMIT;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Active payload limit: in-session choice, else `PI_ARNATIVE_BYTE_WALL_MB`, else `config.json` (default `1 MB`). */
|
|
90
|
+
export function activePayloadLimit(): string {
|
|
91
|
+
const slot = (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
|
|
92
|
+
const fromSlot = parsePayloadLimit(slot);
|
|
93
|
+
if (fromSlot) return fromSlot;
|
|
94
|
+
return envByteWallOverride() ?? savedPayloadLimit();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Apply a payload limit live for this session and persist it to `config.json`. */
|
|
98
|
+
export function setPayloadLimit(choice: string): string {
|
|
99
|
+
const parsed = parsePayloadLimit(choice);
|
|
100
|
+
if (!parsed) throw new Error(`Invalid payload limit: ${choice}`);
|
|
101
|
+
(globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY] = parsed;
|
|
102
|
+
saveChoice(PAYLOAD_LIMIT_KEY, parsed);
|
|
103
|
+
return parsed;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Byte ceilings for an HTTP body wall in MB (ratios target 900/760/720 KB per 1 MB). */
|
|
107
|
+
export function ceilingsForMb(mb: number): ByteCeilings {
|
|
108
|
+
return {
|
|
109
|
+
mb,
|
|
110
|
+
shedTriggerBytes: Math.round(900 * 1024 * mb),
|
|
111
|
+
shedTargetBytes: Math.round(760 * 1024 * mb),
|
|
112
|
+
compactInputBytes: Math.round(720 * 1024 * mb),
|
|
113
|
+
shedTriggerAfter413Bytes: Math.round(820 * 1024 * mb),
|
|
114
|
+
shedTargetAfter413Bytes: Math.round(680 * 1024 * mb),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Active byte ceilings for this session, or `null` when payload limiting is `Off`. */
|
|
119
|
+
export function activeByteCeilings(): ByteCeilings | null {
|
|
120
|
+
const mb = payloadLimitMb(activePayloadLimit());
|
|
121
|
+
return mb === null ? null : ceilingsForMb(mb);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function trimLabelForMb(limitMb: number): string {
|
|
125
|
+
return `trimmed for ${formatMb(limitMb)}MB limit`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Module-load ceilings retained for backward-compatible test/caller imports.
|
|
129
|
+
const INITIAL_CEILINGS = ceilingsForMb(payloadLimitMb(envByteWallOverride() ?? savedPayloadLimit()) ?? 1);
|
|
130
|
+
export const SHED_TRIGGER_BYTES = INITIAL_CEILINGS.shedTriggerBytes;
|
|
131
|
+
export const SHED_TARGET_BYTES = INITIAL_CEILINGS.shedTargetBytes;
|
|
132
|
+
export const COMPACT_INPUT_BYTES = INITIAL_CEILINGS.compactInputBytes;
|
|
51
133
|
const DEFAULT_OVERHEAD_BYTES = 64 * 1024;
|
|
52
134
|
const MIN_MSG_BUDGET_BYTES = 64 * 1024;
|
|
53
135
|
const TRIMMED_TOOL_STUB = "[earlier output omitted; full output in session]";
|
|
@@ -263,7 +345,9 @@ function shrinkToolCallArgs(block: ContentBlockLike, maxArgChars: number, label:
|
|
|
263
345
|
export function shedMessagesForByteLimit<T extends MessageLike>(
|
|
264
346
|
messages: readonly T[],
|
|
265
347
|
targetMsgBytes: number,
|
|
348
|
+
limitMb = payloadLimitMb(activePayloadLimit()) ?? 1,
|
|
266
349
|
): { messages: T[]; bytes: number; changed: boolean } {
|
|
350
|
+
const trimLabel = trimLabelForMb(limitMb);
|
|
267
351
|
const sizes = messages.map((m) => jsonByteLength(m));
|
|
268
352
|
let totalBytes = jsonByteLength(messages);
|
|
269
353
|
if (totalBytes <= targetMsgBytes || messages.length === 0) {
|
|
@@ -342,7 +426,7 @@ export function shedMessagesForByteLimit<T extends MessageLike>(
|
|
|
342
426
|
i,
|
|
343
427
|
mapContentBlocks(out[i], (b) => {
|
|
344
428
|
if (b.type === "text" && typeof b.text === "string" && b.text.length > 600) {
|
|
345
|
-
return { ...b, text: truncateStringHead(b.text, 600,
|
|
429
|
+
return { ...b, text: truncateStringHead(b.text, 600, trimLabel) };
|
|
346
430
|
}
|
|
347
431
|
if (b.type === "thinking" && typeof b.thinking === "string" && b.thinking.length > 300) {
|
|
348
432
|
return { ...b, thinking: truncateStringHead(b.thinking, 300, "trimmed") };
|
|
@@ -361,9 +445,9 @@ export function shedMessagesForByteLimit<T extends MessageLike>(
|
|
|
361
445
|
return { ...b, thinking: truncateStringHead(b.thinking, 300, "trimmed") };
|
|
362
446
|
}
|
|
363
447
|
if (b.type === "text" && typeof b.text === "string" && b.text.length > 8000) {
|
|
364
|
-
return { ...b, text: truncateStringHead(b.text, 8000,
|
|
448
|
+
return { ...b, text: truncateStringHead(b.text, 8000, trimLabel) };
|
|
365
449
|
}
|
|
366
|
-
return shrinkToolCallArgs(b, 4000,
|
|
450
|
+
return shrinkToolCallArgs(b, 4000, trimLabel);
|
|
367
451
|
}),
|
|
368
452
|
);
|
|
369
453
|
}
|
|
@@ -384,7 +468,7 @@ export function shedMessagesForByteLimit<T extends MessageLike>(
|
|
|
384
468
|
if (dropEnd > 0) {
|
|
385
469
|
const kept = out.slice(dropEnd);
|
|
386
470
|
if (kept[0]?.role !== "user") {
|
|
387
|
-
kept.unshift({ role: "user", content: [{ type: "text", text:
|
|
471
|
+
kept.unshift({ role: "user", content: [{ type: "text", text: `[earlier turns omitted for ${formatMb(limitMb)}MB request limit]` }] } as T);
|
|
388
472
|
}
|
|
389
473
|
return { messages: kept, bytes: jsonByteLength(kept), changed: true };
|
|
390
474
|
}
|
|
@@ -457,10 +541,12 @@ let trackedOverheadBytes = -1;
|
|
|
457
541
|
/** Last observed wire size (messages + overhead) for byte-limited models, or null.
|
|
458
542
|
* Consumed by the footer to show payload pressure against the 1 MB proxy wall. */
|
|
459
543
|
export function wireBytesSnapshot(): { bytes: number; limit: number } | null {
|
|
544
|
+
const ceilings = activeByteCeilings();
|
|
545
|
+
if (!ceilings) return null;
|
|
460
546
|
const state = (globalThis as Record<symbol, AutoCompactState | undefined>)[Symbol.for("pi-arnative.autocompactState")];
|
|
461
547
|
if (!state || state.lastMessagesBytes <= 0) return null;
|
|
462
548
|
const overhead = state.overheadBytes > 0 ? state.overheadBytes : DEFAULT_OVERHEAD_BYTES;
|
|
463
|
-
return { bytes: state.lastMessagesBytes + overhead, limit:
|
|
549
|
+
return { bytes: state.lastMessagesBytes + overhead, limit: ceilings.shedTriggerBytes };
|
|
464
550
|
}
|
|
465
551
|
|
|
466
552
|
export default function registerAutoCompact(pi: ExtensionAPI): void {
|
|
@@ -503,6 +589,8 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
|
|
|
503
589
|
});
|
|
504
590
|
|
|
505
591
|
pi.on("context", async (event, ctx) => {
|
|
592
|
+
const ceilings = activeByteCeilings();
|
|
593
|
+
if (!ceilings) return;
|
|
506
594
|
// Skip the full-transcript JSON.stringify entirely for models with no byte wall:
|
|
507
595
|
// measurement is the only cost here, and non-remote sessions pay it every turn.
|
|
508
596
|
if (!state.saw413 && !isByteLimitedModel(ctx?.model)) return;
|
|
@@ -513,13 +601,13 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
|
|
|
513
601
|
state.lastMessagesBytes = msgBytes;
|
|
514
602
|
state.awaitingContextPayload = true;
|
|
515
603
|
|
|
516
|
-
const triggerBytes = state.saw413 ?
|
|
517
|
-
const targetBytes = state.saw413 ?
|
|
604
|
+
const triggerBytes = state.saw413 ? ceilings.shedTriggerAfter413Bytes : ceilings.shedTriggerBytes;
|
|
605
|
+
const targetBytes = state.saw413 ? ceilings.shedTargetAfter413Bytes : ceilings.shedTargetBytes;
|
|
518
606
|
const effectiveOverhead = state.overheadBytes > 0 ? state.overheadBytes : DEFAULT_OVERHEAD_BYTES;
|
|
519
607
|
if (msgBytes + effectiveOverhead < triggerBytes) return;
|
|
520
608
|
|
|
521
609
|
const targetMsgBytes = Math.max(MIN_MSG_BUDGET_BYTES, targetBytes - effectiveOverhead);
|
|
522
|
-
const shed = shedMessagesForByteLimit(messages, targetMsgBytes);
|
|
610
|
+
const shed = shedMessagesForByteLimit(messages, targetMsgBytes, ceilings.mb);
|
|
523
611
|
if (!shed.changed) return;
|
|
524
612
|
|
|
525
613
|
state.lastMessagesBytes = shed.bytes;
|
|
@@ -541,6 +629,8 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
|
|
|
541
629
|
|
|
542
630
|
pi.on("session_before_compact", async (event, ctx) => {
|
|
543
631
|
state.compacting = true;
|
|
632
|
+
const ceilings = activeByteCeilings();
|
|
633
|
+
if (!ceilings) return;
|
|
544
634
|
if (!state.saw413 && !isByteLimitedModel(ctx?.model)) return;
|
|
545
635
|
const prep = (
|
|
546
636
|
event as {
|
|
@@ -553,9 +643,9 @@ export default function registerAutoCompact(pi: ExtensionAPI): void {
|
|
|
553
643
|
)?.preparation;
|
|
554
644
|
if (!prep) return;
|
|
555
645
|
const prevBytes = prep.previousSummary ? jsonByteLength(prep.previousSummary) : 0;
|
|
556
|
-
const summaryBudget = Math.max(128 * 1024,
|
|
646
|
+
const summaryBudget = Math.max(128 * 1024, ceilings.compactInputBytes - prevBytes);
|
|
557
647
|
trimCompactionInput(prep.messagesToSummarize, summaryBudget);
|
|
558
|
-
trimCompactionInput(prep.turnPrefixMessages, Math.round(
|
|
648
|
+
trimCompactionInput(prep.turnPrefixMessages, Math.round(ceilings.compactInputBytes / 2));
|
|
559
649
|
});
|
|
560
650
|
|
|
561
651
|
pi.on("agent_before_settle", async (_event, ctx) => {
|
|
@@ -607,6 +697,22 @@ if (isMain(import.meta.url)) {
|
|
|
607
697
|
const fixture = mkdtempSync(join(tmpdir(), "arnative-autocompact-"));
|
|
608
698
|
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
609
699
|
delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
|
|
700
|
+
delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
|
|
701
|
+
|
|
702
|
+
// Payload limit parsing, persistence, and Off mode.
|
|
703
|
+
assert(parsePayloadLimit("off") === "Off", "parses off case-insensitively");
|
|
704
|
+
assert(parsePayloadLimit("11") === "11 MB" && parsePayloadLimit("11mb") === "11 MB", "normalizes MB unit");
|
|
705
|
+
assert(parsePayloadLimit(16) === "16 MB", "accepts numeric MB");
|
|
706
|
+
assert(parsePayloadLimit("0") === undefined && parsePayloadLimit("2000") === undefined && parsePayloadLimit("abc") === undefined, "rejects out-of-range or invalid payload limits");
|
|
707
|
+
assert(savedPayloadLimit() === "1 MB", "stored payload limit defaults to 1 MB");
|
|
708
|
+
setPayloadLimit("11 MB");
|
|
709
|
+
assert(activePayloadLimit() === "11 MB" && savedPayloadLimit() === "11 MB", "custom payload limit applies live and persists");
|
|
710
|
+
assert(activeByteCeilings()!.shedTriggerBytes === Math.round(900 * 1024 * 11), "custom MB scales shed trigger");
|
|
711
|
+
setPayloadLimit("Off");
|
|
712
|
+
assert(activeByteCeilings() === null, "Off disables byte ceilings");
|
|
713
|
+
delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
|
|
714
|
+
saveChoice(PAYLOAD_LIMIT_KEY, "1 MB");
|
|
715
|
+
resetPresetCache();
|
|
610
716
|
|
|
611
717
|
// Choice parsing and persistence.
|
|
612
718
|
assert(activeAutoCompact() === "Off", "the default is off");
|
|
@@ -851,9 +957,14 @@ if (isMain(import.meta.url)) {
|
|
|
851
957
|
const after413 = (await handlers.context!({ messages: hugeRunMsgs }, nonRemoteCtx)) as { messages?: MessageLike[] } | undefined;
|
|
852
958
|
assert(
|
|
853
959
|
Array.isArray(after413?.messages) &&
|
|
854
|
-
jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <=
|
|
960
|
+
jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <= INITIAL_CEILINGS.shedTargetAfter413Bytes,
|
|
855
961
|
"saw413 activates tighter silent shedding on any model",
|
|
856
962
|
);
|
|
963
|
+
// Payload limit Off skips shedding and clears wireBytesSnapshot even for remote models.
|
|
964
|
+
setPayloadLimit("Off");
|
|
965
|
+
const offResult = await handlers.context!({ messages: hugeRunMsgs }, remoteCtx);
|
|
966
|
+
assert(offResult === undefined && wireBytesSnapshot() === null, "Off disables silent shedding and wireBytesSnapshot");
|
|
967
|
+
delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
|
|
857
968
|
setAutoCompact("Smart");
|
|
858
969
|
|
|
859
970
|
// i1 guard: models with no byte wall never measure payload bytes at all.
|
|
@@ -884,6 +995,7 @@ if (isMain(import.meta.url)) {
|
|
|
884
995
|
rmSync(fixture, { recursive: true, force: true });
|
|
885
996
|
delete process.env.PI_CODING_AGENT_DIR;
|
|
886
997
|
delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
|
|
998
|
+
delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
|
|
887
999
|
delete (globalThis as Record<symbol, unknown>)[Symbol.for("pi-arnative.renderCache")];
|
|
888
1000
|
resetPresetCache();
|
|
889
1001
|
console.log("autocompact.ts self-check OK");
|
package/extensions/budget.ts
CHANGED
|
@@ -24,7 +24,7 @@ import { matchesKey, truncateToWidth, visibleWidth, type Component } from "@eare
|
|
|
24
24
|
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
25
25
|
import { tmpdir } from "node:os";
|
|
26
26
|
import { join } from "node:path";
|
|
27
|
-
import { thinkingColorOf } from "../lib/ansi.ts";
|
|
27
|
+
import { softOf, thinkingColorOf } from "../lib/ansi.ts";
|
|
28
28
|
import { renderScreen, screenTitle } from "../lib/box.ts";
|
|
29
29
|
import { assert, isMain } from "../lib/check.ts";
|
|
30
30
|
import { announce } from "../lib/status-widget.ts";
|
|
@@ -343,6 +343,7 @@ class BudgetModalComponent implements Component {
|
|
|
343
343
|
const bold = th.bold ?? ((t: string) => t);
|
|
344
344
|
const dim = (s: string) => th.fg("dim", s);
|
|
345
345
|
const acc = (s: string) => th.fg("accent", s);
|
|
346
|
+
const soft = softOf(th);
|
|
346
347
|
// Levels ride the active theme's semantic slots: OK accent, WARN warning, OVER error.
|
|
347
348
|
const levelPaint = (level: BudgetLevel) =>
|
|
348
349
|
level === "ok" ? acc : level === "warn" ? (s: string) => th.fg("warning", s) : (s: string) => th.fg("error", s);
|
|
@@ -382,10 +383,10 @@ class BudgetModalComponent implements Component {
|
|
|
382
383
|
for (let i = 0; i < this.rows.length; i++) {
|
|
383
384
|
const row = this.rows[i]!;
|
|
384
385
|
const isSelected = i === this.selected;
|
|
385
|
-
const paint = isSelected ? (s: string) =>
|
|
386
|
+
const paint = isSelected ? (s: string) => soft(bold(s)) : (s: string) => th.fg("text", s);
|
|
386
387
|
const note = budgetRowNote(row.label);
|
|
387
388
|
const noteText = note ? ` ${dim("·")} ${dim(note)}` : "";
|
|
388
|
-
body.push(`${isSelected ? acc("
|
|
389
|
+
body.push(`${isSelected ? acc("❯ ") : " "}${paint(row.label)}${noteText}`);
|
|
389
390
|
}
|
|
390
391
|
return renderScreen(th, width, this.text, body.map((l) => truncateToWidth(l, contentW, "")), this.edge);
|
|
391
392
|
}
|
package/extensions/tools.ts
CHANGED
|
@@ -37,14 +37,18 @@ import {
|
|
|
37
37
|
ToolExecutionComponent,
|
|
38
38
|
} from "@earendil-works/pi-coding-agent";
|
|
39
39
|
import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
40
|
-
import {
|
|
40
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
41
|
+
import { homedir, tmpdir } from "node:os";
|
|
42
|
+
import { join } from "node:path";
|
|
41
43
|
import { inSpans, renderBoxLines as box, type TextSpan, textSpans } from "../lib/box.ts";
|
|
42
44
|
import { getActiveTheme, stripAnsi, softSecondaryOf } from "../lib/ansi.ts";
|
|
43
45
|
import { actionWord } from "../lib/todos.ts";
|
|
46
|
+
import { EDIT_DIFF_KEY, loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
|
|
47
|
+
import { clearRenderCache } from "./render-cache.ts";
|
|
44
48
|
import { assert, isMain } from "../lib/check.ts";
|
|
45
49
|
import { markPatched, originalOf } from "../lib/patch.ts";
|
|
46
50
|
|
|
47
|
-
type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string };
|
|
51
|
+
type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; inverse?(text: string): string };
|
|
48
52
|
type TResult = { content: Array<{ type: string; text?: string }>; isError?: boolean; details?: any };
|
|
49
53
|
type TCtx = { isError?: boolean; toolCallId?: string; args?: any; state?: Record<string, unknown>; durationMs?: number };
|
|
50
54
|
type Res = (r: TResult, th: Theme, soft: (s: string) => string, isErr: boolean, expanded: boolean) => string;
|
|
@@ -881,7 +885,7 @@ function minimal(
|
|
|
881
885
|
name: (th: Theme, soft: (s: string) => string) => string,
|
|
882
886
|
call: (a: any, th: Theme, soft: (s: string) => string, expanded: boolean) => string,
|
|
883
887
|
res: Res = resText,
|
|
884
|
-
full: (r: TResult, th: Theme) => string[] = fullText,
|
|
888
|
+
full: (r: TResult, th: Theme, inner: number) => string[] = fullText,
|
|
885
889
|
): void {
|
|
886
890
|
OWN_BOX.add(String(tool.name ?? ""));
|
|
887
891
|
pi.registerTool({
|
|
@@ -950,7 +954,7 @@ function minimal(
|
|
|
950
954
|
label,
|
|
951
955
|
);
|
|
952
956
|
const resLine = res(result, theme, soft, isErr, expanded);
|
|
953
|
-
if (expanded) rows.push(...full(result, theme));
|
|
957
|
+
if (expanded) rows.push(...full(result, theme, inner));
|
|
954
958
|
else if (resLine) rows.push(oneRow(resLine, inner));
|
|
955
959
|
return box(theme, width, rows);
|
|
956
960
|
});
|
|
@@ -1080,20 +1084,195 @@ function arnativeTools(pi: ExtensionAPI) {
|
|
|
1080
1084
|
}
|
|
1081
1085
|
return `${resHead(th)} ${th.fg("toolDiffAdded", `+${add}`)} / ${th.fg("toolDiffRemoved", `-${del}`)}`;
|
|
1082
1086
|
},
|
|
1083
|
-
(r, th) =>
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1087
|
+
(r, th, inner) => formatEditDiff(r, th, inner),
|
|
1088
|
+
);
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
const EDIT_DIFF_CONFIG_KEY = Symbol.for("pi-arnative.editDiff");
|
|
1092
|
+
const SPLIT_DIFF_MIN_WIDTH = 50;
|
|
1093
|
+
const INTRA_LINE_MAX_TOKENS = 200;
|
|
1094
|
+
|
|
1095
|
+
export type EditDiffMode = "Split" | "Unified";
|
|
1096
|
+
export const EDIT_DIFF_CHOICES: readonly EditDiffMode[] = ["Split", "Unified"];
|
|
1097
|
+
|
|
1098
|
+
export function activeEditDiff(): EditDiffMode {
|
|
1099
|
+
const stored =
|
|
1100
|
+
(globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY] ??
|
|
1101
|
+
loadChoice(EDIT_DIFF_KEY, EDIT_DIFF_CHOICES);
|
|
1102
|
+
return EDIT_DIFF_CHOICES.includes(stored as EditDiffMode)
|
|
1103
|
+
? (stored as EditDiffMode)
|
|
1104
|
+
: "Split";
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
export function setEditDiff(mode: EditDiffMode): void {
|
|
1108
|
+
(globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY] = mode;
|
|
1109
|
+
saveChoice(EDIT_DIFF_KEY, mode);
|
|
1110
|
+
clearRenderCache();
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
type DiffSide = { styled: string } | null;
|
|
1114
|
+
|
|
1115
|
+
function unifiedDiffLines(diff: string, th: Theme): string[] {
|
|
1116
|
+
return diff.split("\n").map((l) =>
|
|
1117
|
+
l.startsWith("+") && !l.startsWith("+++")
|
|
1118
|
+
? th.fg("toolDiffAdded", l)
|
|
1119
|
+
: l.startsWith("-") && !l.startsWith("---")
|
|
1120
|
+
? th.fg("toolDiffRemoved", l)
|
|
1121
|
+
: th.fg("toolDiffContext", l),
|
|
1094
1122
|
);
|
|
1095
1123
|
}
|
|
1096
1124
|
|
|
1125
|
+
function tokenizeDiffLine(s: string): string[] {
|
|
1126
|
+
return s.match(/[A-Za-z0-9_]+|\s+|[^\sA-Za-z0-9_]/g) ?? [];
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
/**
|
|
1130
|
+
* Highlights changed tokens between paired old/new lines using `inverse`,
|
|
1131
|
+
* keeping leading indentation un-highlighted.
|
|
1132
|
+
*/
|
|
1133
|
+
function highlightLinePair(oldText: string, newText: string, th: Theme): { left: string; right: string } {
|
|
1134
|
+
const a = tokenizeDiffLine(oldText);
|
|
1135
|
+
const b = tokenizeDiffLine(newText);
|
|
1136
|
+
if (a.length === 0 || b.length === 0 || a.length > INTRA_LINE_MAX_TOKENS || b.length > INTRA_LINE_MAX_TOKENS) {
|
|
1137
|
+
return { left: th.fg("toolDiffRemoved", oldText), right: th.fg("toolDiffAdded", newText) };
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
const m = a.length;
|
|
1141
|
+
const n = b.length;
|
|
1142
|
+
const dp: Uint16Array[] = Array.from({ length: m + 1 }, () => new Uint16Array(n + 1));
|
|
1143
|
+
for (let i = m - 1; i >= 0; i--) {
|
|
1144
|
+
for (let j = n - 1; j >= 0; j--) {
|
|
1145
|
+
dp[i]![j] = a[i] === b[j] ? dp[i + 1]![j + 1]! + 1 : Math.max(dp[i + 1]![j]!, dp[i]![j + 1]!);
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
const inv = (s: string) => (th.inverse ? th.inverse(s) : `\x1b[7m${s}\x1b[27m`);
|
|
1150
|
+
let left = "";
|
|
1151
|
+
let right = "";
|
|
1152
|
+
let i = 0;
|
|
1153
|
+
let j = 0;
|
|
1154
|
+
let seenNonWsLeft = false;
|
|
1155
|
+
let seenNonWsRight = false;
|
|
1156
|
+
|
|
1157
|
+
const emitChanged = (tok: string, color: string, seenNonWs: boolean): [string, boolean] => {
|
|
1158
|
+
if (!seenNonWs && /^\s+$/.test(tok)) return [th.fg(color, tok), false];
|
|
1159
|
+
return [th.fg(color, inv(tok)), true];
|
|
1160
|
+
};
|
|
1161
|
+
|
|
1162
|
+
while (i < m && j < n) {
|
|
1163
|
+
if (a[i] === b[j]) {
|
|
1164
|
+
const tok = a[i]!;
|
|
1165
|
+
if (tok.trim()) {
|
|
1166
|
+
seenNonWsLeft = true;
|
|
1167
|
+
seenNonWsRight = true;
|
|
1168
|
+
}
|
|
1169
|
+
left += th.fg("toolDiffRemoved", tok);
|
|
1170
|
+
right += th.fg("toolDiffAdded", tok);
|
|
1171
|
+
i++;
|
|
1172
|
+
j++;
|
|
1173
|
+
} else if (dp[i + 1]![j]! >= dp[i]![j + 1]!) {
|
|
1174
|
+
const [chunk, seen] = emitChanged(a[i]!, "toolDiffRemoved", seenNonWsLeft);
|
|
1175
|
+
left += chunk;
|
|
1176
|
+
seenNonWsLeft = seen;
|
|
1177
|
+
i++;
|
|
1178
|
+
} else {
|
|
1179
|
+
const [chunk, seen] = emitChanged(b[j]!, "toolDiffAdded", seenNonWsRight);
|
|
1180
|
+
right += chunk;
|
|
1181
|
+
seenNonWsRight = seen;
|
|
1182
|
+
j++;
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
while (i < m) {
|
|
1186
|
+
const [chunk, seen] = emitChanged(a[i]!, "toolDiffRemoved", seenNonWsLeft);
|
|
1187
|
+
left += chunk;
|
|
1188
|
+
seenNonWsLeft = seen;
|
|
1189
|
+
i++;
|
|
1190
|
+
}
|
|
1191
|
+
while (j < n) {
|
|
1192
|
+
const [chunk, seen] = emitChanged(b[j]!, "toolDiffAdded", seenNonWsRight);
|
|
1193
|
+
right += chunk;
|
|
1194
|
+
seenNonWsRight = seen;
|
|
1195
|
+
j++;
|
|
1196
|
+
}
|
|
1197
|
+
return { left, right };
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
function wrapDiffCell(side: DiffSide, width: number): string[] {
|
|
1201
|
+
if (!side) return [""];
|
|
1202
|
+
const clean = side.styled.replace(/\t/g, " ");
|
|
1203
|
+
return clean === "" ? [""] : wrapTextWithAnsi(clean, width);
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
function renderSplitPair(left: DiffSide, right: DiffSide, leftW: number, rightW: number, sep: string): string[] {
|
|
1207
|
+
const leftLines = wrapDiffCell(left, leftW);
|
|
1208
|
+
const rightLines = wrapDiffCell(right, rightW);
|
|
1209
|
+
const count = Math.max(leftLines.length, rightLines.length);
|
|
1210
|
+
const rows: string[] = [];
|
|
1211
|
+
for (let i = 0; i < count; i++) {
|
|
1212
|
+
const l = leftLines[i] ?? "";
|
|
1213
|
+
const r = rightLines[i] ?? "";
|
|
1214
|
+
const pad = " ".repeat(Math.max(0, leftW - visibleWidth(l)));
|
|
1215
|
+
rows.push(`${l}${pad}${sep}${r}`);
|
|
1216
|
+
}
|
|
1217
|
+
return rows;
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
/**
|
|
1221
|
+
* Formats an `edit` diff side-by-side (Before | After) when the box inner width
|
|
1222
|
+
* is at least {@link SPLIT_DIFF_MIN_WIDTH}, falling back to unified diff on
|
|
1223
|
+
* narrow terminals or when `details.diff` is absent.
|
|
1224
|
+
*/
|
|
1225
|
+
export function formatEditDiff(r: TResult, th: Theme, inner: number, mode: EditDiffMode = activeEditDiff()): string[] {
|
|
1226
|
+
const diff: string = r.details?.diff ?? "";
|
|
1227
|
+
if (!diff) return fullText(r, th);
|
|
1228
|
+
if (mode === "Unified" || inner < SPLIT_DIFF_MIN_WIDTH) return unifiedDiffLines(diff, th);
|
|
1229
|
+
|
|
1230
|
+
const sep = th.fg("dim", " │ ");
|
|
1231
|
+
const leftW = Math.floor((inner - 3) / 2);
|
|
1232
|
+
const rightW = inner - 3 - leftW;
|
|
1233
|
+
const out: string[] = [
|
|
1234
|
+
`${th.fg("dim", "Before")}${" ".repeat(Math.max(0, leftW - 6))}${sep}${th.fg("dim", "After")}`,
|
|
1235
|
+
th.fg("dim", `${"─".repeat(leftW)}─┼─${"─".repeat(rightW)}`),
|
|
1236
|
+
];
|
|
1237
|
+
|
|
1238
|
+
let dels: string[] = [];
|
|
1239
|
+
let adds: string[] = [];
|
|
1240
|
+
const flushChanges = () => {
|
|
1241
|
+
const count = Math.max(dels.length, adds.length);
|
|
1242
|
+
for (let i = 0; i < count; i++) {
|
|
1243
|
+
const d = dels[i];
|
|
1244
|
+
const a = adds[i];
|
|
1245
|
+
if (d !== undefined && a !== undefined) {
|
|
1246
|
+
const { left, right } = highlightLinePair(d, a, th);
|
|
1247
|
+
out.push(...renderSplitPair({ styled: left }, { styled: right }, leftW, rightW, sep));
|
|
1248
|
+
} else {
|
|
1249
|
+
const left: DiffSide = d !== undefined ? { styled: th.fg("toolDiffRemoved", d) } : null;
|
|
1250
|
+
const right: DiffSide = a !== undefined ? { styled: th.fg("toolDiffAdded", a) } : null;
|
|
1251
|
+
out.push(...renderSplitPair(left, right, leftW, rightW, sep));
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
dels = [];
|
|
1255
|
+
adds = [];
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
for (const line of diff.split("\n")) {
|
|
1259
|
+
if (line.startsWith("-") && !line.startsWith("---")) {
|
|
1260
|
+
dels.push(line.slice(1));
|
|
1261
|
+
} else if (line.startsWith("+") && !line.startsWith("+++")) {
|
|
1262
|
+
adds.push(line.slice(1));
|
|
1263
|
+
} else if (line.startsWith(" ")) {
|
|
1264
|
+
flushChanges();
|
|
1265
|
+
const side: DiffSide = { styled: th.fg("toolDiffContext", line.slice(1)) };
|
|
1266
|
+
out.push(...renderSplitPair(side, side, leftW, rightW, sep));
|
|
1267
|
+
} else {
|
|
1268
|
+
flushChanges();
|
|
1269
|
+
out.push(th.fg("toolDiffContext", line));
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
flushChanges();
|
|
1273
|
+
return out;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1097
1276
|
// codemode: pi's renderer wrapped in our box. renderShell "self" keeps the
|
|
1098
1277
|
// execution defaults; renderCall/renderResult draw the box. state.hasResult
|
|
1099
1278
|
// guarantees one box per call, also after reload/restore.
|
|
@@ -1734,6 +1913,40 @@ if (isMain(import.meta.url)) {
|
|
|
1734
1913
|
minRender("edit", { path: "README.md" }, diffRes).every((l) => visibleWidth(l) === 74),
|
|
1735
1914
|
"minimal(): hint row still fills the box width",
|
|
1736
1915
|
);
|
|
1916
|
+
// Side-by-side edit diff: Before | After at wide widths, unified fallback when narrow
|
|
1917
|
+
const diffTmp = mkdtempSync(join(tmpdir(), "arnative-editdiff-"));
|
|
1918
|
+
const prevAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
1919
|
+
process.env.PI_CODING_AGENT_DIR = diffTmp;
|
|
1920
|
+
delete (globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY];
|
|
1921
|
+
resetPresetCache();
|
|
1922
|
+
try {
|
|
1923
|
+
const openedIsolated = minRender("edit", { path: "README.md" }, diffRes, true);
|
|
1924
|
+
assert(openedIsolated.some((l) => l.includes("Before") && l.includes("│") && l.includes("After")), "edit: expanded view shows Before | After header");
|
|
1925
|
+
assert(openedIsolated.some((l) => l.includes("─┼─")), "edit: expanded view shows header separator");
|
|
1926
|
+
assert(openedIsolated.some((l) => l.includes("old") && !l.includes("-old") && l.includes("│") && l.includes("new") && !l.includes("+new")), "edit: expanded view pairs old and new without +/- prefix");
|
|
1927
|
+
const intraRes = { content: [{ type: "text", text: "ok" }], details: { diff: "-const x = 1;\n+const x = 2;" } };
|
|
1928
|
+
const intraLines = formatEditDiff(intraRes, th, 70);
|
|
1929
|
+
assert(intraLines.some((l) => l.includes("const x = \x1b[7m1\x1b[27m;") && l.includes("const x = \x1b[7m2\x1b[27m;")), "edit: intra-line diff highlights only changed tokens");
|
|
1930
|
+
const pureAdd = minRender("edit", { path: "README.md" }, { content: [{ type: "text", text: "ok" }], details: { diff: "+ 10 added\n 11 ctx" } }, true);
|
|
1931
|
+
assert(pureAdd.some((l) => /^\│\s+\│\s+10 added/.test(l)), "edit: pure addition leaves Before column blank and strips +");
|
|
1932
|
+
assert(pureAdd.some((l) => l.includes("11 ctx") && l.indexOf("11 ctx") !== l.lastIndexOf("11 ctx")), "edit: context line appears in both columns");
|
|
1933
|
+
assert(pureAdd.every((l) => visibleWidth(l) === 74), "edit: side-by-side rows keep exact box width");
|
|
1934
|
+
const narrow = formatEditDiff(diffRes, th, 40);
|
|
1935
|
+
assert(!narrow.some((l) => l.includes("Before") && l.includes("After")), "edit: narrow width falls back to unified diff");
|
|
1936
|
+
setEditDiff("Unified");
|
|
1937
|
+
const liveUnified = minRender("edit", { path: "README.md" }, diffRes, true);
|
|
1938
|
+
assert(!liveUnified.some((l) => l.includes("Before") && l.includes("After")), "edit: setEditDiff('Unified') switches immediately");
|
|
1939
|
+
assert(liveUnified.some((l) => l.includes("-old")) && liveUnified.some((l) => l.includes("+new")), "edit: Unified mode keeps +/- lines");
|
|
1940
|
+
setEditDiff("Split");
|
|
1941
|
+
const liveSplit = minRender("edit", { path: "README.md" }, diffRes, true);
|
|
1942
|
+
assert(liveSplit.some((l) => l.includes("Before") && l.includes("After")), "edit: setEditDiff('Split') switches back immediately");
|
|
1943
|
+
} finally {
|
|
1944
|
+
if (prevAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
1945
|
+
else process.env.PI_CODING_AGENT_DIR = prevAgentDir;
|
|
1946
|
+
delete (globalThis as Record<symbol, unknown>)[EDIT_DIFF_CONFIG_KEY];
|
|
1947
|
+
resetPresetCache();
|
|
1948
|
+
rmSync(diffTmp, { recursive: true, force: true });
|
|
1949
|
+
}
|
|
1737
1950
|
}
|
|
1738
1951
|
|
|
1739
1952
|
// Chrome DevTools: their bare renderers are replaced by our box (title + summary).
|