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