@bismawy/pi-arnative 0.13.0 → 0.14.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 +15 -0
- package/README.md +2 -2
- package/extensions/arnative.ts +282 -59
- package/extensions/autocompact.ts +142 -30
- package/extensions/budget.ts +4 -3
- 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 +8 -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
|
}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* 5. `↓ Jump to latest message` pill (fullscreen): bg selectedBg (grey) -> accent,
|
|
13
13
|
* text darkened (theme canvas) so contrast stays high (9.6:1).
|
|
14
14
|
* 6. `ctx.ui.select` rows: pi paints the whole selected row accent -> keep accent on
|
|
15
|
-
* the
|
|
15
|
+
* the `❯` marker and `·` separators, selected text in soft.
|
|
16
16
|
*/
|
|
17
17
|
import {
|
|
18
18
|
AssistantMessageComponent,
|
|
@@ -40,9 +40,9 @@ import {
|
|
|
40
40
|
import { readdirSync, readFileSync } from "node:fs";
|
|
41
41
|
import { renderBoxLines } from "../lib/box.ts";
|
|
42
42
|
import { statusRows } from "../lib/status-widget.ts";
|
|
43
|
-
import { ansiBgOpen, getActiveTheme, setActiveTheme, stripAnsi, themeOf,
|
|
43
|
+
import { ansiBgOpen, getActiveTheme, setActiveTheme, stripAnsi, themeOf, softOf } from "../lib/ansi.ts";
|
|
44
44
|
import { assert, isMain } from "../lib/check.ts";
|
|
45
|
-
import { contrast, oklchToRgb, parseOklch, toHex } from "../lib/color.ts";
|
|
45
|
+
import { contrast, hexToRgb, oklchToRgb, parseOklch, rgbToAnsi256, toHex } from "../lib/color.ts";
|
|
46
46
|
import { expandKeyName } from "../lib/format.ts";
|
|
47
47
|
import { patchOnce } from "../lib/patch.ts";
|
|
48
48
|
|
|
@@ -171,12 +171,12 @@ if (TuiAltScreen?.prototype) {
|
|
|
171
171
|
}
|
|
172
172
|
|
|
173
173
|
// 6. Select menus (ctx.ui.select -> ExtensionSelectorComponent.updateList): pi colors the
|
|
174
|
-
// whole selected row accent. Arnative keeps accent on the
|
|
174
|
+
// whole selected row accent. Arnative keeps accent on the `❯` marker and `·` separators
|
|
175
175
|
// and moves the selected text to soft (accent on themes without the token).
|
|
176
176
|
|
|
177
177
|
/** Selected row body: `·` separators accent, the text around them soft. */
|
|
178
178
|
export function selectRowText(row: string, th: { fg(c: string, t: string): string }): string {
|
|
179
|
-
const soft =
|
|
179
|
+
const soft = softOf(th);
|
|
180
180
|
return row
|
|
181
181
|
.split("·")
|
|
182
182
|
.map((part) => soft(part))
|
|
@@ -197,7 +197,7 @@ if (ExtensionSelectorComponent?.prototype) {
|
|
|
197
197
|
for (let i = 0; i < this.options.length; i++) {
|
|
198
198
|
const text =
|
|
199
199
|
i === this.selectedIndex
|
|
200
|
-
? th.fg("accent", "
|
|
200
|
+
? th.fg("accent", "❯ ") + selectRowText(this.options[i]!, th)
|
|
201
201
|
: ` ${th.fg("text", this.options[i]!)}`;
|
|
202
202
|
this.listContainer.addChild(new Text(text, 1, 0));
|
|
203
203
|
}
|
|
@@ -697,7 +697,7 @@ if (isMain(import.meta.url)) {
|
|
|
697
697
|
assert(accentPill("other text", thPill) === "other text", "pill: non-pill text untouched");
|
|
698
698
|
assert(accentPill(pillOriginal, null) === pillOriginal, "pill: no theme -> passed through");
|
|
699
699
|
|
|
700
|
-
// select rows:
|
|
700
|
+
// select rows: `❯` + `·` stay accent, selected text moves to accentSoft
|
|
701
701
|
const tagFg = { fg: (c: string, t: string) => `<${c}>${t}</${c}>` };
|
|
702
702
|
assert(
|
|
703
703
|
selectRowText("Routing · off", tagFg) === "<accentSoft>Routing </accentSoft><accent>·</accent><accentSoft> off</accentSoft>",
|
|
@@ -718,6 +718,13 @@ if (isMain(import.meta.url)) {
|
|
|
718
718
|
"searchMatchBg", "border", "borderAccent", "borderMuted", "mdCodeBlockBorder", "mdQuoteBorder", "mdHr",
|
|
719
719
|
"scrollbarTrack", "scrollbarThumb",
|
|
720
720
|
]);
|
|
721
|
+
// Every background a box or a highlight paints. These carry no text contrast
|
|
722
|
+
// requirement, but each must still be *visible*: a box the same color as the
|
|
723
|
+
// terminal canvas is not a box.
|
|
724
|
+
const BOX_TOKENS = [
|
|
725
|
+
"userMessageBg", "customMessageBg", "toolPendingBg", "toolSuccessBg", "toolErrorBg",
|
|
726
|
+
"selectedBg", "searchMatchBg",
|
|
727
|
+
];
|
|
721
728
|
const secondary = new Set(["muted", "dim", "mdQuote", "mdLinkUrl", "toolOutput", "toolDiffContext", "thinkingText", "syntaxComment"]);
|
|
722
729
|
// Thinking ramp: the higher the more readable; thinkingMax = accent (measured on the pill path).
|
|
723
730
|
const ramp: Record<string, number> = {
|
|
@@ -831,6 +838,15 @@ if (isMain(import.meta.url)) {
|
|
|
831
838
|
// Scrollbar thumb & highlight must be distinguishable from track/selection (they used to be identical).
|
|
832
839
|
assert(hex("scrollbarThumb") !== hex("scrollbarTrack"), `theme ${f}: scrollbarThumb still equals scrollbarTrack`);
|
|
833
840
|
assert(hex("searchMatchBg") !== hex("selectedBg"), `theme ${f}: searchMatchBg still equals selectedBg`);
|
|
841
|
+
// Every box must be visible on a pure-black terminal AND survive 256-color
|
|
842
|
+
// quantization. At L 0.19 the panel was `#001817` (1.14:1 on black) and every
|
|
843
|
+
// theme's boxes quantized to cube black (index 16) — invisible in both modes.
|
|
844
|
+
for (const tok of BOX_TOKENS) {
|
|
845
|
+
const color = hex(tok);
|
|
846
|
+
assert(contrast(color, "#000000") >= 1.4, `theme ${f}: ${tok} ${color} is invisible on a black terminal`);
|
|
847
|
+
const quantized = rgbToAnsi256(hexToRgb(color));
|
|
848
|
+
assert(quantized !== 16, `theme ${f}: ${tok} ${color} quantizes to index 16 (pure black) in 256-color mode`);
|
|
849
|
+
}
|
|
834
850
|
}
|
|
835
851
|
// Only `muted`, `text` and `selectedBg` exist. pi's Theme constructor maps whatever
|
|
836
852
|
// it gets — including the thinkingMax <- thinkingXhigh fallback — so these probe
|
package/extensions/usage.ts
CHANGED
|
@@ -88,7 +88,7 @@ const statsOf = (
|
|
|
88
88
|
type UsageView = "provider" | "project" | "prices";
|
|
89
89
|
|
|
90
90
|
/** Labels on the range bar, in tab order. */
|
|
91
|
-
const RANGE_LABELS: Record<UsageRange, string> = { all: "All", today: "Today", "7d": "7 day", "30d": "30 day"
|
|
91
|
+
const RANGE_LABELS: Record<UsageRange, string> = { all: "All", today: "Today", "7d": "7 day", "30d": "30 day" };
|
|
92
92
|
/** The three views `v` cycles, in that order, and the view a press would show next. */
|
|
93
93
|
const VIEW_LABELS: Record<UsageView, string> = { provider: "Provider", project: "Project", prices: "Prices" };
|
|
94
94
|
const NEXT_VIEW: Record<UsageView, UsageView> = { provider: "project", project: "prices", prices: "provider" };
|
|
@@ -1323,7 +1323,6 @@ if (isMain(import.meta.url)) {
|
|
|
1323
1323
|
assert(msgIn("today") === 1, "today counts only the message written today");
|
|
1324
1324
|
assert(msgIn("7d") === 1, "7 day stops before the ten-day record, so only today counts");
|
|
1325
1325
|
assert(msgIn("30d") === 2, "30 day covers today and ten days back, not forty-five");
|
|
1326
|
-
assert(msgIn("3m") === 3, "3 month covers all three");
|
|
1327
1326
|
// A window with nothing in it is empty, not an error: the bar can be pressed on a quiet day.
|
|
1328
1327
|
assert(collectUsageSummary(true, "today").totals.msgs >= 1, "today still reports the rows it has");
|
|
1329
1328
|
|
|
@@ -1339,11 +1338,11 @@ if (isMain(import.meta.url)) {
|
|
|
1339
1338
|
const reloaded = JSON.parse(readFileSync(cacheFile, "utf8")) as Record<string, { d?: unknown }>;
|
|
1340
1339
|
assert(Object.values(reloaded).some((item) => item.d !== undefined), "the re-parse writes the day buckets back");
|
|
1341
1340
|
|
|
1342
|
-
// The range bar:
|
|
1341
|
+
// The range bar: four windows, the active one accented, and the counter states how many
|
|
1343
1342
|
// rows exist past the viewport. Tab moves the window and the numbers follow it.
|
|
1344
1343
|
const barModal = new UsageModalComponent(fakeTheme, () => {}, () => {}, "high");
|
|
1345
1344
|
const barOnce = barModal.render(100).map(plain);
|
|
1346
|
-
const barLine = barOnce.find((l) => l.includes("All") && l.includes("Today") && l.includes("
|
|
1345
|
+
const barLine = barOnce.find((l) => l.includes("All") && l.includes("Today") && l.includes("30 day"));
|
|
1347
1346
|
assert(barLine !== undefined, "the range bar names every window on one line");
|
|
1348
1347
|
assert(USAGE_RANGES.every((r) => barLine!.includes(RANGE_LABELS[r])), "every range label is on the bar");
|
|
1349
1348
|
assert(barLine!.indexOf("All") < barLine!.indexOf("Today"), "the bar keeps tab order");
|
package/lib/color.ts
CHANGED
|
@@ -75,6 +75,34 @@ export function toHex(value: string): string {
|
|
|
75
75
|
throw new Error(`Not a hex/oklch color: ${value}`);
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Nearest xterm-256 index for an sRGB color, mirroring `rgbToAnsi256` in
|
|
80
|
+
* @earendil-works/pi-tui (`colors.ts`). pi draws every theme color through that
|
|
81
|
+
* quantizer whenever the terminal is not truecolor, so a value that lands on the
|
|
82
|
+
* 6x6x6 cube black renders as `#000000` no matter what the theme file declared.
|
|
83
|
+
* Kept in sync by test/theme-canvas.test.ts.
|
|
84
|
+
*/
|
|
85
|
+
export function rgbToAnsi256(rgb: Rgb): number {
|
|
86
|
+
const CUBE = [0, 95, 135, 175, 215, 255];
|
|
87
|
+
const GRAY = Array.from({ length: 24 }, (_, i) => 8 + i * 10);
|
|
88
|
+
const nearest = (values: readonly number[], v: number) =>
|
|
89
|
+
values.reduce((best, x, i) => (Math.abs(x - v) < Math.abs(values[best]! - v) ? i : best), 0);
|
|
90
|
+
const distance = (a: Rgb, b: Rgb) => (a.r - b.r) ** 2 * 0.299 + (a.g - b.g) ** 2 * 0.587 + (a.b - b.b) ** 2 * 0.114;
|
|
91
|
+
const [ri, gi, bi] = [rgb.r, rgb.g, rgb.b].map((c) => nearest(CUBE, c)) as [number, number, number];
|
|
92
|
+
const cube = { r: CUBE[ri]!, g: CUBE[gi]!, b: CUBE[bi]! };
|
|
93
|
+
const grayIndex = nearest(GRAY, Math.round(0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b));
|
|
94
|
+
const gray = { r: GRAY[grayIndex]!, g: GRAY[grayIndex]!, b: GRAY[grayIndex]! };
|
|
95
|
+
const spread = Math.max(rgb.r, rgb.g, rgb.b) - Math.min(rgb.r, rgb.g, rgb.b);
|
|
96
|
+
if (spread < 10 && distance(rgb, gray) < distance(rgb, cube)) return 232 + grayIndex;
|
|
97
|
+
return 16 + 36 * ri + 6 * gi + bi;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** `#rrggbb` -> sRGB channels. Inverse of the hex branch of {@link toHex}. */
|
|
101
|
+
export function hexToRgb(hex: string): Rgb {
|
|
102
|
+
const v = toHex(hex);
|
|
103
|
+
return { r: parseInt(v.slice(1, 3), 16), g: parseInt(v.slice(3, 5), 16), b: parseInt(v.slice(5, 7), 16) };
|
|
104
|
+
}
|
|
105
|
+
|
|
78
106
|
function relativeLuminance(hex: string): number {
|
|
79
107
|
const [r, g, b] = [1, 3, 5]
|
|
80
108
|
.map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
|
|
@@ -122,5 +150,11 @@ if (isMain(import.meta.url)) {
|
|
|
122
150
|
const back = hexToOklch(FIXTURE.cyan);
|
|
123
151
|
assert(Math.abs(back.H - 218) < 6, `hexToOklch hue of ${FIXTURE.cyan} ~218 (got ${back.H.toFixed(1)})`);
|
|
124
152
|
assert(oklchToRgb(0.7, 0.4, 145).chroma < 0.4, "out-of-gamut chroma is reduced");
|
|
153
|
+
// Quantizer vectors taken from pi-tui's own table: cube black, the teal panel pi's
|
|
154
|
+
// dark theme uses, and a near-neutral that must fall on the grey ramp.
|
|
155
|
+
assert(rgbToAnsi256({ r: 0, g: 24, b: 23 }) === 16, "near-black quantizes to cube black (index 16)");
|
|
156
|
+
assert(rgbToAnsi256({ r: 33, g: 59, b: 73 }) === 23, "pi dark panel quantizes to 23");
|
|
157
|
+
assert(rgbToAnsi256({ r: 200, g: 200, b: 200 }) >= 232, "neutral grey uses the grey ramp");
|
|
158
|
+
assert(hexToRgb("#1c3f3d").g === 0x3f, "hexToRgb reads channels");
|
|
125
159
|
console.log("lib/color.ts OK");
|
|
126
160
|
}
|
package/lib/list-picker.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* can import it without importing the settings menu back (no import cycle).
|
|
6
6
|
*/
|
|
7
7
|
import { Input, matchesKey, truncateToWidth, visibleWidth, type Component, type Focusable } from "@earendil-works/pi-tui";
|
|
8
|
-
import {
|
|
8
|
+
import { softOf, thinkingColorOf } from "../lib/ansi.ts";
|
|
9
9
|
import { renderScreen, screenTitle, type ScreenText } from "../lib/box.ts";
|
|
10
10
|
import { assert, isMain } from "../lib/check.ts";
|
|
11
11
|
import { ROW_DIVIDER } from "../lib/format.ts";
|
|
@@ -33,7 +33,7 @@ export function rowText(row: ListRow): string {
|
|
|
33
33
|
return row.note ? `${row.label} · ${row.note}` : row.label;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
/** Bare names (preset lists) as rows; the cursor's
|
|
36
|
+
/** Bare names (preset lists) as rows; the cursor's `❯` marks the live value. */
|
|
37
37
|
export const nameRows = (names: readonly string[]): ListRow[] => names.map((label) => ({ label }));
|
|
38
38
|
|
|
39
39
|
interface ListPickerHooks {
|
|
@@ -260,7 +260,7 @@ export class ListPicker implements Component {
|
|
|
260
260
|
render(width: number): string[] {
|
|
261
261
|
const th = this.theme;
|
|
262
262
|
const bold = th.bold ?? ((t: string) => `\x1b[1m${t}\x1b[22m`);
|
|
263
|
-
const soft =
|
|
263
|
+
const soft = softOf(th);
|
|
264
264
|
const edge = (text: string) => this.edge(text);
|
|
265
265
|
const column = Math.max(0, ...this.rows.map((r) => visibleWidth(r.label)));
|
|
266
266
|
const body: string[] = [];
|
|
@@ -272,7 +272,7 @@ export class ListPicker implements Component {
|
|
|
272
272
|
for (let i = windowStart; i < windowEnd; i++) {
|
|
273
273
|
const item = this.rows[shown[i]!]!;
|
|
274
274
|
const isSelected = i === this.selected;
|
|
275
|
-
const paint = isSelected ? (s: string) => soft(bold(s)) : (s: string) => th.fg(
|
|
275
|
+
const paint = isSelected ? (s: string) => soft(bold(s)) : (s: string) => th.fg("text", s);
|
|
276
276
|
const pad = " ".repeat(Math.max(0, column - visibleWidth(item.label)));
|
|
277
277
|
const noteText = this.hooks.note?.(item.label) ?? item.note;
|
|
278
278
|
const note = noteText ? `${th.fg("dim", ROW_DIVIDER)}${th.fg("dim", noteText)}` : "";
|
|
@@ -287,7 +287,7 @@ export class ListPicker implements Component {
|
|
|
287
287
|
const suffix = /(\(.*\))$/.exec(item.label)?.[1] ?? "";
|
|
288
288
|
const head = suffix ? item.label.slice(0, item.label.length - suffix.length) : item.label;
|
|
289
289
|
const tail = suffix ? th.fg("dim", suffix) : "";
|
|
290
|
-
const content = `${isSelected ? th.fg("accent", "
|
|
290
|
+
const content = `${isSelected ? th.fg("accent", "❯ ") : " "}${mark}${paint(head)}${tail}${pad}${note}${chosen}`;
|
|
291
291
|
body.push(truncateToWidth(content, width - 4, ""));
|
|
292
292
|
}
|
|
293
293
|
// Hidden rows are announced, never silently cut (an empty line is still a row).
|
|
@@ -402,7 +402,7 @@ if (isMain(import.meta.url)) {
|
|
|
402
402
|
const lines = picker.render(50);
|
|
403
403
|
assert(lines[0]!.startsWith("╭") && lines[lines.length - 1]!.startsWith("╰"), "picker framed");
|
|
404
404
|
assert(lines.every((l) => visibleWidth(l) === 50), "picker lines fit width 50");
|
|
405
|
-
assert(lines.some((l) => l.includes("
|
|
405
|
+
assert(lines.some((l) => l.includes("❯ a")), "the cursor marks the selection");
|
|
406
406
|
|
|
407
407
|
// The chosen marker: ✓ ends the saved row only, colored by the theme's success slot.
|
|
408
408
|
const chosenPicker = new ListPicker(
|
|
@@ -447,18 +447,18 @@ if (isMain(import.meta.url)) {
|
|
|
447
447
|
frame = scrolled.render(50);
|
|
448
448
|
assert(countItems(frame) === 10, "still 10 rows after scrolling");
|
|
449
449
|
assert(frame.some((l) => l.includes("↑ 9 more")) && frame.some((l) => l.includes("↓ 6 more")), "both ends announce their hidden rows");
|
|
450
|
-
assert(frame.some((l) => l.includes("
|
|
450
|
+
assert(frame.some((l) => l.includes("❯ m14")), "the cursor row stays visible");
|
|
451
451
|
scrolled.handleInput("\x1b[B");
|
|
452
452
|
const frameNext = scrolled.render(50);
|
|
453
453
|
assert(frameNext.length === frame.length && countItems(frameNext) === 10, "the frame height stays constant while scrolling inside the list");
|
|
454
454
|
for (let i = 0; i < 9; i++) scrolled.handleInput("\x1b[B");
|
|
455
455
|
frame = scrolled.render(50);
|
|
456
|
-
assert(frame.some((l) => l.includes("
|
|
456
|
+
assert(frame.some((l) => l.includes("❯ m24")) && frame.some((l) => l.includes("↑ 15 more")) && !frame.some((l) => l.includes("↓")), "the bottom of the list announces only what is above");
|
|
457
457
|
// Wrap at both edges, matching the /jev-eye picker: a held key never sticks.
|
|
458
458
|
scrolled.handleInput("\x1b[B");
|
|
459
|
-
assert(scrolled.render(50).some((l) => l.includes("
|
|
459
|
+
assert(scrolled.render(50).some((l) => l.includes("❯ m0")), "↓ at the last row wraps to the top");
|
|
460
460
|
scrolled.handleInput("\x1b[A");
|
|
461
|
-
assert(scrolled.render(50).some((l) => l.includes("
|
|
461
|
+
assert(scrolled.render(50).some((l) => l.includes("❯ m24")), "↑ at the top row wraps to the last row");
|
|
462
462
|
const short = new ListPicker(fakeTheme, nameRows(["a", "b"]), "a", { preview: quiet, revert: quiet, done: quiet, requestRender: quiet }, { title: screenTitle("Test"), description: "d", legend: "l" }, false, undefined, 10);
|
|
463
463
|
assert(!short.render(50).some((l) => l.includes("more")), "a short list shows no scroll indicators");
|
|
464
464
|
|
|
@@ -511,7 +511,7 @@ if (isMain(import.meta.url)) {
|
|
|
511
511
|
|
|
512
512
|
const summarized = new ListPicker(fakeTheme, nameRows(["a", "b"]), "a", { preview: quiet, revert: quiet, done: quiet, requestRender: quiet, summary: () => ["Box · a"] }, { title: "T", description: "d", legend: "l" }, false);
|
|
513
513
|
const sumLines = summarized.render(40).map(plain);
|
|
514
|
-
assert(sumLines.some((l) => l.includes("Box · a")) && sumLines.indexOf(sumLines.find((l) => l.includes("Box · a"))!) < sumLines.indexOf(sumLines.find((l) => l.includes("
|
|
514
|
+
assert(sumLines.some((l) => l.includes("Box · a")) && sumLines.indexOf(sumLines.find((l) => l.includes("Box · a"))!) < sumLines.indexOf(sumLines.find((l) => l.includes("❯ a"))!), "summary renders above the picker rows");
|
|
515
515
|
|
|
516
516
|
console.log("list-picker.ts self-check OK");
|
|
517
517
|
}
|
package/lib/preset-store.ts
CHANGED
|
@@ -28,6 +28,8 @@ export const BUDGET_MONTH_KEY = "budgetMonth";
|
|
|
28
28
|
export const BUDGET_ENFORCE_KEY = "budgetEnforce";
|
|
29
29
|
/** Transcript render cache: `"On"` / `"Off"`, absent reads as `"On"`. */
|
|
30
30
|
export const RENDER_CACHE_KEY = "renderCache";
|
|
31
|
+
/** Remote proxy payload limit: `"Off"` or `"<N> MB"`, absent reads as `"1 MB"`. */
|
|
32
|
+
export const PAYLOAD_LIMIT_KEY = "payloadLimit";
|
|
31
33
|
|
|
32
34
|
// Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
|
|
33
35
|
// Everything pi-arnative writes lives in one folder (agent dir/arnative); the config moved
|
|
@@ -83,6 +85,11 @@ export function loadChoice<T extends string>(key: string, allowed: readonly T[])
|
|
|
83
85
|
return typeof value === "string" && (allowed as readonly string[]).includes(value) ? (value as T) : undefined;
|
|
84
86
|
}
|
|
85
87
|
|
|
88
|
+
/** Raw stored value for `key` (used by callers with custom parsers like `payloadLimit`). */
|
|
89
|
+
export function loadSetting(key: string): unknown {
|
|
90
|
+
return readConfig()[key];
|
|
91
|
+
}
|
|
92
|
+
|
|
86
93
|
/** The stored value for `key` as a finite number in `[min, max]`, or undefined when absent, empty,
|
|
87
94
|
* unparsable or out of range. Amounts are stored as strings (`"5"`, `""` = unset) because
|
|
88
95
|
* `loadChoice` only accepts strings from an allowed set, so numbers get their own reader. */
|
|
@@ -95,7 +102,7 @@ export function loadNumber(key: string, range: { min: number; max: number }): nu
|
|
|
95
102
|
/** Reading order of `config.json`: the presets in the order the settings menu shows them,
|
|
96
103
|
* then `layoutVersion`, then anything else (a key from another module or a newer version).
|
|
97
104
|
* Times a user edits the file by hand or reads it back. */
|
|
98
|
-
const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "chatboxPreset", "chatboxPrompt", "chatboxDialog", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "modelHeal", "renderCache"];
|
|
105
|
+
const KEY_ORDER = ["headerPreset", "footerPreset", "footerCost", "chatboxPreset", "chatboxPrompt", "chatboxDialog", "budgetDay", "budgetMonth", "budgetEnforce", "spinnerPreset", "spinnerGradient", "layoutVersion", "autoCompact", "payloadLimit", "modelHeal", "renderCache"];
|
|
99
106
|
|
|
100
107
|
/** The record in {@link KEY_ORDER}; unknown keys keep the order they were written in. */
|
|
101
108
|
function ordered(record: Record<string, unknown>): Record<string, unknown> {
|
package/lib/usage-store.ts
CHANGED
|
@@ -88,10 +88,10 @@ function addToRollup(r: Rollup, e: UsageEntry): void {
|
|
|
88
88
|
}
|
|
89
89
|
|
|
90
90
|
/** A time window the dashboard can show. `all` is the whole history. */
|
|
91
|
-
export type UsageRange = "all" | "today" | "7d" | "30d"
|
|
91
|
+
export type UsageRange = "all" | "today" | "7d" | "30d";
|
|
92
92
|
|
|
93
93
|
/** Tab order of the range bar. */
|
|
94
|
-
export const USAGE_RANGES: readonly UsageRange[] = ["all", "today", "7d", "30d"
|
|
94
|
+
export const USAGE_RANGES: readonly UsageRange[] = ["all", "today", "7d", "30d"];
|
|
95
95
|
|
|
96
96
|
/** UTC day bucket key (`YYYY-MM-DD`) of a timestamp. UTC on purpose: local time would make the
|
|
97
97
|
* on-disk cache depend on the timezone of the machine that wrote it, so a restore elsewhere
|
|
@@ -100,7 +100,7 @@ export function dayKey(ms: number): string {
|
|
|
100
100
|
return new Date(ms > 0 ? ms : 0).toISOString().slice(0, 10);
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
-
/** UTC midnight where `range` starts: today, 7 or 30 calendar days back
|
|
103
|
+
/** UTC midnight where `range` starts: today, 7 or 30 calendar days back.
|
|
104
104
|
* `undefined` for `all`, which has no floor. UTC to match the day buckets: a local-midnight
|
|
105
105
|
* floor would cut a UTC+7 "today" at 7am local and drop the morning's spend. */
|
|
106
106
|
export function rangeStart(range: UsageRange, now = Date.now()): number | undefined {
|
|
@@ -108,8 +108,7 @@ export function rangeStart(range: UsageRange, now = Date.now()): number | undefi
|
|
|
108
108
|
const d = new Date(now);
|
|
109
109
|
d.setUTCHours(0, 0, 0, 0);
|
|
110
110
|
if (range === "today") return d.getTime();
|
|
111
|
-
|
|
112
|
-
else d.setUTCDate(d.getUTCDate() - (range === "7d" ? 6 : 29));
|
|
111
|
+
d.setUTCDate(d.getUTCDate() - (range === "7d" ? 6 : 29));
|
|
113
112
|
return d.getTime();
|
|
114
113
|
}
|
|
115
114
|
|