@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.
Files changed (61) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -327
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +113 -161
  18. package/{extensions → lib/features}/timestamps.ts +18 -94
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +5 -6
  39. package/themes/arnative-blossom.json +0 -0
  40. package/themes/arnative-crimson.json +0 -0
  41. package/themes/arnative-cyberpunk.json +0 -0
  42. package/themes/arnative-dracula.json +0 -0
  43. package/themes/arnative-earthy.json +0 -0
  44. package/themes/arnative-garden.json +0 -0
  45. package/themes/arnative-gruvbox.json +0 -0
  46. package/themes/arnative-lemonade.json +0 -0
  47. package/themes/arnative-magical.json +0 -0
  48. package/themes/arnative-matrix.json +0 -0
  49. package/themes/arnative-neutral.json +0 -0
  50. package/themes/arnative-nord.json +0 -0
  51. package/themes/arnative-zinc.json +0 -0
  52. package/themes/arnative.json +0 -0
  53. package/CHANGELOG.md +0 -683
  54. package/extensions/animations.ts +0 -242
  55. package/extensions/footer.ts +0 -2617
  56. package/extensions/tools.ts +0 -2231
  57. package/extensions/ui-render-tweaks.ts +0 -1005
  58. package/extensions/usage-export.ts +0 -283
  59. package/extensions/usage.ts +0 -1406
  60. package/lib/check.ts +0 -21
  61. package/themes/gen-themes.mjs +0 -715
@@ -6,17 +6,15 @@
6
6
  * State lives in `<agent>/arnative/todos/<session id>.json`, so `/reload` and a resumed session
7
7
  * keep the list; every mutation rewrites the file.
8
8
  */
9
- import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
10
- import { tmpdir } from "node:os";
9
+ import { readdirSync, readFileSync, statSync, unlinkSync } from "node:fs";
11
10
  import { join } from "node:path";
12
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
13
- import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+ import { getAgentDir, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext } from "@earendil-works/pi-coding-agent";
14
12
  import type { TuiMouseEvent } from "@earendil-works/pi-tui";
15
- import { assert, isMain } from "../lib/check.ts";
16
- import { writeAtomicSync } from "../lib/preset-store.ts";
17
- import { inSpans, screenTitle, type TextSpan, textSpans } from "../lib/box.ts";
18
- import { ListPicker, type ListPickerText } from "../lib/list-picker.ts";
19
- import { LEGEND_READ_ONLY, SHORTCUT_SCROLL_TODOS_DOWN, SHORTCUT_SCROLL_TODOS_UP, SHORTCUT_TOGGLE_TODOS } from "../lib/shortcuts.ts";
13
+ import { writeJsonAtomicSync } from "../preset-store.ts";
14
+ import { getRuntime } from "../runtime.ts";
15
+ import { createHoldRepeat, inSpans, screenTitle, type TextSpan, textSpans } from "../box.ts";
16
+ import { ListPicker, type ListPickerText } from "../list-picker.ts";
17
+ import { LEGEND_READ_ONLY, SHORTCUT_SCROLL_TODOS_DOWN, SHORTCUT_SCROLL_TODOS_UP, SHORTCUT_TOGGLE_TODOS } from "../shortcuts.ts";
20
18
  import {
21
19
  HINT_COLLAPSE,
22
20
  HINT_EXPAND,
@@ -36,22 +34,15 @@ import {
36
34
  renderTodoBox,
37
35
  todoLayout,
38
36
  todoWindow,
39
- type TaskState,
37
+ type TodoState,
40
38
  type TodoStatus,
41
- } from "../lib/todos.ts";
39
+ } from "../todos.ts";
42
40
 
43
41
  /** pi widget key; the extension owns it, so a reload replaces its own box. */
44
- export const TODO_WIDGET_KEY = "arnative-todos";
45
-
46
- /** Delay before holding a `↑`/`↓ n more` row starts repeating, so a normal click scrolls once. */
47
- const HOLD_DELAY_MS = 250;
48
- /** Step interval while holding a `↑`/`↓ n more` counter row. */
49
- const HOLD_REPEAT_MS = 90;
50
-
51
- const STORE_KEY = Symbol.for("pi-arnative.todos.widget");
42
+ const TODO_WIDGET_KEY = "arnative-todos";
52
43
 
53
44
  interface WidgetStore {
54
- state: TaskState;
45
+ state: TodoState;
55
46
  expanded: boolean;
56
47
  /** First visible task after a scroll; null follows the active task. */
57
48
  top: number | null;
@@ -70,12 +61,11 @@ function doneHideMs(): number {
70
61
  return Number.isFinite(raw) && raw >= 0 ? raw : 30_000;
71
62
  }
72
63
 
73
- /** Module state on globalThis, like the other arnative extensions: `/reload` re-imports the
74
- * module, and a module-local copy would drop the list and the expanded flag. */
64
+ /** Module state on RuntimeState so `/reload` keeps the list and expanded flag. */
75
65
  function store(): WidgetStore {
76
- const holder = globalThis as Record<symbol, WidgetStore | undefined>;
77
- holder[STORE_KEY] ??= { state: emptyTodos(), expanded: false, top: null, registered: false };
78
- return holder[STORE_KEY]!;
66
+ const rt = getRuntime();
67
+ rt.todosWidget ??= { state: emptyTodos(), expanded: false, top: null, registered: false } satisfies WidgetStore;
68
+ return rt.todosWidget as WidgetStore;
79
69
  }
80
70
 
81
71
  /** Completed/empty session todo files older than this are pruned on session start. */
@@ -139,7 +129,7 @@ function loadState(ctx: ExtensionContext, reload = false): void {
139
129
 
140
130
  function saveState(ctx: ExtensionContext): void {
141
131
  try {
142
- writeAtomicSync(stateFile(ctx), `${JSON.stringify(store().state, null, 2)}\n`);
132
+ writeJsonAtomicSync(stateFile(ctx), store().state);
143
133
  } catch {
144
134
  // ignore: the list still renders from memory
145
135
  }
@@ -190,7 +180,7 @@ const PARAMS = {
190
180
  },
191
181
  } as never;
192
182
 
193
- const SUMMARY = (state: TaskState): string => {
183
+ const SUMMARY = (state: TodoState): string => {
194
184
  const { done, total, doing, queued } = countTodos(state);
195
185
  return `${total} tasks: ${doing} in progress, ${queued} queued, ${done} done`;
196
186
  };
@@ -302,7 +292,7 @@ function refresh(ctx: ExtensionContext, force = false): void {
302
292
  if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
303
293
  else cancelHide(s);
304
294
  if (!force && s.registered) {
305
- s.tui?.requestRender(true);
295
+ s.tui?.requestRender(false);
306
296
  return;
307
297
  }
308
298
  ctx.ui?.setWidget?.(
@@ -316,24 +306,14 @@ function refresh(ctx: ExtensionContext, force = false): void {
316
306
  /** Swallows the follow-up release/click after a press on the hint or a counter, because
317
307
  * the re-render between press and click can remove `↑ 1 more` / `↓ 1 more` at that row. */
318
308
  let swallowClick = false;
319
- let holdDelay: ReturnType<typeof setTimeout> | undefined;
320
- let holdRepeat: ReturnType<typeof setInterval> | undefined;
321
- const stopHold = (): void => {
322
- if (holdDelay) {
323
- clearTimeout(holdDelay);
324
- holdDelay = undefined;
325
- }
326
- if (holdRepeat) {
327
- clearInterval(holdRepeat);
328
- holdRepeat = undefined;
329
- }
330
- };
309
+ const hold = createHoldRepeat();
310
+ const stopHold = (): void => hold.stop();
331
311
  const toggleExpanded = (): { handled: true; render: true } => {
332
312
  s.expanded = !s.expanded;
333
313
  s.top = null;
334
314
  if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
335
315
  else cancelHide(s);
336
- s.tui?.requestRender(true);
316
+ s.tui?.requestRender(false);
337
317
  return { handled: true, render: true };
338
318
  };
339
319
  /** Move the five-row window by `delta` rows and repaint. `top` stays absolute, so the
@@ -341,32 +321,17 @@ function refresh(ctx: ExtensionContext, force = false): void {
341
321
  const scroll = (delta: number): void => {
342
322
  const { start } = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
343
323
  s.top = start + delta;
344
- s.tui?.requestRender(true);
324
+ s.tui?.requestRender(false);
345
325
  };
346
326
  const startHold = (delta: -1 | 1): void => {
347
- stopHold();
348
- const step = (): void => {
349
- if (!s.expanded) {
350
- stopHold();
351
- return;
352
- }
327
+ hold.start(() => {
328
+ if (!s.expanded) return false;
353
329
  const win = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
354
- if ((delta < 0 && win.above <= 0) || (delta > 0 && win.below <= 0)) {
355
- stopHold();
356
- return;
357
- }
330
+ if ((delta < 0 && win.above <= 0) || (delta > 0 && win.below <= 0)) return false;
358
331
  scroll(delta);
359
- };
360
- holdDelay = setTimeout(() => {
361
- holdDelay = undefined;
362
- step();
363
- if (s.expanded && holdRepeat === undefined) {
364
- const win = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
365
- if ((delta < 0 && win.above > 0) || (delta > 0 && win.below > 0)) {
366
- holdRepeat = setInterval(step, HOLD_REPEAT_MS);
367
- }
368
- }
369
- }, HOLD_DELAY_MS);
332
+ const next = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
333
+ return (delta < 0 && next.above > 0) || (delta > 0 && next.below > 0);
334
+ });
370
335
  };
371
336
  return {
372
337
  render: (width: number): string[] => {
@@ -508,11 +473,20 @@ export default function (pi: ExtensionAPI) {
508
473
 
509
474
  pi.on("session_start", async (event, ctx) => {
510
475
  const reload = (event as { reason?: string } | undefined)?.reason === "reload";
476
+ // Drop any pending hide timer from the previous session before its ctx goes stale.
477
+ cancelHide(store());
511
478
  loadState(ctx, reload);
512
479
  if (!reload) pruneCompletedTodos(todosDir(), { skipFile: stateFile(ctx) });
513
480
  refresh(ctx, true);
514
481
  });
515
482
 
483
+ pi.on("session_shutdown", () => {
484
+ const s = store();
485
+ cancelHide(s);
486
+ s.registered = false;
487
+ s.tui = undefined;
488
+ });
489
+
516
490
  pi.registerCommand("todos", {
517
491
  description: "Show every task in this session, in progress first",
518
492
  handler: (_args, ctx) => openRecap(ctx),
@@ -540,98 +514,10 @@ export default function (pi: ExtensionAPI) {
540
514
  }
541
515
  }
542
516
 
543
- // Self-check: `node extensions/todos.ts`
544
- if (isMain(import.meta.url)) {
545
- const created = runTodo({ action: "create", tasks: [{ subject: "Satu" }, { subject: "Dua", note: "catatan" }] });
546
- assert(!("isError" in created) && created.content[0]!.text === "Added 2 tasks: #1, #2", `create reports both ids, got ${created.content[0]!.text}`);
547
- const patched = runTodo({ action: "update", id: 1, status: "in_progress", note: "sedang jalan" });
548
- assert(!("isError" in patched) && patched.content[0]!.text === "Updated #1", "update reports the id");
549
- assert(store().state.tasks[0]!.status === "in_progress" && store().state.tasks[0]!.note === "sedang jalan", "update lands in the store");
550
- assert(SUMMARY(store().state) === "2 tasks: 1 in progress, 1 queued, 0 done", `summary, got ${SUMMARY(store().state)}`);
551
- const empty = runTodo({ action: "create", subject: " " });
552
- assert("isError" in empty && empty.isError === true, "an empty create is an error, not a task");
553
- const missing = runTodo({ action: "update", id: 99, status: "completed" });
554
- assert("isError" in missing && missing.content[0]!.text === "no task with id 99", "an unknown id is reported");
555
- const listed = runTodo({ action: "list" });
556
- assert(listed.content[0]!.text.split("\n").length === 2, "list prints one line per task");
557
- assert(runTodo({ action: "delete", id: 2 }).content[0]!.text === "Removed #2", "delete reports the id");
558
- assert(runTodo({ action: "clear" }).content[0]!.text === "Cleared 1 task", "clear counts what it removed");
559
- // The widget's mouse: the hint text expands and folds the box, every other cell is left
560
- // to pi so the task names can be selected and copied.
561
- runTodo({ action: "create", tasks: [{ subject: "Satu" }, { subject: "Dua" }] });
562
- store().expanded = false;
563
- let factory: any;
564
- const widgetCtx: any = { ui: { setWidget: (_key: string, f: any) => (factory = f), theme: null }, thinkingLevel: "off" };
565
- refresh(widgetCtx, true);
566
- const widget: any = factory(undefined, null);
567
- const clickAt = (x: number, y: number): void => {
568
- for (const type of ["press", "release", "click"]) widget.handleMouse({ type, button: "left", x, y });
569
- };
570
- widget.render(80);
571
- const closed = textSpans(widget.render(80), HINT_EXPAND)[0];
572
- assert(closed?.row === 1, `widget: the collapsed hint sits on the first content row, got ${closed?.row}`);
573
- clickAt(closed!.start, closed!.row);
574
- assert(store().expanded === true, "widget: a click on the hint expands");
575
- widget.render(80);
576
- const opened = textSpans(widget.render(80), HINT_COLLAPSE)[0];
577
- assert(opened !== undefined, "widget: the expanded box offers the fold hint");
578
- clickAt(opened!.start, opened!.row);
579
- assert(store().expanded === false, "widget: a click on the fold hint collapses");
580
- // Off the hint nothing is taken, so pi can start a selection over the task rows.
581
- for (const [x, y] of [[5, 1], [5, 2], [5, 3]] as const) {
582
- assert(widget.handleMouse({ type: "press", button: "left", x, y }) === undefined, `widget: a press at ${x},${y} is left to pi`);
583
- }
584
- // A finished list shows its `All tasks finished` row, then leaves: /todos still lists it.
585
- process.env.PI_ARNATIVE_TODO_HIDE_MS = "10";
586
- let lastFactory: any = "untouched";
587
- const hideCtx: any = { ui: { setWidget: (_key: string, f: any) => (lastFactory = f), theme: null }, thinkingLevel: "off" };
588
- for (const task of [...store().state.tasks]) runTodo({ action: "update", id: task.id, status: "completed" });
589
- refresh(hideCtx, true);
590
- assert(typeof lastFactory === "function", "widget: a finished list keeps its box for the wait");
591
- assert(allDone(store().state), "widget: the list really is finished");
592
- await new Promise((resolve) => setTimeout(resolve, 60));
593
- assert(lastFactory === undefined && store().registered === false, "widget: the box leaves once the wait is over");
594
- // A task reopened during the wait cancels it: the box must not vanish under live work.
595
- for (const task of [...store().state.tasks]) runTodo({ action: "update", id: task.id, status: "completed" });
596
- refresh(hideCtx, true);
597
- const reopened = store().state.tasks[0]!;
598
- runTodo({ action: "update", id: reopened.id, status: "in_progress" });
599
- refresh(hideCtx, true);
600
- await new Promise((resolve) => setTimeout(resolve, 60));
601
- assert(typeof lastFactory === "function" && store().registered === true, "widget: live work cancels the wait");
602
- delete process.env.PI_ARNATIVE_TODO_HIDE_MS;
603
- // A new task cancels nothing (the timer already fired) and brings the box back at once.
604
- runTodo({ action: "create", subject: "Lagi" });
605
- refresh(hideCtx, true);
606
- assert(typeof lastFactory === "function", "widget: a new task brings the box back");
607
- // A new session with no file on disk starts empty instead of inheriting the previous session's list.
608
- loadState({ sessionManager: { getSessionId: () => `empty-${process.pid}-${Date.now()}` } } as never);
609
- assert(store().state.tasks.length === 0 && store().expanded === false, "session_start: a fresh session starts with an empty list");
610
- // Auto-prune removes old completed/empty todo files while keeping open, recent, and active-session files.
611
- const pruneTmp = mkdtempSync(join(tmpdir(), "arnative-todos-prune-"));
612
- try {
613
- const now = Date.now();
614
- const oldSec = (now - TODO_PRUNE_AGE_MS - 60_000) / 1000;
615
- const put = (name: string, data: unknown, old: boolean): string => {
616
- const p = join(pruneTmp, name);
617
- writeFileSync(p, JSON.stringify(data));
618
- if (old) utimesSync(p, oldSec, oldSec);
619
- return p;
620
- };
621
- put("old-done.json", { nextId: 2, tasks: [{ id: 1, subject: "a", status: "completed" }] }, true);
622
- put("old-empty.json", { nextId: 1, tasks: [] }, true);
623
- put("old-open.json", { nextId: 2, tasks: [{ id: 1, subject: "b", status: "pending" }] }, true);
624
- put("recent-done.json", { nextId: 2, tasks: [{ id: 1, subject: "c", status: "completed" }] }, false);
625
- const activePath = put("active-done.json", { nextId: 2, tasks: [{ id: 1, subject: "d", status: "completed" }] }, true);
626
- const removed = pruneCompletedTodos(pruneTmp, { now, skipFile: activePath });
627
- const left = readdirSync(pruneTmp).sort();
628
- assert(removed === 2, `prune: expected 2 removed, got ${removed}`);
629
- assert(
630
- left.join(",") === "active-done.json,old-open.json,recent-done.json",
631
- `prune: expected open/recent/active kept, got ${left.join(",")}`,
632
- );
633
- } finally {
634
- rmSync(pruneTmp, { recursive: true, force: true });
635
- }
636
- console.log("todos extension self-check OK");
637
- }
517
+ export const __test = {
518
+ store,
519
+ TODO_PRUNE_AGE_MS,
520
+ loadState,
521
+ SUMMARY,
522
+ refresh,
523
+ };