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