@bismawy/pi-arnative 0.16.1 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -16
- package/extensions/index.ts +41 -0
- package/lib/active-clock.ts +91 -0
- package/lib/ansi.ts +40 -78
- package/lib/box.ts +49 -68
- package/lib/chatbox.ts +371 -0
- package/lib/color.ts +3 -31
- package/lib/compat.ts +0 -60
- package/lib/edit-diff.ts +199 -0
- package/{extensions → lib/features}/arnative.ts +96 -423
- package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -327
- package/{extensions → lib/features}/budget.ts +17 -242
- package/lib/features/footer.ts +2232 -0
- package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
- package/{extensions → lib/features}/model-heal.ts +5 -28
- package/lib/features/progress-group.ts +1557 -0
- package/{extensions → lib/features}/render-cache.ts +113 -161
- package/{extensions → lib/features}/timestamps.ts +18 -94
- package/{extensions → lib/features}/todos.ts +44 -158
- package/lib/features/tools.ts +1202 -0
- package/lib/features/ui-render-tweaks.ts +606 -0
- package/lib/features/usage.ts +786 -0
- package/lib/format.ts +22 -4
- package/lib/git-status.ts +164 -0
- package/lib/list-picker.ts +1 -127
- package/lib/model-heal.ts +70 -162
- package/lib/patch.ts +0 -63
- package/lib/preset-store.ts +17 -133
- package/lib/provider-store.ts +573 -0
- package/lib/provider.ts +52 -851
- package/lib/runtime.ts +209 -0
- package/lib/shortcuts.ts +8 -58
- package/lib/spinner.ts +88 -162
- package/lib/status-widget.ts +4 -30
- package/lib/todos.ts +20 -143
- package/lib/usage-pricing.ts +143 -0
- package/lib/usage-store.ts +44 -378
- package/package.json +5 -6
- package/themes/arnative-blossom.json +0 -0
- package/themes/arnative-crimson.json +0 -0
- package/themes/arnative-cyberpunk.json +0 -0
- package/themes/arnative-dracula.json +0 -0
- package/themes/arnative-earthy.json +0 -0
- package/themes/arnative-garden.json +0 -0
- package/themes/arnative-gruvbox.json +0 -0
- package/themes/arnative-lemonade.json +0 -0
- package/themes/arnative-magical.json +0 -0
- package/themes/arnative-matrix.json +0 -0
- package/themes/arnative-neutral.json +0 -0
- package/themes/arnative-nord.json +0 -0
- package/themes/arnative-zinc.json +0 -0
- package/themes/arnative.json +0 -0
- package/CHANGELOG.md +0 -683
- package/extensions/animations.ts +0 -242
- package/extensions/footer.ts +0 -2617
- package/extensions/tools.ts +0 -2231
- package/extensions/ui-render-tweaks.ts +0 -1005
- package/extensions/usage-export.ts +0 -283
- package/extensions/usage.ts +0 -1406
- package/lib/check.ts +0 -21
- package/themes/gen-themes.mjs +0 -715
package/lib/todos.ts
CHANGED
|
@@ -9,7 +9,6 @@
|
|
|
9
9
|
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
10
10
|
import { softOf, thinkingColorOf } from "./ansi.ts";
|
|
11
11
|
import { renderBoxLines, renderBoxRows } from "./box.ts";
|
|
12
|
-
import { assert, isMain } from "./check.ts";
|
|
13
12
|
|
|
14
13
|
export type TodoStatus = "pending" | "in_progress" | "completed";
|
|
15
14
|
export const LIST_STATUSES = ["pending", "in_progress", "completed"] as const;
|
|
@@ -34,8 +33,8 @@ export const LIST_ICON = "\uf03a";
|
|
|
34
33
|
export const LIST_ROWS = 5;
|
|
35
34
|
/** Bounds of the adaptive window: fewer than three rows says nothing, more than nine eats the
|
|
36
35
|
* chat area even on a tall terminal. */
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
const MIN_LIST_ROWS = 3;
|
|
37
|
+
const MAX_LIST_ROWS = 9;
|
|
39
38
|
/** Lines the box spends on everything that is not a task: frame, heading, two counters. */
|
|
40
39
|
const BOX_CHROME = 5;
|
|
41
40
|
/** Lines kept for the editor, the footer and a usable chat area above the box. */
|
|
@@ -51,15 +50,15 @@ export function listRowsFor(terminalRows: number | undefined): number {
|
|
|
51
50
|
const fit = Math.floor(terminalRows) - BOX_CHROME - SCREEN_RESERVE;
|
|
52
51
|
return Math.min(MAX_LIST_ROWS, Math.max(MIN_LIST_ROWS, fit));
|
|
53
52
|
}
|
|
54
|
-
|
|
53
|
+
const STATUS_GLYPH: Record<TodoStatus, string> = { pending: "◌", in_progress: "◉", completed: "✓" };
|
|
55
54
|
/** Token for the task text itself. Queued recedes to dim and a done task reads as ordinary
|
|
56
55
|
* text; the task in progress takes the soft accent, which is derived rather than a token (see
|
|
57
56
|
* `softOf`), so it is painted separately. */
|
|
58
|
-
|
|
57
|
+
const STATUS_TEXT: Record<TodoStatus, string> = { pending: "dim", in_progress: "text", completed: "text" };
|
|
59
58
|
/** Token per status. In progress borrows the footer's model-name token (`mdHeading`), so the
|
|
60
59
|
* running task is the brightest row in the box, the way the model is the brightest text in
|
|
61
60
|
* the footer. */
|
|
62
|
-
|
|
61
|
+
const STATUS_COLOR: Record<TodoStatus, string> = { pending: "dim", in_progress: "mdHeading", completed: "accent" };
|
|
63
62
|
/** Tried when the theme has no such token; pi throws on an unknown color. */
|
|
64
63
|
const STATUS_FALLBACK: Record<TodoStatus, string> = { pending: "dim", in_progress: "accent", completed: "accent" };
|
|
65
64
|
export const HINT_EXPAND = "[show]";
|
|
@@ -91,7 +90,7 @@ function fgOr(theme: FgTheme, colors: string[], text: string): string {
|
|
|
91
90
|
|
|
92
91
|
/** Every task from a stored file, or `null` when the file is not one. Tolerant on fields,
|
|
93
92
|
* strict on the shape: a hand-edited or half-written file must not break the widget. */
|
|
94
|
-
export function normalizeState(raw: unknown):
|
|
93
|
+
export function normalizeState(raw: unknown): TodoState | null {
|
|
95
94
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
96
95
|
const tasks = (raw as { tasks?: unknown }).tasks;
|
|
97
96
|
if (!Array.isArray(tasks)) return null;
|
|
@@ -111,7 +110,7 @@ export function normalizeState(raw: unknown): TaskState | null {
|
|
|
111
110
|
|
|
112
111
|
/** One row's worth of text: control characters (an ANSI escape in a subject would break the
|
|
113
112
|
* frame) become spaces, runs collapse, and the tail is cut. */
|
|
114
|
-
|
|
113
|
+
function tidy(text: string): string {
|
|
115
114
|
const clean = text
|
|
116
115
|
.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
|
|
117
116
|
.replace(/\s+/g, " ")
|
|
@@ -178,7 +177,7 @@ export const headingText = (state: TodoState): string => {
|
|
|
178
177
|
};
|
|
179
178
|
|
|
180
179
|
/** ` · Tulis widget`, or ` · All tasks finished` once nothing is left (empty when idle). */
|
|
181
|
-
|
|
180
|
+
function collapsedSuffix(state: TodoState): string {
|
|
182
181
|
if (allDone(state)) return ` · ${COLLAPSED_DONE}`;
|
|
183
182
|
const active = activeTodo(state);
|
|
184
183
|
return active ? ` · ${active.subject}` : "";
|
|
@@ -198,18 +197,20 @@ export interface TodoWindow {
|
|
|
198
197
|
}
|
|
199
198
|
|
|
200
199
|
/**
|
|
201
|
-
* The {@link LIST_ROWS} rows the expanded box shows. The window
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
* `↓ n more` rows.
|
|
200
|
+
* The {@link LIST_ROWS} rows the expanded box shows. The window centres on the in-progress task,
|
|
201
|
+
* or the first pending task when idle, or the end of the list once everything is done, so
|
|
202
|
+
* opening a long list lands on current or upcoming work instead of old completed rows. `top`
|
|
203
|
+
* overrides that start after a scroll; it is clamped to the list, so a click past either end
|
|
204
|
+
* parks the window at the edge. `above`/`below` feed the `↑ n more` / `↓ n more` rows.
|
|
206
205
|
*/
|
|
207
206
|
export function todoWindow(state: TodoState, rows = LIST_ROWS, top: number | null = null): TodoWindow {
|
|
208
207
|
const total = state.tasks.length;
|
|
209
208
|
if (total <= rows) return { visible: state.tasks, above: 0, below: 0, start: 0 };
|
|
210
209
|
const active = state.tasks.findIndex((task) => task.status === "in_progress");
|
|
210
|
+
const pending = active === -1 ? state.tasks.findIndex((task) => task.status === "pending") : -1;
|
|
211
|
+
const anchor = active !== -1 ? active : pending !== -1 ? pending : total - 1;
|
|
211
212
|
const centre = Math.floor((rows - 1) / 2);
|
|
212
|
-
const follow =
|
|
213
|
+
const follow = Math.min(Math.max(anchor - centre, 0), total - rows);
|
|
213
214
|
const start = top === null ? follow : Math.min(Math.max(Math.trunc(top), 0), total - rows);
|
|
214
215
|
return { visible: state.tasks.slice(start, start + rows), above: start, below: total - start - rows, start };
|
|
215
216
|
}
|
|
@@ -306,7 +307,7 @@ export function todoLayout(
|
|
|
306
307
|
|
|
307
308
|
/** The word the widget and the recap use for a status (`pending` reads as `queued`,
|
|
308
309
|
* the word the summary line counts). */
|
|
309
|
-
|
|
310
|
+
const statusText = (status: TodoStatus): string =>
|
|
310
311
|
status === "in_progress" ? "in progress" : status === "pending" ? "queued" : status;
|
|
311
312
|
|
|
312
313
|
/** The word after `todo ·` in the tool box title: the status a task moved to, or the action when
|
|
@@ -347,130 +348,6 @@ export function recapSummary(state: TodoState): string {
|
|
|
347
348
|
return [`${total} tasks`, `${doing} in progress`, `${queued} queued`, `${done} done`].join(" · ");
|
|
348
349
|
}
|
|
349
350
|
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
// Writes the token down, so the self-check can name the colour a piece was painted with.
|
|
354
|
-
const marked: FgTheme = { fg: (color, text) => `[${color}]${text}` };
|
|
355
|
-
|
|
356
|
-
let state = emptyTodos();
|
|
357
|
-
assert(headingText(state) === "Todos (0/0)", "empty heading");
|
|
358
|
-
assert(collapsedText(state) === "Todos (0/0)", "empty collapsed row carries no task name");
|
|
359
|
-
assert(widgetRows(marked, state, false, 80)[0]!.startsWith(`[accent]${LIST_ICON} [accentSoft]Todos (0/0)`), "icon accent, count soft accent");
|
|
360
|
-
|
|
361
|
-
let added = addTodo(state, "Siapkan rencana");
|
|
362
|
-
state = added.state;
|
|
363
|
-
assert(added.id === 1 && state.nextId === 2, "first id is 1, next id advances");
|
|
364
|
-
for (const subject of ["Tulis widget", "Tulis layar /todos", "Uji fullscreen", "Rilis"]) state = addTodo(state, subject).state;
|
|
365
|
-
assert(countTodos(state).total === 5 && countTodos(state).queued === 5, "five queued tasks");
|
|
366
|
-
|
|
367
|
-
const patched = patchTodo(state, 2, { status: "in_progress", note: "Memproses bug ABC.txt" });
|
|
368
|
-
assert(patched !== null, "patch a known id");
|
|
369
|
-
state = patched!;
|
|
370
|
-
assert(activeTodo(state)?.subject === "Tulis widget", "the active task is the in-progress one");
|
|
371
|
-
assert(collapsedText(state) === "Todos (0/5) · Tulis widget", `collapsed names the active task, got ${collapsedText(state)}`);
|
|
372
|
-
|
|
373
|
-
state = patchTodo(state, 2, { status: "completed" })!;
|
|
374
|
-
assert(activeTodo(state) === undefined, "no active task after completing the only one");
|
|
375
|
-
// The extension folds the widget away once the list is done, yet the renderer still
|
|
376
|
-
// describes that state: it is a pure function of the list, not of who paints it.
|
|
377
|
-
const doneState = { ...state, tasks: state.tasks.map((task) => ({ ...task, status: "completed" as const })) };
|
|
378
|
-
assert(allDone(doneState) && collapsedText(doneState).endsWith(COLLAPSED_DONE), "a finished list names its end");
|
|
379
|
-
assert(headingText(state) === "Todos (1/5)", "heading counts completed over total");
|
|
380
|
-
assert(patchTodo(state, 99, { status: "completed" }) === null, "an unknown id is rejected");
|
|
381
|
-
assert(removeTodo(state, 99) === null, "removing an unknown id is rejected");
|
|
382
|
-
state = removeTodo(state, 5)!;
|
|
383
|
-
assert(countTodos(state).total === 4, "remove drops one task");
|
|
384
|
-
assert(clearTodos(state).tasks.length === 0, "clear empties the list");
|
|
385
|
-
|
|
386
|
-
// Five-row window: the active task is centred, and the hidden counts add up.
|
|
387
|
-
state = emptyTodos();
|
|
388
|
-
for (let i = 1; i <= 7; i++) state = addTodo(state, `Task ${i}`).state;
|
|
389
|
-
// Adaptive height: the window grows with the terminal, bounded at three and nine.
|
|
390
|
-
assert(listRowsFor(24) === 5 && listRowsFor(30) === 9 && listRowsFor(10) === 3, "listRowsFor bounds");
|
|
391
|
-
assert(listRowsFor(undefined) === LIST_ROWS, "unknown height falls back to the default");
|
|
392
|
-
|
|
393
|
-
assert(todoWindow(state).visible.length === 5, "five rows when more exist");
|
|
394
|
-
assert(todoWindow(state).above === 0 && todoWindow(state).below === 2, "nothing hidden above the first five");
|
|
395
|
-
state = patchTodo(state, 5, { status: "in_progress" })!;
|
|
396
|
-
const mid = todoWindow(state);
|
|
397
|
-
assert(mid.visible.map((t) => t.id).join(",") === "3,4,5,6,7", "the window follows the active task");
|
|
398
|
-
assert(mid.above === 2 && mid.below === 0, "two tasks hidden above");
|
|
399
|
-
assert(mid.above + mid.visible.length + mid.below === 7, "the window accounts for every task");
|
|
400
|
-
state = patchTodo(state, 7, { status: "in_progress" })!;
|
|
401
|
-
assert(todoWindow(state).above === 2, "the window stops at the end of the list instead of sliding past it");
|
|
402
|
-
|
|
403
|
-
// The box: collapsed 3 lines, expanded at most 10 (frame, heading, five rows, two counters).
|
|
404
|
-
state = emptyTodos();
|
|
405
|
-
for (let i = 1; i <= 20; i++) state = addTodo(state, `Task ${i}`).state;
|
|
406
|
-
state = patchTodo(state, 10, { status: "in_progress", note: "sedang menulis" })!;
|
|
407
|
-
const collapsedBox = renderTodoBox(th, state, false, 80);
|
|
408
|
-
assert(collapsedBox.length === 3, `collapsed box is frame+row+frame, got ${collapsedBox.length}`);
|
|
409
|
-
assert(collapsedBox[1]!.includes("Todos (0/20)"), "collapsed box carries the heading");
|
|
410
|
-
assert(collapsedBox[1]!.includes("Task 10"), "collapsed box names the active task");
|
|
411
|
-
assert(collapsedBox[1]!.includes(HINT_EXPAND), "collapsed box carries the expand hint");
|
|
412
|
-
// Narrow terminal: the task name gives way, the hint that opens the box does not.
|
|
413
|
-
const narrow = renderTodoBox(th, state, false, 40);
|
|
414
|
-
assert(narrow[1]!.includes(HINT_EXPAND), "the expand hint survives a narrow box");
|
|
415
|
-
assert(narrow.every((line) => line.length > 0), "a narrow box still renders every line");
|
|
416
|
-
|
|
417
|
-
const expandedBox = renderTodoBox(th, state, true, 40);
|
|
418
|
-
assert(expandedBox.length <= 10, `expanded box stays within the widget budget, got ${expandedBox.length}`);
|
|
419
|
-
assert(expandedBox.some((line) => line.includes("↑ 7 more")), "hidden tasks above are counted");
|
|
420
|
-
assert(expandedBox.some((line) => line.includes("↓ 8 more")), "hidden tasks below are counted");
|
|
421
|
-
assert(expandedBox.some((line) => line.includes("· sedang menulis")), "the in-progress note is rendered");
|
|
422
|
-
assert(!expandedBox.some((line) => line.includes("└─")), "an open branch stays ├─ while rows remain below");
|
|
423
|
-
// With nothing below the window the last row closes the branch.
|
|
424
|
-
const tail = renderTodoBox(th, patchTodo(patchTodo(state, 10, { status: "pending" })!, 20, { status: "in_progress" })!, true, 80);
|
|
425
|
-
assert(tail.some((line) => line.includes("└─")), "the last row closes the branch at the end of the list");
|
|
426
|
-
assert(
|
|
427
|
-
expandedBox.every((line) => line.startsWith("│") || line.startsWith("╭") || line.startsWith("╰")),
|
|
428
|
-
"every line belongs to the box",
|
|
429
|
-
);
|
|
430
|
-
|
|
431
|
-
// A note only belongs to the task being worked on.
|
|
432
|
-
state = patchTodo(state, 10, { status: "pending" })!;
|
|
433
|
-
assert(!renderTodoBox(th, state, true, 40).some((line) => line.includes("sedang menulis")), "a queued task hides its note");
|
|
434
|
-
|
|
435
|
-
// Hostile input: an escape sequence in a subject must not break the frame.
|
|
436
|
-
state = addTodo(emptyTodos(), "bad \u001b[31mred\u001b[0m subject").state;
|
|
437
|
-
const hostile = renderTodoBox(th, state, true, 40);
|
|
438
|
-
assert(!hostile.some((line) => line.includes("\u001b[31m")), "control characters are stripped from a subject");
|
|
439
|
-
assert(hostile.every((line) => line.length > 0), "a stripped subject still renders a row");
|
|
440
|
-
|
|
441
|
-
// Recap order and summary.
|
|
442
|
-
state = emptyTodos();
|
|
443
|
-
state = addTodo(state, "Antre A").state;
|
|
444
|
-
state = addTodo(state, "Jalan B").state;
|
|
445
|
-
state = patchTodo(state, 2, { status: "in_progress" })!;
|
|
446
|
-
state = addTodo(state, "Selesai C").state;
|
|
447
|
-
state = patchTodo(state, 3, { status: "completed" })!;
|
|
448
|
-
assert(recapRows(state).map((r) => r.label).join(" | ") === "◉ Jalan B | ◌ Antre A | ✓ Selesai C", "recap groups by status");
|
|
449
|
-
assert(recapSummary(state) === "3 tasks · 1 in progress · 1 queued · 1 done", `recap summary, got ${recapSummary(state)}`);
|
|
450
|
-
|
|
451
|
-
// A stored file: broken rows go, fields are tidied, nextId follows the highest id.
|
|
452
|
-
const loaded = normalizeState({
|
|
453
|
-
tasks: [
|
|
454
|
-
{ id: 2, subject: " Kedua ", status: "in_progress", note: "sedang jalan" },
|
|
455
|
-
{ id: 5, subject: "Kelima", status: "selesai" },
|
|
456
|
-
{ id: "x", subject: "rusak" },
|
|
457
|
-
{ id: 7, subject: " " },
|
|
458
|
-
{ id: 9, subject: "Ketiga", status: "completed" },
|
|
459
|
-
],
|
|
460
|
-
nextId: 1,
|
|
461
|
-
});
|
|
462
|
-
assert(loaded !== null, "a valid record loads");
|
|
463
|
-
assert(normalizeState(null) === null && normalizeState({ tasks: "no" }) === null, "a broken record is rejected");
|
|
464
|
-
assert(loaded!.tasks.map((task) => task.id).join(",") === "2,5,9", "broken rows are dropped");
|
|
465
|
-
assert(loaded!.tasks[0]!.subject === "Kedua" && loaded!.tasks[0]!.note === "sedang jalan", "fields are tidied");
|
|
466
|
-
assert(loaded!.tasks[1]!.status === "pending", "an unknown status falls back to pending");
|
|
467
|
-
assert(loaded!.nextId === 10, "nextId follows the highest stored id");
|
|
468
|
-
|
|
469
|
-
// The tool box title: status when a task moved, action word otherwise.
|
|
470
|
-
assert(actionWord("update", "completed") === "completed", "a known status wins over the action word");
|
|
471
|
-
assert(actionWord("update", "selesai") === "updated", "an unknown status falls back to the action");
|
|
472
|
-
assert(actionWord("create") === "created" && actionWord("delete") === "removed", "create and delete read as past tense");
|
|
473
|
-
assert(actionWord("list") === "list" && actionWord("nonsense") === "", "list keeps its name, an unknown action says nothing");
|
|
474
|
-
|
|
475
|
-
console.log("todos.ts self-check OK");
|
|
476
|
-
}
|
|
351
|
+
export const __test = {
|
|
352
|
+
fg,
|
|
353
|
+
};
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model price-table loader, cost estimator, token formatter, and UTC usage range math.
|
|
3
|
+
*/
|
|
4
|
+
import { statSync } from "node:fs";
|
|
5
|
+
import { loadModelsConfig, modelsPath } from "./provider-store.ts";
|
|
6
|
+
|
|
7
|
+
/** A time window the dashboard can show. `all` is the whole history. */
|
|
8
|
+
export type UsageRange = "all" | "today" | "7d" | "30d";
|
|
9
|
+
|
|
10
|
+
/** Tab order of the range bar. */
|
|
11
|
+
export const USAGE_RANGES: readonly UsageRange[] = ["all", "today", "7d", "30d"];
|
|
12
|
+
|
|
13
|
+
/** UTC day bucket key (`YYYY-MM-DD`) of a timestamp. */
|
|
14
|
+
export function dayKey(ms: number): string {
|
|
15
|
+
return new Date(ms > 0 ? ms : 0).toISOString().slice(0, 10);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** UTC midnight where `range` starts: today, 7 or 30 calendar days back. `undefined` for `all`. */
|
|
19
|
+
export function rangeStart(range: UsageRange, now = Date.now()): number | undefined {
|
|
20
|
+
if (range === "all") return undefined;
|
|
21
|
+
const d = new Date(now);
|
|
22
|
+
d.setUTCHours(0, 0, 0, 0);
|
|
23
|
+
if (range === "today") return d.getTime();
|
|
24
|
+
d.setUTCDate(d.getUTCDate() - (range === "7d" ? 6 : 29));
|
|
25
|
+
return d.getTime();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type ModelPrices = Record<string, { input?: number; output?: number; cacheRead?: number; cacheWrite?: number }>;
|
|
29
|
+
export type PriceTable = Record<string, ModelPrices>;
|
|
30
|
+
|
|
31
|
+
type ModelsJsonCost = { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };
|
|
32
|
+
|
|
33
|
+
let priceMemo: { key: string; table: PriceTable } | null = null;
|
|
34
|
+
|
|
35
|
+
/** Clear the memoized `models.json` price table (called by `resetUsageCache()`). */
|
|
36
|
+
export function resetPriceMemo(): void {
|
|
37
|
+
priceMemo = null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Rates declared in pi's `models.json` (`providers.<name>.models[].cost`).
|
|
42
|
+
* Memoized on the file's stat so an unchanged file is parsed once.
|
|
43
|
+
*/
|
|
44
|
+
export function loadPriceTable(): PriceTable {
|
|
45
|
+
const path = modelsPath();
|
|
46
|
+
let key: string;
|
|
47
|
+
try {
|
|
48
|
+
const st = statSync(path);
|
|
49
|
+
key = `${path}\u0000${st.mtimeMs}\u0000${st.size}`;
|
|
50
|
+
} catch {
|
|
51
|
+
key = `${path}\u0000absent`;
|
|
52
|
+
}
|
|
53
|
+
if (priceMemo && priceMemo.key === key) return priceMemo.table;
|
|
54
|
+
const table: PriceTable = {};
|
|
55
|
+
try {
|
|
56
|
+
const raw = loadModelsConfig() as {
|
|
57
|
+
providers?: Record<string, { models?: { id?: string; cost?: ModelsJsonCost }[] }>;
|
|
58
|
+
} | undefined;
|
|
59
|
+
for (const [provider, cfg] of Object.entries(raw?.providers ?? {})) {
|
|
60
|
+
const models: ModelPrices = {};
|
|
61
|
+
for (const m of cfg?.models ?? []) {
|
|
62
|
+
const c = m?.cost;
|
|
63
|
+
if (!m?.id || !c || typeof c.input !== "number" || typeof c.output !== "number") continue;
|
|
64
|
+
models[m.id] = {
|
|
65
|
+
input: c.input,
|
|
66
|
+
output: c.output,
|
|
67
|
+
cacheRead: typeof c.cacheRead === "number" ? c.cacheRead : 0,
|
|
68
|
+
cacheWrite: typeof c.cacheWrite === "number" ? c.cacheWrite : 0,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
if (Object.keys(models).length > 0) table[provider] = models;
|
|
72
|
+
}
|
|
73
|
+
} catch {
|
|
74
|
+
// Malformed or absent models.json means no declared rates.
|
|
75
|
+
}
|
|
76
|
+
priceMemo = { key, table };
|
|
77
|
+
return table;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** True when this provider+model has a usable input+output price (cacheRead/cacheWrite are optional). */
|
|
81
|
+
export function hasPrice(provider: string, modelId: string, table: PriceTable = loadPriceTable()): boolean {
|
|
82
|
+
return findPrice(provider, modelId, table) !== null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Rates for one provider+model. The provider's own entry wins over the `*` fallback. */
|
|
86
|
+
function findPrice(
|
|
87
|
+
provider: string,
|
|
88
|
+
modelId: string,
|
|
89
|
+
table: PriceTable,
|
|
90
|
+
): { input: number; output: number; cacheRead: number; cacheWrite: number } | null {
|
|
91
|
+
return rateFor(table[provider], modelId) ?? rateFor(table["*"], modelId);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function rateFor(
|
|
95
|
+
entries: ModelPrices | undefined,
|
|
96
|
+
modelId: string,
|
|
97
|
+
): { input: number; output: number; cacheRead: number; cacheWrite: number } | null {
|
|
98
|
+
if (!entries || typeof entries !== "object") return null;
|
|
99
|
+
const lower = modelId.toLowerCase();
|
|
100
|
+
const keys = Object.keys(entries).filter((k) => !k.startsWith("_"));
|
|
101
|
+
const key =
|
|
102
|
+
keys.find((k) => k.toLowerCase() === lower) ??
|
|
103
|
+
keys.find((k) => lower.endsWith("/" + k.toLowerCase()) || k.toLowerCase().endsWith("/" + lower));
|
|
104
|
+
if (!key) return null;
|
|
105
|
+
const p = entries[key]!;
|
|
106
|
+
if (typeof p.input !== "number" || typeof p.output !== "number") return null;
|
|
107
|
+
return {
|
|
108
|
+
input: p.input,
|
|
109
|
+
output: p.output,
|
|
110
|
+
cacheRead: typeof p.cacheRead === "number" ? p.cacheRead : 0,
|
|
111
|
+
cacheWrite: typeof p.cacheWrite === "number" ? p.cacheWrite : 0,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Cost of one provider+model's token counts from the price table, or null when unpriced. */
|
|
116
|
+
export function estimateCost(
|
|
117
|
+
input: number,
|
|
118
|
+
output: number,
|
|
119
|
+
cacheRead: number,
|
|
120
|
+
cacheWrite: number,
|
|
121
|
+
modelId: string,
|
|
122
|
+
provider: string,
|
|
123
|
+
table: PriceTable = loadPriceTable(),
|
|
124
|
+
): number | null {
|
|
125
|
+
const p = findPrice(provider, modelId, table);
|
|
126
|
+
if (!p) return null;
|
|
127
|
+
return (input / 1e6) * p.input + (output / 1e6) * p.output + (cacheRead / 1e6) * p.cacheRead + (cacheWrite / 1e6) * p.cacheWrite;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Scaled value with 1 decimal ("2.5k"); a value that rounds up to the next unit is promoted (999,999 -> "1M", not "1000k"). */
|
|
131
|
+
const fmtUnit = (v: number, unit: string, next: string): string => {
|
|
132
|
+
const s = v.toFixed(1).replace(/\.0$/, "");
|
|
133
|
+
return s === "1000" ? `1${next}` : `${s}${unit}`;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/** Token count with k/M/B units; 0 or negative = "-". */
|
|
137
|
+
export function formatTokens(n: number): string {
|
|
138
|
+
if (!n || n <= 0) return "-";
|
|
139
|
+
if (n < 1000) return String(n);
|
|
140
|
+
if (n < 1_000_000) return fmtUnit(n / 1000, "k", "M");
|
|
141
|
+
if (n < 1_000_000_000) return fmtUnit(n / 1_000_000, "M", "B");
|
|
142
|
+
return fmtUnit(n / 1_000_000_000, "B", "T");
|
|
143
|
+
}
|