@xynogen/pix-runtime 0.5.2 → 0.5.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xynogen/pix-runtime",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "description": "Pix shared runtime — versioned pix.json config, atomic persistence, typed change events",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -44,8 +44,14 @@ function formatTokens(tokens: number): string {
44
44
 
45
45
  /** Parse a compact token label ("1M", "150k") back to an absolute count. */
46
46
  function parseTokens(label: string): number {
47
- const n = Number.parseFloat(label);
48
- return /m$/i.test(label) ? n * 1_000_000 : n * 1000;
47
+ const raw = label.trim();
48
+ const m = raw.match(/^([0-9]*\.?[0-9]+)\s*([km])?$/i);
49
+ if (!m) return Number.NaN;
50
+ const numStr = m[1] ?? "";
51
+ const n = Number.parseFloat(numStr);
52
+ if (!Number.isFinite(n)) return Number.NaN;
53
+ const suf = (m[2] ?? "").toLowerCase();
54
+ return suf === "m" ? Math.round(n * 1_000_000) : Math.round(n * 1000);
49
55
  }
50
56
 
51
57
  const SETTINGS: SettingRow<unknown>[] = [
@@ -93,7 +99,8 @@ const SETTINGS: SettingRow<unknown>[] = [
93
99
  section: "Compaction",
94
100
  label: "Trigger (% ctx)",
95
101
  handle: compactionSection,
96
- values: ["0", "5", "10", "15", "20", "25", "30", "40", "50", "60", "70", "80", "90"],
102
+ // 0–100 in 5% steps.
103
+ values: Array.from({ length: 21 }, (_, i) => String(i * 5)),
97
104
  read: (v) => String(v.triggerPercent),
98
105
  patch: (value) => ({ triggerPercent: Number(value) }),
99
106
  }),
@@ -135,6 +142,8 @@ export function registerPixCommand(pi: ExtensionAPI, runtime: PixRuntime): void
135
142
  pi.registerCommand("pix", {
136
143
  description: "pix: open shared settings (edit pix.json)",
137
144
  handler: async (_args: string, ctx: ExtensionCommandContext) => {
145
+ // Re-parse pix.json so section parsers remain the single validation source.
146
+ await runtime.reload({ origin: "command", source: "pix" });
138
147
  const ui = ctx.ui as unknown as {
139
148
  custom?: (f: unknown, opts?: unknown) => Promise<unknown>;
140
149
  notify(m: string, t?: "info" | "warning" | "error"): void;
@@ -169,11 +178,29 @@ export function registerPixCommand(pi: ExtensionAPI, runtime: PixRuntime): void
169
178
  const cycle = (direction: -1 | 1) => {
170
179
  const row = SETTINGS[selected];
171
180
  if (!row) return;
172
- const cur = row.values.indexOf(row.read(runtime.get(row.handle)));
173
- const next = (cur + direction + row.values.length) % row.values.length;
174
- const val = row.values[next];
175
- if (val === undefined) return;
176
- void runtime.update(row.handle, row.patch(val), { origin: "command", source: "pix" });
181
+ // Functional updater: the runtime queue serializes writes, and the
182
+ // callback sees the latest committed value — so rapid presses each
183
+ // advance exactly one step instead of collapsing on a stale snapshot.
184
+ const step = (current: unknown): unknown => {
185
+ const curVal = row.read(current);
186
+ let cur = row.values.indexOf(curVal);
187
+ // ponytail: unsupported custom values snap to section default on first change.
188
+ if (cur === -1) {
189
+ const def = row.read(row.handle.defaults);
190
+ const defIdx = row.values.indexOf(def);
191
+ cur = defIdx !== -1 ? defIdx - direction : -1;
192
+ }
193
+ const next = (cur + direction + row.values.length) % row.values.length;
194
+ const val = row.values[next];
195
+ if (val === undefined) return current;
196
+ return { ...(current as object), ...(row.patch(val) as object) };
197
+ };
198
+ // Re-render AFTER the commit lands; the synchronous render in
199
+ // handleInput fires before the queued write and shows a stale value.
200
+ void runtime
201
+ .update(row.handle, step, { origin: "command", source: "pix" })
202
+ .then(() => tui.requestRender())
203
+ .catch(() => ui.notify(`pix: failed to update ${row.label}`, "error"));
177
204
  };
178
205
  const move = (direction: -1 | 1) => {
179
206
  selected = (selected + direction + SETTINGS.length) % SETTINGS.length;
@@ -187,7 +214,8 @@ export function registerPixCommand(pi: ExtensionAPI, runtime: PixRuntime): void
187
214
  const settingBodyLines: number[] = [];
188
215
  let lastSection = "";
189
216
  for (let i = 0; i < SETTINGS.length; i++) {
190
- const row = SETTINGS[i]!;
217
+ const row = SETTINGS[i];
218
+ if (!row) continue;
191
219
  if (row.section !== lastSection) {
192
220
  if (lastSection) body.push("");
193
221
  body.push(theme.fg("dim", ` ${row.section}`));
@@ -241,20 +269,15 @@ export function registerPixCommand(pi: ExtensionAPI, runtime: PixRuntime): void
241
269
  // matchesKey handles both legacy bytes and Kitty CSI-u encodings
242
270
  // for letters and special keys alike — raw string compares like
243
271
  // `data === "k"` silently fail under the Kitty keyboard protocol.
244
- if (matchesKey(data, "k") || matchesKey(data, "up")) move(-1);
245
- else if (matchesKey(data, "j") || matchesKey(data, "down")) move(1);
246
- else if (matchesKey(data, "h") || matchesKey(data, "left")) cycle(-1);
247
- else if (
248
- matchesKey(data, "l") ||
249
- matchesKey(data, "right") ||
250
- matchesKey(data, "space") ||
251
- matchesKey(data, "enter")
252
- )
253
- cycle(1);
254
- else if (matchesKey(data, "escape") || matchesKey(data, "q")) {
272
+ if (kb.matches(data, "tui.select.cancel")) {
255
273
  done(null);
256
274
  return;
257
- } else return;
275
+ }
276
+ if (kb.matches(data, "tui.select.up")) move(-1);
277
+ else if (kb.matches(data, "tui.select.down")) move(1);
278
+ else if (matchesKey(data, Key.left)) cycle(-1);
279
+ else if (matchesKey(data, Key.right)) cycle(1);
280
+ else return;
258
281
  tui.requestRender();
259
282
  },
260
283
  };
@@ -357,12 +380,13 @@ function frameRows(
357
380
  const dashes = "─".repeat(width - 2);
358
381
  const SENTINEL = "\x00";
359
382
  const bgOpen = bg(SENTINEL).split(SENTINEL)[0] ?? "";
360
- const reassert = (s: string): string =>
361
- bgOpen
362
- ? s.replace(/\x1b\[([0-9;]*)m/g, (seq, p: string) =>
363
- p === "0" || p.split(";").includes("49") ? `${seq}${bgOpen}` : seq,
364
- )
365
- : s;
383
+ const reassert = (s: string): string => {
384
+ if (!bgOpen) return s;
385
+ return s.replace(/\x1b\[([0-9;]*)m/g, (seq, p: string) => {
386
+ if (p === "0" || p.split(";").includes("49")) return `${seq}${bgOpen}`;
387
+ return seq;
388
+ });
389
+ };
366
390
  const row = (content: string): string => {
367
391
  const fitted = truncateToWidth(content, inner, "…");
368
392
  const padded = fitted + " ".repeat(Math.max(0, inner - visibleWidth(fitted)));
package/src/runtime.ts CHANGED
@@ -347,12 +347,24 @@ class RuntimeImpl implements PixRuntime {
347
347
  const values = new Map<string, unknown>();
348
348
  for (const s of this.registry.all()) values.set(s.key, s.parse(base[s.key], ctx));
349
349
 
350
- const currentValue = values.get(section.key) as Readonly<T>;
351
- const nextValue =
350
+ // Guard against a version-skewed second runtime copy whose registry
351
+ // lacks this section (e.g. an old npm copy handling a new handle). The
352
+ // functional updater would otherwise crash the whole process on
353
+ // `undefined`. Fall back to the handle's own parse of the raw doc.
354
+ const currentValue = (
355
+ values.has(section.key)
356
+ ? values.get(section.key)
357
+ : section.__section.parse(base[section.key], ctx)
358
+ ) as Readonly<T>;
359
+ const mergedValue =
352
360
  typeof updater === "function"
353
361
  ? (updater as (c: Readonly<T>) => T)(currentValue)
354
362
  : deepMerge(currentValue as T, updater);
355
363
 
364
+ // Re-validate through the section's own parse so a bad patch (NaN,
365
+ // Infinity, wrong type) can never enter the live snapshot.
366
+ const nextValue = section.__section.parse(mergedValue, ctx) as T;
367
+
356
368
  if (JSON.stringify(currentValue) === JSON.stringify(nextValue)) return undefined;
357
369
  values.set(section.key, nextValue);
358
370
 
@@ -31,17 +31,35 @@ function pctOr(v: unknown, fallback: number): number {
31
31
  /** Require a finite token floor of at least 25k. */
32
32
  function minimumTokensOr(v: unknown, fallback: number): number {
33
33
  if (typeof v !== "number" || !Number.isFinite(v)) return fallback;
34
+ // Strings from older/hand-edited pix.json (e.g. "150k") → parse before clamping.
34
35
  return Math.max(MINIMUM_TOKEN_FLOOR, Math.round(v));
35
36
  }
36
37
 
38
+ function parseTokenString(label: string): number | undefined {
39
+ const raw = label.trim();
40
+ if (!raw) return undefined;
41
+ const m = raw.match(/^([0-9]*\.?[0-9]+)\s*([km])?$/i);
42
+ if (!m) return undefined;
43
+ const numStr = m[1] ?? "";
44
+ const n = Number.parseFloat(numStr);
45
+ if (!Number.isFinite(n)) return undefined;
46
+ const suf = (m[2] ?? "").toLowerCase();
47
+ if (suf === "m") return Math.round(n * 1_000_000);
48
+ if (suf === "k") return Math.round(n * 1000);
49
+ return Math.round(n);
50
+ }
51
+
37
52
  export const compactionSection = defineSection<"compaction", CompactionConfig>({
38
53
  key: "compaction",
39
54
  defaults: DEFAULTS,
40
55
  parse(raw) {
41
56
  if (!isObj(raw)) return { ...DEFAULTS };
57
+ const rawMin = raw.minimumTokens;
58
+ const coercedMin =
59
+ typeof rawMin === "string" ? (parseTokenString(rawMin) ?? Number.NaN) : rawMin;
42
60
  return {
43
61
  triggerPercent: pctOr(raw.triggerPercent, DEFAULTS.triggerPercent),
44
- minimumTokens: minimumTokensOr(raw.minimumTokens, DEFAULTS.minimumTokens),
62
+ minimumTokens: minimumTokensOr(coercedMin, DEFAULTS.minimumTokens),
45
63
  };
46
64
  },
47
65
  });