harma-kit 0.1.0 → 0.2.1

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/src/tui.mjs ADDED
@@ -0,0 +1,345 @@
1
+ // Interactive selection (harma select). A pure state machine — reduce(state, key) —
2
+ // plus render(state) and a thin keyboard/terminal layer (runTui). No dependencies.
3
+ //
4
+ // Views: list → picks (a job's models, in order) → model → effort, and confirmQuit.
5
+ // The orchestrator row has one model: list → model → effort.
6
+ // Keys (list): ↑/↓ (k/j) move · enter open · a accept proposal · A accept all ·
7
+ // x clear row · s save · q quit
8
+ // Keys (picks): ↑/↓ move · enter change · + add · d remove · K/J (shift ↑/↓) move the
9
+ // model up/down · a proposal · esc back
10
+ import { emitKeypressEvents } from 'node:readline';
11
+ import { ORCHESTRATOR, MAX_PICKS, describe, describePick, samePick, sameChoice } from './roster.mjs';
12
+
13
+ export function initState({ rows, models, title = 'harma', subtitle = '' }) {
14
+ return { view: 'list', rows, models, title, subtitle, cursor: 0, pickCursor: 0, modelCursor: 0, effortCursor: 0, editIndex: 0, editModel: null, message: '', done: null };
15
+ }
16
+
17
+ const dirty = (s) => s.rows.some((r) => !sameChoice(r.choice, r.original));
18
+ const picksOf = (row) => (row.choice && !row.choice.none ? row.choice.picks ?? [] : []);
19
+
20
+ /** Options shown in the model view: "no model" first for task rows. */
21
+ export function modelList(s) {
22
+ const row = s.rows[s.cursor];
23
+ return row.single ? s.models : [{ none: true }, ...s.models];
24
+ }
25
+
26
+ const clamp = (n, len) => Math.max(0, Math.min(len - 1, n));
27
+ const sourceFor = (row, picks) => (row.proposal && sameChoice({ picks }, row.proposal) ? 'proposta' : 'utente');
28
+
29
+ /** Open the model list to replace pick `index` (or add one when index === picks.length). */
30
+ function openModel(s, next, index) {
31
+ const row = s.rows[s.cursor];
32
+ const picks = picksOf(row);
33
+ const list = modelList(s);
34
+ const target = picks[index]
35
+ ?? row.proposal?.picks.find((p) => !picks.some((q) => q.harness === p.harness && q.model === p.model));
36
+ let i = target ? list.findIndex((m) => !m.none && m.harness === target.harness && m.model === target.model) : -1;
37
+ // Otherwise the first model not already in the list.
38
+ if (i < 0) i = list.findIndex((m) => !m.none && !picks.some((q) => q.harness === m.harness && q.model === m.model));
39
+ return { ...next, view: 'model', editIndex: index, modelCursor: i >= 0 ? i : 0 };
40
+ }
41
+
42
+ function setPicks(s, row, picks, message) {
43
+ const choice = picks.length ? { picks, source: sourceFor(row, picks) } : null;
44
+ return setRow(s, s.cursor, choice, message);
45
+ }
46
+
47
+ export function reduce(s, key) {
48
+ const k = key === 'k' ? 'up' : key === 'j' ? 'down' : key === 'shift-up' ? 'K' : key === 'shift-down' ? 'J' : key;
49
+ const next = { ...s, message: '' };
50
+ const row = s.rows[s.cursor];
51
+
52
+ if (k === 'ctrl-c') return { ...next, done: 'cancel' };
53
+
54
+ if (s.view === 'confirmQuit') {
55
+ if (k === 's') return { ...next, done: 'save' };
56
+ if (k === 'q') return { ...next, done: 'cancel' };
57
+ return { ...next, view: 'list' };
58
+ }
59
+
60
+ if (s.view === 'list') {
61
+ switch (k) {
62
+ case 'up': return { ...next, cursor: clamp(s.cursor - 1, s.rows.length) };
63
+ case 'down': return { ...next, cursor: clamp(s.cursor + 1, s.rows.length) };
64
+ case 'return':
65
+ // A job with models opens its ordered list; otherwise go straight to the first model.
66
+ if (row.single || !picksOf(row).length) return openModel(s, next, 0);
67
+ return { ...next, view: 'picks', pickCursor: 0 };
68
+ case 'a':
69
+ if (!row.proposal) return { ...next, message: 'Nessuna proposta per questa riga: scegli tu con invio.' };
70
+ return setRow(next, s.cursor, { picks: [...row.proposal.picks], source: 'proposta' }, `Accettata la proposta per ${row.type}.`);
71
+ case 'A': {
72
+ let st = next;
73
+ let n = 0;
74
+ s.rows.forEach((r, i) => { if (r.proposal) { st = setRow(st, i, { picks: [...r.proposal.picks], source: 'proposta' }); n++; } });
75
+ return { ...st, message: `Accettate ${n} proposte. s per salvare.` };
76
+ }
77
+ case 'x':
78
+ if (row.single) return { ...next, message: 'L\'orchestratore non si può svuotare.' };
79
+ return setRow(next, s.cursor, null, `${row.type}: da decidere.`);
80
+ case 's': return { ...next, done: 'save' };
81
+ case 'q': case 'escape':
82
+ return dirty(s) ? { ...next, view: 'confirmQuit' } : { ...next, done: 'cancel' };
83
+ default: return next;
84
+ }
85
+ }
86
+
87
+ if (s.view === 'picks') {
88
+ const picks = picksOf(row);
89
+ const n = picks.length + 1; // the last line is "+ aggiungi"
90
+ const at = s.pickCursor;
91
+ switch (k) {
92
+ case 'up': return { ...next, pickCursor: clamp(at - 1, n) };
93
+ case 'down': return { ...next, pickCursor: clamp(at + 1, n) };
94
+ case 'escape': case 'q': return { ...next, view: 'list' };
95
+ case 'return':
96
+ if (at < picks.length) return openModel(s, next, at);
97
+ // fall through: the "+ aggiungi" line
98
+ case '+': case '=':
99
+ if (picks.length >= MAX_PICKS) return { ...next, message: `Al massimo ${MAX_PICKS} modelli per lavoro.` };
100
+ return openModel(s, next, picks.length);
101
+ case 'd': case 'x': case 'backspace': case 'delete': {
102
+ if (at >= picks.length) return next;
103
+ const left = picks.filter((_, i) => i !== at);
104
+ const st = setPicks(next, row, left, `Tolto ${describePick(picks[at])}.`);
105
+ return left.length ? { ...st, pickCursor: clamp(at, left.length + 1) } : { ...st, view: 'list' };
106
+ }
107
+ case 'K': case 'J': {
108
+ const to = k === 'K' ? at - 1 : at + 1;
109
+ if (at >= picks.length || to < 0 || to >= picks.length) return next;
110
+ const moved = [...picks];
111
+ [moved[at], moved[to]] = [moved[to], moved[at]];
112
+ return { ...setPicks(next, row, moved), pickCursor: to };
113
+ }
114
+ case 'a':
115
+ if (!row.proposal) return { ...next, message: 'Nessuna proposta per questo lavoro.' };
116
+ return { ...setRow(next, s.cursor, { picks: [...row.proposal.picks], source: 'proposta' }, 'Lista sostituita con la proposta.'), pickCursor: 0 };
117
+ default: return next;
118
+ }
119
+ }
120
+
121
+ if (s.view === 'model') {
122
+ const list = modelList(s);
123
+ const back = row.single || !picksOf(row).length ? 'list' : 'picks';
124
+ switch (k) {
125
+ case 'up': return { ...next, modelCursor: clamp(s.modelCursor - 1, list.length) };
126
+ case 'down': return { ...next, modelCursor: clamp(s.modelCursor + 1, list.length) };
127
+ case 'escape': case 'q': return { ...next, view: back };
128
+ case 'return': {
129
+ const m = list[s.modelCursor];
130
+ if (m.none) return { ...setRow(next, s.cursor, { none: true, source: 'utente' }, `${row.type}: nessun modello.`), view: 'list' };
131
+ const same = (p) => p && p.harness === m.harness && p.model === m.model;
132
+ const prefer = [picksOf(row)[s.editIndex], ...(row.proposal?.picks ?? [])].find(same)?.effort
133
+ ?? m.best?.effort ?? m.default_effort;
134
+ const i = m.efforts.findIndex((e) => e.effort === prefer);
135
+ return { ...next, view: 'effort', editModel: m, effortCursor: i >= 0 ? i : 0 };
136
+ }
137
+ default: return next;
138
+ }
139
+ }
140
+
141
+ if (s.view === 'effort') {
142
+ const efforts = s.editModel.efforts;
143
+ switch (k) {
144
+ case 'up': return { ...next, effortCursor: clamp(s.effortCursor - 1, efforts.length) };
145
+ case 'down': return { ...next, effortCursor: clamp(s.effortCursor + 1, efforts.length) };
146
+ case 'escape': case 'q': return { ...next, view: 'model' };
147
+ case 'return': {
148
+ const m = s.editModel;
149
+ const pick = { harness: m.harness, model: m.model, effort: efforts[s.effortCursor].effort };
150
+ if (row.single) {
151
+ return { ...setRow(next, s.cursor, { picks: [pick], source: 'utente' }, `${row.type}: ${describePick(pick)}.`), view: 'list', editModel: null };
152
+ }
153
+ const picks = picksOf(row);
154
+ const dup = picks.findIndex((p, i) => i !== s.editIndex && samePick(p, pick));
155
+ if (dup >= 0) return { ...next, view: 'picks', editModel: null, pickCursor: dup, message: `${describePick(pick)} è già nella lista (n.${dup + 1}).` };
156
+ const updated = [...picks];
157
+ updated[s.editIndex] = pick;
158
+ const verb = s.editIndex < picks.length ? 'Cambiato' : 'Aggiunto';
159
+ return { ...setPicks(next, row, updated, `${verb}: ${describePick(pick)} (n.${s.editIndex + 1}).`), view: 'picks', editModel: null, pickCursor: s.editIndex };
160
+ }
161
+ default: return next;
162
+ }
163
+ }
164
+ return next;
165
+ }
166
+
167
+ function setRow(s, i, choice, message) {
168
+ const rows = s.rows.map((r, j) => (j === i ? { ...r, choice } : r));
169
+ return { ...s, rows, message: message ?? s.message };
170
+ }
171
+
172
+ // ── rendering ──────────────────────────────────────────────────────────────
173
+ const ESC = '\x1b[';
174
+ const style = (on) => ({
175
+ bold: (t) => (on ? `${ESC}1m${t}${ESC}0m` : t),
176
+ dim: (t) => (on ? `${ESC}2m${t}${ESC}0m` : t),
177
+ inv: (t) => (on ? `${ESC}7m${t}${ESC}0m` : t),
178
+ green: (t) => (on ? `${ESC}32m${t}${ESC}0m` : t),
179
+ yellow: (t) => (on ? `${ESC}33m${t}${ESC}0m` : t),
180
+ });
181
+
182
+ const fit = (t, w) => (t.length > w ? `${t.slice(0, Math.max(0, w - 1))}…` : t.padEnd(w));
183
+ const num = (x, pre = '') => (x === null || x === undefined ? '?' : `${pre}${x}`);
184
+ const creditText = (m) => (m ? `crediti ${m.credit}${m.remaining !== null && m.remaining !== undefined ? ` (${m.remaining}%)` : ''}` : 'crediti ?');
185
+
186
+ export function render(s, { width = 100, color = true } = {}) {
187
+ const st = style(color);
188
+ const W = Math.max(40, width);
189
+ const narrow = W < 90;
190
+ const lines = [st.bold(s.title), ...(s.subtitle ? [st.dim(s.subtitle)] : []), ''];
191
+ const row = s.rows[s.cursor];
192
+
193
+ if (s.view === 'list' || s.view === 'confirmQuit') {
194
+ lines.push(st.dim(narrow
195
+ ? '↑↓ invio:apri a:accetta A:tutte x s:salva q:esci'
196
+ : '↑↓ sposta · invio apri (modelli ed effort) · a accetta proposta · A accetta tutte · x svuota · s salva · q esci'), '');
197
+ const cType = 16;
198
+ const cCol = narrow ? 0 : Math.min(40, Math.floor((W - cType - 4) / 2));
199
+ lines.push(st.dim(` ${fit('lavoro', cType)}${narrow ? '' : fit('proposta', cCol)}scelta (in ordine di preferenza)`));
200
+ s.rows.forEach((r, i) => {
201
+ const pp = r.proposal?.picks ?? [];
202
+ const prop = pp.length > 1 ? `${describePick(pp[0])} +${pp.length - 1}` : describe(r.proposal);
203
+ let ch = describe(r.choice);
204
+ if (r.choice && !r.choice.none && r.proposal && sameChoice(r.choice, r.proposal)) ch = st.green(`${ch} ${r.single ? 'attuale' : '✓ proposta'}`);
205
+ else if (r.choice && !r.choice.none) ch = st.yellow(`${ch} ${r.choice.source === 'proposta' ? '(proposta precedente)' : '(tua)'}`);
206
+ else if (r.choice?.none) ch = st.yellow(ch);
207
+ else ch = st.dim(ch);
208
+ const changed = !sameChoice(r.choice, r.original) ? '*' : ' ';
209
+ const line = `${fit(r.type, cType)}${narrow ? '' : `${fit(prop, cCol - 1)} `}`;
210
+ lines.push(i === s.cursor ? `${st.inv(`❯${changed}${line}`)}${ch}` : ` ${changed}${line}${ch}`);
211
+ });
212
+ lines.push('', st.dim(row.label));
213
+ if (row.proposal) lines.push(...wrap(`proposta: ${describe(row.proposal)}`, W));
214
+ if (row.proposal?.why) lines.push(...wrap(`motivi: ${row.proposal.why}`, W).map(st.dim));
215
+ if (!row.single) lines.push(...wrap('Invio apre la lista dei modelli del lavoro: puoi metterne più di uno, in ordine; al dispatch harma usa il primo con crediti utilizzabili.', W).map(st.dim));
216
+ if (s.view === 'confirmQuit') lines.push('', st.bold('Modifiche non salvate — s salva ed esci · q esci senza salvare · altro tasto torna'));
217
+ }
218
+
219
+ if (s.view === 'picks') {
220
+ const picks = picksOf(row);
221
+ lines.push(st.bold(`Modelli per ${row.type}, in ordine di preferenza`), st.dim(narrow
222
+ ? 'invio:cambia +:aggiungi d:togli K/J:sposta a:proposta esc'
223
+ : '↑↓ sposta · invio cambia · + aggiungi · d togli · K/J (shift ↑↓) sposta su/giù · a proposta · esc indietro'), '');
224
+ picks.forEach((p, i) => {
225
+ const m = s.models.find((x) => x.harness === p.harness && x.model === p.model);
226
+ const e = m?.efforts.find((x) => x.effort === p.effort);
227
+ const text = narrow
228
+ ? `${i + 1}. ${describePick(p)} ${m?.credit ?? '?'}`
229
+ : `${i + 1}. ${fit(describePick(p), 40)} indice ${fit(num(e?.index), 6)} ${fit(`costo/task ${num(e?.cost, '$')}`, 18)} ${creditText(m)}`;
230
+ lines.push(i === s.pickCursor ? st.inv(`❯ ${text}`) : ` ${text}`);
231
+ });
232
+ const add = picks.length >= MAX_PICKS ? st.dim(`(massimo ${MAX_PICKS} modelli)`) : '+ aggiungi un modello';
233
+ lines.push(s.pickCursor === picks.length ? st.inv(`❯ ${add}`) : ` ${add}`);
234
+ lines.push('', ...wrap('Al dispatch harma prende il primo della lista. Salta un modello se la sua CLI manca o i crediti sono esauriti, e preferisce uno dopo se i crediti del primo sono "scarso" e quelli dell\'altro no.', W).map(st.dim));
235
+ if (row.proposal) lines.push('', ...wrap(`proposta: ${describe(row.proposal)}`, W).map(st.dim));
236
+ }
237
+
238
+ if (s.view === 'model') {
239
+ const adding = !row.single && s.editIndex >= picksOf(row).length;
240
+ lines.push(st.dim(`${row.single ? 'Modello' : adding ? `Aggiungi il modello n.${s.editIndex + 1}` : `Cambia il modello n.${s.editIndex + 1}`} per ${row.type} · ↑↓ sposta · invio scegli · esc indietro`), '');
241
+ const list = modelList(s);
242
+ const height = 18;
243
+ const start = clamp(s.modelCursor - Math.floor(height / 2), Math.max(1, list.length - height + 1));
244
+ const proposed = row.proposal?.picks ?? [];
245
+ const taken = picksOf(row);
246
+ list.slice(start, start + height).forEach((m, j) => {
247
+ const i = start + j;
248
+ const text = m.none ? '— nessun modello per questo lavoro'
249
+ : narrow
250
+ ? `${fit(`${m.harness}:${m.model}`, Math.min(30, W - 30))} ${fit(`max ${num(m.best?.index)}`, 9)} ${m.credit}`
251
+ : `${fit(`${m.harness}:${m.model}`, 34)} ${fit(`indice max ${num(m.best?.index)}${m.best ? ` @${m.best.effort}` : ''}`, 24)} ${creditText(m)}`;
252
+ const pi = m.none ? -1 : proposed.findIndex((p) => p.harness === m.harness && p.model === m.model);
253
+ const ti = m.none ? -1 : taken.findIndex((p) => p.harness === m.harness && p.model === m.model);
254
+ const mark = narrow
255
+ ? `${ti >= 0 ? ` n.${ti + 1}` : ''}${pi === 0 ? ' ←prop.' : pi > 0 ? ' ←ris.' : ''}`
256
+ : `${ti >= 0 ? ` · già n.${ti + 1}` : ''}${pi === 0 ? ' ← proposta' : pi > 0 ? ' ← riserva proposta' : ''}`;
257
+ lines.push(i === s.modelCursor ? st.inv(`❯ ${text}${mark}`) : ` ${text}${st.dim(mark)}`);
258
+ });
259
+ if (list.length > height) lines.push(st.dim(` … ${list.length} modelli`));
260
+ }
261
+
262
+ if (s.view === 'effort') {
263
+ const m = s.editModel;
264
+ lines.push(st.dim(`Effort per ${m.harness}:${m.model} (${row.type}) · ↑↓ sposta · invio conferma · esc indietro`), '');
265
+ if (m.effort_fixed) lines.push(st.dim(' Questa CLI non permette di scegliere l\'effort: usa il suo default.'), '');
266
+ m.efforts.forEach((e, i) => {
267
+ const text = `${fit(e.effort ?? 'default', 10)} indice ${fit(num(e.index), 6)} costo/task ${num(e.cost, '$')}`;
268
+ const isProp = (row.proposal?.picks ?? []).some((p) => samePick(p, { harness: m.harness, model: m.model, effort: e.effort }));
269
+ const mark = isProp ? ' ← proposta' : '';
270
+ lines.push(i === s.effortCursor ? st.inv(`❯ ${text}${mark}`) : ` ${text}${st.dim(mark)}`);
271
+ });
272
+ lines.push('', st.dim('Indice: Artificial Analysis Intelligence Index; ? = non misurato.'));
273
+ }
274
+
275
+ if (s.message) lines.push('', s.message);
276
+ return lines.map((l) => clip(l, W)).join('\n');
277
+ }
278
+
279
+ /** Word-wrap plain text to `width` columns. */
280
+ export function wrap(text, width) {
281
+ const out = [];
282
+ let line = '';
283
+ for (const word of String(text).split(' ')) {
284
+ if (line && line.length + 1 + word.length > width) { out.push(line); line = word; } else line = line ? `${line} ${word}` : word;
285
+ }
286
+ if (line) out.push(line);
287
+ return out;
288
+ }
289
+
290
+ /** Cut a line to `width` visible characters, keeping ANSI escapes intact. */
291
+ export function clip(line, width) {
292
+ let visible = 0;
293
+ let out = '';
294
+ for (let i = 0; i < line.length; i++) {
295
+ if (line[i] === '\x1b') {
296
+ const m = line.slice(i).match(/^\x1b\[[0-9;?]*[A-Za-z]/);
297
+ if (m) { out += m[0]; i += m[0].length - 1; continue; }
298
+ }
299
+ if (visible >= width) { out += '\x1b[0m'; break; }
300
+ out += line[i];
301
+ visible++;
302
+ }
303
+ return out;
304
+ }
305
+
306
+ // ── terminal I/O ───────────────────────────────────────────────────────────
307
+ export function keyName(str, key = {}) {
308
+ if (key.ctrl && key.name === 'c') return 'ctrl-c';
309
+ if (key.shift && (key.name === 'up' || key.name === 'down')) return `shift-${key.name}`;
310
+ if (['up', 'down', 'return', 'escape', 'enter', 'backspace', 'delete'].includes(key.name)) return key.name === 'enter' ? 'return' : key.name;
311
+ return str ?? key.name ?? null;
312
+ }
313
+
314
+ /** Run the TUI on a TTY; resolves with the final state (done: 'save' | 'cancel'). */
315
+ export function runTui(state, { input = process.stdin, output = process.stdout } = {}) {
316
+ if (!input.isTTY || !output.isTTY) {
317
+ return Promise.reject(new Error('harma select richiede un terminale interattivo'));
318
+ }
319
+ return new Promise((resolve) => {
320
+ let s = state;
321
+ emitKeypressEvents(input);
322
+ input.setRawMode(true);
323
+ input.resume();
324
+ output.write(`${ESC}?1049h${ESC}?25l`); // alternate screen, hide cursor
325
+ const draw = () => output.write(`${ESC}H${ESC}2J${render(s, { width: output.columns ?? 100 })}`);
326
+ const onKey = (str, key) => {
327
+ const name = keyName(str, key);
328
+ if (!name) return;
329
+ s = reduce(s, name);
330
+ if (s.done) {
331
+ input.off('keypress', onKey);
332
+ output.off('resize', draw);
333
+ input.setRawMode(false);
334
+ input.pause();
335
+ output.write(`${ESC}?25h${ESC}?1049l`);
336
+ resolve(s);
337
+ return;
338
+ }
339
+ draw();
340
+ };
341
+ input.on('keypress', onKey);
342
+ output.on('resize', draw);
343
+ draw();
344
+ });
345
+ }