harma-kit 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,49 @@
1
+ # harma command reference
2
+
3
+ Every command takes `--json`. Targets are `harness:model` (for example `claude:claude-opus-5-5`); `harma models --json` lists the valid ones.
4
+
5
+ ## Commands
6
+
7
+ | Command | Use |
8
+ |---|---|
9
+ | `init --orchestrator h:m --effort e [--backend auto\|herdr\|hc] [--policy confirm\|auto-within-budget]` | Create `.harma/` and record the orchestrator. Don't pass `--policy auto-within-budget` unless the user asked for it |
10
+ | `models` | Agent CLIs on PATH, models, efforts, source of each row |
11
+ | `credits` | Remaining share and state per provider, with source and time |
12
+ | `rank [--refresh] [--top N]` | AA index and cost per task per model × effort |
13
+ | `route <job> [--author h:m] [--top N]` | Candidates for a job, the user's saved list (`user_choice`) and the model dispatch would take now (`user_pick`) |
14
+ | `select --open [--wait] [--timeout s]` | Selection screen in a focused herdr tab (or `hc` terminal); `--wait` returns the saved choices (default 900 s) |
15
+ | `select --set "job=h:m@e\|h:m@e,job=none"` | Record the user's choices; `\|` separates models in order of preference; the orchestrator takes one model; at most 5 per job |
16
+ | `select --accept` / `select --show` | Accept all proposals (only if the user said so) / print choices |
17
+ | `dispatch --name n (--model h:m [--effort e] \| --task-type job) [--prompt "…" \| --prompt-file f] [--cwd dir] [--wait] [--timeout s] [--yes]` | Start an agent and send the task |
18
+ | `send n "text" [--wait] [--timeout s] [--yes]` | More work for an open agent |
19
+ | `read n [--lines N]` | Recent screen output of an agent |
20
+ | `status [--all]` | Open agents (all with `--all`): model, effort, live state, age, session id |
21
+ | `costs` | Estimated cost per agent, credits per provider, `advice` |
22
+ | `cleanup [--dry-run] [--agent n] [--force] [--workspace]` | Save session ids, close finished agents |
23
+ | `resume n [--print-only] [--yes]` | Reopen a closed agent's session (Claude Code and Codex) |
24
+ | `doctor` | Check the environment |
25
+
26
+ Jobs: `pianificazione` (planning), `sviluppo` (development), `review`, `debugging`, `ricerca` (research), `estrazione` (extraction). English aliases are accepted.
27
+
28
+ ## Exit codes
29
+
30
+ - `0`: done
31
+ - `1`: error; the message has a hint
32
+ - `3`: needs the user's confirmation; nothing started. Show the plan, ask, rerun with `--yes`
33
+ - `4`: `dispatch` started the agent but it waits on a dialog; the task wasn't sent (see troubleshooting.md)
34
+
35
+ ## Credit states
36
+
37
+ `ampio` (60% or more left), `ok`, `scarso` (below 20%), `esaurito` (below 5%), `sconosciuto` (not measured). The user can change the thresholds in `.harma/config.json` → `thresholds`.
38
+
39
+ ## How dispatch picks from the user's list
40
+
41
+ In the user's order: skip a model whose CLI isn't installed or whose credits are `esaurito`; pass over a `scarso` model when a later one has more; take the first left. With none left, dispatch fails and lists each reason. The plan's `why` names the position taken and the models skipped.
42
+
43
+ ## Backends and files
44
+
45
+ - **herdr**: one workspace per project (`harma:<project>`), one tab per agent
46
+ - **herdr-core (`hc`)**: headless terminals labelled `harma.project` and `harma.agent`; the user opens one with `hc attach <name>`
47
+ - **`.harma/config.json`**: orchestrator, backend, policy, budgets, thresholds, routing overrides, `roster` (the user's models per job)
48
+ - **`.harma/agents.jsonl`**: append-only events (started, session, prompted, blocked, closed, resumed, roster)
49
+ - **`.harma/cache/`**: last inventory, credits, rank, selection status
@@ -0,0 +1,37 @@
1
+ # harma troubleshooting
2
+
3
+ ## Exit code 4: the agent waits on a dialog
4
+
5
+ The agent started but waits on a question, often "trust this folder?" in a new directory, and the task wasn't delivered.
6
+
7
+ 1. `harma read <name>` to see the question
8
+ 2. Tell the user what it asks and ask them to answer it in the agent's tab or terminal. Don't answer it yourself, even when the answer looks obvious: trust and approval decisions belong to the user
9
+ 3. After they confirm, `harma send <name> "<task>" --yes` (this needs their yes for the send)
10
+
11
+ ## No usable model for a job
12
+
13
+ `dispatch --task-type` fails when every model on the user's list for that job has a missing CLI or exhausted credits; the hint lists the reason for each. Tell the user and offer options: add a model with `harma select`, wait for the provider's reset, or use `--model` for this dispatch if they pick one. If the user chose "no model" for the job, dispatch refuses it on purpose; ask before working around it.
14
+
15
+ ## Selection screen without a terminal
16
+
17
+ `harma select` with no options needs an interactive terminal, which you don't have. Use `harma select --open --wait --json`, or ask in chat and record with `--set`.
18
+
19
+ ## Credits are `sconosciuto`
20
+
21
+ harma has no reliable figure. Say so; don't estimate. Suggest one of: install or start CodexBar, enable the provider in CodexBar, or declare a budget in `.harma/config.json`:
22
+
23
+ ```json
24
+ { "budgets": { "codex": { "limit": 100, "currency": "USD" } } }
25
+ ```
26
+
27
+ ## A model has no score
28
+
29
+ The bundled Artificial Analysis snapshot doesn't cover it. If `AA_API_KEY` is set, `harma rank --refresh` may fill it in. An unscored model never appears in proposals, but the user can still choose it.
30
+
31
+ ## Cleanup keeps an agent
32
+
33
+ `working` or `blocked` agents, and agents without a known session id, stay open. Check with `harma status --json` and `harma read <name>`. Use `--force` only when the user asks, since it loses that agent's context.
34
+
35
+ ## Anything else
36
+
37
+ `harma doctor` lists what's missing (backends, agent CLIs, CodexBar, AA key, installed skill) and how to install it. Don't start, stop or restart a herdr or hc server yourself.
package/src/backends.mjs CHANGED
@@ -127,6 +127,17 @@ export class HerdrBackend {
127
127
  return { ok: res.ok, detail: res.ok ? 'tab chiuso' : res.stderr.trim() };
128
128
  }
129
129
 
130
+ /** A focused tab in the project workspace running a shell command (used for the select TUI). */
131
+ async openTab({ root, project, label, command }) {
132
+ const ws = await this.ensureWorkspace(root, project);
133
+ const tab = okJson(await this.exec(['tab', 'create', '--workspace', ws.id, '--cwd', root, '--label', label, '--focus']), 'herdr tab create');
134
+ const tabId = tab?.result?.tab?.tab_id;
135
+ const paneId = tab?.result?.root_pane?.pane_id;
136
+ if (!tabId || !paneId) throw new HarmaError('herdr tab create: risposta senza tab_id/pane_id');
137
+ okJson(await this.exec(['pane', 'run', paneId, command]), 'herdr pane run');
138
+ return { tab: tabId, pane: paneId, workspace: ws.id, workspaceCreated: ws.created };
139
+ }
140
+
130
141
  /** Only for the workspace harma created for this project (config.herdr.workspace_id). */
131
142
  async closeWorkspace(id) {
132
143
  const res = await this.exec(['workspace', 'close', id]);
package/src/cli.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  cmdInit, cmdModels, cmdCredits, cmdRank, cmdRoute, cmdDispatch, cmdSend, cmdRead,
3
- cmdStatus, cmdCosts, cmdCleanup, cmdResume,
3
+ cmdStatus, cmdCosts, cmdCleanup, cmdResume, cmdSelect,
4
4
  } from './commands.mjs';
5
5
  import { cmdInstall, cmdUninstall, cmdDoctor } from './install.mjs';
6
6
  import { HarmaError } from './util.mjs';
7
7
 
8
- const BOOLEAN = new Set(['json', 'yes', 'wait', 'refresh', 'dry-run', 'force', 'all', 'print-only', 'help', 'version', 'workspace']);
8
+ const BOOLEAN = new Set(['json', 'yes', 'wait', 'refresh', 'dry-run', 'force', 'all', 'print-only', 'help', 'version', 'workspace', 'open', 'accept', 'show', 'close-tab']);
9
9
 
10
10
  export function parseArgs(argv) {
11
11
  const flags = { _: [] };
@@ -37,6 +37,12 @@ Conoscere le risorse
37
37
  rank [--refresh] [--top N] intelligenza per modello × effort (Artificial Analysis)
38
38
  route <tipo> [--author h:m] classifica per: pianificazione, sviluppo, review, debugging, ricerca, estrazione
39
39
 
40
+ Scegliere i modelli (l'utente valida o cambia le proposte)
41
+ select TUI: modello ed effort per l'orchestratore; per ogni lavoro uno o più
42
+ modelli in ordine (al dispatch: il primo con crediti utilizzabili)
43
+ select --open [--wait] apre la TUI in un tab herdr (o terminale hc) e aspetta il salvataggio
44
+ select --accept | --set "sviluppo=codex:gpt-6.2-sol@high|claude:claude-sonnet-5-5@high,review=none" | --show
45
+
40
46
  Delegare (con policy "confirm" serve --yes, dopo il consenso dell'utente)
41
47
  dispatch --name <n> (--model h:m [--effort e] | --task-type <tipo>) [--prompt "…" | --prompt-file f] [--wait] [--yes]
42
48
  send <nome> "<testo>" [--wait] [--yes]
@@ -59,7 +65,7 @@ Installazione
59
65
  const COMMANDS = {
60
66
  init: cmdInit, models: cmdModels, credits: cmdCredits, rank: cmdRank, route: cmdRoute,
61
67
  dispatch: cmdDispatch, send: cmdSend, read: cmdRead, status: cmdStatus, costs: cmdCosts,
62
- cleanup: cmdCleanup, resume: cmdResume, install: cmdInstall, uninstall: cmdUninstall, doctor: cmdDoctor,
68
+ cleanup: cmdCleanup, resume: cmdResume, select: cmdSelect, install: cmdInstall, uninstall: cmdUninstall, doctor: cmdDoctor,
63
69
  };
64
70
 
65
71
  export async function main(argv, opts = {}) {
package/src/commands.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
- import { loadCatalog } from './catalog.mjs';
3
+ import { loadCatalog, harnesses } from './catalog.mjs';
4
4
  import { parseTarget, effortValues, launchSpec, resumeArgv, meta } from './harness.mjs';
5
5
  import {
6
6
  projectRoot, loadConfig, saveConfig, appendEvent, readEvents, agentsFromEvents,
@@ -12,7 +12,11 @@ import { rankRows, refreshFromAA } from './rank.mjs';
12
12
  import { route, taskProfile, TASK_PROFILES } from './route.mjs';
13
13
  import { selectBackend, HerdrBackend, HcBackend, projectId, checkAgentName } from './backends.mjs';
14
14
  import { usageFor, estimateCost, findCodexSession } from './usage.mjs';
15
- import { table, HarmaError, now, which } from './util.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';
16
20
 
17
21
  export const EXIT_NEEDS_CONFIRM = 3;
18
22
  export const EXIT_BLOCKED = 4; // agent started, waiting on a dialog; task not delivered
@@ -25,6 +29,13 @@ function ctx(opts) {
25
29
  return { env, root, catalog, out: opts.out ?? ((s) => process.stdout.write(s + '\n')) };
26
30
  }
27
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
+
28
39
  const emit = (c, flags, data, text) => c.out(flags.json ? JSON.stringify(data, null, 2) : text());
29
40
 
30
41
  // 1 ─ orchestrator ─────────────────────────────────────────────────────────
@@ -148,8 +159,16 @@ export async function cmdRoute(flags, opts = {}) {
148
159
  const author = flags.author ? authorOf(flags.author, c.catalog) : null;
149
160
  const res = route(type, { rankRows: rankRows(c.catalog, inv.models), credits: credits.rows, config: cfg, author, top: Number(flags.top ?? 5) });
150
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
+ }
151
167
  emit(c, flags, res, () => [
152
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'}`,
153
172
  table(res.candidates.map((r, i) => ({ '#': i + 1, modello: `${r.harness}:${r.model}`, effort: r.effort, punteggio: r.score, motivi: r.why }))),
154
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.',
155
174
  ].join('\n'));
@@ -173,6 +192,21 @@ export async function cmdDispatch(flags, opts = {}) {
173
192
  if (flags.model) {
174
193
  const t = parseTarget(flags.model, c.catalog);
175
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('; ')}` : ''}` };
176
210
  } else {
177
211
  if (!flags['task-type']) throw new HarmaError('Serve --model <harness>:<model> oppure --task-type <tipo>');
178
212
  const inv = await currentInventory(c, cfg);
@@ -519,4 +553,128 @@ export async function cmdResume(flags, opts = {}) {
519
553
  return { resumed: true, argv };
520
554
  }
521
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.2-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
+
522
680
  export { DEFAULT_CONFIG, taskProfile };
package/src/harness.mjs CHANGED
@@ -20,15 +20,16 @@ export const HARNESS_META = {
20
20
  // Claude Code pointed at another provider: needs that provider's env set up.
21
21
  'claude-moonshot': { codexbar: 'moonshot', variantOf: 'claude' },
22
22
  'claude-zai': { codexbar: 'zai', variantOf: 'claude' },
23
+ 'claude-qwencloud': { codexbar: 'qwencloud', variantOf: 'claude' },
23
24
  };
24
25
 
25
26
  export function meta(name) {
26
27
  return HARNESS_META[name] ?? {};
27
28
  }
28
29
 
29
- /** Parse "codex:gpt-6-astra" or a bare model id (harness inferred from the catalog). */
30
+ /** Parse "codex:gpt-6.2-astra" or a bare model id (harness inferred from the catalog). */
30
31
  export function parseTarget(spec, catalog) {
31
- if (!spec) throw new HarmaError('Manca il modello: usa <harness>:<model>, es. codex:gpt-6-astra');
32
+ if (!spec) throw new HarmaError('Manca il modello: usa <harness>:<model>, es. codex:gpt-6.2-astra');
32
33
  const hs = harnesses(catalog);
33
34
  if (spec.includes(':')) {
34
35
  const [harness, model] = spec.split(/:(.*)/s);
package/src/rank.mjs CHANGED
@@ -38,21 +38,31 @@ const VARIANT_WORDS = new Set([...EFFORT_ORDER, 'non-reasoning', 'reasoning', 't
38
38
  * the variant is the first effort word in the name's parenthetical
39
39
  * ("Claude Opus 5.5 (Max)") and the family slug drops "-<variant>".
40
40
  */
41
- export function aaFamilies(rows) {
41
+ export function aaFamilies(rows, pick = (r) => r.evaluations?.artificial_analysis_intelligence_index ?? null) {
42
42
  const out = {};
43
43
  for (const r of rows) {
44
44
  const name = r.name ?? '';
45
45
  const slug = r.slug ?? '';
46
- const index = r.evaluations?.artificial_analysis_intelligence_index ?? null;
47
46
  let variant = null;
48
47
  const m = name.match(VARIANT);
49
48
  if (m) variant = m[2].split(',').map((p) => p.trim().toLowerCase()).find((p) => VARIANT_WORDS.has(p)) ?? null;
50
49
  const family = variant && slug.endsWith(`-${variant}`) ? slug.slice(0, -variant.length - 1) : slug;
51
- (out[family] ??= {})[variant ?? 'default'] = index;
50
+ (out[family] ??= {})[variant ?? 'default'] = pick(r);
52
51
  }
53
52
  return out;
54
53
  }
55
54
 
55
+ /** Cost per task in USD from an AA language-models row (V2 shape), or null. */
56
+ const aaRowCost = (r) => r.artificial_analysis_intelligence_index_cost?.cost_per_task?.total_cost ?? null;
57
+
58
+ // The legacy /api/v2/data/llms/models endpoint was retired on 2026-11-04.
59
+ export const AA_FREE_URL = 'https://artificialanalysis.ai/api/v2/language/models/free';
60
+ const aaUrl = (catalog) => (!catalog.aa_api_url || catalog.aa_api_url.includes('/data/llms/') ? AA_FREE_URL : catalog.aa_api_url);
61
+ const MAX_PAGES = 20;
62
+
63
+ const sameScores = (a, b) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b ?? {}).sort());
64
+ const nonNull = (o) => Object.fromEntries(Object.entries(o ?? {}).filter(([, v]) => v !== null && v !== undefined));
65
+
56
66
  export function aaKey(env = process.env) {
57
67
  if (env.AA_API_KEY) return env.AA_API_KEY;
58
68
  const file = join(env.HOME || homedir(), '.local/share/delegation-kit/config/artificial-analysis.env');
@@ -69,27 +79,37 @@ export async function refreshFromAA(catalog, { env = process.env, fetchImpl = fe
69
79
  if (!key) {
70
80
  throw new HarmaError('Nessuna chiave Artificial Analysis', { hint: 'Imposta AA_API_KEY (gratuita su artificialanalysis.ai). Senza chiave harma usa lo snapshot incluso.' });
71
81
  }
72
- let res;
73
- try {
74
- res = await fetchImpl(catalog.aa_api_url, { headers: { 'x-api-key': key, Accept: 'application/json', 'User-Agent': 'harma' } });
75
- } catch (e) {
76
- throw new HarmaError(`Artificial Analysis non raggiungibile: ${e.name}`);
82
+ const url = aaUrl(catalog);
83
+ const rows = [];
84
+ for (let page = 1; page <= MAX_PAGES; page++) {
85
+ let res;
86
+ try {
87
+ res = await fetchImpl(`${url}${url.includes('?') ? '&' : '?'}page=${page}`, { headers: { 'x-api-key': key, Accept: 'application/json', 'User-Agent': 'harma' } });
88
+ } catch (e) {
89
+ throw new HarmaError(`Artificial Analysis non raggiungibile: ${e.name}`);
90
+ }
91
+ if (!res.ok) throw new HarmaError(`Artificial Analysis ha risposto HTTP ${res.status}`);
92
+ const body = await res.json();
93
+ const data = Array.isArray(body) ? body : body?.data;
94
+ if (!Array.isArray(data)) throw new HarmaError('Risposta Artificial Analysis inattesa');
95
+ rows.push(...data);
96
+ if (!body?.pagination?.has_more) break;
77
97
  }
78
- if (!res.ok) throw new HarmaError(`Artificial Analysis ha risposto HTTP ${res.status}`);
79
- const body = await res.json();
80
- const rows = Array.isArray(body) ? body : body?.data;
81
- if (!Array.isArray(rows)) throw new HarmaError('Risposta Artificial Analysis inattesa');
82
98
  const fams = aaFamilies(rows);
99
+ const costs = aaFamilies(rows, aaRowCost);
83
100
  const today = new Date().toISOString().slice(0, 10);
84
101
  const next = structuredClone(catalog);
85
102
  delete next.origin;
103
+ next.aa_api_url = url;
86
104
  const changes = [];
87
105
  for (const [id, m] of Object.entries(next.models)) {
88
106
  const fam = m.aa?.slug ? fams[m.aa.slug] : null;
89
107
  if (!fam) { changes.push({ model: id, change: m.aa?.slug ? 'non trovato su AA' : 'senza slug AA' }); continue; }
90
- const index = Object.fromEntries(Object.entries(fam).filter(([, v]) => v !== null && v !== undefined));
91
- if (JSON.stringify(index) !== JSON.stringify(m.aa.index)) changes.push({ model: id, change: 'indice aggiornato', old: m.aa.index, new: index });
108
+ const index = nonNull(fam);
109
+ const cost = nonNull(costs[m.aa.slug]);
110
+ if (!sameScores(index, m.aa.index)) changes.push({ model: id, change: 'indice aggiornato', old: m.aa.index, new: index });
92
111
  m.aa.index = Object.keys(index).length ? index : null;
112
+ if (Object.keys(cost).length) m.aa.cost_per_task = cost;
93
113
  m.aa.date = today;
94
114
  m.aa.source = 'aa-api';
95
115
  }
package/src/roster.mjs ADDED
@@ -0,0 +1,177 @@
1
+ // The roster: which models (in order of preference) the user wants for each
2
+ // kind of work, plus the orchestrator. Proposals come from route(); the user
3
+ // accepts or overrides them in the TUI (harma select) or with --accept / --set.
4
+ // Stored in .harma/config.json → roster, orchestrator.
5
+ //
6
+ // A row's choice is null (undecided), { none: true } (no model for this job) or
7
+ // { picks: [{harness, model, effort}, …] } in order of preference. At dispatch
8
+ // choosePick() takes the first pick with usable credits.
9
+ import { route, TASK_PROFILES, taskProfile } from './route.mjs';
10
+ import { EFFORT_ORDER, HarmaError, now } from './util.mjs';
11
+
12
+ export const ORCHESTRATOR = 'orchestratore';
13
+ export const TASK_TYPES = Object.keys(TASK_PROFILES);
14
+ export const MAX_PICKS = 5;
15
+
16
+ /** One option per installed harness:model, with every effort's index and cost. */
17
+ export function modelOptions(invModels, rankRowsArr, credits = []) {
18
+ const creditBy = new Map(credits.map((c) => [c.harness, c]));
19
+ const out = [];
20
+ for (const m of invModels) {
21
+ const rows = rankRowsArr.filter((r) => r.harness === m.harness && r.model === m.model);
22
+ const efforts = (m.efforts?.length ? m.efforts : [null]).map((e) => {
23
+ const r = rows.find((x) => x.effort === e);
24
+ return { effort: e, index: r?.index ?? null, cost: r?.cost_per_task ?? null };
25
+ }).sort((a, b) => EFFORT_ORDER.indexOf(a.effort) - EFFORT_ORDER.indexOf(b.effort));
26
+ const known = efforts.filter((e) => e.index !== null);
27
+ const best = known.length ? known.reduce((a, b) => (b.index > a.index ? b : a)) : null;
28
+ const c = creditBy.get(m.harness);
29
+ out.push({
30
+ harness: m.harness, model: m.model, provider: rows[0]?.provider ?? null,
31
+ efforts, best, default_effort: m.default_effort ?? null, effort_fixed: Boolean(m.effort_fixed),
32
+ credit: c?.status ?? 'sconosciuto', remaining: c?.remaining_pct ?? null,
33
+ });
34
+ }
35
+ return out.sort((a, b) => (b.best?.index ?? -1) - (a.best?.index ?? -1));
36
+ }
37
+
38
+ /** Picks of a saved roster entry; reads the 0.2.0 single-model shape too. */
39
+ export function rosterPicks(entry) {
40
+ if (!entry || entry.none) return [];
41
+ if (Array.isArray(entry.picks)) return entry.picks.map(bare);
42
+ return entry.harness ? [bare(entry)] : [];
43
+ }
44
+
45
+ const bare = (x) => ({ harness: x.harness, model: x.model, effort: x.effort ?? null });
46
+
47
+ /** Rows for the selection: orchestrator first, then one per task type. */
48
+ export function selectionRows({ cfg, rankRowsArr, credits }) {
49
+ const rows = [{
50
+ type: ORCHESTRATOR,
51
+ label: 'orchestratore (dirige il progetto)',
52
+ single: true,
53
+ proposal: cfg.orchestrator ? { picks: [bare(cfg.orchestrator)] } : null,
54
+ choice: cfg.orchestrator ? { picks: [bare(cfg.orchestrator)], source: 'configurato' } : null,
55
+ }];
56
+ for (const type of TASK_TYPES) {
57
+ const p = taskProfile(type, cfg);
58
+ const res = route(type, { rankRows: rankRowsArr, credits, config: cfg, top: 1000 });
59
+ const cands = res?.candidates ?? [];
60
+ const first = cands[0];
61
+ // A backup on another CLI, so a job still has a model when one provider runs low.
62
+ const backup = first && cands.find((c) => c.harness !== first.harness);
63
+ const saved = cfg.roster?.[type];
64
+ rows.push({
65
+ type,
66
+ label: p.label,
67
+ proposal: first ? {
68
+ picks: [first, backup].filter(Boolean).map(bare),
69
+ why: `${first.why}${backup ? ` · riserva su un'altra CLI: ${describePick(backup)}` : ''}`,
70
+ } : null,
71
+ choice: !saved ? null : saved.none ? { none: true, source: saved.source } : { picks: rosterPicks(saved), source: saved.source ?? 'utente' },
72
+ });
73
+ }
74
+ for (const r of rows) r.original = r.choice ? structuredClone(r.choice) : null;
75
+ return rows;
76
+ }
77
+
78
+ export const samePick = (a, b) => Boolean(a && b && !a.none && !b.none
79
+ && a.harness === b.harness && a.model === b.model && (a.effort ?? null) === (b.effort ?? null));
80
+
81
+ /** Same choice: both undecided, both "none", or the same picks in the same order. */
82
+ export function sameChoice(a, b) {
83
+ if (!a && !b) return true;
84
+ if (!a || !b) return false;
85
+ if (a.none || b.none) return Boolean(a.none && b.none);
86
+ const pa = a.picks ?? [a];
87
+ const pb = b.picks ?? [b];
88
+ return pa.length === pb.length && pa.every((p, i) => samePick(p, pb[i]));
89
+ }
90
+
91
+ export const describePick = (p) => `${p.harness}:${p.model} @ ${p.effort ?? 'default'}`;
92
+
93
+ /** A single pick, a choice with picks, a saved roster entry, "none" or nothing. */
94
+ export function describe(p) {
95
+ if (!p) return '— da decidere';
96
+ if (p.none) return '— nessun modello';
97
+ const picks = p.picks ?? (p.harness ? [p] : []);
98
+ if (!picks.length) return '— da decidere';
99
+ return picks.map(describePick).join(' → ');
100
+ }
101
+
102
+ const CREDIT_RANK = { ampio: 0, ok: 0, sconosciuto: 0, scarso: 1 };
103
+
104
+ /**
105
+ * Which of the user's picks to use now. The user's order wins; a pick is skipped
106
+ * when its CLI is missing or its credits are exhausted, and passed over for a
107
+ * later one when its credits are low ("scarso") and a later one's are not.
108
+ */
109
+ export function choosePick(picks, credits = [], { installed = () => true } = {}) {
110
+ const by = new Map(credits.map((c) => [c.harness, c]));
111
+ const rated = picks.map((p, i) => {
112
+ const c = by.get(p.harness);
113
+ const credit = c?.status ?? 'sconosciuto';
114
+ const skip = !installed(p.harness) ? 'CLI non installata' : credit === 'esaurito' ? 'crediti esauriti' : null;
115
+ return { ...bare(p), position: i + 1, credit, remaining: c?.remaining_pct ?? null, skip };
116
+ });
117
+ const usable = rated.filter((p) => !p.skip);
118
+ const best = usable.reduce((a, p) => (a === null || CREDIT_RANK[p.credit] < CREDIT_RANK[a.credit] ? p : a), null);
119
+ const notes = rated.filter((p) => p !== best && best && p.position < best.position)
120
+ .map((p) => `n.${p.position} ${describePick(p)} saltato: ${p.skip ?? `crediti ${p.credit}`}`);
121
+ return { pick: best, rated, notes };
122
+ }
123
+
124
+ /** "sviluppo=codex:gpt-6.2-sol@high|claude:claude-sonnet-5-5@high,review=none,orchestratore=claude:claude-opus-5-5@high" */
125
+ export function parseSetSpec(spec, { catalog, parseTarget, effortValues }) {
126
+ const out = {};
127
+ for (const part of String(spec).split(',').map((s) => s.trim()).filter(Boolean)) {
128
+ const [rawType, value] = part.split(/=(.*)/s);
129
+ const type = rawType === ORCHESTRATOR || TASK_PROFILES[rawType] ? rawType : taskProfile(rawType)?.type;
130
+ if (!type) throw new HarmaError(`Tipo di lavoro sconosciuto in --set: ${rawType}`, { hint: `Tipi: ${[ORCHESTRATOR, ...TASK_TYPES].join(', ')}` });
131
+ if (!value) throw new HarmaError(`--set ${rawType}: manca il modello (tipo=harness:modello@effort)`);
132
+ if (value === 'none') {
133
+ if (type === ORCHESTRATOR) throw new HarmaError('L\'orchestratore non può essere "none"');
134
+ out[type] = { none: true, source: 'utente' };
135
+ continue;
136
+ }
137
+ const picks = value.split('|').map((s) => s.trim()).filter(Boolean).map((v) => {
138
+ const [target, effort] = v.split('@');
139
+ const t = parseTarget(target, catalog);
140
+ const allowed = effortValues(t.harness, t.model, catalog);
141
+ if (effort && allowed.length && !allowed.includes(effort)) {
142
+ throw new HarmaError(`Effort ${effort} non supportato da ${t.harness}:${t.model}`, { hint: `Valori: ${allowed.join(', ')}` });
143
+ }
144
+ return { harness: t.harness, model: t.model, effort: effort || catalog.models?.[t.model]?.effort_default || null };
145
+ });
146
+ if (type === ORCHESTRATOR && picks.length > 1) throw new HarmaError('L\'orchestratore è un solo modello');
147
+ if (picks.length > MAX_PICKS) throw new HarmaError(`Al massimo ${MAX_PICKS} modelli per lavoro`);
148
+ const dup = picks.find((p, i) => picks.findIndex((q) => samePick(p, q)) !== i);
149
+ if (dup) throw new HarmaError(`--set ${type}: ${describePick(dup)} compare due volte`);
150
+ out[type] = { picks, source: 'utente' };
151
+ }
152
+ return out;
153
+ }
154
+
155
+ /** Write the rows' choices into cfg (roster + orchestrator). Returns the saved roster. */
156
+ export function applySelection(cfg, rows) {
157
+ const at = now();
158
+ const roster = { ...(cfg.roster ?? {}) };
159
+ for (const r of rows) {
160
+ if (r.type === ORCHESTRATOR) {
161
+ const o = r.choice?.picks?.[0];
162
+ if (o && !sameChoice(r.choice, r.original)) cfg.orchestrator = { ...bare(o), set_at: at };
163
+ continue;
164
+ }
165
+ if (!r.choice || (!r.choice.none && !r.choice.picks?.length)) { delete roster[r.type]; continue; }
166
+ if (r.choice.none) { roster[r.type] = { none: true, source: 'utente', at }; continue; }
167
+ roster[r.type] = {
168
+ picks: r.choice.picks.map(bare),
169
+ source: r.proposal && sameChoice(r.choice, r.proposal) ? 'proposta' : 'utente',
170
+ proposed: r.proposal ? describe(r.proposal) : null,
171
+ at,
172
+ };
173
+ }
174
+ cfg.roster = roster;
175
+ cfg.roster_updated_at = at;
176
+ return roster;
177
+ }