@haven_ai/cli 0.1.33-alpha.0 → 0.1.35-alpha.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/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { rm, mkdir, writeFile, chmod, readFile } from 'fs/promises';
2
2
  import { homedir } from 'os';
3
3
  import { join, resolve } from 'path';
4
+ import { spawn } from 'child_process';
4
5
 
5
6
  // src/args.ts
6
7
  var VALUE_FLAGS = /* @__PURE__ */ new Set([
@@ -14,24 +15,53 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
14
15
  "--format",
15
16
  "--from",
16
17
  "--to",
17
- "--company"
18
+ "--company",
19
+ "--name",
20
+ "--budget",
21
+ "--token",
22
+ "--period",
23
+ "--status",
24
+ "--amount",
25
+ "--recipient",
26
+ "--expires"
18
27
  ]);
19
28
  function parseArgs(argv) {
20
29
  const positionals = [];
21
- const flags = { json: false, help: false, version: false, yes: false };
30
+ const flags = {
31
+ json: false,
32
+ help: false,
33
+ version: false,
34
+ yes: false,
35
+ noWait: false,
36
+ run: false,
37
+ wait: false,
38
+ hashes: false
39
+ };
22
40
  for (let i = 0; i < argv.length; i += 1) {
23
41
  const arg = argv[i];
24
42
  if (arg === "--json") flags.json = true;
25
43
  else if (arg === "--help" || arg === "-h") flags.help = true;
26
44
  else if (arg === "--version" || arg === "-v") flags.version = true;
27
45
  else if (arg === "--yes" || arg === "-y") flags.yes = true;
46
+ else if (arg === "--no-wait") flags.noWait = true;
47
+ else if (arg === "--run") flags.run = true;
48
+ else if (arg === "--wait") flags.wait = true;
49
+ else if (arg === "--hashes") flags.hashes = true;
28
50
  else if (VALUE_FLAGS.has(arg)) {
29
51
  const value = argv[++i];
30
52
  if (value === void 0 || value.startsWith("--")) {
31
53
  throw new Error(`Missing value for ${arg}`);
32
54
  }
33
55
  if (arg === "--api") flags.api = value;
34
- else if (arg === "--email") flags.email = value;
56
+ else if (arg === "--name") flags.name = value;
57
+ else if (arg === "--budget") flags.budget = value;
58
+ else if (arg === "--token") flags.token = value;
59
+ else if (arg === "--status") flags.status = value;
60
+ else if (arg === "--period") {
61
+ const n = Number(value);
62
+ if (!Number.isInteger(n) || n < 0) throw new Error("--period must be a whole number of minutes");
63
+ flags.period = n;
64
+ } else if (arg === "--email") flags.email = value;
35
65
  else if (arg === "--safe") flags.safe = value;
36
66
  else if (arg === "--agent") flags.agent = value;
37
67
  else if (arg === "--limit") {
@@ -45,6 +75,14 @@ function parseArgs(argv) {
45
75
  } else if (arg === "--direction") {
46
76
  if (value !== "in" && value !== "out") throw new Error('--direction must be "in" or "out"');
47
77
  flags.direction = value;
78
+ } else if (arg === "--recipient") {
79
+ flags.recipient = value;
80
+ } else if (arg === "--amount") {
81
+ flags.amount = value;
82
+ } else if (arg === "--expires") {
83
+ const n = Number(value);
84
+ if (!Number.isInteger(n) || n <= 0) throw new Error("--expires must be a unix timestamp in seconds");
85
+ flags.expires = n;
48
86
  } else if (arg === "--format") {
49
87
  if (value !== "csv" && value !== "sie") throw new Error('--format must be "csv" or "sie"');
50
88
  flags.format = value;
@@ -62,21 +100,35 @@ function parseArgs(argv) {
62
100
  }
63
101
  function helpText() {
64
102
  return [
65
- "haven \u2014 terminal-native companion to the Haven dashboard",
103
+ "haven \u2014 set up and run a Haven agent from the terminal. It never signs.",
66
104
  "",
67
105
  "Usage: haven <command> [subcommand] [options]",
68
106
  "",
69
107
  "Auth:",
70
- " login [--email <e>] Sign in (password via prompt or HAVEN_PASSWORD)",
108
+ " login Sign in. Opens a browser device-code approval by default \u2014",
109
+ " it prints a code and a link, and never asks for a password",
110
+ " login --email <e> Password path instead (prompt, or HAVEN_PASSWORD)",
71
111
  " logout Clear the saved session",
72
- " whoami Show the signed-in user",
112
+ " whoami Show the signed-in user, session expiry and API URL",
113
+ "",
114
+ "For agents:",
115
+ " guide Print the agent onboarding runbook (same text as /for-agents.md)",
116
+ " agents connect --name <n> --budget <amount> --token USDC --period <minutes>",
117
+ " Create a connection setup; prints the connector command and",
118
+ " the approval link for your human. --run executes it here.",
119
+ " agents connect --status <setupId> [--wait] Read one setup's status",
73
120
  "",
74
121
  "Read:",
75
122
  " wallets list List your Haven wallets",
76
123
  " wallets balances [--safe <id|address>] Token balances for a wallet",
124
+ " wallets funding [--safe <id|address>] [--wait] The paste-ready funding",
125
+ " instruction: what to send, where, on which chain.",
126
+ " --wait polls until the account counts as funded.",
77
127
  " agents list List your agents",
78
128
  " agents show <id> Show one agent + its budget",
79
129
  " budget show <agentId> Show an agent's configured budget",
130
+ " budget show <agentId> --hashes Its delegation hashes \u2014 the second",
131
+ " argument `budget revoke` takes, printed nowhere else",
80
132
  " activity list [--safe <id|address>] [--agent <id>] [--direction in|out] [--limit <n>] [--offset <n>]",
81
133
  " activity export [filters] Emit CSV to stdout (--format csv, default)",
82
134
  " activity export --format sie [--from <ISO>] [--to <ISO>] [--company <name>]",
@@ -85,19 +137,33 @@ function helpText() {
85
137
  " contacts list List your address book",
86
138
  "",
87
139
  "Manage (backend-only \u2014 no on-chain signing):",
88
- " agents pause|resume <id>",
140
+ " agents pause <id> Stop the agent spending; keeps its budget",
141
+ " agents resume <id> Let it spend again",
89
142
  " agents revoke <id> --yes Permanently revoke an agent",
90
143
  " agents rotate-key <id> Issue a new API key (shown once)",
91
144
  " agents rename <id> <name>",
92
145
  " wallets rename <id> <name>",
93
- " contacts add <name> <address> | contacts remove <id>",
146
+ " contacts add <name> <address> Save an address under a name",
147
+ " contacts remove <id> Forget one",
148
+ "",
149
+ "Budgets (construct-and-hand-off \u2014 the CLI never signs, #2539):",
150
+ " budget grant <agentId> --amount <n> --token USDC --period <minutes>",
151
+ " [--recipient <address>] [--expires <unix-s>] [--wait]",
152
+ " Prints a signing link; the human signs in the dashboard.",
153
+ " budget revoke <agentId> <delegationHash> [--wait]",
154
+ " Prints a revocation link; the human signs in the dashboard.",
94
155
  "",
95
156
  "Options:",
96
- " --json Machine-readable output (for scripting)",
157
+ " --json One JSON value on stdout, prose on stderr, on every",
158
+ " command including refusals: { ok: false, error: { code, message, hint? } }",
97
159
  " --yes, -y Skip the confirmation prompt for destructive actions",
98
- " --api <url> Backend URL (default: HAVEN_API_URL or http://localhost:3001)",
160
+ " --api <url> Backend URL. Default: HAVEN_API_URL, else Haven's hosted",
161
+ " production backend \u2014 NOT localhost. On any other",
162
+ " deployment an omitted flag connects to production.",
99
163
  " --help, --version",
100
164
  "",
165
+ "Exit codes: 0 ok \xB7 1 failed \xB7 2 usage \xB7 3 not authenticated \xB7 4 refused \xB7 5 network",
166
+ "",
101
167
  "On-chain actions (deploy, budgets, approvers, send) are signed in the",
102
168
  "dashboard \u2014 this CLI reads and manages; it never holds your keys."
103
169
  ].join("\n");
@@ -106,10 +172,20 @@ function helpText() {
106
172
  // src/api.ts
107
173
  var CliApiError = class extends Error {
108
174
  status;
109
- constructor(message, status) {
175
+ /**
176
+ * The parsed response body, when there was one (#2526).
177
+ *
178
+ * The message is built FROM `body.error` for humans, and the device flow
179
+ * needs the same value as DATA: `authorization_pending` and `slow_down` are
180
+ * control signals in a poll loop, and branching on them by matching the
181
+ * message string would make the loop depend on prose that is free to change.
182
+ */
183
+ body;
184
+ constructor(message, status, body) {
110
185
  super(message);
111
186
  this.name = "CliApiError";
112
187
  this.status = status;
188
+ this.body = body;
113
189
  }
114
190
  };
115
191
  function createCliApi({ baseUrl, token, fetchImpl = fetch }) {
@@ -138,7 +214,7 @@ function createCliApi({ baseUrl, token, fetchImpl = fetch }) {
138
214
  const payload = text ? safeParse(text) : void 0;
139
215
  if (!res.ok) {
140
216
  const message = (payload && typeof payload === "object" && "error" in payload && typeof payload.error === "string" ? payload.error : null) ?? `Request failed (HTTP ${res.status}).`;
141
- throw new CliApiError(message, res.status);
217
+ throw new CliApiError(message, res.status, payload);
142
218
  }
143
219
  return payload;
144
220
  }
@@ -240,63 +316,344 @@ function toCsv(headers, rows) {
240
316
  return lines.join("\r\n");
241
317
  }
242
318
 
319
+ // src/errors.ts
320
+ var EXIT = {
321
+ ok: 0,
322
+ /** Something failed and none of the specific codes below describe it. */
323
+ failed: 1,
324
+ /** The command line was wrong: unknown command, missing argument, bad flag. */
325
+ usage: 2,
326
+ /** No stored session, or the backend rejected the one we have. Log in again. */
327
+ notAuthenticated: 3,
328
+ /** Authenticated, and the backend refused anyway (403, 410, other 4xx). */
329
+ refused: 4,
330
+ /** The backend could not be reached at all. */
331
+ network: 5
332
+ };
333
+ var UsageError = class extends Error {
334
+ hint;
335
+ constructor(message, hint) {
336
+ super(message);
337
+ this.name = "UsageError";
338
+ this.hint = hint;
339
+ }
340
+ };
341
+ var HavenCliError = class extends Error {
342
+ exit;
343
+ hint;
344
+ constructor(message, exit, hint) {
345
+ super(message);
346
+ this.name = "HavenCliError";
347
+ this.exit = exit;
348
+ this.hint = hint;
349
+ }
350
+ };
351
+ function toFailure(err) {
352
+ if (err instanceof UsageError) {
353
+ return { code: "usage", exit: EXIT.usage, message: err.message, hint: err.hint };
354
+ }
355
+ if (err instanceof HavenCliError) {
356
+ const code = err.exit === EXIT.notAuthenticated ? "not_authenticated" : err.exit === EXIT.refused ? "refused" : err.exit === EXIT.network ? "network" : "failed";
357
+ return { code, exit: err.exit, message: err.message, hint: err.hint };
358
+ }
359
+ if (err instanceof CliApiError) {
360
+ if (err.status === 0) {
361
+ return {
362
+ code: "network",
363
+ exit: EXIT.network,
364
+ message: err.message,
365
+ hint: "Check the network and `--api`, then retry."
366
+ };
367
+ }
368
+ if (err.status === 401) {
369
+ return {
370
+ code: "not_authenticated",
371
+ exit: EXIT.notAuthenticated,
372
+ message: err.message,
373
+ hint: "Run `haven login` (or set HAVEN_EMAIL and HAVEN_PASSWORD)."
374
+ };
375
+ }
376
+ if (err.status >= 400 && err.status < 500) {
377
+ return { code: "refused", exit: EXIT.refused, message: err.message };
378
+ }
379
+ return { code: "failed", exit: EXIT.failed, message: err.message };
380
+ }
381
+ return { code: "failed", exit: EXIT.failed, message: err instanceof Error ? err.message : String(err) };
382
+ }
383
+
384
+ // src/output.ts
385
+ function createOutput(json, out, err) {
386
+ return {
387
+ json,
388
+ data(payload, human) {
389
+ out(json ? JSON.stringify(payload, null, 2) : human());
390
+ },
391
+ text(content, meta) {
392
+ out(json ? JSON.stringify({ ok: true, ...meta, content }, null, 2) : content);
393
+ },
394
+ note(line) {
395
+ if (json) err(line);
396
+ else out(line);
397
+ },
398
+ failure(failure) {
399
+ const body = {
400
+ ok: false,
401
+ error: {
402
+ code: failure.code,
403
+ message: failure.message,
404
+ ...failure.hint ? { hint: failure.hint } : {}
405
+ }
406
+ };
407
+ if (json) out(JSON.stringify(body, null, 2));
408
+ else err(failure.hint ? `${failure.message}
409
+ ${failure.hint}` : failure.message);
410
+ }
411
+ };
412
+ }
413
+
414
+ // src/agent-guidance-text.ts
415
+ var HAVEN_AGENT_RUNBOOK_MD = "# Haven for agents \u2014 set your user up to let you pay\n\nYou are an AI agent whose user has no Haven account yet, or has one but has not connected you.\n\n> Links below are paths on this same host: resolve them against the URL you fetched this file from.\n\n## What Haven is, in three sentences\n\nYour user gives you a **budget on their own account** \u2014 not their wallet, and not a key to their funds. The budget is a delegation they sign, enforced on-chain: a payment over it, to the wrong recipient, or past its expiry is refused at execution time, not by a dashboard promise. Haven constructs and relays the payments; you get an agent credential and a signing key made on your machine, and your user can revoke the budget without you and without Haven.\n\n## The sequence\n\nFour of the six steps are your user's \u2014 each needs a human signature or a human decision. The rest is yours. If they already have a funded account, start at step 3.\n\n1. **HUMAN \u2014 create the account.** Name, email, password, then a passkey (Face ID / Touch ID) or a wallet. Never offer to enter any of it: you must not have their password, and the passkey is bound to their device. With a terminal, `npx @haven_ai/cli login --api <api-url>` afterwards gets you a scoped session for steps 3-4 (that flag or `HAVEN_API_URL`, on the first command \u2014 the session then remembers the backend; **the CLI's built-in default is Haven's hosted production backend**, so on any other deployment an omitted flag connects you somewhere real and wrong rather than failing) \u2014 they approve a code in the browser, you never hold their password. It can set up agents and read the account; it cannot sign, approve a budget, move funds, or rotate any agent's keys.\n2. **HUMAN \u2014 fund it.** USDC only, no ETH: Haven sponsors the gas. `haven wallets funding` prints the address, the amount **and which chain** in one place; without a CLI session, the dashboard's funding card shows the address and amount and its Receive-funds screen names the chain. Read the chain off whichever you used and put it in your message \u2014 never assume one: a testnet deployment and production both call themselves Haven.\n3. **HUMAN \u2014 create the agent, set its budget**, and paste you the **setup prompt** it hands back. With a CLI session (step 1) you can do this step yourself: `haven agents connect --name <n> --budget <amount> --token USDC --period <minutes>` prints the same connector command and approval link; add `--run` to do step 4 too.\n4. **YOU \u2014 run the connector command** in that prompt (below). It makes your signing key locally, registering only the public address.\n5. **HUMAN \u2014 approve the budget** with their passkey, in the Haven tab they created the agent in: it advances to the approval step by itself once your run registers.\n6. **YOU \u2014 verify, then pay.**\n\n## Budget changes later (second token, raise, revoke)\n\nThe first budget rides the setup above. After the agent exists, a CLI session can construct the LATER changes \u2014 a second token, a bigger amount, a recipient pin, a stop \u2014 and hand your user a link; the human still signs, every time:\n\n```\nhaven budget grant <agentId> --amount <n> --token USDC --period <minutes> [--recipient <address>] [--wait]\nhaven budget revoke <agentId> <delegationHash> [--wait]\n```\n\nThe CLI never signs: it prints a dashboard link, your user opens it and signs with their passkey or wallet. `--wait` polls until the human's signature lands. The hash for `revoke` is in `haven agents show <agentId>`.\n\n## Hand-off scripts\n\nSend these as your own message, `<host>` replaced by the host you fetched this file from. Say what you cannot do, not only what they must.\n\n**Before signup** (step 1):\n\n> I can do everything except the parts that need your signature. Please open `<host>/signup?next=/agents&via=agent` \u2014 name, email, password, then a passkey (Face ID / Touch ID) or a wallet. That is your account's key: I should not have it, and I will never ask for your password. Already have one? `<host>/login?next=/agents`.\n\n**At the passkey step:**\n\n> The passkey must be made on your own device \u2014 it is what keeps the account yours, so nobody, Haven included, can move your funds without you. If this browser cannot, open `<host>/onboarding?next=/agents` on your phone and finish there.\n\n**At funding** (step 2):\n\n> Your Haven account needs USDC before I can pay for anything \u2014 USDC only, no ETH: Haven sponsors the gas. Before you send anything, let me get you the exact address **and network** \u2014 `haven wallets funding` prints both, and the funding card on `<host>/dashboard` shows the same. Please do not send to an address or a chain I have not confirmed with you; a small amount first is fine.\n\n**At the budget** (step 3):\n\n> On `<host>/agents`, create an agent for me and set a budget \u2014 say 25 USDC per day. That is the limit I cannot exceed. It hands back a setup prompt: paste it to me and I run it here.\n\n**At budget approval** (step 5) \u2014 the moment your run reports that approval is required, before anything else. Send the first if your run carried `approval.url`, the second if it did not.\n\n> Setup is done on my side. Approve the budget here: <approval.url>. Approve it with your passkey; nothing can be spent until you do.\n\n> Setup is done on my side. Go back to the Haven tab where you created the agent \u2014 it should now be asking you to approve the budget. Approve it with your passkey; nothing can be spent until you do.\n\n## What you run\n\nThe setup prompt carries a **connector command** shaped like this:\n\n```\nnpx -y @haven_ai/connect@<channel> --setup EXAMPLE-SETUP-TOKEN-NOT-REAL --api <api-url> --ack-local-tools\n```\n\nRun the prompt's version, not this one: the token is one-time, the API URL is the backend's own, and `<channel>` is the npm tag your prompt names \u2014 never a tag you pick. The rules below come from that prompt, so \"me\" in them is your user, not Haven.\n\n- If you are an AI agent running this command yourself rather than a human pasting it, you should append --json: the connector then emits one machine-readable, secret-free result object on stdout with progress on stderr, and returns promptly instead of blocking while it waits for the budget approval.\n- When a --json outcome reports approval.required: true, your first action must be to relay the approval instruction to me in your own reply \u2014 if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget \u2014 before verifying the connection, restarting anything, or any other step. Never build that link yourself: relay the one the outcome gave you or none at all. Any restart the outcome asks for is a separate instruction to give me afterwards, once the approval is done.\n- If you ran the command without --json, the connector waits for the approval itself and prints its next steps when it finishes: relay the budget-approval instruction to me \u2014 the approval link if those steps printed one, otherwise that you need to return to Haven and approve this agent's budget \u2014 only if those printed next steps still ask for it. If they report the budget as already approved, there is nothing for me to approve.\n- Only two changes to the command above are permitted, and no others: appending --json, and \u2014 only if the connector refuses because it could not determine the agent runtime \u2014 re-running it once with --runtime <name> added, naming the harness you are running in, using one of the values that refusal lists. Never invent a runtime name and never change anything else.\n- Do not print private keys, API keys, credential file contents, or config secrets in chat or logs.\n\nIf the approval wait times out, nothing is lost \u2014 your agent is registered and the budget is still waiting to be approved. Send your user the `approval.url` your run reported, or, if it carried none, ask them to finish it in that same Haven tab. The outcome carries no setup id, so never assemble an approval link out of parts \u2014 relay the whole one it gave you or none at all.\n\n## How to verify\n\nCall `haven_get_agent`, one of the Haven MCP tools the connector wires into your runtime in step 4. It returns identity plus `spend_authority_readiness`:\n\n- `ready` \u2014 a budget is live; you can pay.\n- `needs_approval` \u2014 the connector finished, nobody approved yet. Ask your user again, in their Haven tab; there is no queue to wait in.\n- `revoked` \u2014 the credential is not active; ask your user to create a new agent.\n\n`ready` covers hosted identity and the budget only, not your local signer. Check that with `npx -y @haven_ai/connect@<channel> --doctor`, the same tag your prompt named \u2014 a separate command, so the two-changes rule does not bind it.\n\n## If you cannot open a browser\n\nNothing here needs you to. Steps 1-3 are links: hand your user the full `<host>/\u2026` URL and ask them to say when it is done. Step 5 is a link only when your run reported one in `approval.url` \u2014 otherwise it is the tab they already have open, as above. Then poll `haven_get_agent` until it reads `ready`. Do not route around the sign-in wall \u2014 it makes the account theirs, not yours.\n\n## Vocabulary\n\n| Term | What it is |\n|---|---|\n| **setup prompt** | The text the dashboard hands your user to paste to you. Carries the command and its rules. |\n| **connector command** | The `npx -y @haven_ai/connect@\u2026` line you run. One-time token, one use. |\n| **agent credential** | Your API key (`sk_agent_\u2026`), written to `~/.haven`. It identifies you; alone it cannot move money. |\n| **delegate key** | Your signing key, made on this machine and never sent anywhere. |\n| **budget** | The on-chain delegation your user signed. It authorises the payment; Haven constructs and relays it. |\n\nNext: [your agent hit a 402](/402.md) \xB7 [everything agent-readable](/llms.txt)\n";
416
+
417
+ // src/token.ts
418
+ function sessionExpiry(token) {
419
+ const segment = token.split(".")[1];
420
+ if (!segment) return null;
421
+ try {
422
+ const json = Buffer.from(segment.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
423
+ const claims = JSON.parse(json);
424
+ if (typeof claims.exp !== "number" || !Number.isFinite(claims.exp)) return null;
425
+ return new Date(claims.exp * 1e3).toISOString();
426
+ } catch {
427
+ return null;
428
+ }
429
+ }
430
+
431
+ // src/amount.ts
432
+ function decimalLabel(decimals) {
433
+ return decimals === 1 ? "1 decimal place" : `${decimals} decimal places`;
434
+ }
435
+ function parseTokenAmount(input, decimals, tokenSymbol) {
436
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 36) {
437
+ return { ok: false, message: `Unusable token decimals: ${String(decimals)}` };
438
+ }
439
+ const trimmed = String(input ?? "").trim();
440
+ const human = trimmed.startsWith(".") ? `0${trimmed}` : trimmed;
441
+ const label = tokenSymbol ? ` ${tokenSymbol}` : "";
442
+ if (human === "") return { ok: false, message: "Enter an amount greater than 0" };
443
+ if (!/^\d+(?:\.\d+)?$/.test(human)) {
444
+ return { ok: false, message: `Enter a valid${label} amount \u2014 digits, with an optional decimal point` };
445
+ }
446
+ const [whole, fraction = ""] = human.split(".");
447
+ if (fraction.length > decimals) {
448
+ return {
449
+ ok: false,
450
+ message: `${tokenSymbol ?? "This token"} supports up to ${decimalLabel(decimals)}`
451
+ };
452
+ }
453
+ const atomic = BigInt(`${whole}${fraction.padEnd(decimals, "0")}`);
454
+ if (atomic === 0n) return { ok: false, message: "Enter an amount greater than 0" };
455
+ return { ok: true, human, atomic: atomic.toString() };
456
+ }
457
+ function splitConnectorCommand(command) {
458
+ const argv = [];
459
+ let current = "";
460
+ let quoted = false;
461
+ let started = false;
462
+ for (let i = 0; i < command.length; i += 1) {
463
+ const ch = command[i];
464
+ if (quoted) {
465
+ if (ch === "'") quoted = false;
466
+ else current += ch;
467
+ continue;
468
+ }
469
+ if (ch === "'") {
470
+ quoted = true;
471
+ started = true;
472
+ continue;
473
+ }
474
+ if (ch === " " || ch === " ") {
475
+ if (started) argv.push(current);
476
+ current = "";
477
+ started = false;
478
+ continue;
479
+ }
480
+ if (ch === "\\") {
481
+ if (command[i + 1] === "'") {
482
+ current += "'";
483
+ started = true;
484
+ i += 1;
485
+ continue;
486
+ }
487
+ throw new Error("Refusing to run a connector command with a backslash escape");
488
+ }
489
+ if (ch === '"' || ch === "`" || ch === "$" || ch === "|" || ch === "&" || ch === ";" || ch === ">" || ch === "<" || ch === "(" || ch === ")" || ch === "\n") {
490
+ throw new Error(`Refusing to run a connector command containing ${JSON.stringify(ch)}`);
491
+ }
492
+ current += ch;
493
+ started = true;
494
+ }
495
+ if (quoted) throw new Error("Refusing to run a connector command with an unterminated quote");
496
+ if (started) argv.push(current);
497
+ if (argv.length === 0) throw new Error("The backend returned an empty connector command");
498
+ return argv;
499
+ }
500
+ var nodeSpawner = (command, args, onStderr) => new Promise((resolve2, reject) => {
501
+ const child = spawn(command, args, { shell: false, stdio: ["ignore", "pipe", "pipe"] });
502
+ let stdout = "";
503
+ let stderr = "";
504
+ child.stdout.setEncoding("utf8");
505
+ child.stderr.setEncoding("utf8");
506
+ child.stdout.on("data", (chunk) => {
507
+ stdout += chunk;
508
+ });
509
+ child.stderr.on("data", (chunk) => {
510
+ stderr += chunk;
511
+ onStderr(chunk);
512
+ });
513
+ child.on("error", reject);
514
+ child.on("close", (code) => resolve2({ stdout, stderr, exitCode: code ?? 1 }));
515
+ });
516
+ function parseOutcome(stdout) {
517
+ const noise = [];
518
+ let outcome = null;
519
+ let depth = 0;
520
+ let start = -1;
521
+ let inString = false;
522
+ let escaped = false;
523
+ let plain = "";
524
+ for (let i = 0; i < stdout.length; i += 1) {
525
+ const ch = stdout[i];
526
+ if (depth === 0) {
527
+ if (ch === "{") {
528
+ depth = 1;
529
+ start = i;
530
+ inString = false;
531
+ escaped = false;
532
+ } else {
533
+ plain += ch;
534
+ }
535
+ continue;
536
+ }
537
+ if (inString) {
538
+ if (escaped) escaped = false;
539
+ else if (ch === "\\") escaped = true;
540
+ else if (ch === '"') inString = false;
541
+ continue;
542
+ }
543
+ if (ch === '"') inString = true;
544
+ else if (ch === "{") depth += 1;
545
+ else if (ch === "}") {
546
+ depth -= 1;
547
+ if (depth === 0) {
548
+ const candidate = stdout.slice(start, i + 1);
549
+ try {
550
+ outcome = JSON.parse(candidate);
551
+ } catch {
552
+ plain += candidate;
553
+ }
554
+ start = -1;
555
+ }
556
+ }
557
+ }
558
+ if (depth > 0 && start >= 0) plain += stdout.slice(start);
559
+ for (const line of plain.split("\n")) {
560
+ const text = line.trim();
561
+ if (text) noise.push(text);
562
+ }
563
+ return { outcome, noise: noise.join("\n") };
564
+ }
565
+ function isRefusal(outcome) {
566
+ return Boolean(outcome?.error);
567
+ }
568
+ function relayLine(outcome) {
569
+ if (!outcome) return null;
570
+ if (outcome.error) {
571
+ const message = outcome.error.message?.trim();
572
+ const next = outcome.error.next_action ?? outcome.next_action;
573
+ return message ? `${message}${next ? ` (next: ${next})` : ""}` : `The connector refused${next ? `: ${next}` : "."}`;
574
+ }
575
+ if (outcome.approval?.required) {
576
+ return outcome.approval.url ? `Approve the budget to finish: ${outcome.approval.url}` : "Approve the budget in your Haven tab to finish.";
577
+ }
578
+ return null;
579
+ }
580
+ async function runConnector(connectorCommand, spawner, onStderr) {
581
+ const argv = splitConnectorCommand(connectorCommand);
582
+ const args = [...argv.slice(1), "--json"];
583
+ const { stdout, stderr, exitCode } = await spawner(argv[0], args, onStderr);
584
+ const { outcome, noise } = parseOutcome(stdout);
585
+ return { outcome, exitCode, stderr, stdoutNoise: noise };
586
+ }
587
+
243
588
  // src/commands.ts
244
589
  var DEFAULT_API = "https://havenbackend-production-8a00.up.railway.app";
245
- var CLI_VERSION = "0.1.33-alpha.0";
590
+ var CLI_VERSION = "0.1.35-alpha.0";
246
591
  async function run(argv, deps = {}) {
592
+ const out = deps.out ?? ((l) => process.stdout.write(`${l}
593
+ `));
594
+ const err = deps.err ?? ((l) => process.stderr.write(`${l}
595
+ `));
596
+ const json = argv.includes("--json");
597
+ const o = createOutput(json, out, err);
247
598
  const d = {
248
599
  sessionStore: deps.sessionStore ?? createSessionStore(),
249
600
  makeApi: deps.makeApi ?? ((baseUrl, token) => createCliApi({ baseUrl, token })),
250
601
  promptPassword: deps.promptPassword ?? (() => Promise.reject(new Error("No password input available"))),
251
- out: deps.out ?? ((l) => process.stdout.write(`${l}
252
- `)),
253
- err: deps.err ?? ((l) => process.stderr.write(`${l}
254
- `)),
255
- env: deps.env ?? process.env
602
+ sleep: deps.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms))),
603
+ spawner: deps.spawner ?? nodeSpawner,
604
+ out,
605
+ err,
606
+ env: deps.env ?? process.env,
607
+ o
256
608
  };
257
609
  let args;
258
610
  try {
259
611
  args = parseArgs(argv);
260
612
  } catch (e) {
261
- d.err(e instanceof Error ? e.message : String(e));
262
- return 1;
613
+ return fail(d, new UsageError(e instanceof Error ? e.message : String(e), "Run `haven --help`."));
263
614
  }
264
615
  if (args.flags.version) {
265
- d.out(CLI_VERSION);
266
- return 0;
616
+ o.data({ version: CLI_VERSION }, () => CLI_VERSION);
617
+ return EXIT.ok;
267
618
  }
268
619
  if (args.flags.help || !args.command) {
269
- d.out(helpText());
270
- return 0;
620
+ o.data({ help: helpText() }, () => helpText());
621
+ return EXIT.ok;
271
622
  }
272
623
  try {
273
624
  return await dispatch(args, d);
274
625
  } catch (e) {
275
- if (e instanceof CliApiError) {
276
- d.err(e.message);
277
- return e.status === 401 ? 2 : 1;
278
- }
279
- d.err(e instanceof Error ? e.message : String(e));
280
- return 1;
626
+ return fail(d, e);
281
627
  }
282
628
  }
629
+ function fail(d, err) {
630
+ const failure = toFailure(err);
631
+ d.o.failure(failure);
632
+ return failure.exit;
633
+ }
283
634
  async function dispatch(args, d) {
284
635
  const key = args.sub ? `${args.command} ${args.sub}` : args.command;
285
636
  switch (key) {
637
+ case "guide":
638
+ return cmdGuide(args, d);
286
639
  case "login":
287
640
  return cmdLogin(args, d);
288
641
  case "logout":
289
- return cmdLogout(d);
642
+ return cmdLogout(args, d);
290
643
  case "whoami":
291
644
  return cmdWhoami(args, d);
292
645
  case "wallets list":
293
646
  return cmdWalletsList(args, d);
294
647
  case "wallets balances":
295
648
  return cmdWalletsBalances(args, d);
649
+ case "wallets funding":
650
+ return cmdWalletsFunding(args, d);
296
651
  case "agents list":
297
652
  return cmdAgentsList(args, d);
298
653
  case "agents show":
299
654
  return cmdAgentsShow(args, d);
655
+ case "agents connect":
656
+ return cmdAgentsConnect(args, d);
300
657
  case "agents pause":
301
658
  return cmdAgentLifecycle(args, d, "pause");
302
659
  case "agents resume":
@@ -309,6 +666,10 @@ async function dispatch(args, d) {
309
666
  return cmdAgentRename(args, d);
310
667
  case "budget show":
311
668
  return cmdBudgetShow(args, d);
669
+ case "budget grant":
670
+ return cmdBudgetGrant(args, d);
671
+ case "budget revoke":
672
+ return cmdBudgetRevoke(args, d);
312
673
  case "wallets rename":
313
674
  return cmdWalletRename(args, d);
314
675
  case "activity list":
@@ -324,8 +685,7 @@ async function dispatch(args, d) {
324
685
  case "contacts remove":
325
686
  return cmdContactsRemove(args, d);
326
687
  default:
327
- d.err(`Unknown command: ${key}. Run \`haven --help\`.`);
328
- return 1;
688
+ throw new UsageError(`Unknown command: ${key}.`, "Run `haven --help` for the command list.");
329
689
  }
330
690
  }
331
691
  function baseUrlFor(args, d, session) {
@@ -333,40 +693,109 @@ function baseUrlFor(args, d, session) {
333
693
  }
334
694
  async function authed(args, d) {
335
695
  const session = await d.sessionStore.load();
336
- if (!session) throw new CliApiError("Not authenticated. Run `haven login` first.", 401);
696
+ if (!session) throw new CliApiError("Not authenticated.", 401);
337
697
  return { session, api: d.makeApi(baseUrlFor(args, d, session), session.token) };
338
698
  }
339
- function emit(d, json, data, human) {
340
- d.out(json ? JSON.stringify(data, null, 2) : human());
699
+ function emit(d, _json, data, human) {
700
+ d.o.data(data, human);
701
+ }
702
+ async function cmdGuide(_args, d) {
703
+ d.o.data({ ok: true, format: "markdown", content: HAVEN_AGENT_RUNBOOK_MD }, () => HAVEN_AGENT_RUNBOOK_MD);
704
+ return EXIT.ok;
705
+ }
706
+ async function deviceLogin(args, d, baseUrl) {
707
+ const api = d.makeApi(baseUrl);
708
+ const label = d.env.HAVEN_CLIENT_LABEL ?? `Haven CLI on ${d.env.HOSTNAME ?? "this machine"}`;
709
+ const start = await api.post("/auth/device/start", { client_label: label });
710
+ const deadline = Date.now() + start.expires_in * 1e3;
711
+ d.o.data(
712
+ {
713
+ ok: true,
714
+ verification_url: start.verification_url,
715
+ user_code: start.user_code,
716
+ expires_at: new Date(deadline).toISOString()
717
+ },
718
+ () => `Open ${start.verification_url}
719
+ and approve the code ${start.user_code}.
720
+ It expires in ${Math.round(start.expires_in / 60)} minutes.`
721
+ );
722
+ if (args.flags.noWait) return EXIT.ok;
723
+ let interval = start.interval * 1e3;
724
+ for (; ; ) {
725
+ if (Date.now() >= deadline) {
726
+ throw new HavenCliError("The code expired before it was approved.", EXIT.notAuthenticated);
727
+ }
728
+ await d.sleep(interval);
729
+ let res = null;
730
+ try {
731
+ res = await api.post("/auth/device/token", {
732
+ device_code: start.device_code
733
+ });
734
+ } catch (err) {
735
+ const code = deviceErrorCode(err);
736
+ if (code === "authorization_pending") continue;
737
+ if (code === "slow_down") {
738
+ interval += 5e3;
739
+ continue;
740
+ }
741
+ if (code === "access_denied") {
742
+ throw new HavenCliError("The request was denied.", EXIT.refused);
743
+ }
744
+ if (code === "expired_token") {
745
+ throw new HavenCliError("The code expired before it was approved.", EXIT.notAuthenticated);
746
+ }
747
+ throw err;
748
+ }
749
+ await d.sessionStore.save({ token: res.token, apiBaseUrl: baseUrl, user: res.user });
750
+ emit(
751
+ d,
752
+ args.flags.json,
753
+ { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },
754
+ () => `Signed in as ${res.user.email}.`
755
+ );
756
+ return EXIT.ok;
757
+ }
758
+ }
759
+ function deviceErrorCode(err) {
760
+ const body = err?.body;
761
+ return typeof body?.error === "string" ? body.error : null;
341
762
  }
342
763
  async function cmdLogin(args, d) {
343
764
  const email = args.flags.email ?? d.env.HAVEN_EMAIL;
344
765
  if (!email) {
345
- d.err("Provide an email with --email (or HAVEN_EMAIL).");
346
- return 1;
766
+ return deviceLogin(args, d, baseUrlFor(args, d, null));
347
767
  }
348
768
  const password = d.env.HAVEN_PASSWORD ?? await d.promptPassword();
349
769
  if (!password) {
350
- d.err("A password is required.");
351
- return 1;
770
+ throw new UsageError("A password is required.", "Set HAVEN_PASSWORD for a non-interactive run.");
352
771
  }
353
772
  const baseUrl = baseUrlFor(args, d, null);
354
773
  const api = d.makeApi(baseUrl);
355
774
  const res = await api.post("/auth/login", { email, password });
356
775
  await d.sessionStore.save({ token: res.token, apiBaseUrl: baseUrl, user: res.user });
357
- emit(d, args.flags.json, { user: res.user, apiBaseUrl: baseUrl }, () => `Signed in as ${res.user.email}.`);
358
- return 0;
776
+ emit(
777
+ d,
778
+ args.flags.json,
779
+ { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },
780
+ () => `Signed in as ${res.user.email}.`
781
+ );
782
+ return EXIT.ok;
359
783
  }
360
- async function cmdLogout(d) {
784
+ async function cmdLogout(args, d) {
361
785
  await d.sessionStore.clear();
362
- d.out("Signed out.");
363
- return 0;
786
+ emit(d, args.flags.json, { ok: true, signed_out: true }, () => "Signed out.");
787
+ return EXIT.ok;
364
788
  }
365
789
  async function cmdWhoami(args, d) {
366
- const { api } = await authed(args, d);
790
+ const { session, api } = await authed(args, d);
367
791
  const user = await api.get("/auth/me");
368
- emit(d, args.flags.json, user, () => `${user.email}${user.name ? ` (${user.name})` : ""}`);
369
- return 0;
792
+ emit(
793
+ d,
794
+ args.flags.json,
795
+ { ...user, id: user.id, email: user.email, expires_at: sessionExpiry(session.token), api_url: session.apiBaseUrl },
796
+ () => `${user.email}${user.name ? ` (${user.name})` : ""}`
797
+ );
798
+ return EXIT.ok;
370
799
  }
371
800
  async function cmdWalletsList(args, d) {
372
801
  const { api } = await authed(args, d);
@@ -380,15 +809,15 @@ async function cmdWalletsList(args, d) {
380
809
  safes.map((s) => [s.name, chainName(s.chain_id), truncateAddress(s.safe_address), s.is_default ? "\u2713" : ""])
381
810
  )
382
811
  );
383
- return 0;
812
+ return EXIT.ok;
384
813
  }
385
814
  async function cmdWalletsBalances(args, d) {
386
815
  const { api } = await authed(args, d);
387
816
  const { safes } = await api.get("/user/safes");
388
817
  const safe = pickSafe(safes, args.flags.safe);
389
818
  if (!safe) {
390
- d.err(args.flags.safe ? `No wallet matches "${args.flags.safe}".` : "No Haven wallet found.");
391
- return 1;
819
+ if (args.flags.safe) throw new UsageError(`No wallet matches "${args.flags.safe}".`);
820
+ throw new CliApiError("No Haven wallet found.", 404);
392
821
  }
393
822
  const { balances } = await api.get(
394
823
  `/balances/${safe.safe_address}?chain_id=${safe.chain_id}`
@@ -402,13 +831,72 @@ async function cmdWalletsBalances(args, d) {
402
831
  balances.length === 0 ? " (no balances)" : table(["TOKEN", "BALANCE"], balances.map((b) => [b.symbol, b.formatted]))
403
832
  ].join("\n")
404
833
  );
405
- return 0;
834
+ return EXIT.ok;
406
835
  }
407
836
  function pickSafe(safes, ref) {
408
837
  if (!ref) return safes.find((s) => s.is_default) ?? safes[0];
409
838
  const lower = ref.toLowerCase();
410
839
  return safes.find((s) => s.id === ref || s.safe_address.toLowerCase() === lower);
411
840
  }
841
+ async function cmdWalletsFunding(args, d) {
842
+ const { api } = await authed(args, d);
843
+ const { safes } = await api.get("/user/safes");
844
+ const safe = pickSafe(safes, args.flags.safe);
845
+ if (!safe) {
846
+ if (args.flags.safe) throw new UsageError(`No wallet matches "${args.flags.safe}".`);
847
+ throw new CliApiError("No Haven wallet found.", 404);
848
+ }
849
+ const funding = await api.get(`/user/safes/${safe.id}/funding`);
850
+ if (!args.flags.wait) {
851
+ emitFunding(d, funding);
852
+ return EXIT.ok;
853
+ }
854
+ const started = Date.now();
855
+ const pollMs = Number(d.env.HAVEN_FUNDING_POLL_MS ?? "5000");
856
+ const waitMs = Number(d.env.HAVEN_FUNDING_WAIT_MS ?? String(2 * 60 * 60 * 1e3));
857
+ if (!Number.isFinite(pollMs) || pollMs <= 0 || !Number.isFinite(waitMs) || waitMs <= 0) {
858
+ throw new UsageError("HAVEN_FUNDING_POLL_MS / HAVEN_FUNDING_WAIT_MS must be positive numbers of milliseconds");
859
+ }
860
+ let current = funding;
861
+ for (; ; ) {
862
+ const spent = Date.now() - started;
863
+ if (spent >= waitMs) {
864
+ throw new HavenCliError(
865
+ `Still not funded after ${elapsedLabel(spent)} \u2014 the transfer may not have landed yet. Check the explorer link, then re-run.`,
866
+ EXIT.failed
867
+ );
868
+ }
869
+ await d.sleep(pollMs);
870
+ current = await api.get(`/user/safes/${safe.id}/funding`);
871
+ if (current.funded) break;
872
+ d.o.note(`Still waiting after ${elapsedLabel(Date.now() - started)} \u2014 funded: no.`);
873
+ }
874
+ d.o.note(`Account shows funded after ${elapsedLabel(Date.now() - started)}.`);
875
+ emitFunding(d, current);
876
+ return EXIT.ok;
877
+ }
878
+ function emitFunding(d, funding) {
879
+ emit(d, d.o.json, funding, () => {
880
+ const token = funding.tokens.find((t) => t.minimum_useful_human !== null);
881
+ const asset = token ? `at least ${token.minimum_useful_human} ${token.symbol}` : funding.native.needed ? funding.native.symbol : "USDC";
882
+ const gas = funding.native.needed ? ` plus ${funding.native.symbol} for gas` : " \u2014 no gas token needed; Haven sponsors it";
883
+ const faucet = funding.faucet_url !== void 0 ? ` faucet: ${funding.faucet_url},` : "";
884
+ return [
885
+ `Send ${asset} on ${funding.chain.name} to ${funding.account_address}${gas}.`,
886
+ `Explorer: ${funding.chain.explorer_url}.${faucet ? faucet.slice(0, -1) : ""}`,
887
+ funding.funded ? "The account already counts as funded." : "Nothing has arrived yet."
888
+ ].join("\n");
889
+ });
890
+ }
891
+ function elapsedLabel(ms) {
892
+ const total = Math.floor(ms / 1e3);
893
+ const h = Math.floor(total / 3600);
894
+ const m = Math.floor(total % 3600 / 60);
895
+ const s = total % 60;
896
+ if (h > 0) return `${h}h${String(m).padStart(2, "0")}m`;
897
+ if (m > 0) return `${m}m${String(s).padStart(2, "0")}s`;
898
+ return `${s}s`;
899
+ }
412
900
  async function cmdAgentsList(args, d) {
413
901
  const { api } = await authed(args, d);
414
902
  const { agents } = await api.get("/agents");
@@ -421,14 +909,11 @@ async function cmdAgentsList(args, d) {
421
909
  agents.map((a) => [a.id, a.name, a.status, budgetSummary(a.allowances)])
422
910
  )
423
911
  );
424
- return 0;
912
+ return EXIT.ok;
425
913
  }
426
914
  async function cmdAgentsShow(args, d) {
427
915
  const id = args.positionals[0];
428
- if (!id) {
429
- d.err("Usage: haven agents show <id>");
430
- return 1;
431
- }
916
+ if (!id) throw new UsageError("Usage: haven agents show <id>");
432
917
  const { api } = await authed(args, d);
433
918
  const agent = await api.get(`/agents/${id}`);
434
919
  emit(
@@ -441,15 +926,26 @@ async function cmdAgentsShow(args, d) {
441
926
  `budget: ${budgetSummary(agent.allowances)}`
442
927
  ].join("\n")
443
928
  );
444
- return 0;
929
+ return EXIT.ok;
445
930
  }
931
+ var HASH_DISCOVERY_HINT = "haven budget show <agentId> --hashes";
446
932
  async function cmdBudgetShow(args, d) {
447
933
  const id = args.positionals[0];
448
- if (!id) {
449
- d.err("Usage: haven budget show <agentId>");
450
- return 1;
451
- }
934
+ if (!id) throw new UsageError("Usage: haven budget show <agentId> [--hashes]");
452
935
  const { api } = await authed(args, d);
936
+ if (args.flags.hashes) {
937
+ const { delegations } = await api.get(`/agents/${id}/delegations`);
938
+ emit(
939
+ d,
940
+ args.flags.json,
941
+ delegations,
942
+ () => delegations.length === 0 ? `No delegations on agent ${id}.` : table(
943
+ ["DELEGATION HASH", "STATUS", "VERSION"],
944
+ delegations.map((r) => [r.delegation_hash, r.status, String(r.version)])
945
+ )
946
+ );
947
+ return EXIT.ok;
948
+ }
453
949
  const agent = await api.get(`/agents/${id}`);
454
950
  const allowances = agent.allowances ?? [];
455
951
  emit(
@@ -461,12 +957,148 @@ async function cmdBudgetShow(args, d) {
461
957
  allowances.map((a) => [a.token_symbol, a.allowance_amount, resetLabel(a.reset_period_min)])
462
958
  )
463
959
  );
464
- return 0;
960
+ return EXIT.ok;
465
961
  }
466
962
  function budgetSummary(allowances) {
467
963
  if (!allowances || allowances.length === 0) return "\u2014";
468
964
  return allowances.map((a) => `${a.allowance_amount} ${a.token_symbol}`).join(", ");
469
965
  }
966
+ var BUDGET_WAIT_TIMEOUT_S = 15 * 60;
967
+ var BUDGET_WAIT_INTERVAL_MS = 5e3;
968
+ async function cmdBudgetGrant(args, d) {
969
+ const id = args.positionals[0];
970
+ if (!id) {
971
+ throw new UsageError("Usage: haven budget grant <agentId> --amount 25 --token USDC --period <minutes> [--recipient <address>] [--expires <unix-seconds>] [--wait]");
972
+ }
973
+ if (!args.flags.amount || !args.flags.token || args.flags.period === void 0) {
974
+ throw new UsageError("--amount, --token and --period are required (period is whole minutes, at least 1)");
975
+ }
976
+ if (args.flags.period < 1) {
977
+ throw new UsageError("--period must be at least 1 minute for a budget grant. A recurring budget is the only shape this rail has; `haven agents connect --period 0` is a different field on a different route.");
978
+ }
979
+ const { api } = await authed(args, d);
980
+ const agent = await api.get(`/agents/${id}`);
981
+ if (agent.account_type !== "delegator_hybrid") {
982
+ throw new HavenCliError(
983
+ `Agent ${id} is not on the delegation rail \u2014 budgets are managed from the dashboard for this account.`,
984
+ EXIT.refused
985
+ );
986
+ }
987
+ if (!agent.safe_address || !agent.safe_chain_id) {
988
+ throw new HavenCliError(`Agent ${id} has no wallet assigned yet \u2014 connect it first.`, EXIT.refused);
989
+ }
990
+ const { balances } = await api.get(
991
+ `/balances/${agent.safe_address}?chain_id=${agent.safe_chain_id}`
992
+ );
993
+ const wanted = args.flags.token.trim().toUpperCase();
994
+ const token = balances.find((b) => b.symbol.toUpperCase() === wanted);
995
+ if (!token || !token.address) {
996
+ const known = balances.map((b) => b.symbol).join(", ");
997
+ throw new UsageError(`Unknown token ${args.flags.token} on this wallet's chain. Available: ${known || "none"}`);
998
+ }
999
+ const amount = parseTokenAmount(args.flags.amount, token.decimals, token.symbol);
1000
+ if (!amount.ok) throw new UsageError(amount.message);
1001
+ const built = await api.post(`/agents/${id}/delegations/build`, {
1002
+ token_address: token.address,
1003
+ recipient_address: args.flags.recipient ?? null,
1004
+ budget_atomic: amount.atomic,
1005
+ period_seconds: args.flags.period * 60,
1006
+ ...args.flags.expires !== void 0 ? { expires_at: args.flags.expires } : {}
1007
+ });
1008
+ const emitGrant = (status) => emit(
1009
+ d,
1010
+ args.flags.json,
1011
+ { ...built, agent_id: id, status: status ?? "pending" },
1012
+ () => [
1013
+ `Budget of ${args.flags.amount} ${token.symbol} per ${args.flags.period} minutes built for agent ${id}.`,
1014
+ args.flags.recipient ? `Recipient pin: ${args.flags.recipient}` : null,
1015
+ "Open this link and sign \u2014 the budget goes live the moment you do:",
1016
+ built.signing_url,
1017
+ `Delegation: ${built.delegation_hash} (version ${built.version})`,
1018
+ status === "active" ? "Signed and active." : "Waiting for your signature. Run the same command with --wait to poll until it is active."
1019
+ ].filter((line) => line !== null).join("\n")
1020
+ );
1021
+ emitGrant();
1022
+ if (!args.flags.wait) return EXIT.ok;
1023
+ const deadline = Date.now() + BUDGET_WAIT_TIMEOUT_S * 1e3;
1024
+ while (Date.now() < deadline) {
1025
+ await d.sleep(BUDGET_WAIT_INTERVAL_MS);
1026
+ const { delegations } = await api.get(`/agents/${id}/delegations`);
1027
+ const mine = delegations.find((row) => row.delegation_hash === built.delegation_hash);
1028
+ if (mine?.status === "active") {
1029
+ emitGrant("active");
1030
+ return EXIT.ok;
1031
+ }
1032
+ if (mine?.status === "revoked" || mine?.status === "replaced") {
1033
+ throw new HavenCliError(
1034
+ `Delegation ${built.delegation_hash} is now ${mine.status} without being signed.`,
1035
+ EXIT.refused
1036
+ );
1037
+ }
1038
+ }
1039
+ throw new HavenCliError(
1040
+ `Timed out waiting for delegation ${built.delegation_hash} to go active (${BUDGET_WAIT_TIMEOUT_S / 60} minutes). The signing link stays valid until it expires \u2014 sign it, or rerun with --wait.`,
1041
+ EXIT.failed
1042
+ );
1043
+ }
1044
+ async function cmdBudgetRevoke(args, d) {
1045
+ const [id, hash] = args.positionals;
1046
+ if (!id || !hash) throw new UsageError("Usage: haven budget revoke <agentId> <delegationHash> [--wait]");
1047
+ if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {
1048
+ throw new UsageError(`The delegation hash must be 0x followed by 64 hex characters \u2014 \`${HASH_DISCOVERY_HINT}\` lists them, or the dashboard.`);
1049
+ }
1050
+ const { api } = await authed(args, d);
1051
+ const { delegations } = await api.get(`/agents/${id}/delegations`);
1052
+ const row = delegations.find((r) => r.delegation_hash.toLowerCase() === hash.toLowerCase());
1053
+ if (!row) {
1054
+ throw new HavenCliError(`No delegation ${hash} on agent ${id}.`, EXIT.refused);
1055
+ }
1056
+ if (row.status === "revoked") {
1057
+ throw new HavenCliError(`Delegation ${hash} is already revoked.`, EXIT.refused);
1058
+ }
1059
+ if (row.status === "replaced") {
1060
+ throw new HavenCliError(
1061
+ `Delegation ${hash} was already replaced by a newer grant \u2014 nothing to revoke.`,
1062
+ EXIT.refused
1063
+ );
1064
+ }
1065
+ const prepared = await api.post(`/agents/${id}/delegations/${hash}/revoke`, {});
1066
+ const revokeUrl = prepared.revocation_url;
1067
+ if (!revokeUrl) {
1068
+ throw new HavenCliError(
1069
+ "The backend did not return a revocation link \u2014 it may be older than #2539. Finish the revocation in the dashboard.",
1070
+ EXIT.failed
1071
+ );
1072
+ }
1073
+ const emitRevoke = (status) => emit(
1074
+ d,
1075
+ args.flags.json,
1076
+ { agent_id: id, delegation_hash: hash, status, ...prepared },
1077
+ () => [
1078
+ "Revocation prepared \u2014 one signature, sponsored (no gas).",
1079
+ "Open this link and sign to stop this budget:",
1080
+ revokeUrl,
1081
+ `Delegation: ${hash}`,
1082
+ status === "revoked" ? "Revoked." : "The budget keeps working until you sign. Run the same command with --wait to poll until it is revoked."
1083
+ ].filter((line) => line !== null).join("\n")
1084
+ );
1085
+ emitRevoke("pending_revoke");
1086
+ if (!args.flags.wait) return EXIT.ok;
1087
+ const deadline = Date.now() + BUDGET_WAIT_TIMEOUT_S * 1e3;
1088
+ while (Date.now() < deadline) {
1089
+ await d.sleep(BUDGET_WAIT_INTERVAL_MS);
1090
+ const { delegations: after } = await api.get(`/agents/${id}/delegations`);
1091
+ const mine = after.find((r) => r.delegation_hash.toLowerCase() === hash.toLowerCase());
1092
+ if (mine?.status === "revoked") {
1093
+ emitRevoke("revoked");
1094
+ return EXIT.ok;
1095
+ }
1096
+ }
1097
+ throw new HavenCliError(
1098
+ `Timed out waiting for delegation ${hash} to be revoked (${BUDGET_WAIT_TIMEOUT_S / 60} minutes). The link stays valid \u2014 sign it, or rerun with --wait.`,
1099
+ EXIT.failed
1100
+ );
1101
+ }
470
1102
  function resetLabel(mins) {
471
1103
  if (mins === 0) return "one-time";
472
1104
  if (mins === 1440) return "daily";
@@ -476,75 +1108,64 @@ function resetLabel(mins) {
476
1108
  }
477
1109
  async function cmdAgentLifecycle(args, d, action) {
478
1110
  const id = args.positionals[0];
479
- if (!id) {
480
- d.err(`Usage: haven agents ${action} <id>`);
481
- return 1;
482
- }
1111
+ if (!id) throw new UsageError(`Usage: haven agents ${action} <id>`);
483
1112
  const { api } = await authed(args, d);
484
1113
  await api.post(`/agents/${id}/${action}`);
485
- d.out(`Agent ${id} ${action === "pause" ? "paused" : "resumed"}.`);
486
- return 0;
1114
+ const status = action === "pause" ? "paused" : "resumed";
1115
+ emit(d, args.flags.json, { ok: true, agent_id: id, status }, () => `Agent ${id} ${status}.`);
1116
+ return EXIT.ok;
487
1117
  }
488
1118
  async function cmdAgentRevoke(args, d) {
489
1119
  const id = args.positionals[0];
490
- if (!id) {
491
- d.err("Usage: haven agents revoke <id> --yes");
492
- return 1;
493
- }
1120
+ if (!id) throw new UsageError("Usage: haven agents revoke <id> --yes");
494
1121
  if (!args.flags.yes) {
495
- d.err(`This permanently revokes agent ${id}. Re-run with --yes to confirm.`);
496
- return 1;
1122
+ throw new UsageError(
1123
+ `This permanently revokes agent ${id}.`,
1124
+ "Re-run with --yes to confirm. Revoke is terminal \u2014 the agent cannot go back to active."
1125
+ );
497
1126
  }
498
1127
  const { api } = await authed(args, d);
499
1128
  await api.post(`/agents/${id}/revoke`);
500
- d.out(`Agent ${id} revoked. To also remove its on-chain allowance, use the dashboard.`);
501
- return 0;
1129
+ emit(
1130
+ d,
1131
+ args.flags.json,
1132
+ { ok: true, agent_id: id, status: "revoked" },
1133
+ () => `Agent ${id} revoked. To also remove its on-chain allowance, use the dashboard.`
1134
+ );
1135
+ return EXIT.ok;
502
1136
  }
503
1137
  async function cmdAgentRotateKey(args, d) {
504
1138
  const id = args.positionals[0];
505
- if (!id) {
506
- d.err("Usage: haven agents rotate-key <id>");
507
- return 1;
508
- }
1139
+ if (!id) throw new UsageError("Usage: haven agents rotate-key <id>");
509
1140
  const { api } = await authed(args, d);
510
1141
  const res = await api.post(`/agents/${id}/rotate-key`);
511
- if (args.flags.json) {
512
- d.out(JSON.stringify(res, null, 2));
513
- } else {
514
- d.out("New API key (shown once \u2014 store it now; the old key stops working):");
515
- d.out(res.api_key);
516
- }
517
- return 0;
1142
+ d.o.note("New API key (shown once \u2014 store it now; the old key stops working):");
1143
+ emit(d, args.flags.json, res, () => res.api_key);
1144
+ return EXIT.ok;
518
1145
  }
519
1146
  async function cmdAgentRename(args, d) {
520
1147
  const [id, ...nameParts] = args.positionals;
521
1148
  const name = nameParts.join(" ").trim();
522
- if (!id || !name) {
523
- d.err("Usage: haven agents rename <id> <name>");
524
- return 1;
525
- }
1149
+ if (!id || !name) throw new UsageError("Usage: haven agents rename <id> <name>");
526
1150
  const { api } = await authed(args, d);
527
1151
  await api.put(`/agents/${id}`, { name });
528
- d.out(`Agent ${id} renamed to "${name}".`);
529
- return 0;
1152
+ emit(d, args.flags.json, { ok: true, agent_id: id, name }, () => `Agent ${id} renamed to "${name}".`);
1153
+ return EXIT.ok;
530
1154
  }
531
1155
  async function cmdWalletRename(args, d) {
532
1156
  const [id, ...nameParts] = args.positionals;
533
1157
  const name = nameParts.join(" ").trim();
534
- if (!id || !name) {
535
- d.err("Usage: haven wallets rename <id> <name>");
536
- return 1;
537
- }
1158
+ if (!id || !name) throw new UsageError("Usage: haven wallets rename <id> <name>");
538
1159
  const { api } = await authed(args, d);
539
1160
  await api.put(`/user/safes/${id}`, { name });
540
- d.out(`Wallet ${id} renamed to "${name}".`);
541
- return 0;
1161
+ emit(d, args.flags.json, { ok: true, safe_id: id, name }, () => `Wallet ${id} renamed to "${name}".`);
1162
+ return EXIT.ok;
542
1163
  }
543
1164
  async function resolveSafeId(args, api) {
544
1165
  if (!args.flags.safe) return void 0;
545
1166
  const { safes } = await api.get("/user/safes");
546
1167
  const safe = pickSafe(safes, args.flags.safe);
547
- if (!safe) throw new CliApiError(`No wallet matches "${args.flags.safe}".`, 1);
1168
+ if (!safe) throw new UsageError(`No wallet matches "${args.flags.safe}".`);
548
1169
  return safe.id;
549
1170
  }
550
1171
  async function cmdActivityList(args, d) {
@@ -573,7 +1194,7 @@ async function cmdActivityList(args, d) {
573
1194
  ])
574
1195
  )
575
1196
  );
576
- return 0;
1197
+ return EXIT.ok;
577
1198
  }
578
1199
  async function cmdActivityExport(args, d) {
579
1200
  if (args.flags.format === "sie") return exportSie(args, d);
@@ -615,8 +1236,8 @@ async function cmdActivityExport(args, d) {
615
1236
  t.hash,
616
1237
  t.chainId != null ? String(t.chainId) : ""
617
1238
  ]);
618
- d.out(toCsv(headers, rows));
619
- return 0;
1239
+ d.o.text(toCsv(headers, rows), { format: "csv", rows: rows.length });
1240
+ return EXIT.ok;
620
1241
  }
621
1242
  function exportType(t) {
622
1243
  if (t.activityType === "delegate_sweep") return "allowance funding";
@@ -636,8 +1257,8 @@ async function exportSie(args, d) {
636
1257
  if (args.flags.to) params.set("to", args.flags.to);
637
1258
  if (args.flags.company) params.set("company", args.flags.company);
638
1259
  const content = await api.getText(`/accounting/export?${params.toString()}`);
639
- d.out(content);
640
- return 0;
1260
+ d.o.text(content, { format: "sie" });
1261
+ return EXIT.ok;
641
1262
  }
642
1263
  async function cmdCatalogList(args, d) {
643
1264
  const { api } = await authed(args, d);
@@ -651,7 +1272,127 @@ async function cmdCatalogList(args, d) {
651
1272
  entries.map((e) => [e.name, e.category, e.rail, e.price_display ?? "\u2014", e.status])
652
1273
  )
653
1274
  );
654
- return 0;
1275
+ return EXIT.ok;
1276
+ }
1277
+ async function resolveWalletAndToken(args, api, symbol) {
1278
+ const { safes } = await api.get("/user/safes");
1279
+ if (safes.length === 0) {
1280
+ throw new HavenCliError("No wallet on this account yet \u2014 finish onboarding first.", EXIT.refused);
1281
+ }
1282
+ const safe = args.flags.safe ? safes.find((s) => s.id === args.flags.safe || s.safe_address === args.flags.safe) : safes.find((s) => s.is_default) ?? safes[0];
1283
+ if (!safe) throw new UsageError(`No wallet matches --safe ${args.flags.safe}`);
1284
+ const { balances } = await api.get(
1285
+ `/balances/${safe.safe_address}?chain_id=${safe.chain_id}`
1286
+ );
1287
+ const wanted = symbol.trim().toUpperCase();
1288
+ const token = balances.find((b) => b.symbol.toUpperCase() === wanted);
1289
+ if (!token) {
1290
+ const known = balances.map((b) => b.symbol).join(", ");
1291
+ throw new UsageError(`Unknown token ${symbol} on this wallet's chain. Available: ${known || "none"}`);
1292
+ }
1293
+ return { safeId: safe.id, token };
1294
+ }
1295
+ var SETTLED = /* @__PURE__ */ new Set(["active", "expired", "cancelled", "failed"]);
1296
+ async function pollSetup(api, setupId, d, wait) {
1297
+ let status = await api.get(`/agent-connection-setups/${setupId}`);
1298
+ if (!wait) return status;
1299
+ const deadline = new Date(status.expires_at).getTime();
1300
+ while (!SETTLED.has(status.status) && Date.now() < deadline) {
1301
+ await d.sleep(5e3);
1302
+ status = await api.get(`/agent-connection-setups/${setupId}`);
1303
+ }
1304
+ return status;
1305
+ }
1306
+ async function cmdAgentsConnect(args, d) {
1307
+ const { api } = await authed(args, d);
1308
+ if (args.flags.status) {
1309
+ const status = await pollSetup(api, args.flags.status, d, args.flags.wait);
1310
+ emit(
1311
+ d,
1312
+ args.flags.json,
1313
+ status,
1314
+ () => [
1315
+ `setup ${status.setup_id}: ${status.status}`,
1316
+ status.agent_id ? `agent: ${status.agent_id}` : null,
1317
+ SETTLED.has(status.status) ? null : `approve: ${status.approval_url}`
1318
+ ].filter(Boolean).join("\n")
1319
+ );
1320
+ return EXIT.ok;
1321
+ }
1322
+ const name = args.flags.name?.trim();
1323
+ if (!name) throw new UsageError("Usage: haven agents connect --name <name> --budget <amount> --token USDC --period <minutes>");
1324
+ if (!args.flags.budget || !args.flags.token || args.flags.period === void 0) {
1325
+ throw new UsageError("--budget, --token and --period are required (period is whole minutes; 0 means one-time)");
1326
+ }
1327
+ const { safeId, token } = await resolveWalletAndToken(args, api, args.flags.token);
1328
+ const amount = parseTokenAmount(args.flags.budget, token.decimals, token.symbol);
1329
+ if (!amount.ok) throw new UsageError(amount.message);
1330
+ const setup = await api.post("/agent-connection-setups", {
1331
+ name,
1332
+ safe_id: safeId,
1333
+ allowances: [
1334
+ {
1335
+ token_address: token.address ?? "0x0000000000000000000000000000000000000000",
1336
+ token_symbol: token.symbol,
1337
+ // ATOMIC on the way in, human on the way back (#2295). Converted here
1338
+ // exactly once, from the decimals the backend just told us.
1339
+ allowance_amount: amount.atomic,
1340
+ reset_period_min: args.flags.period
1341
+ }
1342
+ ],
1343
+ // How this setup was made, for connect attribution (#2302). The route
1344
+ // already accepts any slug, so nothing backend-side had to change.
1345
+ source: "cli",
1346
+ // #2522: the hand-off marker, set only when an agent is driving this CLI
1347
+ // and says so. Never inferred — a guess here mislabels a human's own run.
1348
+ ...d.env.HAVEN_AGENT_DRIVEN === "1" ? { via: "agent" } : {}
1349
+ });
1350
+ if (!args.flags.run) {
1351
+ emit(
1352
+ d,
1353
+ args.flags.json,
1354
+ setup,
1355
+ () => [
1356
+ "Run this where the agent runs:",
1357
+ "",
1358
+ setup.connector_command,
1359
+ "",
1360
+ `Then approve the budget: ${setup.approval_url}`,
1361
+ `Setup ${setup.setup_id} expires ${setup.expires_at}.`
1362
+ ].join("\n")
1363
+ );
1364
+ return EXIT.ok;
1365
+ }
1366
+ const run2 = await runConnector(setup.connector_command, d.spawner, (chunk) => d.err(chunk.trimEnd()));
1367
+ const relay = relayLine(run2.outcome);
1368
+ const merged = {
1369
+ setup_id: setup.setup_id,
1370
+ approval_url: setup.approval_url,
1371
+ connector_command: setup.connector_command,
1372
+ connector_exit_code: run2.exitCode,
1373
+ outcome: run2.outcome,
1374
+ relay
1375
+ };
1376
+ if (isRefusal(run2.outcome)) {
1377
+ emitConnectResult(d, args.flags.json, merged, relay);
1378
+ return EXIT.refused;
1379
+ }
1380
+ if (!run2.outcome) {
1381
+ throw new HavenCliError(
1382
+ `The connector produced no outcome (exit ${run2.exitCode}).${run2.stdoutNoise ? ` Output: ${run2.stdoutNoise}` : ""}`,
1383
+ run2.exitCode === 0 ? EXIT.failed : EXIT.failed
1384
+ );
1385
+ }
1386
+ emitConnectResult(d, args.flags.json, merged, relay);
1387
+ return EXIT.ok;
1388
+ }
1389
+ function emitConnectResult(d, json, merged, relay) {
1390
+ emit(
1391
+ d,
1392
+ json,
1393
+ merged,
1394
+ () => [relay, relay ? "" : null, `setup ${merged.setup_id}: ${merged.outcome?.outcome ?? "unknown"}`].filter((line) => line !== null).join("\n")
1395
+ );
655
1396
  }
656
1397
  async function cmdContactsList(args, d) {
657
1398
  const { api } = await authed(args, d);
@@ -662,30 +1403,24 @@ async function cmdContactsList(args, d) {
662
1403
  contacts,
663
1404
  () => contacts.length === 0 ? "No contacts yet." : table(["ID", "NAME", "ADDRESS"], contacts.map((c) => [c.id, c.name, truncateAddress(c.address)]))
664
1405
  );
665
- return 0;
1406
+ return EXIT.ok;
666
1407
  }
667
1408
  async function cmdContactsAdd(args, d) {
668
1409
  const [address, ...nameParts] = [...args.positionals].reverse();
669
1410
  const name = nameParts.reverse().join(" ").trim();
670
- if (!name || !address) {
671
- d.err("Usage: haven contacts add <name> <address>");
672
- return 1;
673
- }
1411
+ if (!name || !address) throw new UsageError("Usage: haven contacts add <name> <address>");
674
1412
  const { api } = await authed(args, d);
675
1413
  const contact = await api.post("/contacts", { name, address });
676
1414
  emit(d, args.flags.json, contact, () => `Added contact "${contact.name}" (${truncateAddress(contact.address)}).`);
677
- return 0;
1415
+ return EXIT.ok;
678
1416
  }
679
1417
  async function cmdContactsRemove(args, d) {
680
1418
  const id = args.positionals[0];
681
- if (!id) {
682
- d.err("Usage: haven contacts remove <id>");
683
- return 1;
684
- }
1419
+ if (!id) throw new UsageError("Usage: haven contacts remove <id>");
685
1420
  const { api } = await authed(args, d);
686
1421
  await api.del(`/contacts/${id}`);
687
- d.out(`Contact ${id} removed.`);
688
- return 0;
1422
+ emit(d, args.flags.json, { ok: true, contact_id: id, removed: true }, () => `Contact ${id} removed.`);
1423
+ return EXIT.ok;
689
1424
  }
690
1425
 
691
1426
  export { CliApiError, createCliApi, createSessionStore, helpText, parseArgs, run, sessionPath };