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