@gonrocca/zero-pi 0.1.29 → 0.1.30

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 CHANGED
@@ -59,7 +59,7 @@ into `/forge` for you.
59
59
 
60
60
  | Feature | What it does |
61
61
  | ------- | ------------ |
62
- | **`/zero-models`** | Pick the model + provider for each SDD phase — interactive or direct. |
62
+ | **`/zero-models`** | Pick the model + provider for each SDD phase — a boxed-window picker, or set one directly. |
63
63
  | **Autotune** | Learns which model fits each phase from your run history and re-tunes itself. |
64
64
  | **`/zero-sync`** | Folds each run's spec delta into a canonical, project-wide spec store. |
65
65
  | **Run memory** | Every run recalls and saves traces to Cortex, so runs learn from each other. |
@@ -19,8 +19,28 @@ import { readFileSync, writeFileSync } from "node:fs";
19
19
  import { homedir } from "node:os";
20
20
  import { join } from "node:path";
21
21
 
22
+ // `@earendil-works/pi-tui` is provided by the pi runtime as an ambient bare
23
+ // specifier — it is NOT a `package.json` dependency. It is loaded lazily, via
24
+ // a dynamic `import()` inside the no-arg handler branch, NOT a top-level value
25
+ // import: a static `import { Box } from "@earendil-works/pi-tui"` would be
26
+ // evaluated whenever any consumer imports this module — including
27
+ // `zero-models.test.ts`, which imports the deterministic helpers — and would
28
+ // crash `node --test` with `ERR_MODULE_NOT_FOUND`. `import type` below is
29
+ // fully erased by `--experimental-strip-types`, so it never triggers
30
+ // resolution. The runtime classes are reached only from inside pi.
31
+ import type { Component } from "@earendil-works/pi-tui";
32
+
22
33
  import { readAutotuneMode, type AutotuneMode } from "./autotune.ts";
23
34
  import type { AutotunePending } from "./autotune-extension.ts";
35
+ import {
36
+ back,
37
+ createPickerState,
38
+ enter,
39
+ navigate,
40
+ submitText,
41
+ type EnterResult,
42
+ type PickerState,
43
+ } from "./zero-models-picker.ts";
24
44
 
25
45
  /** The SDD phases, in pipeline order. */
26
46
  export const PHASES = ["explore", "plan", "build", "veredicto"] as const;
@@ -181,11 +201,41 @@ export function groupByProvider(models: readonly PiModel[]): Map<string, string[
181
201
  return map;
182
202
  }
183
203
 
204
+ /** The pi-TUI host handed to a `ctx.ui.custom()` factory — only the one
205
+ * method the picker shell uses. */
206
+ interface PiTui {
207
+ requestRender(): void;
208
+ }
209
+ /** A pi-TUI component that groups children vertically and renders a frame. */
210
+ interface PiBox extends Component {
211
+ addChild(child: Component): void;
212
+ }
213
+ /** The slice of `@earendil-works/pi-tui` the boxed picker constructs at
214
+ * runtime — `Box`/`Text`/`Spacer` constructors, captured from the lazy
215
+ * dynamic `import()` so this module never statically resolves the specifier. */
216
+ interface PiTuiModule {
217
+ Box: new (paddingX?: number, paddingY?: number) => PiBox;
218
+ Text: new (content: string, paddingX?: number, paddingY?: number) => Component;
219
+ Spacer: new (lines: number) => Component;
220
+ }
221
+ /** A pi theme — only the foreground-color helper the picker uses. */
222
+ interface PiTheme {
223
+ fg(color: string, text: string): string;
224
+ }
225
+ /** The factory `ctx.ui.custom()` invokes to build the boxed component. */
226
+ type PiCustomFactory<T> = (
227
+ tui: PiTui,
228
+ theme: PiTheme,
229
+ keybindings: unknown,
230
+ done: (result: T) => void,
231
+ ) => Component;
232
+
184
233
  /** The slice of pi's extension API this command uses. */
185
234
  interface PiUI {
186
235
  select(prompt: string, options: string[]): Promise<string | undefined>;
187
236
  input(prompt: string, placeholder?: string): Promise<string | undefined>;
188
237
  notify(message: string, type?: "info" | "warning" | "error"): void;
238
+ custom<T>(factory: PiCustomFactory<T>): Promise<T>;
189
239
  }
190
240
  /** pi's model registry — the source of every provider's model list. */
191
241
  interface PiModelRegistry {
@@ -206,10 +256,6 @@ interface PiExtensionAPI {
206
256
  ): void;
207
257
  }
208
258
 
209
- const SAVE_AND_EXIT = "— guardar y salir —";
210
- const CUSTOM_MODEL = "— otro modelo (escribir) —";
211
- const CUSTOM_PROVIDER = "— otro provider (escribir) —";
212
-
213
259
  /**
214
260
  * Group models by provider for the picker.
215
261
  *
@@ -249,6 +295,192 @@ function resolveProvider(
249
295
  return undefined;
250
296
  }
251
297
 
298
+ /** The boxed-panel title row. */
299
+ const PICKER_TITLE = "zero · modelos SDD";
300
+ /** The dim help line shown at the foot of the boxed panel. */
301
+ const PICKER_HELP = "↑↓ navegar · enter elegir · esc volver";
302
+
303
+ /** ANSI arrow-key escape sequences. */
304
+ const KEY_UP = "\x1b[A";
305
+ const KEY_DOWN = "\x1b[B";
306
+ const KEY_ESC = "\x1b";
307
+ /** Enter — CR or LF, depending on the terminal. */
308
+ const KEY_ENTER = new Set(["\r", "\n", "\r\n"]);
309
+ /** Backspace — DEL or BS. */
310
+ const KEY_BACKSPACE = new Set(["\x7f", "\x08"]);
311
+
312
+ /**
313
+ * Clamp a rendered line to `width` columns so it never overflows the box
314
+ * frame (tui.md "Line Width" is a hard rule). A plain slice is enough here —
315
+ * the picker emits no ANSI inside its row strings except whole-line theming,
316
+ * and `theme.fg` is applied *after* truncation by the caller where it matters.
317
+ */
318
+ function clampLine(line: string, width: number): string {
319
+ if (width <= 0) return "";
320
+ return line.length > width ? line.slice(0, width) : line;
321
+ }
322
+
323
+ /**
324
+ * Build the inline pi-TUI component for the no-arg picker.
325
+ *
326
+ * The component owns no navigation logic — it holds one mutable `PickerState`,
327
+ * forwards keystrokes to the pure transition functions of
328
+ * `zero-models-picker.ts`, and re-renders. A `save`/`quit` `EnterResult` ends
329
+ * the component via `done(result)`.
330
+ *
331
+ * Custom typed provider/model values use an inline character buffer handled
332
+ * directly in `handleInput` (the design's documented fallback for the embedded
333
+ * `Input`): pi-tui's `Input` is not shipped with type definitions in this pi
334
+ * build and an embedded-input + `Focusable` wiring is the design's named
335
+ * highest-risk path — the inline buffer is self-contained, needs no ambient
336
+ * class beyond `Box`/`Text`/`Spacer`, and keeps the pure module's `submitText`
337
+ * contract untouched.
338
+ *
339
+ * The whole `handleInput` body is wrapped in a `try/catch` that closes the
340
+ * component cleanly via `done({ type: "quit" })` on any error (Req 9).
341
+ */
342
+ function createPickerComponent(
343
+ initial: PickerState,
344
+ pitui: PiTuiModule,
345
+ theme: PiTheme,
346
+ tui: PiTui,
347
+ done: (result: EnterResult) => void,
348
+ ): Component {
349
+ const { Box, Text, Spacer } = pitui;
350
+ // The single mutable state reference; reassigned from the pure functions.
351
+ let state = initial;
352
+ // Inline text buffer — non-null only while `state.textPrompt` is open.
353
+ let buffer: string | null = null;
354
+
355
+ /** Render the boxed panel for the current state. */
356
+ function render(width: number): string[] {
357
+ const box = new Box(1, 1);
358
+ const inner = Math.max(1, width - 4); // account for the box's paddingX
359
+
360
+ box.addChild(new Text(clampLine(PICKER_TITLE, inner), 0, 0));
361
+ box.addChild(new Spacer(1));
362
+
363
+ if (state.textPrompt) {
364
+ // Inline text-entry mode: show the prompt label and the typed buffer.
365
+ box.addChild(
366
+ new Text(clampLine(state.textPrompt.label, inner), 0, 0),
367
+ );
368
+ const typed = `> ${buffer ?? ""}`;
369
+ box.addChild(
370
+ new Text(theme.fg("accent", clampLine(typed, inner)), 0, 0),
371
+ );
372
+ box.addChild(new Spacer(1));
373
+ box.addChild(
374
+ new Text(
375
+ theme.fg("dim", clampLine("enter confirmar · esc volver", inner)),
376
+ 0,
377
+ 0,
378
+ ),
379
+ );
380
+ return box.render(width);
381
+ }
382
+
383
+ state.entries.forEach((entry, index) => {
384
+ if (index === state.cursor) {
385
+ const row = clampLine(`> ${entry.label}`, inner);
386
+ box.addChild(new Text(theme.fg("accent", row), 0, 0));
387
+ } else {
388
+ const row = clampLine(` ${entry.label}`, inner);
389
+ box.addChild(new Text(theme.fg("dim", row), 0, 0));
390
+ }
391
+ });
392
+
393
+ box.addChild(new Spacer(1));
394
+ box.addChild(
395
+ new Text(theme.fg("dim", clampLine(PICKER_HELP, inner)), 0, 0),
396
+ );
397
+ return box.render(width);
398
+ }
399
+
400
+ /** Apply an `EnterResult` — re-render on `state`, close on `save`/`quit`. */
401
+ function applyResult(result: EnterResult): void {
402
+ if (result.type === "state") {
403
+ state = result.state;
404
+ tui.requestRender();
405
+ } else {
406
+ done(result);
407
+ }
408
+ }
409
+
410
+ /** Route a keystroke while the inline text buffer is open. */
411
+ function handleTextInput(data: string): void {
412
+ if (data === KEY_ESC) {
413
+ // Esc abandons the typed value and returns to the current list screen
414
+ // unchanged. `submitText` with an empty string is exactly that no-op:
415
+ // it clears `textPrompt` and rebuilds the list without committing.
416
+ state = submitText(state, "");
417
+ buffer = null;
418
+ tui.requestRender();
419
+ return;
420
+ }
421
+ if (KEY_ENTER.has(data)) {
422
+ state = submitText(state, buffer ?? "");
423
+ buffer = null;
424
+ tui.requestRender();
425
+ return;
426
+ }
427
+ if (KEY_BACKSPACE.has(data)) {
428
+ buffer = (buffer ?? "").slice(0, -1);
429
+ tui.requestRender();
430
+ return;
431
+ }
432
+ // Append printable characters only (skip control sequences).
433
+ if (data.length >= 1 && data.charCodeAt(0) >= 32 && !data.startsWith("\x1b")) {
434
+ buffer = (buffer ?? "") + data;
435
+ tui.requestRender();
436
+ }
437
+ }
438
+
439
+ /** Receive a keystroke; never throws out — a failure closes the picker. */
440
+ function handleInput(data: string): void {
441
+ try {
442
+ // Inline text-entry mode takes input until it submits or escapes.
443
+ if (state.textPrompt) {
444
+ handleTextInput(data);
445
+ return;
446
+ }
447
+
448
+ if (data === KEY_UP) {
449
+ state = navigate(state, -1);
450
+ tui.requestRender();
451
+ return;
452
+ }
453
+ if (data === KEY_DOWN) {
454
+ state = navigate(state, 1);
455
+ tui.requestRender();
456
+ return;
457
+ }
458
+ if (KEY_ENTER.has(data)) {
459
+ const result = enter(state);
460
+ // `enter` on a custom-* row opens `textPrompt`; arm the buffer.
461
+ if (result.type === "state" && result.state.textPrompt) buffer = "";
462
+ applyResult(result);
463
+ return;
464
+ }
465
+ if (data === KEY_ESC) {
466
+ applyResult(back(state));
467
+ return;
468
+ }
469
+ } catch {
470
+ // A render/transition bug must never wedge the pi session — close.
471
+ done({ type: "quit" });
472
+ }
473
+ }
474
+
475
+ return {
476
+ render,
477
+ invalidate(): void {
478
+ /* stateless render — nothing cached to clear */
479
+ },
480
+ handleInput,
481
+ };
482
+ }
483
+
252
484
  /**
253
485
  * The pi extension entry point — registers the `/zero-models` command.
254
486
  */
@@ -315,115 +547,68 @@ export default function register(pi?: PiExtensionAPI): void {
315
547
  return;
316
548
  }
317
549
 
318
- // Interactive form: pick a phase, a provider, a model until saved.
319
- let changed = false;
320
- let autotuneMode = readAutotuneMode(data);
321
- let autotuneChanged = false;
322
- let pending = readAutotunePending(data);
323
- let pendingApplied = false;
324
- for (;;) {
325
- const applyEntry =
326
- pending.length > 0
327
- ? `★ aplicar sugerencia: ${pending
328
- .map((p) => `${p.phase} → ${p.to}`)
329
- .join(", ")}`
330
- : null;
331
- const autotuneEntry = `autotune → ${autotuneMode}`;
332
-
333
- const phasePick = await ctx.ui.select("zero · modelos SDD elegí una fase", [
334
- ...(applyEntry ? [applyEntry] : []),
335
- ...PHASES.map(
336
- (p) => `${p} → ${providers[p] ? `${providers[p]}/` : ""}${models[p]}`,
337
- ),
338
- autotuneEntry,
339
- SAVE_AND_EXIT,
340
- ]);
341
- if (!phasePick || phasePick === SAVE_AND_EXIT) break;
342
-
343
- // Apply the pending autotune suggestion.
344
- if (applyEntry && phasePick === applyEntry) {
345
- for (const adj of pending) models[adj.phase] = adj.to;
346
- changed = true;
347
- pendingApplied = true;
348
- pending = [];
349
- continue;
350
- }
351
-
352
- // Change the autotune mode.
353
- if (phasePick === autotuneEntry) {
354
- const modePick = await ctx.ui.select(
355
- "Modo de autotune",
356
- AUTOTUNE_MODES.map((m) => formatAutotune(m)),
357
- );
358
- if (!modePick) continue;
359
- const picked = parseAutotuneArg(modePick.split(/\s/)[0]);
360
- if (picked && picked !== autotuneMode) {
361
- autotuneMode = picked;
362
- autotuneChanged = true;
363
- }
364
- continue;
365
- }
366
-
367
- const phase = phasePick.split(/\s/)[0];
368
- if (!isPhase(phase)) break;
369
-
370
- // Pick a provider — from the registry, or typed when unknown.
371
- let provider = providers[phase];
372
- let modelChoices = FALLBACK_MODELS;
373
- if (groups.size > 0) {
374
- const providerPick = await ctx.ui.select(`Provider para «${phase}»`, [
375
- ...[...groups.keys()].sort(),
376
- CUSTOM_PROVIDER,
377
- ]);
378
- if (!providerPick) continue;
379
- if (providerPick === CUSTOM_PROVIDER) {
380
- const typed = await ctx.ui.input(
381
- `Provider para «${phase}»`,
382
- providers[phase] || "",
383
- );
384
- if (!typed || typed.trim() === "") continue;
385
- provider = typed.trim();
386
- modelChoices = groups.get(provider) ?? [];
387
- } else {
388
- provider = providerPick;
389
- modelChoices = groups.get(providerPick) ?? [];
390
- }
391
- }
392
-
393
- // Pick a model within that provider — or type one.
394
- const label = provider ? `Modelo para «${phase}» (${provider})` : `Modelo para «${phase}»`;
395
- const modelPick = await ctx.ui.select(label, [...modelChoices, CUSTOM_MODEL]);
396
- if (!modelPick) continue;
550
+ // Interactive form: open the boxed picker, then persist on save.
551
+ const autotuneMode = readAutotuneMode(data);
552
+ const pending = readAutotunePending(data);
553
+
554
+ const initialState = createPickerState({
555
+ models,
556
+ providers,
557
+ autotuneMode,
558
+ pending,
559
+ groups,
560
+ fallbackModels: FALLBACK_MODELS,
561
+ });
562
+
563
+ // Load pi-tui lazily — the bare specifier resolves only inside pi.
564
+ // This `import()` lives in the handler (already inside the swallowing
565
+ // `try/catch`), so a resolution failure becomes an error notification
566
+ // and never escapes (Req 9).
567
+ const pitui = (await import(
568
+ "@earendil-works/pi-tui"
569
+ )) as unknown as PiTuiModule;
570
+
571
+ const result = await ctx.ui.custom<EnterResult>((tui, theme, _kb, done) =>
572
+ createPickerComponent(initialState, pitui, theme, tui, done),
573
+ );
397
574
 
398
- let model = modelPick;
399
- if (modelPick === CUSTOM_MODEL) {
400
- const typed = await ctx.ui.input(label, models[phase]);
401
- if (!typed || typed.trim() === "") continue;
402
- model = typed.trim();
403
- }
404
- models[phase] = model;
405
- providers[phase] = provider || resolveProvider(ctx.modelRegistry, model) || "";
406
- changed = true;
575
+ if (result.type !== "save") {
576
+ // Esc / quit (or a contained UI failure): write nothing, leaving
577
+ // `zero.json` byte-for-byte unchanged, and report the leave-as-is
578
+ // state the existing "sin cambios" notification text.
579
+ ctx.ui.notify(
580
+ `zero · modelos SDD (sin cambios):\n${formatPhases(models, providers)}\n` +
581
+ ` autotune ${autotuneMode}`,
582
+ "info",
583
+ );
584
+ return;
407
585
  }
408
586
 
409
- if (changed || autotuneChanged) {
587
+ // Save: pull the accumulated edits off the final picker state.
588
+ const edits = result.state.edits;
589
+ if (edits.changed || edits.autotuneChanged) {
410
590
  // Build the patch, preserving every other key via the spread. When
411
591
  // the pending suggestion was applied, clear the `autotunePending` key.
412
- const patch: Record<string, unknown> = { models, providers };
413
- if (autotuneChanged) patch.autotune = autotuneMode;
592
+ const patch: Record<string, unknown> = {
593
+ models: edits.models,
594
+ providers: edits.providers,
595
+ };
596
+ if (edits.autotuneChanged) patch.autotune = edits.autotuneMode;
414
597
 
415
598
  const merged = { ...data, ...patch };
416
- if (pendingApplied) delete merged.autotunePending;
599
+ if (edits.pendingApplied) delete merged.autotunePending;
417
600
  writeFileSync(zeroJsonPath(), `${JSON.stringify(merged, null, 2)}\n`, "utf8");
418
601
 
419
- const summary = [`zero · modelos SDD guardados:\n${formatPhases(models, providers)}`];
420
- summary.push(` autotune ${autotuneMode}`);
421
- if (pendingApplied) summary.push("sugerencia aplicada");
602
+ const summary = [
603
+ `zero · modelos SDD guardados:\n${formatPhases(edits.models, edits.providers)}`,
604
+ ];
605
+ summary.push(` autotune ${edits.autotuneMode}`);
606
+ if (edits.pendingApplied) summary.push("sugerencia aplicada");
422
607
  ctx.ui.notify(summary.join("\n"), "info");
423
608
  } else {
424
609
  ctx.ui.notify(
425
- `zero · modelos SDD (sin cambios):\n${formatPhases(models, providers)}\n` +
426
- ` autotune ${autotuneMode}`,
610
+ `zero · modelos SDD (sin cambios):\n${formatPhases(edits.models, edits.providers)}\n` +
611
+ ` autotune ${edits.autotuneMode}`,
427
612
  "info",
428
613
  );
429
614
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gonrocca/zero-pi",
3
- "version": "0.1.29",
3
+ "version": "0.1.30",
4
4
  "description": "zero-pi — an installable layer for pi (pi.dev): the zero spec-driven development workflow, per-phase model autotune, and skill auto-learning. Adds capability to pi without modifying pi.",
5
5
  "type": "module",
6
6
  "keywords": [