harma-kit 0.0.0-stage → 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/route.mjs ADDED
@@ -0,0 +1,69 @@
1
+ // Which model for which job. A score per (harness, model, effort):
2
+ // score = index − cost_weight × cost_per_task + credit adjustment
3
+ // filtered by min_index, by installed CLIs and by credit state. The profiles
4
+ // below are defaults; .harma/config.json "routing" overrides them per task type.
5
+
6
+ export const TASK_PROFILES = {
7
+ pianificazione: { min_index: 45, cost_weight: 0.5, label: 'pianificazione: massima intelligenza, il costo conta poco' },
8
+ sviluppo: { min_index: 40, cost_weight: 1.5, label: 'sviluppo: intelligenza alta a costo ragionevole' },
9
+ review: { min_index: 42, cost_weight: 1, different_vendor: true, label: 'review: vendor diverso da chi ha scritto il codice' },
10
+ debugging: { min_index: 45, cost_weight: 0.75, label: 'debugging: intelligenza alta, il costo conta poco' },
11
+ ricerca: { min_index: 35, cost_weight: 1.5, label: 'ricerca: buona intelligenza, costo contenuto' },
12
+ estrazione: { min_index: 30, mode: 'cheapest', label: 'estrazione: il più economico con indice ≥ soglia' },
13
+ };
14
+
15
+ export const TASK_ALIASES = {
16
+ planning: 'pianificazione', plan: 'pianificazione',
17
+ development: 'sviluppo', dev: 'sviluppo', build: 'sviluppo', implementazione: 'sviluppo',
18
+ revisione: 'review', 'code-review': 'review',
19
+ debug: 'debugging', 'problem-solving': 'debugging', problemi: 'debugging',
20
+ research: 'ricerca',
21
+ extraction: 'estrazione', clerk: 'estrazione',
22
+ };
23
+
24
+ export function taskProfile(type, config = {}) {
25
+ const key = TASK_PROFILES[type] ? type : TASK_ALIASES[type];
26
+ if (!key) return null;
27
+ return { type: key, ...TASK_PROFILES[key], ...(config.routing?.[key] ?? {}) };
28
+ }
29
+
30
+ const CREDIT_ADJUST = { ampio: 2, ok: 0, scarso: -8, sconosciuto: -1 };
31
+
32
+ /**
33
+ * rankRows: from rank.mjs. credits: rows from credits.mjs (by harness).
34
+ * author: {harness, model, provider} of the code under review, for review.
35
+ */
36
+ export function route(type, { rankRows, credits = [], config = {}, author = null, top = 5 }) {
37
+ const p = taskProfile(type, config);
38
+ if (!p) return null;
39
+ const creditBy = new Map(credits.map((c) => [c.harness, c]));
40
+ // Unknown cost is never treated as cheap: assume the highest known cost.
41
+ const knownCosts = rankRows.map((r) => r.cost_per_task).filter((x) => x !== null);
42
+ const worstCost = knownCosts.length ? Math.max(...knownCosts) : 0;
43
+ const out = [];
44
+ const skipped = [];
45
+ for (const r of rankRows) {
46
+ const c = creditBy.get(r.harness);
47
+ const status = c?.status ?? 'sconosciuto';
48
+ const why = [];
49
+ if (r.index === null) { skipped.push({ ...r, reason: 'indice AA sconosciuto' }); continue; }
50
+ if (r.index < p.min_index) { skipped.push({ ...r, reason: `indice ${r.index} < ${p.min_index}` }); continue; }
51
+ if (status === 'esaurito') { skipped.push({ ...r, reason: `crediti ${r.harness} esauriti` }); continue; }
52
+ if (p.different_vendor && author && r.provider && r.provider === author.provider) {
53
+ skipped.push({ ...r, reason: `stesso vendor dell'autore (${author.provider})` });
54
+ continue;
55
+ }
56
+ const cost = r.cost_per_task ?? worstCost;
57
+ const adj = CREDIT_ADJUST[status] ?? 0;
58
+ // cheapest: order by cost; the credit adjustment only breaks ties.
59
+ const score = p.mode === 'cheapest'
60
+ ? Math.round((-cost + adj / 1000) * 1000) / 1000
61
+ : Math.round((r.index - p.cost_weight * cost + adj) * 10) / 10;
62
+ why.push(`indice ${r.index}`);
63
+ why.push(r.cost_per_task === null ? `costo/task sconosciuto (assunto il più alto: $${worstCost})` : `costo/task $${r.cost_per_task}`);
64
+ why.push(`crediti ${status}${c?.remaining_pct !== null && c?.remaining_pct !== undefined ? ` (${c.remaining_pct}% residuo)` : ''}`);
65
+ out.push({ ...r, score, credit: status, why: why.join(' · ') });
66
+ }
67
+ out.sort((a, b) => b.score - a.score || b.index - a.index);
68
+ return { profile: p, candidates: out.slice(0, top), skipped };
69
+ }
package/src/state.mjs ADDED
@@ -0,0 +1,134 @@
1
+ // Project state lives in <project>/.harma/:
2
+ // config.json orchestrator, dispatch policy, budgets, thresholds, backend
3
+ // agents.jsonl append-only lifecycle events (started, session, closed, ...)
4
+ // cache/*.json inventory, credits, rank — each with fetchedAt and source
5
+ import { mkdirSync, writeFileSync, appendFileSync, existsSync, readFileSync } from 'node:fs';
6
+ import { join, dirname, resolve } from 'node:path';
7
+ import { readJson, readJsonl, now, HarmaError } from './util.mjs';
8
+
9
+ export const STATE_DIR = '.harma';
10
+
11
+ export const DEFAULT_CONFIG = {
12
+ schema_version: 1,
13
+ orchestrator: null, // {harness, model, effort}
14
+ backend: 'auto', // auto | herdr | hc
15
+ dispatch_policy: 'confirm', // confirm | auto-within-budget
16
+ budgets: {}, // provider -> {limit, currency, period}
17
+ thresholds: {
18
+ low_remaining_pct: 20, // under this, delegate less to the provider
19
+ exhausted_remaining_pct: 5, // under this, do not route to it
20
+ high_remaining_pct: 60, // over this, the provider can take more work
21
+ },
22
+ routing: {}, // task type -> overrides, see route.mjs
23
+ };
24
+
25
+ /** Find the project root: the nearest ancestor holding .harma, else cwd. */
26
+ export function projectRoot(start = process.cwd()) {
27
+ let dir = resolve(start);
28
+ for (;;) {
29
+ if (existsSync(join(dir, STATE_DIR, 'config.json'))) return dir;
30
+ const up = dirname(dir);
31
+ if (up === dir) return resolve(start);
32
+ dir = up;
33
+ }
34
+ }
35
+
36
+ export function statePath(root, ...parts) {
37
+ return join(root, STATE_DIR, ...parts);
38
+ }
39
+
40
+ export function loadConfig(root, { required = false } = {}) {
41
+ const cfg = readJson(statePath(root, 'config.json'));
42
+ if (!cfg && required) {
43
+ throw new HarmaError('Nessun progetto harma qui.', { hint: 'Esegui prima: harma init --orchestrator <harness>:<model> --effort <level>' });
44
+ }
45
+ return mergeDeep(structuredClone(DEFAULT_CONFIG), cfg ?? {});
46
+ }
47
+
48
+ export function saveConfig(root, cfg) {
49
+ mkdirSync(statePath(root), { recursive: true });
50
+ writeFileSync(statePath(root, 'config.json'), JSON.stringify(cfg, null, 2) + '\n');
51
+ ensureGitignore(root);
52
+ }
53
+
54
+ function ensureGitignore(root) {
55
+ const p = statePath(root, '.gitignore');
56
+ if (!existsSync(p)) writeFileSync(p, 'cache/\n');
57
+ }
58
+
59
+ export function appendEvent(root, event) {
60
+ mkdirSync(statePath(root), { recursive: true });
61
+ const rec = { at: now(), ...event };
62
+ appendFileSync(statePath(root, 'agents.jsonl'), JSON.stringify(rec) + '\n');
63
+ return rec;
64
+ }
65
+
66
+ export function readEvents(root) {
67
+ return readJsonl(statePath(root, 'agents.jsonl'));
68
+ }
69
+
70
+ /** Fold the event log into one record per agent name. */
71
+ export function agentsFromEvents(events) {
72
+ const agents = new Map();
73
+ for (const e of events) {
74
+ if (!e.agent) continue;
75
+ const cur = agents.get(e.agent) ?? { name: e.agent, history: [] };
76
+ cur.history.push(e.type);
77
+ switch (e.type) {
78
+ case 'started':
79
+ Object.assign(cur, {
80
+ harness: e.harness, model: e.model, effort: e.effort, task_type: e.task_type,
81
+ backend: e.backend, target: e.target, cwd: e.cwd, started_at: e.at,
82
+ session_id: e.session_id ?? cur.session_id ?? null, closed_at: null, state: 'open',
83
+ });
84
+ break;
85
+ case 'session':
86
+ cur.session_id = e.session_id;
87
+ cur.session_source = e.source;
88
+ break;
89
+ case 'closed':
90
+ cur.closed_at = e.at;
91
+ cur.state = 'closed';
92
+ cur.result = e.result ?? cur.result;
93
+ break;
94
+ case 'resumed':
95
+ cur.state = 'open';
96
+ cur.closed_at = null;
97
+ cur.target = e.target ?? cur.target;
98
+ cur.backend = e.backend ?? cur.backend;
99
+ break;
100
+ default:
101
+ break;
102
+ }
103
+ agents.set(e.agent, cur);
104
+ }
105
+ return [...agents.values()];
106
+ }
107
+
108
+ export function writeCache(root, name, data) {
109
+ mkdirSync(statePath(root, 'cache'), { recursive: true });
110
+ writeFileSync(statePath(root, 'cache', `${name}.json`), JSON.stringify(data, null, 2) + '\n');
111
+ }
112
+
113
+ export function readCache(root, name) {
114
+ return readJson(statePath(root, 'cache', `${name}.json`));
115
+ }
116
+
117
+ export function hasProject(root) {
118
+ return existsSync(statePath(root, 'config.json'));
119
+ }
120
+
121
+ function mergeDeep(base, extra) {
122
+ for (const [k, v] of Object.entries(extra)) {
123
+ if (v && typeof v === 'object' && !Array.isArray(v) && base[k] && typeof base[k] === 'object') {
124
+ base[k] = mergeDeep(base[k], v);
125
+ } else {
126
+ base[k] = v;
127
+ }
128
+ }
129
+ return base;
130
+ }
131
+
132
+ export function readText(path) {
133
+ try { return readFileSync(path, 'utf8'); } catch { return null; }
134
+ }
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
+ }
package/src/usage.mjs ADDED
@@ -0,0 +1,127 @@
1
+ // Token usage from the CLIs' own session logs, and an API-list-price estimate.
2
+ // Claude Code: ~/.claude/projects/<slug>/<session-id>.jsonl, assistant
3
+ // entries carry message.usage and message.model.
4
+ // Codex: ~/.codex/sessions/YYYY/MM/DD/rollout-*-<session-id>.jsonl,
5
+ // session_meta.payload.id, turn_context.payload.model/effort,
6
+ // event_msg token_count payload.info.total_token_usage (cumulative).
7
+ // For subscriptions this is what the tokens would cost at API list price,
8
+ // not what is billed.
9
+ import { readdirSync, statSync, existsSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { homedir } from 'node:os';
12
+ import { readJsonl } from './util.mjs';
13
+
14
+ // Multipliers on the input price. Anthropic publishes these (cache write
15
+ // 1.25x for 5 min, 2x for 1 h, read 0.1x). For OpenAI the cached-input ratio
16
+ // is not in the catalog: 0.1x is an assumption and is reported as one.
17
+ export const PRICE_RULES = {
18
+ anthropic: { cacheWrite5m: 1.25, cacheWrite1h: 2, cacheRead: 0.1, assumed: false },
19
+ openai: { cacheRead: 0.1, assumed: true },
20
+ };
21
+
22
+ function files(dir, { suffix = '.jsonl', sinceMs = 0, match } = {}) {
23
+ if (!existsSync(dir)) return [];
24
+ let names;
25
+ try { names = readdirSync(dir, { recursive: true }); } catch { return []; }
26
+ const out = [];
27
+ for (const n of names) {
28
+ const name = String(n);
29
+ if (!name.endsWith(suffix)) continue;
30
+ if (match && !match(name)) continue;
31
+ const p = join(dir, name);
32
+ try { if (statSync(p).mtimeMs >= sinceMs) out.push(p); } catch { /* gone */ }
33
+ }
34
+ return out;
35
+ }
36
+
37
+ const home = (env) => env.HOME || homedir();
38
+
39
+ export function claudeUsage({ env = process.env, sessionIds, sinceMs = 0 } = {}) {
40
+ const dir = join(home(env), '.claude', 'projects');
41
+ const ids = sessionIds ? new Set(sessionIds) : null;
42
+ const paths = files(dir, { sinceMs, match: ids ? (n) => ids.has(n.split('/').pop().replace(/\.jsonl$/, '')) : undefined });
43
+ const bySession = {};
44
+ for (const p of paths) {
45
+ for (const e of readJsonl(p)) {
46
+ const u = e?.message?.usage;
47
+ if (e.type !== 'assistant' || !u) continue;
48
+ if (Date.parse(e.timestamp ?? 0) < sinceMs) continue;
49
+ const sid = e.sessionId ?? p.split('/').pop().replace(/\.jsonl$/, '');
50
+ if (ids && !ids.has(sid)) continue;
51
+ const s = (bySession[sid] ??= { harness: 'claude', session_id: sid, model: null, cwd: e.cwd ?? null, input: 0, cache_write_5m: 0, cache_write_1h: 0, cache_read: 0, output: 0 });
52
+ s.model = e.message.model ?? s.model;
53
+ s.input += u.input_tokens ?? 0;
54
+ const cc = u.cache_creation ?? {};
55
+ const w1h = cc.ephemeral_1h_input_tokens ?? 0;
56
+ s.cache_write_1h += w1h;
57
+ s.cache_write_5m += (u.cache_creation_input_tokens ?? 0) - w1h;
58
+ s.cache_read += u.cache_read_input_tokens ?? 0;
59
+ s.output += u.output_tokens ?? 0;
60
+ }
61
+ }
62
+ return Object.values(bySession);
63
+ }
64
+
65
+ export function codexUsage({ env = process.env, sessionIds, sinceMs = 0 } = {}) {
66
+ const dir = join(home(env), '.codex', 'sessions');
67
+ const ids = sessionIds ? new Set(sessionIds) : null;
68
+ const paths = files(dir, { sinceMs, match: (n) => /rollout-.*\.jsonl$/.test(n) && (!ids || [...ids].some((id) => n.endsWith(`${id}.jsonl`))) });
69
+ const out = [];
70
+ for (const p of paths) {
71
+ let s = null;
72
+ for (const e of readJsonl(p)) {
73
+ const pl = e.payload ?? {};
74
+ if (e.type === 'session_meta') {
75
+ s = { harness: 'codex', session_id: pl.id, model: null, effort: null, cwd: pl.cwd ?? null, started_at: pl.timestamp ?? e.timestamp, input: 0, cache_read: 0, output: 0, reasoning: 0 };
76
+ } else if (s && e.type === 'turn_context') {
77
+ s.model = pl.model ?? s.model;
78
+ s.effort = pl.effort ?? s.effort;
79
+ } else if (s && pl.type === 'token_count' && pl.info?.total_token_usage) {
80
+ const t = pl.info.total_token_usage; // cumulative: last one wins
81
+ s.input = (t.input_tokens ?? 0) - (t.cached_input_tokens ?? 0);
82
+ s.cache_read = t.cached_input_tokens ?? 0;
83
+ s.output = t.output_tokens ?? 0;
84
+ s.reasoning = t.reasoning_output_tokens ?? 0;
85
+ }
86
+ }
87
+ if (s && (!ids || ids.has(s.session_id))) out.push(s);
88
+ }
89
+ return out;
90
+ }
91
+
92
+ /** Codex session started in <cwd> at or after <sinceMs> (the first one). */
93
+ export function findCodexSession({ env = process.env, cwd, sinceMs }) {
94
+ const sessions = codexUsage({ env, sinceMs: sinceMs - 60_000 })
95
+ .filter((s) => s.cwd === cwd && Date.parse(s.started_at ?? 0) >= sinceMs - 5_000)
96
+ .sort((a, b) => Date.parse(a.started_at) - Date.parse(b.started_at));
97
+ return sessions[0]?.session_id ?? null;
98
+ }
99
+
100
+ /** Estimated USD at API list price; null when the model has no price. */
101
+ export function estimateCost(session, catalog) {
102
+ const model = catalog.models?.[session.model] ?? catalog.models?.[normalizeModel(session.model, catalog)];
103
+ const price = model?.pricing;
104
+ if (!price) return { usd: null, note: `prezzo sconosciuto per ${session.model ?? 'modello ignoto'}` };
105
+ const rules = PRICE_RULES[model.provider] ?? { cacheRead: 1, assumed: true };
106
+ const inP = price.input / 1e6;
107
+ const outP = price.output / 1e6;
108
+ let usd = (session.input ?? 0) * inP + (session.output ?? 0) * outP + (session.cache_read ?? 0) * inP * (rules.cacheRead ?? 1);
109
+ usd += (session.cache_write_5m ?? 0) * inP * (rules.cacheWrite5m ?? 1);
110
+ usd += (session.cache_write_1h ?? 0) * inP * (rules.cacheWrite1h ?? 1);
111
+ return {
112
+ usd: Math.round(usd * 100) / 100,
113
+ note: `listino ${price.source} ${price.verified_on}${rules.assumed ? '; input in cache a 0.1× (ipotesi)' : ''}`,
114
+ };
115
+ }
116
+
117
+ function normalizeModel(name, catalog) {
118
+ if (!name) return null;
119
+ // "claude-opus-5-5-20261001" or "claude-opus-5-5[1m]" -> catalog id
120
+ return Object.keys(catalog.models ?? {}).find((id) => name.startsWith(id)) ?? null;
121
+ }
122
+
123
+ export function usageFor(harness, opts) {
124
+ if (harness === 'claude') return claudeUsage(opts);
125
+ if (harness === 'codex') return codexUsage(opts);
126
+ return [];
127
+ }