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.
@@ -0,0 +1,680 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { loadCatalog, harnesses } from './catalog.mjs';
4
+ import { parseTarget, effortValues, launchSpec, resumeArgv, meta } from './harness.mjs';
5
+ import {
6
+ projectRoot, loadConfig, saveConfig, appendEvent, readEvents, agentsFromEvents,
7
+ writeCache, readCache, hasProject, DEFAULT_CONFIG,
8
+ } from './state.mjs';
9
+ import { inventory } from './inventory.mjs';
10
+ import { collectCredits } from './credits.mjs';
11
+ import { rankRows, refreshFromAA } from './rank.mjs';
12
+ import { route, taskProfile, TASK_PROFILES } from './route.mjs';
13
+ import { selectBackend, HerdrBackend, HcBackend, projectId, checkAgentName } from './backends.mjs';
14
+ import { usageFor, estimateCost, findCodexSession } from './usage.mjs';
15
+ import { table, HarmaError, now, which, readJson, run } from './util.mjs';
16
+ import { modelOptions, selectionRows, applySelection, parseSetSpec, describe, describePick, ORCHESTRATOR, rosterPicks, choosePick } from './roster.mjs';
17
+ import { initState, runTui } from './tui.mjs';
18
+ import { statePath } from './state.mjs';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ export const EXIT_NEEDS_CONFIRM = 3;
22
+ export const EXIT_BLOCKED = 4; // agent started, waiting on a dialog; task not delivered
23
+ const CREDIT_TTL_MS = 15 * 60_000;
24
+
25
+ function ctx(opts) {
26
+ const env = opts.env ?? process.env;
27
+ const root = projectRoot(opts.cwd ?? process.cwd());
28
+ const catalog = loadCatalog({ env });
29
+ return { env, root, catalog, out: opts.out ?? ((s) => process.stdout.write(s + '\n')) };
30
+ }
31
+
32
+ /** Is the CLI that runs this harness on PATH? */
33
+ function installedHarness(c, harness) {
34
+ const h = harnesses(c.catalog)[harness];
35
+ if (!h) return false;
36
+ return Boolean(which(meta(harness).interactiveBinary ?? h.binary.split(' ')[0], c.env));
37
+ }
38
+
39
+ const emit = (c, flags, data, text) => c.out(flags.json ? JSON.stringify(data, null, 2) : text());
40
+
41
+ // 1 ─ orchestrator ─────────────────────────────────────────────────────────
42
+ export async function cmdInit(flags, opts = {}) {
43
+ const c = ctx(opts);
44
+ const root = resolve(opts.cwd ?? process.cwd());
45
+ const cfg = loadConfig(root);
46
+ if (!flags.orchestrator) throw new HarmaError('Manca --orchestrator <harness>:<model>', { hint: 'es. harma init --orchestrator claude:claude-opus-5-5 --effort high' });
47
+ const t = parseTarget(flags.orchestrator, c.catalog);
48
+ const allowed = effortValues(t.harness, t.model, c.catalog);
49
+ const effort = flags.effort ?? c.catalog.models?.[t.model]?.effort_default ?? null;
50
+ if (effort && allowed.length && !allowed.includes(effort)) {
51
+ throw new HarmaError(`Effort ${effort} non supportato da ${t.harness}:${t.model}`, { hint: `Valori: ${allowed.join(', ')}` });
52
+ }
53
+ cfg.orchestrator = { harness: t.harness, model: t.model, effort, set_at: now() };
54
+ if (flags.backend) cfg.backend = flags.backend;
55
+ if (flags.policy) {
56
+ if (!['confirm', 'auto-within-budget'].includes(flags.policy)) throw new HarmaError('--policy: confirm | auto-within-budget');
57
+ cfg.dispatch_policy = flags.policy;
58
+ }
59
+ saveConfig(root, cfg);
60
+ appendEvent(root, { type: 'orchestrator', ...cfg.orchestrator });
61
+ emit({ ...c, root }, flags, cfg, () => [
62
+ `Progetto harma: ${root}`,
63
+ `Orchestratore: ${t.harness}:${t.model} @ ${effort ?? 'default'}`,
64
+ `Backend: ${cfg.backend} · Policy di delega: ${cfg.dispatch_policy}`,
65
+ 'Prossimi passi: harma models · harma credits · harma rank',
66
+ ].join('\n'));
67
+ return cfg;
68
+ }
69
+
70
+ // 2 ─ inventory ────────────────────────────────────────────────────────────
71
+ export async function cmdModels(flags, opts = {}) {
72
+ const c = ctx(opts);
73
+ const cfg = loadConfig(c.root);
74
+ const inv = await inventory({ catalog: c.catalog, env: c.env, config: cfg });
75
+ if (hasProject(c.root)) writeCache(c.root, 'inventory', inv);
76
+ emit(c, flags, inv, () => [
77
+ 'CLI di agenti',
78
+ table(inv.clis, ['harness', 'state', 'version', 'billing', 'effort_via']),
79
+ '',
80
+ 'Modelli utilizzabili',
81
+ table(inv.models.map((m) => ({ ...m, efforts: m.efforts.join(','), in_catalog: m.in_catalog ? 'sì' : 'no' })),
82
+ ['harness', 'model', 'efforts', 'default_effort', 'in_catalog', 'source']),
83
+ ].join('\n'));
84
+ return inv;
85
+ }
86
+
87
+ async function currentInventory(c, cfg, { fresh = false } = {}) {
88
+ const cached = !fresh && hasProject(c.root) ? readCache(c.root, 'inventory') : null;
89
+ return cached ?? inventory({ catalog: c.catalog, env: c.env, config: cfg, versions: false });
90
+ }
91
+
92
+ // 3 ─ credits ──────────────────────────────────────────────────────────────
93
+ export async function cmdCredits(flags, opts = {}) {
94
+ const c = ctx(opts);
95
+ const cfg = loadConfig(c.root);
96
+ const inv = await currentInventory(c, cfg);
97
+ const names = inv.clis.filter((x) => x.state === 'installato').map((x) => x.harness);
98
+ const credits = await collectCredits({ harnessNames: names, config: cfg, catalog: c.catalog, env: c.env, codexbar: opts.codexbar });
99
+ if (hasProject(c.root)) writeCache(c.root, 'credits', credits);
100
+ emit(c, flags, credits, () => [
101
+ `Crediti (${credits.fetched_at}; codexbar: ${credits.codexbar})`,
102
+ table(credits.rows.map((r) => ({
103
+ harness: r.harness,
104
+ provider: r.provider,
105
+ residuo: r.remaining_pct === null ? 'sconosciuto' : `${r.remaining_pct}%`,
106
+ stato: r.status,
107
+ finestre: r.windows.map((w) => `${w.window} ${w.used_pct}%`).join(' ') || null,
108
+ 'stima 7g': r.estimate ? `$${r.estimate.usd}` : null,
109
+ fonte: r.source ?? r.detail,
110
+ }))),
111
+ '',
112
+ 'Stima 7g = token dei log locali × listino API: per un abbonamento non è l\'addebito reale.',
113
+ ].join('\n'));
114
+ return credits;
115
+ }
116
+
117
+ async function currentCredits(c, cfg, inv, opts) {
118
+ const cached = hasProject(c.root) ? readCache(c.root, 'credits') : null;
119
+ if (cached && Date.now() - Date.parse(cached.fetched_at) < CREDIT_TTL_MS) return cached;
120
+ const names = inv.clis.filter((x) => x.state === 'installato').map((x) => x.harness);
121
+ const credits = await collectCredits({ harnessNames: names, config: cfg, catalog: c.catalog, env: c.env, codexbar: opts.codexbar });
122
+ if (hasProject(c.root)) writeCache(c.root, 'credits', credits);
123
+ return credits;
124
+ }
125
+
126
+ // 4 ─ intelligence ─────────────────────────────────────────────────────────
127
+ export async function cmdRank(flags, opts = {}) {
128
+ let c = ctx(opts);
129
+ let refresh = null;
130
+ if (flags.refresh) {
131
+ refresh = await refreshFromAA(c.catalog, { env: c.env, fetchImpl: opts.fetchImpl });
132
+ c = ctx(opts);
133
+ }
134
+ const cfg = loadConfig(c.root);
135
+ const inv = await currentInventory(c, cfg);
136
+ const rows = rankRows(c.catalog, inv.models);
137
+ const top = Number(flags.top ?? rows.length);
138
+ const data = { catalog: { origin: c.catalog.origin, generated_at: c.catalog.generated_at, attribution: c.catalog.attribution }, refresh, rows: rows.slice(0, top) };
139
+ if (hasProject(c.root)) writeCache(c.root, 'rank', { fetched_at: now(), ...data });
140
+ emit(c, flags, data, () => [
141
+ `Intelligenza per modello × effort — ${c.catalog.attribution}`,
142
+ `Catalogo: ${c.catalog.origin === 'bundled' ? `snapshot incluso (registro ${c.catalog.registry_updated})` : `aggiornato da AA il ${c.catalog.generated_at}`}${refresh ? ` · aggiornati ${refresh.changes.filter((x) => x.change === 'indice aggiornato').length} modelli` : ''}`,
143
+ table(rows.slice(0, top).map((r) => ({
144
+ harness: r.harness, model: r.model, effort: r.effort,
145
+ indice: r.index ?? 'sconosciuto', 'costo/task': r.cost_per_task === null ? '—' : `$${r.cost_per_task}`, 'data AA': r.aa_date,
146
+ }))),
147
+ ].join('\n'));
148
+ return data;
149
+ }
150
+
151
+ // 5 ─ routing ──────────────────────────────────────────────────────────────
152
+ export async function cmdRoute(flags, opts = {}) {
153
+ const c = ctx(opts);
154
+ const cfg = loadConfig(c.root);
155
+ const type = flags._[0];
156
+ if (!type) throw new HarmaError('Manca il tipo di lavoro', { hint: `Tipi: ${Object.keys(TASK_PROFILES).join(', ')}` });
157
+ const inv = await currentInventory(c, cfg);
158
+ const credits = await currentCredits(c, cfg, inv, opts);
159
+ const author = flags.author ? authorOf(flags.author, c.catalog) : null;
160
+ const res = route(type, { rankRows: rankRows(c.catalog, inv.models), credits: credits.rows, config: cfg, author, top: Number(flags.top ?? 5) });
161
+ if (!res) throw new HarmaError(`Tipo di lavoro sconosciuto: ${type}`, { hint: `Tipi: ${Object.keys(TASK_PROFILES).join(', ')}` });
162
+ res.user_choice = cfg.roster?.[res.profile.type] ?? null;
163
+ if (res.user_choice && !res.user_choice.none) {
164
+ const chosen = choosePick(rosterPicks(res.user_choice), credits.rows, { installed: (h) => installedHarness(c, h) });
165
+ res.user_pick = chosen.pick ? { ...chosen.pick, notes: chosen.notes } : null;
166
+ }
167
+ emit(c, flags, res, () => [
168
+ `Routing — ${res.profile.label}`,
169
+ !res.user_choice ? 'Nessuna scelta dell\'utente per questo lavoro: proponila con harma select.'
170
+ : res.user_choice.none ? 'L\'utente ha scelto: nessun modello per questo lavoro.'
171
+ : `Scelta dell'utente (harma select): ${describe(res.user_choice)}\n ora dispatch --task-type ${res.profile.type} userebbe: ${res.user_pick ? `${describePick(res.user_pick)} (n.${res.user_pick.position})${res.user_pick.notes.length ? ` — ${res.user_pick.notes.join('; ')}` : ''}` : 'nessuno: tutti i modelli scelti sono senza crediti o non installati'}`,
172
+ table(res.candidates.map((r, i) => ({ '#': i + 1, modello: `${r.harness}:${r.model}`, effort: r.effort, punteggio: r.score, motivi: r.why }))),
173
+ res.candidates.length ? `\nPer avviarlo: harma dispatch --name <nome> --task-type ${res.profile.type} --model ${res.candidates[0].harness}:${res.candidates[0].model} --effort ${res.candidates[0].effort} --prompt "<compito>"` : '\nNessun candidato: abbassa min_index in .harma/config.json routing o controlla crediti e CLI.',
174
+ ].join('\n'));
175
+ return res;
176
+ }
177
+
178
+ function authorOf(spec, catalog) {
179
+ const t = parseTarget(spec, catalog);
180
+ return { ...t, provider: catalog.models?.[t.model]?.provider ?? null };
181
+ }
182
+
183
+ // 5b ─ dispatch ────────────────────────────────────────────────────────────
184
+ export async function cmdDispatch(flags, opts = {}) {
185
+ const c = ctx(opts);
186
+ const cfg = loadConfig(c.root, { required: true });
187
+ checkAgentName(flags.name);
188
+ const existing = agentsFromEvents(readEvents(c.root)).find((a) => a.name === flags.name && a.state === 'open');
189
+ if (existing) throw new HarmaError(`L'agente ${flags.name} è già aperto`, { hint: 'Scegli un altro nome, o `harma send` per dargli altro lavoro' });
190
+
191
+ let pick;
192
+ if (flags.model) {
193
+ const t = parseTarget(flags.model, c.catalog);
194
+ pick = { harness: t.harness, model: t.model, effort: flags.effort ?? c.catalog.models?.[t.model]?.effort_default ?? null, why: 'scelto esplicitamente' };
195
+ } else if (flags['task-type'] && cfg.roster?.[taskProfile(flags['task-type'], cfg)?.type]) {
196
+ const type = taskProfile(flags['task-type'], cfg).type;
197
+ const chosen = cfg.roster[type];
198
+ if (chosen.none) throw new HarmaError(`Per ${type} l'utente ha scelto di non usare nessun modello`, { hint: 'Cambia la scelta con harma select, o passa --model esplicitamente' });
199
+ const picks = rosterPicks(chosen);
200
+ const inv = await currentInventory(c, cfg);
201
+ const credits = await currentCredits(c, cfg, inv, opts);
202
+ const { pick: p, rated, notes } = choosePick(picks, credits.rows, { installed: (h) => installedHarness(c, h) });
203
+ if (!p) {
204
+ throw new HarmaError(`Nessuno dei modelli scelti per ${type} è utilizzabile ora`, {
205
+ hint: `${rated.map((r) => `n.${r.position} ${describePick(r)}: ${r.skip}`).join('; ')} — cambia la lista con harma select, o passa --model esplicitamente`,
206
+ });
207
+ }
208
+ const where = picks.length > 1 ? `n.${p.position} di ${picks.length}` : 'unica';
209
+ pick = { harness: p.harness, model: p.model, effort: flags.effort ?? p.effort, why: `scelta dell'utente per ${type} (harma select, ${chosen.source}; ${where}, crediti ${p.credit})${notes.length ? ` — ${notes.join('; ')}` : ''}` };
210
+ } else {
211
+ if (!flags['task-type']) throw new HarmaError('Serve --model <harness>:<model> oppure --task-type <tipo>');
212
+ const inv = await currentInventory(c, cfg);
213
+ const credits = await currentCredits(c, cfg, inv, opts);
214
+ const res = route(flags['task-type'], { rankRows: rankRows(c.catalog, inv.models), credits: credits.rows, config: cfg, author: flags.author ? authorOf(flags.author, c.catalog) : null, top: 1 });
215
+ if (!res?.candidates.length) throw new HarmaError(`Nessun modello adatto per ${flags['task-type']}`);
216
+ pick = { ...res.candidates[0], why: `routing ${res.profile.type}: ${res.candidates[0].why}` };
217
+ }
218
+ const prompt = flags['prompt-file'] ? readFileSync(flags['prompt-file'], 'utf8') : flags.prompt ?? null;
219
+ const cwd = resolve(flags.cwd ?? c.root);
220
+ const spec = launchSpec(pick, c.catalog);
221
+ if (!which(spec.argv[0], c.env)) {
222
+ throw new HarmaError(`${spec.argv[0]} non è installato su questa macchina`, { hint: 'Vedi harma models per le CLI disponibili' });
223
+ }
224
+ const plan = {
225
+ agent: flags.name, task_type: flags['task-type'] ?? null,
226
+ harness: pick.harness, model: pick.model, effort: pick.effort, why: pick.why,
227
+ cwd, argv: spec.argv, env: spec.env, notes: spec.notes,
228
+ prompt_chars: prompt?.length ?? 0, policy: cfg.dispatch_policy,
229
+ };
230
+
231
+ const gate = await dispatchGate(c, cfg, pick.harness, flags, opts);
232
+ if (!gate.allowed) {
233
+ emit(c, flags, { needs_confirmation: true, reason: gate.reason, plan }, () => [
234
+ 'CONFERMA RICHIESTA — nessun agente è stato avviato.',
235
+ `Motivo: ${gate.reason}`,
236
+ `Agente ${plan.agent}: ${plan.harness}:${plan.model} @ ${plan.effort ?? 'default'} (${plan.why})`,
237
+ `Comando: ${plan.argv.join(' ')}${Object.keys(plan.env).length ? ` env ${JSON.stringify(plan.env)}` : ''}`,
238
+ ...plan.notes.map((n) => `Nota: ${n}`),
239
+ 'Se l\'utente approva, ripeti lo stesso comando con --yes.',
240
+ ].join('\n'));
241
+ return { needsConfirmation: true, plan, exitCode: EXIT_NEEDS_CONFIRM };
242
+ }
243
+
244
+ const backend = opts.backend ?? await selectBackend({ choice: flags.backend, config: cfg, env: c.env });
245
+ const project = projectId(c.root);
246
+ const startedMs = Date.now();
247
+ const started = await backend.start({ name: flags.name, cwd, argv: spec.argv, env: spec.env, harness: pick.harness, root: c.root, project });
248
+ if (started.workspaceCreated) { cfg.herdr = { ...(cfg.herdr ?? {}), workspace_id: started.workspace }; saveConfig(c.root, cfg); }
249
+ appendEvent(c.root, {
250
+ type: 'started', agent: flags.name, harness: pick.harness, model: pick.model, effort: pick.effort,
251
+ task_type: flags['task-type'] ?? null, backend: backend.name, target: { name: started.target, tab: started.tab ?? null, pane: started.pane ?? null, address: started.address ?? null },
252
+ cwd, session_id: spec.sessionId, why: pick.why, confirmed_by: gate.by, started_ms: startedMs,
253
+ });
254
+ let sid = spec.sessionId ?? await discoverSession(backend, { name: started.target, harness: pick.harness, cwd, sinceMs: startedMs, env: c.env });
255
+ if (sid && sid !== spec.sessionId) appendEvent(c.root, { type: 'session', agent: flags.name, session_id: sid, source: backend.name });
256
+ let promptState = prompt ? 'sent' : 'none';
257
+ if (prompt) {
258
+ try {
259
+ await backend.prompt(started.target, prompt, { wait: Boolean(flags.wait), timeoutSec: Number(flags.timeout ?? 600) });
260
+ appendEvent(c.root, { type: 'prompted', agent: flags.name, chars: prompt.length });
261
+ } catch (e) {
262
+ if (e.code !== 'agent_blocked') throw e;
263
+ // Started and recorded, but waiting on a dialog (e.g. folder trust): the user must answer it.
264
+ promptState = 'blocked';
265
+ appendEvent(c.root, { type: 'blocked', agent: flags.name, detail: 'prompt non inviato: l\'agente aspetta un input' });
266
+ }
267
+ }
268
+ if (!sid && promptState === 'sent') {
269
+ // Codex registers its session on the first turn: look again now.
270
+ sid = await discoverSession(backend, { name: started.target, harness: pick.harness, cwd, sinceMs: startedMs, env: c.env });
271
+ if (sid) appendEvent(c.root, { type: 'session', agent: flags.name, session_id: sid, source: backend.name });
272
+ }
273
+ const result = { started: true, plan, target: started, session_id: sid ?? null, prompt: promptState, exitCode: promptState === 'blocked' ? EXIT_BLOCKED : 0 };
274
+ emit(c, flags, result, () => [
275
+ `Avviato ${flags.name}: ${pick.harness}:${pick.model} @ ${pick.effort ?? 'default'} su ${backend.name} (${started.tab ?? started.address ?? started.target})`,
276
+ `Sessione: ${sid ?? 'non ancora nota (verrà letta alla chiusura)'}`,
277
+ promptState === 'sent' ? `Compito inviato (${prompt.length} caratteri)${flags.wait ? '; atteso fino a stato stabile' : ''}.`
278
+ : promptState === 'blocked' ? `BLOCCATO: ${flags.name} aspetta una risposta (es. fiducia nella cartella) e il compito NON è stato inviato.\nLeggi con: harma read ${flags.name} — chiedi all'utente di rispondere nel suo terminale, poi: harma send ${flags.name} "<compito>" --yes`
279
+ : 'Nessun compito inviato: usa harma send.',
280
+ ...plan.notes.map((n) => `Nota: ${n}`),
281
+ ].join('\n'));
282
+ return result;
283
+ }
284
+
285
+ /** Policy check. confirm: only --yes. auto-within-budget: provider credits ok/ampio. */
286
+ async function dispatchGate(c, cfg, harness, flags, opts) {
287
+ if (flags.yes) return { allowed: true, by: 'utente (--yes)' };
288
+ if (cfg.dispatch_policy !== 'auto-within-budget') {
289
+ return { allowed: false, reason: 'policy "confirm": ogni avvio di agente richiede il consenso esplicito dell\'utente' };
290
+ }
291
+ const inv = await currentInventory(c, cfg);
292
+ const credits = await currentCredits(c, cfg, inv, opts);
293
+ const row = credits.rows.find((r) => r.harness === harness);
294
+ if (row && ['ok', 'ampio'].includes(row.status)) return { allowed: true, by: `policy auto-within-budget (crediti ${row.status})` };
295
+ return { allowed: false, reason: `policy auto-within-budget: crediti ${harness} ${row?.status ?? 'sconosciuti'}` };
296
+ }
297
+
298
+ async function discoverSession(backend, { name, harness, cwd, sinceMs, env }) {
299
+ if (backend.name === 'herdr') {
300
+ try {
301
+ const live = (await backend.list()).find((a) => a.name === name || a.target === name);
302
+ if (live?.sessionId) return live.sessionId;
303
+ } catch { /* fall through */ }
304
+ }
305
+ if (harness === 'codex') return findCodexSession({ env, cwd, sinceMs });
306
+ return null;
307
+ }
308
+
309
+ // send / read ──────────────────────────────────────────────────────────────
310
+ export async function cmdSend(flags, opts = {}) {
311
+ const c = ctx(opts);
312
+ const cfg = loadConfig(c.root, { required: true });
313
+ const [name, ...rest] = flags._;
314
+ const text = flags['prompt-file'] ? readFileSync(flags['prompt-file'], 'utf8') : rest.join(' ');
315
+ const agent = openAgent(c, name);
316
+ if (!text) throw new HarmaError('Manca il testo da inviare');
317
+ const gate = await dispatchGate(c, cfg, agent.harness, flags, opts);
318
+ if (!gate.allowed) {
319
+ emit(c, flags, { needs_confirmation: true, reason: gate.reason, agent: name, chars: text.length }, () =>
320
+ `CONFERMA RICHIESTA — nulla è stato inviato a ${name}.\nMotivo: ${gate.reason}\nSe l'utente approva, ripeti con --yes.`);
321
+ return { needsConfirmation: true, exitCode: EXIT_NEEDS_CONFIRM };
322
+ }
323
+ const backend = opts.backend ?? backendFor(agent, cfg, c.env);
324
+ await backend.prompt(agent.target?.name ?? name, text, { wait: Boolean(flags.wait), timeoutSec: Number(flags.timeout ?? 600) });
325
+ appendEvent(c.root, { type: 'prompted', agent: name, chars: text.length, confirmed_by: gate.by });
326
+ c.out(flags.json ? JSON.stringify({ sent: true }) : `Inviato a ${name} (${text.length} caratteri).`);
327
+ return { sent: true };
328
+ }
329
+
330
+ export async function cmdRead(flags, opts = {}) {
331
+ const c = ctx(opts);
332
+ const cfg = loadConfig(c.root, { required: true });
333
+ const agent = openAgent(c, flags._[0]);
334
+ const backend = opts.backend ?? backendFor(agent, cfg, c.env);
335
+ const text = await backend.read(agent.target?.name ?? agent.name, Number(flags.lines ?? 120));
336
+ c.out(text);
337
+ return text;
338
+ }
339
+
340
+ function openAgent(c, name) {
341
+ if (!name) throw new HarmaError('Manca il nome dell\'agente');
342
+ const a = agentsFromEvents(readEvents(c.root)).find((x) => x.name === name);
343
+ if (!a) throw new HarmaError(`Agente sconosciuto: ${name}`, { hint: 'Vedi harma status' });
344
+ if (a.state !== 'open') throw new HarmaError(`L'agente ${name} è chiuso`, { hint: `harma resume ${name}` });
345
+ return a;
346
+ }
347
+
348
+ function backendFor(agent, cfg, env) {
349
+ return agent.backend === 'hc' ? new HcBackend({ env }) : new HerdrBackend({ env, config: cfg });
350
+ }
351
+
352
+ // 6 ─ monitoring ───────────────────────────────────────────────────────────
353
+ export async function cmdStatus(flags, opts = {}) {
354
+ const c = ctx(opts);
355
+ const cfg = loadConfig(c.root, { required: true });
356
+ const agents = agentsFromEvents(readEvents(c.root));
357
+ const live = await liveByBackend(c, cfg, agents, opts);
358
+ const rows = agents.filter((a) => flags.all || a.state === 'open').map((a) => {
359
+ const l = findLive(a, live[a.backend]);
360
+ return {
361
+ agente: a.name,
362
+ modello: `${a.harness}:${a.model}`,
363
+ effort: a.effort,
364
+ lavoro: a.task_type,
365
+ registro: a.state === 'open' ? 'aperto' : 'chiuso',
366
+ stato: a.state === 'closed' ? '—' : (l ? (l.status ?? 'nessuno stato') : (live[a.backend] ? 'non trovato' : 'backend non raggiungibile')),
367
+ backend: `${a.backend} ${a.target?.tab ?? a.target?.address ?? ''}`.trim(),
368
+ da: a.started_at ? ago(a.started_at) : null,
369
+ sessione: a.session_id ? a.session_id.slice(0, 8) + '…' : (l?.sessionId ? l.sessionId.slice(0, 8) + '…' : null),
370
+ };
371
+ });
372
+ const data = { orchestrator: cfg.orchestrator, policy: cfg.dispatch_policy, agents: rows };
373
+ emit(c, flags, data, () => [
374
+ `Orchestratore: ${cfg.orchestrator ? `${cfg.orchestrator.harness}:${cfg.orchestrator.model} @ ${cfg.orchestrator.effort}` : 'non impostato'} · policy ${cfg.dispatch_policy}`,
375
+ table(rows),
376
+ ].join('\n'));
377
+ return data;
378
+ }
379
+
380
+ async function liveByBackend(c, cfg, agents, opts) {
381
+ const out = {};
382
+ const used = new Set(agents.filter((a) => a.state === 'open').map((a) => a.backend));
383
+ for (const name of used) {
384
+ const b = opts.backend?.name === name ? opts.backend : (name === 'hc' ? new HcBackend({ env: c.env }) : new HerdrBackend({ env: c.env, config: cfg }));
385
+ try { out[name] = await b.list(projectId(c.root)); } catch { out[name] = null; }
386
+ }
387
+ return out;
388
+ }
389
+
390
+ /** Drop `flag` and the value after it; with no flag, return args unchanged. */
391
+ export function withoutFlag(args, flag) {
392
+ if (!flag) return [...args];
393
+ const i = args.indexOf(flag);
394
+ return i < 0 ? [...args] : [...args.slice(0, i), ...args.slice(i + 2)];
395
+ }
396
+
397
+ /** The live terminal of a registered agent: by pane (herdr), address (hc), then name. */
398
+ export function findLive(a, list) {
399
+ if (!list) return null;
400
+ const t = a.target ?? {};
401
+ return list.find((x) => t.pane && x.pane === t.pane)
402
+ ?? list.find((x) => t.address && x.address === t.address)
403
+ ?? list.find((x) => x.name && x.name === (t.name ?? a.name))
404
+ ?? null;
405
+ }
406
+
407
+ function ago(iso) {
408
+ const m = Math.round((Date.now() - Date.parse(iso)) / 60_000);
409
+ return m < 60 ? `${m} min` : m < 1440 ? `${Math.round(m / 60)} h` : `${Math.round(m / 1440)} g`;
410
+ }
411
+
412
+ // 7 ─ costs ────────────────────────────────────────────────────────────────
413
+ export async function cmdCosts(flags, opts = {}) {
414
+ const c = ctx(opts);
415
+ const cfg = loadConfig(c.root, { required: true });
416
+ const agents = agentsFromEvents(readEvents(c.root));
417
+ // An open agent's id may be known to the backend before harma records it.
418
+ const live = await liveByBackend(c, cfg, agents.filter((a) => !a.session_id), opts);
419
+ for (const a of agents) {
420
+ if (!a.session_id && a.state === 'open') a.session_id = findLive(a, live[a.backend])?.sessionId ?? null;
421
+ }
422
+ const perAgent = [];
423
+ for (const a of agents) {
424
+ if (!a.session_id || !meta(a.harness).logs) {
425
+ perAgent.push({ agente: a.name, modello: `${a.harness}:${a.model}`, token: null, stima: null, nota: a.session_id ? `nessun log locale per ${a.harness}` : 'id di sessione non ancora noto' });
426
+ continue;
427
+ }
428
+ const s = usageFor(a.harness, { env: c.env, sessionIds: [a.session_id] })[0];
429
+ if (!s) { perAgent.push({ agente: a.name, modello: `${a.harness}:${a.model}`, token: 0, stima: null, nota: 'sessione senza consumi registrati' }); continue; }
430
+ const est = estimateCost(s, c.catalog);
431
+ const tokens = (s.input ?? 0) + (s.output ?? 0) + (s.cache_read ?? 0) + (s.cache_write_5m ?? 0) + (s.cache_write_1h ?? 0);
432
+ perAgent.push({ agente: a.name, modello: `${a.harness}:${s.model ?? a.model}`, token: tokens, stima: est.usd === null ? null : `$${est.usd}`, nota: est.note });
433
+ }
434
+ const inv = await currentInventory(c, cfg);
435
+ const credits = await currentCredits(c, cfg, inv, opts);
436
+ const advice = adviceFor(credits.rows, agents);
437
+ const data = { agents: perAgent, providers: credits.rows, advice };
438
+ emit(c, flags, data, () => [
439
+ 'Costo per agente (stima a listino API dai log locali)',
440
+ table(perAgent),
441
+ '',
442
+ 'Crediti per provider',
443
+ table(credits.rows.map((r) => ({ harness: r.harness, residuo: r.remaining_pct === null ? 'sconosciuto' : `${r.remaining_pct}%`, stato: r.status, fonte: r.source ?? r.detail }))),
444
+ '',
445
+ 'Indicazioni di delega',
446
+ ...advice.map((x) => `- ${x}`),
447
+ ].join('\n'));
448
+ return data;
449
+ }
450
+
451
+ export function adviceFor(rows, agents = []) {
452
+ const open = new Map();
453
+ for (const a of agents) if (a.state === 'open') open.set(a.harness, (open.get(a.harness) ?? 0) + 1);
454
+ const roomy = rows.filter((r) => r.status === 'ampio').map((r) => r.harness);
455
+ const out = [];
456
+ for (const r of rows) {
457
+ const n = open.get(r.harness) ?? 0;
458
+ const busy = n ? ` (agenti aperti: ${n})` : '';
459
+ if (r.status === 'esaurito') {
460
+ const reset = r.windows?.map((w) => w.resets_at).filter(Boolean).sort()[0];
461
+ out.push(`${r.harness}: crediti esauriti${busy} — non delegare${reset ? ` fino a ${reset}` : ''}${roomy.length ? `; sposta il lavoro su ${roomy.join(', ')}` : ''}.`);
462
+ } else if (r.status === 'scarso') {
463
+ out.push(`${r.harness}: crediti scarsi (${r.remaining_pct}%)${busy} — delega di meno${roomy.length ? `; preferisci ${roomy.join(', ')}` : ''}.`);
464
+ } else if (r.status === 'ampio') {
465
+ out.push(`${r.harness}: margine ampio (${r.remaining_pct}%)${busy} — può prendere più lavoro.`);
466
+ } else if (r.status === 'sconosciuto') {
467
+ out.push(`${r.harness}: crediti sconosciuti — attiva ${r.provider ?? 'il provider'} in CodexBar o dichiara un budget in .harma/config.json → budgets.${r.provider ?? '<provider>'}.`);
468
+ }
469
+ }
470
+ return out;
471
+ }
472
+
473
+ // 8 ─ cleanup and resume ───────────────────────────────────────────────────
474
+ export async function cmdCleanup(flags, opts = {}) {
475
+ const c = ctx(opts);
476
+ const cfg = loadConfig(c.root, { required: true });
477
+ const agents = agentsFromEvents(readEvents(c.root)).filter((a) => a.state === 'open' && (!flags.agent || a.name === flags.agent));
478
+ const live = await liveByBackend(c, cfg, agents, opts);
479
+ const report = [];
480
+ for (const a of agents) {
481
+ const l = findLive(a, live[a.backend]);
482
+ const status = l?.status ?? (live[a.backend] ? 'non trovato' : 'backend non raggiungibile');
483
+ if (!live[a.backend]) { report.push({ agente: a.name, azione: 'saltato', motivo: status }); continue; }
484
+ if (['working', 'blocked'].includes(status) && !flags.force) {
485
+ report.push({ agente: a.name, azione: 'tenuto', motivo: status === 'working' ? 'sta lavorando' : 'aspetta una risposta (blocked): leggilo con harma read' });
486
+ continue;
487
+ }
488
+ let sid = a.session_id ?? l?.sessionId ?? null;
489
+ let source = a.session_id ? 'registro' : (l?.sessionId ? a.backend : null);
490
+ if (!sid && a.harness === 'codex') { sid = findCodexSession({ env: c.env, cwd: a.cwd, sinceMs: Date.parse(a.started_at) }); source = sid ? 'log codex' : null; }
491
+ if (!sid && !flags.force && status !== 'non trovato') {
492
+ report.push({ agente: a.name, azione: 'tenuto', motivo: 'id di sessione non trovato: chiudendo si perde il contesto (usa --force per chiudere comunque)' });
493
+ continue;
494
+ }
495
+ if (flags['dry-run']) { report.push({ agente: a.name, azione: 'da chiudere', motivo: status, sessione: sid }); continue; }
496
+ if (sid && sid !== a.session_id) appendEvent(c.root, { type: 'session', agent: a.name, session_id: sid, source });
497
+ let closed = { ok: true, detail: 'già chiuso nel backend' };
498
+ if (status !== 'non trovato') {
499
+ const b = opts.backend?.name === a.backend ? opts.backend : backendFor(a, cfg, c.env);
500
+ closed = await b.close({ target: a.target?.name ?? a.name, tab: a.target?.tab });
501
+ }
502
+ if (closed.ok) appendEvent(c.root, { type: 'closed', agent: a.name, session_id: sid, last_status: status });
503
+ report.push({ agente: a.name, azione: closed.ok ? 'chiuso' : 'errore', motivo: closed.detail, sessione: sid });
504
+ }
505
+ // --workspace: close harma's own herdr workspace once no harma agent is open.
506
+ if (flags.workspace && !flags['dry-run'] && cfg.herdr?.workspace_id) {
507
+ const stillOpen = agentsFromEvents(readEvents(c.root)).filter((a) => a.state === 'open');
508
+ if (stillOpen.length) {
509
+ report.push({ agente: '(workspace)', azione: 'tenuto', motivo: `agenti ancora aperti: ${stillOpen.map((a) => a.name).join(', ')}` });
510
+ } else {
511
+ const b = opts.backend?.name === 'herdr' ? opts.backend : new HerdrBackend({ env: c.env, config: cfg });
512
+ const res = await b.closeWorkspace(cfg.herdr.workspace_id);
513
+ if (res.ok) { delete cfg.herdr.workspace_id; saveConfig(c.root, cfg); }
514
+ report.push({ agente: '(workspace)', azione: res.ok ? 'chiuso' : 'errore', motivo: res.detail });
515
+ }
516
+ }
517
+ emit(c, flags, { report }, () => [
518
+ flags['dry-run'] ? 'Anteprima pulizia (nulla è stato chiuso)' : 'Pulizia agenti',
519
+ table(report),
520
+ 'harma chiude solo terminali e tab che ha creato; ogni id di sessione resta in .harma/agents.jsonl.',
521
+ ].join('\n'));
522
+ return { report };
523
+ }
524
+
525
+ export async function cmdResume(flags, opts = {}) {
526
+ const c = ctx(opts);
527
+ const cfg = loadConfig(c.root, { required: true });
528
+ const name = flags._[0];
529
+ const a = agentsFromEvents(readEvents(c.root)).find((x) => x.name === name);
530
+ if (!a) throw new HarmaError(`Agente sconosciuto: ${name}`);
531
+ if (a.state === 'open') throw new HarmaError(`${name} è già aperto`, { hint: `harma read ${name}` });
532
+ if (!a.session_id) throw new HarmaError(`Nessun id di sessione salvato per ${name}`);
533
+ const base = resumeArgv(a.harness, a.session_id);
534
+ if (!base) throw new HarmaError(`Non so riprendere sessioni di ${a.harness}`, { hint: `id salvato: ${a.session_id}` });
535
+ const spec = launchSpec({ harness: a.harness, model: a.model, effort: a.effort }, c.catalog, { sessionId: a.session_id });
536
+ // resume argv + model/effort flags, without the "new session id" flag and its value
537
+ const flagsOnly = withoutFlag(spec.argv.slice(1), meta(a.harness).presetSession);
538
+ const argv = [...base, ...flagsOnly];
539
+ const gate = await dispatchGate(c, cfg, a.harness, flags, opts);
540
+ if (!gate.allowed || flags['print-only']) {
541
+ emit(c, flags, { needs_confirmation: !gate.allowed, argv, cwd: a.cwd }, () => [
542
+ gate.allowed ? 'Comando di ripresa:' : `CONFERMA RICHIESTA — ${gate.reason}`,
543
+ `cd ${a.cwd} && ${argv.join(' ')}`,
544
+ gate.allowed ? '' : 'Se l\'utente approva, ripeti con --yes per riaprirlo in un nuovo terminale.',
545
+ ].join('\n').trim());
546
+ return { needsConfirmation: !gate.allowed, argv, exitCode: gate.allowed ? 0 : EXIT_NEEDS_CONFIRM };
547
+ }
548
+ const backend = opts.backend ?? await selectBackend({ choice: flags.backend ?? a.backend, config: cfg, env: c.env });
549
+ const started = await backend.start({ name, cwd: a.cwd, argv, env: spec.env, harness: a.harness, root: c.root, project: projectId(c.root) });
550
+ if (started.workspaceCreated) { cfg.herdr = { ...(cfg.herdr ?? {}), workspace_id: started.workspace }; saveConfig(c.root, cfg); }
551
+ appendEvent(c.root, { type: 'resumed', agent: name, session_id: a.session_id, backend: backend.name, target: { name: started.target, tab: started.tab ?? null, pane: started.pane ?? null, address: started.address ?? null }, confirmed_by: gate.by });
552
+ c.out(flags.json ? JSON.stringify({ resumed: true, argv }) : `Ripreso ${name} (sessione ${a.session_id}) su ${backend.name}.`);
553
+ return { resumed: true, argv };
554
+ }
555
+
556
+ // select ─ the user validates or picks model + effort per job ─────────────
557
+ const BIN = fileURLToPath(new URL('../bin/harma.mjs', import.meta.url));
558
+
559
+ export async function cmdSelect(flags, opts = {}) {
560
+ const c = ctx(opts);
561
+ const cfg = loadConfig(c.root, { required: true });
562
+ if (flags.open) return openSelect(c, cfg, flags, opts);
563
+
564
+ if (!flags.json && !flags.show) c.out('Carico modelli, crediti e proposte…');
565
+ const inv = await currentInventory(c, cfg);
566
+ const credits = await currentCredits(c, cfg, inv, opts);
567
+ const rr = rankRows(c.catalog, inv.models);
568
+ const rows = selectionRows({ cfg, rankRowsArr: rr, credits: credits.rows });
569
+ const models = modelOptions(inv.models, rr, credits.rows);
570
+
571
+ if (flags.show) return showSelection(c, flags, rows);
572
+
573
+ let outcome;
574
+ let finalRows = rows;
575
+ if (flags.accept || flags.set) {
576
+ if (flags.accept) {
577
+ finalRows = finalRows.map((r) => (r.proposal ? { ...r, choice: { picks: [...r.proposal.picks], source: 'proposta' } } : r));
578
+ }
579
+ if (flags.set) {
580
+ const parsed = parseSetSpec(flags.set, { catalog: c.catalog, parseTarget, effortValues });
581
+ finalRows = finalRows.map((r) => (parsed[r.type] ? { ...r, choice: parsed[r.type] } : r));
582
+ }
583
+ outcome = 'save';
584
+ } else {
585
+ const input = opts.input ?? process.stdin;
586
+ const output = opts.output ?? process.stdout;
587
+ if (!input.isTTY || !output.isTTY) {
588
+ throw new HarmaError('harma select è interattivo e qui non c\'è un terminale', {
589
+ hint: 'Apri la TUI in un tab herdr con: harma select --open --wait · oppure senza TUI: harma select --accept | --set "sviluppo=codex:gpt-6.1-sol@high,…" | --show',
590
+ });
591
+ }
592
+ const orch = cfg.orchestrator ? describe(cfg.orchestrator) : 'non impostato';
593
+ const end = await (opts.runTui ?? runTui)(initState({ rows, models, title: 'harma · modelli del progetto', subtitle: `orchestratore ${orch} · ${c.root}` }), { input, output });
594
+ outcome = end.done;
595
+ finalRows = end.rows;
596
+ }
597
+
598
+ if (outcome !== 'save') {
599
+ writeCache(c.root, 'select-status', { state: 'cancelled', at: now() });
600
+ c.out(flags.json ? JSON.stringify({ saved: false }) : 'Nessuna modifica salvata.');
601
+ await closeOwnTab(flags, c.env);
602
+ return { saved: false };
603
+ }
604
+ const roster = applySelection(cfg, finalRows);
605
+ saveConfig(c.root, cfg);
606
+ appendEvent(c.root, { type: 'roster', orchestrator: cfg.orchestrator, roster });
607
+ writeCache(c.root, 'select-status', { state: 'saved', at: cfg.roster_updated_at });
608
+ showSelection(c, flags, finalRows, 'Scelte salvate in .harma/config.json');
609
+ await closeOwnTab(flags, c.env);
610
+ return { saved: true, orchestrator: cfg.orchestrator, roster };
611
+ }
612
+
613
+ function showSelection(c, flags, rows, heading = 'Modelli per lavoro') {
614
+ const data = rows.map((r) => ({
615
+ lavoro: r.type,
616
+ proposta: describe(r.proposal),
617
+ scelta: describe(r.choice),
618
+ fonte: !r.choice ? '—' : r.type === ORCHESTRATOR ? 'configurato' : (r.choice.none ? 'utente' : r.choice.source === 'proposta' ? 'proposta accettata' : 'utente'),
619
+ }));
620
+ // One block per job: the choice can be several models long, a table would wrap.
621
+ emit(c, flags, { rows: data }, () => [heading, ...data.flatMap((d) => [
622
+ `${d.lavoro}: ${d.scelta}${d.fonte !== '—' ? ` (${d.fonte})` : ''}`,
623
+ ...(d.proposta !== d.scelta ? [` proposta: ${d.proposta}`] : []),
624
+ ])].join('\n'));
625
+ return { rows: data };
626
+ }
627
+
628
+ /** Inside a herdr tab opened by --open: close it when the TUI ends. */
629
+ async function closeOwnTab(flags, env) {
630
+ if (flags['close-tab'] && env.HERDR_TAB_ID) await run('herdr', ['tab', 'close', env.HERDR_TAB_ID], { env });
631
+ }
632
+
633
+ /** Open the TUI where the user can see it (a focused herdr tab, or an hc terminal); optionally wait. */
634
+ async function openSelect(c, cfg, flags, opts) {
635
+ const startedAt = now();
636
+ const cmd = [process.execPath, BIN, 'select', '--close-tab'].map(shq).join(' ');
637
+ const backend = opts.backend ?? await selectBackend({ choice: flags.backend, config: cfg, env: c.env });
638
+ let where;
639
+ if (backend.name === 'herdr') {
640
+ const tab = await backend.openTab({ root: c.root, project: projectId(c.root), label: 'harma-select', command: cmd });
641
+ if (tab.workspaceCreated) {
642
+ // Re-read: the TUI may already have saved choices into config.json.
643
+ const fresh = loadConfig(c.root);
644
+ fresh.herdr = { ...(fresh.herdr ?? {}), workspace_id: tab.workspace };
645
+ saveConfig(c.root, fresh);
646
+ }
647
+ where = `tab herdr ${tab.tab} (in primo piano)`;
648
+ } else {
649
+ await backend.exec(['run', '--bg', '--json', '--name', 'harma-select', '--cwd', c.root, '--no-parent', '--', process.execPath, BIN, 'select']);
650
+ where = 'terminale hc "harma-select": aprilo con hc attach harma-select';
651
+ }
652
+ if (!flags.wait) {
653
+ emit(c, flags, { opened: true, where }, () => `Selezione aperta nel ${where}. Quando l'utente salva: harma select --show`);
654
+ return { opened: true };
655
+ }
656
+ if (!flags.json) c.out(`Selezione aperta nel ${where}. Attendo che l'utente salvi o esca…`);
657
+ const timeoutMs = Number(flags.timeout ?? 900) * 1000;
658
+ const deadline = Date.now() + timeoutMs;
659
+ const poll = opts.pollMs ?? 1500;
660
+ while (Date.now() < deadline) {
661
+ const st = readJson(statePath(c.root, 'cache', 'select-status.json'));
662
+ if (st && st.at > startedAt) {
663
+ if (st.state !== 'saved') {
664
+ emit(c, flags, { saved: false }, () => 'L\'utente è uscito senza salvare.');
665
+ return { saved: false };
666
+ }
667
+ const fresh = loadConfig(c.root);
668
+ const data = { saved: true, orchestrator: fresh.orchestrator, roster: fresh.roster };
669
+ emit(c, flags, data, () => ['Scelte dell\'utente:', `orchestratore: ${describe(fresh.orchestrator)}`,
670
+ ...Object.entries(fresh.roster ?? {}).map(([t, v]) => `${t}: ${describe(v)} (${v.source})`)].join('\n'));
671
+ return data;
672
+ }
673
+ await new Promise((r) => setTimeout(r, poll));
674
+ }
675
+ throw new HarmaError(`Nessuna risposta dalla selezione entro ${timeoutMs / 1000}s`, { hint: 'Il tab resta aperto: riprova con harma select --show più tardi' });
676
+ }
677
+
678
+ const shq = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${String(s).replace(/'/g, `'\\''`)}'`);
679
+
680
+ export { DEFAULT_CONFIG, taskProfile };