harma-kit 0.1.0 → 0.2.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.
package/src/roster.mjs ADDED
@@ -0,0 +1,177 @@
1
+ // The roster: which models (in order of preference) the user wants for each
2
+ // kind of work, plus the orchestrator. Proposals come from route(); the user
3
+ // accepts or overrides them in the TUI (harma select) or with --accept / --set.
4
+ // Stored in .harma/config.json → roster, orchestrator.
5
+ //
6
+ // A row's choice is null (undecided), { none: true } (no model for this job) or
7
+ // { picks: [{harness, model, effort}, …] } in order of preference. At dispatch
8
+ // choosePick() takes the first pick with usable credits.
9
+ import { route, TASK_PROFILES, taskProfile } from './route.mjs';
10
+ import { EFFORT_ORDER, HarmaError, now } from './util.mjs';
11
+
12
+ export const ORCHESTRATOR = 'orchestratore';
13
+ export const TASK_TYPES = Object.keys(TASK_PROFILES);
14
+ export const MAX_PICKS = 5;
15
+
16
+ /** One option per installed harness:model, with every effort's index and cost. */
17
+ export function modelOptions(invModels, rankRowsArr, credits = []) {
18
+ const creditBy = new Map(credits.map((c) => [c.harness, c]));
19
+ const out = [];
20
+ for (const m of invModels) {
21
+ const rows = rankRowsArr.filter((r) => r.harness === m.harness && r.model === m.model);
22
+ const efforts = (m.efforts?.length ? m.efforts : [null]).map((e) => {
23
+ const r = rows.find((x) => x.effort === e);
24
+ return { effort: e, index: r?.index ?? null, cost: r?.cost_per_task ?? null };
25
+ }).sort((a, b) => EFFORT_ORDER.indexOf(a.effort) - EFFORT_ORDER.indexOf(b.effort));
26
+ const known = efforts.filter((e) => e.index !== null);
27
+ const best = known.length ? known.reduce((a, b) => (b.index > a.index ? b : a)) : null;
28
+ const c = creditBy.get(m.harness);
29
+ out.push({
30
+ harness: m.harness, model: m.model, provider: rows[0]?.provider ?? null,
31
+ efforts, best, default_effort: m.default_effort ?? null, effort_fixed: Boolean(m.effort_fixed),
32
+ credit: c?.status ?? 'sconosciuto', remaining: c?.remaining_pct ?? null,
33
+ });
34
+ }
35
+ return out.sort((a, b) => (b.best?.index ?? -1) - (a.best?.index ?? -1));
36
+ }
37
+
38
+ /** Picks of a saved roster entry; reads the 0.2.0 single-model shape too. */
39
+ export function rosterPicks(entry) {
40
+ if (!entry || entry.none) return [];
41
+ if (Array.isArray(entry.picks)) return entry.picks.map(bare);
42
+ return entry.harness ? [bare(entry)] : [];
43
+ }
44
+
45
+ const bare = (x) => ({ harness: x.harness, model: x.model, effort: x.effort ?? null });
46
+
47
+ /** Rows for the selection: orchestrator first, then one per task type. */
48
+ export function selectionRows({ cfg, rankRowsArr, credits }) {
49
+ const rows = [{
50
+ type: ORCHESTRATOR,
51
+ label: 'orchestratore (dirige il progetto)',
52
+ single: true,
53
+ proposal: cfg.orchestrator ? { picks: [bare(cfg.orchestrator)] } : null,
54
+ choice: cfg.orchestrator ? { picks: [bare(cfg.orchestrator)], source: 'configurato' } : null,
55
+ }];
56
+ for (const type of TASK_TYPES) {
57
+ const p = taskProfile(type, cfg);
58
+ const res = route(type, { rankRows: rankRowsArr, credits, config: cfg, top: 1000 });
59
+ const cands = res?.candidates ?? [];
60
+ const first = cands[0];
61
+ // A backup on another CLI, so a job still has a model when one provider runs low.
62
+ const backup = first && cands.find((c) => c.harness !== first.harness);
63
+ const saved = cfg.roster?.[type];
64
+ rows.push({
65
+ type,
66
+ label: p.label,
67
+ proposal: first ? {
68
+ picks: [first, backup].filter(Boolean).map(bare),
69
+ why: `${first.why}${backup ? ` · riserva su un'altra CLI: ${describePick(backup)}` : ''}`,
70
+ } : null,
71
+ choice: !saved ? null : saved.none ? { none: true, source: saved.source } : { picks: rosterPicks(saved), source: saved.source ?? 'utente' },
72
+ });
73
+ }
74
+ for (const r of rows) r.original = r.choice ? structuredClone(r.choice) : null;
75
+ return rows;
76
+ }
77
+
78
+ export const samePick = (a, b) => Boolean(a && b && !a.none && !b.none
79
+ && a.harness === b.harness && a.model === b.model && (a.effort ?? null) === (b.effort ?? null));
80
+
81
+ /** Same choice: both undecided, both "none", or the same picks in the same order. */
82
+ export function sameChoice(a, b) {
83
+ if (!a && !b) return true;
84
+ if (!a || !b) return false;
85
+ if (a.none || b.none) return Boolean(a.none && b.none);
86
+ const pa = a.picks ?? [a];
87
+ const pb = b.picks ?? [b];
88
+ return pa.length === pb.length && pa.every((p, i) => samePick(p, pb[i]));
89
+ }
90
+
91
+ export const describePick = (p) => `${p.harness}:${p.model} @ ${p.effort ?? 'default'}`;
92
+
93
+ /** A single pick, a choice with picks, a saved roster entry, "none" or nothing. */
94
+ export function describe(p) {
95
+ if (!p) return '— da decidere';
96
+ if (p.none) return '— nessun modello';
97
+ const picks = p.picks ?? (p.harness ? [p] : []);
98
+ if (!picks.length) return '— da decidere';
99
+ return picks.map(describePick).join(' → ');
100
+ }
101
+
102
+ const CREDIT_RANK = { ampio: 0, ok: 0, sconosciuto: 0, scarso: 1 };
103
+
104
+ /**
105
+ * Which of the user's picks to use now. The user's order wins; a pick is skipped
106
+ * when its CLI is missing or its credits are exhausted, and passed over for a
107
+ * later one when its credits are low ("scarso") and a later one's are not.
108
+ */
109
+ export function choosePick(picks, credits = [], { installed = () => true } = {}) {
110
+ const by = new Map(credits.map((c) => [c.harness, c]));
111
+ const rated = picks.map((p, i) => {
112
+ const c = by.get(p.harness);
113
+ const credit = c?.status ?? 'sconosciuto';
114
+ const skip = !installed(p.harness) ? 'CLI non installata' : credit === 'esaurito' ? 'crediti esauriti' : null;
115
+ return { ...bare(p), position: i + 1, credit, remaining: c?.remaining_pct ?? null, skip };
116
+ });
117
+ const usable = rated.filter((p) => !p.skip);
118
+ const best = usable.reduce((a, p) => (a === null || CREDIT_RANK[p.credit] < CREDIT_RANK[a.credit] ? p : a), null);
119
+ const notes = rated.filter((p) => p !== best && best && p.position < best.position)
120
+ .map((p) => `n.${p.position} ${describePick(p)} saltato: ${p.skip ?? `crediti ${p.credit}`}`);
121
+ return { pick: best, rated, notes };
122
+ }
123
+
124
+ /** "sviluppo=codex:gpt-6.1-sol@high|claude:claude-sonnet-5-5@high,review=none,orchestratore=claude:claude-opus-5-5@high" */
125
+ export function parseSetSpec(spec, { catalog, parseTarget, effortValues }) {
126
+ const out = {};
127
+ for (const part of String(spec).split(',').map((s) => s.trim()).filter(Boolean)) {
128
+ const [rawType, value] = part.split(/=(.*)/s);
129
+ const type = rawType === ORCHESTRATOR || TASK_PROFILES[rawType] ? rawType : taskProfile(rawType)?.type;
130
+ if (!type) throw new HarmaError(`Tipo di lavoro sconosciuto in --set: ${rawType}`, { hint: `Tipi: ${[ORCHESTRATOR, ...TASK_TYPES].join(', ')}` });
131
+ if (!value) throw new HarmaError(`--set ${rawType}: manca il modello (tipo=harness:modello@effort)`);
132
+ if (value === 'none') {
133
+ if (type === ORCHESTRATOR) throw new HarmaError('L\'orchestratore non può essere "none"');
134
+ out[type] = { none: true, source: 'utente' };
135
+ continue;
136
+ }
137
+ const picks = value.split('|').map((s) => s.trim()).filter(Boolean).map((v) => {
138
+ const [target, effort] = v.split('@');
139
+ const t = parseTarget(target, catalog);
140
+ const allowed = effortValues(t.harness, t.model, catalog);
141
+ if (effort && allowed.length && !allowed.includes(effort)) {
142
+ throw new HarmaError(`Effort ${effort} non supportato da ${t.harness}:${t.model}`, { hint: `Valori: ${allowed.join(', ')}` });
143
+ }
144
+ return { harness: t.harness, model: t.model, effort: effort || catalog.models?.[t.model]?.effort_default || null };
145
+ });
146
+ if (type === ORCHESTRATOR && picks.length > 1) throw new HarmaError('L\'orchestratore è un solo modello');
147
+ if (picks.length > MAX_PICKS) throw new HarmaError(`Al massimo ${MAX_PICKS} modelli per lavoro`);
148
+ const dup = picks.find((p, i) => picks.findIndex((q) => samePick(p, q)) !== i);
149
+ if (dup) throw new HarmaError(`--set ${type}: ${describePick(dup)} compare due volte`);
150
+ out[type] = { picks, source: 'utente' };
151
+ }
152
+ return out;
153
+ }
154
+
155
+ /** Write the rows' choices into cfg (roster + orchestrator). Returns the saved roster. */
156
+ export function applySelection(cfg, rows) {
157
+ const at = now();
158
+ const roster = { ...(cfg.roster ?? {}) };
159
+ for (const r of rows) {
160
+ if (r.type === ORCHESTRATOR) {
161
+ const o = r.choice?.picks?.[0];
162
+ if (o && !sameChoice(r.choice, r.original)) cfg.orchestrator = { ...bare(o), set_at: at };
163
+ continue;
164
+ }
165
+ if (!r.choice || (!r.choice.none && !r.choice.picks?.length)) { delete roster[r.type]; continue; }
166
+ if (r.choice.none) { roster[r.type] = { none: true, source: 'utente', at }; continue; }
167
+ roster[r.type] = {
168
+ picks: r.choice.picks.map(bare),
169
+ source: r.proposal && sameChoice(r.choice, r.proposal) ? 'proposta' : 'utente',
170
+ proposed: r.proposal ? describe(r.proposal) : null,
171
+ at,
172
+ };
173
+ }
174
+ cfg.roster = roster;
175
+ cfg.roster_updated_at = at;
176
+ return roster;
177
+ }
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
+ }