pi-mega-compact 0.8.22 → 0.8.24

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 (63) hide show
  1. package/LICENSE +6 -2
  2. package/README.md +1 -1
  3. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +8 -0
  4. package/dist/extensions/dashboard-server/api-contracts/game-types.js +7 -0
  5. package/dist/extensions/mega-runtime/append-event.js +24 -0
  6. package/dist/extensions/mega-runtime/bind-repo.js +65 -0
  7. package/dist/extensions/mega-runtime/capture-model.js +87 -0
  8. package/dist/extensions/mega-runtime/dashboard-snapshot.js +118 -0
  9. package/dist/extensions/mega-runtime/effects.js +86 -0
  10. package/dist/extensions/mega-runtime/engine-view.js +11 -0
  11. package/dist/extensions/mega-runtime/game-state.js +116 -0
  12. package/dist/extensions/mega-runtime/get-state-dir.js +10 -0
  13. package/dist/extensions/mega-runtime/perf.js +49 -0
  14. package/dist/extensions/mega-runtime/pressure-getters.js +64 -0
  15. package/dist/extensions/mega-runtime/render-widget.js +17 -0
  16. package/dist/extensions/mega-runtime/reset-runtime.js +50 -0
  17. package/dist/extensions/mega-runtime/runtime-helpers.js +73 -0
  18. package/dist/extensions/mega-runtime/runtime-snapshot.js +204 -0
  19. package/dist/extensions/mega-runtime/runtime.js +352 -0
  20. package/dist/extensions/mega-runtime/snapshot.js +142 -0
  21. package/dist/extensions/mega-runtime/state.js +5 -1151
  22. package/dist/extensions/mega-runtime/status.js +11 -0
  23. package/dist/extensions/mega-runtime/widget-ansi.js +207 -0
  24. package/dist/extensions/mega-runtime/widget-types.js +8 -0
  25. package/dist/extensions/mega-runtime/widget.js +15 -204
  26. package/dist/extensions/openclaw-mega-compact.js +291 -0
  27. package/dist/src/dedup/raptor/multilevel.js +172 -0
  28. package/dist/src/dedup/raptor/multilevel.test.js +203 -0
  29. package/dist/src/dedup/raptor/retrieval.js +1 -1
  30. package/dist/src/minilm.js +92 -0
  31. package/dist/src/wordpiece.js +129 -0
  32. package/extensions/dashboard-client/dist/assets/index-D_WtU2TV.js.map +1 -1
  33. package/extensions/dashboard-server/api-contracts/endpoints.ts +30 -155
  34. package/extensions/dashboard-server/api-contracts/game-types.ts +172 -0
  35. package/extensions/mega-runtime/DECOMPOSITION.md +180 -0
  36. package/extensions/mega-runtime/README.md +38 -0
  37. package/extensions/mega-runtime/append-event.ts +40 -0
  38. package/extensions/mega-runtime/bind-repo.ts +81 -0
  39. package/extensions/mega-runtime/capture-model.ts +101 -0
  40. package/extensions/mega-runtime/dashboard-snapshot.ts +173 -0
  41. package/extensions/mega-runtime/effects.ts +129 -0
  42. package/extensions/mega-runtime/engine-view.ts +17 -0
  43. package/extensions/mega-runtime/game-state.ts +149 -0
  44. package/extensions/mega-runtime/get-state-dir.ts +19 -0
  45. package/extensions/mega-runtime/perf.ts +60 -0
  46. package/extensions/mega-runtime/pressure-getters.ts +96 -0
  47. package/extensions/mega-runtime/render-widget.ts +41 -0
  48. package/extensions/mega-runtime/reset-runtime.ts +80 -0
  49. package/extensions/mega-runtime/runtime-helpers.ts +119 -0
  50. package/extensions/mega-runtime/runtime-snapshot.ts +289 -0
  51. package/extensions/mega-runtime/runtime.ts +437 -0
  52. package/extensions/mega-runtime/snapshot.ts +230 -0
  53. package/extensions/mega-runtime/state.ts +5 -1268
  54. package/extensions/mega-runtime/status.ts +26 -0
  55. package/extensions/mega-runtime/widget-ansi.ts +217 -0
  56. package/extensions/mega-runtime/widget-types.ts +80 -0
  57. package/extensions/mega-runtime/widget.ts +34 -285
  58. package/package.json +2 -2
  59. package/src/dedup/raptor/multilevel.test.ts +278 -0
  60. package/src/dedup/raptor/multilevel.ts +246 -0
  61. package/src/dedup/raptor/retrieval.ts +1 -1
  62. package/dist/extensions/dashboard-client/src/hooks/useApi.js +0 -51
  63. package/dist/extensions/dashboard-client/src/hooks/useSSE.js +0 -63
@@ -0,0 +1,26 @@
1
+ /**
2
+ * status.ts — extracted `MegaRuntime.setStatus()`: the runtime status-key text
3
+ * mirrored to pi's status line and the dashboard. Same thin-delegate pattern
4
+ * as the other runtime.ts extractions.
5
+ */
6
+
7
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
+ import { STATUS_KEY } from "./helpers.js";
9
+
10
+ // ---------------------------------------------------------------------- types
11
+
12
+ /** The slice of `MegaRuntime` setStatus writes (the dashboard status text). */
13
+ export interface SetStatusContext {
14
+ statusKey: string | undefined;
15
+ }
16
+
17
+ // ------------------------------------------------------------------ setStatus
18
+
19
+ export function setStatusImpl(
20
+ self: SetStatusContext,
21
+ ctx: ExtensionContext,
22
+ text: string | undefined,
23
+ ): void {
24
+ self.statusKey = text;
25
+ ctx.ui.setStatus(STATUS_KEY, text);
26
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * widget-ansi.ts — the ANSI palette, theme resolution, panel layout helpers,
3
+ * and ambient border-effect helpers extracted from the original widget.ts.
4
+ *
5
+ * Pure rendering primitives with zero runtime-state dependencies. The render
6
+ * function (widget.ts) and the snapshot computation (snapshot.ts) import these;
7
+ * `C` is also re-exported via the widget barrel for mega-pipeline/mega-commands.
8
+ */
9
+
10
+ // pi-tui's OWN width measurers — the same functions pi-tui uses to enforce its
11
+ // render-width check ("visibleWidth(line) > width" → crash). Measuring with
12
+ // these guarantees we never disagree on a grapheme's width (e.g. RGI emoji
13
+ // like ⚡ which pi-tui counts as 2 but a naive regex counts as 1), and
14
+ // truncateToWidth both pads AND hard-clips to exactly `width` cells, so no
15
+ // off-by-one can trip the strict `> width` guard. (Fix for the
16
+ // `Rendered line N exceeds terminal width (W > W-1)` crash.)
17
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
18
+ import { getTheme, DEFAULT_THEME } from "../../src/config/themes.js";
19
+ import type { WidgetData } from "./widget-types.js";
20
+
21
+ // ── ANSI palette ───────────────────────────────────────────────────────────
22
+ // The pi TUI's Text component preserves ANSI escape codes (see wrapTextWithAnsi),
23
+ // so raw escapes render as colors. No chalk dependency needed — these are just
24
+ // strings. Exported because mega-pipeline.ts and mega-commands.ts import `C`
25
+ // from the mega-runtime barrel.
26
+ export const C = {
27
+ reset: "\x1b[0m",
28
+ dim: "\x1b[2m",
29
+ bold: "\x1b[1m",
30
+ amber: "\x1b[38;5;214m", // tier / ready
31
+ green: "\x1b[38;5;120m", // saved
32
+ cyan: "\x1b[38;5;51m", // used / live activity
33
+ teal: "\x1b[38;5;37m", // processing (compress/dedup)
34
+ magenta: "\x1b[38;5;201m", // dedup rate
35
+ blue: "\x1b[38;5;75m", // repo totals
36
+ gray: "\x1b[38;5;245m", // labels
37
+ red: "\x1b[38;5;203m", // pressure / overflow
38
+ };
39
+
40
+ export const PULSE = ["◐", "◓", "◑", "◒"];
41
+
42
+ // ── Full-width widget panel helpers ────────────────────────────────────────
43
+ // pi's above-editor widget renderer (a Container of Text lines) does NOT pass
44
+ // a terminal width to setWidget(), so lines render left-aligned by default. To
45
+ // make the widget read as a full-width status panel we pad each line to the
46
+ // real terminal width with a background fill. NOTE: C.reset is a FULL SGR
47
+ // reset, so we re-apply the panel bg after every reset to keep the background
48
+ // continuous under colored text (and under pi's own trailing reset).
49
+ /** Default panel background (dark slate). Used when no theme is threaded or
50
+ * the theme is transparent (no bg fill). Parametrized per-render via the
51
+ * `panelTheme` arg so game-mode themes can restyle the panel background.
52
+ * A transparent theme yields `""` so panelLine/panelBar still call
53
+ * truncateToWidth (the width guard holds — empty prefix adds zero cells). */
54
+ export const DEFAULT_PANEL_BG = "\x1b[48;5;236m"; // dark slate panel background
55
+
56
+ /** Resolve the panel-background SGR prefix for a theme id. Transparent themes
57
+ * (bg=null) and unknown themes yield `""` (no bg fill) — the width guard in
58
+ * panelLine/panelBar still applies via truncateToWidth. */
59
+ export function panelBgFor(theme: string | undefined): string {
60
+ if (!theme || theme === DEFAULT_THEME) return "";
61
+ const t = getTheme(theme);
62
+ const bg = t?.ansi.bg;
63
+ return bg ? `\x1b[${bg}m` : "";
64
+ }
65
+
66
+ /** Resolve a theme ANSI accent/mega/fg SGR prefix (`\x1b[<params>m`) for the
67
+ * given role. Falls back to `""` (no SGR) for transparent/unknown themes so
68
+ * game-mode text still renders in the default fg without color noise. */
69
+ export function themeAnsi(theme: string | undefined, role: "fg" | "accent" | "mega"): string {
70
+ const t = theme ? getTheme(theme) : undefined;
71
+ const params = t?.ansi[role];
72
+ return params ? `\x1b[${params}m` : "";
73
+ }
74
+
75
+ /** Emit a full SGR reset, OR `""` if `sgr` is empty (transparent theme). Keeps
76
+ * the panel bg continuous by NOT clobbering it with a bare reset when the
77
+ * accent/mega prefix was a no-op. */
78
+ export function sgrReset(sgr: string): string {
79
+ return sgr ? "\x1b[0m" : "";
80
+ }
81
+
82
+ // (Visible-width measurement is delegated to pi-tui's `visibleWidth` — imported
83
+ // above — so our width math can never diverge from pi-tui's render-width check.)
84
+
85
+ /** Wrap a string (with ANSI codes) to fit within `maxWidth` visible chars.
86
+ * Splits at │ separators or whitespace when possible. */
87
+ export function wrapLine(text: string, maxWidth: number, panelBg: string): string[] {
88
+ if (maxWidth <= 0) return [text];
89
+ const panelRst = "\x1b[0m" + panelBg;
90
+ const result: string[] = [];
91
+ let current = "";
92
+ let currentW = 0;
93
+ // Split at │ boundaries first
94
+ const segments = text.split("│");
95
+ for (let i = 0; i < segments.length; i++) {
96
+ const seg = (i > 0 ? "│" : "") + segments[i];
97
+ const segW = visibleWidth(panelBg + seg.replace(/\x1b\[0m/g, panelRst));
98
+ if (currentW + segW <= maxWidth || currentW === 0) {
99
+ current += seg;
100
+ currentW += segW;
101
+ } else {
102
+ result.push(current);
103
+ current = seg;
104
+ currentW = segW;
105
+ }
106
+ }
107
+ if (current) result.push(current);
108
+ return result;
109
+ }
110
+
111
+ export function panelLine(content: string, width: number, panelBg: string = DEFAULT_PANEL_BG): string {
112
+ if (width <= 0) return "";
113
+ const panelRst = "\x1b[0m" + panelBg;
114
+ // Apply the panel background; swap every inner full-reset for a reset that
115
+ // re-applies the bg so the fill stays continuous under colored text.
116
+ const withBg = panelBg + content.replace(/\x1b\[0m/g, panelRst);
117
+ // truncateToWidth(line, width, "", true) returns EXACTLY `width` visible cells
118
+ // (by pi-tui's measure), ANSI-preserved, space-padded. It hard-clips overflow
119
+ // — so even a segment wider than `width` (or a width-rule mismatch) can never
120
+ // produce a line that trips pi-tui's strict `visibleWidth(line) > width` check.
121
+ return truncateToWidth(withBg, width, "", true) + "\x1b[0m";
122
+ }
123
+
124
+ /** A full-width hairline bar (top/bottom border of the panel). */
125
+ export function panelBar(width: number, ch = "─", panelBg: string = DEFAULT_PANEL_BG): string {
126
+ // `─` (U+2500) is narrow (1 cell) in both our measure and pi-tui's, so a
127
+ // `ch.repeat(width)` bar is exactly `width` cells and already passes the
128
+ // `> width` guard. truncateToWidth is belt-and-suspenders in case `ch` is
129
+ // ever swapped for a wide/fullwidth character.
130
+ return truncateToWidth(panelBg + ch.repeat(Math.max(0, width)), width, "", false) + "\x1b[0m";
131
+ }
132
+
133
+ // ── v0.8.3: ambient border-effect helpers ───────────────────────────────
134
+ // The panel borders animate when an `activeEffect` is armed (level-up,
135
+ // mega-cache overshoot, achievement unlock, compaction start). Two modes:
136
+ // • pulse — a sine ramp on a 256-color base (accent=51 / mega=214 / red=203):
137
+ // the base index is scaled by sin(π·t) so the border swells 0→peak→0 over
138
+ // the duration, then returns to '' (idle). 256-color indices are clamped
139
+ // to 0–255 defensively (the bases are all ≤214 so the clamp rarely bites).
140
+ // • flash — a 120ms hard on/off alternate using the base index at full.
141
+ // Returns '' when idle, expired, or elapsed<0 (clock skew) so non-effect
142
+ // renders are byte-identical to the pre-effect panel (S31 matrix stays green).
143
+ export const EFFECT_BASE: Record<"accent" | "mega" | "red", number> = {
144
+ accent: 51,
145
+ mega: 214,
146
+ red: 203,
147
+ };
148
+
149
+ /** Resolve the per-frame border-fg SGR for an active effect. '' when idle or
150
+ * expired (the widget's real per-frame expiry enforcer — snapshot-level clear
151
+ * is just bookkeeping since snapshot is event-driven). */
152
+ export function effectBorderSgr(
153
+ ae: NonNullable<WidgetData["activeEffect"]> | null,
154
+ now: number,
155
+ ): string {
156
+ if (!ae) return "";
157
+ const elapsed = now - ae.startedAt;
158
+ if (elapsed < 0 || elapsed >= ae.durationMs) return "";
159
+ const base = EFFECT_BASE[ae.role];
160
+ if (ae.type === "flash") {
161
+ // 120ms hard alternate: on (full base) / off (no SGR).
162
+ return Math.floor(elapsed / 120) % 2 === 0 ? `\x1b[38;5;${base}m` : "";
163
+ }
164
+ // pulse: sine ramp 0 → peak → 0 over the duration.
165
+ const t = elapsed / ae.durationMs;
166
+ const amp = Math.sin(Math.PI * t); // 0 at start/end, 1 at midpoint
167
+ const idx = Math.max(0, Math.min(255, Math.round(base * amp)));
168
+ return `\x1b[38;5;${idx}m`;
169
+ }
170
+
171
+ /** Prepend the effect border SGR to a panel bar line. The SGR is a pure-fg
172
+ * escape (zero visible width), so it never perturbs truncateToWidth's width
173
+ * math — the bar's own `\x1b[0m` tail resets both fg + bg. No-op when sgr=''. */
174
+ export function effectBar(bar: string, sgr: string): string {
175
+ return sgr ? sgr + bar : bar;
176
+ }
177
+
178
+ /** Token-count formatter: M at/above 1e6, k at/above 1e3, raw below.
179
+ * 5,472,700 → "5.5mil", 24,100 → "24.1k", 142 → "142". */
180
+ export function fmtTokens(x: number): string {
181
+ return x >= 1_000_000
182
+ ? `${(x / 1_000_000).toFixed(1)}mil`
183
+ : x >= 1000
184
+ ? `${(x / 1000).toFixed(1)}k`
185
+ : `${Math.round(x)}`;
186
+ }
187
+
188
+ /** Retro gradient bar — `w` cells shaded by fill position (green→amber→red).
189
+ * Used for CONTEXT fill where low=green (room) and high=red (near the limit). */
190
+ export function ramp(pct: number, w = 12): string {
191
+ const cells = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"];
192
+ const scaled = Math.max(0, Math.min(w, pct * w));
193
+ const full = Math.floor(scaled);
194
+ const frac = scaled - full;
195
+ const fracCell = frac > 0 ? cells[Math.round(frac * (cells.length - 1))] : "";
196
+ let out = "";
197
+ for (let i = 0; i < full; i++)
198
+ out += (i / w < 0.6 ? C.green : i / w < 0.85 ? C.amber : C.red) + "█";
199
+ if (fracCell)
200
+ out +=
201
+ (full / w < 0.6 ? C.green : full / w < 0.85 ? C.amber : C.red) + fracCell;
202
+ out +=
203
+ C.dim + "░".repeat(Math.max(0, w - full - (fracCell ? 1 : 0))) + C.reset;
204
+ return out;
205
+ }
206
+
207
+ /** Human "time since" string from a millisecond delta (or null → "never"). */
208
+ export function sinceCompactStr(ms: number | null): string {
209
+ if (ms == null) return "never";
210
+ const s = Math.floor(ms / 1000);
211
+ if (s < 60) return `${s}s ago`;
212
+ const m = Math.floor(s / 60);
213
+ if (m < 60) return `${m}m ago`;
214
+ const h = Math.floor(m / 60);
215
+ if (h < 24) return `${h}h ago`;
216
+ return `${Math.floor(h / 24)}d ago`;
217
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * widget-types.ts — the `TickerEntry` and `WidgetData` interfaces extracted from
3
+ * the original widget.ts so the ANSI helpers (widget-ansi.ts) and the render
4
+ * function (widget.ts) can import them without a cycle.
5
+ *
6
+ * Pure type definitions — zero runtime code, zero imports.
7
+ */
8
+
9
+ /** Ticker ring-buffer entry (recall/activity history for the widget footer). */
10
+ export interface TickerEntry {
11
+ text: string;
12
+ at: number;
13
+ }
14
+
15
+ /** Immutable snapshot of everything the above-editor widget needs to render.
16
+ * Computed once per `snapshot()` (event-driven) and read by `buildWidgetLines`
17
+ * on every TUI render frame, so frame rendering stays allocation-cheap and the
18
+ * panel auto-fits whatever width pi passes to the setWidget factory. */
19
+ export interface WidgetData {
20
+ version: string;
21
+ tierLabel: string;
22
+ triggerLabel: string;
23
+ pctStr: string;
24
+ tokStr: string;
25
+ maxStr: string;
26
+ ctxPct: number;
27
+ chk: number;
28
+ agentStr: string;
29
+ turnStr: string;
30
+ dedupStr: string;
31
+ sessIn: number;
32
+ sessKept: number;
33
+ sTxt: string;
34
+ repoIn: number;
35
+ repoKept: number;
36
+ rTxt: string;
37
+ repoChk: number;
38
+ repoSess: number;
39
+ modelStr: string;
40
+ sinceCompact: number | null;
41
+ embedderName: string;
42
+ compStr: string;
43
+ driftStatus: "ok" | "warn";
44
+ agentsActive: boolean;
45
+ fresh: boolean;
46
+ ticker: TickerEntry[];
47
+ lastWhy: string | undefined;
48
+ tierTrace: string | undefined;
49
+ pulsing: boolean;
50
+ // ── S31: game-mode theming + display modes + level + MEGA CACHE flare ──
51
+ /** Game mode on (shows level + MEGA CACHE flare; hides them when off). */
52
+ gameMode?: boolean;
53
+ /** Theme id (src/config/themes). Drives the panel bg + accent/mega ANSI. */
54
+ theme?: string;
55
+ /** TUI display mode: 'full' (default) = the full stats panel; 'minimal' = a
56
+ * one-line `LVL n | cache NN%` view flanked by panel bars. */
57
+ tuiMode?: "full" | "minimal";
58
+ /** Player level (game-mode). Stub = 1 until S33 wires the real scoring. */
59
+ level?: number;
60
+ /** Cache hit rate as a percent (0..100+, may exceed 100 → MEGA CACHE). */
61
+ cachePct?: number;
62
+ /** MEGA CACHE flare armed (fires at cachePct >= 100 + gameMode on). Adds the
63
+ * ANSI MEGA CACHE banner + the oopsie gag to the header. */
64
+ megaCacheFlare?: boolean;
65
+ /** The peak cache % that armed the flare (for the oopsie toast text). */
66
+ megaCacheFlarePct?: number;
67
+ levelUpFlare?: boolean;
68
+ /** S35: achievement-unlock flare -- renders a one-line toast for one cycle. */
69
+ achievementFlare?: boolean;
70
+ achievementFlareTitles?: string[];
71
+ /** v0.8.3: ambient animated border effect (null when idle/expired). The
72
+ * widget computes the per-frame phase from startedAt vs Date.now() and
73
+ * renders a pulse/flash on the panel borders; '' once the window elapses. */
74
+ activeEffect?: {
75
+ type: "pulse" | "flash";
76
+ role: "accent" | "mega" | "red";
77
+ startedAt: number;
78
+ durationMs: number;
79
+ } | null;
80
+ }
@@ -1,294 +1,43 @@
1
1
  /**
2
- * widget.ts — above-editor widget rendering helpers (free functions, consts,
3
- * and interfaces) extracted from the original mega-runtime.ts monolith.
2
+ * widget.ts — above-editor widget rendering. Now a thin module that owns the
3
+ * `buildWidgetLines` render function and re-exports the ANSI helpers
4
+ * (widget-ansi.ts) + the interfaces (widget-types.ts) so every existing
5
+ * `import { C, TickerEntry, WidgetData, buildWidgetLines } from "./widget.js"`
6
+ * continues to resolve with no consumer changes.
4
7
  *
5
- * These are pure rendering primitives with zero runtime-state dependencies;
6
- * the `MegaRuntime` class (state.ts) imports them to paint the panel.
8
+ * Originally a single ~422-line file; split for the Phase 2 decomposition
9
+ * (see DECOMPOSITION.md). Pure rendering primitives zero runtime-state
10
+ * dependencies; the `MegaRuntime` class (runtime.ts) imports them to paint the
11
+ * panel.
7
12
  */
8
13
 
9
- // pi-tui's OWN width measurers the same functions pi-tui uses to enforce its
10
- // render-width check ("visibleWidth(line) > width" → crash). Measuring with
11
- // these guarantees we never disagree on a grapheme's width (e.g. RGI emoji
12
- // like ⚡ which pi-tui counts as 2 but a naive regex counts as 1), and
13
- // truncateToWidth both pads AND hard-clips to exactly `width` cells, so no
14
- // off-by-one can trip the strict `> width` guard. (Fix for the
15
- // `Rendered line N exceeds terminal width (W > W-1)` crash.)
16
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
17
- import { getTheme, DEFAULT_THEME } from "../../src/config/themes.js";
18
-
19
- // ── ANSI palette ───────────────────────────────────────────────────────────
20
- // The pi TUI's Text component preserves ANSI escape codes (see wrapTextWithAnsi),
21
- // so raw escapes render as colors. No chalk dependency needed — these are just
22
- // strings. Exported because mega-pipeline.ts and mega-commands.ts import `C`
23
- // from the mega-runtime barrel.
24
- export const C = {
25
- reset: "\x1b[0m",
26
- dim: "\x1b[2m",
27
- bold: "\x1b[1m",
28
- amber: "\x1b[38;5;214m", // tier / ready
29
- green: "\x1b[38;5;120m", // saved
30
- cyan: "\x1b[38;5;51m", // used / live activity
31
- teal: "\x1b[38;5;37m", // processing (compress/dedup)
32
- magenta: "\x1b[38;5;201m", // dedup rate
33
- blue: "\x1b[38;5;75m", // repo totals
34
- gray: "\x1b[38;5;245m", // labels
35
- red: "\x1b[38;5;203m", // pressure / overflow
36
- };
37
-
38
- const PULSE = ["◐", "◓", "◑", "◒"];
39
-
40
- // ── Full-width widget panel helpers ────────────────────────────────────────
41
- // pi's above-editor widget renderer (a Container of Text lines) does NOT pass
42
- // a terminal width to setWidget(), so lines render left-aligned by default. To
43
- // make the widget read as a full-width status panel we pad each line to the
44
- // real terminal width with a background fill. NOTE: C.reset is a FULL SGR
45
- // reset, so we re-apply the panel bg after every reset to keep the background
46
- // continuous under colored text (and under pi's own trailing reset).
47
- /** Default panel background (dark slate). Used when no theme is threaded or
48
- * the theme is transparent (no bg fill). Parametrized per-render via the
49
- * `panelTheme` arg so game-mode themes can restyle the panel background.
50
- * A transparent theme yields `""` so panelLine/panelBar still call
51
- * truncateToWidth (the width guard holds — empty prefix adds zero cells). */
52
- const DEFAULT_PANEL_BG = "\x1b[48;5;236m"; // dark slate panel background
53
-
54
- /** Resolve the panel-background SGR prefix for a theme id. Transparent themes
55
- * (bg=null) and unknown themes yield `""` (no bg fill) — the width guard in
56
- * panelLine/panelBar still applies via truncateToWidth. */
57
- function panelBgFor(theme: string | undefined): string {
58
- if (!theme || theme === DEFAULT_THEME) return "";
59
- const t = getTheme(theme);
60
- const bg = t?.ansi.bg;
61
- return bg ? `\x1b[${bg}m` : "";
62
- }
63
-
64
- /** Resolve a theme ANSI accent/mega/fg SGR prefix (`\x1b[<params>m`) for the
65
- * given role. Falls back to `""` (no SGR) for transparent/unknown themes so
66
- * game-mode text still renders in the default fg without color noise. */
67
- function themeAnsi(theme: string | undefined, role: "fg" | "accent" | "mega"): string {
68
- const t = theme ? getTheme(theme) : undefined;
69
- const params = t?.ansi[role];
70
- return params ? `\x1b[${params}m` : "";
71
- }
72
-
73
- /** Emit a full SGR reset, OR `""` if `sgr` is empty (transparent theme). Keeps
74
- * the panel bg continuous by NOT clobbering it with a bare reset when the
75
- * accent/mega prefix was a no-op. */
76
- function sgrReset(sgr: string): string {
77
- return sgr ? "\x1b[0m" : "";
78
- }
79
-
80
- // (Visible-width measurement is delegated to pi-tui's `visibleWidth` — imported
81
- // above — so our width math can never diverge from pi-tui's render-width check.)
82
-
83
- /** Wrap a string (with ANSI codes) to fit within `maxWidth` visible chars.
84
- * Splits at │ separators or whitespace when possible. */
85
- function wrapLine(text: string, maxWidth: number, panelBg: string): string[] {
86
- if (maxWidth <= 0) return [text];
87
- const panelRst = "\x1b[0m" + panelBg;
88
- const result: string[] = [];
89
- let current = "";
90
- let currentW = 0;
91
- // Split at │ boundaries first
92
- const segments = text.split("│");
93
- for (let i = 0; i < segments.length; i++) {
94
- const seg = (i > 0 ? "│" : "") + segments[i];
95
- const segW = visibleWidth(panelBg + seg.replace(/\x1b\[0m/g, panelRst));
96
- if (currentW + segW <= maxWidth || currentW === 0) {
97
- current += seg;
98
- currentW += segW;
99
- } else {
100
- result.push(current);
101
- current = seg;
102
- currentW = segW;
103
- }
104
- }
105
- if (current) result.push(current);
106
- return result;
107
- }
108
-
109
- function panelLine(content: string, width: number, panelBg: string = DEFAULT_PANEL_BG): string {
110
- if (width <= 0) return "";
111
- const panelRst = "\x1b[0m" + panelBg;
112
- // Apply the panel background; swap every inner full-reset for a reset that
113
- // re-applies the bg so the fill stays continuous under colored text.
114
- const withBg = panelBg + content.replace(/\x1b\[0m/g, panelRst);
115
- // truncateToWidth(line, width, "", true) returns EXACTLY `width` visible cells
116
- // (by pi-tui's measure), ANSI-preserved, space-padded. It hard-clips overflow
117
- // — so even a segment wider than `width` (or a width-rule mismatch) can never
118
- // produce a line that trips pi-tui's strict `visibleWidth(line) > width` check.
119
- return truncateToWidth(withBg, width, "", true) + "\x1b[0m";
120
- }
121
-
122
- /** A full-width hairline bar (top/bottom border of the panel). */
123
- function panelBar(width: number, ch = "─", panelBg: string = DEFAULT_PANEL_BG): string {
124
- // `─` (U+2500) is narrow (1 cell) in both our measure and pi-tui's, so a
125
- // `ch.repeat(width)` bar is exactly `width` cells and already passes the
126
- // `> width` guard. truncateToWidth is belt-and-suspenders in case `ch` is
127
- // ever swapped for a wide/fullwidth character.
128
- return truncateToWidth(panelBg + ch.repeat(Math.max(0, width)), width, "", false) + "\x1b[0m";
129
- }
130
-
131
- // ── v0.8.3: ambient border-effect helpers ───────────────────────────────
132
- // The panel borders animate when an `activeEffect` is armed (level-up,
133
- // mega-cache overshoot, achievement unlock, compaction start). Two modes:
134
- // • pulse — a sine ramp on a 256-color base (accent=51 / mega=214 / red=203):
135
- // the base index is scaled by sin(π·t) so the border swells 0→peak→0 over
136
- // the duration, then returns to '' (idle). 256-color indices are clamped
137
- // to 0–255 defensively (the bases are all ≤214 so the clamp rarely bites).
138
- // • flash — a 120ms hard on/off alternate using the base index at full.
139
- // Returns '' when idle, expired, or elapsed<0 (clock skew) so non-effect
140
- // renders are byte-identical to the pre-effect panel (S31 matrix stays green).
141
- const EFFECT_BASE: Record<"accent" | "mega" | "red", number> = {
142
- accent: 51,
143
- mega: 214,
144
- red: 203,
145
- };
146
-
147
- /** Resolve the per-frame border-fg SGR for an active effect. '' when idle or
148
- * expired (the widget's real per-frame expiry enforcer — snapshot-level clear
149
- * is just bookkeeping since snapshot is event-driven). */
150
- function effectBorderSgr(
151
- ae: NonNullable<WidgetData["activeEffect"]> | null,
152
- now: number,
153
- ): string {
154
- if (!ae) return "";
155
- const elapsed = now - ae.startedAt;
156
- if (elapsed < 0 || elapsed >= ae.durationMs) return "";
157
- const base = EFFECT_BASE[ae.role];
158
- if (ae.type === "flash") {
159
- // 120ms hard alternate: on (full base) / off (no SGR).
160
- return Math.floor(elapsed / 120) % 2 === 0 ? `\x1b[38;5;${base}m` : "";
161
- }
162
- // pulse: sine ramp 0 → peak → 0 over the duration.
163
- const t = elapsed / ae.durationMs;
164
- const amp = Math.sin(Math.PI * t); // 0 at start/end, 1 at midpoint
165
- const idx = Math.max(0, Math.min(255, Math.round(base * amp)));
166
- return `\x1b[38;5;${idx}m`;
167
- }
168
-
169
- /** Prepend the effect border SGR to a panel bar line. The SGR is a pure-fg
170
- * escape (zero visible width), so it never perturbs truncateToWidth's width
171
- * math — the bar's own `\x1b[0m` tail resets both fg + bg. No-op when sgr=''. */
172
- function effectBar(bar: string, sgr: string): string {
173
- return sgr ? sgr + bar : bar;
174
- }
175
-
176
- /** Token-count formatter: M at/above 1e6, k at/above 1e3, raw below.
177
- * 5,472,700 → "5.5mil", 24,100 → "24.1k", 142 → "142". */
178
- function fmtTokens(x: number): string {
179
- return x >= 1_000_000
180
- ? `${(x / 1_000_000).toFixed(1)}mil`
181
- : x >= 1000
182
- ? `${(x / 1000).toFixed(1)}k`
183
- : `${Math.round(x)}`;
184
- }
185
-
186
- /** Retro gradient bar — `w` cells shaded by fill position (green→amber→red).
187
- * Used for CONTEXT fill where low=green (room) and high=red (near the limit). */
188
- function ramp(pct: number, w = 12): string {
189
- const cells = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"];
190
- const scaled = Math.max(0, Math.min(w, pct * w));
191
- const full = Math.floor(scaled);
192
- const frac = scaled - full;
193
- const fracCell = frac > 0 ? cells[Math.round(frac * (cells.length - 1))] : "";
194
- let out = "";
195
- for (let i = 0; i < full; i++)
196
- out += (i / w < 0.6 ? C.green : i / w < 0.85 ? C.amber : C.red) + "█";
197
- if (fracCell)
198
- out +=
199
- (full / w < 0.6 ? C.green : full / w < 0.85 ? C.amber : C.red) + fracCell;
200
- out +=
201
- C.dim + "░".repeat(Math.max(0, w - full - (fracCell ? 1 : 0))) + C.reset;
202
- return out;
203
- }
204
-
205
- /** Human "time since" string from a millisecond delta (or null → "never"). */
206
- function sinceCompactStr(ms: number | null): string {
207
- if (ms == null) return "never";
208
- const s = Math.floor(ms / 1000);
209
- if (s < 60) return `${s}s ago`;
210
- const m = Math.floor(s / 60);
211
- if (m < 60) return `${m}m ago`;
212
- const h = Math.floor(m / 60);
213
- if (h < 24) return `${h}h ago`;
214
- return `${Math.floor(h / 24)}d ago`;
215
- }
216
-
217
- /** Ticker ring-buffer entry (recall/activity history for the widget footer). */
218
- export interface TickerEntry {
219
- text: string;
220
- at: number;
221
- }
222
-
223
- /** Immutable snapshot of everything the above-editor widget needs to render.
224
- * Computed once per `snapshot()` (event-driven) and read by `buildWidgetLines`
225
- * on every TUI render frame, so frame rendering stays allocation-cheap and the
226
- * panel auto-fits whatever width pi passes to the setWidget factory. */
227
- export interface WidgetData {
228
- version: string;
229
- tierLabel: string;
230
- triggerLabel: string;
231
- pctStr: string;
232
- tokStr: string;
233
- maxStr: string;
234
- ctxPct: number;
235
- chk: number;
236
- agentStr: string;
237
- turnStr: string;
238
- dedupStr: string;
239
- sessIn: number;
240
- sessKept: number;
241
- sTxt: string;
242
- repoIn: number;
243
- repoKept: number;
244
- rTxt: string;
245
- repoChk: number;
246
- repoSess: number;
247
- modelStr: string;
248
- sinceCompact: number | null;
249
- embedderName: string;
250
- compStr: string;
251
- driftStatus: "ok" | "warn";
252
- agentsActive: boolean;
253
- fresh: boolean;
254
- ticker: TickerEntry[];
255
- lastWhy: string | undefined;
256
- tierTrace: string | undefined;
257
- pulsing: boolean;
258
- // ── S31: game-mode theming + display modes + level + MEGA CACHE flare ──
259
- /** Game mode on (shows level + MEGA CACHE flare; hides them when off). */
260
- gameMode?: boolean;
261
- /** Theme id (src/config/themes). Drives the panel bg + accent/mega ANSI. */
262
- theme?: string;
263
- /** TUI display mode: 'full' (default) = the full stats panel; 'minimal' = a
264
- * one-line `LVL n | cache NN%` view flanked by panel bars. */
265
- tuiMode?: "full" | "minimal";
266
- /** Player level (game-mode). Stub = 1 until S33 wires the real scoring. */
267
- level?: number;
268
- /** Cache hit rate as a percent (0..100+, may exceed 100 → MEGA CACHE). */
269
- cachePct?: number;
270
- /** MEGA CACHE flare armed (fires at cachePct >= 100 + gameMode on). Adds the
271
- * ANSI MEGA CACHE banner + the oopsie gag to the header. */
272
- megaCacheFlare?: boolean;
273
- /** The peak cache % that armed the flare (for the oopsie toast text). */
274
- megaCacheFlarePct?: number;
275
- levelUpFlare?: boolean;
276
- /** S35: achievement-unlock flare -- renders a one-line toast for one cycle. */
277
- achievementFlare?: boolean;
278
- achievementFlareTitles?: string[];
279
- /** v0.8.3: ambient animated border effect (null when idle/expired). The
280
- * widget computes the per-frame phase from startedAt vs Date.now() and
281
- * renders a pulse/flash on the panel borders; '' once the window elapses. */
282
- activeEffect?: {
283
- type: "pulse" | "flash";
284
- role: "accent" | "mega" | "red";
285
- startedAt: number;
286
- durationMs: number;
287
- } | null;
288
- }
14
+ // Re-export the ANSI palette + layout/effect helpers and the interfaces so the
15
+ // barrel (`extensions/mega-runtime.ts` does `export * from "./widget.js"`) and
16
+ // every direct consumer keep resolving the same named exports.
17
+ export {
18
+ C,
19
+ PULSE,
20
+ DEFAULT_PANEL_BG,
21
+ EFFECT_BASE,
22
+ panelBgFor,
23
+ themeAnsi,
24
+ sgrReset,
25
+ wrapLine,
26
+ panelLine,
27
+ panelBar,
28
+ effectBorderSgr,
29
+ effectBar,
30
+ fmtTokens,
31
+ ramp,
32
+ sinceCompactStr,
33
+ } from "./widget-ansi.js";
34
+ export type { TickerEntry, WidgetData } from "./widget-types.js";
35
+
36
+ import { C, PULSE, DEFAULT_PANEL_BG, panelBgFor, themeAnsi, sgrReset, wrapLine, panelLine, panelBar, effectBorderSgr, effectBar, fmtTokens, ramp, sinceCompactStr } from "./widget-ansi.js";
37
+ import type { WidgetData } from "./widget-types.js";
289
38
 
290
39
  // ── buildWidgetLines ───────────────────────────────────────────────────────
291
- // Kept as a free function (not a MegaRuntime method) so state.ts stays
40
+ // Kept as a free function (not a MegaRuntime method) so runtime.ts stays
292
41
  // focused on state management. It reads the WidgetData snapshot + the live
293
42
  // activeAgents counter (passed in) and returns the panel lines.
294
43
 
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.8.22",
3
+ "version": "0.8.24",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
- "license": "BSD-2-Clause",
6
+ "license": "BSD-3-Clause",
7
7
  "author": "TheArchitectit",
8
8
  "homepage": "https://github.com/TheArchitectit/pi-mega-compact",
9
9
  "repository": {