@haven_ai/cli 0.0.0-dev.202609042048.ad6cc9b → 0.0.0-dev.202609050705.51c3d92

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,8 @@
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 { emitKeypressEvents } from 'readline';
6
6
 
7
7
  // src/args.ts
8
8
  var VALUE_FLAGS = /* @__PURE__ */ new Set([
@@ -71,7 +71,10 @@ function helpText() {
71
71
  "Auth:",
72
72
  " login [--email <e>] Sign in (password via prompt or HAVEN_PASSWORD)",
73
73
  " logout Clear the saved session",
74
- " whoami Show the signed-in user",
74
+ " whoami Show the signed-in user, session expiry and API URL",
75
+ "",
76
+ "For agents:",
77
+ " guide Print the agent onboarding runbook (same text as /for-agents.md)",
75
78
  "",
76
79
  "Read:",
77
80
  " wallets list List your Haven wallets",
@@ -95,11 +98,14 @@ function helpText() {
95
98
  " contacts add <name> <address> | contacts remove <id>",
96
99
  "",
97
100
  "Options:",
98
- " --json Machine-readable output (for scripting)",
101
+ " --json One JSON value on stdout, prose on stderr, on every",
102
+ " command including refusals: { ok: false, error: { code, message, hint? } }",
99
103
  " --yes, -y Skip the confirmation prompt for destructive actions",
100
104
  " --api <url> Backend URL (default: HAVEN_API_URL or http://localhost:3001)",
101
105
  " --help, --version",
102
106
  "",
107
+ "Exit codes: 0 ok \xB7 1 failed \xB7 2 usage \xB7 3 not authenticated \xB7 4 refused \xB7 5 network",
108
+ "",
103
109
  "On-chain actions (deploy, budgets, approvers, send) are signed in the",
104
110
  "dashboard \u2014 this CLI reads and manages; it never holds your keys."
105
111
  ].join("\n");
@@ -242,53 +248,157 @@ function toCsv(headers, rows) {
242
248
  return lines.join("\r\n");
243
249
  }
244
250
 
251
+ // src/errors.ts
252
+ var EXIT = {
253
+ ok: 0,
254
+ /** Something failed and none of the specific codes below describe it. */
255
+ failed: 1,
256
+ /** The command line was wrong: unknown command, missing argument, bad flag. */
257
+ usage: 2,
258
+ /** No stored session, or the backend rejected the one we have. Log in again. */
259
+ notAuthenticated: 3,
260
+ /** Authenticated, and the backend refused anyway (403, 410, other 4xx). */
261
+ refused: 4,
262
+ /** The backend could not be reached at all. */
263
+ network: 5
264
+ };
265
+ var UsageError = class extends Error {
266
+ hint;
267
+ constructor(message, hint) {
268
+ super(message);
269
+ this.name = "UsageError";
270
+ this.hint = hint;
271
+ }
272
+ };
273
+ function toFailure(err) {
274
+ if (err instanceof UsageError) {
275
+ return { code: "usage", exit: EXIT.usage, message: err.message, hint: err.hint };
276
+ }
277
+ if (err instanceof CliApiError) {
278
+ if (err.status === 0) {
279
+ return {
280
+ code: "network",
281
+ exit: EXIT.network,
282
+ message: err.message,
283
+ hint: "Check the network and `--api`, then retry."
284
+ };
285
+ }
286
+ if (err.status === 401) {
287
+ return {
288
+ code: "not_authenticated",
289
+ exit: EXIT.notAuthenticated,
290
+ message: err.message,
291
+ hint: "Run `haven login` (or set HAVEN_EMAIL and HAVEN_PASSWORD)."
292
+ };
293
+ }
294
+ if (err.status >= 400 && err.status < 500) {
295
+ return { code: "refused", exit: EXIT.refused, message: err.message };
296
+ }
297
+ return { code: "failed", exit: EXIT.failed, message: err.message };
298
+ }
299
+ return { code: "failed", exit: EXIT.failed, message: err instanceof Error ? err.message : String(err) };
300
+ }
301
+
302
+ // src/output.ts
303
+ function createOutput(json, out, err) {
304
+ return {
305
+ json,
306
+ data(payload, human) {
307
+ out(json ? JSON.stringify(payload, null, 2) : human());
308
+ },
309
+ text(content, meta) {
310
+ out(json ? JSON.stringify({ ok: true, ...meta, content }, null, 2) : content);
311
+ },
312
+ note(line) {
313
+ if (json) err(line);
314
+ else out(line);
315
+ },
316
+ failure(failure) {
317
+ const body = {
318
+ ok: false,
319
+ error: {
320
+ code: failure.code,
321
+ message: failure.message,
322
+ ...failure.hint ? { hint: failure.hint } : {}
323
+ }
324
+ };
325
+ if (json) out(JSON.stringify(body, null, 2));
326
+ else err(failure.hint ? `${failure.message}
327
+ ${failure.hint}` : failure.message);
328
+ }
329
+ };
330
+ }
331
+
332
+ // src/agent-guidance-text.ts
333
+ 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.\n2. **HUMAN \u2014 fund it.** USDC on Base, to the address the dashboard shows.\n3. **HUMAN \u2014 create the agent, set its budget**, and paste you the **setup prompt** it hands back.\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## 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 on Base before I can pay for anything \u2014 USDC only, no ETH: Haven sponsors the gas. The dashboard shows the address to send it to; 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";
334
+
335
+ // src/token.ts
336
+ function sessionExpiry(token) {
337
+ const segment = token.split(".")[1];
338
+ if (!segment) return null;
339
+ try {
340
+ const json = Buffer.from(segment.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
341
+ const claims = JSON.parse(json);
342
+ if (typeof claims.exp !== "number" || !Number.isFinite(claims.exp)) return null;
343
+ return new Date(claims.exp * 1e3).toISOString();
344
+ } catch {
345
+ return null;
346
+ }
347
+ }
348
+
245
349
  // src/commands.ts
246
350
  var DEFAULT_API = "https://havenbackend-production-8a00.up.railway.app";
247
- var CLI_VERSION = "0.0.0-dev.202609042048.ad6cc9b";
351
+ var CLI_VERSION = "0.0.0-dev.202609050705.51c3d92";
248
352
  async function run(argv, deps = {}) {
353
+ const out = deps.out ?? ((l) => process.stdout.write(`${l}
354
+ `));
355
+ const err = deps.err ?? ((l) => process.stderr.write(`${l}
356
+ `));
357
+ const json = argv.includes("--json");
358
+ const o = createOutput(json, out, err);
249
359
  const d = {
250
360
  sessionStore: deps.sessionStore ?? createSessionStore(),
251
361
  makeApi: deps.makeApi ?? ((baseUrl, token) => createCliApi({ baseUrl, token })),
252
362
  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
363
+ out,
364
+ err,
365
+ env: deps.env ?? process.env,
366
+ o
258
367
  };
259
368
  let args;
260
369
  try {
261
370
  args = parseArgs(argv);
262
371
  } catch (e) {
263
- d.err(e instanceof Error ? e.message : String(e));
264
- return 1;
372
+ return fail(d, new UsageError(e instanceof Error ? e.message : String(e), "Run `haven --help`."));
265
373
  }
266
374
  if (args.flags.version) {
267
- d.out(CLI_VERSION);
268
- return 0;
375
+ o.data({ version: CLI_VERSION }, () => CLI_VERSION);
376
+ return EXIT.ok;
269
377
  }
270
378
  if (args.flags.help || !args.command) {
271
- d.out(helpText());
272
- return 0;
379
+ o.data({ help: helpText() }, () => helpText());
380
+ return EXIT.ok;
273
381
  }
274
382
  try {
275
383
  return await dispatch(args, d);
276
384
  } 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;
385
+ return fail(d, e);
283
386
  }
284
387
  }
388
+ function fail(d, err) {
389
+ const failure = toFailure(err);
390
+ d.o.failure(failure);
391
+ return failure.exit;
392
+ }
285
393
  async function dispatch(args, d) {
286
394
  const key = args.sub ? `${args.command} ${args.sub}` : args.command;
287
395
  switch (key) {
396
+ case "guide":
397
+ return cmdGuide(args, d);
288
398
  case "login":
289
399
  return cmdLogin(args, d);
290
400
  case "logout":
291
- return cmdLogout(d);
401
+ return cmdLogout(args, d);
292
402
  case "whoami":
293
403
  return cmdWhoami(args, d);
294
404
  case "wallets list":
@@ -326,8 +436,7 @@ async function dispatch(args, d) {
326
436
  case "contacts remove":
327
437
  return cmdContactsRemove(args, d);
328
438
  default:
329
- d.err(`Unknown command: ${key}. Run \`haven --help\`.`);
330
- return 1;
439
+ throw new UsageError(`Unknown command: ${key}.`, "Run `haven --help` for the command list.");
331
440
  }
332
441
  }
333
442
  function baseUrlFor(args, d, session) {
@@ -335,40 +444,52 @@ function baseUrlFor(args, d, session) {
335
444
  }
336
445
  async function authed(args, d) {
337
446
  const session = await d.sessionStore.load();
338
- if (!session) throw new CliApiError("Not authenticated. Run `haven login` first.", 401);
447
+ if (!session) throw new CliApiError("Not authenticated.", 401);
339
448
  return { session, api: d.makeApi(baseUrlFor(args, d, session), session.token) };
340
449
  }
341
- function emit(d, json, data, human) {
342
- d.out(json ? JSON.stringify(data, null, 2) : human());
450
+ function emit(d, _json, data, human) {
451
+ d.o.data(data, human);
452
+ }
453
+ async function cmdGuide(_args, d) {
454
+ d.o.data({ ok: true, format: "markdown", content: HAVEN_AGENT_RUNBOOK_MD }, () => HAVEN_AGENT_RUNBOOK_MD);
455
+ return EXIT.ok;
343
456
  }
344
457
  async function cmdLogin(args, d) {
345
458
  const email = args.flags.email ?? d.env.HAVEN_EMAIL;
346
459
  if (!email) {
347
- d.err("Provide an email with --email (or HAVEN_EMAIL).");
348
- return 1;
460
+ throw new UsageError("An email is required.", "Pass --email <address>, or set HAVEN_EMAIL.");
349
461
  }
350
462
  const password = d.env.HAVEN_PASSWORD ?? await d.promptPassword();
351
463
  if (!password) {
352
- d.err("A password is required.");
353
- return 1;
464
+ throw new UsageError("A password is required.", "Set HAVEN_PASSWORD for a non-interactive run.");
354
465
  }
355
466
  const baseUrl = baseUrlFor(args, d, null);
356
467
  const api = d.makeApi(baseUrl);
357
468
  const res = await api.post("/auth/login", { email, password });
358
469
  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;
470
+ emit(
471
+ d,
472
+ args.flags.json,
473
+ { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },
474
+ () => `Signed in as ${res.user.email}.`
475
+ );
476
+ return EXIT.ok;
361
477
  }
362
- async function cmdLogout(d) {
478
+ async function cmdLogout(args, d) {
363
479
  await d.sessionStore.clear();
364
- d.out("Signed out.");
365
- return 0;
480
+ emit(d, args.flags.json, { ok: true, signed_out: true }, () => "Signed out.");
481
+ return EXIT.ok;
366
482
  }
367
483
  async function cmdWhoami(args, d) {
368
- const { api } = await authed(args, d);
484
+ const { session, api } = await authed(args, d);
369
485
  const user = await api.get("/auth/me");
370
- emit(d, args.flags.json, user, () => `${user.email}${user.name ? ` (${user.name})` : ""}`);
371
- return 0;
486
+ emit(
487
+ d,
488
+ args.flags.json,
489
+ { ...user, id: user.id, email: user.email, expires_at: sessionExpiry(session.token), api_url: session.apiBaseUrl },
490
+ () => `${user.email}${user.name ? ` (${user.name})` : ""}`
491
+ );
492
+ return EXIT.ok;
372
493
  }
373
494
  async function cmdWalletsList(args, d) {
374
495
  const { api } = await authed(args, d);
@@ -382,15 +503,15 @@ async function cmdWalletsList(args, d) {
382
503
  safes.map((s) => [s.name, chainName(s.chain_id), truncateAddress(s.safe_address), s.is_default ? "\u2713" : ""])
383
504
  )
384
505
  );
385
- return 0;
506
+ return EXIT.ok;
386
507
  }
387
508
  async function cmdWalletsBalances(args, d) {
388
509
  const { api } = await authed(args, d);
389
510
  const { safes } = await api.get("/user/safes");
390
511
  const safe = pickSafe(safes, args.flags.safe);
391
512
  if (!safe) {
392
- d.err(args.flags.safe ? `No wallet matches "${args.flags.safe}".` : "No Haven wallet found.");
393
- return 1;
513
+ if (args.flags.safe) throw new UsageError(`No wallet matches "${args.flags.safe}".`);
514
+ throw new CliApiError("No Haven wallet found.", 404);
394
515
  }
395
516
  const { balances } = await api.get(
396
517
  `/balances/${safe.safe_address}?chain_id=${safe.chain_id}`
@@ -404,7 +525,7 @@ async function cmdWalletsBalances(args, d) {
404
525
  balances.length === 0 ? " (no balances)" : table(["TOKEN", "BALANCE"], balances.map((b) => [b.symbol, b.formatted]))
405
526
  ].join("\n")
406
527
  );
407
- return 0;
528
+ return EXIT.ok;
408
529
  }
409
530
  function pickSafe(safes, ref) {
410
531
  if (!ref) return safes.find((s) => s.is_default) ?? safes[0];
@@ -423,14 +544,11 @@ async function cmdAgentsList(args, d) {
423
544
  agents.map((a) => [a.id, a.name, a.status, budgetSummary(a.allowances)])
424
545
  )
425
546
  );
426
- return 0;
547
+ return EXIT.ok;
427
548
  }
428
549
  async function cmdAgentsShow(args, d) {
429
550
  const id = args.positionals[0];
430
- if (!id) {
431
- d.err("Usage: haven agents show <id>");
432
- return 1;
433
- }
551
+ if (!id) throw new UsageError("Usage: haven agents show <id>");
434
552
  const { api } = await authed(args, d);
435
553
  const agent = await api.get(`/agents/${id}`);
436
554
  emit(
@@ -443,14 +561,11 @@ async function cmdAgentsShow(args, d) {
443
561
  `budget: ${budgetSummary(agent.allowances)}`
444
562
  ].join("\n")
445
563
  );
446
- return 0;
564
+ return EXIT.ok;
447
565
  }
448
566
  async function cmdBudgetShow(args, d) {
449
567
  const id = args.positionals[0];
450
- if (!id) {
451
- d.err("Usage: haven budget show <agentId>");
452
- return 1;
453
- }
568
+ if (!id) throw new UsageError("Usage: haven budget show <agentId>");
454
569
  const { api } = await authed(args, d);
455
570
  const agent = await api.get(`/agents/${id}`);
456
571
  const allowances = agent.allowances ?? [];
@@ -463,7 +578,7 @@ async function cmdBudgetShow(args, d) {
463
578
  allowances.map((a) => [a.token_symbol, a.allowance_amount, resetLabel(a.reset_period_min)])
464
579
  )
465
580
  );
466
- return 0;
581
+ return EXIT.ok;
467
582
  }
468
583
  function budgetSummary(allowances) {
469
584
  if (!allowances || allowances.length === 0) return "\u2014";
@@ -478,75 +593,64 @@ function resetLabel(mins) {
478
593
  }
479
594
  async function cmdAgentLifecycle(args, d, action) {
480
595
  const id = args.positionals[0];
481
- if (!id) {
482
- d.err(`Usage: haven agents ${action} <id>`);
483
- return 1;
484
- }
596
+ if (!id) throw new UsageError(`Usage: haven agents ${action} <id>`);
485
597
  const { api } = await authed(args, d);
486
598
  await api.post(`/agents/${id}/${action}`);
487
- d.out(`Agent ${id} ${action === "pause" ? "paused" : "resumed"}.`);
488
- return 0;
599
+ const status = action === "pause" ? "paused" : "resumed";
600
+ emit(d, args.flags.json, { ok: true, agent_id: id, status }, () => `Agent ${id} ${status}.`);
601
+ return EXIT.ok;
489
602
  }
490
603
  async function cmdAgentRevoke(args, d) {
491
604
  const id = args.positionals[0];
492
- if (!id) {
493
- d.err("Usage: haven agents revoke <id> --yes");
494
- return 1;
495
- }
605
+ if (!id) throw new UsageError("Usage: haven agents revoke <id> --yes");
496
606
  if (!args.flags.yes) {
497
- d.err(`This permanently revokes agent ${id}. Re-run with --yes to confirm.`);
498
- return 1;
607
+ throw new UsageError(
608
+ `This permanently revokes agent ${id}.`,
609
+ "Re-run with --yes to confirm. Revoke is terminal \u2014 the agent cannot go back to active."
610
+ );
499
611
  }
500
612
  const { api } = await authed(args, d);
501
613
  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;
614
+ emit(
615
+ d,
616
+ args.flags.json,
617
+ { ok: true, agent_id: id, status: "revoked" },
618
+ () => `Agent ${id} revoked. To also remove its on-chain allowance, use the dashboard.`
619
+ );
620
+ return EXIT.ok;
504
621
  }
505
622
  async function cmdAgentRotateKey(args, d) {
506
623
  const id = args.positionals[0];
507
- if (!id) {
508
- d.err("Usage: haven agents rotate-key <id>");
509
- return 1;
510
- }
624
+ if (!id) throw new UsageError("Usage: haven agents rotate-key <id>");
511
625
  const { api } = await authed(args, d);
512
626
  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;
627
+ d.o.note("New API key (shown once \u2014 store it now; the old key stops working):");
628
+ emit(d, args.flags.json, res, () => res.api_key);
629
+ return EXIT.ok;
520
630
  }
521
631
  async function cmdAgentRename(args, d) {
522
632
  const [id, ...nameParts] = args.positionals;
523
633
  const name = nameParts.join(" ").trim();
524
- if (!id || !name) {
525
- d.err("Usage: haven agents rename <id> <name>");
526
- return 1;
527
- }
634
+ if (!id || !name) throw new UsageError("Usage: haven agents rename <id> <name>");
528
635
  const { api } = await authed(args, d);
529
636
  await api.put(`/agents/${id}`, { name });
530
- d.out(`Agent ${id} renamed to "${name}".`);
531
- return 0;
637
+ emit(d, args.flags.json, { ok: true, agent_id: id, name }, () => `Agent ${id} renamed to "${name}".`);
638
+ return EXIT.ok;
532
639
  }
533
640
  async function cmdWalletRename(args, d) {
534
641
  const [id, ...nameParts] = args.positionals;
535
642
  const name = nameParts.join(" ").trim();
536
- if (!id || !name) {
537
- d.err("Usage: haven wallets rename <id> <name>");
538
- return 1;
539
- }
643
+ if (!id || !name) throw new UsageError("Usage: haven wallets rename <id> <name>");
540
644
  const { api } = await authed(args, d);
541
645
  await api.put(`/user/safes/${id}`, { name });
542
- d.out(`Wallet ${id} renamed to "${name}".`);
543
- return 0;
646
+ emit(d, args.flags.json, { ok: true, safe_id: id, name }, () => `Wallet ${id} renamed to "${name}".`);
647
+ return EXIT.ok;
544
648
  }
545
649
  async function resolveSafeId(args, api) {
546
650
  if (!args.flags.safe) return void 0;
547
651
  const { safes } = await api.get("/user/safes");
548
652
  const safe = pickSafe(safes, args.flags.safe);
549
- if (!safe) throw new CliApiError(`No wallet matches "${args.flags.safe}".`, 1);
653
+ if (!safe) throw new UsageError(`No wallet matches "${args.flags.safe}".`);
550
654
  return safe.id;
551
655
  }
552
656
  async function cmdActivityList(args, d) {
@@ -575,7 +679,7 @@ async function cmdActivityList(args, d) {
575
679
  ])
576
680
  )
577
681
  );
578
- return 0;
682
+ return EXIT.ok;
579
683
  }
580
684
  async function cmdActivityExport(args, d) {
581
685
  if (args.flags.format === "sie") return exportSie(args, d);
@@ -617,8 +721,8 @@ async function cmdActivityExport(args, d) {
617
721
  t.hash,
618
722
  t.chainId != null ? String(t.chainId) : ""
619
723
  ]);
620
- d.out(toCsv(headers, rows));
621
- return 0;
724
+ d.o.text(toCsv(headers, rows), { format: "csv", rows: rows.length });
725
+ return EXIT.ok;
622
726
  }
623
727
  function exportType(t) {
624
728
  if (t.activityType === "delegate_sweep") return "allowance funding";
@@ -638,8 +742,8 @@ async function exportSie(args, d) {
638
742
  if (args.flags.to) params.set("to", args.flags.to);
639
743
  if (args.flags.company) params.set("company", args.flags.company);
640
744
  const content = await api.getText(`/accounting/export?${params.toString()}`);
641
- d.out(content);
642
- return 0;
745
+ d.o.text(content, { format: "sie" });
746
+ return EXIT.ok;
643
747
  }
644
748
  async function cmdCatalogList(args, d) {
645
749
  const { api } = await authed(args, d);
@@ -653,7 +757,7 @@ async function cmdCatalogList(args, d) {
653
757
  entries.map((e) => [e.name, e.category, e.rail, e.price_display ?? "\u2014", e.status])
654
758
  )
655
759
  );
656
- return 0;
760
+ return EXIT.ok;
657
761
  }
658
762
  async function cmdContactsList(args, d) {
659
763
  const { api } = await authed(args, d);
@@ -664,36 +768,28 @@ async function cmdContactsList(args, d) {
664
768
  contacts,
665
769
  () => contacts.length === 0 ? "No contacts yet." : table(["ID", "NAME", "ADDRESS"], contacts.map((c) => [c.id, c.name, truncateAddress(c.address)]))
666
770
  );
667
- return 0;
771
+ return EXIT.ok;
668
772
  }
669
773
  async function cmdContactsAdd(args, d) {
670
774
  const [address, ...nameParts] = [...args.positionals].reverse();
671
775
  const name = nameParts.reverse().join(" ").trim();
672
- if (!name || !address) {
673
- d.err("Usage: haven contacts add <name> <address>");
674
- return 1;
675
- }
776
+ if (!name || !address) throw new UsageError("Usage: haven contacts add <name> <address>");
676
777
  const { api } = await authed(args, d);
677
778
  const contact = await api.post("/contacts", { name, address });
678
779
  emit(d, args.flags.json, contact, () => `Added contact "${contact.name}" (${truncateAddress(contact.address)}).`);
679
- return 0;
780
+ return EXIT.ok;
680
781
  }
681
782
  async function cmdContactsRemove(args, d) {
682
783
  const id = args.positionals[0];
683
- if (!id) {
684
- d.err("Usage: haven contacts remove <id>");
685
- return 1;
686
- }
784
+ if (!id) throw new UsageError("Usage: haven contacts remove <id>");
687
785
  const { api } = await authed(args, d);
688
786
  await api.del(`/contacts/${id}`);
689
- d.out(`Contact ${id} removed.`);
690
- return 0;
787
+ emit(d, args.flags.json, { ok: true, contact_id: id, removed: true }, () => `Contact ${id} removed.`);
788
+ return EXIT.ok;
691
789
  }
692
-
693
- // src/cli.ts
694
- function promptPassword() {
790
+ function promptPasswordWith(streams) {
695
791
  return new Promise((resolve2, reject) => {
696
- const { stdin, stdout } = process;
792
+ const { stdin, stderr } = streams;
697
793
  if (!stdin.isTTY) {
698
794
  let data = "";
699
795
  stdin.setEncoding("utf8");
@@ -702,18 +798,18 @@ function promptPassword() {
702
798
  stdin.on("error", reject);
703
799
  return;
704
800
  }
705
- stdout.write("Password: ");
801
+ stderr.write("Password: ");
706
802
  emitKeypressEvents(stdin);
707
803
  stdin.setRawMode(true);
708
804
  let value = "";
709
805
  const onKey = (char, key) => {
710
806
  if (key.name === "return" || key.name === "enter") {
711
807
  cleanup();
712
- stdout.write("\n");
808
+ stderr.write("\n");
713
809
  resolve2(value);
714
810
  } else if (key.ctrl && key.name === "c") {
715
811
  cleanup();
716
- stdout.write("\n");
812
+ stderr.write("\n");
717
813
  reject(new Error("Cancelled"));
718
814
  } else if (key.name === "backspace") {
719
815
  value = value.slice(0, -1);
@@ -730,9 +826,20 @@ function promptPassword() {
730
826
  stdin.on("keypress", onKey);
731
827
  });
732
828
  }
829
+
830
+ // src/cli.ts
831
+ function promptPassword() {
832
+ return promptPasswordWith({ stdin: process.stdin, stdout: process.stdout, stderr: process.stderr });
833
+ }
733
834
  run(process.argv.slice(2), { promptPassword }).then((code) => process.exit(code)).catch((err) => {
734
- process.stderr.write(`${err instanceof Error ? err.message : String(err)}
835
+ const message = err instanceof Error ? err.message : String(err);
836
+ if (process.argv.includes("--json")) {
837
+ process.stdout.write(`${JSON.stringify({ ok: false, error: { code: "failed", message } }, null, 2)}
838
+ `);
839
+ } else {
840
+ process.stderr.write(`${message}
735
841
  `);
842
+ }
736
843
  process.exit(1);
737
844
  });
738
845
  //# sourceMappingURL=cli.js.map