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.
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "harma-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A skill for Claude Code and Codex that lets one orchestrator model run a project: it inventories the models on your machine, reads their credits and intelligence per effort, routes work to them through herdr or herdr-core, watches cost, and saves every agent's session before closing it.",
5
+ "keywords": [
6
+ "claude-code",
7
+ "codex",
8
+ "skill",
9
+ "orchestration",
10
+ "multi-agent",
11
+ "herdr",
12
+ "coding-agents"
13
+ ],
14
+ "author": "matteoscurati",
15
+ "license": "MIT",
16
+ "homepage": "https://github.com/matteoscurati/harma#readme",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/matteoscurati/harma.git"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/matteoscurati/harma/issues"
23
+ },
24
+ "type": "module",
25
+ "bin": {
26
+ "harma": "bin/harma.mjs",
27
+ "harma-kit": "bin/harma.mjs"
28
+ },
29
+ "files": [
30
+ "bin/",
31
+ "src/",
32
+ "skill/",
33
+ "data/",
34
+ "README.md",
35
+ "CHANGELOG.md",
36
+ "LICENSE"
37
+ ],
38
+ "scripts": {
39
+ "test": "node --test tests/*.test.mjs",
40
+ "doctor": "node bin/harma.mjs doctor",
41
+ "import-catalog": "node scripts/import-catalog.mjs",
42
+ "prepublishOnly": "npm test"
43
+ },
44
+ "engines": {
45
+ "node": ">=20"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ }
50
+ }
package/skill/SKILL.md ADDED
@@ -0,0 +1,131 @@
1
+ ---
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.
4
+ ---
5
+
6
+ # harma
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.
31
+
32
+ ## Workflow
33
+
34
+ ### 1. Set the orchestrator
35
+ When the user names the model (and effort) responsible for the project:
36
+ ```
37
+ harma init --orchestrator <harness>:<model> --effort <level>
38
+ ```
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.
41
+
42
+ ### 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
+
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
71
+ ```
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
+
76
+ ### 4. Monitor
77
+ ```
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
81
+ ```
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
+
87
+ ### 5. Watch cost
88
+ ```
89
+ harma costs --json
90
+ ```
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
+
94
+ ### 6. Keep it clean
95
+ 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
+
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
109
+ ```
110
+
111
+ ## Backends
112
+
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.
117
+
118
+ ## Files
119
+
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`).
123
+
124
+ ## Troubleshooting
125
+
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.
@@ -0,0 +1,222 @@
1
+ // Terminal backends. Both expose the same interface:
2
+ // available() -> {ok, version, detail}
3
+ // start({name, cwd, argv, env, harness, project}) -> {target, tab?, sessionId?}
4
+ // list(project) -> [{target, name, status, cwd, sessionId, owned, raw}]
5
+ // prompt(target, text, {wait, timeoutSec})
6
+ // read(target, lines) -> text
7
+ // close(target) -> {ok}
8
+ // herdr: the full app (workspaces, tabs, panes); one tab per agent in a
9
+ // per-project workspace, so closing an agent closes its window.
10
+ // hc (herdr-core): headless terminals; ownership through labels.
11
+ import { basename } from 'node:path';
12
+ import { createHash } from 'node:crypto';
13
+ import { run, which, parseJson, HarmaError } from './util.mjs';
14
+ import { meta } from './harness.mjs';
15
+
16
+ export function projectId(root) {
17
+ return `${basename(root).toLowerCase().replace(/[^a-z0-9_-]/g, '-').slice(0, 20)}-${createHash('sha1').update(root).digest('hex').slice(0, 6)}`;
18
+ }
19
+
20
+ const AGENT_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
21
+ export function checkAgentName(name) {
22
+ if (!AGENT_NAME.test(name ?? '')) {
23
+ throw new HarmaError(`Nome agente non valido: ${name}`, { hint: 'Usa [a-z][a-z0-9_-]{0,31}, es. builder, review-1' });
24
+ }
25
+ }
26
+
27
+ function okJson(res, what) {
28
+ const data = parseJson(res.stdout);
29
+ if (!res.ok) {
30
+ const err = parseJson(res.stderr);
31
+ const e = new HarmaError(`${what} fallito: ${err?.error?.message ?? err?.message ?? (res.stderr.trim() || res.error || `exit ${res.code}`)}`);
32
+ e.code = err?.error?.code ?? null;
33
+ if (!e.code && /\bblocked\b/i.test(res.stderr)) e.code = 'agent_blocked';
34
+ throw e;
35
+ }
36
+ return data;
37
+ }
38
+
39
+ // ---------------------------------------------------------------- herdr
40
+ export class HerdrBackend {
41
+ constructor({ bin = 'herdr', env = process.env, config = {} } = {}) {
42
+ this.name = 'herdr';
43
+ this.bin = bin;
44
+ this.env = env;
45
+ this.config = config; // project config (holds herdr.workspace_id)
46
+ }
47
+
48
+ exec(args, opts = {}) { return run(this.bin, args, { env: this.env, ...opts }); }
49
+
50
+ async available() {
51
+ if (!which(this.bin, this.env)) return { ok: false, detail: 'herdr non è nel PATH' };
52
+ const res = await this.exec(['status', 'server'], { timeout: 15_000 });
53
+ const running = /status:\s*running/.test(res.stdout);
54
+ const version = (res.stdout.match(/version:\s*(\S+)/) ?? [])[1] ?? null;
55
+ return { ok: running, version, detail: running ? 'server attivo' : 'server herdr non attivo (avvia herdr)' };
56
+ }
57
+
58
+ async ensureWorkspace(root, project) {
59
+ const known = this.config.herdr?.workspace_id;
60
+ if (known) {
61
+ const got = await this.exec(['workspace', 'get', known]);
62
+ if (got.ok) return { id: known, created: false };
63
+ }
64
+ const res = await this.exec(['workspace', 'create', '--cwd', root, '--label', `harma:${project}`, '--no-focus']);
65
+ const data = okJson(res, 'herdr workspace create');
66
+ const id = data?.result?.workspace?.workspace_id ?? data?.result?.workspace?.id;
67
+ if (!id) throw new HarmaError('herdr workspace create: risposta senza workspace_id');
68
+ return { id, created: true };
69
+ }
70
+
71
+ async start({ name, cwd, argv, env = {}, harness, root, project }) {
72
+ checkAgentName(name);
73
+ const kind = meta(harness).herdrKind;
74
+ if (!kind) throw new HarmaError(`herdr non riconosce ${harness} come agente`, { hint: 'Usa --backend hc per questa CLI' });
75
+ const ws = await this.ensureWorkspace(root, project);
76
+ const tabArgs = ['tab', 'create', '--workspace', ws.id, '--cwd', cwd, '--label', name, '--no-focus'];
77
+ for (const [k, v] of Object.entries(env)) tabArgs.push('--env', `${k}=${v}`);
78
+ const tab = okJson(await this.exec(tabArgs), 'herdr tab create');
79
+ const tabId = tab?.result?.tab?.tab_id;
80
+ const paneId = tab?.result?.root_pane?.pane_id;
81
+ if (!tabId || !paneId) throw new HarmaError('herdr tab create: risposta senza tab_id/pane_id');
82
+ const startArgs = ['agent', 'start', name, '--kind', kind, '--pane', paneId, '--timeout', '60000'];
83
+ if (argv.length > 1) startArgs.push('--', ...argv.slice(1));
84
+ const started = await this.exec(startArgs, { timeout: 90_000 });
85
+ if (!started.ok) {
86
+ const err = parseJson(started.stderr);
87
+ // agent_not_ready keeps the agent: it is blocked at startup (e.g. trust dialog).
88
+ if (err?.error?.code !== 'agent_not_ready') {
89
+ await this.exec(['tab', 'close', tabId]);
90
+ okJson(started, 'herdr agent start');
91
+ }
92
+ }
93
+ return { target: name, tab: tabId, pane: paneId, workspace: ws.id, workspaceCreated: ws.created };
94
+ }
95
+
96
+ async list() {
97
+ const data = okJson(await this.exec(['agent', 'list']), 'herdr agent list');
98
+ return (data?.result?.agents ?? []).map((a) => ({
99
+ target: a.name ?? a.pane_id,
100
+ name: a.name ?? null,
101
+ kind: a.agent,
102
+ status: a.agent_status ?? null,
103
+ cwd: a.cwd,
104
+ tab: a.tab_id,
105
+ pane: a.pane_id,
106
+ sessionId: a.agent_session?.value ?? null,
107
+ raw: a,
108
+ }));
109
+ }
110
+
111
+ async prompt(target, text, { wait = false, timeoutSec = 600 } = {}) {
112
+ const args = ['agent', 'prompt', target, text];
113
+ if (wait) args.push('--wait', '--timeout', String(timeoutSec * 1000));
114
+ return okJson(await this.exec(args, { timeout: (timeoutSec + 30) * 1000 }), 'herdr agent prompt');
115
+ }
116
+
117
+ async read(target, lines = 120) {
118
+ const res = await this.exec(['agent', 'read', target, '--source', 'recent-unwrapped', '--lines', String(lines)]);
119
+ const data = parseJson(res.stdout);
120
+ if (!res.ok) okJson(res, 'herdr agent read');
121
+ return data?.result?.text ?? data?.result?.content ?? res.stdout;
122
+ }
123
+
124
+ async close({ tab, target }) {
125
+ if (!tab) throw new HarmaError(`Nessun tab registrato per ${target}: harma chiude solo le finestre che ha creato`);
126
+ const res = await this.exec(['tab', 'close', tab]);
127
+ return { ok: res.ok, detail: res.ok ? 'tab chiuso' : res.stderr.trim() };
128
+ }
129
+
130
+ /** Only for the workspace harma created for this project (config.herdr.workspace_id). */
131
+ async closeWorkspace(id) {
132
+ const res = await this.exec(['workspace', 'close', id]);
133
+ return { ok: res.ok, detail: res.ok ? `workspace ${id} chiuso` : res.stderr.trim() };
134
+ }
135
+ }
136
+
137
+ // ---------------------------------------------------------------- hc
138
+ export class HcBackend {
139
+ constructor({ bin = 'hc', env = process.env } = {}) {
140
+ this.name = 'hc';
141
+ this.bin = bin;
142
+ this.env = env;
143
+ }
144
+
145
+ exec(args, opts = {}) { return run(this.bin, args, { env: this.env, ...opts }); }
146
+
147
+ async available() {
148
+ if (!which(this.bin, this.env)) {
149
+ return { ok: false, detail: 'hc non è nel PATH (installa herdr-core: https://github.com/herdrdev/herdr-core)' };
150
+ }
151
+ const v = await this.exec(['--version'], { timeout: 10_000 });
152
+ const st = await this.exec(['server', 'status', '--json'], { timeout: 15_000 });
153
+ return { ok: st.ok, version: v.stdout.trim().split(/\s+/).pop() || null, detail: st.ok ? 'core attivo' : 'core non raggiungibile (hc server start)' };
154
+ }
155
+
156
+ async start({ name, cwd, argv, env = {}, project }) {
157
+ checkAgentName(name);
158
+ const args = ['run', '--bg', '--json', '--name', name, '--cwd', cwd,
159
+ '--label', `harma.project=${project}`, '--label', `harma.agent=${name}`, '--outlive-parent'];
160
+ const envPairs = Object.entries(env).map(([k, v]) => `${k}=${v}`);
161
+ args.push('--', ...(envPairs.length ? ['env', ...envPairs] : []), ...argv);
162
+ const data = okJson(await this.exec(args, { timeout: 60_000 }), 'hc run');
163
+ const t = data?.terminal ?? data?.result ?? data;
164
+ return { target: t?.name ?? name, address: t?.address ?? null };
165
+ }
166
+
167
+ async list(project) {
168
+ const args = ['ls', '--json', '--all'];
169
+ if (project) args.push('--label', `harma.project=${project}`);
170
+ const data = okJson(await this.exec(args), 'hc ls');
171
+ const terms = Array.isArray(data) ? data : (data?.terminals ?? []);
172
+ return terms.map((t) => ({
173
+ target: t.name ?? t.address,
174
+ name: t.name ?? null,
175
+ address: t.address,
176
+ status: t.state === 'finished' ? 'finished' : (t.status?.status ?? (typeof t.status === 'string' ? t.status : null)),
177
+ cwd: t.foreground?.cwd ?? t.cwd,
178
+ sessionId: null,
179
+ labels: t.labels ?? {},
180
+ raw: t,
181
+ }));
182
+ }
183
+
184
+ async prompt(target, text, { wait = false, timeoutSec = 600 } = {}) {
185
+ const args = ['send', '--json', target, text];
186
+ if (wait) args.push('--wait', '--timeout', String(timeoutSec));
187
+ return okJson(await this.exec(args, { timeout: (timeoutSec + 30) * 1000 }), 'hc send');
188
+ }
189
+
190
+ async read(target, lines = 120) {
191
+ const res = await this.exec(['read', target, '--lines', String(lines)]);
192
+ if (!res.ok) okJson(res, 'hc read');
193
+ return res.stdout;
194
+ }
195
+
196
+ async close({ target }) {
197
+ const k = await this.exec(['kill', '--json', target]);
198
+ const r = await this.exec(['rm', '--json', target]);
199
+ return { ok: k.ok || r.ok, detail: [k.ok ? 'terminato' : k.stderr.trim(), r.ok ? 'rimosso' : r.stderr.trim()].filter(Boolean).join('; ') };
200
+ }
201
+ }
202
+
203
+ /** Pick the backend: explicit, else configured, else the first that is running (herdr, then hc). */
204
+ export async function selectBackend({ choice, config = {}, env = process.env } = {}) {
205
+ const want = choice ?? (config.backend && config.backend !== 'auto' ? config.backend : null);
206
+ const make = (n) => (n === 'herdr' ? new HerdrBackend({ env, config }) : new HcBackend({ env }));
207
+ if (want) {
208
+ if (!['herdr', 'hc'].includes(want)) throw new HarmaError(`Backend sconosciuto: ${want}`, { hint: 'herdr | hc' });
209
+ const b = make(want);
210
+ const a = await b.available();
211
+ if (!a.ok) throw new HarmaError(`Backend ${want} non disponibile: ${a.detail}`);
212
+ return b;
213
+ }
214
+ const reasons = [];
215
+ for (const n of ['herdr', 'hc']) {
216
+ const b = make(n);
217
+ const a = await b.available();
218
+ if (a.ok) return b;
219
+ reasons.push(`${n}: ${a.detail}`);
220
+ }
221
+ throw new HarmaError('Nessun backend di terminali disponibile', { hint: reasons.join(' · ') });
222
+ }
@@ -0,0 +1,54 @@
1
+ // The model catalog: models, efforts, prices, Artificial Analysis figures,
2
+ // and how each agent CLI takes a model and an effort.
3
+ // The bundled snapshot (data/catalog.json) is overridden by a user-level
4
+ // refresh (~/.config/harma/catalog.json) when that one is newer.
5
+ import { join, dirname } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { homedir } from 'node:os';
8
+ import { readJson } from './util.mjs';
9
+
10
+ const BUNDLED = join(dirname(fileURLToPath(import.meta.url)), '..', 'data', 'catalog.json');
11
+
12
+ export function userCatalogPath(env = process.env) {
13
+ const base = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), '.config');
14
+ return join(base, 'harma', 'catalog.json');
15
+ }
16
+
17
+ export function loadCatalog({ env = process.env, path } = {}) {
18
+ if (path) return readJson(path);
19
+ const bundled = readJson(BUNDLED);
20
+ const user = readJson(userCatalogPath(env));
21
+ if (user && (user.generated_at ?? '') >= (bundled?.generated_at ?? '')) {
22
+ return { ...user, origin: 'user-refresh' };
23
+ }
24
+ return { ...bundled, origin: 'bundled' };
25
+ }
26
+
27
+ /** "claude-cli" -> "claude"; "claude-cli-zai" -> "claude-zai". */
28
+ export function harnessName(tool) {
29
+ return tool.replace(/-cli(-|$)/, (_, tail) => (tail ? '-' : ''));
30
+ }
31
+
32
+ /** Harnesses keyed by short name. */
33
+ export function harnesses(catalog) {
34
+ const out = {};
35
+ for (const [tool, h] of Object.entries(catalog.harnesses ?? {})) {
36
+ out[harnessName(tool)] = { tool, ...h };
37
+ }
38
+ return out;
39
+ }
40
+
41
+ /** AA index for a model at an effort: exact effort, else the model's only/"default" row. */
42
+ export function aaIndex(model, effort) {
43
+ const idx = model?.aa?.index;
44
+ if (!idx) return null;
45
+ if (idx[effort] !== undefined) return idx[effort];
46
+ if (idx.default !== undefined && Object.keys(idx).length === 1) return idx.default;
47
+ return null;
48
+ }
49
+
50
+ export function aaCost(model, effort) {
51
+ const c = model?.aa?.cost_per_task;
52
+ if (!c) return null;
53
+ return c[effort] ?? (Object.keys(c).length === 1 ? Object.values(c)[0] : null);
54
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,92 @@
1
+ import {
2
+ cmdInit, cmdModels, cmdCredits, cmdRank, cmdRoute, cmdDispatch, cmdSend, cmdRead,
3
+ cmdStatus, cmdCosts, cmdCleanup, cmdResume,
4
+ } from './commands.mjs';
5
+ import { cmdInstall, cmdUninstall, cmdDoctor } from './install.mjs';
6
+ import { HarmaError } from './util.mjs';
7
+
8
+ const BOOLEAN = new Set(['json', 'yes', 'wait', 'refresh', 'dry-run', 'force', 'all', 'print-only', 'help', 'version', 'workspace']);
9
+
10
+ export function parseArgs(argv) {
11
+ const flags = { _: [] };
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const a = argv[i];
14
+ if (a === '--') { flags._.push(...argv.slice(i + 1)); break; }
15
+ if (a.startsWith('--')) {
16
+ const [k, inline] = a.slice(2).split(/=(.*)/s);
17
+ if (inline !== undefined) flags[k] = inline;
18
+ else if (BOOLEAN.has(k)) flags[k] = true;
19
+ else if (i + 1 < argv.length) flags[k] = argv[++i];
20
+ else throw new HarmaError(`--${k} richiede un valore`);
21
+ } else if (a === '-h') flags.help = true;
22
+ else flags._.push(a);
23
+ }
24
+ return flags;
25
+ }
26
+
27
+ export const HELP = `harma — un modello orchestratore che dirige gli altri agenti del progetto
28
+
29
+ Uso: harma <comando> [opzioni] (--json su ogni comando per output leggibile da un agente)
30
+
31
+ Progetto
32
+ init --orchestrator <harness>:<model> --effort <level> [--backend auto|herdr|hc] [--policy confirm|auto-within-budget]
33
+
34
+ Conoscere le risorse
35
+ models CLI di agenti, modelli ed effort su questa macchina
36
+ credits crediti e limiti per provider (CodexBar, budget, stima dai log)
37
+ rank [--refresh] [--top N] intelligenza per modello × effort (Artificial Analysis)
38
+ route <tipo> [--author h:m] classifica per: pianificazione, sviluppo, review, debugging, ricerca, estrazione
39
+
40
+ Delegare (con policy "confirm" serve --yes, dopo il consenso dell'utente)
41
+ dispatch --name <n> (--model h:m [--effort e] | --task-type <tipo>) [--prompt "…" | --prompt-file f] [--wait] [--yes]
42
+ send <nome> "<testo>" [--wait] [--yes]
43
+ read <nome> [--lines N]
44
+
45
+ Sorvegliare
46
+ status [--all] stato di ogni agente aperto
47
+ costs costo per agente, crediti per provider, indicazioni di delega
48
+
49
+ Pulire e riprendere
50
+ cleanup [--dry-run] [--agent <nome>] [--force] [--workspace] salva l'id di sessione e chiude le finestre finite
51
+ resume <nome> [--yes] [--print-only] riapre la sessione salvata con il suo contesto
52
+
53
+ Installazione
54
+ install [--target claude|codex|both] [--force] installa la skill
55
+ uninstall [--target …]
56
+ doctor controlla l'ambiente
57
+ `;
58
+
59
+ const COMMANDS = {
60
+ init: cmdInit, models: cmdModels, credits: cmdCredits, rank: cmdRank, route: cmdRoute,
61
+ dispatch: cmdDispatch, send: cmdSend, read: cmdRead, status: cmdStatus, costs: cmdCosts,
62
+ cleanup: cmdCleanup, resume: cmdResume, install: cmdInstall, uninstall: cmdUninstall, doctor: cmdDoctor,
63
+ };
64
+
65
+ export async function main(argv, opts = {}) {
66
+ const out = opts.out ?? ((s) => process.stdout.write(s + '\n'));
67
+ const err = opts.err ?? ((s) => process.stderr.write(s + '\n'));
68
+ let flags;
69
+ try { flags = parseArgs(argv); } catch (e) { err(`harma: ${e.message}`); return 2; }
70
+ const [cmd, ...rest] = flags._;
71
+ if (flags.version || cmd === 'version') {
72
+ const { readFileSync } = await import('node:fs');
73
+ out(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
74
+ return 0;
75
+ }
76
+ if (!cmd || flags.help || cmd === 'help') { out(HELP); return 0; }
77
+ const fn = COMMANDS[cmd];
78
+ if (!fn) { err(`harma: comando sconosciuto "${cmd}"\n\n${HELP}`); return 2; }
79
+ flags._ = rest;
80
+ try {
81
+ const res = await fn(flags, { ...opts, out });
82
+ return res?.exitCode ?? 0;
83
+ } catch (e) {
84
+ if (e instanceof HarmaError) {
85
+ if (flags.json) out(JSON.stringify({ error: e.message, hint: e.hint ?? null }));
86
+ else err(`harma: ${e.message}${e.hint ? `\n → ${e.hint}` : ''}`);
87
+ return e.exitCode ?? 1;
88
+ }
89
+ err(`harma: errore inatteso: ${e.stack ?? e}`);
90
+ return 1;
91
+ }
92
+ }