harma-kit 0.0.0-stage → 0.1.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,522 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { loadCatalog } 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 } from './util.mjs';
16
+
17
+ export const EXIT_NEEDS_CONFIRM = 3;
18
+ export const EXIT_BLOCKED = 4; // agent started, waiting on a dialog; task not delivered
19
+ const CREDIT_TTL_MS = 15 * 60_000;
20
+
21
+ function ctx(opts) {
22
+ const env = opts.env ?? process.env;
23
+ const root = projectRoot(opts.cwd ?? process.cwd());
24
+ const catalog = loadCatalog({ env });
25
+ return { env, root, catalog, out: opts.out ?? ((s) => process.stdout.write(s + '\n')) };
26
+ }
27
+
28
+ const emit = (c, flags, data, text) => c.out(flags.json ? JSON.stringify(data, null, 2) : text());
29
+
30
+ // 1 ─ orchestrator ─────────────────────────────────────────────────────────
31
+ export async function cmdInit(flags, opts = {}) {
32
+ const c = ctx(opts);
33
+ const root = resolve(opts.cwd ?? process.cwd());
34
+ const cfg = loadConfig(root);
35
+ if (!flags.orchestrator) throw new HarmaError('Manca --orchestrator <harness>:<model>', { hint: 'es. harma init --orchestrator claude:claude-opus-5-5 --effort high' });
36
+ const t = parseTarget(flags.orchestrator, c.catalog);
37
+ const allowed = effortValues(t.harness, t.model, c.catalog);
38
+ const effort = flags.effort ?? c.catalog.models?.[t.model]?.effort_default ?? null;
39
+ if (effort && allowed.length && !allowed.includes(effort)) {
40
+ throw new HarmaError(`Effort ${effort} non supportato da ${t.harness}:${t.model}`, { hint: `Valori: ${allowed.join(', ')}` });
41
+ }
42
+ cfg.orchestrator = { harness: t.harness, model: t.model, effort, set_at: now() };
43
+ if (flags.backend) cfg.backend = flags.backend;
44
+ if (flags.policy) {
45
+ if (!['confirm', 'auto-within-budget'].includes(flags.policy)) throw new HarmaError('--policy: confirm | auto-within-budget');
46
+ cfg.dispatch_policy = flags.policy;
47
+ }
48
+ saveConfig(root, cfg);
49
+ appendEvent(root, { type: 'orchestrator', ...cfg.orchestrator });
50
+ emit({ ...c, root }, flags, cfg, () => [
51
+ `Progetto harma: ${root}`,
52
+ `Orchestratore: ${t.harness}:${t.model} @ ${effort ?? 'default'}`,
53
+ `Backend: ${cfg.backend} · Policy di delega: ${cfg.dispatch_policy}`,
54
+ 'Prossimi passi: harma models · harma credits · harma rank',
55
+ ].join('\n'));
56
+ return cfg;
57
+ }
58
+
59
+ // 2 ─ inventory ────────────────────────────────────────────────────────────
60
+ export async function cmdModels(flags, opts = {}) {
61
+ const c = ctx(opts);
62
+ const cfg = loadConfig(c.root);
63
+ const inv = await inventory({ catalog: c.catalog, env: c.env, config: cfg });
64
+ if (hasProject(c.root)) writeCache(c.root, 'inventory', inv);
65
+ emit(c, flags, inv, () => [
66
+ 'CLI di agenti',
67
+ table(inv.clis, ['harness', 'state', 'version', 'billing', 'effort_via']),
68
+ '',
69
+ 'Modelli utilizzabili',
70
+ table(inv.models.map((m) => ({ ...m, efforts: m.efforts.join(','), in_catalog: m.in_catalog ? 'sì' : 'no' })),
71
+ ['harness', 'model', 'efforts', 'default_effort', 'in_catalog', 'source']),
72
+ ].join('\n'));
73
+ return inv;
74
+ }
75
+
76
+ async function currentInventory(c, cfg, { fresh = false } = {}) {
77
+ const cached = !fresh && hasProject(c.root) ? readCache(c.root, 'inventory') : null;
78
+ return cached ?? inventory({ catalog: c.catalog, env: c.env, config: cfg, versions: false });
79
+ }
80
+
81
+ // 3 ─ credits ──────────────────────────────────────────────────────────────
82
+ export async function cmdCredits(flags, opts = {}) {
83
+ const c = ctx(opts);
84
+ const cfg = loadConfig(c.root);
85
+ const inv = await currentInventory(c, cfg);
86
+ const names = inv.clis.filter((x) => x.state === 'installato').map((x) => x.harness);
87
+ const credits = await collectCredits({ harnessNames: names, config: cfg, catalog: c.catalog, env: c.env, codexbar: opts.codexbar });
88
+ if (hasProject(c.root)) writeCache(c.root, 'credits', credits);
89
+ emit(c, flags, credits, () => [
90
+ `Crediti (${credits.fetched_at}; codexbar: ${credits.codexbar})`,
91
+ table(credits.rows.map((r) => ({
92
+ harness: r.harness,
93
+ provider: r.provider,
94
+ residuo: r.remaining_pct === null ? 'sconosciuto' : `${r.remaining_pct}%`,
95
+ stato: r.status,
96
+ finestre: r.windows.map((w) => `${w.window} ${w.used_pct}%`).join(' ') || null,
97
+ 'stima 7g': r.estimate ? `$${r.estimate.usd}` : null,
98
+ fonte: r.source ?? r.detail,
99
+ }))),
100
+ '',
101
+ 'Stima 7g = token dei log locali × listino API: per un abbonamento non è l\'addebito reale.',
102
+ ].join('\n'));
103
+ return credits;
104
+ }
105
+
106
+ async function currentCredits(c, cfg, inv, opts) {
107
+ const cached = hasProject(c.root) ? readCache(c.root, 'credits') : null;
108
+ if (cached && Date.now() - Date.parse(cached.fetched_at) < CREDIT_TTL_MS) return cached;
109
+ const names = inv.clis.filter((x) => x.state === 'installato').map((x) => x.harness);
110
+ const credits = await collectCredits({ harnessNames: names, config: cfg, catalog: c.catalog, env: c.env, codexbar: opts.codexbar });
111
+ if (hasProject(c.root)) writeCache(c.root, 'credits', credits);
112
+ return credits;
113
+ }
114
+
115
+ // 4 ─ intelligence ─────────────────────────────────────────────────────────
116
+ export async function cmdRank(flags, opts = {}) {
117
+ let c = ctx(opts);
118
+ let refresh = null;
119
+ if (flags.refresh) {
120
+ refresh = await refreshFromAA(c.catalog, { env: c.env, fetchImpl: opts.fetchImpl });
121
+ c = ctx(opts);
122
+ }
123
+ const cfg = loadConfig(c.root);
124
+ const inv = await currentInventory(c, cfg);
125
+ const rows = rankRows(c.catalog, inv.models);
126
+ const top = Number(flags.top ?? rows.length);
127
+ const data = { catalog: { origin: c.catalog.origin, generated_at: c.catalog.generated_at, attribution: c.catalog.attribution }, refresh, rows: rows.slice(0, top) };
128
+ if (hasProject(c.root)) writeCache(c.root, 'rank', { fetched_at: now(), ...data });
129
+ emit(c, flags, data, () => [
130
+ `Intelligenza per modello × effort — ${c.catalog.attribution}`,
131
+ `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` : ''}`,
132
+ table(rows.slice(0, top).map((r) => ({
133
+ harness: r.harness, model: r.model, effort: r.effort,
134
+ indice: r.index ?? 'sconosciuto', 'costo/task': r.cost_per_task === null ? '—' : `$${r.cost_per_task}`, 'data AA': r.aa_date,
135
+ }))),
136
+ ].join('\n'));
137
+ return data;
138
+ }
139
+
140
+ // 5 ─ routing ──────────────────────────────────────────────────────────────
141
+ export async function cmdRoute(flags, opts = {}) {
142
+ const c = ctx(opts);
143
+ const cfg = loadConfig(c.root);
144
+ const type = flags._[0];
145
+ if (!type) throw new HarmaError('Manca il tipo di lavoro', { hint: `Tipi: ${Object.keys(TASK_PROFILES).join(', ')}` });
146
+ const inv = await currentInventory(c, cfg);
147
+ const credits = await currentCredits(c, cfg, inv, opts);
148
+ const author = flags.author ? authorOf(flags.author, c.catalog) : null;
149
+ const res = route(type, { rankRows: rankRows(c.catalog, inv.models), credits: credits.rows, config: cfg, author, top: Number(flags.top ?? 5) });
150
+ if (!res) throw new HarmaError(`Tipo di lavoro sconosciuto: ${type}`, { hint: `Tipi: ${Object.keys(TASK_PROFILES).join(', ')}` });
151
+ emit(c, flags, res, () => [
152
+ `Routing — ${res.profile.label}`,
153
+ table(res.candidates.map((r, i) => ({ '#': i + 1, modello: `${r.harness}:${r.model}`, effort: r.effort, punteggio: r.score, motivi: r.why }))),
154
+ 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.',
155
+ ].join('\n'));
156
+ return res;
157
+ }
158
+
159
+ function authorOf(spec, catalog) {
160
+ const t = parseTarget(spec, catalog);
161
+ return { ...t, provider: catalog.models?.[t.model]?.provider ?? null };
162
+ }
163
+
164
+ // 5b ─ dispatch ────────────────────────────────────────────────────────────
165
+ export async function cmdDispatch(flags, opts = {}) {
166
+ const c = ctx(opts);
167
+ const cfg = loadConfig(c.root, { required: true });
168
+ checkAgentName(flags.name);
169
+ const existing = agentsFromEvents(readEvents(c.root)).find((a) => a.name === flags.name && a.state === 'open');
170
+ if (existing) throw new HarmaError(`L'agente ${flags.name} è già aperto`, { hint: 'Scegli un altro nome, o `harma send` per dargli altro lavoro' });
171
+
172
+ let pick;
173
+ if (flags.model) {
174
+ const t = parseTarget(flags.model, c.catalog);
175
+ pick = { harness: t.harness, model: t.model, effort: flags.effort ?? c.catalog.models?.[t.model]?.effort_default ?? null, why: 'scelto esplicitamente' };
176
+ } else {
177
+ if (!flags['task-type']) throw new HarmaError('Serve --model <harness>:<model> oppure --task-type <tipo>');
178
+ const inv = await currentInventory(c, cfg);
179
+ const credits = await currentCredits(c, cfg, inv, opts);
180
+ 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 });
181
+ if (!res?.candidates.length) throw new HarmaError(`Nessun modello adatto per ${flags['task-type']}`);
182
+ pick = { ...res.candidates[0], why: `routing ${res.profile.type}: ${res.candidates[0].why}` };
183
+ }
184
+ const prompt = flags['prompt-file'] ? readFileSync(flags['prompt-file'], 'utf8') : flags.prompt ?? null;
185
+ const cwd = resolve(flags.cwd ?? c.root);
186
+ const spec = launchSpec(pick, c.catalog);
187
+ if (!which(spec.argv[0], c.env)) {
188
+ throw new HarmaError(`${spec.argv[0]} non è installato su questa macchina`, { hint: 'Vedi harma models per le CLI disponibili' });
189
+ }
190
+ const plan = {
191
+ agent: flags.name, task_type: flags['task-type'] ?? null,
192
+ harness: pick.harness, model: pick.model, effort: pick.effort, why: pick.why,
193
+ cwd, argv: spec.argv, env: spec.env, notes: spec.notes,
194
+ prompt_chars: prompt?.length ?? 0, policy: cfg.dispatch_policy,
195
+ };
196
+
197
+ const gate = await dispatchGate(c, cfg, pick.harness, flags, opts);
198
+ if (!gate.allowed) {
199
+ emit(c, flags, { needs_confirmation: true, reason: gate.reason, plan }, () => [
200
+ 'CONFERMA RICHIESTA — nessun agente è stato avviato.',
201
+ `Motivo: ${gate.reason}`,
202
+ `Agente ${plan.agent}: ${plan.harness}:${plan.model} @ ${plan.effort ?? 'default'} (${plan.why})`,
203
+ `Comando: ${plan.argv.join(' ')}${Object.keys(plan.env).length ? ` env ${JSON.stringify(plan.env)}` : ''}`,
204
+ ...plan.notes.map((n) => `Nota: ${n}`),
205
+ 'Se l\'utente approva, ripeti lo stesso comando con --yes.',
206
+ ].join('\n'));
207
+ return { needsConfirmation: true, plan, exitCode: EXIT_NEEDS_CONFIRM };
208
+ }
209
+
210
+ const backend = opts.backend ?? await selectBackend({ choice: flags.backend, config: cfg, env: c.env });
211
+ const project = projectId(c.root);
212
+ const startedMs = Date.now();
213
+ const started = await backend.start({ name: flags.name, cwd, argv: spec.argv, env: spec.env, harness: pick.harness, root: c.root, project });
214
+ if (started.workspaceCreated) { cfg.herdr = { ...(cfg.herdr ?? {}), workspace_id: started.workspace }; saveConfig(c.root, cfg); }
215
+ appendEvent(c.root, {
216
+ type: 'started', agent: flags.name, harness: pick.harness, model: pick.model, effort: pick.effort,
217
+ 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 },
218
+ cwd, session_id: spec.sessionId, why: pick.why, confirmed_by: gate.by, started_ms: startedMs,
219
+ });
220
+ let sid = spec.sessionId ?? await discoverSession(backend, { name: started.target, harness: pick.harness, cwd, sinceMs: startedMs, env: c.env });
221
+ if (sid && sid !== spec.sessionId) appendEvent(c.root, { type: 'session', agent: flags.name, session_id: sid, source: backend.name });
222
+ let promptState = prompt ? 'sent' : 'none';
223
+ if (prompt) {
224
+ try {
225
+ await backend.prompt(started.target, prompt, { wait: Boolean(flags.wait), timeoutSec: Number(flags.timeout ?? 600) });
226
+ appendEvent(c.root, { type: 'prompted', agent: flags.name, chars: prompt.length });
227
+ } catch (e) {
228
+ if (e.code !== 'agent_blocked') throw e;
229
+ // Started and recorded, but waiting on a dialog (e.g. folder trust): the user must answer it.
230
+ promptState = 'blocked';
231
+ appendEvent(c.root, { type: 'blocked', agent: flags.name, detail: 'prompt non inviato: l\'agente aspetta un input' });
232
+ }
233
+ }
234
+ if (!sid && promptState === 'sent') {
235
+ // Codex registers its session on the first turn: look again now.
236
+ sid = await discoverSession(backend, { name: started.target, harness: pick.harness, cwd, sinceMs: startedMs, env: c.env });
237
+ if (sid) appendEvent(c.root, { type: 'session', agent: flags.name, session_id: sid, source: backend.name });
238
+ }
239
+ const result = { started: true, plan, target: started, session_id: sid ?? null, prompt: promptState, exitCode: promptState === 'blocked' ? EXIT_BLOCKED : 0 };
240
+ emit(c, flags, result, () => [
241
+ `Avviato ${flags.name}: ${pick.harness}:${pick.model} @ ${pick.effort ?? 'default'} su ${backend.name} (${started.tab ?? started.address ?? started.target})`,
242
+ `Sessione: ${sid ?? 'non ancora nota (verrà letta alla chiusura)'}`,
243
+ promptState === 'sent' ? `Compito inviato (${prompt.length} caratteri)${flags.wait ? '; atteso fino a stato stabile' : ''}.`
244
+ : 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`
245
+ : 'Nessun compito inviato: usa harma send.',
246
+ ...plan.notes.map((n) => `Nota: ${n}`),
247
+ ].join('\n'));
248
+ return result;
249
+ }
250
+
251
+ /** Policy check. confirm: only --yes. auto-within-budget: provider credits ok/ampio. */
252
+ async function dispatchGate(c, cfg, harness, flags, opts) {
253
+ if (flags.yes) return { allowed: true, by: 'utente (--yes)' };
254
+ if (cfg.dispatch_policy !== 'auto-within-budget') {
255
+ return { allowed: false, reason: 'policy "confirm": ogni avvio di agente richiede il consenso esplicito dell\'utente' };
256
+ }
257
+ const inv = await currentInventory(c, cfg);
258
+ const credits = await currentCredits(c, cfg, inv, opts);
259
+ const row = credits.rows.find((r) => r.harness === harness);
260
+ if (row && ['ok', 'ampio'].includes(row.status)) return { allowed: true, by: `policy auto-within-budget (crediti ${row.status})` };
261
+ return { allowed: false, reason: `policy auto-within-budget: crediti ${harness} ${row?.status ?? 'sconosciuti'}` };
262
+ }
263
+
264
+ async function discoverSession(backend, { name, harness, cwd, sinceMs, env }) {
265
+ if (backend.name === 'herdr') {
266
+ try {
267
+ const live = (await backend.list()).find((a) => a.name === name || a.target === name);
268
+ if (live?.sessionId) return live.sessionId;
269
+ } catch { /* fall through */ }
270
+ }
271
+ if (harness === 'codex') return findCodexSession({ env, cwd, sinceMs });
272
+ return null;
273
+ }
274
+
275
+ // send / read ──────────────────────────────────────────────────────────────
276
+ export async function cmdSend(flags, opts = {}) {
277
+ const c = ctx(opts);
278
+ const cfg = loadConfig(c.root, { required: true });
279
+ const [name, ...rest] = flags._;
280
+ const text = flags['prompt-file'] ? readFileSync(flags['prompt-file'], 'utf8') : rest.join(' ');
281
+ const agent = openAgent(c, name);
282
+ if (!text) throw new HarmaError('Manca il testo da inviare');
283
+ const gate = await dispatchGate(c, cfg, agent.harness, flags, opts);
284
+ if (!gate.allowed) {
285
+ emit(c, flags, { needs_confirmation: true, reason: gate.reason, agent: name, chars: text.length }, () =>
286
+ `CONFERMA RICHIESTA — nulla è stato inviato a ${name}.\nMotivo: ${gate.reason}\nSe l'utente approva, ripeti con --yes.`);
287
+ return { needsConfirmation: true, exitCode: EXIT_NEEDS_CONFIRM };
288
+ }
289
+ const backend = opts.backend ?? backendFor(agent, cfg, c.env);
290
+ await backend.prompt(agent.target?.name ?? name, text, { wait: Boolean(flags.wait), timeoutSec: Number(flags.timeout ?? 600) });
291
+ appendEvent(c.root, { type: 'prompted', agent: name, chars: text.length, confirmed_by: gate.by });
292
+ c.out(flags.json ? JSON.stringify({ sent: true }) : `Inviato a ${name} (${text.length} caratteri).`);
293
+ return { sent: true };
294
+ }
295
+
296
+ export async function cmdRead(flags, opts = {}) {
297
+ const c = ctx(opts);
298
+ const cfg = loadConfig(c.root, { required: true });
299
+ const agent = openAgent(c, flags._[0]);
300
+ const backend = opts.backend ?? backendFor(agent, cfg, c.env);
301
+ const text = await backend.read(agent.target?.name ?? agent.name, Number(flags.lines ?? 120));
302
+ c.out(text);
303
+ return text;
304
+ }
305
+
306
+ function openAgent(c, name) {
307
+ if (!name) throw new HarmaError('Manca il nome dell\'agente');
308
+ const a = agentsFromEvents(readEvents(c.root)).find((x) => x.name === name);
309
+ if (!a) throw new HarmaError(`Agente sconosciuto: ${name}`, { hint: 'Vedi harma status' });
310
+ if (a.state !== 'open') throw new HarmaError(`L'agente ${name} è chiuso`, { hint: `harma resume ${name}` });
311
+ return a;
312
+ }
313
+
314
+ function backendFor(agent, cfg, env) {
315
+ return agent.backend === 'hc' ? new HcBackend({ env }) : new HerdrBackend({ env, config: cfg });
316
+ }
317
+
318
+ // 6 ─ monitoring ───────────────────────────────────────────────────────────
319
+ export async function cmdStatus(flags, opts = {}) {
320
+ const c = ctx(opts);
321
+ const cfg = loadConfig(c.root, { required: true });
322
+ const agents = agentsFromEvents(readEvents(c.root));
323
+ const live = await liveByBackend(c, cfg, agents, opts);
324
+ const rows = agents.filter((a) => flags.all || a.state === 'open').map((a) => {
325
+ const l = findLive(a, live[a.backend]);
326
+ return {
327
+ agente: a.name,
328
+ modello: `${a.harness}:${a.model}`,
329
+ effort: a.effort,
330
+ lavoro: a.task_type,
331
+ registro: a.state === 'open' ? 'aperto' : 'chiuso',
332
+ stato: a.state === 'closed' ? '—' : (l ? (l.status ?? 'nessuno stato') : (live[a.backend] ? 'non trovato' : 'backend non raggiungibile')),
333
+ backend: `${a.backend} ${a.target?.tab ?? a.target?.address ?? ''}`.trim(),
334
+ da: a.started_at ? ago(a.started_at) : null,
335
+ sessione: a.session_id ? a.session_id.slice(0, 8) + '…' : (l?.sessionId ? l.sessionId.slice(0, 8) + '…' : null),
336
+ };
337
+ });
338
+ const data = { orchestrator: cfg.orchestrator, policy: cfg.dispatch_policy, agents: rows };
339
+ emit(c, flags, data, () => [
340
+ `Orchestratore: ${cfg.orchestrator ? `${cfg.orchestrator.harness}:${cfg.orchestrator.model} @ ${cfg.orchestrator.effort}` : 'non impostato'} · policy ${cfg.dispatch_policy}`,
341
+ table(rows),
342
+ ].join('\n'));
343
+ return data;
344
+ }
345
+
346
+ async function liveByBackend(c, cfg, agents, opts) {
347
+ const out = {};
348
+ const used = new Set(agents.filter((a) => a.state === 'open').map((a) => a.backend));
349
+ for (const name of used) {
350
+ const b = opts.backend?.name === name ? opts.backend : (name === 'hc' ? new HcBackend({ env: c.env }) : new HerdrBackend({ env: c.env, config: cfg }));
351
+ try { out[name] = await b.list(projectId(c.root)); } catch { out[name] = null; }
352
+ }
353
+ return out;
354
+ }
355
+
356
+ /** Drop `flag` and the value after it; with no flag, return args unchanged. */
357
+ export function withoutFlag(args, flag) {
358
+ if (!flag) return [...args];
359
+ const i = args.indexOf(flag);
360
+ return i < 0 ? [...args] : [...args.slice(0, i), ...args.slice(i + 2)];
361
+ }
362
+
363
+ /** The live terminal of a registered agent: by pane (herdr), address (hc), then name. */
364
+ export function findLive(a, list) {
365
+ if (!list) return null;
366
+ const t = a.target ?? {};
367
+ return list.find((x) => t.pane && x.pane === t.pane)
368
+ ?? list.find((x) => t.address && x.address === t.address)
369
+ ?? list.find((x) => x.name && x.name === (t.name ?? a.name))
370
+ ?? null;
371
+ }
372
+
373
+ function ago(iso) {
374
+ const m = Math.round((Date.now() - Date.parse(iso)) / 60_000);
375
+ return m < 60 ? `${m} min` : m < 1440 ? `${Math.round(m / 60)} h` : `${Math.round(m / 1440)} g`;
376
+ }
377
+
378
+ // 7 ─ costs ────────────────────────────────────────────────────────────────
379
+ export async function cmdCosts(flags, opts = {}) {
380
+ const c = ctx(opts);
381
+ const cfg = loadConfig(c.root, { required: true });
382
+ const agents = agentsFromEvents(readEvents(c.root));
383
+ // An open agent's id may be known to the backend before harma records it.
384
+ const live = await liveByBackend(c, cfg, agents.filter((a) => !a.session_id), opts);
385
+ for (const a of agents) {
386
+ if (!a.session_id && a.state === 'open') a.session_id = findLive(a, live[a.backend])?.sessionId ?? null;
387
+ }
388
+ const perAgent = [];
389
+ for (const a of agents) {
390
+ if (!a.session_id || !meta(a.harness).logs) {
391
+ 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' });
392
+ continue;
393
+ }
394
+ const s = usageFor(a.harness, { env: c.env, sessionIds: [a.session_id] })[0];
395
+ if (!s) { perAgent.push({ agente: a.name, modello: `${a.harness}:${a.model}`, token: 0, stima: null, nota: 'sessione senza consumi registrati' }); continue; }
396
+ const est = estimateCost(s, c.catalog);
397
+ const tokens = (s.input ?? 0) + (s.output ?? 0) + (s.cache_read ?? 0) + (s.cache_write_5m ?? 0) + (s.cache_write_1h ?? 0);
398
+ perAgent.push({ agente: a.name, modello: `${a.harness}:${s.model ?? a.model}`, token: tokens, stima: est.usd === null ? null : `$${est.usd}`, nota: est.note });
399
+ }
400
+ const inv = await currentInventory(c, cfg);
401
+ const credits = await currentCredits(c, cfg, inv, opts);
402
+ const advice = adviceFor(credits.rows, agents);
403
+ const data = { agents: perAgent, providers: credits.rows, advice };
404
+ emit(c, flags, data, () => [
405
+ 'Costo per agente (stima a listino API dai log locali)',
406
+ table(perAgent),
407
+ '',
408
+ 'Crediti per provider',
409
+ 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 }))),
410
+ '',
411
+ 'Indicazioni di delega',
412
+ ...advice.map((x) => `- ${x}`),
413
+ ].join('\n'));
414
+ return data;
415
+ }
416
+
417
+ export function adviceFor(rows, agents = []) {
418
+ const open = new Map();
419
+ for (const a of agents) if (a.state === 'open') open.set(a.harness, (open.get(a.harness) ?? 0) + 1);
420
+ const roomy = rows.filter((r) => r.status === 'ampio').map((r) => r.harness);
421
+ const out = [];
422
+ for (const r of rows) {
423
+ const n = open.get(r.harness) ?? 0;
424
+ const busy = n ? ` (agenti aperti: ${n})` : '';
425
+ if (r.status === 'esaurito') {
426
+ const reset = r.windows?.map((w) => w.resets_at).filter(Boolean).sort()[0];
427
+ out.push(`${r.harness}: crediti esauriti${busy} — non delegare${reset ? ` fino a ${reset}` : ''}${roomy.length ? `; sposta il lavoro su ${roomy.join(', ')}` : ''}.`);
428
+ } else if (r.status === 'scarso') {
429
+ out.push(`${r.harness}: crediti scarsi (${r.remaining_pct}%)${busy} — delega di meno${roomy.length ? `; preferisci ${roomy.join(', ')}` : ''}.`);
430
+ } else if (r.status === 'ampio') {
431
+ out.push(`${r.harness}: margine ampio (${r.remaining_pct}%)${busy} — può prendere più lavoro.`);
432
+ } else if (r.status === 'sconosciuto') {
433
+ 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>'}.`);
434
+ }
435
+ }
436
+ return out;
437
+ }
438
+
439
+ // 8 ─ cleanup and resume ───────────────────────────────────────────────────
440
+ export async function cmdCleanup(flags, opts = {}) {
441
+ const c = ctx(opts);
442
+ const cfg = loadConfig(c.root, { required: true });
443
+ const agents = agentsFromEvents(readEvents(c.root)).filter((a) => a.state === 'open' && (!flags.agent || a.name === flags.agent));
444
+ const live = await liveByBackend(c, cfg, agents, opts);
445
+ const report = [];
446
+ for (const a of agents) {
447
+ const l = findLive(a, live[a.backend]);
448
+ const status = l?.status ?? (live[a.backend] ? 'non trovato' : 'backend non raggiungibile');
449
+ if (!live[a.backend]) { report.push({ agente: a.name, azione: 'saltato', motivo: status }); continue; }
450
+ if (['working', 'blocked'].includes(status) && !flags.force) {
451
+ report.push({ agente: a.name, azione: 'tenuto', motivo: status === 'working' ? 'sta lavorando' : 'aspetta una risposta (blocked): leggilo con harma read' });
452
+ continue;
453
+ }
454
+ let sid = a.session_id ?? l?.sessionId ?? null;
455
+ let source = a.session_id ? 'registro' : (l?.sessionId ? a.backend : null);
456
+ if (!sid && a.harness === 'codex') { sid = findCodexSession({ env: c.env, cwd: a.cwd, sinceMs: Date.parse(a.started_at) }); source = sid ? 'log codex' : null; }
457
+ if (!sid && !flags.force && status !== 'non trovato') {
458
+ report.push({ agente: a.name, azione: 'tenuto', motivo: 'id di sessione non trovato: chiudendo si perde il contesto (usa --force per chiudere comunque)' });
459
+ continue;
460
+ }
461
+ if (flags['dry-run']) { report.push({ agente: a.name, azione: 'da chiudere', motivo: status, sessione: sid }); continue; }
462
+ if (sid && sid !== a.session_id) appendEvent(c.root, { type: 'session', agent: a.name, session_id: sid, source });
463
+ let closed = { ok: true, detail: 'già chiuso nel backend' };
464
+ if (status !== 'non trovato') {
465
+ const b = opts.backend?.name === a.backend ? opts.backend : backendFor(a, cfg, c.env);
466
+ closed = await b.close({ target: a.target?.name ?? a.name, tab: a.target?.tab });
467
+ }
468
+ if (closed.ok) appendEvent(c.root, { type: 'closed', agent: a.name, session_id: sid, last_status: status });
469
+ report.push({ agente: a.name, azione: closed.ok ? 'chiuso' : 'errore', motivo: closed.detail, sessione: sid });
470
+ }
471
+ // --workspace: close harma's own herdr workspace once no harma agent is open.
472
+ if (flags.workspace && !flags['dry-run'] && cfg.herdr?.workspace_id) {
473
+ const stillOpen = agentsFromEvents(readEvents(c.root)).filter((a) => a.state === 'open');
474
+ if (stillOpen.length) {
475
+ report.push({ agente: '(workspace)', azione: 'tenuto', motivo: `agenti ancora aperti: ${stillOpen.map((a) => a.name).join(', ')}` });
476
+ } else {
477
+ const b = opts.backend?.name === 'herdr' ? opts.backend : new HerdrBackend({ env: c.env, config: cfg });
478
+ const res = await b.closeWorkspace(cfg.herdr.workspace_id);
479
+ if (res.ok) { delete cfg.herdr.workspace_id; saveConfig(c.root, cfg); }
480
+ report.push({ agente: '(workspace)', azione: res.ok ? 'chiuso' : 'errore', motivo: res.detail });
481
+ }
482
+ }
483
+ emit(c, flags, { report }, () => [
484
+ flags['dry-run'] ? 'Anteprima pulizia (nulla è stato chiuso)' : 'Pulizia agenti',
485
+ table(report),
486
+ 'harma chiude solo terminali e tab che ha creato; ogni id di sessione resta in .harma/agents.jsonl.',
487
+ ].join('\n'));
488
+ return { report };
489
+ }
490
+
491
+ export async function cmdResume(flags, opts = {}) {
492
+ const c = ctx(opts);
493
+ const cfg = loadConfig(c.root, { required: true });
494
+ const name = flags._[0];
495
+ const a = agentsFromEvents(readEvents(c.root)).find((x) => x.name === name);
496
+ if (!a) throw new HarmaError(`Agente sconosciuto: ${name}`);
497
+ if (a.state === 'open') throw new HarmaError(`${name} è già aperto`, { hint: `harma read ${name}` });
498
+ if (!a.session_id) throw new HarmaError(`Nessun id di sessione salvato per ${name}`);
499
+ const base = resumeArgv(a.harness, a.session_id);
500
+ if (!base) throw new HarmaError(`Non so riprendere sessioni di ${a.harness}`, { hint: `id salvato: ${a.session_id}` });
501
+ const spec = launchSpec({ harness: a.harness, model: a.model, effort: a.effort }, c.catalog, { sessionId: a.session_id });
502
+ // resume argv + model/effort flags, without the "new session id" flag and its value
503
+ const flagsOnly = withoutFlag(spec.argv.slice(1), meta(a.harness).presetSession);
504
+ const argv = [...base, ...flagsOnly];
505
+ const gate = await dispatchGate(c, cfg, a.harness, flags, opts);
506
+ if (!gate.allowed || flags['print-only']) {
507
+ emit(c, flags, { needs_confirmation: !gate.allowed, argv, cwd: a.cwd }, () => [
508
+ gate.allowed ? 'Comando di ripresa:' : `CONFERMA RICHIESTA — ${gate.reason}`,
509
+ `cd ${a.cwd} && ${argv.join(' ')}`,
510
+ gate.allowed ? '' : 'Se l\'utente approva, ripeti con --yes per riaprirlo in un nuovo terminale.',
511
+ ].join('\n').trim());
512
+ return { needsConfirmation: !gate.allowed, argv, exitCode: gate.allowed ? 0 : EXIT_NEEDS_CONFIRM };
513
+ }
514
+ const backend = opts.backend ?? await selectBackend({ choice: flags.backend ?? a.backend, config: cfg, env: c.env });
515
+ const started = await backend.start({ name, cwd: a.cwd, argv, env: spec.env, harness: a.harness, root: c.root, project: projectId(c.root) });
516
+ if (started.workspaceCreated) { cfg.herdr = { ...(cfg.herdr ?? {}), workspace_id: started.workspace }; saveConfig(c.root, cfg); }
517
+ 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 });
518
+ c.out(flags.json ? JSON.stringify({ resumed: true, argv }) : `Ripreso ${name} (sessione ${a.session_id}) su ${backend.name}.`);
519
+ return { resumed: true, argv };
520
+ }
521
+
522
+ export { DEFAULT_CONFIG, taskProfile };
@@ -0,0 +1,101 @@
1
+ // Credits and limits per provider.
2
+ // Primary source: CodexBar (`codexbar usage --format json --provider all`).
3
+ // Fallbacks, in order: a budget the user declared in .harma/config.json,
4
+ // then the local-log estimate (claude, codex). Otherwise "sconosciuto".
5
+ import { run, which, parseJson, stripIdentity, now } from './util.mjs';
6
+ import { HARNESS_META } from './harness.mjs';
7
+ import { usageFor, estimateCost } from './usage.mjs';
8
+
9
+ export async function readCodexbar({ env = process.env, bin = 'codexbar', timeoutSec = 120 } = {}) {
10
+ if (!which(bin, env)) return { ok: false, detail: 'codexbar non installato (https://github.com/steipete/CodexBar)', entries: [] };
11
+ const res = await run(bin, ['usage', '--format', 'json', '--provider', 'all', '--no-color'], { env, timeout: timeoutSec * 1000 });
12
+ const data = parseJson(res.stdout);
13
+ if (!Array.isArray(data)) {
14
+ return { ok: false, detail: `codexbar non ha restituito JSON (exit ${res.code})`, entries: [] };
15
+ }
16
+ return { ok: true, entries: data.map(stripIdentity) };
17
+ }
18
+
19
+ /** Collapse one CodexBar entry to the figures harma uses. */
20
+ export function summarizeEntry(e) {
21
+ const u = e.usage ?? {};
22
+ const windows = ['primary', 'secondary', 'tertiary']
23
+ .map((k) => (u[k] && typeof u[k].usedPercent === 'number' ? { window: k, used_pct: round(u[k].usedPercent), resets_at: u[k].resetsAt ?? null, minutes: u[k].windowMinutes ?? null } : null))
24
+ .filter(Boolean);
25
+ const maxUsed = windows.length ? Math.max(...windows.map((w) => w.used_pct)) : null;
26
+ const pc = u.providerCost;
27
+ const cost = pc && (pc.used !== undefined || pc.limit !== undefined) ? {
28
+ used: pc.used ?? null, limit: pc.limit ?? null, currency: pc.currencyCode ?? null, period: pc.period ?? null,
29
+ } : null;
30
+ let remaining = maxUsed === null ? null : round(100 - maxUsed);
31
+ if (remaining === null && cost?.limit) remaining = round(100 - (100 * (cost.used ?? 0)) / cost.limit);
32
+ return {
33
+ provider: e.provider,
34
+ ok: !e.error && !!e.usage,
35
+ error: e.error ? (e.error.message ?? String(e.error)).slice(0, 160) : null,
36
+ source: `codexbar:${e.source ?? '?'}`,
37
+ updated_at: u.updatedAt ?? null,
38
+ windows,
39
+ remaining_pct: remaining,
40
+ credits_remaining: e.credits?.remaining ?? null,
41
+ cost,
42
+ };
43
+ }
44
+
45
+ export function classify(remaining, thresholds) {
46
+ if (remaining === null || remaining === undefined) return 'sconosciuto';
47
+ if (remaining < thresholds.exhausted_remaining_pct) return 'esaurito';
48
+ if (remaining < thresholds.low_remaining_pct) return 'scarso';
49
+ if (remaining >= thresholds.high_remaining_pct) return 'ampio';
50
+ return 'ok';
51
+ }
52
+
53
+ /**
54
+ * One row per harness: its provider's credit state with source and time.
55
+ * `harnessNames` are the harnesses to report (normally the installed ones).
56
+ */
57
+ export async function collectCredits({ harnessNames, config, catalog, env = process.env, codexbar, windowDays = 7 }) {
58
+ const cb = codexbar ?? await readCodexbar({ env });
59
+ const byProvider = new Map(cb.entries.map((e) => [e.provider, summarizeEntry(e)]));
60
+ const sinceMs = Date.now() - windowDays * 86_400_000;
61
+ const rows = [];
62
+ for (const h of harnessNames) {
63
+ const provider = HARNESS_META[h]?.codexbar ?? null;
64
+ const s = provider ? byProvider.get(provider) : null;
65
+ const row = {
66
+ harness: h, provider, fetched_at: now(),
67
+ source: null, remaining_pct: null, status: 'sconosciuto', detail: null, windows: [], cost: null, estimate: null,
68
+ };
69
+ if (s?.ok) {
70
+ Object.assign(row, { source: s.source, remaining_pct: s.remaining_pct, windows: s.windows, cost: s.cost, credits_remaining: s.credits_remaining, updated_at: s.updated_at });
71
+ } else if (s?.error) {
72
+ row.detail = `codexbar: ${s.error}`;
73
+ } else if (!cb.ok) {
74
+ row.detail = cb.detail;
75
+ } else if (provider) {
76
+ row.detail = `codexbar non riporta ${provider} (attivalo nell'app CodexBar)`;
77
+ }
78
+ const spent = HARNESS_META[h]?.logs ? estimateSpend(h, catalog, env, sinceMs) : null;
79
+ if (spent !== null) {
80
+ row.estimate = { usd: spent, window_days: windowDays, note: 'stima a listino API dai log locali; non è l\'addebito di un abbonamento' };
81
+ }
82
+ const budget = provider ? config.budgets?.[provider] : null;
83
+ if (row.remaining_pct === null && budget?.limit && spent !== null) {
84
+ row.remaining_pct = round(100 - (100 * spent) / budget.limit);
85
+ row.source = `budget dichiarato (${budget.limit} ${budget.currency ?? 'USD'}) − stima log locali ${windowDays}g`;
86
+ }
87
+ row.status = classify(row.remaining_pct, config.thresholds);
88
+ rows.push(row);
89
+ }
90
+ return { fetched_at: now(), codexbar: cb.ok ? 'ok' : cb.detail, rows };
91
+ }
92
+
93
+ function estimateSpend(harness, catalog, env, sinceMs) {
94
+ const sessions = usageFor(harness, { env, sinceMs });
95
+ if (!sessions.length) return null;
96
+ let total = 0;
97
+ for (const s of sessions) total += estimateCost(s, catalog).usd ?? 0;
98
+ return Math.round(total * 100) / 100;
99
+ }
100
+
101
+ function round(n) { return Math.round(n * 10) / 10; }