harma-kit 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/skill/SKILL.md CHANGED
@@ -1,131 +1,122 @@
1
1
  ---
2
2
  name: harma
3
- description: Run a project as the orchestrator model over other coding agents with the harma CLI — inventory the models and efforts on this machine, read their credits, rank them by Artificial Analysis intelligence per effort, route planning/development/review/debugging/research/extraction to the best fit, monitor agents, track cost, and close finished agents after saving their session ids so they can be resumed. Use when the user names an orchestrator for a project, asks which models are available or how much credit is left, asks to delegate work across models, to check on or clean up agents, or to resume an agent's session. Do not use for a single-model task the user did not ask to delegate.
3
+ description: Run a project as the orchestrator model over other coding agents with the harma CLI. It inventories the agent CLIs, models and effort levels on this machine, reads each provider's remaining credits, ranks models by Artificial Analysis intelligence per effort, lets the user choose one or more models per job, starts agents in herdr or herdr-core terminals after consent, monitors them, tracks cost, and closes finished agents after saving their session ids so they can be resumed. Use it whenever the user names an orchestrator or a model "responsible" for a project, asks which models or effort levels are available, how much credit is left, which model is best for planning, development, review, debugging, research or extraction, wants work delegated or split across models or agents, wants to check on, clean up or resume agents, or mentions harma or herdr, in any language (for example "orchestratore", "quali modelli ho", "crediti", "delega", "riprendi la sessione"). Do not use it for a task the user wants done by the current model alone.
4
4
  ---
5
5
 
6
6
  # harma
7
7
 
8
- You are, or are about to become, the **orchestrator** of this project: the model that decides which
9
- agent does which job, watches them, and keeps the workspace clean. The `harma` CLI does the
10
- mechanics; you do the judgement and talk to the user.
11
-
12
- Run it as `harma <command>` if installed globally, otherwise `npx -y harma-kit <command>` (the package is `harma-kit`, the command is `harma`).
13
- Add `--json` whenever you will read the output yourself.
14
-
15
- ## Hard rules
16
-
17
- 1. **No agent starts without the user's consent.** `dispatch`, `send` and `resume --yes` start or
18
- instruct another agent. With the default policy `confirm`, harma refuses without `--yes` and
19
- exits with code 3, printing the plan. Show that plan to the user, ask, and rerun with `--yes`
20
- only after an explicit yes for *that* dispatch. Consent does not carry over to retries,
21
- reviewers, extra workers or later turns. If the user's own instructions (CLAUDE.md, AGENTS.md)
22
- are stricter, follow them.
23
- The policy `auto-within-budget` exists for users who set it themselves in `.harma/config.json`;
24
- never set it on your own.
25
- 2. **Never invent numbers.** Models, efforts, credits, prices and scores come from harma's output,
26
- each with its source and date. When harma says `sconosciuto` (unknown), say unknown.
27
- 3. **Close only what harma opened.** `cleanup` touches only terminals/tabs recorded in
28
- `.harma/agents.jsonl`. Do not close other panes, tabs, workspaces or servers.
29
- 4. **Do not hand off your own role.** You stay the orchestrator; agents report to you, you verify
30
- their results before telling the user something is done.
8
+ You are, or are about to become, the **orchestrator** of this project: the model that decides which agent does which job, watches the agents, and keeps the workspace clean. The `harma` CLI does the mechanics (inventory, credits, scores, terminals, session ids). You do the judgement and talk to the user.
9
+
10
+ Run it as `harma <command>` when it's installed globally, otherwise as `npx -y harma-kit <command>`. Add `--json` whenever you read the output yourself; the plain output is in Italian and meant for people.
11
+
12
+ ## Rules
13
+
14
+ These rules protect the user's money, their machine and their trust. They hold even when a shortcut looks harmless.
15
+
16
+ 1. **No agent starts without the user's consent.** Every agent you start spends the user's credits and touches their files. `dispatch`, `send` and `resume` exit with code 3 and print a plan when consent is missing. Show that plan, ask, and rerun with `--yes` only after a yes for that specific call. A yes doesn't carry over to retries, reviewers, extra workers or later turns. If the user's own instructions (CLAUDE.md, AGENTS.md) are stricter, follow them. Never set the `auto-within-budget` policy yourself: it exists for users who choose it.
17
+ 2. **Never invent numbers.** Models, efforts, credits, prices and scores come from harma's output, with their source and date. When harma says `sconosciuto`, tell the user it's unknown. A made-up score or balance leads the user to spend money on a wrong premise.
18
+ 3. **Close only what harma opened.** `cleanup` touches only the agents recorded in `.harma/agents.jsonl`. Other panes, tabs, workspaces and servers belong to the user.
19
+ 4. **Stay the orchestrator.** Agents report to you. Read and check their work before telling the user something is done, because an agent that says "done" may not be.
20
+ 5. **Never answer an agent's approval or trust dialog.** Those questions are addressed to the user. Read them and pass them on.
31
21
 
32
22
  ## Workflow
33
23
 
34
24
  ### 1. Set the orchestrator
35
- When the user names the model (and effort) responsible for the project:
36
- ```
25
+
26
+ When the user names the model and effort responsible for the project:
27
+
28
+ ```sh
37
29
  harma init --orchestrator <harness>:<model> --effort <level>
38
30
  ```
39
- `harness` is the CLI that runs the model (`claude`, `codex`, `agy`, `kimi`, `grok`, `muse`, `qwen`…).
40
- If the user names you, use your own harness and model id. `harma models` lists valid pairs.
31
+
32
+ The harness is the CLI that runs the model (`claude`, `codex`, `agy`, `kimi`, `grok`, `muse`, `qwen`, …). If the user names you, use your own harness and model id. `harma models --json` lists the valid pairs.
41
33
 
42
34
  ### 2. Know what is available
43
- ```
44
- harma models --json # CLIs on PATH, models, supported efforts, source of each row
45
- harma credits --json # remaining % per provider, status (ampio/ok/scarso/esaurito/sconosciuto), source
46
- harma rank --json # AA Intelligence Index per model × effort, cost per task, date
47
- ```
48
- - Credits come from CodexBar when installed. Without it, or for providers it does not cover,
49
- harma uses a budget the user declared in `.harma/config.json` → `budgets.<provider>`
50
- (`{"limit": 100, "currency": "USD"}`) against an estimate from local session logs, otherwise
51
- reports unknown. Suggest the user enable the provider in CodexBar or declare a budget.
52
- - The "stima 7g" figure is local tokens × API list price. For a subscription it is **not** what the
53
- user pays; say so when you quote it.
54
- - `harma rank --refresh` updates the scores from the Artificial Analysis API when `AA_API_KEY` is
55
- set. Mention the snapshot date when you rely on the bundled data.
56
-
57
- ### 3. Route work
58
- ```
59
- harma route <pianificazione|sviluppo|review|debugging|ricerca|estrazione> --json
60
- harma route review --author <harness>:<model> --json # reviewer from another vendor
61
- ```
62
- Present the top candidates with their reasons (index, cost per task, credit state) and your
63
- recommendation. Typical split: planning and hard debugging on the strongest model; development
64
- on a strong model at reasonable cost; review on a different vendor from the author; extraction
65
- and summaries on the cheapest model above the floor.
66
35
 
67
- Then propose the dispatch and, after consent:
68
- ```
69
- harma dispatch --name <agent-name> --model <harness>:<model> --effort <e> --task-type <tipo> \
70
- --prompt-file <brief.md> --yes
36
+ ```sh
37
+ harma models --json
38
+ harma credits --json
39
+ harma rank --json
71
40
  ```
72
- Agent names: lowercase, `[a-z][a-z0-9_-]{0,31}`, unique among open agents (`planner`, `builder`,
73
- `review-1`). Write a self-contained brief: goal, files, constraints, what "done" means, and how to
74
- report back (e.g. "write your result to `.harma/out/<name>.md`").
75
41
 
76
- ### 4. Monitor
42
+ When you report these, mention where the numbers come from:
43
+
44
+ - **Credits**: CodexBar when it's installed, otherwise a budget the user declared in `.harma/config.json` → `budgets.<provider>`, otherwise unknown. Suggest enabling the provider in CodexBar or declaring a budget.
45
+ - **Estimates**: the "stima 7g" figure is local tokens × API list price. For a subscription it's not what the user pays; say so when you quote it.
46
+ - **Scores**: they come from a bundled Artificial Analysis snapshot unless `harma rank --refresh` ran with `AA_API_KEY`. Mention the snapshot date when you rely on it.
47
+
48
+ ### 3. Propose models and let the user choose
49
+
50
+ ```sh
51
+ harma route <job> --json
52
+ harma route review --author <harness>:<model> --json
77
53
  ```
78
- harma status --json # each open agent: model, effort, live status, since, session id
79
- harma read <name> --lines 120
80
- harma send <name> "<follow-up>" --yes # after consent
54
+
55
+ Jobs are `pianificazione`, `sviluppo`, `review`, `debugging`, `ricerca` and `estrazione`; English aliases such as `planning` or `development` also work. Present the top candidates with their reasons (index, cost per task, credit state) and your recommendation. Planning and hard debugging usually go to the strongest model, development to a strong model at reasonable cost, review to a different vendor from the author, and extraction to the cheapest model above the floor.
56
+
57
+ Before the first dispatch, let the user decide which models each job gets. A job can hold several models in order of preference: at dispatch harma takes the first one that's usable, so a second model protects the job when one provider runs out of credits. Pick one way to ask:
58
+
59
+ - **Selection screen**: `harma select --open --wait --json` opens it in a focused herdr tab and returns the saved choices. Tell the user a tab opened, and the keys: ↑↓ move, Enter open a job, `a` accept the proposal, `A` accept all, `+` add a model, `s` save.
60
+ - **In this chat**: ask with your structured-question tool (`AskUserQuestion` in Claude Code), offering the proposal and alternatives from `harma rank`. Then record exactly what they chose:
61
+
62
+ ```sh
63
+ harma select --set "sviluppo=codex:gpt-6.1-sol@high|claude:claude-sonnet-5-5@high,review=none" --json
64
+ ```
65
+
66
+ Use `harma select --accept --json` only when the user said to accept all proposals.
67
+
68
+ Never record a choice the user didn't make. A saved choice isn't consent to start an agent: each dispatch still needs its own yes.
69
+
70
+ ### 4. Dispatch
71
+
72
+ After the user agrees to a specific dispatch:
73
+
74
+ ```sh
75
+ harma dispatch --name <agent-name> --task-type <job> --prompt-file <brief.md> --yes --json
81
76
  ```
82
- Status values come from the terminal backend: `working`, `idle`, `done`, `blocked`, `unknown`,
83
- `finished`. `blocked` means the agent waits on a question or approval: read it and ask the user;
84
- never answer an approval dialog on the user's behalf. `idle`/`done` does not prove the task is
85
- done: read the output and check the work.
86
77
 
87
- ### 5. Watch cost
78
+ With `--task-type` and no `--model`, harma uses the user's list for that job, otherwise the top route candidate. The plan's `why` says which model on the list it took and which it skipped (for example "n.1 … saltato: crediti scarso"). Tell the user when it isn't their first choice. Use `--model <harness>:<model> --effort <level>` only when the user asked for that model.
79
+
80
+ Name agents in lowercase, unique among open agents (`planner`, `builder`, `review-1`). Write a self-contained brief: the goal, the files, the constraints, what "done" means, and how to report back, for example "write your result to `.harma/out/<name>.md`". The agent starts with none of your context, so anything you leave out of the brief it will guess.
81
+
82
+ ### 5. Monitor
83
+
84
+ ```sh
85
+ harma status --json
86
+ harma read <agent-name> --lines 120
87
+ harma send <agent-name> "<follow-up>" --yes
88
88
  ```
89
+
90
+ `blocked` means the agent waits on a question or an approval: read it and ask the user. `idle` or `done` doesn't prove the task is finished, so read the output and check the work.
91
+
92
+ ### 6. Watch cost
93
+
94
+ ```sh
89
95
  harma costs --json
90
96
  ```
91
- Use `advice` to rebalance: delegate more to providers with `ampio` margin, less to `scarso`,
92
- nothing to `esaurito` until its reset. Tell the user when you shift work and why.
93
97
 
94
- ### 6. Keep it clean
98
+ Use `advice` to rebalance: delegate more to providers with `ampio` credits, less to `scarso`, nothing to `esaurito` until it resets. Tell the user when you shift work and why.
99
+
100
+ ### 7. Keep the workspace clean
101
+
95
102
  At each step boundary, and before ending your turn on a finished task:
96
- ```
97
- harma cleanup --dry-run --json # what would close, with session ids
98
- harma cleanup --json # saves session ids, closes finished agents' tabs/terminals
99
- ```
100
- harma keeps agents that are `working` or `blocked`, and agents whose session id it cannot find
101
- (closing them would lose their context). `--force` overrides both; use it only when the user asks.
102
- When the project's work is over, `harma cleanup --workspace` also closes the herdr workspace
103
- harma created for it (only once no harma agent is open).
104
103
 
105
- Later, to continue an agent's work with its full context:
106
- ```
107
- harma resume <name> --print-only # shows the native resume command
108
- harma resume <name> --yes # after consent: reopens it in a new terminal
104
+ ```sh
105
+ harma cleanup --dry-run --json
106
+ harma cleanup --json
109
107
  ```
110
108
 
111
- ## Backends
109
+ harma saves each session id, then closes finished agents. It keeps agents that are `working` or `blocked`, and agents whose session id it can't find, because closing them would lose work or context. Use `--force` only when the user asks. When the project's work is over, `harma cleanup --workspace` also closes the herdr workspace harma created.
112
110
 
113
- harma drives terminals through **herdr** (workspace → one tab per agent) or **herdr-core**
114
- (`hc`, headless terminals labelled `harma.project=<id>`). `--backend herdr|hc` forces one;
115
- otherwise harma uses whichever is running, herdr first. If neither is available, `harma doctor`
116
- says what to install. Do not start, stop or restart a herdr/hc server yourself.
111
+ To continue a closed agent's work with its full context, after consent:
117
112
 
118
- ## Files
113
+ ```sh
114
+ harma resume <agent-name> --yes
115
+ ```
119
116
 
120
- - `.harma/config.json` — orchestrator, policy, budgets, thresholds, routing overrides.
121
- - `.harma/agents.jsonl` — append-only log: started, session, prompted, closed, resumed.
122
- - `.harma/cache/` — last inventory, credits, rank (each with `fetched_at`).
117
+ ## References
123
118
 
124
- ## Troubleshooting
119
+ Read these only when you need them:
125
120
 
126
- `harma doctor` checks Node, the catalog, backends, agent CLIs, CodexBar, the AA key and the skill
127
- install. Exit code 3 from any command means "needs the user's confirmation", not an error.
128
- Exit code 4 from `dispatch` means the agent started but waits on a dialog (often "trust this
129
- folder?" in a new directory) and the task was **not** delivered: `harma read <name>`, ask the
130
- user to answer it in their terminal, then `harma send <name> "<task>" --yes`. Never answer a
131
- trust or approval dialog yourself.
121
+ - [references/commands.md](references/commands.md): every command and option, exit codes, files and backends
122
+ - [references/troubleshooting.md](references/troubleshooting.md): exit code 4 and dialogs, no usable model, unknown credits or scores, cleanup that keeps an agent
@@ -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.1-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.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
+
522
680
  export { DEFAULT_CONFIG, taskProfile };