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