@haven_ai/cli 0.0.0-dev.202610141909.1546aaa → 0.0.0-dev.202610142033.0d2f50f
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 +7 -1
- package/dist/cli.cjs +22 -8
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +22 -8
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +22 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +22 -8
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/args.ts","../src/api.ts","../src/session.ts","../src/format.ts","../src/csv.ts","../src/errors.ts","../src/output.ts","../src/agent-guidance-text.ts","../src/token.ts","../src/amount.ts","../src/connect-runner.ts","../../../node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/sha3.ts","../../../node_modules/@scure/bip39/esm/wordlists/english.js","../src/secret-check.ts","../src/commands.ts"],"names":["resolve","readFile","join","homedir","run","refusal"],"mappings":";;;;;;;AAyFA,IAAM,WAAA,uBAAkB,GAAA,CAAI;AAAA,EAC1B,OAAA;AAAA,EAAS,SAAA;AAAA,EAAW,QAAA;AAAA,EAAU,SAAA;AAAA,EAAW,SAAA;AAAA,EAAW,UAAA;AAAA,EAAY,aAAA;AAAA,EAChE,UAAA;AAAA,EAAY,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,WAAA;AAAA,EAC9B,QAAA;AAAA,EAAU,UAAA;AAAA,EAAY,SAAA;AAAA,EAAW,UAAA;AAAA,EAAY,UAAA;AAAA,EAC7C,UAAA;AAAA,EAAY,aAAA;AAAA,EAAe,WAAA;AAAA,EAAa;AAC1C,CAAC,CAAA;AAMM,SAAS,UAAU,IAAA,EAA4B;AACpD,EAAA,MAAM,cAAwB,EAAC;AAC/B,EAAA,MAAM,KAAA,GA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AA,CAAA,EAAI;AAAA,MAClG,OAAOA,QAAAA,CAAQ,KAAA;AAAA,MACf,QAAQA,QAAAA,CAAQ;AAAA,KACjB,CAAA;AAAA,EACH;AAKA,EAAA,CAAA,CAAE,CAAA,CAAE,IAAA;AAAA,IACF;AAAA,GACF;AAEA,EAAA,MAAM,SAAS,MAAM,GAAA,CAAI,KAA6D,WAAA,EAAa,EAAE,MAAM,CAAA;AAC3G,EAAA,IAAA,CAAK,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,IAAA,EAAM,EAAE,EAAA,EAAI,IAAA,EAAM,GAAG,MAAA,EAAO,EAAG,MAAM,CAAA,uBAAA,EAA0B,MAAA,CAAO,EAAE,CAAA,EAAA,CAAI,CAAA;AAC/F,EAAA,OAAO,IAAA,CAAK,EAAA;AACd","file":"index.js","sourcesContent":["export interface ParsedArgs {\n command?: string\n sub?: string\n positionals: string[]\n flags: {\n json: boolean\n help: boolean\n /** #2526: print the code and exit instead of polling for approval. */\n noWait: boolean\n /** #2527: run the printed connector command as a child process. */\n run: boolean\n /** #2527: poll `agents connect --status` until it settles. */\n wait: boolean\n /**\n * #2612: list the delegation HASHES on `budget show`, which is the only\n * thing `budget revoke` accepts as its second argument. Behind a flag\n * because `budget show --json` has emitted a bare allowances array since\n * the first CLI scaffold, and a second shape on the same command would\n * break every existing consumer of it.\n */\n hashes: boolean\n version: boolean\n yes: boolean\n /**\n * #3729: override for `agents revoke` — revoke the agent even though a\n * budget delegation is still live on-chain (pending, active or replaced),\n * saying so out loud instead of silently leaving the budget redeemable.\n * Without it the command refuses and lists the exact `haven budget\n * revoke` command for each live row.\n */\n keepBudget: boolean\n api?: string\n email?: string\n safe?: string\n agent?: string\n limit?: number\n offset?: number\n direction?: 'in' | 'out'\n format?: string\n from?: string\n to?: string\n company?: string\n /** #2527 */\n name?: string\n budget?: string\n token?: string\n period?: number\n status?: string\n /**\n * #2539: the budget magnitude for `budget grant`, in whole tokens as you\n * would say it (`25` is 25 USDC) — parsed to atomic units with decimals\n * read from the backend, exactly like `agents connect`'s --budget. Named\n * --amount because the issue's command sketch does, and because a grant\n * is not the same decision as a connect.\n */\n amount?: string\n /**\n * #2539: optional recipient pin for `budget grant`. An ADDRESS the budget\n * may pay and nobody else — the caveat enforcer set at build time. Absent\n * means an open budget, exactly like the dashboard form's blank field.\n */\n recipient?: string\n /**\n * #2539: optional expiry (unix seconds) for `budget grant`. Absent lets\n * the backend default (now + 90 days), the same default the dashboard's\n * builds get.\n */\n expires?: number\n /**\n * #2618: the device code for `haven login --poll <device_code>` — ONE poll\n * round against POST /auth/device/token, for an agent that printed the\n * link with `--no-wait` and came back later. The value is REQUIRED: a bare\n * `--poll` would look like it resumed something.\n */\n poll?: string\n /**\n * #2527: deliberately absent — `--recipient` for `agents connect`. The\n * issue sketched one, and neither `POST /agents` nor\n * `POST /agent-connection-setups` has a field to\n * put it in: a recipient pin lives in the delegation's caveat enforcers and\n * is set when the human approves the budget. A flag accepted here would\n * either be silently dropped or invent a wire field, and a budget control\n * that looks applied and is not is worse than one you cannot ask for.\n * (Note: `budget grant` DOES take `--recipient` — the delegation build\n * route has that field; connect does not.)\n */\n }\n}\n\nconst VALUE_FLAGS = new Set([\n '--api', '--email', '--safe', '--agent', '--limit', '--offset', '--direction',\n '--format', '--from', '--to', '--company',\n '--name', '--budget', '--token', '--period', '--status',\n '--amount', '--recipient', '--expires', '--poll',\n])\n\n/**\n * `haven <command> [sub] [positionals] [--flags]`. Deliberately small — no\n * dependency, no clever aliasing. Unknown flags throw so typos fail loudly.\n */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const positionals: string[] = []\n const flags: ParsedArgs['flags'] = {\n json: false, help: false, version: false, yes: false, noWait: false, run: false, wait: false, hashes: false, keepBudget: false,\n }\n\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i]\n if (arg === '--json') flags.json = true\n else if (arg === '--help' || arg === '-h') flags.help = true\n else if (arg === '--version' || arg === '-v') flags.version = true\n else if (arg === '--yes' || arg === '-y') flags.yes = true\n else if (arg === '--keep-budget') flags.keepBudget = true\n else if (arg === '--no-wait') flags.noWait = true\n else if (arg === '--run') flags.run = true\n else if (arg === '--wait') flags.wait = true\n else if (arg === '--hashes') flags.hashes = true\n else if (VALUE_FLAGS.has(arg)) {\n const value = argv[++i]\n if (value === undefined || value.startsWith('--')) {\n throw new Error(`Missing value for ${arg}`)\n }\n if (arg === '--api') flags.api = value\n else if (arg === '--name') flags.name = value\n else if (arg === '--budget') flags.budget = value\n else if (arg === '--token') flags.token = value\n else if (arg === '--status') flags.status = value\n else if (arg === '--period') {\n const n = Number(value)\n if (!Number.isInteger(n) || n < 0) throw new Error('--period must be a whole number of minutes')\n flags.period = n\n }\n else if (arg === '--email') flags.email = value\n else if (arg === '--safe') flags.safe = value\n else if (arg === '--agent') flags.agent = value\n else if (arg === '--limit') {\n const n = Number(value)\n if (!Number.isInteger(n) || n <= 0) throw new Error('--limit must be a positive integer')\n flags.limit = n\n } else if (arg === '--offset') {\n const n = Number(value)\n if (!Number.isInteger(n) || n < 0) throw new Error('--offset must be a non-negative integer')\n flags.offset = n\n } else if (arg === '--direction') {\n if (value !== 'in' && value !== 'out') throw new Error('--direction must be \"in\" or \"out\"')\n flags.direction = value\n } else if (arg === '--recipient') {\n flags.recipient = value\n } else if (arg === '--amount') {\n flags.amount = value\n } else if (arg === '--expires') {\n const n = Number(value)\n if (!Number.isInteger(n) || n <= 0) throw new Error('--expires must be a unix timestamp in seconds')\n flags.expires = n\n } else if (arg === '--format') {\n if (value !== 'csv' && value !== 'sie') throw new Error('--format must be \"csv\" or \"sie\"')\n flags.format = value\n } else if (arg === '--poll') {\n flags.poll = value\n } else if (arg === '--from') flags.from = value\n else if (arg === '--to') flags.to = value\n else if (arg === '--company') flags.company = value\n } else if (arg.startsWith('--')) {\n throw new Error(`Unknown option: ${arg}`)\n } else {\n positionals.push(arg)\n }\n }\n\n const [command, sub, ...rest] = positionals\n return { command, sub, positionals: rest, flags }\n}\n\nexport function helpText(): string {\n return [\n 'haven — set up and run a Haven agent from the terminal. It never signs.',\n '',\n 'Usage: haven <command> [subcommand] [options]',\n '',\n 'Auth:',\n ' login Sign in. Opens a browser device-code approval by default —',\n ' it prints a code and a link, and never asks for a password',\n ' login --email <e> Password path instead (prompt, or HAVEN_PASSWORD)',\n ' login --no-wait Print the link and exit instead of polling. Under --json,',\n ' pass it: you get the object back at once (it carries',\n ' device_code) and finish with `login --poll <device_code>`',\n ' login --poll <code> One poll round of a started device flow: exit 0 approved,',\n ' 3 still pending (the object carries retry_after), 4 denied',\n ' logout Clear the saved session',\n ' whoami Show the signed-in user, session expiry and API URL',\n '',\n 'For agents:',\n ' guide Print the agent onboarding runbook (same text as /for-agents.md)',\n ' agents connect --name <n> --budget <amount> --token USDC --period <minutes>',\n ' Create a connection setup; prints the connector command and',\n ' the approval link for your human. --run executes it here.',\n ' agents connect --status <setupId> [--wait] Read one setup\\'s status',\n '',\n 'Read:',\n ' wallets list List your Haven wallets',\n ' wallets balances [--safe <id|address>] Token balances for a wallet',\n ' wallets funding [--safe <id|address>] [--wait] The paste-ready funding',\n ' instruction: what to send, where, on which chain.',\n ' --wait polls until the account counts as funded.',\n ' agents list List your agents',\n ' agents show <id> Show one agent + its budget',\n ' budget show <agentId> Show an agent\\'s configured budget',\n ' budget show <agentId> --hashes Its delegation hashes — the second',\n ' argument `budget revoke` takes, printed nowhere else',\n ' activity list [--safe <id|address>] [--agent <id>] [--direction in|out] [--limit <n>] [--offset <n>]',\n ' Wallet-scoped history; --agent narrows it (--json rows carry scope, timestampSource)',\n ' activity export [filters] Emit CSV to stdout (--format csv, default)',\n ' activity export --format sie [--from <ISO>] [--to <ISO>] [--company <name>]',\n ' Bookkeeping-ready SIE 4I (Fortnox/Visma/Bokio)',\n ' catalog list List payable services',\n ' contacts list List your address book',\n '',\n 'Feedback:',\n ' feedback submit \"<text>\" Send feedback or a bug report. Needs',\n ' `haven login`. It refuses to send text that',\n ' looks like a credential, but cannot catch',\n ' every secret shape — never include one.',\n '',\n 'Manage (backend-only — no on-chain signing):',\n ' agents pause <id> Block payments through Haven; the budget',\n ' stays live on-chain (end it: budget revoke)',\n ' agents resume <id> Allow payments through Haven again',\n ' agents revoke <id> --yes Retire the agent in Haven (terminal). Ends no',\n ' budget on-chain: run budget revoke first; refuses',\n ' while a budget is still live unless --keep-budget',\n ' agents rotate-key <id> Issue a new API key (shown once)',\n ' agents rename <id> <name>',\n ' wallets rename <id> <name>',\n ' contacts add <name> <address> Save an address under a name',\n ' contacts remove <id> Forget one',\n '',\n 'Budgets (construct-and-hand-off — the CLI never signs, #2539):',\n ' budget grant <agentId> --amount <n> --token USDC --period <minutes>',\n ' [--recipient <address>] [--expires <unix-s>] [--wait]',\n ' Prints a signing link; the human signs in the dashboard.',\n ' budget revoke <agentId> <delegationHash> [--wait]',\n ' Prints a revocation link; the human signs in the dashboard.',\n '',\n 'Options:',\n ' --json One JSON value on stdout, prose on stderr, on every',\n ' command including refusals: { ok: false, error: { code, message, hint? } }',\n ' --yes, -y Skip the confirmation prompt for destructive actions',\n ' --api <url> Backend URL. Default: HAVEN_API_URL, else Haven\\'s hosted',\n ' production backend — NOT localhost. On any other',\n ' deployment an omitted flag connects to production.',\n ' --help, --version',\n '',\n 'Exit codes: 0 ok · 1 failed · 2 usage · 3 not authenticated · 4 refused · 5 network',\n '',\n 'On-chain actions (deploy, budgets, approvers, send) are signed in the',\n 'dashboard — this CLI reads and manages; it never holds your keys.',\n ].join('\\n')\n}\n","export class CliApiError extends Error {\n status: number\n /**\n * The parsed response body, when there was one (#2526).\n *\n * The message is built FROM `body.error` for humans, and the device flow\n * needs the same value as DATA: `authorization_pending` and `slow_down` are\n * control signals in a poll loop, and branching on them by matching the\n * message string would make the loop depend on prose that is free to change.\n */\n body?: unknown\n constructor(message: string, status: number, body?: unknown) {\n super(message)\n this.name = 'CliApiError'\n this.status = status\n this.body = body\n }\n}\n\nexport interface CliApi {\n get<T>(path: string): Promise<T>\n post<T>(path: string, body?: unknown): Promise<T>\n put<T>(path: string, body?: unknown): Promise<T>\n del<T>(path: string): Promise<T>\n /** GET a non-JSON body (e.g. an export file) as raw text. */\n getText(path: string): Promise<string>\n}\n\nexport interface CreateCliApiOptions {\n baseUrl: string\n token?: string\n fetchImpl?: typeof fetch\n /**\n * #3303: `@haven_ai/cli/<version>`, sent as `X-Haven-Client` so the backend\n * can tell an outdated CLI what to run. Passed in by `commands.ts`, which\n * owns `CLI_VERSION`, rather than imported here (commands.ts imports this file).\n */\n clientIdentity?: string\n}\n\n/**\n * Minimal JSON client for the Haven backend. Sends the user JWT as a Bearer\n * token when present, and surfaces backend `{ error }` messages as\n * `CliApiError` so commands can print something human.\n */\nexport function createCliApi({ baseUrl, token, fetchImpl = fetch, clientIdentity }: CreateCliApiOptions): CliApi {\n const root = baseUrl.replace(/\\/+$/, '')\n\n async function request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = { Accept: 'application/json' }\n if (token) headers.Authorization = `Bearer ${token}`\n if (clientIdentity) headers['X-Haven-Client'] = clientIdentity\n if (body !== undefined) headers['Content-Type'] = 'application/json'\n\n let res: Response\n try {\n res = await fetchImpl(`${root}${path}`, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n })\n } catch (err) {\n throw new CliApiError(\n `Could not reach Haven at ${root}: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n }\n\n if (res.status === 401) {\n throw new CliApiError('Not authenticated. Run `haven login` first.', 401)\n }\n\n const text = await res.text()\n const payload = text ? safeParse(text) : undefined\n\n if (!res.ok) {\n const message =\n (payload && typeof payload === 'object' && 'error' in payload && typeof payload.error === 'string'\n ? payload.error\n : null) ?? `Request failed (HTTP ${res.status}).`\n throw new CliApiError(message, res.status, payload)\n }\n\n return payload as T\n }\n\n async function requestText(path: string): Promise<string> {\n const headers: Record<string, string> = { Accept: 'text/plain' }\n if (token) headers.Authorization = `Bearer ${token}`\n if (clientIdentity) headers['X-Haven-Client'] = clientIdentity\n\n let res: Response\n try {\n res = await fetchImpl(`${root}${path}`, { method: 'GET', headers })\n } catch (err) {\n throw new CliApiError(\n `Could not reach Haven at ${root}: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n }\n\n if (res.status === 401) {\n throw new CliApiError('Not authenticated. Run `haven login` first.', 401)\n }\n\n const text = await res.text()\n if (!res.ok) {\n const payload = text ? safeParse(text) : undefined\n const message =\n (payload && typeof payload === 'object' && 'error' in payload && typeof payload.error === 'string'\n ? payload.error\n : null) ?? `Request failed (HTTP ${res.status}).`\n throw new CliApiError(message, res.status)\n }\n return text\n }\n\n return {\n get: <T>(path: string) => request<T>('GET', path),\n post: <T>(path: string, body?: unknown) => request<T>('POST', path, body),\n put: <T>(path: string, body?: unknown) => request<T>('PUT', path, body),\n del: <T>(path: string) => request<T>('DELETE', path),\n getText: (path: string) => requestText(path),\n }\n}\n\nfunction safeParse(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n","import { mkdir, readFile, rm, writeFile, chmod } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\n/**\n * The signed-in user session. The token is a *user* JWT (same credential the\n * dashboard holds) — treat it like a secret: stored owner-only, never logged,\n * never sent anywhere but the Haven API. `apiBaseUrl` is pinned at login so\n * later commands talk to the same backend.\n */\nexport interface Session {\n token: string\n apiBaseUrl: string\n user: { id: string; email: string; name: string | null }\n}\n\nexport interface SessionStore {\n load(): Promise<Session | null>\n save(session: Session): Promise<void>\n clear(): Promise<void>\n path: string\n}\n\nfunction sessionDir(homeDir: string): string {\n return resolve(homeDir, '.haven')\n}\n\nexport function sessionPath(homeDir: string = homedir()): string {\n return join(sessionDir(homeDir), 'session.json')\n}\n\n/** File-backed session store, owner-only perms (0600 file in a 0700 dir). */\nexport function createSessionStore(homeDir: string = homedir()): SessionStore {\n const path = sessionPath(homeDir)\n return {\n path,\n async load() {\n try {\n const raw = await readFile(path, 'utf8')\n const parsed = JSON.parse(raw) as Partial<Session>\n if (!parsed.token || !parsed.apiBaseUrl || !parsed.user) return null\n return parsed as Session\n } catch {\n return null\n }\n },\n async save(session) {\n await mkdir(sessionDir(homeDir), { recursive: true, mode: 0o700 })\n await writeFile(path, `${JSON.stringify(session, null, 2)}\\n`, { mode: 0o600 })\n await chmod(path, 0o600).catch(() => undefined)\n },\n async clear() {\n await rm(path, { force: true })\n },\n }\n}\n","/** Tiny fixed-width table for human output. Scriptable callers use `--json`. */\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n )\n const line = (cells: string[]) =>\n cells.map((c, i) => (c ?? '').padEnd(widths[i])).join(' ').trimEnd()\n return [line(headers), line(widths.map((w) => '-'.repeat(w))), ...rows.map(line)].join('\\n')\n}\n\nexport function truncateAddress(address: string): string {\n if (!address || address.length <= 12) return address\n return `${address.slice(0, 6)}…${address.slice(-4)}`\n}\n\nconst CHAIN_NAMES: Record<number, string> = { 8453: 'Base', 84532: 'Base Sepolia' }\n\nexport function chainName(chainId: number): string {\n return CHAIN_NAMES[chainId] ?? `chain ${chainId}`\n}\n\n/**\n * \"5m ago\", \"2h ago\", \"3d ago\" — the ladder the dashboard's stale-balance\n * indicator renders (`packages/frontend/src/components/haven/\n * BalanceFreshnessIndicator.tsx`), lifted for the CLI so both surfaces word\n * the same wire marker the same way. Just-now keeps both boundaries the\n * frontend's helper keeps: a clock slightly ahead of the read, and reads\n * younger than a minute.\n */\nexport function timeAgo(iso: string): string {\n const diff = Date.now() - new Date(iso).getTime()\n if (diff < 60_000) return 'just now'\n const mins = Math.floor(diff / 60_000)\n if (mins < 60) return `${mins}m ago`\n const hours = Math.floor(mins / 60)\n if (hours < 24) return `${hours}h ago`\n const days = Math.floor(hours / 24)\n if (days < 30) return `${days}d ago`\n const months = Math.floor(days / 30)\n if (months < 12) return `${months}mo ago`\n return `${Math.floor(days / 365)}y ago`\n}\n","/**\n * CSV serialization for `haven activity export`. Mirrors the dashboard export\n * (#411): RFC 4180 quoting, CRLF line endings, and a spreadsheet\n * formula-injection guard. Kept self-contained so the CLI has no @haven_ai/*\n * runtime dependency.\n */\n\n/** Quote per RFC 4180 and neutralise leading =,+,-,@ (Excel formula injection). */\nfunction csvField(value: string): string {\n let v = value\n if (/^[=+\\-@\\t\\r]/.test(v)) v = `'${v}`\n return `\"${v.replace(/\"/g, '\"\"')}\"`\n}\n\nexport function toCsv(headers: string[], rows: string[][]): string {\n const lines = [headers.join(','), ...rows.map((r) => r.map(csvField).join(','))]\n return lines.join('\\r\\n')\n}\n","import { CliApiError } from './api.js'\n\n/**\n * Exit codes (#2525). Documented in README.md § For agents and scripts, and\n * asserted in `json-contract.test.ts` (every code, over the whole command list)\n * and `commands.test.ts` (the individual commands that produce them) — an agent\n * branches on these, so they are a contract rather than an implementation\n * detail.\n */\nexport const EXIT = {\n ok: 0,\n /** Something failed and none of the specific codes below describe it. */\n failed: 1,\n /** The command line was wrong: unknown command, missing argument, bad flag. */\n usage: 2,\n /** No stored session, or the backend rejected the one we have. Log in again. */\n notAuthenticated: 3,\n /** Authenticated, and the backend refused anyway (403, 410, other 4xx). */\n refused: 4,\n /** The backend could not be reached at all. */\n network: 5,\n} as const\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT]\n\n/** Machine-readable `error.code` values, one per exit code above 0. */\nexport type FailureCode = 'failed' | 'usage' | 'not_authenticated' | 'refused' | 'network'\n\n/** A wrong command line. Carries `usage` so callers do not guess the exit code. */\nexport class UsageError extends Error {\n readonly hint?: string\n constructor(message: string, hint?: string) {\n super(message)\n this.name = 'UsageError'\n this.hint = hint\n }\n}\n\n/**\n * A failure that already knows its exit code (#2526).\n *\n * The device flow's outcomes are not exceptions in the usual sense — a denied\n * approval and an expired code are ordinary, expected answers — but they must\n * still exit non-zero with the RIGHT code, because that is the contract an\n * agent reads. Carrying the code on the error keeps the decision at the place\n * that knows the outcome rather than in a string match downstream.\n */\nexport class HavenCliError extends Error {\n readonly exit: ExitCode\n readonly hint?: string\n /**\n * #3597: additional typed fields merged into the `--json` error object\n * (`error.layer`, `error.reason`, …) — for a refusal where the FREE-TEXT\n * hint is not enough to branch on. `feedback submit`'s secret check is the\n * first caller: an agent needs `error.layer` (which of the four checks\n * refused) as a number, not a string it has to parse out of a sentence.\n */\n readonly extra?: Record<string, unknown>\n constructor(message: string, exit: ExitCode, hint?: string, extra?: Record<string, unknown>) {\n super(message)\n this.name = 'HavenCliError'\n this.exit = exit\n this.hint = hint\n this.extra = extra\n }\n}\n\nexport interface Failure {\n code: FailureCode\n exit: ExitCode\n message: string\n hint?: string\n extra?: Record<string, unknown>\n}\n\n/**\n * One place that decides what an error means, so the JSON body and the exit\n * code cannot disagree — they are read off the same object.\n *\n * **On 401 → `not_authenticated`, not `refused`.** The issue lists 401\n * alongside 403/410 under \"refused by the backend\", and separately lists\n * \"not logged in / session expired\" — the two overlap, and a 401 is exactly\n * the second one. An agent seeing `not_authenticated` knows to re-run\n * `haven login`; `refused` tells it the opposite (the session is fine, the\n * action is not allowed). Splitting them on the wire is the whole point of\n * having two codes, so 401 resolves to the one it can act on.\n */\nexport function toFailure(err: unknown): Failure {\n if (err instanceof UsageError) {\n return { code: 'usage', exit: EXIT.usage, message: err.message, hint: err.hint }\n }\n if (err instanceof HavenCliError) {\n // The error already decided; this only translates the number to its slug,\n // so the JSON body and the exit code still come off one object.\n const code: FailureCode =\n err.exit === EXIT.notAuthenticated\n ? 'not_authenticated'\n : err.exit === EXIT.refused\n ? 'refused'\n : err.exit === EXIT.network\n ? 'network'\n : 'failed'\n return { code, exit: err.exit, message: err.message, hint: err.hint, extra: err.extra }\n }\n if (err instanceof CliApiError) {\n if (err.status === 0) {\n return {\n code: 'network',\n exit: EXIT.network,\n message: err.message,\n hint: 'Check the network and `--api`, then retry.',\n }\n }\n if (err.status === 401) {\n return {\n code: 'not_authenticated',\n exit: EXIT.notAuthenticated,\n message: err.message,\n // #2618: the device flow is named FIRST because it is the path an\n // agent can actually run — an agent never holds its user's password,\n // which is the runbook's first rule; the previous hint led with the\n // credentials as if they were the normal route. HAVEN_EMAIL and\n // HAVEN_PASSWORD remain for a HUMAN scripting non-interactively.\n hint: 'Run `haven login` (device flow — 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.',\n }\n }\n if (err.status >= 400 && err.status < 500) {\n // 403 and 410 are the named cases; every other 4xx is the same shape of\n // answer — the backend understood and said no — so it gets the same code\n // rather than falling through to the generic one.\n return { code: 'refused', exit: EXIT.refused, message: err.message }\n }\n return { code: 'failed', exit: EXIT.failed, message: err.message }\n }\n return { code: 'failed', exit: EXIT.failed, message: err instanceof Error ? err.message : String(err) }\n}\n","import type { Failure } from './errors.js'\n\n/**\n * The `--json` contract (#2525).\n *\n * Under `--json`, **stdout carries exactly one JSON value and nothing else** —\n * every line of human prose goes to stderr instead. That is what lets an agent\n * pipe stdout straight into a parser without stripping progress chatter, and\n * it is why `note()` exists: the same call site prints a sentence for a human\n * and stays silent (on stdout) for a machine.\n *\n * Success keeps the payload shape each command already emitted — including the\n * bare arrays that `agents list` and friends return — so this change adds a\n * failure contract without breaking a script that already parses a success.\n * Failures are always the object `{ ok: false, error: { code, message, hint? } }`.\n */\nexport interface Output {\n readonly json: boolean\n /** The command's success payload. At most one per run, on stdout. */\n data(payload: unknown, human: () => string): void\n /** Raw text (an export file). Printed as-is; wrapped under `--json`. */\n text(content: string, meta: Record<string, unknown>): void\n /** Human prose. Stdout in prose mode; stderr under `--json`. */\n note(line: string): void\n /** The one failure object. Always stdout under `--json`, stderr otherwise. */\n failure(failure: Failure): void\n}\n\nexport function createOutput(\n json: boolean,\n out: (line: string) => void,\n err: (line: string) => void,\n): Output {\n return {\n json,\n data(payload, human) {\n out(json ? JSON.stringify(payload, null, 2) : human())\n },\n text(content, meta) {\n // A CSV/SIE body is the payload in prose mode. Under --json it becomes a\n // field of the single object, so the contract (\"one JSON value on\n // stdout\") holds for exports too and the content stays recoverable.\n out(json ? JSON.stringify({ ok: true, ...meta, content }, null, 2) : content)\n },\n note(line) {\n if (json) err(line)\n else out(line)\n },\n failure(failure) {\n const body = {\n ok: false as const,\n error: {\n // `extra` spreads FIRST (#3597 round 2, N-a): it is per-command\n // (e.g. the secret check's `layer`/`reason`), so it must never be\n // able to clobber the contract fields every command shares —\n // `code`, `message`, `hint` are spread AFTER and always win.\n ...(failure.extra ?? {}),\n code: failure.code,\n message: failure.message,\n ...(failure.hint ? { hint: failure.hint } : {}),\n },\n }\n if (json) out(JSON.stringify(body, null, 2))\n else err(failure.hint ? `${failure.message}\\n${failure.hint}` : failure.message)\n },\n }\n}\n","/**\n * The agent onboarding runbook — GENERATED, do not edit by hand.\n *\n * Canonical source: `packages/sdk/src/agent-guidance.ts` (#2523), served to\n * agents at `/for-agents.md`. This is a decoupled copy so `@haven_ai/cli`\n * keeps zero runtime dependencies: importing it from the SDK would put ethers,\n * viem and x402 on the `npx @haven_ai/cli` path for one Markdown string.\n * Same arrangement, and the same reason, as\n * `packages/frontend/src/lib/agent-skill-bundle.ts`.\n *\n * Regenerate: node packages/cli/scripts/sync-agent-guidance.mjs\n * The parity test in `agent-guidance-text.test.ts` fails if you forget.\n */\n\nexport const HAVEN_AGENT_RUNBOOK_MD = \"# Haven for agents — 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** — 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 — 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 — 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, `<packages.cli.one_liner> login --api <api-url>` afterwards gets you a scoped session for steps 3-4 (that flag or `HAVEN_API_URL`, on the first command — 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) — they approve a code in the browser, you never hold their password. That command is the manifest's `packages.cli.one_liner` (`/.well-known/haven.json`) — run it as given: `packages.cli.channel` serves the full spec. 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>` — 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 — fund it.** USDC only, no ETH: Haven sponsors the gas. `/.well-known/haven.json` names `chains.default` as the deployment's expected chain, but after login `haven wallets funding` prints the address, the amount and which chain in one place; confirm that chain before you message your user. Without a CLI session, the dashboard's funding card shows the address and amount and its Receive-funds screen names the chain; never assume one: a testnet deployment and production both call themselves Haven. Before you write that message, read the manifest: `environment` says whether this deployment is `production`, and each `chains.supported` entry says whether that chain is a `testnet`. Real money is at stake only on a non-testnet chain of a `production` deployment — tell your user which case theirs is.\\n3. **HUMAN — 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 — run the connector command** in that prompt (see What you run). It makes your signing key locally, registering only the public address.\\n5. **HUMAN — 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 — verify, then pay.**\\n\\n## Budget changes later (second token, raise, revoke)\\n\\nThe first budget rides the setup in The sequence. After the agent exists, a CLI session can construct the LATER changes — a second token, a bigger amount, a recipient pin, a stop — 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 budget show <agentId> --hashes`.\\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` — 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 — 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 — USDC only, no ETH: Haven sponsors the gas. Before you send anything, let me get you the exact address **and network** — `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 — 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) — 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 — 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 — 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 — if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget — 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 — the approval link if those steps printed one, otherwise that you need to return to Haven and approve this agent's budget — 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 three changes to the command above are permitted, and no others: appending --json; re-running it once with --runtime <name> added, only if the connector refuses because it could not determine the agent runtime, naming the harness you are running in and using one of the values that refusal lists; and re-running it once with the one flag I chose added, only after I have answered a wiring_collision relay — --name <the suggested_name or a name I gave> to add alongside, or --replace to replace — keeping any change already made. If that re-run is refused too, relay the refusal to me and stop. 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 — 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 — 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` — a budget is live: you have the authority to pay. It does not say the account holds funds — the `allowances[]` rows carry `funds_cover_remaining`, and `false` there is a heads-up to mention to your user, not a refusal.\\n- `needs_approval` — the connector finished, nobody approved yet. Ask your user again, in their Haven tab; there is no queue to wait in.\\n- `revoked` — 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 — a separate command, so the command-modification rule does not bind it.\\n\\n## If you cannot open a browser\\n\\nNothing here needs you to. Steps 1-3 — account, funding, budget — are links: hand your user the full `<host>/…` URL and ask them to say when it is done. Step 5 is a link only when your run reported one in `approval.url` — otherwise it is the tab they already have open. Then poll `haven_get_agent` until it reads `ready`. Do not route around the sign-in wall — it makes the account theirs, not yours.\\n\\n## If something breaks\\n\\nIf a Haven result carries `client_update`, that client is out of date: run its `upgrade_command` exactly as given — a connector command may name your pair with `--name <slug>` — then any repair line it prints, then retry. `required: true` means payments are refused until you do. What changed: [/releases](/releases).\\n\\nSomething else wrong? `haven feedback submit \\\"<text>\\\"` sends it to Haven — it needs `haven login` first. Never put a credential in that text: no API key, no delegate key, no session token, no recovery phrase.\\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@…` line you run. One-time token, one use. |\\n| **agent credential** | Your API key (`sk_agent_…`), 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) · [everything agent-readable](/llms.txt)\\n\"\n","/**\n * Read the expiry out of the stored session JWT (#2525).\n *\n * `whoami --json` and `login --json` report when the session dies, and the\n * only place that fact exists is the token's own `exp` claim — the backend\n * signs it with `expiresIn: '7d'` (`routes/auth.ts`) and `/auth/me` does not\n * return it. So the payload segment is base64url-decoded and read.\n *\n * This deliberately does NOT verify the signature, and must never be used to\n * decide anything but what to print: the CLI has no key to verify with, and a\n * forged `exp` would only mislead the user about a token the backend will\n * reject on its own terms. It never logs, echoes or returns the token itself.\n */\nexport function sessionExpiry(token: string): string | null {\n const segment = token.split('.')[1]\n if (!segment) return null\n try {\n const json = Buffer.from(segment.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')\n const claims = JSON.parse(json) as { exp?: unknown }\n if (typeof claims.exp !== 'number' || !Number.isFinite(claims.exp)) return null\n return new Date(claims.exp * 1000).toISOString()\n } catch {\n // A token we cannot read is not an error worth failing a command over —\n // the expiry is informational, and every other field still resolves.\n return null\n }\n}\n","/**\n * Human token amounts → atomic units, without a dependency (#2527).\n *\n * ## Why this exists rather than `parseUnits`\n *\n * The dashboard modal converts with viem's `parseUnits` before it POSTs\n * (`useAgentConnectionSetup.ts`), and this CLI has to produce the same string\n * for the same input. It cannot call the same function: `@haven_ai/cli` ships\n * with **zero runtime dependencies** — asserted by a test, because `npx\n * @haven_ai/cli` is the path an agent uses and viem's tree is ~94 MB — so this\n * is the arithmetic done in strings over Node builtins.\n *\n * ## The two shapes, and why this direction is the dangerous one\n *\n * `allowance_amount` is ATOMIC on the way in and HUMAN-DECIMAL on the way back\n * (#2295). One name, two shapes. Nothing here sniffs which it is holding: the\n * caller says, and this function only ever converts human → atomic. A number\n * that is wrong by 10^6 is a budget that is wrong by a factor of a million.\n *\n * ## Excess precision is REFUSED, never rounded\n *\n * `parseUnits` ROUNDS the excess rather than dropping it, which is worse than\n * it sounds: measured against viem, `parseUnits('1.9999999', 6)` is `2000000n`\n * — **two whole tokens** — and `parseUnits('0.0000005', 6)` is `1n`, a budget\n * conjured out of a value below the token's precision. An earlier version of\n * this comment said it truncates to `1999999n`; that was wrong, and the truth\n * is the stronger argument for refusing (haven-reviewer, #2527).\n *\n * For a field a person typed and is about to authorise, quietly changing the\n * number is worse than declining it, so this mirrors the modal's own\n * `validateMoneyInput`, which refuses before it ever reaches `parseUnits`. The\n * rule is the same on both surfaces on purpose: a budget the dashboard would\n * not accept must not become acceptable by being typed into a terminal.\n */\n\nexport interface AmountResult {\n ok: true\n /** The normalised human string, e.g. `.5` → `0.5`. */\n human: string\n /** Atomic units as a decimal string — what the wire wants. */\n atomic: string\n}\n\nexport interface AmountRefusal {\n ok: false\n message: string\n}\n\nfunction decimalLabel(decimals: number): string {\n return decimals === 1 ? '1 decimal place' : `${decimals} decimal places`\n}\n\n/**\n * Convert a human amount to atomic units for a token with `decimals`.\n *\n * Refuses rather than guesses: anything that is not a plain non-negative\n * decimal, anything that is zero, and anything carrying more fraction digits\n * than the token can represent.\n */\nexport function parseTokenAmount(\n input: string,\n decimals: number,\n tokenSymbol?: string,\n): AmountResult | AmountRefusal {\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 36) {\n return { ok: false, message: `Unusable token decimals: ${String(decimals)}` }\n }\n\n // `.5` → `0.5`, matching the modal's `normalizeMoneyInput` so the two\n // surfaces accept the same set of strings.\n const trimmed = String(input ?? '').trim()\n const human = trimmed.startsWith('.') ? `0${trimmed}` : trimmed\n const label = tokenSymbol ? ` ${tokenSymbol}` : ''\n\n if (human === '') return { ok: false, message: 'Enter an amount greater than 0' }\n // No sign, no exponent, no separators. `1e6` and `1_000` are the shapes most\n // likely to be meant well and read wrong, so they are refused by omission.\n if (!/^\\d+(?:\\.\\d+)?$/.test(human)) {\n return { ok: false, message: `Enter a valid${label} amount — digits, with an optional decimal point` }\n }\n\n const [whole, fraction = ''] = human.split('.')\n if (fraction.length > decimals) {\n return {\n ok: false,\n message: `${tokenSymbol ?? 'This token'} supports up to ${decimalLabel(decimals)}`,\n }\n }\n\n // Right-pad the fraction to the token's precision and concatenate: the whole\n // conversion, with no float anywhere near it. BigInt then strips leading\n // zeros, so `0.5` at 6 decimals is `500000` rather than `0500000`.\n const atomic = BigInt(`${whole}${fraction.padEnd(decimals, '0')}`)\n if (atomic === 0n) return { ok: false, message: 'Enter an amount greater than 0' }\n\n return { ok: true, human, atomic: atomic.toString() }\n}\n","import { spawn } from 'node:child_process'\n\n/**\n * Running the connector as a child process, for `haven agents connect --run`\n * (#2527).\n *\n * ## The command is not ours to edit\n *\n * The backend builds `connector_command` and the setup prompt states the rule\n * an agent must follow: the command may be changed in only the ways it\n * lists, and appending `--json` is one of them. So this splits the printed command and\n * appends `--json` — nothing else. It does not add `--replace`, it does not add\n * `--name`, it does not rewrite `--api`, and it never composes a command of its\n * own. `haven agents connect` has no flags for those on purpose: a wiring\n * collision is a decision for the human, and a CLI that could resolve one would\n * be making that decision on their behalf (boundary note on #2527 from #2551).\n *\n * ## Why the exit code is not the verdict\n *\n * The connector exits **1** on a refusal while still writing a complete outcome\n * object to stdout (`cli.test.ts`, the `wiring_collision` case). Treating a\n * non-zero exit as \"it did not run\" would throw away exactly the structured\n * refusal the human needs. So the outcome is parsed from stdout whatever the\n * exit code was, and the exit code only decides what to do when there is no\n * parseable outcome at all.\n *\n * ## Refusals are recognised structurally, never by name\n *\n * A refusal is \"the outcome carries an `error`\". The relay text comes from\n * `error.next_action`. Nothing here enumerates `runtime_undetermined` or\n * `wiring_collision`, so a refusal added to the connector tomorrow reaches the\n * user through this path without a CLI change — which is the whole point of\n * the connector having a typed vocabulary in the first place.\n */\n\n/** The connector's `--json` outcome. Only the fields this CLI reads. */\nexport interface ConnectorOutcome {\n schema_version?: number\n outcome?: 'complete' | 'action_required' | 'failed' | string\n next_action?: string\n approval?: { required?: boolean; expires_at?: string | null; url?: string }\n error?: {\n code?: string\n next_action?: string\n message?: string\n allowed_runtimes?: readonly string[]\n installed_clients?: readonly string[]\n suggested_runtime?: string\n superseded_agent_ids?: readonly string[]\n suggested_name?: string\n }\n [key: string]: unknown\n}\n\nexport interface ConnectorRun {\n /** The parsed outcome, when the connector produced one. */\n outcome: ConnectorOutcome | null\n exitCode: number\n /** Everything the connector wrote to stderr, already streamed to ours. */\n stderr: string\n /** stdout that was not the outcome object — kept so a failure can say why. */\n stdoutNoise: string\n}\n\nexport interface Spawner {\n (command: string, args: string[], onStderr: (chunk: string) => void): Promise<{\n stdout: string\n stderr: string\n exitCode: number\n }>\n}\n\n/**\n * Split a printed connector command into argv.\n *\n * The backend shell-quotes the setup token and the API url with single quotes\n * (`buildConnectorCommand`), so this understands single quotes and nothing\n * else. It is deliberately not a shell: no globbing, no variable expansion, no\n * `&&`. A command carrying anything this cannot represent is refused rather\n * than approximated, because the alternative is executing a rewritten version\n * of a command whose whole contract is that it is not rewritten.\n */\nexport function splitConnectorCommand(command: string): string[] {\n const argv: string[] = []\n let current = ''\n let quoted = false\n let started = false\n\n for (let i = 0; i < command.length; i += 1) {\n const ch = command[i]\n if (quoted) {\n if (ch === \"'\") quoted = false\n else current += ch\n continue\n }\n if (ch === \"'\") {\n quoted = true\n started = true\n continue\n }\n if (ch === ' ' || ch === '\\t') {\n if (started) argv.push(current)\n current = ''\n started = false\n continue\n }\n // The ONE backslash form this understands: POSIX `'\\''`, which is how the\n // backend's `shellQuote` escapes a single quote inside a quoted value\n // (`'a'\\''b'` means `a'b`). Supported because the builder can emit it, and\n // a command the builder can produce but `--run` cannot execute is a broken\n // contract rather than a safe refusal. Every OTHER backslash is still\n // refused — this is a parser for one known quoting function, not a shell.\n if (ch === '\\\\') {\n if (command[i + 1] === \"'\") {\n current += \"'\"\n started = true\n i += 1\n continue\n }\n throw new Error('Refusing to run a connector command with a backslash escape')\n }\n if (ch === '\"' || ch === '`' || ch === '$' || ch === '|' || ch === '&' || ch === ';' ||\n ch === '>' || ch === '<' || ch === '(' || ch === ')' || ch === '\\n') {\n throw new Error(`Refusing to run a connector command containing ${JSON.stringify(ch)}`)\n }\n current += ch\n started = true\n }\n if (quoted) throw new Error('Refusing to run a connector command with an unterminated quote')\n if (started) argv.push(current)\n if (argv.length === 0) throw new Error('The backend returned an empty connector command')\n return argv\n}\n\n/** The real spawner. Injected in tests so no child process runs there. */\nexport const nodeSpawner: Spawner = (command, args, onStderr) =>\n new Promise((resolve, reject) => {\n // `shell: false` is the point: argv goes to the process as-is, so nothing\n // in a token or url can be read as shell syntax.\n const child = spawn(command, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] })\n let stdout = ''\n let stderr = ''\n child.stdout.setEncoding('utf8')\n child.stderr.setEncoding('utf8')\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk\n })\n child.stderr.on('data', (chunk: string) => {\n stderr += chunk\n // Streamed rather than buffered to the end: a connector run can take\n // minutes, and its stderr is the only progress a human sees.\n onStderr(chunk)\n })\n child.on('error', reject)\n child.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? 1 }))\n })\n\n/**\n * Find the connector's outcome object in its stdout.\n *\n * The contract is one JSON object on stdout under `--json`. This assumes none\n * of the things that contract does not actually say: not that the object is\n * the whole stream (a package manager on the `npx` path writes its own lines),\n * not that it is on one line (a pretty-printed object), and not that it is\n * alone on its line (`npm notice {...}`). Each of those assumptions turned a\n * real refusal into \"no outcome\" in an earlier version. The LAST balanced\n * object wins.\n */\nexport function parseOutcome(stdout: string): { outcome: ConnectorOutcome | null; noise: string } {\n const noise: string[] = []\n let outcome: ConnectorOutcome | null = null\n\n // A scanner over the WHOLE stream, not over lines. Two assumptions died\n // here, both of them unstated until a reviewer looked: that the object is on\n // one line (a pretty-printed refusal was swallowed), and that the object is\n // ALONE on its line (`npm notice {...}` or a trailing word dropped it the\n // same way). Both regressed a real refusal to \"the connector produced no\n // outcome\", losing the exit code and the `next_action` a caller branches on.\n // Anything outside a balanced object is noise; the LAST balanced object\n // wins, so a stray object from a package manager cannot displace the\n // outcome.\n let depth = 0\n let start = -1\n let inString = false\n let escaped = false\n let plain = ''\n\n for (let i = 0; i < stdout.length; i += 1) {\n const ch = stdout[i]\n\n if (depth === 0) {\n if (ch === '{') {\n depth = 1\n start = i\n inString = false\n escaped = false\n } else {\n plain += ch\n }\n continue\n }\n\n if (inString) {\n if (escaped) escaped = false\n else if (ch === '\\\\') escaped = true\n else if (ch === '\"') inString = false\n continue\n }\n if (ch === '\"') inString = true\n else if (ch === '{') depth += 1\n else if (ch === '}') {\n depth -= 1\n if (depth === 0) {\n const candidate = stdout.slice(start, i + 1)\n try {\n // No `Array.isArray` check here, deliberately. A candidate always\n // starts at `{`, so `JSON.parse` can only return an object — the\n // anchor IS the guarantee. An earlier version carried the array\n // check as well and a mutation removing it passed the whole suite,\n // because it was unreachable: a guard nothing can violate reads like\n // protection while proving nothing, which is the shape this file has\n // already been wrong about once.\n outcome = JSON.parse(candidate) as ConnectorOutcome\n } catch {\n plain += candidate\n }\n start = -1\n }\n }\n }\n\n // An object that never closed is not an outcome; keep it readable rather\n // than dropping it, so a truncated stream still says something.\n if (depth > 0 && start >= 0) plain += stdout.slice(start)\n\n for (const line of plain.split('\\n')) {\n const text = line.trim()\n if (text) noise.push(text)\n }\n return { outcome, noise: noise.join('\\n') }\n}\n\n/** Is this outcome a refusal the human has to act on? */\nexport function isRefusal(outcome: ConnectorOutcome | null): boolean {\n return Boolean(outcome?.error)\n}\n\n/**\n * The one line that goes first (#2483's one-gate rule).\n *\n * An approval that is waiting outranks everything else on screen, and a\n * refusal outranks a completed run. The text is built from what the connector\n * said rather than from a table of codes here.\n */\nexport function relayLine(outcome: ConnectorOutcome | null): string | null {\n if (!outcome) return null\n if (outcome.error) {\n const message = outcome.error.message?.trim()\n const next = outcome.error.next_action ?? outcome.next_action\n // The message is the connector's own prose and is what a human reads; the\n // next action is what an agent branches on. Both, in that order.\n return message\n ? `${message}${next ? ` (next: ${next})` : ''}`\n : `The connector refused${next ? `: ${next}` : '.'}`\n }\n if (outcome.approval?.required) {\n return outcome.approval.url\n ? `Approve the budget to finish: ${outcome.approval.url}`\n : 'Approve the budget in your Haven tab to finish.'\n }\n return null\n}\n\n/**\n * Run the connector command, appending `--json` and nothing else.\n */\nexport async function runConnector(\n connectorCommand: string,\n spawner: Spawner,\n onStderr: (chunk: string) => void,\n): Promise<ConnectorRun> {\n const argv = splitConnectorCommand(connectorCommand)\n // Appended, never inserted: the rule is \"exactly `--json` appended\", and a\n // flag placed anywhere else is a different command line.\n const args = [...argv.slice(1), '--json']\n const { stdout, stderr, exitCode } = await spawner(argv[0], args, onStderr)\n const { outcome, noise } = parseOutcome(stdout)\n return { outcome, exitCode, stderr, stdoutNoise: noise }\n}\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++) B[x] = s[y + x];\n for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n\n/** Keccak sponge function. */\nexport class Keccak extends Hash<Keccak> implements HashXOF<Keccak> {\n protected state: Uint8Array;\n protected pos = 0;\n protected posOut = 0;\n protected finished = false;\n protected state32: Uint32Array;\n protected destroyed = false;\n\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen) this.keccak();\n }\n return this;\n }\n protected finish(): void {\n if (this.finished) return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n protected writeInto(out: Uint8Array): Uint8Array {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len; ) {\n if (this.posOut >= blockLen) this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out: Uint8Array): Uint8Array {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes: number): Uint8Array {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array): Uint8Array {\n aoutput(out, this);\n if (this.finished) throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to?: Keccak): Keccak {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\n\nconst gen = (suffix: number, blockLen: number, outputLen: number) =>\n createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer<HashXOF<Keccak>, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n","export const wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n","/**\n * The secret check `haven feedback submit` runs before any request carrying\n * the text is sent (#3597, owner decision 2026-10-02).\n *\n * A raw private key and a transaction/delegation/schema hash share one shape\n * — 64 hex characters, with or without `0x` — so shape alone cannot decide.\n * The check asks what a string would DO. Every layer below runs locally\n * first; layer 3's network reads fetch this user's own addresses to compare\n * against, and never carry the submitted text itself.\n *\n * **Zero runtime dependencies stays true at the `dependencies` field.**\n * `@noble/hashes` (Keccak-256 — `node:crypto` has secp256k1 but not that) and\n * `@scure/bip39` (the English wordlist) are devDependencies, bundled by tsup\n * into `dist/*` (see `agent-guidance-text.test.ts`'s sibling guard, and the\n * CLI README's zero-deps note). This file must never import\n * `@haven_ai/connect` — that package pulls in ethers, which is exactly the\n * install-weight problem the zero-deps rule exists to avoid, and it is also\n * simply unnecessary: the credential files this reads are plain JSON.\n */\nimport { readFile, readdir } from 'node:fs/promises'\nimport { createECDH } from 'node:crypto'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { keccak_256 } from '@noble/hashes/sha3'\nimport { wordlist as BIP39_ENGLISH } from '@scure/bip39/wordlists/english'\nimport { CliApiError, type CliApi } from './api.js'\n\n/** Mirrors the backend's own cap (`routes/feedback.ts`'s `MAX_FEEDBACK_TEXT_LENGTH`). */\nexport const MAX_FEEDBACK_TEXT_LENGTH = 4000\n\nexport type SecretCheckReason =\n | 'agent_api_key'\n | 'setup_token'\n | 'session_jwt'\n | 'labelled_parameter'\n | 'url_credentials'\n | 'rpc_path_key'\n | 'local_credential'\n | 'private_key'\n | 'address_check_unavailable'\n | 'recovery_phrase'\n\nexport interface SecretCheckRefusal {\n layer: 1 | 2 | 3 | 4\n reason: SecretCheckReason\n /** Human-readable; never includes the refused text itself. */\n message: string\n}\n\nfunction refusal(layer: SecretCheckRefusal['layer'], reason: SecretCheckReason, message: string): SecretCheckRefusal {\n return { layer, reason, message }\n}\n\n// ── Layer 1 — prefixed and labelled secrets ─────────────────────────\n//\n// A superset of `redactVendorSecrets` (`packages/backend/src/domain/redact-vendor-secrets.ts`)\n// — the backend re-runs the identical list server-side\n// (`packages/backend/src/modules/feedback/secret-check.ts`), so stored text\n// can never trip the ops grant script's vendor-secret refusal.\n// No false positives: every pattern here is a label or a prefix, never a bare\n// shape (a bare 64-hex token is layer 3).\n\nconst LABELLED_PATTERNS: ReadonlyArray<{ reason: SecretCheckReason; re: RegExp }> = [\n { reason: 'agent_api_key', re: /sk_agent_[A-Za-z0-9]/ },\n { reason: 'setup_token', re: /hv_setup_[A-Za-z0-9]/ },\n // A session JWT: three dot-separated base64url parts, each non-empty.\n // `\\beyJ` (not the looser `\\bey`), which is the base64url encoding of `{\"`\n // — every real JWT header starts there, and the tighter anchor stops\n // ordinary words like \"eyebrow\" or \"eyelet\" from matching their own tail.\n { reason: 'session_jwt', re: /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/ },\n // key= / api_key= / api-key= / apikey= / token= / secret=, `\\b`-bounded —\n // the same boundary `redact-vendor-secrets.ts:19` uses.\n { reason: 'labelled_parameter', re: /\\b(api[_-]?key|key|token|secret)=[^&\\s\"'\\\\)]+/i },\n { reason: 'url_credentials', re: /https?:\\/\\/[^\\s/@]+:[^\\s@]+@/i },\n { reason: 'rpc_path_key', re: /\\/(?:rpc|v2)\\/[A-Za-z0-9_-]{16,}/ },\n]\n\nexport function checkLabelledSecrets(text: string): SecretCheckRefusal | null {\n for (const { reason, re } of LABELLED_PATTERNS) {\n if (re.test(text)) {\n return refusal(\n 1,\n reason,\n 'Refusing to send: the text looks like it contains a secret (a credential label or prefix matched). Remove it and try again.',\n )\n }\n }\n return null\n}\n\n// ── Layer 2 — secrets this machine holds, exact match ───────────────\n//\n// Read with `node:fs` only — never `@haven_ai/connect`. Case-insensitive,\n// `0x`-normalised, never printed. A custom `--credentials-dir` cannot be\n// discovered; that is accepted residual risk (the issue's own words).\n\nexport interface LocalSecretSources {\n /** Overrides `~/.haven/agents` — tests only. */\n baseDir?: string\n env?: NodeJS.ProcessEnv\n /** This CLI's own `~/.haven/session.json` token, passed in by the caller. */\n sessionToken?: string\n}\n\nfunction normalize(value: string): string {\n return value.trim().toLowerCase().replace(/^0x/, '')\n}\n\nasync function readJsonStringField(path: string, field: string): Promise<string | null> {\n try {\n const raw = await readFile(path, 'utf8')\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const value = parsed[field]\n return typeof value === 'string' && value.length > 0 ? value : null\n } catch {\n return null\n }\n}\n\n/**\n * Every local secret source the issue names:\n * `~/.haven/agents/<slug>/signer.json` (`delegate_key`), `identity.json`\n * (`api_key`), `rekey-pending.json` (`new_delegate_key`) — including\n * TOMBSTONED directories, which keep their keys and are deliberately NOT\n * skipped here (unlike agent discovery for a `--rekey` target) — the\n * `HAVEN_DELEGATE_KEY` env var, and this CLI's own session token.\n */\nexport async function readLocalSecrets(sources: LocalSecretSources = {}): Promise<Set<string>> {\n const secrets = new Set<string>()\n const env = sources.env ?? process.env\n const envKey = env.HAVEN_DELEGATE_KEY\n if (envKey) secrets.add(normalize(envKey))\n if (sources.sessionToken) secrets.add(normalize(sources.sessionToken))\n\n const root = sources.baseDir ?? join(homedir(), '.haven', 'agents')\n let entries: string[] = []\n try {\n entries = await readdir(root)\n } catch {\n return secrets\n }\n\n for (const entry of entries) {\n const dir = join(root, entry)\n const delegateKey = await readJsonStringField(join(dir, 'signer.json'), 'delegate_key')\n if (delegateKey) secrets.add(normalize(delegateKey))\n const apiKey = await readJsonStringField(join(dir, 'identity.json'), 'api_key')\n if (apiKey) secrets.add(normalize(apiKey))\n const pendingKey = await readJsonStringField(join(dir, 'rekey-pending.json'), 'new_delegate_key')\n if (pendingKey) secrets.add(normalize(pendingKey))\n }\n return secrets\n}\n\nexport function checkExactSecretMatch(text: string, secrets: ReadonlySet<string>): SecretCheckRefusal | null {\n if (secrets.size === 0) return null\n const haystack = text.toLowerCase()\n for (const secret of secrets) {\n // A short needle risks matching unrelated text; every real secret here\n // (a key, an API key, a session token) is far longer than this.\n if (secret.length >= 8 && haystack.includes(secret)) {\n return refusal(\n 2,\n 'local_credential',\n 'Refusing to send: the text contains a credential this machine holds (an agent delegate key, an agent API key, a pending re-key, or your own session token). Remove it and try again.',\n )\n }\n }\n return null\n}\n\n// ── Layer 3 — any other 64-hex token: derive and compare ────────────\n\n/**\n * A token is exactly 64 hex characters, optional `0x`, bounded by a\n * non-hex character on both sides — so a 128-hex calldata run yields ZERO\n * candidates rather than being windowed into two.\n */\nexport function findHexTokenCandidates(text: string): string[] {\n const matches = text.matchAll(/(?<![0-9a-fA-F])(0x)?([0-9a-fA-F]{64})(?![0-9a-fA-F])/g)\n return [...matches].map((m) => m[2])\n}\n\n/**\n * Treat a 64-hex token as a secp256k1 private key and derive its Ethereum\n * address, or `null` when it is not a valid key — a zero key or a key ≥ the\n * curve order `n` makes `createECDH.setPrivateKey` throw, and that token\n * simply passes (most real tokens here are hashes, not keys).\n */\nexport function deriveAddressFromHexToken(token: string): string | null {\n try {\n const ecdh = createECDH('secp256k1')\n ecdh.setPrivateKey(Buffer.from(token, 'hex'))\n const uncompressed = ecdh.getPublicKey() // 65 bytes, 0x04 prefix\n const hash = keccak_256(uncompressed.subarray(1))\n return `0x${Buffer.from(hash.subarray(12)).toString('hex')}`\n } catch {\n return null\n }\n}\n\ninterface AgentsResponse {\n agents: Array<{ delegate_address?: string }>\n}\ninterface AccountsResponse {\n accounts: Array<{ account_address?: string; chain_id: number }>\n}\ninterface HybridAccountSignersResponse {\n owner_address: string | null\n}\n\n/**\n * This user's key-backed addresses: every agent's `delegate_address` (from\n * `GET /agents`) and every account's `owner_address` (from\n * `GET /accounts/hybrid/{address}/signers?chain_id=`, one call per account\n * per chain). Smart-account addresses (CREATE2, no private key) and\n * passkeys (P-256) can never match a derived secp256k1 address, so they are\n * not in the set.\n */\nexport async function collectKeyBackedAddresses(api: CliApi): Promise<Set<string>> {\n const addresses = new Set<string>()\n const { agents } = await api.get<AgentsResponse>('/agents')\n for (const agent of agents) {\n if (agent.delegate_address) addresses.add(agent.delegate_address.toLowerCase())\n }\n const { accounts } = await api.get<AccountsResponse>('/user/accounts')\n for (const account of accounts) {\n if (!account.account_address) continue\n const signers = await api.get<HybridAccountSignersResponse>(\n `/accounts/hybrid/${account.account_address}/signers?chain_id=${account.chain_id}`,\n )\n if (signers.owner_address) addresses.add(signers.owner_address.toLowerCase())\n }\n return addresses\n}\n\n/**\n * The address reads happen ONLY when at least one 64-hex candidate exists.\n * If a read fails, this fails CLOSED — refuses to send, with a message that\n * fits what actually failed. A transient/network failure gets a retry hint;\n * a 401/403 (the session cannot read this — the owner-cli allow-list refused\n * it, or the session itself is bad) or a 409 (the account's signer\n * configuration is unknown — nothing to compare against) are NOT fixed by\n * retrying the same call, so each gets its own distinct wording rather than\n * a reachability hint that would just repeat.\n */\nexport async function checkKeyBackedAddresses(text: string, api: CliApi): Promise<SecretCheckRefusal | null> {\n const candidates = findHexTokenCandidates(text)\n if (candidates.length === 0) return null\n\n let keyBacked: Set<string>\n try {\n keyBacked = await collectKeyBackedAddresses(api)\n } catch (err) {\n if (err instanceof CliApiError && (err.status === 401 || err.status === 403)) {\n return refusal(\n 3,\n 'address_check_unavailable',\n 'Refusing to send: could not verify whether the text contains a private key — your session cannot read the data this check needs. Run `haven login` again; retrying this submission will not help.',\n )\n }\n if (err instanceof CliApiError && err.status === 409) {\n return refusal(\n 3,\n 'address_check_unavailable',\n \"Refusing to send: could not verify whether the text contains a private key — one of your accounts' signer configuration is unknown, so there is nothing to compare against. Retrying this submission will not help; contact support.\",\n )\n }\n return refusal(\n 3,\n 'address_check_unavailable',\n 'Refusing to send: could not verify whether the text contains a private key (the address check failed). Retry once Haven is reachable.',\n )\n }\n\n for (const token of candidates) {\n const address = deriveAddressFromHexToken(token)\n if (address && keyBacked.has(address.toLowerCase())) {\n return refusal(\n 3,\n 'private_key',\n 'Refusing to send: the text contains what looks like the private key for one of your agents or accounts. Remove it and try again.',\n )\n }\n }\n return null\n}\n\n// ── Layer 4 — recovery phrases ───────────────────────────────────────\n\nconst BIP39_WORDS = new Set(BIP39_ENGLISH.map((word) => word.toLowerCase()))\n/** The shortest mnemonic BIP-39 mints. Any run at least this long contains one. */\nconst MIN_RECOVERY_PHRASE_WORDS = 12\n\n/**\n * A run of 12, 15, 18, 21 or 24 CONSECUTIVE BIP-39 English words. Checking\n * for a run of at least 12 is sufficient: a longer run CONTAINS a 12-word\n * run, which is itself refusable — there is no case where a longer run\n * should pass that a 12-word one would refuse.\n */\nexport function checkRecoveryPhrase(text: string): SecretCheckRefusal | null {\n const tokens = text.split(/\\s+/).map((t) => t.replace(/^[^A-Za-z]+|[^A-Za-z]+$/g, '').toLowerCase())\n let run = 0\n for (const token of tokens) {\n if (token && BIP39_WORDS.has(token)) {\n run += 1\n if (run >= MIN_RECOVERY_PHRASE_WORDS) {\n return refusal(\n 4,\n 'recovery_phrase',\n 'Refusing to send: the text looks like it contains a recovery phrase (12 or more consecutive seed words). Remove it and try again.',\n )\n }\n } else {\n run = 0\n }\n }\n return null\n}\n\n// ── Composition ───────────────────────────────────────────────────────\n\nexport interface SecretCheckDeps {\n api: CliApi\n localSecrets?: LocalSecretSources\n}\n\n/**\n * Run every layer, in order, and return the first refusal — or `null` when\n * the text may be sent. Every layer except 3's address reads is local; none\n * of them, including layer 3, ever transmits the text itself.\n */\nexport async function checkTextForSecrets(text: string, deps: SecretCheckDeps): Promise<SecretCheckRefusal | null> {\n const layer1 = checkLabelledSecrets(text)\n if (layer1) return layer1\n\n const localSecrets = await readLocalSecrets(deps.localSecrets)\n const layer2 = checkExactSecretMatch(text, localSecrets)\n if (layer2) return layer2\n\n const layer3 = await checkKeyBackedAddresses(text, deps.api)\n if (layer3) return layer3\n\n return checkRecoveryPhrase(text)\n}\n","import { parseArgs, helpText, type ParsedArgs } from './args.js'\nimport { createCliApi, CliApiError, type CliApi } from './api.js'\nimport { createSessionStore, type Session, type SessionStore } from './session.js'\nimport { chainName, table, timeAgo, truncateAddress } from './format.js'\nimport { toCsv } from './csv.js'\nimport { EXIT, HavenCliError, UsageError, toFailure, type ExitCode } from './errors.js'\nimport { createOutput, type Output } from './output.js'\nimport { HAVEN_AGENT_RUNBOOK_MD } from './agent-guidance-text.js'\nimport { sessionExpiry } from './token.js'\nimport { parseTokenAmount } from './amount.js'\nimport {\n isRefusal,\n nodeSpawner,\n relayLine,\n runConnector,\n type ConnectorOutcome,\n type Spawner,\n} from './connect-runner.js'\nimport { checkTextForSecrets, MAX_FEEDBACK_TEXT_LENGTH } from './secret-check.js'\n\n// Hosted Haven backend. Override with `--api <url>` or HAVEN_API_URL (e.g. a\n// local backend at http://localhost:3001, or your own domain once self-hosted).\nexport const DEFAULT_API = 'https://havenbackend-production-8a00.up.railway.app'\n// Self-reported CLI version. Owned by scripts/release-bump.mjs, which rewrites\n// the string literal below on every release — keep it a bare quoted literal.\nexport const CLI_VERSION = '0.0.0-dev.202610141909.1546aaa'\n\n/** #3303: the `X-Haven-Client` value every Haven API request from this CLI carries. */\nexport const CLI_CLIENT_IDENTITY = `@haven_ai/cli/${CLI_VERSION}`\n\nexport interface RunDeps {\n sessionStore?: SessionStore\n /** Build an API client; injected so tests can stub the backend. */\n makeApi?: (baseUrl: string, token?: string) => CliApi\n promptPassword?: () => Promise<string>\n /** #2526: injected so the device poll loop is testable without real time. */\n sleep?: (ms: number) => Promise<void>\n /** #2527: injected so `--run` is testable without spawning a real process. */\n spawner?: Spawner\n out?: (line: string) => void\n err?: (line: string) => void\n env?: NodeJS.ProcessEnv\n /**\n * #3597: overrides where `feedback submit`'s secret check (layer 2) looks\n * for local agent credentials. Tests only — production never sets it, so\n * the check reads the real `~/.haven/agents` the way the connect package's\n * own `defaultCredentialRoot` does, and tests that must not touch a\n * developer's real credentials pass a temp directory instead.\n */\n credentialsBaseDir?: string\n}\n\ninterface ResolvedDeps {\n sessionStore: SessionStore\n makeApi: (baseUrl: string, token?: string) => CliApi\n promptPassword: () => Promise<string>\n sleep: (ms: number) => Promise<void>\n spawner: Spawner\n out: (line: string) => void\n err: (line: string) => void\n env: NodeJS.ProcessEnv\n credentialsBaseDir?: string\n /** Set once `--json` is known; every command writes through it. */\n o: Output\n}\n\n/**\n * Every command this CLI dispatches, as data (#2525).\n *\n * The table-driven contract test in `json-contract.test.ts` iterates THIS list\n * and asserts each command's `--json` refusal is one JSON object on stdout, so\n * a command added to `dispatch` without adding it here is not covered. Its\n * ceiling, stated plainly: the test proves the listed commands honour the\n * contract, not that the list is complete. A drift test below pins the list\n * against `dispatch`'s own switch to close that gap by execution.\n */\nexport const COMMANDS = [\n 'login', 'logout', 'whoami', 'guide',\n 'wallets list', 'wallets balances', 'wallets rename', 'wallets funding',\n 'agents list', 'agents show', 'agents pause', 'agents resume', 'agents revoke',\n 'agents rotate-key', 'agents rename', 'agents connect',\n 'budget show', 'budget grant', 'budget revoke',\n 'activity list', 'activity export',\n 'catalog list',\n 'contacts list', 'contacts add', 'contacts remove',\n 'feedback submit',\n] as const\n\n// ── Backend response shapes (subset the CLI needs) ──────────────────\n/** A linked Haven account as `GET /user/accounts` lists it. */\ninterface Safe { id: string; account_address?: string; chain_id: number; name: string; is_default: boolean }\nfunction accountAddressOf(s: { account_address?: string | null }): string {\n return s.account_address ?? ''\n}\ninterface Allowance { token_symbol: string; allowance_amount: string; reset_period_min: number }\ninterface Agent {\n id: string\n name: string\n status: string\n allowances?: Allowance[]\n /** #3597: the spec's `Agent` schema always carries it; added here for the feedback secret check's layer 3. */\n delegate_address?: string\n /**\n * #3729: how many delegation rows are still live (pending, active or\n * replaced), computed server-side — the CLI gates the revoke on this rather\n * than keeping its own copy of the live set. Optional so an older backend\n * that predates the field reads as \"nothing live\" rather than crashing.\n */\n live_delegation_count?: number\n}\ninterface Balance { symbol: string; formatted: string; balance: string }\n/**\n * The additive balance-freshness marker from the wire (#3295), read by the\n * CLI since #3318. Present on a `GET /balances/:accountAddress` entry only\n * when that entry's on-chain read FAILED: `stale` = the served figure is the\n * last successfully read balance and `asOf` says when it was read;\n * `unavailable` = no balance has ever been read for this token, so the\n * accompanying balance string is a filler, not a figure. Absent on a clean\n * read — which is how the marker stays additive for every existing consumer.\n */\ninterface BalanceFreshness {\n status: 'stale' | 'unavailable'\n /** ISO 8601 — present exactly when `status` is `'stale'`. */\n asOf?: string\n}\ninterface BalanceToken {\n symbol: string\n address: string | null\n decimals: number\n balanceFreshness?: BalanceFreshness\n}\ninterface Txn {\n hash: string; direction: 'in' | 'out'; valueFormatted: string; asset: string\n source?: string; timestamp: number; accountName?: string\n from?: string; to?: string; isError?: boolean\n tokenSymbol?: string; tokenAddress?: string; chainId?: number; accountAddress?: string\n agentName?: string; paymentFlowStatus?: string | null; activityType?: string\n}\ninterface CatalogEntry { name: string; category: string; rail: string; price_display?: string | null; status: string }\ninterface Contact { id: string; name: string; address: string }\ninterface CreateSetupResponse {\n setup_id: string\n status: string\n approval_url: string\n expires_at: string\n connector_command: string\n connector_package: string\n setup_prompt: string\n}\ninterface SetupStatus {\n setup_id: string\n status: string\n agent_id: string | null\n approval_url: string\n expires_at: string\n}\n\n/** `GET /user/accounts/:id/funding` — the wire shape the route documents. */\ninterface FundingResponse {\n account_address: string\n chain: { id: number; name: string; explorer_url: string }\n tokens: {\n symbol: string\n address: string\n decimals: number\n balance_human: string\n minimum_useful_human: string | null\n }[]\n native: { symbol: string; balance_human: string; needed: boolean }\n funded: boolean\n faucet_url?: string\n}\n\n/** Entry point. Returns a process exit code; never throws for expected errors. */\nexport async function run(argv: string[], deps: RunDeps = {}): Promise<number> {\n const out = deps.out ?? ((l: string) => process.stdout.write(`${l}\\n`))\n const err = deps.err ?? ((l: string) => process.stderr.write(`${l}\\n`))\n\n // `--json` has to be known before anything can be emitted, including a parse\n // failure's own message. Scanning argv for the flag is deliberate: parseArgs\n // throws on a bad line, and a refusal that ignored --json because the parse\n // failed would break the contract exactly when a caller most needs it.\n const json = argv.includes('--json')\n const o = createOutput(json, out, err)\n\n const d: ResolvedDeps = {\n sessionStore: deps.sessionStore ?? createSessionStore(),\n makeApi: deps.makeApi ?? ((baseUrl, token) => createCliApi({ baseUrl, token, clientIdentity: CLI_CLIENT_IDENTITY })),\n promptPassword: deps.promptPassword ?? (() => Promise.reject(new Error('No password input available'))),\n sleep: deps.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))),\n spawner: deps.spawner ?? nodeSpawner,\n out,\n err,\n env: deps.env ?? process.env,\n credentialsBaseDir: deps.credentialsBaseDir,\n o,\n }\n\n let args: ParsedArgs\n try {\n args = parseArgs(argv)\n } catch (e) {\n return fail(d, new UsageError(e instanceof Error ? e.message : String(e), 'Run `haven --help`.'))\n }\n\n if (args.flags.version) {\n o.data({ version: CLI_VERSION }, () => CLI_VERSION)\n return EXIT.ok\n }\n if (args.flags.help || !args.command) {\n o.data({ help: helpText() }, () => helpText())\n return EXIT.ok\n }\n\n try {\n return await dispatch(args, d)\n } catch (e) {\n return fail(d, e)\n }\n}\n\n/** The single exit: one failure object, one exit code, read off one decision. */\nfunction fail(d: ResolvedDeps, err: unknown): ExitCode {\n const failure = toFailure(err)\n d.o.failure(failure)\n return failure.exit\n}\n\nasync function dispatch(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const key = args.sub ? `${args.command} ${args.sub}` : args.command\n switch (key) {\n case 'guide': return cmdGuide(args, d)\n case 'login': return cmdLogin(args, d)\n case 'logout': return cmdLogout(args, d)\n case 'whoami': return cmdWhoami(args, d)\n case 'wallets list': return cmdWalletsList(args, d)\n case 'wallets balances': return cmdWalletsBalances(args, d)\n case 'wallets funding': return cmdWalletsFunding(args, d)\n case 'agents list': return cmdAgentsList(args, d)\n case 'agents show': return cmdAgentsShow(args, d)\n case 'agents connect': return cmdAgentsConnect(args, d)\n case 'agents pause': return cmdAgentLifecycle(args, d, 'pause')\n case 'agents resume': return cmdAgentLifecycle(args, d, 'resume')\n case 'agents revoke': return cmdAgentRevoke(args, d)\n case 'agents rotate-key': return cmdAgentRotateKey(args, d)\n case 'agents rename': return cmdAgentRename(args, d)\n case 'budget show': return cmdBudgetShow(args, d)\n case 'budget grant': return cmdBudgetGrant(args, d)\n case 'budget revoke': return cmdBudgetRevoke(args, d)\n case 'wallets rename': return cmdWalletRename(args, d)\n case 'activity list': return cmdActivityList(args, d)\n case 'activity export': return cmdActivityExport(args, d)\n case 'catalog list': return cmdCatalogList(args, d)\n case 'contacts list': return cmdContactsList(args, d)\n case 'contacts add': return cmdContactsAdd(args, d)\n case 'contacts remove': return cmdContactsRemove(args, d)\n case 'feedback submit': return cmdFeedbackSubmit(args, d)\n default:\n throw new UsageError(`Unknown command: ${key}.`, 'Run `haven --help` for the command list.')\n }\n}\n\nfunction baseUrlFor(args: ParsedArgs, d: ResolvedDeps, session: Session | null): string {\n return args.flags.api ?? session?.apiBaseUrl ?? d.env.HAVEN_API_URL ?? DEFAULT_API\n}\n\nasync function authed(args: ParsedArgs, d: ResolvedDeps): Promise<{ session: Session; api: CliApi }> {\n const session = await d.sessionStore.load()\n // Status 401 so a missing local session and a rejected one produce the same\n // code and the same advice — from the caller's side they are one situation.\n if (!session) throw new CliApiError('Not authenticated.', 401)\n return { session, api: d.makeApi(baseUrlFor(args, d, session), session.token) }\n}\n\nfunction emit(d: ResolvedDeps, _json: boolean, data: unknown, human: () => string): void {\n d.o.data(data, human)\n}\n\n// ── Guide ───────────────────────────────────────────────────────────\n\n/**\n * Print the agent onboarding runbook — the same text served at\n * `/for-agents.md` (#2523). Offline by construction: the string is compiled in,\n * so an agent with no session and no network still gets the instructions that\n * tell it what to do about exactly that.\n */\nasync function cmdGuide(_args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n d.o.data({ ok: true, format: 'markdown', content: HAVEN_AGENT_RUNBOOK_MD }, () => HAVEN_AGENT_RUNBOOK_MD)\n return EXIT.ok\n}\n\n// ── Auth ────────────────────────────────────────────────────────────\n\ninterface DeviceStart {\n device_code: string\n user_code: string\n verification_url: string\n expires_in: number\n interval: number\n}\n\n/**\n * Browser-approved login (#2526), the DEFAULT for `haven login`.\n *\n * The reason this is the default and the password path is not: an agent drives\n * this CLI, and an agent must never hold its user's password. The cold-test\n * agent correctly refused to type one. This asks the human instead — the agent\n * pastes a link, and every signature stays with the person.\n *\n * Under `--json` the first object is emitted BEFORE polling starts, so an agent\n * can hand its user the link immediately rather than after the flow completes.\n */\nasync function deviceLogin(args: ParsedArgs, d: ResolvedDeps, baseUrl: string): Promise<number> {\n const api = d.makeApi(baseUrl)\n const label = d.env.HAVEN_CLIENT_LABEL ?? `Haven CLI on ${d.env.HOSTNAME ?? 'this machine'}`\n const start = await api.post<DeviceStart>('/auth/device/start', { client_label: label })\n\n const deadline = Date.now() + start.expires_in * 1000\n // Emitted first, not last: the whole point is that the agent can pass the\n // link on while the poll runs. `device_code` is #2618: without it, the\n // `--no-wait` object had nothing an agent could feed to\n // `haven login --poll` — the resume command existed on the flag parser and\n // nowhere an agent could reach it.\n d.o.data(\n {\n ok: true,\n verification_url: start.verification_url,\n user_code: start.user_code,\n device_code: start.device_code,\n interval: start.interval,\n expires_at: new Date(deadline).toISOString(),\n },\n () =>\n `Open ${start.verification_url}\\nand approve the code ${start.user_code}.\\n` +\n `It expires in ${Math.round(start.expires_in / 60)} minutes.`,\n )\n\n if (args.flags.noWait) return EXIT.ok\n\n // #2618: under --json, ten minutes of polling defeats the point of the\n // flag — an agent that expected to regain control sat out its whole turn.\n // --json now defaults to a SHORT wait (30 s, the issue's figure): still\n // long enough to catch a human who approves right away, short enough that\n // the agent gets a pending object instead of a blocked turn. An explicit\n // --no-wait keeps its documented immediate return, and human prose mode\n // keeps the full wait the flow always had.\n const jsonWaitMs = args.flags.json ? 30_000 : start.expires_in * 1000\n const waitUntil = Date.now() + jsonWaitMs\n\n // The server names the interval; the client does not invent one. `slow_down`\n // widens it, which is the only backoff signal this flow has.\n let interval = start.interval * 1000\n for (;;) {\n if (Date.now() >= deadline) {\n throw new HavenCliError('The code expired before it was approved.', EXIT.notAuthenticated)\n }\n if (Date.now() >= waitUntil) {\n // Time out at the CLIENT's deadline, not the code's: emit the pending\n // object carrying the device code so `haven login --poll\n // <device_code>` can pick the flow up — nothing is lost, exit 3\n // (not_authenticated: \"keep the flow, you are just not signed in yet\").\n d.o.data(\n { status: 'pending', device_code: start.device_code, retry_after: Math.round(interval / 1000) },\n () => 'Still waiting for approval — run the same command again to keep waiting.',\n )\n return EXIT.notAuthenticated\n }\n await d.sleep(interval)\n let res: { token: string; user: Session['user'] } | null = null\n try {\n res = await api.post<{ token: string; user: Session['user'] }>('/auth/device/token', {\n device_code: start.device_code,\n })\n } catch (err) {\n const code = deviceErrorCode(err)\n if (code === 'authorization_pending') continue\n if (code === 'slow_down') {\n interval += 5000\n continue\n }\n if (code === 'access_denied') {\n throw new HavenCliError('The request was denied.', EXIT.refused)\n }\n if (code === 'expired_token') {\n throw new HavenCliError('The code expired before it was approved.', EXIT.notAuthenticated)\n }\n throw err\n }\n await d.sessionStore.save({ token: res.token, apiBaseUrl: baseUrl, user: res.user })\n emit(\n d,\n args.flags.json,\n { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },\n () => `Signed in as ${res!.user.email}.`,\n )\n return EXIT.ok\n }\n}\n\n/** The RFC 8628 error slug in a 400 body, or null. */\nfunction deviceErrorCode(err: unknown): string | null {\n const body = (err as { body?: { error?: unknown } } | undefined)?.body\n return typeof body?.error === 'string' ? body.error : null\n}\n\n/**\n * #2618: the suggested gap between `haven login --poll` rounds, in seconds.\n * Mirrors what the backend's device start has named in `interval` so far —\n * the CLI never invents a different number, and one poll round per invocation\n * keeps the request rate at whatever the caller's retry loop chooses.\n */\nconst POLL_RETRY_AFTER_SECONDS = 5\n\n/**\n * ONE poll round of the device flow (#2618) — the second command of the\n * non-blocking sequence `login --json --no-wait`, then `login --poll\n * <device_code>`. The blocking loop cannot serve an agent that must return\n * promptly, and killing it loses the code; this performs the poll the loop\n * WOULD have done and hands the outcome straight back as an exit code:\n * 0 approved (session saved, same success object as the blocking path),\n * 3 pending (a `{ status, device_code, retry_after }` object — poll again),\n * 4 denied. The server answers `expired_token` for an unknown code too, so\n * that also exits 3: expired means start over, and 3 is \"not signed in\".\n */\nasync function devicePollOnce(\n args: ParsedArgs,\n d: ResolvedDeps,\n baseUrl: string,\n deviceCode: string,\n): Promise<number> {\n const api = d.makeApi(baseUrl)\n let res: { token: string; user: Session['user'] } | null = null\n try {\n res = await api.post<{ token: string; user: Session['user'] }>('/auth/device/token', {\n device_code: deviceCode,\n })\n } catch (err) {\n // Same slug mapping as the blocking loop above — one flow, one vocabulary.\n const code = deviceErrorCode(err)\n if (code === 'authorization_pending') {\n d.o.data(\n { status: 'pending', device_code: deviceCode, retry_after: POLL_RETRY_AFTER_SECONDS },\n () => 'Not approved yet — poll again shortly.',\n )\n return EXIT.notAuthenticated\n }\n if (code === 'slow_down') {\n // The server is saying the same thing the blocking loop's widening is:\n // back off. The next round should wait LONGER than the named interval.\n d.o.data(\n {\n status: 'pending',\n device_code: deviceCode,\n retry_after: POLL_RETRY_AFTER_SECONDS + 5,\n },\n () => 'Polling too fast — wait a moment longer, then poll again.',\n )\n return EXIT.notAuthenticated\n }\n if (code === 'access_denied') {\n throw new HavenCliError('The request was denied.', EXIT.refused)\n }\n if (code === 'expired_token') {\n throw new HavenCliError('The code expired before it was approved.', EXIT.notAuthenticated)\n }\n throw err\n }\n await d.sessionStore.save({ token: res.token, apiBaseUrl: baseUrl, user: res.user })\n emit(\n d,\n args.flags.json,\n { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },\n () => `Signed in as ${res!.user.email}.`,\n )\n return EXIT.ok\n}\n\nasync function cmdLogin(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n // #2618: the resume step of the non-blocking sequence. `--poll` takes the\n // device code the `--no-wait` (or timed-out `--json`) object carried and\n // performs exactly ONE round against POST /auth/device/token — see\n // `devicePollOnce`. It cannot be combined with the password path: a poll\n // belongs to a started device flow, and silently starting a login instead\n // would look like the flow was resumed when it was not.\n if (args.flags.poll) {\n return devicePollOnce(args, d, baseUrlFor(args, d, null), args.flags.poll)\n }\n const email = args.flags.email ?? d.env.HAVEN_EMAIL\n // #2526: the browser flow is the DEFAULT. `--email` (or HAVEN_EMAIL) keeps\n // the password path for a human who wants it — it is not removed, it is no\n // longer what an agent gets by asking for `login`.\n if (!email) {\n return deviceLogin(args, d, baseUrlFor(args, d, null))\n }\n const password = d.env.HAVEN_PASSWORD ?? (await d.promptPassword())\n if (!password) {\n throw new UsageError('A password is required.', 'Set HAVEN_PASSWORD for a non-interactive run.')\n }\n const baseUrl = baseUrlFor(args, d, null)\n const api = d.makeApi(baseUrl)\n const res = await api.post<{ token: string; user: Session['user'] }>('/auth/login', { email, password })\n await d.sessionStore.save({ token: res.token, apiBaseUrl: baseUrl, user: res.user })\n // The issue specifies { ok, email, expires_at }; `user` and `apiBaseUrl` stay\n // because they were already the shape and dropping them would break a script\n // that reads them for no gain. Neither the password nor the token is echoed —\n // `expires_at` is derived from the token, never the token itself.\n emit(\n d,\n args.flags.json,\n { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },\n () => `Signed in as ${res.user.email}.`,\n )\n return EXIT.ok\n}\n\nasync function cmdLogout(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n await d.sessionStore.clear()\n emit(d, args.flags.json, { ok: true, signed_out: true }, () => 'Signed out.')\n return EXIT.ok\n}\n\nasync function cmdWhoami(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { session, api } = await authed(args, d)\n const user = await api.get<Session['user']>('/auth/me')\n // The four fields #2525 asks for — id, email, session expiry, api url — laid\n // over the profile the route already returned, so nothing a caller reads\n // today disappears. `expires_at` is null when the token carries no readable\n // `exp`, which is a fact worth reporting rather than an error.\n emit(\n d,\n args.flags.json,\n { ...user, id: user.id, email: user.email, expires_at: sessionExpiry(session.token), api_url: session.apiBaseUrl },\n () => `${user.email}${user.name ? ` (${user.name})` : ''}`,\n )\n return EXIT.ok\n}\n\n// ── Wallets ─────────────────────────────────────────────────────────\n\n/**\n * Read the `accounts` envelope off `GET /user/accounts`, failing LOUDLY when\n * it is absent (#2914).\n *\n * The envelope key moved `safes` -> `accounts` in the naming contraction, and\n * this file kept reading the old one. Five call sites destructured an\n * `undefined` array and every wallets command died on\n * `Cannot read properties of undefined (reading 'length')` — a stack trace\n * blaming the CLI for a SERVER shape change, with nothing naming the real\n * cause. Nothing caught it: `api.get<T>` is an unchecked generic over a\n * hand-written interface, `@haven_ai/core` cannot be a dependency here\n * (it is `private: true` and this package publishes), and every fixture in\n * the suite encoded the old envelope, so the tests were green against a\n * response shape the server had stopped sending.\n *\n * So the envelope is read through one function that says what went wrong.\n * This is the same principle the rest of the slice applies to the server —\n * a shape mismatch should be a typed refusal naming the cause, never a\n * silent `undefined` that surfaces somewhere else.\n */\nfunction accountsEnvelope(body: { accounts?: Safe[] }): Safe[] {\n if (!Array.isArray(body.accounts)) {\n throw new Error(\n \"GET /user/accounts did not return an `accounts` array. This CLI needs a Haven backend \" +\n 'from the release that carries #2914 or later; an older server returns the retired ' +\n '`safes` envelope. Upgrade the backend, or pin an older @haven_ai/cli.',\n )\n }\n return body.accounts\n}\n\n/**\n * One TOKEN/BALANCE table cell (#3318).\n *\n * The wire carries an additive `balanceFreshness` marker beside the balance\n * (since #3295): `stale` means the figure is real but was last read from the\n * chain at `asOf`, `unavailable` means nothing has ever been read and the\n * `'0'` beside it is a filler. Printing either as if it were current is how\n * #2769 read: a failed read renders a number the wallet does not hold. So a\n * stale entry keeps its figure and gains `≈ … (as of 45m ago)` — the tilde is\n * the \"not exact\" signal, the timestamp says how far behind it is; an\n * unavailable entry prints `unavailable` instead of the filler zero.\n * A clean entry — marker absent — renders exactly as before, byte for byte,\n * which is what keeps this additive for every existing consumer of the table.\n */\nfunction renderBalanceCell(entry: Balance & { balanceFreshness?: BalanceFreshness }): string {\n const marker = entry.balanceFreshness\n if (!marker) return entry.formatted\n if (marker.status === 'unavailable') return 'unavailable'\n return `≈ ${entry.formatted} (as of ${timeAgo(marker.asOf ?? '')})`\n}\n\nasync function cmdWalletsList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n emit(d, args.flags.json, accounts, () =>\n accounts.length === 0\n ? 'No Haven wallets yet.'\n : table(\n ['NAME', 'NETWORK', 'ADDRESS', 'DEFAULT'],\n accounts.map((s) => [s.name, chainName(s.chain_id), truncateAddress(accountAddressOf(s)), s.is_default ? '✓' : '']),\n ),\n )\n return EXIT.ok\n}\n\nasync function cmdWalletsBalances(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n const safe = pickSafe(accounts, args.flags.safe)\n if (!safe) {\n if (args.flags.safe) throw new UsageError(`No wallet matches \"${args.flags.safe}\".`)\n throw new CliApiError('No Haven wallet found.', 404)\n }\n const { balances } = await api.get<{ balances: Balance[] }>(\n `/balances/${accountAddressOf(safe)}?chain_id=${safe.chain_id}`,\n )\n emit(d, args.flags.json, { account: safe.name, chainId: safe.chain_id, balances }, () =>\n [\n `${safe.name} · ${chainName(safe.chain_id)} · ${truncateAddress(accountAddressOf(safe))}`,\n balances.length === 0\n ? ' (no balances)'\n : table(\n ['TOKEN', 'BALANCE'],\n balances.map((b) => [b.symbol, renderBalanceCell(b)]),\n ),\n ].join('\\n'),\n )\n return EXIT.ok\n}\n\nfunction pickSafe(accounts: Safe[], ref?: string): Safe | undefined {\n if (!ref) return accounts.find((s) => s.is_default) ?? accounts[0]\n const lower = ref.toLowerCase()\n return accounts.find((s) => s.id === ref || accountAddressOf(s).toLowerCase() === lower)\n}\n\n// ── Wallet funding (#2534) ──────────────────────────────────────────\n\n/**\n * The paste-ready funding instruction, read from the backend.\n *\n * The endpoint is the source; this command renders it. Every number in the\n * prose — the minimum to send, the address, the explorer link — comes out of\n * the response, so the CLI, the dashboard's funding card and the backend's\n * own docs cannot drift apart: `@haven_ai/core` owns the constants, the\n * route composes them, and nothing here repeats one. Prose mode prints the\n * sentence an agent hands to its human; `--json` prints the response object\n * itself, so a machine that wants to relay fields rather than a sentence has\n * the same facts in the same place.\n *\n * `--wait` polls until `funded` flips — how a turn actually waits out a human\n * moving money — with elapsed time visible so nobody stares at a silent\n * terminal. It exits 0 once funded and 1 on timeout (elapsed time in the\n * message); it never sends anything, never touches a faucet — this is\n * read-only facts for the human to act on, whatever the flag.\n */\nasync function cmdWalletsFunding(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n const safe = pickSafe(accounts, args.flags.safe)\n if (!safe) {\n if (args.flags.safe) throw new UsageError(`No wallet matches \"${args.flags.safe}\".`)\n throw new CliApiError('No Haven wallet found.', 404)\n }\n // The endpoint is keyed by account ID and resolves ownership itself — the\n // address/chain in the response are the route's answer, not ours to compose.\n const funding = await api.get<FundingResponse>(`/user/accounts/${safe.id}/funding`)\n\n if (!args.flags.wait) {\n emitFunding(d, funding)\n return EXIT.ok\n }\n\n // ── `--wait`: poll until the human's transfer lands ────────────────\n const started = Date.now()\n // The poll interval, injectable so tests can run the loop without real time.\n const pollMs = Number(d.env.HAVEN_FUNDING_POLL_MS ?? '5000')\n // A default cap, not a guess about the user's patience: two hours covers a\n // bank-transfer detour, and `HAVEN_FUNDING_WAIT_MS` shortens it for tests.\n const waitMs = Number(d.env.HAVEN_FUNDING_WAIT_MS ?? String(2 * 60 * 60 * 1000))\n if (!Number.isFinite(pollMs) || pollMs <= 0 || !Number.isFinite(waitMs) || waitMs <= 0) {\n throw new UsageError('HAVEN_FUNDING_POLL_MS / HAVEN_FUNDING_WAIT_MS must be positive numbers of milliseconds')\n }\n let current = funding\n for (;;) {\n // The cap is checked BEFORE each poll, so a zero-length wait exits without\n // ever calling the endpoint twice.\n const spent = Date.now() - started\n if (spent >= waitMs) {\n throw new HavenCliError(\n `Still not funded after ${elapsedLabel(spent)} — the transfer may not have landed yet. Check the explorer link, then re-run.`,\n EXIT.failed,\n )\n }\n await d.sleep(pollMs)\n current = await api.get<FundingResponse>(`/user/accounts/${safe.id}/funding`)\n if (current.funded) break\n d.o.note(`Still waiting after ${elapsedLabel(Date.now() - started)} — funded: no.`)\n }\n d.o.note(`Account shows funded after ${elapsedLabel(Date.now() - started)}.`)\n emitFunding(d, current)\n return EXIT.ok\n}\n\n/** One renderer, both modes: prose carries the paste-ready sentence. */\nfunction emitFunding(d: ResolvedDeps, funding: FundingResponse): void {\n emit(d, d.o.json, funding, () => {\n const token = funding.tokens.find((t) => t.minimum_useful_human !== null)\n const asset = token\n ? `at least ${token.minimum_useful_human} ${token.symbol}`\n : funding.native.needed\n ? funding.native.symbol\n : 'USDC'\n const gas = funding.native.needed\n ? ` plus ${funding.native.symbol} for gas`\n : ' — no gas token needed; Haven sponsors it'\n const faucet = funding.faucet_url !== undefined ? ` faucet: ${funding.faucet_url},` : ''\n return [\n `Send ${asset} on ${funding.chain.name} to ${funding.account_address}${gas}.`,\n `Explorer: ${funding.chain.explorer_url}.${faucet ? faucet.slice(0, -1) : ''}`,\n funding.funded ? 'The account already counts as funded.' : 'Nothing has arrived yet.',\n ].join('\\n')\n })\n}\n\n/** `83s` → `1m23s` → `1h02m` — the poll line and the timeout message share it. */\nfunction elapsedLabel(ms: number): string {\n const total = Math.floor(ms / 1000)\n const h = Math.floor(total / 3600)\n const m = Math.floor((total % 3600) / 60)\n const s = total % 60\n if (h > 0) return `${h}h${String(m).padStart(2, '0')}m`\n if (m > 0) return `${m}m${String(s).padStart(2, '0')}s`\n return `${s}s`\n}\n\n// ── Agents & budget ─────────────────────────────────────────────────\n\nasync function cmdAgentsList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const { agents } = await api.get<{ agents: Agent[] }>('/agents')\n emit(d, args.flags.json, agents, () =>\n agents.length === 0\n ? 'No agents yet.'\n : table(\n ['ID', 'NAME', 'STATUS', 'BUDGETS'],\n agents.map((a) => [a.id, a.name, a.status, budgetSummary(a.allowances)]),\n ),\n )\n return EXIT.ok\n}\n\nasync function cmdAgentsShow(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven agents show <id>')\n const { api } = await authed(args, d)\n const agent = await api.get<Agent>(`/agents/${id}`)\n emit(d, args.flags.json, agent, () =>\n [\n `${agent.name} [${agent.status}]`,\n `id: ${agent.id}`,\n `budget: ${budgetSummary(agent.allowances)}`,\n ].join('\\n'),\n )\n return EXIT.ok\n}\n\n/**\n * The one command that prints a delegation hash (#2612).\n *\n * `budget revoke` takes a hash as its second argument, and until this existed\n * NO `haven` command printed one — while the README and the revoke usage error\n * both said `haven agents show` did. It does not: that response carries the\n * allowances projection and has no hash field at all. Both now point here, and\n * a test asserts this literal appears in the README AND that running it emits\n * a hash, so the instruction and the output cannot drift apart again.\n */\nexport const HASH_DISCOVERY_HINT = 'haven budget show <agentId> --hashes'\n\nasync function cmdBudgetShow(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven budget show <agentId> [--hashes]')\n const { api } = await authed(args, d)\n\n // #2612: a DIFFERENT read, deliberately behind a flag. The hashes live on\n // GET /agents/:id/delegations, not on the agent's allowances projection, and\n // `budget show --json` has emitted a bare allowances array since the first\n // CLI scaffold — adding a second shape to that array would break every\n // existing consumer of it.\n if (args.flags.hashes) {\n const { delegations } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n emit(d, args.flags.json, delegations, () =>\n delegations.length === 0\n ? `No delegations on agent ${id}.`\n : table(\n ['DELEGATION HASH', 'STATUS', 'VERSION'],\n delegations.map((r) => [r.delegation_hash, r.status, String(r.version)]),\n ),\n )\n return EXIT.ok\n }\n\n const agent = await api.get<Agent>(`/agents/${id}`)\n const allowances = agent.allowances ?? []\n emit(d, args.flags.json, allowances, () =>\n allowances.length === 0\n ? `${agent.name} has no configured budget.`\n : table(\n ['TOKEN', 'AMOUNT', 'RESETS'],\n allowances.map((a) => [a.token_symbol, a.allowance_amount, resetLabel(a.reset_period_min)]),\n ),\n )\n return EXIT.ok\n}\n\nfunction budgetSummary(allowances?: Allowance[]): string {\n if (!allowances || allowances.length === 0) return '—'\n return allowances.map((a) => `${a.allowance_amount} ${a.token_symbol}`).join(', ')\n}\n\n// ── Budget grant/revoke (#2539, C3) — construct-and-hand-off ────────────────\n//\n// Both commands CONSTRUCT a signature request and print a dashboard link the\n// human signs in the browser. The CLI never signs and never calls activate —\n// that is the whole safety property of this slice, and the reason the backend\n// allow-list can carry build + revoke-prepare at all.\n\n/** The POST /agents/:id/delegations/build response the CLI consumes (#2539). */\ninterface DelegationBuild {\n delegation_hash: string\n version: number\n /** The same value as delegation_hash — one identifier, no new column. */\n build_id: string\n typed_data_hash: string\n signing_url: string\n}\n\n/** One row of GET /agents/:id/delegations (#2539's --wait reads these). */\ninterface DelegationRow {\n delegation_hash: string\n version: number\n status: 'pending' | 'active' | 'replaced' | 'revoked'\n /**\n * #3922: the backend's budget-view liveness (`active` and unexpired). Absent\n * on an older backend — a missing value means \"derive from `status`\", never\n * false.\n */\n is_live?: boolean\n}\n\n/**\n * The \"still enabled\" delegation statuses (#3922): a row is enabled on-chain\n * until the chain confirms it dead, so only `revoked` is not. This is the CLI's\n * ONE copy of `STILL_ENABLED_DELEGATION_STATUSES` from `@haven_ai/core` — the\n * published CLI cannot depend on that private package — and\n * `commands.test.ts` pins the two together. The revoke gate reads STATUS, not\n * `is_live`: it guards against leaving on-chain authority behind and must work\n * against an older backend that sends no `is_live`.\n */\nconst STILL_ENABLED_STATUSES: ReadonlySet<string> = new Set([\n 'pending',\n 'active',\n 'replaced',\n])\n\n/** The POST /agents/:id/delegations/:hash/revoke prepare response (#2539). */\ninterface RevocationPrepare {\n signature_scheme?: 'eip712_userop' | 'webauthn_userop'\n /** Dashboard revoke link, built by the backend from its own FRONTEND_URL. */\n revocation_url?: string\n}\n\n/** How long `--wait` polls before giving up. */\nconst BUDGET_WAIT_TIMEOUT_S = 15 * 60\nconst BUDGET_WAIT_INTERVAL_MS = 5_000\n\n/**\n * `haven budget grant` — construct the budget delegation, hand the signature\n * to the human (#2539).\n *\n * Calls the build route with the owner_cli session, stores nothing itself,\n * and prints the signing link the backend built. `--wait` polls the agent's\n * delegation list for the returned hash to reach `active`, which converges\n * because the build is idempotent within its expiry: the dashboard form's own\n * rebuild of the same grant returns the SAME hash instead of minting a new\n * version that would strand this poller.\n */\nasync function cmdBudgetGrant(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) {\n throw new UsageError('Usage: haven budget grant <agentId> --amount 25 --token USDC --period <minutes> [--recipient <address>] [--expires <unix-seconds>] [--wait]')\n }\n if (!args.flags.amount || !args.flags.token || args.flags.period === undefined) {\n throw new UsageError('--amount, --token and --period are required (period is whole minutes, at least 1)')\n }\n // The delegation rail has no one-time period: `/delegations/build` refuses\n // anything under 60 seconds. `agents connect` DOES take `--period 0` for\n // `reset_period_min`, which is a different field on a different route, and\n // this command's usage text was first written from that convention — so a\n // caller following it hit an opaque 400 from the backend instead of this\n // sentence. Refuse it here, where the message can say what to pass instead.\n if (args.flags.period < 1) {\n 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.')\n }\n const { api } = await authed(args, d)\n\n // Fail fast on the rail this command cannot serve, and read the token's\n // decimals from the backend — the same registry the dashboard form sizes\n // budgets with, never a local table.\n const agent = await api.get<Agent & {\n account_type?: string | null\n account_address?: string | null\n account_chain_id?: number | null\n }>(`/agents/${id}`)\n if (agent.account_type !== 'delegator_hybrid') {\n throw new HavenCliError(\n `Agent ${id} is not on the delegation rail — budgets are managed from the dashboard for this account.`,\n EXIT.refused,\n )\n }\n const accountAddress = agent.account_address\n const accountChainId = agent.account_chain_id\n if (!accountAddress || !accountChainId) {\n throw new HavenCliError(`Agent ${id} has no wallet assigned yet — connect it first.`, EXIT.refused)\n }\n const { balances } = await api.get<{ balances: BalanceToken[] }>(\n `/balances/${accountAddress}?chain_id=${accountChainId}`,\n )\n const wanted = args.flags.token.trim().toUpperCase()\n const token = balances.find((b) => b.symbol.toUpperCase() === wanted)\n if (!token || !token.address) {\n const known = balances.map((b) => b.symbol).join(', ')\n throw new UsageError(`Unknown token ${args.flags.token} on this wallet's chain. Available: ${known || 'none'}`)\n }\n const amount = parseTokenAmount(args.flags.amount, token.decimals, token.symbol)\n if (!amount.ok) throw new UsageError(amount.message)\n\n const built = await api.post<DelegationBuild>(`/agents/${id}/delegations/build`, {\n token_address: token.address,\n recipient_address: args.flags.recipient ?? null,\n budget_atomic: amount.atomic,\n period_seconds: args.flags.period * 60,\n ...(args.flags.expires !== undefined ? { expires_at: args.flags.expires } : {}),\n })\n\n const emitGrant = (status?: DelegationRow['status']) =>\n emit(d, args.flags.json, { ...built, agent_id: id, status: status ?? 'pending' }, () =>\n [\n `Budget of ${args.flags.amount} ${token.symbol} per ${args.flags.period} minutes built for agent ${id}.`,\n args.flags.recipient ? `Recipient pin: ${args.flags.recipient}` : null,\n 'Open this link and sign — the budget goes live the moment you do:',\n built.signing_url,\n `Delegation: ${built.delegation_hash} (version ${built.version})`,\n status === 'active' ? 'Signed and active.' : 'Waiting for your signature. Run the same command with --wait to poll until it is active.',\n ]\n .filter((line): line is string => line !== null)\n .join('\\n'),\n )\n\n emitGrant()\n if (!args.flags.wait) return EXIT.ok\n\n const deadline = Date.now() + BUDGET_WAIT_TIMEOUT_S * 1000\n while (Date.now() < deadline) {\n await d.sleep(BUDGET_WAIT_INTERVAL_MS)\n const { delegations } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n const mine = delegations.find((row) => row.delegation_hash === built.delegation_hash)\n // #3922: the backend's `is_live` when sent; an older backend omits it, so\n // fall back to the status it always sent (missing is never \"not live\").\n if (mine && (mine.is_live ?? mine.status === 'active')) {\n emitGrant('active')\n return EXIT.ok\n }\n if (mine?.status === 'revoked' || mine?.status === 'replaced') {\n throw new HavenCliError(\n `Delegation ${built.delegation_hash} is now ${mine.status} without being signed.`,\n EXIT.refused,\n )\n }\n }\n throw new HavenCliError(\n `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 — sign it, or rerun with --wait.`,\n EXIT.failed,\n )\n}\n\n/**\n * `haven budget revoke` — prepare the revocation, hand the signature to the\n * human (#2539).\n *\n * Calls the per-hash revoke PREPARE route (one sponsored UserOp, unsigned)\n * and prints the revocation link the backend built. Nothing is submitted and\n * no row flips here: the budget keeps working until the owner signs in the\n * dashboard, which is what `--wait` polls for.\n */\nasync function cmdBudgetRevoke(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const [id, hash] = args.positionals\n if (!id || !hash) throw new UsageError('Usage: haven budget revoke <agentId> <delegationHash> [--wait]')\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {\n throw new UsageError(`The delegation hash must be 0x followed by 64 hex characters — \\`${HASH_DISCOVERY_HINT}\\` lists them, or the dashboard.`)\n }\n\n const { api } = await authed(args, d)\n const { delegations } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n const row = delegations.find((r) => r.delegation_hash.toLowerCase() === hash.toLowerCase())\n if (!row) {\n throw new HavenCliError(`No delegation ${hash} on agent ${id}.`, EXIT.refused)\n }\n if (row.status === 'revoked') {\n throw new HavenCliError(`Delegation ${hash} is already revoked.`, EXIT.refused)\n }\n // #3542 / #3729: a `replaced` row is still live — the newer grant does not\n // undo it until the newer delegation is itself revoked. The backend's\n // prepare route accepts `replaced` (it only rejects `revoked`), so this\n // refusal was a dead end for an agent whose only live row had been\n // replaced: the row is prepared for revocation like any other live one.\n\n // PREPARE only: the response carries the unsigned UserOp and the dashboard\n // link. The /submit step stays owner-session-only by design.\n const prepared = await api.post<RevocationPrepare>(`/agents/${id}/delegations/${hash}/revoke`, {})\n const revokeUrl = prepared.revocation_url\n if (!revokeUrl) {\n throw new HavenCliError(\n 'The backend did not return a revocation link — it may be older than #2539. Finish the revocation in the dashboard.',\n EXIT.failed,\n )\n }\n\n const emitRevoke = (status: DelegationRow['status'] | 'pending_revoke') =>\n emit(d, args.flags.json, { agent_id: id, delegation_hash: hash, status, ...prepared }, () =>\n [\n 'Revocation prepared — one signature, sponsored (no gas).',\n 'Open this link and sign to stop this budget:',\n revokeUrl,\n `Delegation: ${hash}`,\n status === 'revoked' ? 'Revoked.' : 'The budget keeps working until you sign. Run the same command with --wait to poll until it is revoked.',\n ]\n .filter((line): line is string => line !== null)\n .join('\\n'),\n )\n\n emitRevoke('pending_revoke')\n if (!args.flags.wait) return EXIT.ok\n\n const deadline = Date.now() + BUDGET_WAIT_TIMEOUT_S * 1000\n while (Date.now() < deadline) {\n await d.sleep(BUDGET_WAIT_INTERVAL_MS)\n const { delegations: after } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n const mine = after.find((r) => r.delegation_hash.toLowerCase() === hash.toLowerCase())\n if (mine?.status === 'revoked') {\n emitRevoke('revoked')\n return EXIT.ok\n }\n }\n throw new HavenCliError(\n `Timed out waiting for delegation ${hash} to be revoked (${BUDGET_WAIT_TIMEOUT_S / 60} minutes). The link stays valid — sign it, or rerun with --wait.`,\n EXIT.failed,\n )\n}\n\nfunction resetLabel(mins: number): string {\n if (mins === 0) return 'one-time'\n if (mins === 1440) return 'daily'\n if (mins === 10080) return 'weekly'\n if (mins === 43200) return 'monthly'\n return `every ${mins}m`\n}\n\nasync function cmdAgentLifecycle(args: ParsedArgs, d: ResolvedDeps, action: 'pause' | 'resume'): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError(`Usage: haven agents ${action} <id>`)\n const { api } = await authed(args, d)\n await api.post(`/agents/${id}/${action}`)\n const status = action === 'pause' ? 'paused' : 'resumed'\n // #3722: pause/resume are Haven-side only; say so, so nobody reads \"paused\" as a stopped budget.\n emit(d, args.flags.json, { ok: true, agent_id: id, status }, () =>\n action === 'pause'\n ? `Agent ${id} paused: payments through Haven are blocked, but its budget stays live on-chain (end it with \\`haven budget revoke\\`).`\n : `Agent ${id} resumed: payments through Haven are allowed again.`,\n )\n return EXIT.ok\n}\n\nasync function cmdAgentRevoke(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven agents revoke <id> [--keep-budget] --yes')\n // Revoke is terminal (status can't go back to active). Require explicit --yes\n // so it can't happen by accident in a script.\n if (!args.flags.yes) {\n throw new UsageError(\n `This permanently retires agent ${id} in Haven.`,\n 'Re-run with --yes to confirm. Revoke is terminal — the agent cannot go back to active. ' +\n 'It ends no budget on-chain: end each live budget with `haven budget revoke <agentId> <delegationHash>`.',\n )\n }\n const { api } = await authed(args, d)\n\n // #3729: POST /agents/:id/revoke is a status flip — it changes no delegation\n // row and makes no on-chain call — so a live budget delegation outlives the\n // revoke, and whoever holds the delegate key can keep redeeming it. The\n // gate reads the server's own live count instead of keeping a CLI copy of\n // the live set, then names each live row's exact revocation command. A\n // budget going live between this read and the POST is accepted: this is a\n // client-side guard, not an authority control (the superseded-agent path\n // and older CLIs can still create that state).\n let live: DelegationRow[] = []\n try {\n const agent = await api.get<Agent>(`/agents/${id}`)\n if ((agent.live_delegation_count ?? 0) > 0) {\n const { delegations } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n live = delegations.filter((r) => STILL_ENABLED_STATUSES.has(r.status))\n }\n } catch (err) {\n // Fail closed: without the live set, no revoke. The read's own exit\n // class stands (401 → 3, network → 5, 403/404 → refused) — the note only\n // explains why the revoke never happened, it does not re-classify the\n // failure.\n d.o.note(`Couldn't check budgets for agent ${id}, so the revocation was not attempted.`)\n throw err\n }\n\n if (live.length > 0 && !args.flags.keepBudget) {\n throw new HavenCliError(\n `Agent ${id} still has a live on-chain budget. Revoking now would leave it redeemable by the delegate key.`,\n EXIT.refused,\n [\n ...live.map((r) => `haven budget revoke ${id} ${r.delegation_hash} # ${r.status}`),\n 'Remove agent… in the dashboard ends every live budget with one signature, before revoking.',\n 'To revoke the agent anyway and leave the budget live on-chain, re-run with --keep-budget.',\n ].join('\\n'),\n // The machine branch: a script skips the prose and reads the rows.\n { live_delegations: live.map(({ delegation_hash, status }) => ({ delegation_hash, status })) },\n )\n }\n\n await api.post(`/agents/${id}/revoke`)\n emit(\n d,\n args.flags.json,\n live.length > 0\n ? {\n ok: true,\n agent_id: id,\n status: 'revoked',\n live_delegations: live.map(({ delegation_hash, status }) => ({ delegation_hash, status })),\n }\n : { ok: true, agent_id: id, status: 'revoked' },\n () =>\n live.length > 0\n ? [\n `Agent ${id} revoked.`,\n `Its budget is still live on-chain: the delegate key can keep spending until each delegation is revoked.`,\n ...live.map((r) => `haven budget revoke ${id} ${r.delegation_hash} # ${r.status}`),\n ].join('\\n')\n : `Agent ${id} revoked in Haven. It had no live budget on-chain.`,\n )\n return EXIT.ok\n}\n\nasync function cmdAgentRotateKey(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven agents rotate-key <id>')\n const { api } = await authed(args, d)\n const res = await api.post<{ api_key: string; api_key_prefix: string }>(`/agents/${id}/rotate-key`)\n // The key is the payload, so it belongs on stdout in both modes. The\n // SENTENCE about it is prose and moves to stderr under --json, which is what\n // keeps stdout a single parseable object with a secret in exactly one field.\n d.o.note('New API key (shown once — store it now; the old key stops working):')\n emit(d, args.flags.json, res, () => res.api_key)\n return EXIT.ok\n}\n\nasync function cmdAgentRename(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const [id, ...nameParts] = args.positionals\n const name = nameParts.join(' ').trim()\n if (!id || !name) throw new UsageError('Usage: haven agents rename <id> <name>')\n const { api } = await authed(args, d)\n await api.put(`/agents/${id}`, { name })\n emit(d, args.flags.json, { ok: true, agent_id: id, name }, () => `Agent ${id} renamed to \"${name}\".`)\n return EXIT.ok\n}\n\nasync function cmdWalletRename(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const [id, ...nameParts] = args.positionals\n const name = nameParts.join(' ').trim()\n if (!id || !name) throw new UsageError('Usage: haven wallets rename <id> <name>')\n const { api } = await authed(args, d)\n await api.put(`/user/accounts/${id}`, { name })\n emit(d, args.flags.json, { ok: true, account_id: id, name }, () => `Wallet ${id} renamed to \"${name}\".`)\n return EXIT.ok\n}\n\n// ── Activity ────────────────────────────────────────────────────────\n\n/**\n * Resolve `--safe` (id or address) to an account id for the `/transactions` filter,\n * mirroring `wallets balances`. Throws if `--safe` was given but matches no\n * wallet, so a typo'd filter fails loudly instead of silently returning all rows.\n */\nasync function resolveAccountId(args: ParsedArgs, api: CliApi): Promise<string | undefined> {\n if (!args.flags.safe) return undefined\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n const safe = pickSafe(accounts, args.flags.safe)\n if (!safe) throw new UsageError(`No wallet matches \"${args.flags.safe}\".`)\n return safe.id\n}\n\nasync function cmdActivityList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const accountId = await resolveAccountId(args, api)\n const params = new URLSearchParams({\n offset: String(args.flags.offset ?? 0),\n limit: String(args.flags.limit ?? 25),\n })\n if (accountId) params.set('accountId', accountId)\n if (args.flags.agent) params.set('agentId', args.flags.agent)\n const { transactions } = await api.get<{ transactions: Txn[] }>(`/transactions?${params.toString()}`)\n const visible = args.flags.direction\n ? transactions.filter((t) => t.direction === args.flags.direction)\n : transactions\n emit(d, args.flags.json, visible, () =>\n visible.length === 0\n ? 'No activity.'\n : table(\n ['DATE', 'DIR', 'AMOUNT', 'TYPE', 'ACCOUNT'],\n visible.map((t) => [\n new Date(t.timestamp * 1000).toISOString().slice(0, 10),\n t.direction === 'in' ? 'in' : 'out',\n `${t.direction === 'in' ? '+' : '-'}${t.valueFormatted} ${t.asset}`,\n t.source ?? 'transfer',\n t.accountName ?? '',\n ]),\n ),\n )\n return EXIT.ok\n}\n\nasync function cmdActivityExport(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n if (args.flags.format === 'sie') return exportSie(args, d)\n const { api } = await authed(args, d)\n const accountId = await resolveAccountId(args, api)\n const params = new URLSearchParams({\n offset: String(args.flags.offset ?? 0),\n limit: String(args.flags.limit ?? 1000),\n })\n if (accountId) params.set('accountId', accountId)\n if (args.flags.agent) params.set('agentId', args.flags.agent)\n const { transactions } = await api.get<{ transactions: Txn[] }>(`/transactions?${params.toString()}`)\n const visible = args.flags.direction\n ? transactions.filter((t) => t.direction === args.flags.direction)\n : transactions\n\n // Same columns as the dashboard export (#411), minus counterparty_name\n // (no contacts join in the CLI yet).\n const headers = [\n 'date', 'type', 'status', 'direction', 'amount', 'token_symbol', 'token_address',\n 'counterparty_address', 'agent_name', 'tx_hash', 'chain_id', 'account_address',\n ]\n const rows = visible.map((t) => [\n new Date(t.timestamp * 1000).toISOString(),\n exportType(t),\n exportStatus(t),\n t.direction,\n t.valueFormatted,\n t.tokenSymbol ?? t.asset ?? '',\n t.tokenAddress ?? '',\n (t.direction === 'in' ? t.from : t.to) ?? '',\n t.agentName ?? '',\n t.hash,\n t.chainId != null ? String(t.chainId) : '',\n t.accountAddress ?? '',\n ])\n d.o.text(toCsv(headers, rows), { format: 'csv', rows: rows.length })\n return EXIT.ok\n}\n\nfunction exportType(t: Txn): string {\n if (t.activityType === 'delegate_sweep') return 'sweep'\n if (t.source === 'x402') return 'x402'\n if (t.source === 'mpp_demo') return 'mpp'\n return t.direction === 'in' ? 'receive' : 'send'\n}\n\nfunction exportStatus(t: Txn): string {\n if (t.isError) return 'failed'\n if (t.paymentFlowStatus === 'confirming_merchant') return 'pending'\n return 'executed'\n}\n\n/** SIE 4I export: the backend builds the verifikat file (book-time SEK + BAS). */\nasync function exportSie(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const params = new URLSearchParams({ format: 'sie' })\n if (args.flags.from) params.set('from', args.flags.from)\n if (args.flags.to) params.set('to', args.flags.to)\n if (args.flags.company) params.set('company', args.flags.company)\n const content = await api.getText(`/accounting/export?${params.toString()}`)\n d.o.text(content, { format: 'sie' })\n return EXIT.ok\n}\n\n// ── Catalog ─────────────────────────────────────────────────────────\n\nasync function cmdCatalogList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const { entries } = await api.get<{ entries: CatalogEntry[] }>('/catalog')\n emit(d, args.flags.json, entries, () =>\n entries.length === 0\n ? 'Catalog is empty.'\n : table(\n ['NAME', 'CATEGORY', 'RAIL', 'PRICE', 'STATUS'],\n entries.map((e) => [e.name, e.category, e.rail, e.price_display ?? '—', e.status]),\n ),\n )\n return EXIT.ok\n}\n\n\n// ── Connect (#2527) ─────────────────────────────────────────────────\n\n/**\n * Resolve the wallet this setup belongs to, and the token's decimals.\n *\n * The decimals are READ from the backend rather than kept in a table here.\n * `GET /balances/:accountAddress` lists every token the chain is configured for —\n * zero balance included — with its address and decimals, which is the same\n * registry the dashboard modal reads. A local table would be a second source\n * of truth for a number that decides a budget's magnitude, and it would drift\n * silently the first time a chain gained a token.\n */\nasync function resolveWalletAndToken(\n args: ParsedArgs,\n api: CliApi,\n symbol: string,\n): Promise<{ accountId: string; token: BalanceToken }> {\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n if (accounts.length === 0) {\n throw new HavenCliError('No wallet on this account yet — finish onboarding first.', EXIT.refused)\n }\n const safe = args.flags.safe\n ? accounts.find((s) => s.id === args.flags.safe || accountAddressOf(s) === args.flags.safe)\n : (accounts.find((s) => s.is_default) ?? accounts[0])\n if (!safe) throw new UsageError(`No wallet matches --safe ${args.flags.safe}`)\n\n // `chain_id` is REQUIRED here, not decorative. A passkey set derives the same\n // account address on every chain, so one address can own more than one\n // ownership row (an account on each of two chains) — and\n // `GET /balances/:address` answers `400 chain_id required` rather than\n // guessing when it finds more than one (`routes/balances.ts`). `wallets\n // balances` has always passed it; this call omitted it and would have failed\n // for any address with accounts on more than one chain (haven-reviewer,\n // #2527).\n const { balances } = await api.get<{ balances: BalanceToken[] }>(\n `/balances/${accountAddressOf(safe)}?chain_id=${safe.chain_id}`,\n )\n const wanted = symbol.trim().toUpperCase()\n const token = balances.find((b) => b.symbol.toUpperCase() === wanted)\n if (!token) {\n const known = balances.map((b) => b.symbol).join(', ')\n throw new UsageError(`Unknown token ${symbol} on this wallet's chain. Available: ${known || 'none'}`)\n }\n return { accountId: safe.id, token }\n}\n\n/** Poll a setup until it leaves the states that are still in flight. */\nconst SETTLED = new Set(['active', 'expired', 'cancelled', 'failed'])\n\nasync function pollSetup(\n api: CliApi,\n setupId: string,\n d: ResolvedDeps,\n wait: boolean,\n): Promise<SetupStatus> {\n let status = await api.get<SetupStatus>(`/agent-connection-setups/${setupId}`)\n if (!wait) return status\n // Bounded by the setup's own expiry rather than a local guess, so the loop\n // cannot outlive the thing it is watching.\n const deadline = new Date(status.expires_at).getTime()\n while (!SETTLED.has(status.status) && Date.now() < deadline) {\n await d.sleep(5000)\n status = await api.get<SetupStatus>(`/agent-connection-setups/${setupId}`)\n }\n return status\n}\n\n/**\n * `haven agents connect` — the connect flow without the dashboard modal.\n *\n * Three shapes: create a setup, `--status <id>` to read one, and `--run` to\n * additionally execute the connector command the backend printed.\n *\n * The command is PRINTED, never composed. `connector_command` comes back from\n * `POST /agent-connection-setups` and is emitted verbatim, which is what makes\n * it byte-identical to the dashboard's for the same setup — they are the same\n * string from the same builder, not two constructions that have to be kept in\n * agreement.\n */\nasync function cmdAgentsConnect(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n\n if (args.flags.status) {\n const status = await pollSetup(api, args.flags.status, d, args.flags.wait)\n emit(d, args.flags.json, status, () =>\n [\n `setup ${status.setup_id}: ${status.status}`,\n status.agent_id ? `agent: ${status.agent_id}` : null,\n SETTLED.has(status.status) ? null : `approve: ${status.approval_url}`,\n ]\n .filter(Boolean)\n .join('\\n'),\n )\n return EXIT.ok\n }\n\n const name = args.flags.name?.trim()\n if (!name) throw new UsageError('Usage: haven agents connect --name <name> --budget <amount> --token USDC --period <minutes>')\n if (!args.flags.budget || !args.flags.token || args.flags.period === undefined) {\n throw new UsageError('--budget, --token and --period are required (period is whole minutes; 0 means one-time)')\n }\n\n const { accountId, token } = await resolveWalletAndToken(args, api, args.flags.token)\n const amount = parseTokenAmount(args.flags.budget, token.decimals, token.symbol)\n if (!amount.ok) throw new UsageError(amount.message)\n\n const setup = await api.post<CreateSetupResponse>('/agent-connection-setups', {\n name,\n account_id: accountId,\n allowances: [\n {\n token_address: token.address ?? '0x0000000000000000000000000000000000000000',\n token_symbol: token.symbol,\n // ATOMIC on the way in, human on the way back (#2295). Converted here\n // exactly once, from the decimals the backend just told us.\n allowance_amount: amount.atomic,\n reset_period_min: args.flags.period,\n },\n ],\n // How this setup was made, for connect attribution (#2302). The route\n // already accepts any slug, so nothing backend-side had to change.\n source: 'cli',\n // #2522: the hand-off marker, set only when an agent is driving this CLI\n // and says so. Never inferred — a guess here mislabels a human's own run.\n ...(d.env.HAVEN_AGENT_DRIVEN === '1' ? { via: 'agent' } : {}),\n })\n\n if (!args.flags.run) {\n emit(d, args.flags.json, setup, () =>\n [\n 'Run this where the agent runs:',\n '',\n setup.connector_command,\n '',\n `Then approve the budget: ${setup.approval_url}`,\n `Setup ${setup.setup_id} expires ${setup.expires_at}.`,\n ].join('\\n'),\n )\n return EXIT.ok\n }\n\n // `--run`: execute the printed command with `--json` appended and nothing\n // else changed. The connector's stderr is streamed as it arrives — a run can\n // take minutes and that is the only progress anyone sees.\n const run = await runConnector(setup.connector_command, d.spawner, (chunk) => d.err(chunk.trimEnd()))\n const relay = relayLine(run.outcome)\n const merged = {\n setup_id: setup.setup_id,\n approval_url: setup.approval_url,\n connector_command: setup.connector_command,\n connector_exit_code: run.exitCode,\n outcome: run.outcome,\n relay,\n }\n\n if (isRefusal(run.outcome)) {\n // Exit 4 with the refusal carried whole. Recognised by the presence of\n // `error`, never by matching a code — a refusal the connector adds later\n // reaches the user through this same path with no CLI change.\n emitConnectResult(d, args.flags.json, merged, relay)\n return EXIT.refused\n }\n if (!run.outcome) {\n throw new HavenCliError(\n `The connector produced no outcome (exit ${run.exitCode}).${run.stdoutNoise ? ` Output: ${run.stdoutNoise}` : ''}`,\n run.exitCode === 0 ? EXIT.failed : EXIT.failed,\n )\n }\n emitConnectResult(d, args.flags.json, merged, relay)\n return EXIT.ok\n}\n\n/**\n * Print a `--run` result with the relay line FIRST under prose (#2483's\n * one-gate rule): whatever the human has to act on outranks the record of what\n * happened, because a link buried under an outcome dump is a link nobody sees.\n */\nfunction emitConnectResult(\n d: ResolvedDeps,\n json: boolean,\n merged: { relay: string | null; outcome: ConnectorOutcome | null; setup_id: string },\n relay: string | null,\n): void {\n emit(d, json, merged, () =>\n [relay, relay ? '' : null, `setup ${merged.setup_id}: ${merged.outcome?.outcome ?? 'unknown'}`]\n .filter((line) => line !== null)\n .join('\\n'),\n )\n}\n\n// ── Contacts ────────────────────────────────────────────────────────\n\nasync function cmdContactsList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const { contacts } = await api.get<{ contacts: Contact[] }>('/contacts')\n emit(d, args.flags.json, contacts, () =>\n contacts.length === 0\n ? 'No contacts yet.'\n : table(['ID', 'NAME', 'ADDRESS'], contacts.map((c) => [c.id, c.name, truncateAddress(c.address)])),\n )\n return EXIT.ok\n}\n\nasync function cmdContactsAdd(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const [address, ...nameParts] = [...args.positionals].reverse()\n // positionals are <name...> <address>; address is last, name is the rest.\n const name = nameParts.reverse().join(' ').trim()\n if (!name || !address) throw new UsageError('Usage: haven contacts add <name> <address>')\n const { api } = await authed(args, d)\n const contact = await api.post<Contact>('/contacts', { name, address })\n emit(d, args.flags.json, contact, () => `Added contact \"${contact.name}\" (${truncateAddress(contact.address)}).`)\n return EXIT.ok\n}\n\nasync function cmdContactsRemove(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven contacts remove <id>')\n const { api } = await authed(args, d)\n await api.del(`/contacts/${id}`)\n emit(d, args.flags.json, { ok: true, contact_id: id, removed: true }, () => `Contact ${id} removed.`)\n return EXIT.ok\n}\n\n// ── Feedback ──────────────────────────────────────────────────────────\n\n/**\n * `haven feedback submit \"<text>\"` (#3597). Several unquoted words are\n * JOINED into one text with a single space between them — the same\n * convention `contacts add <name...> <address>` already uses for its own\n * free-text argument — rather than refused, so a bug report does not have to\n * be hand-quoted.\n *\n * `authed` runs FIRST (a command with no session refuses before anything\n * else, same as every other command), then the secret check runs — and it\n * is the check, not `authed`, that has to run before the one call that would\n * carry the text (`api.post` at the end): a refusal here never reaches the\n * network at all.\n */\nasync function cmdFeedbackSubmit(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const text = args.positionals.join(' ').trim()\n if (!text) throw new UsageError('Usage: haven feedback submit \"<text>\"')\n // Code points, not UTF-16 units — `text.length` double-counts anything\n // outside the Basic Multilingual Plane (an emoji in a bug report is not\n // exotic), and the backend's own ceiling (`routes/feedback.ts`'s ajv\n // schema `maxLength`) counts code points too. `[...text]` iterates by\n // code point.\n if ([...text].length > MAX_FEEDBACK_TEXT_LENGTH) {\n throw new UsageError(`Feedback text must be ${MAX_FEEDBACK_TEXT_LENGTH} characters (code points) or fewer.`)\n }\n\n const { session, api } = await authed(args, d)\n\n const refusal = await checkTextForSecrets(text, {\n api,\n localSecrets: { sessionToken: session.token, env: d.env, baseDir: d.credentialsBaseDir },\n })\n if (refusal) {\n throw new HavenCliError(refusal.message, EXIT.refused, `layer ${refusal.layer}: ${refusal.reason}`, {\n layer: refusal.layer,\n reason: refusal.reason,\n })\n }\n\n // The one residual-risk case the check cannot catch by shape at all: a\n // plain password has no recognisable form. stderr only, so `--json`'s\n // stdout contract (one value, nothing else) stays exactly one value.\n d.o.note(\n 'Reminder: never include a password or any other credential in feedback text — this check cannot recognise one by shape.',\n )\n\n const result = await api.post<{ id: string; created_at: string; expires_at: string }>('/feedback', { text })\n emit(d, args.flags.json, { ok: true, ...result }, () => `Feedback submitted (id ${result.id}).`)\n return EXIT.ok\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/args.ts","../src/api.ts","../src/session.ts","../src/format.ts","../src/csv.ts","../src/errors.ts","../src/output.ts","../src/agent-guidance-text.ts","../src/token.ts","../src/amount.ts","../src/connect-runner.ts","../../../node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/sha3.ts","../../../node_modules/@scure/bip39/esm/wordlists/english.js","../src/secret-check.ts","../src/commands.ts"],"names":["resolve","readFile","join","homedir","run","refusal"],"mappings":";;;;;;;AAyFA,IAAM,WAAA,uBAAkB,GAAA,CAAI;AAAA,EAC1B,OAAA;AAAA,EAAS,SAAA;AAAA,EAAW,QAAA;AAAA,EAAU,SAAA;AAAA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AAA,EAAI,IAAA,EAAM,GAAG,MAAA,EAAO,EAAG,MAAM,CAAA,uBAAA,EAA0B,MAAA,CAAO,EAAE,CAAA,EAAA,CAAI,CAAA;AAC/F,EAAA,OAAO,IAAA,CAAK,EAAA;AACd","file":"index.js","sourcesContent":["export interface ParsedArgs {\n command?: string\n sub?: string\n positionals: string[]\n flags: {\n json: boolean\n help: boolean\n /** #2526: print the code and exit instead of polling for approval. */\n noWait: boolean\n /** #2527: run the printed connector command as a child process. */\n run: boolean\n /** #2527: poll `agents connect --status` until it settles. */\n wait: boolean\n /**\n * #2612: list the delegation HASHES on `budget show`, which is the only\n * thing `budget revoke` accepts as its second argument. Behind a flag\n * because `budget show --json` has emitted a bare allowances array since\n * the first CLI scaffold, and a second shape on the same command would\n * break every existing consumer of it.\n */\n hashes: boolean\n version: boolean\n yes: boolean\n /**\n * #3729: override for `agents revoke` — revoke the agent even though a\n * budget delegation is still live on-chain (pending, active or replaced),\n * saying so out loud instead of silently leaving the budget redeemable.\n * Without it the command refuses and lists the exact `haven budget\n * revoke` command for each live row.\n */\n keepBudget: boolean\n api?: string\n email?: string\n safe?: string\n agent?: string\n limit?: number\n offset?: number\n direction?: 'in' | 'out'\n format?: string\n from?: string\n to?: string\n company?: string\n /** #2527 */\n name?: string\n budget?: string\n token?: string\n period?: number\n status?: string\n /**\n * #2539: the budget magnitude for `budget grant`, in whole tokens as you\n * would say it (`25` is 25 USDC) — parsed to atomic units with decimals\n * read from the backend, exactly like `agents connect`'s --budget. Named\n * --amount because the issue's command sketch does, and because a grant\n * is not the same decision as a connect.\n */\n amount?: string\n /**\n * #2539: optional recipient pin for `budget grant`. An ADDRESS the budget\n * may pay and nobody else — the caveat enforcer set at build time. Absent\n * means an open budget, exactly like the dashboard form's blank field.\n */\n recipient?: string\n /**\n * #2539: optional expiry (unix seconds) for `budget grant`. Absent lets\n * the backend default (now + 90 days), the same default the dashboard's\n * builds get.\n */\n expires?: number\n /**\n * #2618: the device code for `haven login --poll <device_code>` — ONE poll\n * round against POST /auth/device/token, for an agent that printed the\n * link with `--no-wait` and came back later. The value is REQUIRED: a bare\n * `--poll` would look like it resumed something.\n */\n poll?: string\n /**\n * #2527: deliberately absent — `--recipient` for `agents connect`. The\n * issue sketched one, and neither `POST /agents` nor\n * `POST /agent-connection-setups` has a field to\n * put it in: a recipient pin lives in the delegation's caveat enforcers and\n * is set when the human approves the budget. A flag accepted here would\n * either be silently dropped or invent a wire field, and a budget control\n * that looks applied and is not is worse than one you cannot ask for.\n * (Note: `budget grant` DOES take `--recipient` — the delegation build\n * route has that field; connect does not.)\n */\n }\n}\n\nconst VALUE_FLAGS = new Set([\n '--api', '--email', '--safe', '--agent', '--limit', '--offset', '--direction',\n '--format', '--from', '--to', '--company',\n '--name', '--budget', '--token', '--period', '--status',\n '--amount', '--recipient', '--expires', '--poll',\n])\n\n/**\n * `haven <command> [sub] [positionals] [--flags]`. Deliberately small — no\n * dependency, no clever aliasing. Unknown flags throw so typos fail loudly.\n */\nexport function parseArgs(argv: string[]): ParsedArgs {\n const positionals: string[] = []\n const flags: ParsedArgs['flags'] = {\n json: false, help: false, version: false, yes: false, noWait: false, run: false, wait: false, hashes: false, keepBudget: false,\n }\n\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i]\n if (arg === '--json') flags.json = true\n else if (arg === '--help' || arg === '-h') flags.help = true\n else if (arg === '--version' || arg === '-v') flags.version = true\n else if (arg === '--yes' || arg === '-y') flags.yes = true\n else if (arg === '--keep-budget') flags.keepBudget = true\n else if (arg === '--no-wait') flags.noWait = true\n else if (arg === '--run') flags.run = true\n else if (arg === '--wait') flags.wait = true\n else if (arg === '--hashes') flags.hashes = true\n else if (VALUE_FLAGS.has(arg)) {\n const value = argv[++i]\n if (value === undefined || value.startsWith('--')) {\n throw new Error(`Missing value for ${arg}`)\n }\n if (arg === '--api') flags.api = value\n else if (arg === '--name') flags.name = value\n else if (arg === '--budget') flags.budget = value\n else if (arg === '--token') flags.token = value\n else if (arg === '--status') flags.status = value\n else if (arg === '--period') {\n const n = Number(value)\n if (!Number.isInteger(n) || n < 0) throw new Error('--period must be a whole number of minutes')\n flags.period = n\n }\n else if (arg === '--email') flags.email = value\n else if (arg === '--safe') flags.safe = value\n else if (arg === '--agent') flags.agent = value\n else if (arg === '--limit') {\n const n = Number(value)\n if (!Number.isInteger(n) || n <= 0) throw new Error('--limit must be a positive integer')\n flags.limit = n\n } else if (arg === '--offset') {\n const n = Number(value)\n if (!Number.isInteger(n) || n < 0) throw new Error('--offset must be a non-negative integer')\n flags.offset = n\n } else if (arg === '--direction') {\n if (value !== 'in' && value !== 'out') throw new Error('--direction must be \"in\" or \"out\"')\n flags.direction = value\n } else if (arg === '--recipient') {\n flags.recipient = value\n } else if (arg === '--amount') {\n flags.amount = value\n } else if (arg === '--expires') {\n const n = Number(value)\n if (!Number.isInteger(n) || n <= 0) throw new Error('--expires must be a unix timestamp in seconds')\n flags.expires = n\n } else if (arg === '--format') {\n if (value !== 'csv' && value !== 'sie') throw new Error('--format must be \"csv\" or \"sie\"')\n flags.format = value\n } else if (arg === '--poll') {\n flags.poll = value\n } else if (arg === '--from') flags.from = value\n else if (arg === '--to') flags.to = value\n else if (arg === '--company') flags.company = value\n } else if (arg.startsWith('--')) {\n throw new Error(`Unknown option: ${arg}`)\n } else {\n positionals.push(arg)\n }\n }\n\n const [command, sub, ...rest] = positionals\n return { command, sub, positionals: rest, flags }\n}\n\nexport function helpText(): string {\n return [\n 'haven — set up and run a Haven agent from the terminal. It never signs.',\n '',\n 'Usage: haven <command> [subcommand] [options]',\n '',\n 'Auth:',\n ' login Sign in. Opens a browser device-code approval by default —',\n ' it prints a code and a link, and never asks for a password',\n ' login --email <e> Password path instead (prompt, or HAVEN_PASSWORD)',\n ' login --no-wait Print the link and exit instead of polling. Under --json,',\n ' pass it: you get the object back at once (it carries',\n ' device_code) and finish with `login --poll <device_code>`',\n ' login --poll <code> One poll round of a started device flow: exit 0 approved,',\n ' 3 still pending (the object carries retry_after), 4 denied',\n ' logout Clear the saved session',\n ' whoami Show the signed-in user, session expiry and API URL',\n '',\n 'For agents:',\n ' guide Print the agent onboarding runbook (same text as /for-agents.md)',\n ' agents connect --name <n> --budget <amount> --token USDC --period <minutes>',\n ' Create a connection setup; prints the connector command and',\n ' the approval link for your human. --run executes it here.',\n ' agents connect --status <setupId> [--wait] Read one setup\\'s status',\n '',\n 'Read:',\n ' wallets list List your Haven wallets',\n ' wallets balances [--safe <id|address>] Token balances for a wallet',\n ' wallets funding [--safe <id|address>] [--wait] The paste-ready funding',\n ' instruction: what to send, where, on which chain.',\n ' --wait polls until the account counts as funded.',\n ' agents list List your agents',\n ' agents show <id> Show one agent + its budget',\n ' budget show <agentId> Show an agent\\'s configured budget',\n ' budget show <agentId> --hashes Its delegation hashes — the second',\n ' argument `budget revoke` takes, printed nowhere else',\n ' activity list [--safe <id|address>] [--agent <id>] [--direction in|out] [--limit <n>] [--offset <n>]',\n ' Wallet-scoped history; --agent narrows it (--json rows carry scope, timestampSource)',\n ' activity export [filters] Emit CSV to stdout (--format csv, default)',\n ' activity export --format sie [--from <ISO>] [--to <ISO>] [--company <name>]',\n ' Bookkeeping-ready SIE 4I (Fortnox/Visma/Bokio)',\n ' catalog list List payable services',\n ' contacts list List your address book',\n '',\n 'Feedback:',\n ' feedback submit \"<text>\" Send feedback or a bug report. Needs',\n ' `haven login`. It refuses to send text that',\n ' looks like a credential, but cannot catch',\n ' every secret shape — never include one.',\n '',\n 'Manage (backend-only — no on-chain signing):',\n ' agents pause <id> Block payments through Haven; the budget',\n ' stays live on-chain (end it: budget revoke)',\n ' agents resume <id> Allow payments through Haven again',\n ' agents revoke <id> --yes Retire the agent in Haven (terminal). Ends no',\n ' budget on-chain: run budget revoke first; refuses',\n ' while a budget is still live unless --keep-budget',\n ' agents rotate-key <id> Issue a new API key (shown once)',\n ' agents rename <id> <name>',\n ' wallets rename <id> <name>',\n ' contacts add <name> <address> Save an address under a name',\n ' contacts remove <id> Forget one',\n '',\n 'Budgets (construct-and-hand-off — the CLI never signs, #2539):',\n ' budget grant <agentId> --amount <n> --token USDC --period <minutes>',\n ' [--recipient <address>] [--expires <unix-s>] [--wait]',\n ' Prints a signing link; the human signs in the dashboard.',\n ' budget revoke <agentId> <delegationHash> [--wait]',\n ' Prints a revocation link; the human signs in the dashboard.',\n '',\n 'Options:',\n ' --json One JSON value on stdout, prose on stderr, on every',\n ' command including refusals: { ok: false, error: { code, message, hint? } }',\n ' --yes, -y Skip the confirmation prompt for destructive actions',\n ' --api <url> Backend URL. Default: HAVEN_API_URL, else Haven\\'s hosted',\n ' production backend — NOT localhost. On any other',\n ' deployment an omitted flag connects to production.',\n ' --help, --version',\n '',\n 'Exit codes: 0 ok · 1 failed · 2 usage · 3 not authenticated · 4 refused · 5 network',\n '',\n 'On-chain actions (deploy, budgets, approvers, send) are signed in the',\n 'dashboard — this CLI reads and manages; it never holds your keys.',\n ].join('\\n')\n}\n","export class CliApiError extends Error {\n status: number\n /**\n * The parsed response body, when there was one (#2526).\n *\n * The message is built FROM `body.error` for humans, and the device flow\n * needs the same value as DATA: `authorization_pending` and `slow_down` are\n * control signals in a poll loop, and branching on them by matching the\n * message string would make the loop depend on prose that is free to change.\n */\n body?: unknown\n constructor(message: string, status: number, body?: unknown) {\n super(message)\n this.name = 'CliApiError'\n this.status = status\n this.body = body\n }\n}\n\nexport interface CliApi {\n get<T>(path: string): Promise<T>\n post<T>(path: string, body?: unknown): Promise<T>\n put<T>(path: string, body?: unknown): Promise<T>\n del<T>(path: string): Promise<T>\n /** GET a non-JSON body (e.g. an export file) as raw text. */\n getText(path: string): Promise<string>\n}\n\nexport interface CreateCliApiOptions {\n baseUrl: string\n token?: string\n fetchImpl?: typeof fetch\n /**\n * #3303: `@haven_ai/cli/<version>`, sent as `X-Haven-Client` so the backend\n * can tell an outdated CLI what to run. Passed in by `commands.ts`, which\n * owns `CLI_VERSION`, rather than imported here (commands.ts imports this file).\n */\n clientIdentity?: string\n}\n\n/**\n * Minimal JSON client for the Haven backend. Sends the user JWT as a Bearer\n * token when present, and surfaces backend `{ error }` messages as\n * `CliApiError` so commands can print something human.\n */\nexport function createCliApi({ baseUrl, token, fetchImpl = fetch, clientIdentity }: CreateCliApiOptions): CliApi {\n const root = baseUrl.replace(/\\/+$/, '')\n\n async function request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = { Accept: 'application/json' }\n if (token) headers.Authorization = `Bearer ${token}`\n if (clientIdentity) headers['X-Haven-Client'] = clientIdentity\n if (body !== undefined) headers['Content-Type'] = 'application/json'\n\n let res: Response\n try {\n res = await fetchImpl(`${root}${path}`, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : undefined,\n })\n } catch (err) {\n throw new CliApiError(\n `Could not reach Haven at ${root}: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n }\n\n if (res.status === 401) {\n throw new CliApiError('Not authenticated. Run `haven login` first.', 401)\n }\n\n const text = await res.text()\n const payload = text ? safeParse(text) : undefined\n\n if (!res.ok) {\n const message =\n (payload && typeof payload === 'object' && 'error' in payload && typeof payload.error === 'string'\n ? payload.error\n : null) ?? `Request failed (HTTP ${res.status}).`\n throw new CliApiError(message, res.status, payload)\n }\n\n return payload as T\n }\n\n async function requestText(path: string): Promise<string> {\n const headers: Record<string, string> = { Accept: 'text/plain' }\n if (token) headers.Authorization = `Bearer ${token}`\n if (clientIdentity) headers['X-Haven-Client'] = clientIdentity\n\n let res: Response\n try {\n res = await fetchImpl(`${root}${path}`, { method: 'GET', headers })\n } catch (err) {\n throw new CliApiError(\n `Could not reach Haven at ${root}: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n )\n }\n\n if (res.status === 401) {\n throw new CliApiError('Not authenticated. Run `haven login` first.', 401)\n }\n\n const text = await res.text()\n if (!res.ok) {\n const payload = text ? safeParse(text) : undefined\n const message =\n (payload && typeof payload === 'object' && 'error' in payload && typeof payload.error === 'string'\n ? payload.error\n : null) ?? `Request failed (HTTP ${res.status}).`\n throw new CliApiError(message, res.status)\n }\n return text\n }\n\n return {\n get: <T>(path: string) => request<T>('GET', path),\n post: <T>(path: string, body?: unknown) => request<T>('POST', path, body),\n put: <T>(path: string, body?: unknown) => request<T>('PUT', path, body),\n del: <T>(path: string) => request<T>('DELETE', path),\n getText: (path: string) => requestText(path),\n }\n}\n\nfunction safeParse(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n","import { mkdir, readFile, rm, writeFile, chmod } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\n/**\n * The signed-in user session. The token is a *user* JWT (same credential the\n * dashboard holds) — treat it like a secret: stored owner-only, never logged,\n * never sent anywhere but the Haven API. `apiBaseUrl` is pinned at login so\n * later commands talk to the same backend.\n */\nexport interface Session {\n token: string\n apiBaseUrl: string\n user: { id: string; email: string; name: string | null }\n}\n\nexport interface SessionStore {\n load(): Promise<Session | null>\n save(session: Session): Promise<void>\n clear(): Promise<void>\n path: string\n}\n\nfunction sessionDir(homeDir: string): string {\n return resolve(homeDir, '.haven')\n}\n\nexport function sessionPath(homeDir: string = homedir()): string {\n return join(sessionDir(homeDir), 'session.json')\n}\n\n/** File-backed session store, owner-only perms (0600 file in a 0700 dir). */\nexport function createSessionStore(homeDir: string = homedir()): SessionStore {\n const path = sessionPath(homeDir)\n return {\n path,\n async load() {\n try {\n const raw = await readFile(path, 'utf8')\n const parsed = JSON.parse(raw) as Partial<Session>\n if (!parsed.token || !parsed.apiBaseUrl || !parsed.user) return null\n return parsed as Session\n } catch {\n return null\n }\n },\n async save(session) {\n await mkdir(sessionDir(homeDir), { recursive: true, mode: 0o700 })\n await writeFile(path, `${JSON.stringify(session, null, 2)}\\n`, { mode: 0o600 })\n await chmod(path, 0o600).catch(() => undefined)\n },\n async clear() {\n await rm(path, { force: true })\n },\n }\n}\n","/** Tiny fixed-width table for human output. Scriptable callers use `--json`. */\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n )\n const line = (cells: string[]) =>\n cells.map((c, i) => (c ?? '').padEnd(widths[i])).join(' ').trimEnd()\n return [line(headers), line(widths.map((w) => '-'.repeat(w))), ...rows.map(line)].join('\\n')\n}\n\nexport function truncateAddress(address: string): string {\n if (!address || address.length <= 12) return address\n return `${address.slice(0, 6)}…${address.slice(-4)}`\n}\n\nconst CHAIN_NAMES: Record<number, string> = { 8453: 'Base', 84532: 'Base Sepolia' }\n\nexport function chainName(chainId: number): string {\n return CHAIN_NAMES[chainId] ?? `chain ${chainId}`\n}\n\n/**\n * \"5m ago\", \"2h ago\", \"3d ago\" — the ladder the dashboard's stale-balance\n * indicator renders (`packages/frontend/src/components/haven/\n * BalanceFreshnessIndicator.tsx`), lifted for the CLI so both surfaces word\n * the same wire marker the same way. Just-now keeps both boundaries the\n * frontend's helper keeps: a clock slightly ahead of the read, and reads\n * younger than a minute.\n */\nexport function timeAgo(iso: string): string {\n const diff = Date.now() - new Date(iso).getTime()\n if (diff < 60_000) return 'just now'\n const mins = Math.floor(diff / 60_000)\n if (mins < 60) return `${mins}m ago`\n const hours = Math.floor(mins / 60)\n if (hours < 24) return `${hours}h ago`\n const days = Math.floor(hours / 24)\n if (days < 30) return `${days}d ago`\n const months = Math.floor(days / 30)\n if (months < 12) return `${months}mo ago`\n return `${Math.floor(days / 365)}y ago`\n}\n","/**\n * CSV serialization for `haven activity export`. Mirrors the dashboard export\n * (#411): RFC 4180 quoting, CRLF line endings, and a spreadsheet\n * formula-injection guard. Kept self-contained so the CLI has no @haven_ai/*\n * runtime dependency.\n */\n\n/** Quote per RFC 4180 and neutralise leading =,+,-,@ (Excel formula injection). */\nfunction csvField(value: string): string {\n let v = value\n if (/^[=+\\-@\\t\\r]/.test(v)) v = `'${v}`\n return `\"${v.replace(/\"/g, '\"\"')}\"`\n}\n\nexport function toCsv(headers: string[], rows: string[][]): string {\n const lines = [headers.join(','), ...rows.map((r) => r.map(csvField).join(','))]\n return lines.join('\\r\\n')\n}\n","import { CliApiError } from './api.js'\n\n/**\n * Exit codes (#2525). Documented in README.md § For agents and scripts, and\n * asserted in `json-contract.test.ts` (every code, over the whole command list)\n * and `commands.test.ts` (the individual commands that produce them) — an agent\n * branches on these, so they are a contract rather than an implementation\n * detail.\n */\nexport const EXIT = {\n ok: 0,\n /** Something failed and none of the specific codes below describe it. */\n failed: 1,\n /** The command line was wrong: unknown command, missing argument, bad flag. */\n usage: 2,\n /** No stored session, or the backend rejected the one we have. Log in again. */\n notAuthenticated: 3,\n /** Authenticated, and the backend refused anyway (403, 410, other 4xx). */\n refused: 4,\n /** The backend could not be reached at all. */\n network: 5,\n} as const\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT]\n\n/** Machine-readable `error.code` values, one per exit code above 0. */\nexport type FailureCode = 'failed' | 'usage' | 'not_authenticated' | 'refused' | 'network'\n\n/** A wrong command line. Carries `usage` so callers do not guess the exit code. */\nexport class UsageError extends Error {\n readonly hint?: string\n constructor(message: string, hint?: string) {\n super(message)\n this.name = 'UsageError'\n this.hint = hint\n }\n}\n\n/**\n * A failure that already knows its exit code (#2526).\n *\n * The device flow's outcomes are not exceptions in the usual sense — a denied\n * approval and an expired code are ordinary, expected answers — but they must\n * still exit non-zero with the RIGHT code, because that is the contract an\n * agent reads. Carrying the code on the error keeps the decision at the place\n * that knows the outcome rather than in a string match downstream.\n */\nexport class HavenCliError extends Error {\n readonly exit: ExitCode\n readonly hint?: string\n /**\n * #3597: additional typed fields merged into the `--json` error object\n * (`error.layer`, `error.reason`, …) — for a refusal where the FREE-TEXT\n * hint is not enough to branch on. `feedback submit`'s secret check is the\n * first caller: an agent needs `error.layer` (which of the four checks\n * refused) as a number, not a string it has to parse out of a sentence.\n */\n readonly extra?: Record<string, unknown>\n constructor(message: string, exit: ExitCode, hint?: string, extra?: Record<string, unknown>) {\n super(message)\n this.name = 'HavenCliError'\n this.exit = exit\n this.hint = hint\n this.extra = extra\n }\n}\n\nexport interface Failure {\n code: FailureCode\n exit: ExitCode\n message: string\n hint?: string\n extra?: Record<string, unknown>\n}\n\n/**\n * One place that decides what an error means, so the JSON body and the exit\n * code cannot disagree — they are read off the same object.\n *\n * **On 401 → `not_authenticated`, not `refused`.** The issue lists 401\n * alongside 403/410 under \"refused by the backend\", and separately lists\n * \"not logged in / session expired\" — the two overlap, and a 401 is exactly\n * the second one. An agent seeing `not_authenticated` knows to re-run\n * `haven login`; `refused` tells it the opposite (the session is fine, the\n * action is not allowed). Splitting them on the wire is the whole point of\n * having two codes, so 401 resolves to the one it can act on.\n */\nexport function toFailure(err: unknown): Failure {\n if (err instanceof UsageError) {\n return { code: 'usage', exit: EXIT.usage, message: err.message, hint: err.hint }\n }\n if (err instanceof HavenCliError) {\n // The error already decided; this only translates the number to its slug,\n // so the JSON body and the exit code still come off one object.\n const code: FailureCode =\n err.exit === EXIT.notAuthenticated\n ? 'not_authenticated'\n : err.exit === EXIT.refused\n ? 'refused'\n : err.exit === EXIT.network\n ? 'network'\n : 'failed'\n return { code, exit: err.exit, message: err.message, hint: err.hint, extra: err.extra }\n }\n if (err instanceof CliApiError) {\n if (err.status === 0) {\n return {\n code: 'network',\n exit: EXIT.network,\n message: err.message,\n hint: 'Check the network and `--api`, then retry.',\n }\n }\n if (err.status === 401) {\n return {\n code: 'not_authenticated',\n exit: EXIT.notAuthenticated,\n message: err.message,\n // #2618: the device flow is named FIRST because it is the path an\n // agent can actually run — an agent never holds its user's password,\n // which is the runbook's first rule; the previous hint led with the\n // credentials as if they were the normal route. HAVEN_EMAIL and\n // HAVEN_PASSWORD remain for a HUMAN scripting non-interactively.\n hint: 'Run `haven login` (device flow — 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.',\n }\n }\n if (err.status >= 400 && err.status < 500) {\n // 403 and 410 are the named cases; every other 4xx is the same shape of\n // answer — the backend understood and said no — so it gets the same code\n // rather than falling through to the generic one.\n return { code: 'refused', exit: EXIT.refused, message: err.message }\n }\n return { code: 'failed', exit: EXIT.failed, message: err.message }\n }\n return { code: 'failed', exit: EXIT.failed, message: err instanceof Error ? err.message : String(err) }\n}\n","import type { Failure } from './errors.js'\n\n/**\n * The `--json` contract (#2525).\n *\n * Under `--json`, **stdout carries exactly one JSON value and nothing else** —\n * every line of human prose goes to stderr instead. That is what lets an agent\n * pipe stdout straight into a parser without stripping progress chatter, and\n * it is why `note()` exists: the same call site prints a sentence for a human\n * and stays silent (on stdout) for a machine.\n *\n * Success keeps the payload shape each command already emitted — including the\n * bare arrays that `agents list` and friends return — so this change adds a\n * failure contract without breaking a script that already parses a success.\n * Failures are always the object `{ ok: false, error: { code, message, hint? } }`.\n */\nexport interface Output {\n readonly json: boolean\n /** The command's success payload. At most one per run, on stdout. */\n data(payload: unknown, human: () => string): void\n /** Raw text (an export file). Printed as-is; wrapped under `--json`. */\n text(content: string, meta: Record<string, unknown>): void\n /** Human prose. Stdout in prose mode; stderr under `--json`. */\n note(line: string): void\n /** The one failure object. Always stdout under `--json`, stderr otherwise. */\n failure(failure: Failure): void\n}\n\nexport function createOutput(\n json: boolean,\n out: (line: string) => void,\n err: (line: string) => void,\n): Output {\n return {\n json,\n data(payload, human) {\n out(json ? JSON.stringify(payload, null, 2) : human())\n },\n text(content, meta) {\n // A CSV/SIE body is the payload in prose mode. Under --json it becomes a\n // field of the single object, so the contract (\"one JSON value on\n // stdout\") holds for exports too and the content stays recoverable.\n out(json ? JSON.stringify({ ok: true, ...meta, content }, null, 2) : content)\n },\n note(line) {\n if (json) err(line)\n else out(line)\n },\n failure(failure) {\n const body = {\n ok: false as const,\n error: {\n // `extra` spreads FIRST (#3597 round 2, N-a): it is per-command\n // (e.g. the secret check's `layer`/`reason`), so it must never be\n // able to clobber the contract fields every command shares —\n // `code`, `message`, `hint` are spread AFTER and always win.\n ...(failure.extra ?? {}),\n code: failure.code,\n message: failure.message,\n ...(failure.hint ? { hint: failure.hint } : {}),\n },\n }\n if (json) out(JSON.stringify(body, null, 2))\n else err(failure.hint ? `${failure.message}\\n${failure.hint}` : failure.message)\n },\n }\n}\n","/**\n * The agent onboarding runbook — GENERATED, do not edit by hand.\n *\n * Canonical source: `packages/sdk/src/agent-guidance.ts` (#2523), served to\n * agents at `/for-agents.md`. This is a decoupled copy so `@haven_ai/cli`\n * keeps zero runtime dependencies: importing it from the SDK would put ethers,\n * viem and x402 on the `npx @haven_ai/cli` path for one Markdown string.\n * Same arrangement, and the same reason, as\n * `packages/frontend/src/lib/agent-skill-bundle.ts`.\n *\n * Regenerate: node packages/cli/scripts/sync-agent-guidance.mjs\n * The parity test in `agent-guidance-text.test.ts` fails if you forget.\n */\n\nexport const HAVEN_AGENT_RUNBOOK_MD = \"# Haven for agents — 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** — 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 — 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 — 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, `<packages.cli.one_liner> login --api <api-url>` afterwards gets you a scoped session for steps 3-4 (that flag or `HAVEN_API_URL`, on the first command — 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) — they approve a code in the browser, you never hold their password. That command is the manifest's `packages.cli.one_liner` (`/.well-known/haven.json`) — run it as given: `packages.cli.channel` serves the full spec. 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>` — 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 — fund it.** USDC only, no ETH: Haven sponsors the gas. `/.well-known/haven.json` names `chains.default` as the deployment's expected chain, but after login `haven wallets funding` prints the address, the amount and which chain in one place; confirm that chain before you message your user. Without a CLI session, the dashboard's funding card shows the address and amount and its Receive-funds screen names the chain; never assume one: a testnet deployment and production both call themselves Haven. Before you write that message, read the manifest: `environment` says whether this deployment is `production`, and each `chains.supported` entry says whether that chain is a `testnet`. Real money is at stake only on a non-testnet chain of a `production` deployment — tell your user which case theirs is.\\n3. **HUMAN — 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 — run the connector command** in that prompt (see What you run). It makes your signing key locally, registering only the public address.\\n5. **HUMAN — 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 — verify, then pay.**\\n\\n## Budget changes later (second token, raise, revoke)\\n\\nThe first budget rides the setup in The sequence. After the agent exists, a CLI session can construct the LATER changes — a second token, a bigger amount, a recipient pin, a stop — 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 budget show <agentId> --hashes`.\\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` — 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 — 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 — USDC only, no ETH: Haven sponsors the gas. Before you send anything, let me get you the exact address **and network** — `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 — 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) — 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 — 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 — 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 — if the outcome carries approval.url, give me that link; otherwise tell me to return to Haven and approve this agent's budget — 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 — the approval link if those steps printed one, otherwise that you need to return to Haven and approve this agent's budget — 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 three changes to the command above are permitted, and no others: appending --json; re-running it once with --runtime <name> added, only if the connector refuses because it could not determine the agent runtime, naming the harness you are running in and using one of the values that refusal lists; and re-running it once with the one flag I chose added, only after I have answered a wiring_collision relay — --name <the suggested_name or a name I gave> to add alongside, or --replace to replace — keeping any change already made. If that re-run is refused too, relay the refusal to me and stop. 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 — 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 — 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` — a budget is live: you have the authority to pay. It does not say the account holds funds — the `allowances[]` rows carry `funds_cover_remaining`, and `false` there is a heads-up to mention to your user, not a refusal.\\n- `needs_approval` — the connector finished, nobody approved yet. Ask your user again, in their Haven tab; there is no queue to wait in.\\n- `revoked` — 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 — a separate command, so the command-modification rule does not bind it.\\n\\n## If you cannot open a browser\\n\\nNothing here needs you to. Steps 1-3 — account, funding, budget — are links: hand your user the full `<host>/…` URL and ask them to say when it is done. Step 5 is a link only when your run reported one in `approval.url` — otherwise it is the tab they already have open. Then poll `haven_get_agent` until it reads `ready`. Do not route around the sign-in wall — it makes the account theirs, not yours.\\n\\n## If something breaks\\n\\nIf a Haven result carries `client_update`, that client is out of date: run its `upgrade_command` exactly as given — a connector command may name your pair with `--name <slug>` — then any repair line it prints, then retry. `required: true` means payments are refused until you do. What changed: [/releases](/releases).\\n\\nSomething else wrong? `haven feedback submit \\\"<text>\\\"` sends it to Haven — it needs `haven login` first. Never put a credential in that text: no API key, no delegate key, no session token, no recovery phrase.\\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@…` line you run. One-time token, one use. |\\n| **agent credential** | Your API key (`sk_agent_…`), 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) · [everything agent-readable](/llms.txt)\\n\"\n","/**\n * Read the expiry out of the stored session JWT (#2525).\n *\n * `whoami --json` and `login --json` report when the session dies, and the\n * only place that fact exists is the token's own `exp` claim — the backend\n * signs it with `expiresIn: '7d'` (`routes/auth.ts`) and `/auth/me` does not\n * return it. So the payload segment is base64url-decoded and read.\n *\n * This deliberately does NOT verify the signature, and must never be used to\n * decide anything but what to print: the CLI has no key to verify with, and a\n * forged `exp` would only mislead the user about a token the backend will\n * reject on its own terms. It never logs, echoes or returns the token itself.\n */\nexport function sessionExpiry(token: string): string | null {\n const segment = token.split('.')[1]\n if (!segment) return null\n try {\n const json = Buffer.from(segment.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')\n const claims = JSON.parse(json) as { exp?: unknown }\n if (typeof claims.exp !== 'number' || !Number.isFinite(claims.exp)) return null\n return new Date(claims.exp * 1000).toISOString()\n } catch {\n // A token we cannot read is not an error worth failing a command over —\n // the expiry is informational, and every other field still resolves.\n return null\n }\n}\n","/**\n * Human token amounts → atomic units, without a dependency (#2527).\n *\n * ## Why this exists rather than `parseUnits`\n *\n * The dashboard modal converts with viem's `parseUnits` before it POSTs\n * (`useAgentConnectionSetup.ts`), and this CLI has to produce the same string\n * for the same input. It cannot call the same function: `@haven_ai/cli` ships\n * with **zero runtime dependencies** — asserted by a test, because `npx\n * @haven_ai/cli` is the path an agent uses and viem's tree is ~94 MB — so this\n * is the arithmetic done in strings over Node builtins.\n *\n * ## The two shapes, and why this direction is the dangerous one\n *\n * `allowance_amount` is ATOMIC on the way in and HUMAN-DECIMAL on the way back\n * (#2295). One name, two shapes. Nothing here sniffs which it is holding: the\n * caller says, and this function only ever converts human → atomic. A number\n * that is wrong by 10^6 is a budget that is wrong by a factor of a million.\n *\n * ## Excess precision is REFUSED, never rounded\n *\n * `parseUnits` ROUNDS the excess rather than dropping it, which is worse than\n * it sounds: measured against viem, `parseUnits('1.9999999', 6)` is `2000000n`\n * — **two whole tokens** — and `parseUnits('0.0000005', 6)` is `1n`, a budget\n * conjured out of a value below the token's precision. An earlier version of\n * this comment said it truncates to `1999999n`; that was wrong, and the truth\n * is the stronger argument for refusing (haven-reviewer, #2527).\n *\n * For a field a person typed and is about to authorise, quietly changing the\n * number is worse than declining it, so this mirrors the modal's own\n * `validateMoneyInput`, which refuses before it ever reaches `parseUnits`. The\n * rule is the same on both surfaces on purpose: a budget the dashboard would\n * not accept must not become acceptable by being typed into a terminal.\n */\n\nexport interface AmountResult {\n ok: true\n /** The normalised human string, e.g. `.5` → `0.5`. */\n human: string\n /** Atomic units as a decimal string — what the wire wants. */\n atomic: string\n}\n\nexport interface AmountRefusal {\n ok: false\n message: string\n}\n\nfunction decimalLabel(decimals: number): string {\n return decimals === 1 ? '1 decimal place' : `${decimals} decimal places`\n}\n\n/**\n * Convert a human amount to atomic units for a token with `decimals`.\n *\n * Refuses rather than guesses: anything that is not a plain non-negative\n * decimal, anything that is zero, and anything carrying more fraction digits\n * than the token can represent.\n */\nexport function parseTokenAmount(\n input: string,\n decimals: number,\n tokenSymbol?: string,\n): AmountResult | AmountRefusal {\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 36) {\n return { ok: false, message: `Unusable token decimals: ${String(decimals)}` }\n }\n\n // `.5` → `0.5`, matching the modal's `normalizeMoneyInput` so the two\n // surfaces accept the same set of strings.\n const trimmed = String(input ?? '').trim()\n const human = trimmed.startsWith('.') ? `0${trimmed}` : trimmed\n const label = tokenSymbol ? ` ${tokenSymbol}` : ''\n\n if (human === '') return { ok: false, message: 'Enter an amount greater than 0' }\n // No sign, no exponent, no separators. `1e6` and `1_000` are the shapes most\n // likely to be meant well and read wrong, so they are refused by omission.\n if (!/^\\d+(?:\\.\\d+)?$/.test(human)) {\n return { ok: false, message: `Enter a valid${label} amount — digits, with an optional decimal point` }\n }\n\n const [whole, fraction = ''] = human.split('.')\n if (fraction.length > decimals) {\n return {\n ok: false,\n message: `${tokenSymbol ?? 'This token'} supports up to ${decimalLabel(decimals)}`,\n }\n }\n\n // Right-pad the fraction to the token's precision and concatenate: the whole\n // conversion, with no float anywhere near it. BigInt then strips leading\n // zeros, so `0.5` at 6 decimals is `500000` rather than `0500000`.\n const atomic = BigInt(`${whole}${fraction.padEnd(decimals, '0')}`)\n if (atomic === 0n) return { ok: false, message: 'Enter an amount greater than 0' }\n\n return { ok: true, human, atomic: atomic.toString() }\n}\n","import { spawn } from 'node:child_process'\n\n/**\n * Running the connector as a child process, for `haven agents connect --run`\n * (#2527).\n *\n * ## The command is not ours to edit\n *\n * The backend builds `connector_command` and the setup prompt states the rule\n * an agent must follow: the command may be changed in only the ways it\n * lists, and appending `--json` is one of them. So this splits the printed command and\n * appends `--json` — nothing else. It does not add `--replace`, it does not add\n * `--name`, it does not rewrite `--api`, and it never composes a command of its\n * own. `haven agents connect` has no flags for those on purpose: a wiring\n * collision is a decision for the human, and a CLI that could resolve one would\n * be making that decision on their behalf (boundary note on #2527 from #2551).\n *\n * ## Why the exit code is not the verdict\n *\n * The connector exits **1** on a refusal while still writing a complete outcome\n * object to stdout (`cli.test.ts`, the `wiring_collision` case). Treating a\n * non-zero exit as \"it did not run\" would throw away exactly the structured\n * refusal the human needs. So the outcome is parsed from stdout whatever the\n * exit code was, and the exit code only decides what to do when there is no\n * parseable outcome at all.\n *\n * ## Refusals are recognised structurally, never by name\n *\n * A refusal is \"the outcome carries an `error`\". The relay text comes from\n * `error.next_action`. Nothing here enumerates `runtime_undetermined` or\n * `wiring_collision`, so a refusal added to the connector tomorrow reaches the\n * user through this path without a CLI change — which is the whole point of\n * the connector having a typed vocabulary in the first place.\n */\n\n/** The connector's `--json` outcome. Only the fields this CLI reads. */\nexport interface ConnectorOutcome {\n schema_version?: number\n outcome?: 'complete' | 'action_required' | 'failed' | string\n next_action?: string\n approval?: { required?: boolean; expires_at?: string | null; url?: string }\n error?: {\n code?: string\n next_action?: string\n message?: string\n allowed_runtimes?: readonly string[]\n installed_clients?: readonly string[]\n suggested_runtime?: string\n superseded_agent_ids?: readonly string[]\n suggested_name?: string\n }\n [key: string]: unknown\n}\n\nexport interface ConnectorRun {\n /** The parsed outcome, when the connector produced one. */\n outcome: ConnectorOutcome | null\n exitCode: number\n /** Everything the connector wrote to stderr, already streamed to ours. */\n stderr: string\n /** stdout that was not the outcome object — kept so a failure can say why. */\n stdoutNoise: string\n}\n\nexport interface Spawner {\n (command: string, args: string[], onStderr: (chunk: string) => void): Promise<{\n stdout: string\n stderr: string\n exitCode: number\n }>\n}\n\n/**\n * Split a printed connector command into argv.\n *\n * The backend shell-quotes the setup token and the API url with single quotes\n * (`buildConnectorCommand`), so this understands single quotes and nothing\n * else. It is deliberately not a shell: no globbing, no variable expansion, no\n * `&&`. A command carrying anything this cannot represent is refused rather\n * than approximated, because the alternative is executing a rewritten version\n * of a command whose whole contract is that it is not rewritten.\n */\nexport function splitConnectorCommand(command: string): string[] {\n const argv: string[] = []\n let current = ''\n let quoted = false\n let started = false\n\n for (let i = 0; i < command.length; i += 1) {\n const ch = command[i]\n if (quoted) {\n if (ch === \"'\") quoted = false\n else current += ch\n continue\n }\n if (ch === \"'\") {\n quoted = true\n started = true\n continue\n }\n if (ch === ' ' || ch === '\\t') {\n if (started) argv.push(current)\n current = ''\n started = false\n continue\n }\n // The ONE backslash form this understands: POSIX `'\\''`, which is how the\n // backend's `shellQuote` escapes a single quote inside a quoted value\n // (`'a'\\''b'` means `a'b`). Supported because the builder can emit it, and\n // a command the builder can produce but `--run` cannot execute is a broken\n // contract rather than a safe refusal. Every OTHER backslash is still\n // refused — this is a parser for one known quoting function, not a shell.\n if (ch === '\\\\') {\n if (command[i + 1] === \"'\") {\n current += \"'\"\n started = true\n i += 1\n continue\n }\n throw new Error('Refusing to run a connector command with a backslash escape')\n }\n if (ch === '\"' || ch === '`' || ch === '$' || ch === '|' || ch === '&' || ch === ';' ||\n ch === '>' || ch === '<' || ch === '(' || ch === ')' || ch === '\\n') {\n throw new Error(`Refusing to run a connector command containing ${JSON.stringify(ch)}`)\n }\n current += ch\n started = true\n }\n if (quoted) throw new Error('Refusing to run a connector command with an unterminated quote')\n if (started) argv.push(current)\n if (argv.length === 0) throw new Error('The backend returned an empty connector command')\n return argv\n}\n\n/** The real spawner. Injected in tests so no child process runs there. */\nexport const nodeSpawner: Spawner = (command, args, onStderr) =>\n new Promise((resolve, reject) => {\n // `shell: false` is the point: argv goes to the process as-is, so nothing\n // in a token or url can be read as shell syntax.\n const child = spawn(command, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] })\n let stdout = ''\n let stderr = ''\n child.stdout.setEncoding('utf8')\n child.stderr.setEncoding('utf8')\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk\n })\n child.stderr.on('data', (chunk: string) => {\n stderr += chunk\n // Streamed rather than buffered to the end: a connector run can take\n // minutes, and its stderr is the only progress a human sees.\n onStderr(chunk)\n })\n child.on('error', reject)\n child.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? 1 }))\n })\n\n/**\n * Find the connector's outcome object in its stdout.\n *\n * The contract is one JSON object on stdout under `--json`. This assumes none\n * of the things that contract does not actually say: not that the object is\n * the whole stream (a package manager on the `npx` path writes its own lines),\n * not that it is on one line (a pretty-printed object), and not that it is\n * alone on its line (`npm notice {...}`). Each of those assumptions turned a\n * real refusal into \"no outcome\" in an earlier version. The LAST balanced\n * object wins.\n */\nexport function parseOutcome(stdout: string): { outcome: ConnectorOutcome | null; noise: string } {\n const noise: string[] = []\n let outcome: ConnectorOutcome | null = null\n\n // A scanner over the WHOLE stream, not over lines. Two assumptions died\n // here, both of them unstated until a reviewer looked: that the object is on\n // one line (a pretty-printed refusal was swallowed), and that the object is\n // ALONE on its line (`npm notice {...}` or a trailing word dropped it the\n // same way). Both regressed a real refusal to \"the connector produced no\n // outcome\", losing the exit code and the `next_action` a caller branches on.\n // Anything outside a balanced object is noise; the LAST balanced object\n // wins, so a stray object from a package manager cannot displace the\n // outcome.\n let depth = 0\n let start = -1\n let inString = false\n let escaped = false\n let plain = ''\n\n for (let i = 0; i < stdout.length; i += 1) {\n const ch = stdout[i]\n\n if (depth === 0) {\n if (ch === '{') {\n depth = 1\n start = i\n inString = false\n escaped = false\n } else {\n plain += ch\n }\n continue\n }\n\n if (inString) {\n if (escaped) escaped = false\n else if (ch === '\\\\') escaped = true\n else if (ch === '\"') inString = false\n continue\n }\n if (ch === '\"') inString = true\n else if (ch === '{') depth += 1\n else if (ch === '}') {\n depth -= 1\n if (depth === 0) {\n const candidate = stdout.slice(start, i + 1)\n try {\n // No `Array.isArray` check here, deliberately. A candidate always\n // starts at `{`, so `JSON.parse` can only return an object — the\n // anchor IS the guarantee. An earlier version carried the array\n // check as well and a mutation removing it passed the whole suite,\n // because it was unreachable: a guard nothing can violate reads like\n // protection while proving nothing, which is the shape this file has\n // already been wrong about once.\n outcome = JSON.parse(candidate) as ConnectorOutcome\n } catch {\n plain += candidate\n }\n start = -1\n }\n }\n }\n\n // An object that never closed is not an outcome; keep it readable rather\n // than dropping it, so a truncated stream still says something.\n if (depth > 0 && start >= 0) plain += stdout.slice(start)\n\n for (const line of plain.split('\\n')) {\n const text = line.trim()\n if (text) noise.push(text)\n }\n return { outcome, noise: noise.join('\\n') }\n}\n\n/** Is this outcome a refusal the human has to act on? */\nexport function isRefusal(outcome: ConnectorOutcome | null): boolean {\n return Boolean(outcome?.error)\n}\n\n/**\n * The one line that goes first (#2483's one-gate rule).\n *\n * An approval that is waiting outranks everything else on screen, and a\n * refusal outranks a completed run. The text is built from what the connector\n * said rather than from a table of codes here.\n */\nexport function relayLine(outcome: ConnectorOutcome | null): string | null {\n if (!outcome) return null\n if (outcome.error) {\n const message = outcome.error.message?.trim()\n const next = outcome.error.next_action ?? outcome.next_action\n // The message is the connector's own prose and is what a human reads; the\n // next action is what an agent branches on. Both, in that order.\n return message\n ? `${message}${next ? ` (next: ${next})` : ''}`\n : `The connector refused${next ? `: ${next}` : '.'}`\n }\n if (outcome.approval?.required) {\n return outcome.approval.url\n ? `Approve the budget to finish: ${outcome.approval.url}`\n : 'Approve the budget in your Haven tab to finish.'\n }\n return null\n}\n\n/**\n * Run the connector command, appending `--json` and nothing else.\n */\nexport async function runConnector(\n connectorCommand: string,\n spawner: Spawner,\n onStderr: (chunk: string) => void,\n): Promise<ConnectorRun> {\n const argv = splitConnectorCommand(connectorCommand)\n // Appended, never inserted: the rule is \"exactly `--json` appended\", and a\n // flag placed anywhere else is a different command line.\n const args = [...argv.slice(1), '--json']\n const { stdout, stderr, exitCode } = await spawner(argv[0], args, onStderr)\n const { outcome, noise } = parseOutcome(stdout)\n return { outcome, exitCode, stderr, stdoutNoise: noise }\n}\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++) B[x] = s[y + x];\n for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n\n/** Keccak sponge function. */\nexport class Keccak extends Hash<Keccak> implements HashXOF<Keccak> {\n protected state: Uint8Array;\n protected pos = 0;\n protected posOut = 0;\n protected finished = false;\n protected state32: Uint32Array;\n protected destroyed = false;\n\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen) this.keccak();\n }\n return this;\n }\n protected finish(): void {\n if (this.finished) return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n protected writeInto(out: Uint8Array): Uint8Array {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len; ) {\n if (this.posOut >= blockLen) this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out: Uint8Array): Uint8Array {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes: number): Uint8Array {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array): Uint8Array {\n aoutput(out, this);\n if (this.finished) throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to?: Keccak): Keccak {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\n\nconst gen = (suffix: number, blockLen: number, outputLen: number) =>\n createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer<HashXOF<Keccak>, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n","export const wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n","/**\n * The secret check `haven feedback submit` runs before any request carrying\n * the text is sent (#3597, owner decision 2026-10-02).\n *\n * A raw private key and a transaction/delegation/schema hash share one shape\n * — 64 hex characters, with or without `0x` — so shape alone cannot decide.\n * The check asks what a string would DO. Every layer below runs locally\n * first; layer 3's network reads fetch this user's own addresses to compare\n * against, and never carry the submitted text itself.\n *\n * **Zero runtime dependencies stays true at the `dependencies` field.**\n * `@noble/hashes` (Keccak-256 — `node:crypto` has secp256k1 but not that) and\n * `@scure/bip39` (the English wordlist) are devDependencies, bundled by tsup\n * into `dist/*` (see `agent-guidance-text.test.ts`'s sibling guard, and the\n * CLI README's zero-deps note). This file must never import\n * `@haven_ai/connect` — that package pulls in ethers, which is exactly the\n * install-weight problem the zero-deps rule exists to avoid, and it is also\n * simply unnecessary: the credential files this reads are plain JSON.\n */\nimport { readFile, readdir } from 'node:fs/promises'\nimport { createECDH } from 'node:crypto'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { keccak_256 } from '@noble/hashes/sha3'\nimport { wordlist as BIP39_ENGLISH } from '@scure/bip39/wordlists/english'\nimport { CliApiError, type CliApi } from './api.js'\n\n/** Mirrors the backend's own cap (`routes/feedback.ts`'s `MAX_FEEDBACK_TEXT_LENGTH`). */\nexport const MAX_FEEDBACK_TEXT_LENGTH = 4000\n\nexport type SecretCheckReason =\n | 'agent_api_key'\n | 'setup_token'\n | 'session_jwt'\n | 'labelled_parameter'\n | 'url_credentials'\n | 'rpc_path_key'\n | 'local_credential'\n | 'private_key'\n | 'address_check_unavailable'\n | 'recovery_phrase'\n\nexport interface SecretCheckRefusal {\n layer: 1 | 2 | 3 | 4\n reason: SecretCheckReason\n /** Human-readable; never includes the refused text itself. */\n message: string\n}\n\nfunction refusal(layer: SecretCheckRefusal['layer'], reason: SecretCheckReason, message: string): SecretCheckRefusal {\n return { layer, reason, message }\n}\n\n// ── Layer 1 — prefixed and labelled secrets ─────────────────────────\n//\n// A superset of `redactVendorSecrets` (`packages/backend/src/domain/redact-vendor-secrets.ts`)\n// — the backend re-runs the identical list server-side\n// (`packages/backend/src/modules/feedback/secret-check.ts`), so stored text\n// can never trip the ops grant script's vendor-secret refusal.\n// No false positives: every pattern here is a label or a prefix, never a bare\n// shape (a bare 64-hex token is layer 3).\n\nconst LABELLED_PATTERNS: ReadonlyArray<{ reason: SecretCheckReason; re: RegExp }> = [\n { reason: 'agent_api_key', re: /sk_agent_[A-Za-z0-9]/ },\n { reason: 'setup_token', re: /hv_setup_[A-Za-z0-9]/ },\n // A session JWT: three dot-separated base64url parts, each non-empty.\n // `\\beyJ` (not the looser `\\bey`), which is the base64url encoding of `{\"`\n // — every real JWT header starts there, and the tighter anchor stops\n // ordinary words like \"eyebrow\" or \"eyelet\" from matching their own tail.\n { reason: 'session_jwt', re: /\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/ },\n // key= / api_key= / api-key= / apikey= / token= / secret=, `\\b`-bounded —\n // the same boundary `redact-vendor-secrets.ts:19` uses.\n { reason: 'labelled_parameter', re: /\\b(api[_-]?key|key|token|secret)=[^&\\s\"'\\\\)]+/i },\n { reason: 'url_credentials', re: /https?:\\/\\/[^\\s/@]+:[^\\s@]+@/i },\n { reason: 'rpc_path_key', re: /\\/(?:rpc|v2)\\/[A-Za-z0-9_-]{16,}/ },\n]\n\nexport function checkLabelledSecrets(text: string): SecretCheckRefusal | null {\n for (const { reason, re } of LABELLED_PATTERNS) {\n if (re.test(text)) {\n return refusal(\n 1,\n reason,\n 'Refusing to send: the text looks like it contains a secret (a credential label or prefix matched). Remove it and try again.',\n )\n }\n }\n return null\n}\n\n// ── Layer 2 — secrets this machine holds, exact match ───────────────\n//\n// Read with `node:fs` only — never `@haven_ai/connect`. Case-insensitive,\n// `0x`-normalised, never printed. A custom `--credentials-dir` cannot be\n// discovered; that is accepted residual risk (the issue's own words).\n\nexport interface LocalSecretSources {\n /** Overrides `~/.haven/agents` — tests only. */\n baseDir?: string\n env?: NodeJS.ProcessEnv\n /** This CLI's own `~/.haven/session.json` token, passed in by the caller. */\n sessionToken?: string\n}\n\nfunction normalize(value: string): string {\n return value.trim().toLowerCase().replace(/^0x/, '')\n}\n\nasync function readJsonStringField(path: string, field: string): Promise<string | null> {\n try {\n const raw = await readFile(path, 'utf8')\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const value = parsed[field]\n return typeof value === 'string' && value.length > 0 ? value : null\n } catch {\n return null\n }\n}\n\n/**\n * Every local secret source the issue names:\n * `~/.haven/agents/<slug>/signer.json` (`delegate_key`), `identity.json`\n * (`api_key`), `rekey-pending.json` (`new_delegate_key`) — including\n * TOMBSTONED directories, which keep their keys and are deliberately NOT\n * skipped here (unlike agent discovery for a `--rekey` target) — the\n * `HAVEN_DELEGATE_KEY` env var, and this CLI's own session token.\n */\nexport async function readLocalSecrets(sources: LocalSecretSources = {}): Promise<Set<string>> {\n const secrets = new Set<string>()\n const env = sources.env ?? process.env\n const envKey = env.HAVEN_DELEGATE_KEY\n if (envKey) secrets.add(normalize(envKey))\n if (sources.sessionToken) secrets.add(normalize(sources.sessionToken))\n\n const root = sources.baseDir ?? join(homedir(), '.haven', 'agents')\n let entries: string[] = []\n try {\n entries = await readdir(root)\n } catch {\n return secrets\n }\n\n for (const entry of entries) {\n const dir = join(root, entry)\n const delegateKey = await readJsonStringField(join(dir, 'signer.json'), 'delegate_key')\n if (delegateKey) secrets.add(normalize(delegateKey))\n const apiKey = await readJsonStringField(join(dir, 'identity.json'), 'api_key')\n if (apiKey) secrets.add(normalize(apiKey))\n const pendingKey = await readJsonStringField(join(dir, 'rekey-pending.json'), 'new_delegate_key')\n if (pendingKey) secrets.add(normalize(pendingKey))\n }\n return secrets\n}\n\nexport function checkExactSecretMatch(text: string, secrets: ReadonlySet<string>): SecretCheckRefusal | null {\n if (secrets.size === 0) return null\n const haystack = text.toLowerCase()\n for (const secret of secrets) {\n // A short needle risks matching unrelated text; every real secret here\n // (a key, an API key, a session token) is far longer than this.\n if (secret.length >= 8 && haystack.includes(secret)) {\n return refusal(\n 2,\n 'local_credential',\n 'Refusing to send: the text contains a credential this machine holds (an agent delegate key, an agent API key, a pending re-key, or your own session token). Remove it and try again.',\n )\n }\n }\n return null\n}\n\n// ── Layer 3 — any other 64-hex token: derive and compare ────────────\n\n/**\n * A token is exactly 64 hex characters, optional `0x`, bounded by a\n * non-hex character on both sides — so a 128-hex calldata run yields ZERO\n * candidates rather than being windowed into two.\n */\nexport function findHexTokenCandidates(text: string): string[] {\n const matches = text.matchAll(/(?<![0-9a-fA-F])(0x)?([0-9a-fA-F]{64})(?![0-9a-fA-F])/g)\n return [...matches].map((m) => m[2])\n}\n\n/**\n * Treat a 64-hex token as a secp256k1 private key and derive its Ethereum\n * address, or `null` when it is not a valid key — a zero key or a key ≥ the\n * curve order `n` makes `createECDH.setPrivateKey` throw, and that token\n * simply passes (most real tokens here are hashes, not keys).\n */\nexport function deriveAddressFromHexToken(token: string): string | null {\n try {\n const ecdh = createECDH('secp256k1')\n ecdh.setPrivateKey(Buffer.from(token, 'hex'))\n const uncompressed = ecdh.getPublicKey() // 65 bytes, 0x04 prefix\n const hash = keccak_256(uncompressed.subarray(1))\n return `0x${Buffer.from(hash.subarray(12)).toString('hex')}`\n } catch {\n return null\n }\n}\n\ninterface AgentsResponse {\n agents: Array<{ delegate_address?: string }>\n}\ninterface AccountsResponse {\n accounts: Array<{ account_address?: string; chain_id: number }>\n}\ninterface HybridAccountSignersResponse {\n owner_address: string | null\n}\n\n/**\n * This user's key-backed addresses: every agent's `delegate_address` (from\n * `GET /agents`) and every account's `owner_address` (from\n * `GET /accounts/hybrid/{address}/signers?chain_id=`, one call per account\n * per chain). Smart-account addresses (CREATE2, no private key) and\n * passkeys (P-256) can never match a derived secp256k1 address, so they are\n * not in the set.\n */\nexport async function collectKeyBackedAddresses(api: CliApi): Promise<Set<string>> {\n const addresses = new Set<string>()\n const { agents } = await api.get<AgentsResponse>('/agents')\n for (const agent of agents) {\n if (agent.delegate_address) addresses.add(agent.delegate_address.toLowerCase())\n }\n const { accounts } = await api.get<AccountsResponse>('/user/accounts')\n for (const account of accounts) {\n if (!account.account_address) continue\n const signers = await api.get<HybridAccountSignersResponse>(\n `/accounts/hybrid/${account.account_address}/signers?chain_id=${account.chain_id}`,\n )\n if (signers.owner_address) addresses.add(signers.owner_address.toLowerCase())\n }\n return addresses\n}\n\n/**\n * The address reads happen ONLY when at least one 64-hex candidate exists.\n * If a read fails, this fails CLOSED — refuses to send, with a message that\n * fits what actually failed. A transient/network failure gets a retry hint;\n * a 401/403 (the session cannot read this — the owner-cli allow-list refused\n * it, or the session itself is bad) or a 409 (the account's signer\n * configuration is unknown — nothing to compare against) are NOT fixed by\n * retrying the same call, so each gets its own distinct wording rather than\n * a reachability hint that would just repeat.\n */\nexport async function checkKeyBackedAddresses(text: string, api: CliApi): Promise<SecretCheckRefusal | null> {\n const candidates = findHexTokenCandidates(text)\n if (candidates.length === 0) return null\n\n let keyBacked: Set<string>\n try {\n keyBacked = await collectKeyBackedAddresses(api)\n } catch (err) {\n if (err instanceof CliApiError && (err.status === 401 || err.status === 403)) {\n return refusal(\n 3,\n 'address_check_unavailable',\n 'Refusing to send: could not verify whether the text contains a private key — your session cannot read the data this check needs. Run `haven login` again; retrying this submission will not help.',\n )\n }\n if (err instanceof CliApiError && err.status === 409) {\n return refusal(\n 3,\n 'address_check_unavailable',\n \"Refusing to send: could not verify whether the text contains a private key — one of your accounts' signer configuration is unknown, so there is nothing to compare against. Retrying this submission will not help; contact support.\",\n )\n }\n return refusal(\n 3,\n 'address_check_unavailable',\n 'Refusing to send: could not verify whether the text contains a private key (the address check failed). Retry once Haven is reachable.',\n )\n }\n\n for (const token of candidates) {\n const address = deriveAddressFromHexToken(token)\n if (address && keyBacked.has(address.toLowerCase())) {\n return refusal(\n 3,\n 'private_key',\n 'Refusing to send: the text contains what looks like the private key for one of your agents or accounts. Remove it and try again.',\n )\n }\n }\n return null\n}\n\n// ── Layer 4 — recovery phrases ───────────────────────────────────────\n\nconst BIP39_WORDS = new Set(BIP39_ENGLISH.map((word) => word.toLowerCase()))\n/** The shortest mnemonic BIP-39 mints. Any run at least this long contains one. */\nconst MIN_RECOVERY_PHRASE_WORDS = 12\n\n/**\n * A run of 12, 15, 18, 21 or 24 CONSECUTIVE BIP-39 English words. Checking\n * for a run of at least 12 is sufficient: a longer run CONTAINS a 12-word\n * run, which is itself refusable — there is no case where a longer run\n * should pass that a 12-word one would refuse.\n */\nexport function checkRecoveryPhrase(text: string): SecretCheckRefusal | null {\n const tokens = text.split(/\\s+/).map((t) => t.replace(/^[^A-Za-z]+|[^A-Za-z]+$/g, '').toLowerCase())\n let run = 0\n for (const token of tokens) {\n if (token && BIP39_WORDS.has(token)) {\n run += 1\n if (run >= MIN_RECOVERY_PHRASE_WORDS) {\n return refusal(\n 4,\n 'recovery_phrase',\n 'Refusing to send: the text looks like it contains a recovery phrase (12 or more consecutive seed words). Remove it and try again.',\n )\n }\n } else {\n run = 0\n }\n }\n return null\n}\n\n// ── Composition ───────────────────────────────────────────────────────\n\nexport interface SecretCheckDeps {\n api: CliApi\n localSecrets?: LocalSecretSources\n}\n\n/**\n * Run every layer, in order, and return the first refusal — or `null` when\n * the text may be sent. Every layer except 3's address reads is local; none\n * of them, including layer 3, ever transmits the text itself.\n */\nexport async function checkTextForSecrets(text: string, deps: SecretCheckDeps): Promise<SecretCheckRefusal | null> {\n const layer1 = checkLabelledSecrets(text)\n if (layer1) return layer1\n\n const localSecrets = await readLocalSecrets(deps.localSecrets)\n const layer2 = checkExactSecretMatch(text, localSecrets)\n if (layer2) return layer2\n\n const layer3 = await checkKeyBackedAddresses(text, deps.api)\n if (layer3) return layer3\n\n return checkRecoveryPhrase(text)\n}\n","import { parseArgs, helpText, type ParsedArgs } from './args.js'\nimport { createCliApi, CliApiError, type CliApi } from './api.js'\nimport { createSessionStore, type Session, type SessionStore } from './session.js'\nimport { chainName, table, timeAgo, truncateAddress } from './format.js'\nimport { toCsv } from './csv.js'\nimport { EXIT, HavenCliError, UsageError, toFailure, type ExitCode } from './errors.js'\nimport { createOutput, type Output } from './output.js'\nimport { HAVEN_AGENT_RUNBOOK_MD } from './agent-guidance-text.js'\nimport { sessionExpiry } from './token.js'\nimport { parseTokenAmount } from './amount.js'\nimport {\n isRefusal,\n nodeSpawner,\n relayLine,\n runConnector,\n type ConnectorOutcome,\n type Spawner,\n} from './connect-runner.js'\nimport { checkTextForSecrets, MAX_FEEDBACK_TEXT_LENGTH } from './secret-check.js'\n\n// Hosted Haven backend. Override with `--api <url>` or HAVEN_API_URL (e.g. a\n// local backend at http://localhost:3001, or your own domain once self-hosted).\nexport const DEFAULT_API = 'https://havenbackend-production-8a00.up.railway.app'\n// Self-reported CLI version. Owned by scripts/release-bump.mjs, which rewrites\n// the string literal below on every release — keep it a bare quoted literal.\nexport const CLI_VERSION = '0.0.0-dev.202610142033.0d2f50f'\n\n/** #3303: the `X-Haven-Client` value every Haven API request from this CLI carries. */\nexport const CLI_CLIENT_IDENTITY = `@haven_ai/cli/${CLI_VERSION}`\n\nexport interface RunDeps {\n sessionStore?: SessionStore\n /** Build an API client; injected so tests can stub the backend. */\n makeApi?: (baseUrl: string, token?: string) => CliApi\n promptPassword?: () => Promise<string>\n /** #2526: injected so the device poll loop is testable without real time. */\n sleep?: (ms: number) => Promise<void>\n /** #2527: injected so `--run` is testable without spawning a real process. */\n spawner?: Spawner\n out?: (line: string) => void\n err?: (line: string) => void\n env?: NodeJS.ProcessEnv\n /**\n * #3597: overrides where `feedback submit`'s secret check (layer 2) looks\n * for local agent credentials. Tests only — production never sets it, so\n * the check reads the real `~/.haven/agents` the way the connect package's\n * own `defaultCredentialRoot` does, and tests that must not touch a\n * developer's real credentials pass a temp directory instead.\n */\n credentialsBaseDir?: string\n}\n\ninterface ResolvedDeps {\n sessionStore: SessionStore\n makeApi: (baseUrl: string, token?: string) => CliApi\n promptPassword: () => Promise<string>\n sleep: (ms: number) => Promise<void>\n spawner: Spawner\n out: (line: string) => void\n err: (line: string) => void\n env: NodeJS.ProcessEnv\n credentialsBaseDir?: string\n /** Set once `--json` is known; every command writes through it. */\n o: Output\n}\n\n/**\n * Every command this CLI dispatches, as data (#2525).\n *\n * The table-driven contract test in `json-contract.test.ts` iterates THIS list\n * and asserts each command's `--json` refusal is one JSON object on stdout, so\n * a command added to `dispatch` without adding it here is not covered. Its\n * ceiling, stated plainly: the test proves the listed commands honour the\n * contract, not that the list is complete. A drift test below pins the list\n * against `dispatch`'s own switch to close that gap by execution.\n */\nexport const COMMANDS = [\n 'login', 'logout', 'whoami', 'guide',\n 'wallets list', 'wallets balances', 'wallets rename', 'wallets funding',\n 'agents list', 'agents show', 'agents pause', 'agents resume', 'agents revoke',\n 'agents rotate-key', 'agents rename', 'agents connect',\n 'budget show', 'budget grant', 'budget revoke',\n 'activity list', 'activity export',\n 'catalog list',\n 'contacts list', 'contacts add', 'contacts remove',\n 'feedback submit',\n] as const\n\n// ── Backend response shapes (subset the CLI needs) ──────────────────\n/** A linked Haven account as `GET /user/accounts` lists it. */\ninterface Safe { id: string; account_address?: string; chain_id: number; name: string; is_default: boolean }\nfunction accountAddressOf(s: { account_address?: string | null }): string {\n return s.account_address ?? ''\n}\ninterface Allowance { token_symbol: string; allowance_amount: string; reset_period_min: number }\ninterface Agent {\n id: string\n name: string\n status: string\n allowances?: Allowance[]\n /** #3597: the spec's `Agent` schema always carries it; added here for the feedback secret check's layer 3. */\n delegate_address?: string\n /**\n * #3729: how many delegation rows are still live (pending, active or\n * replaced), computed server-side — the CLI gates the revoke on this rather\n * than keeping its own copy of the live set. Optional so an older backend\n * that predates the field reads as \"nothing live\" rather than crashing.\n */\n live_delegation_count?: number\n}\ninterface Balance { symbol: string; formatted: string; balance: string }\n/**\n * The additive balance-freshness marker from the wire (#3295), read by the\n * CLI since #3318. Present on a `GET /balances/:accountAddress` entry only\n * when that entry's on-chain read FAILED: `stale` = the served figure is the\n * last successfully read balance and `asOf` says when it was read;\n * `unavailable` = no balance has ever been read for this token, so the\n * accompanying balance string is a filler, not a figure. Absent on a clean\n * read — which is how the marker stays additive for every existing consumer.\n */\ninterface BalanceFreshness {\n status: 'stale' | 'unavailable'\n /** ISO 8601 — present exactly when `status` is `'stale'`. */\n asOf?: string\n}\ninterface BalanceToken {\n symbol: string\n address: string | null\n decimals: number\n balanceFreshness?: BalanceFreshness\n}\ninterface Txn {\n hash: string; direction: 'in' | 'out'; valueFormatted: string; asset: string\n source?: string; timestamp: number; accountName?: string\n from?: string; to?: string; isError?: boolean\n tokenSymbol?: string; tokenAddress?: string; chainId?: number; accountAddress?: string\n agentName?: string; paymentFlowStatus?: string | null; activityType?: string\n}\ninterface CatalogEntry { name: string; category: string; rail: string; price_display?: string | null; status: string }\ninterface Contact { id: string; name: string; address: string }\ninterface CreateSetupResponse {\n setup_id: string\n status: string\n approval_url: string\n expires_at: string\n connector_command: string\n connector_package: string\n setup_prompt: string\n}\ninterface SetupStatus {\n setup_id: string\n status: string\n agent_id: string | null\n approval_url: string\n expires_at: string\n}\n\n/** `GET /user/accounts/:id/funding` — the wire shape the route documents. */\ninterface FundingResponse {\n account_address: string\n chain: { id: number; name: string; explorer_url: string }\n tokens: {\n symbol: string\n address: string\n decimals: number\n balance_human: string\n minimum_useful_human: string | null\n }[]\n native: { symbol: string; balance_human: string; needed: boolean }\n funded: boolean\n faucet_url?: string\n}\n\n/** Entry point. Returns a process exit code; never throws for expected errors. */\nexport async function run(argv: string[], deps: RunDeps = {}): Promise<number> {\n const out = deps.out ?? ((l: string) => process.stdout.write(`${l}\\n`))\n const err = deps.err ?? ((l: string) => process.stderr.write(`${l}\\n`))\n\n // `--json` has to be known before anything can be emitted, including a parse\n // failure's own message. Scanning argv for the flag is deliberate: parseArgs\n // throws on a bad line, and a refusal that ignored --json because the parse\n // failed would break the contract exactly when a caller most needs it.\n const json = argv.includes('--json')\n const o = createOutput(json, out, err)\n\n const d: ResolvedDeps = {\n sessionStore: deps.sessionStore ?? createSessionStore(),\n makeApi: deps.makeApi ?? ((baseUrl, token) => createCliApi({ baseUrl, token, clientIdentity: CLI_CLIENT_IDENTITY })),\n promptPassword: deps.promptPassword ?? (() => Promise.reject(new Error('No password input available'))),\n sleep: deps.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))),\n spawner: deps.spawner ?? nodeSpawner,\n out,\n err,\n env: deps.env ?? process.env,\n credentialsBaseDir: deps.credentialsBaseDir,\n o,\n }\n\n let args: ParsedArgs\n try {\n args = parseArgs(argv)\n } catch (e) {\n return fail(d, new UsageError(e instanceof Error ? e.message : String(e), 'Run `haven --help`.'))\n }\n\n if (args.flags.version) {\n o.data({ version: CLI_VERSION }, () => CLI_VERSION)\n return EXIT.ok\n }\n if (args.flags.help || !args.command) {\n o.data({ help: helpText() }, () => helpText())\n return EXIT.ok\n }\n\n try {\n return await dispatch(args, d)\n } catch (e) {\n return fail(d, e)\n }\n}\n\n/** The single exit: one failure object, one exit code, read off one decision. */\nfunction fail(d: ResolvedDeps, err: unknown): ExitCode {\n const failure = toFailure(err)\n d.o.failure(failure)\n return failure.exit\n}\n\nasync function dispatch(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const key = args.sub ? `${args.command} ${args.sub}` : args.command\n switch (key) {\n case 'guide': return cmdGuide(args, d)\n case 'login': return cmdLogin(args, d)\n case 'logout': return cmdLogout(args, d)\n case 'whoami': return cmdWhoami(args, d)\n case 'wallets list': return cmdWalletsList(args, d)\n case 'wallets balances': return cmdWalletsBalances(args, d)\n case 'wallets funding': return cmdWalletsFunding(args, d)\n case 'agents list': return cmdAgentsList(args, d)\n case 'agents show': return cmdAgentsShow(args, d)\n case 'agents connect': return cmdAgentsConnect(args, d)\n case 'agents pause': return cmdAgentLifecycle(args, d, 'pause')\n case 'agents resume': return cmdAgentLifecycle(args, d, 'resume')\n case 'agents revoke': return cmdAgentRevoke(args, d)\n case 'agents rotate-key': return cmdAgentRotateKey(args, d)\n case 'agents rename': return cmdAgentRename(args, d)\n case 'budget show': return cmdBudgetShow(args, d)\n case 'budget grant': return cmdBudgetGrant(args, d)\n case 'budget revoke': return cmdBudgetRevoke(args, d)\n case 'wallets rename': return cmdWalletRename(args, d)\n case 'activity list': return cmdActivityList(args, d)\n case 'activity export': return cmdActivityExport(args, d)\n case 'catalog list': return cmdCatalogList(args, d)\n case 'contacts list': return cmdContactsList(args, d)\n case 'contacts add': return cmdContactsAdd(args, d)\n case 'contacts remove': return cmdContactsRemove(args, d)\n case 'feedback submit': return cmdFeedbackSubmit(args, d)\n default:\n throw new UsageError(`Unknown command: ${key}.`, 'Run `haven --help` for the command list.')\n }\n}\n\nfunction baseUrlFor(args: ParsedArgs, d: ResolvedDeps, session: Session | null): string {\n return args.flags.api ?? session?.apiBaseUrl ?? d.env.HAVEN_API_URL ?? DEFAULT_API\n}\n\nasync function authed(args: ParsedArgs, d: ResolvedDeps): Promise<{ session: Session; api: CliApi }> {\n const session = await d.sessionStore.load()\n // Status 401 so a missing local session and a rejected one produce the same\n // code and the same advice — from the caller's side they are one situation.\n if (!session) throw new CliApiError('Not authenticated.', 401)\n return { session, api: d.makeApi(baseUrlFor(args, d, session), session.token) }\n}\n\nfunction emit(d: ResolvedDeps, _json: boolean, data: unknown, human: () => string): void {\n d.o.data(data, human)\n}\n\n// ── Guide ───────────────────────────────────────────────────────────\n\n/**\n * Print the agent onboarding runbook — the same text served at\n * `/for-agents.md` (#2523). Offline by construction: the string is compiled in,\n * so an agent with no session and no network still gets the instructions that\n * tell it what to do about exactly that.\n */\nasync function cmdGuide(_args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n d.o.data({ ok: true, format: 'markdown', content: HAVEN_AGENT_RUNBOOK_MD }, () => HAVEN_AGENT_RUNBOOK_MD)\n return EXIT.ok\n}\n\n// ── Auth ────────────────────────────────────────────────────────────\n\ninterface DeviceStart {\n device_code: string\n user_code: string\n verification_url: string\n expires_in: number\n interval: number\n}\n\n/**\n * Browser-approved login (#2526), the DEFAULT for `haven login`.\n *\n * The reason this is the default and the password path is not: an agent drives\n * this CLI, and an agent must never hold its user's password. The cold-test\n * agent correctly refused to type one. This asks the human instead — the agent\n * pastes a link, and every signature stays with the person.\n *\n * Under `--json` the first object is emitted BEFORE polling starts, so an agent\n * can hand its user the link immediately rather than after the flow completes.\n */\nasync function deviceLogin(args: ParsedArgs, d: ResolvedDeps, baseUrl: string): Promise<number> {\n const api = d.makeApi(baseUrl)\n const label = d.env.HAVEN_CLIENT_LABEL ?? `Haven CLI on ${d.env.HOSTNAME ?? 'this machine'}`\n const start = await api.post<DeviceStart>('/auth/device/start', { client_label: label })\n\n const deadline = Date.now() + start.expires_in * 1000\n // Emitted first, not last: the whole point is that the agent can pass the\n // link on while the poll runs. `device_code` is #2618: without it, the\n // `--no-wait` object had nothing an agent could feed to\n // `haven login --poll` — the resume command existed on the flag parser and\n // nowhere an agent could reach it.\n d.o.data(\n {\n ok: true,\n verification_url: start.verification_url,\n user_code: start.user_code,\n device_code: start.device_code,\n interval: start.interval,\n expires_at: new Date(deadline).toISOString(),\n },\n () =>\n `Open ${start.verification_url}\\nand approve the code ${start.user_code}.\\n` +\n `It expires in ${Math.round(start.expires_in / 60)} minutes.`,\n )\n\n if (args.flags.noWait) return EXIT.ok\n\n // #2618: under --json, ten minutes of polling defeats the point of the\n // flag — an agent that expected to regain control sat out its whole turn.\n // --json now defaults to a SHORT wait (30 s, the issue's figure): still\n // long enough to catch a human who approves right away, short enough that\n // the agent gets a pending object instead of a blocked turn. An explicit\n // --no-wait keeps its documented immediate return, and human prose mode\n // keeps the full wait the flow always had.\n const jsonWaitMs = args.flags.json ? 30_000 : start.expires_in * 1000\n const waitUntil = Date.now() + jsonWaitMs\n\n // The server names the interval; the client does not invent one. `slow_down`\n // widens it, which is the only backoff signal this flow has.\n let interval = start.interval * 1000\n for (;;) {\n if (Date.now() >= deadline) {\n throw new HavenCliError('The code expired before it was approved.', EXIT.notAuthenticated)\n }\n if (Date.now() >= waitUntil) {\n // Time out at the CLIENT's deadline, not the code's: emit the pending\n // object carrying the device code so `haven login --poll\n // <device_code>` can pick the flow up — nothing is lost, exit 3\n // (not_authenticated: \"keep the flow, you are just not signed in yet\").\n d.o.data(\n { status: 'pending', device_code: start.device_code, retry_after: Math.round(interval / 1000) },\n () => 'Still waiting for approval — run the same command again to keep waiting.',\n )\n return EXIT.notAuthenticated\n }\n await d.sleep(interval)\n let res: { token: string; user: Session['user'] } | null = null\n try {\n res = await api.post<{ token: string; user: Session['user'] }>('/auth/device/token', {\n device_code: start.device_code,\n })\n } catch (err) {\n const code = deviceErrorCode(err)\n if (code === 'authorization_pending') continue\n if (code === 'slow_down') {\n interval += 5000\n continue\n }\n if (code === 'access_denied') {\n throw new HavenCliError('The request was denied.', EXIT.refused)\n }\n if (code === 'expired_token') {\n throw new HavenCliError('The code expired before it was approved.', EXIT.notAuthenticated)\n }\n throw err\n }\n await d.sessionStore.save({ token: res.token, apiBaseUrl: baseUrl, user: res.user })\n emit(\n d,\n args.flags.json,\n { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },\n () => `Signed in as ${res!.user.email}.`,\n )\n return EXIT.ok\n }\n}\n\n/** The RFC 8628 error slug in a 400 body, or null. */\nfunction deviceErrorCode(err: unknown): string | null {\n const body = (err as { body?: { error?: unknown } } | undefined)?.body\n return typeof body?.error === 'string' ? body.error : null\n}\n\n/**\n * #2618: the suggested gap between `haven login --poll` rounds, in seconds.\n * Mirrors what the backend's device start has named in `interval` so far —\n * the CLI never invents a different number, and one poll round per invocation\n * keeps the request rate at whatever the caller's retry loop chooses.\n */\nconst POLL_RETRY_AFTER_SECONDS = 5\n\n/**\n * ONE poll round of the device flow (#2618) — the second command of the\n * non-blocking sequence `login --json --no-wait`, then `login --poll\n * <device_code>`. The blocking loop cannot serve an agent that must return\n * promptly, and killing it loses the code; this performs the poll the loop\n * WOULD have done and hands the outcome straight back as an exit code:\n * 0 approved (session saved, same success object as the blocking path),\n * 3 pending (a `{ status, device_code, retry_after }` object — poll again),\n * 4 denied. The server answers `expired_token` for an unknown code too, so\n * that also exits 3: expired means start over, and 3 is \"not signed in\".\n */\nasync function devicePollOnce(\n args: ParsedArgs,\n d: ResolvedDeps,\n baseUrl: string,\n deviceCode: string,\n): Promise<number> {\n const api = d.makeApi(baseUrl)\n let res: { token: string; user: Session['user'] } | null = null\n try {\n res = await api.post<{ token: string; user: Session['user'] }>('/auth/device/token', {\n device_code: deviceCode,\n })\n } catch (err) {\n // Same slug mapping as the blocking loop above — one flow, one vocabulary.\n const code = deviceErrorCode(err)\n if (code === 'authorization_pending') {\n d.o.data(\n { status: 'pending', device_code: deviceCode, retry_after: POLL_RETRY_AFTER_SECONDS },\n () => 'Not approved yet — poll again shortly.',\n )\n return EXIT.notAuthenticated\n }\n if (code === 'slow_down') {\n // The server is saying the same thing the blocking loop's widening is:\n // back off. The next round should wait LONGER than the named interval.\n d.o.data(\n {\n status: 'pending',\n device_code: deviceCode,\n retry_after: POLL_RETRY_AFTER_SECONDS + 5,\n },\n () => 'Polling too fast — wait a moment longer, then poll again.',\n )\n return EXIT.notAuthenticated\n }\n if (code === 'access_denied') {\n throw new HavenCliError('The request was denied.', EXIT.refused)\n }\n if (code === 'expired_token') {\n throw new HavenCliError('The code expired before it was approved.', EXIT.notAuthenticated)\n }\n throw err\n }\n await d.sessionStore.save({ token: res.token, apiBaseUrl: baseUrl, user: res.user })\n emit(\n d,\n args.flags.json,\n { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },\n () => `Signed in as ${res!.user.email}.`,\n )\n return EXIT.ok\n}\n\nasync function cmdLogin(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n // #2618: the resume step of the non-blocking sequence. `--poll` takes the\n // device code the `--no-wait` (or timed-out `--json`) object carried and\n // performs exactly ONE round against POST /auth/device/token — see\n // `devicePollOnce`. It cannot be combined with the password path: a poll\n // belongs to a started device flow, and silently starting a login instead\n // would look like the flow was resumed when it was not.\n if (args.flags.poll) {\n return devicePollOnce(args, d, baseUrlFor(args, d, null), args.flags.poll)\n }\n const email = args.flags.email ?? d.env.HAVEN_EMAIL\n // #2526: the browser flow is the DEFAULT. `--email` (or HAVEN_EMAIL) keeps\n // the password path for a human who wants it — it is not removed, it is no\n // longer what an agent gets by asking for `login`.\n if (!email) {\n return deviceLogin(args, d, baseUrlFor(args, d, null))\n }\n const password = d.env.HAVEN_PASSWORD ?? (await d.promptPassword())\n if (!password) {\n throw new UsageError('A password is required.', 'Set HAVEN_PASSWORD for a non-interactive run.')\n }\n const baseUrl = baseUrlFor(args, d, null)\n const api = d.makeApi(baseUrl)\n const res = await api.post<{ token: string; user: Session['user'] }>('/auth/login', { email, password })\n await d.sessionStore.save({ token: res.token, apiBaseUrl: baseUrl, user: res.user })\n // The issue specifies { ok, email, expires_at }; `user` and `apiBaseUrl` stay\n // because they were already the shape and dropping them would break a script\n // that reads them for no gain. Neither the password nor the token is echoed —\n // `expires_at` is derived from the token, never the token itself.\n emit(\n d,\n args.flags.json,\n { ok: true, email: res.user.email, expires_at: sessionExpiry(res.token), user: res.user, apiBaseUrl: baseUrl },\n () => `Signed in as ${res.user.email}.`,\n )\n return EXIT.ok\n}\n\nasync function cmdLogout(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n await d.sessionStore.clear()\n emit(d, args.flags.json, { ok: true, signed_out: true }, () => 'Signed out.')\n return EXIT.ok\n}\n\nasync function cmdWhoami(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { session, api } = await authed(args, d)\n const user = await api.get<Session['user']>('/auth/me')\n // The four fields #2525 asks for — id, email, session expiry, api url — laid\n // over the profile the route already returned, so nothing a caller reads\n // today disappears. `expires_at` is null when the token carries no readable\n // `exp`, which is a fact worth reporting rather than an error.\n emit(\n d,\n args.flags.json,\n { ...user, id: user.id, email: user.email, expires_at: sessionExpiry(session.token), api_url: session.apiBaseUrl },\n () => `${user.email}${user.name ? ` (${user.name})` : ''}`,\n )\n return EXIT.ok\n}\n\n// ── Wallets ─────────────────────────────────────────────────────────\n\n/**\n * Read the `accounts` envelope off `GET /user/accounts`, failing LOUDLY when\n * it is absent (#2914).\n *\n * The envelope key moved `safes` -> `accounts` in the naming contraction, and\n * this file kept reading the old one. Five call sites destructured an\n * `undefined` array and every wallets command died on\n * `Cannot read properties of undefined (reading 'length')` — a stack trace\n * blaming the CLI for a SERVER shape change, with nothing naming the real\n * cause. Nothing caught it: `api.get<T>` is an unchecked generic over a\n * hand-written interface, `@haven_ai/core` cannot be a dependency here\n * (it is `private: true` and this package publishes), and every fixture in\n * the suite encoded the old envelope, so the tests were green against a\n * response shape the server had stopped sending.\n *\n * So the envelope is read through one function that says what went wrong.\n * This is the same principle the rest of the slice applies to the server —\n * a shape mismatch should be a typed refusal naming the cause, never a\n * silent `undefined` that surfaces somewhere else.\n */\nfunction accountsEnvelope(body: { accounts?: Safe[] }): Safe[] {\n if (!Array.isArray(body.accounts)) {\n throw new Error(\n \"GET /user/accounts did not return an `accounts` array. This CLI needs a Haven backend \" +\n 'from the release that carries #2914 or later; an older server returns the retired ' +\n '`safes` envelope. Upgrade the backend, or pin an older @haven_ai/cli.',\n )\n }\n return body.accounts\n}\n\n/**\n * One TOKEN/BALANCE table cell (#3318).\n *\n * The wire carries an additive `balanceFreshness` marker beside the balance\n * (since #3295): `stale` means the figure is real but was last read from the\n * chain at `asOf`, `unavailable` means nothing has ever been read and the\n * `'0'` beside it is a filler. Printing either as if it were current is how\n * #2769 read: a failed read renders a number the wallet does not hold. So a\n * stale entry keeps its figure and gains `≈ … (as of 45m ago)` — the tilde is\n * the \"not exact\" signal, the timestamp says how far behind it is; an\n * unavailable entry prints `unavailable` instead of the filler zero.\n * A clean entry — marker absent — renders exactly as before, byte for byte,\n * which is what keeps this additive for every existing consumer of the table.\n */\nfunction renderBalanceCell(entry: Balance & { balanceFreshness?: BalanceFreshness }): string {\n const marker = entry.balanceFreshness\n if (!marker) return entry.formatted\n if (marker.status === 'unavailable') return 'unavailable'\n return `≈ ${entry.formatted} (as of ${timeAgo(marker.asOf ?? '')})`\n}\n\nasync function cmdWalletsList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n emit(d, args.flags.json, accounts, () =>\n accounts.length === 0\n ? 'No Haven wallets yet.'\n : table(\n ['NAME', 'NETWORK', 'ADDRESS', 'DEFAULT'],\n accounts.map((s) => [s.name, chainName(s.chain_id), truncateAddress(accountAddressOf(s)), s.is_default ? '✓' : '']),\n ),\n )\n return EXIT.ok\n}\n\nasync function cmdWalletsBalances(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n const safe = pickSafe(accounts, args.flags.safe)\n if (!safe) {\n if (args.flags.safe) throw new UsageError(`No wallet matches \"${args.flags.safe}\".`)\n throw new CliApiError('No Haven wallet found.', 404)\n }\n const { balances } = await api.get<{ balances: Balance[] }>(\n `/balances/${accountAddressOf(safe)}?chain_id=${safe.chain_id}`,\n )\n emit(d, args.flags.json, { account: safe.name, chainId: safe.chain_id, balances }, () =>\n [\n `${safe.name} · ${chainName(safe.chain_id)} · ${truncateAddress(accountAddressOf(safe))}`,\n balances.length === 0\n ? ' (no balances)'\n : table(\n ['TOKEN', 'BALANCE'],\n balances.map((b) => [b.symbol, renderBalanceCell(b)]),\n ),\n ].join('\\n'),\n )\n return EXIT.ok\n}\n\nfunction pickSafe(accounts: Safe[], ref?: string): Safe | undefined {\n if (!ref) return accounts.find((s) => s.is_default) ?? accounts[0]\n const lower = ref.toLowerCase()\n return accounts.find((s) => s.id === ref || accountAddressOf(s).toLowerCase() === lower)\n}\n\n// ── Wallet funding (#2534) ──────────────────────────────────────────\n\n/**\n * The paste-ready funding instruction, read from the backend.\n *\n * The endpoint is the source; this command renders it. Every number in the\n * prose — the minimum to send, the address, the explorer link — comes out of\n * the response, so the CLI, the dashboard's funding card and the backend's\n * own docs cannot drift apart: `@haven_ai/core` owns the constants, the\n * route composes them, and nothing here repeats one. Prose mode prints the\n * sentence an agent hands to its human; `--json` prints the response object\n * itself, so a machine that wants to relay fields rather than a sentence has\n * the same facts in the same place.\n *\n * `--wait` polls until `funded` flips — how a turn actually waits out a human\n * moving money — with elapsed time visible so nobody stares at a silent\n * terminal. It exits 0 once funded and 1 on timeout (elapsed time in the\n * message); it never sends anything, never touches a faucet — this is\n * read-only facts for the human to act on, whatever the flag.\n */\nasync function cmdWalletsFunding(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n const safe = pickSafe(accounts, args.flags.safe)\n if (!safe) {\n if (args.flags.safe) throw new UsageError(`No wallet matches \"${args.flags.safe}\".`)\n throw new CliApiError('No Haven wallet found.', 404)\n }\n // The endpoint is keyed by account ID and resolves ownership itself — the\n // address/chain in the response are the route's answer, not ours to compose.\n const funding = await api.get<FundingResponse>(`/user/accounts/${safe.id}/funding`)\n\n if (!args.flags.wait) {\n emitFunding(d, funding)\n return EXIT.ok\n }\n\n // ── `--wait`: poll until the human's transfer lands ────────────────\n const started = Date.now()\n // The poll interval, injectable so tests can run the loop without real time.\n const pollMs = Number(d.env.HAVEN_FUNDING_POLL_MS ?? '5000')\n // A default cap, not a guess about the user's patience: two hours covers a\n // bank-transfer detour, and `HAVEN_FUNDING_WAIT_MS` shortens it for tests.\n const waitMs = Number(d.env.HAVEN_FUNDING_WAIT_MS ?? String(2 * 60 * 60 * 1000))\n if (!Number.isFinite(pollMs) || pollMs <= 0 || !Number.isFinite(waitMs) || waitMs <= 0) {\n throw new UsageError('HAVEN_FUNDING_POLL_MS / HAVEN_FUNDING_WAIT_MS must be positive numbers of milliseconds')\n }\n let current = funding\n for (;;) {\n // The cap is checked BEFORE each poll, so a zero-length wait exits without\n // ever calling the endpoint twice.\n const spent = Date.now() - started\n if (spent >= waitMs) {\n throw new HavenCliError(\n `Still not funded after ${elapsedLabel(spent)} — the transfer may not have landed yet. Check the explorer link, then re-run.`,\n EXIT.failed,\n )\n }\n await d.sleep(pollMs)\n current = await api.get<FundingResponse>(`/user/accounts/${safe.id}/funding`)\n if (current.funded) break\n d.o.note(`Still waiting after ${elapsedLabel(Date.now() - started)} — funded: no.`)\n }\n d.o.note(`Account shows funded after ${elapsedLabel(Date.now() - started)}.`)\n emitFunding(d, current)\n return EXIT.ok\n}\n\n/** One renderer, both modes: prose carries the paste-ready sentence. */\nfunction emitFunding(d: ResolvedDeps, funding: FundingResponse): void {\n emit(d, d.o.json, funding, () => {\n const token = funding.tokens.find((t) => t.minimum_useful_human !== null)\n const asset = token\n ? `at least ${token.minimum_useful_human} ${token.symbol}`\n : funding.native.needed\n ? funding.native.symbol\n : 'USDC'\n const gas = funding.native.needed\n ? ` plus ${funding.native.symbol} for gas`\n : ' — no gas token needed; Haven sponsors it'\n const faucet = funding.faucet_url !== undefined ? ` faucet: ${funding.faucet_url},` : ''\n return [\n `Send ${asset} on ${funding.chain.name} to ${funding.account_address}${gas}.`,\n `Explorer: ${funding.chain.explorer_url}.${faucet ? faucet.slice(0, -1) : ''}`,\n funding.funded ? 'The account already counts as funded.' : 'Nothing has arrived yet.',\n ].join('\\n')\n })\n}\n\n/** `83s` → `1m23s` → `1h02m` — the poll line and the timeout message share it. */\nfunction elapsedLabel(ms: number): string {\n const total = Math.floor(ms / 1000)\n const h = Math.floor(total / 3600)\n const m = Math.floor((total % 3600) / 60)\n const s = total % 60\n if (h > 0) return `${h}h${String(m).padStart(2, '0')}m`\n if (m > 0) return `${m}m${String(s).padStart(2, '0')}s`\n return `${s}s`\n}\n\n// ── Agents & budget ─────────────────────────────────────────────────\n\nasync function cmdAgentsList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const { agents } = await api.get<{ agents: Agent[] }>('/agents')\n emit(d, args.flags.json, agents, () =>\n agents.length === 0\n ? 'No agents yet.'\n : table(\n ['ID', 'NAME', 'STATUS', 'BUDGETS'],\n agents.map((a) => [a.id, a.name, a.status, budgetSummary(a.allowances)]),\n ),\n )\n return EXIT.ok\n}\n\nasync function cmdAgentsShow(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven agents show <id>')\n const { api } = await authed(args, d)\n const agent = await api.get<Agent>(`/agents/${id}`)\n emit(d, args.flags.json, agent, () =>\n [\n `${agent.name} [${agent.status}]`,\n `id: ${agent.id}`,\n `budget: ${budgetSummary(agent.allowances)}`,\n ].join('\\n'),\n )\n return EXIT.ok\n}\n\n/**\n * The one command that prints a delegation hash (#2612).\n *\n * `budget revoke` takes a hash as its second argument, and until this existed\n * NO `haven` command printed one — while the README and the revoke usage error\n * both said `haven agents show` did. It does not: that response carries the\n * allowances projection and has no hash field at all. Both now point here, and\n * a test asserts this literal appears in the README AND that running it emits\n * a hash, so the instruction and the output cannot drift apart again.\n */\nexport const HASH_DISCOVERY_HINT = 'haven budget show <agentId> --hashes'\n\nasync function cmdBudgetShow(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven budget show <agentId> [--hashes]')\n const { api } = await authed(args, d)\n\n // #2612: a DIFFERENT read, deliberately behind a flag. The hashes live on\n // GET /agents/:id/delegations, not on the agent's allowances projection, and\n // `budget show --json` has emitted a bare allowances array since the first\n // CLI scaffold — adding a second shape to that array would break every\n // existing consumer of it.\n if (args.flags.hashes) {\n const { delegations } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n emit(d, args.flags.json, delegations, () =>\n delegations.length === 0\n ? `No delegations on agent ${id}.`\n : table(\n ['DELEGATION HASH', 'STATUS', 'VERSION'],\n delegations.map((r) => [r.delegation_hash, r.status, String(r.version)]),\n ),\n )\n return EXIT.ok\n }\n\n const agent = await api.get<Agent>(`/agents/${id}`)\n const allowances = agent.allowances ?? []\n emit(d, args.flags.json, allowances, () =>\n allowances.length === 0\n ? `${agent.name} has no configured budget.`\n : table(\n ['TOKEN', 'AMOUNT', 'RESETS'],\n allowances.map((a) => [a.token_symbol, a.allowance_amount, resetLabel(a.reset_period_min)]),\n ),\n )\n return EXIT.ok\n}\n\nfunction budgetSummary(allowances?: Allowance[]): string {\n if (!allowances || allowances.length === 0) return '—'\n return allowances.map((a) => `${a.allowance_amount} ${a.token_symbol}`).join(', ')\n}\n\n// ── Budget grant/revoke (#2539, C3) — construct-and-hand-off ────────────────\n//\n// Both commands CONSTRUCT a signature request and print a dashboard link the\n// human signs in the browser. The CLI never signs and never calls activate —\n// that is the whole safety property of this slice, and the reason the backend\n// allow-list can carry build + revoke-prepare at all.\n\n/** The POST /agents/:id/delegations/build response the CLI consumes (#2539). */\ninterface DelegationBuild {\n delegation_hash: string\n version: number\n /** The same value as delegation_hash — one identifier, no new column. */\n build_id: string\n typed_data_hash: string\n signing_url: string\n}\n\n/** One row of GET /agents/:id/delegations (#2539's --wait reads these). */\ninterface DelegationRow {\n delegation_hash: string\n version: number\n status: 'pending' | 'active' | 'replaced' | 'revoked'\n /**\n * #3922: the backend's budget-view liveness (`active` and unexpired). Absent\n * on an older backend — a missing value means \"derive from `status`\", never\n * false.\n */\n is_live?: boolean\n}\n\n/**\n * The \"still enabled\" delegation statuses (#3922): a row is enabled on-chain\n * until the chain confirms it dead, so only `revoked` is not. This is the CLI's\n * ONE copy of `STILL_ENABLED_DELEGATION_STATUSES` from `@haven_ai/core` — the\n * published CLI cannot depend on that private package — and\n * `commands.test.ts` pins the two together. The revoke gate reads STATUS, not\n * `is_live`: it guards against leaving on-chain authority behind and must work\n * against an older backend that sends no `is_live`.\n */\nconst STILL_ENABLED_STATUSES: ReadonlySet<string> = new Set([\n 'pending',\n 'active',\n 'replaced',\n])\n\n/** The POST /agents/:id/delegations/:hash/revoke prepare response (#2539). */\ninterface RevocationPrepare {\n signature_scheme?: 'eip712_userop' | 'webauthn_userop'\n /** Dashboard revoke link, built by the backend from its own FRONTEND_URL. */\n revocation_url?: string\n}\n\n/** How long `--wait` polls before giving up. */\nconst BUDGET_WAIT_TIMEOUT_S = 15 * 60\nconst BUDGET_WAIT_INTERVAL_MS = 5_000\n\n/**\n * `haven budget grant` — construct the budget delegation, hand the signature\n * to the human (#2539).\n *\n * Calls the build route with the owner_cli session, stores nothing itself,\n * and prints the signing link the backend built. `--wait` polls the agent's\n * delegation list for the returned hash to reach `active`, which converges\n * because the build is idempotent within its expiry: the dashboard form's own\n * rebuild of the same grant returns the SAME hash instead of minting a new\n * version that would strand this poller.\n */\nasync function cmdBudgetGrant(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) {\n throw new UsageError('Usage: haven budget grant <agentId> --amount 25 --token USDC --period <minutes> [--recipient <address>] [--expires <unix-seconds>] [--wait]')\n }\n if (!args.flags.amount || !args.flags.token || args.flags.period === undefined) {\n throw new UsageError('--amount, --token and --period are required (period is whole minutes, at least 1)')\n }\n // The delegation rail has no one-time period: `/delegations/build` refuses\n // anything under 60 seconds. `agents connect` DOES take `--period 0` for\n // `reset_period_min`, which is a different field on a different route, and\n // this command's usage text was first written from that convention — so a\n // caller following it hit an opaque 400 from the backend instead of this\n // sentence. Refuse it here, where the message can say what to pass instead.\n if (args.flags.period < 1) {\n 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.')\n }\n const { api } = await authed(args, d)\n\n // Fail fast on the rail this command cannot serve, and read the token's\n // decimals from the backend — the same registry the dashboard form sizes\n // budgets with, never a local table.\n const agent = await api.get<Agent & {\n account_type?: string | null\n account_address?: string | null\n account_chain_id?: number | null\n }>(`/agents/${id}`)\n if (agent.account_type !== 'delegator_hybrid') {\n throw new HavenCliError(\n `Agent ${id} is not on the delegation rail — budgets are managed from the dashboard for this account.`,\n EXIT.refused,\n )\n }\n const accountAddress = agent.account_address\n const accountChainId = agent.account_chain_id\n if (!accountAddress || !accountChainId) {\n throw new HavenCliError(`Agent ${id} has no wallet assigned yet — connect it first.`, EXIT.refused)\n }\n const { balances } = await api.get<{ balances: BalanceToken[] }>(\n `/balances/${accountAddress}?chain_id=${accountChainId}`,\n )\n const wanted = args.flags.token.trim().toUpperCase()\n const token = balances.find((b) => b.symbol.toUpperCase() === wanted)\n if (!token || !token.address) {\n const known = balances.map((b) => b.symbol).join(', ')\n throw new UsageError(`Unknown token ${args.flags.token} on this wallet's chain. Available: ${known || 'none'}`)\n }\n const amount = parseTokenAmount(args.flags.amount, token.decimals, token.symbol)\n if (!amount.ok) throw new UsageError(amount.message)\n\n let built: DelegationBuild\n try {\n built = await api.post<DelegationBuild>(`/agents/${id}/delegations/build`, {\n token_address: token.address,\n recipient_address: args.flags.recipient ?? null,\n budget_atomic: amount.atomic,\n period_seconds: args.flags.period * 60,\n ...(args.flags.expires !== undefined ? { expires_at: args.flags.expires } : {}),\n })\n } catch (err) {\n // #3933: a live budget already holds this (token, recipient) slot. A grant\n // cannot replace it — that would leave the old one enabled on-chain — so\n // the owner edits it on the agent page, which replaces it and stops the\n // old one. Branch on the code, never the sentence.\n const body = err instanceof CliApiError ? (err.body as { error_code?: string; existing_delegation_hash?: string } | undefined) : undefined\n if (body?.error_code === 'BUDGET_SLOT_OCCUPIED') {\n throw new HavenCliError(\n err instanceof Error ? err.message : 'This agent already has a live budget for this token and recipient.',\n EXIT.refused,\n \"Edit that budget on the agent's page in the Haven dashboard instead: editing replaces it and stops the old one on-chain. Open task and sub-budgets carved from the old budget end when it is stopped.\",\n { error_code: 'BUDGET_SLOT_OCCUPIED', existing_delegation_hash: body.existing_delegation_hash ?? null },\n )\n }\n throw err\n }\n\n const emitGrant = (status?: DelegationRow['status']) =>\n emit(d, args.flags.json, { ...built, agent_id: id, status: status ?? 'pending' }, () =>\n [\n `Budget of ${args.flags.amount} ${token.symbol} per ${args.flags.period} minutes built for agent ${id}.`,\n args.flags.recipient ? `Recipient pin: ${args.flags.recipient}` : null,\n 'Open this link and sign — the budget goes live the moment you do:',\n built.signing_url,\n `Delegation: ${built.delegation_hash} (version ${built.version})`,\n status === 'active' ? 'Signed and active.' : 'Waiting for your signature. Run the same command with --wait to poll until it is active.',\n ]\n .filter((line): line is string => line !== null)\n .join('\\n'),\n )\n\n emitGrant()\n if (!args.flags.wait) return EXIT.ok\n\n const deadline = Date.now() + BUDGET_WAIT_TIMEOUT_S * 1000\n while (Date.now() < deadline) {\n await d.sleep(BUDGET_WAIT_INTERVAL_MS)\n const { delegations } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n const mine = delegations.find((row) => row.delegation_hash === built.delegation_hash)\n // #3922: the backend's `is_live` when sent; an older backend omits it, so\n // fall back to the status it always sent (missing is never \"not live\").\n if (mine && (mine.is_live ?? mine.status === 'active')) {\n emitGrant('active')\n return EXIT.ok\n }\n if (mine?.status === 'revoked' || mine?.status === 'replaced') {\n throw new HavenCliError(\n `Delegation ${built.delegation_hash} is now ${mine.status} without being signed.`,\n EXIT.refused,\n )\n }\n }\n throw new HavenCliError(\n `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 — sign it, or rerun with --wait.`,\n EXIT.failed,\n )\n}\n\n/**\n * `haven budget revoke` — prepare the revocation, hand the signature to the\n * human (#2539).\n *\n * Calls the per-hash revoke PREPARE route (one sponsored UserOp, unsigned)\n * and prints the revocation link the backend built. Nothing is submitted and\n * no row flips here: the budget keeps working until the owner signs in the\n * dashboard, which is what `--wait` polls for.\n */\nasync function cmdBudgetRevoke(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const [id, hash] = args.positionals\n if (!id || !hash) throw new UsageError('Usage: haven budget revoke <agentId> <delegationHash> [--wait]')\n if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {\n throw new UsageError(`The delegation hash must be 0x followed by 64 hex characters — \\`${HASH_DISCOVERY_HINT}\\` lists them, or the dashboard.`)\n }\n\n const { api } = await authed(args, d)\n const { delegations } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n const row = delegations.find((r) => r.delegation_hash.toLowerCase() === hash.toLowerCase())\n if (!row) {\n throw new HavenCliError(`No delegation ${hash} on agent ${id}.`, EXIT.refused)\n }\n if (row.status === 'revoked') {\n throw new HavenCliError(`Delegation ${hash} is already revoked.`, EXIT.refused)\n }\n // #3542 / #3729: a `replaced` row is still live — the newer grant does not\n // undo it until the newer delegation is itself revoked. The backend's\n // prepare route accepts `replaced` (it only rejects `revoked`), so this\n // refusal was a dead end for an agent whose only live row had been\n // replaced: the row is prepared for revocation like any other live one.\n\n // PREPARE only: the response carries the unsigned UserOp and the dashboard\n // link. The /submit step stays owner-session-only by design.\n const prepared = await api.post<RevocationPrepare>(`/agents/${id}/delegations/${hash}/revoke`, {})\n const revokeUrl = prepared.revocation_url\n if (!revokeUrl) {\n throw new HavenCliError(\n 'The backend did not return a revocation link — it may be older than #2539. Finish the revocation in the dashboard.',\n EXIT.failed,\n )\n }\n\n const emitRevoke = (status: DelegationRow['status'] | 'pending_revoke') =>\n emit(d, args.flags.json, { agent_id: id, delegation_hash: hash, status, ...prepared }, () =>\n [\n 'Revocation prepared — one signature, sponsored (no gas).',\n 'Open this link and sign to stop this budget:',\n revokeUrl,\n `Delegation: ${hash}`,\n status === 'revoked' ? 'Revoked.' : 'The budget keeps working until you sign. Run the same command with --wait to poll until it is revoked.',\n ]\n .filter((line): line is string => line !== null)\n .join('\\n'),\n )\n\n emitRevoke('pending_revoke')\n if (!args.flags.wait) return EXIT.ok\n\n const deadline = Date.now() + BUDGET_WAIT_TIMEOUT_S * 1000\n while (Date.now() < deadline) {\n await d.sleep(BUDGET_WAIT_INTERVAL_MS)\n const { delegations: after } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n const mine = after.find((r) => r.delegation_hash.toLowerCase() === hash.toLowerCase())\n if (mine?.status === 'revoked') {\n emitRevoke('revoked')\n return EXIT.ok\n }\n }\n throw new HavenCliError(\n `Timed out waiting for delegation ${hash} to be revoked (${BUDGET_WAIT_TIMEOUT_S / 60} minutes). The link stays valid — sign it, or rerun with --wait.`,\n EXIT.failed,\n )\n}\n\nfunction resetLabel(mins: number): string {\n if (mins === 0) return 'one-time'\n if (mins === 1440) return 'daily'\n if (mins === 10080) return 'weekly'\n if (mins === 43200) return 'monthly'\n return `every ${mins}m`\n}\n\nasync function cmdAgentLifecycle(args: ParsedArgs, d: ResolvedDeps, action: 'pause' | 'resume'): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError(`Usage: haven agents ${action} <id>`)\n const { api } = await authed(args, d)\n await api.post(`/agents/${id}/${action}`)\n const status = action === 'pause' ? 'paused' : 'resumed'\n // #3722: pause/resume are Haven-side only; say so, so nobody reads \"paused\" as a stopped budget.\n emit(d, args.flags.json, { ok: true, agent_id: id, status }, () =>\n action === 'pause'\n ? `Agent ${id} paused: payments through Haven are blocked, but its budget stays live on-chain (end it with \\`haven budget revoke\\`).`\n : `Agent ${id} resumed: payments through Haven are allowed again.`,\n )\n return EXIT.ok\n}\n\nasync function cmdAgentRevoke(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven agents revoke <id> [--keep-budget] --yes')\n // Revoke is terminal (status can't go back to active). Require explicit --yes\n // so it can't happen by accident in a script.\n if (!args.flags.yes) {\n throw new UsageError(\n `This permanently retires agent ${id} in Haven.`,\n 'Re-run with --yes to confirm. Revoke is terminal — the agent cannot go back to active. ' +\n 'It ends no budget on-chain: end each live budget with `haven budget revoke <agentId> <delegationHash>`.',\n )\n }\n const { api } = await authed(args, d)\n\n // #3729: POST /agents/:id/revoke is a status flip — it changes no delegation\n // row and makes no on-chain call — so a live budget delegation outlives the\n // revoke, and whoever holds the delegate key can keep redeeming it. The\n // gate reads the server's own live count instead of keeping a CLI copy of\n // the live set, then names each live row's exact revocation command. A\n // budget going live between this read and the POST is accepted: this is a\n // client-side guard, not an authority control (the superseded-agent path\n // and older CLIs can still create that state).\n let live: DelegationRow[] = []\n try {\n const agent = await api.get<Agent>(`/agents/${id}`)\n if ((agent.live_delegation_count ?? 0) > 0) {\n const { delegations } = await api.get<{ delegations: DelegationRow[] }>(`/agents/${id}/delegations`)\n live = delegations.filter((r) => STILL_ENABLED_STATUSES.has(r.status))\n }\n } catch (err) {\n // Fail closed: without the live set, no revoke. The read's own exit\n // class stands (401 → 3, network → 5, 403/404 → refused) — the note only\n // explains why the revoke never happened, it does not re-classify the\n // failure.\n d.o.note(`Couldn't check budgets for agent ${id}, so the revocation was not attempted.`)\n throw err\n }\n\n if (live.length > 0 && !args.flags.keepBudget) {\n throw new HavenCliError(\n `Agent ${id} still has a live on-chain budget. Revoking now would leave it redeemable by the delegate key.`,\n EXIT.refused,\n [\n ...live.map((r) => `haven budget revoke ${id} ${r.delegation_hash} # ${r.status}`),\n 'Remove agent… in the dashboard ends every live budget with one signature, before revoking.',\n 'To revoke the agent anyway and leave the budget live on-chain, re-run with --keep-budget.',\n ].join('\\n'),\n // The machine branch: a script skips the prose and reads the rows.\n { live_delegations: live.map(({ delegation_hash, status }) => ({ delegation_hash, status })) },\n )\n }\n\n await api.post(`/agents/${id}/revoke`)\n emit(\n d,\n args.flags.json,\n live.length > 0\n ? {\n ok: true,\n agent_id: id,\n status: 'revoked',\n live_delegations: live.map(({ delegation_hash, status }) => ({ delegation_hash, status })),\n }\n : { ok: true, agent_id: id, status: 'revoked' },\n () =>\n live.length > 0\n ? [\n `Agent ${id} revoked.`,\n `Its budget is still live on-chain: the delegate key can keep spending until each delegation is revoked.`,\n ...live.map((r) => `haven budget revoke ${id} ${r.delegation_hash} # ${r.status}`),\n ].join('\\n')\n : `Agent ${id} revoked in Haven. It had no live budget on-chain.`,\n )\n return EXIT.ok\n}\n\nasync function cmdAgentRotateKey(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven agents rotate-key <id>')\n const { api } = await authed(args, d)\n const res = await api.post<{ api_key: string; api_key_prefix: string }>(`/agents/${id}/rotate-key`)\n // The key is the payload, so it belongs on stdout in both modes. The\n // SENTENCE about it is prose and moves to stderr under --json, which is what\n // keeps stdout a single parseable object with a secret in exactly one field.\n d.o.note('New API key (shown once — store it now; the old key stops working):')\n emit(d, args.flags.json, res, () => res.api_key)\n return EXIT.ok\n}\n\nasync function cmdAgentRename(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const [id, ...nameParts] = args.positionals\n const name = nameParts.join(' ').trim()\n if (!id || !name) throw new UsageError('Usage: haven agents rename <id> <name>')\n const { api } = await authed(args, d)\n await api.put(`/agents/${id}`, { name })\n emit(d, args.flags.json, { ok: true, agent_id: id, name }, () => `Agent ${id} renamed to \"${name}\".`)\n return EXIT.ok\n}\n\nasync function cmdWalletRename(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const [id, ...nameParts] = args.positionals\n const name = nameParts.join(' ').trim()\n if (!id || !name) throw new UsageError('Usage: haven wallets rename <id> <name>')\n const { api } = await authed(args, d)\n await api.put(`/user/accounts/${id}`, { name })\n emit(d, args.flags.json, { ok: true, account_id: id, name }, () => `Wallet ${id} renamed to \"${name}\".`)\n return EXIT.ok\n}\n\n// ── Activity ────────────────────────────────────────────────────────\n\n/**\n * Resolve `--safe` (id or address) to an account id for the `/transactions` filter,\n * mirroring `wallets balances`. Throws if `--safe` was given but matches no\n * wallet, so a typo'd filter fails loudly instead of silently returning all rows.\n */\nasync function resolveAccountId(args: ParsedArgs, api: CliApi): Promise<string | undefined> {\n if (!args.flags.safe) return undefined\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n const safe = pickSafe(accounts, args.flags.safe)\n if (!safe) throw new UsageError(`No wallet matches \"${args.flags.safe}\".`)\n return safe.id\n}\n\nasync function cmdActivityList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const accountId = await resolveAccountId(args, api)\n const params = new URLSearchParams({\n offset: String(args.flags.offset ?? 0),\n limit: String(args.flags.limit ?? 25),\n })\n if (accountId) params.set('accountId', accountId)\n if (args.flags.agent) params.set('agentId', args.flags.agent)\n const { transactions } = await api.get<{ transactions: Txn[] }>(`/transactions?${params.toString()}`)\n const visible = args.flags.direction\n ? transactions.filter((t) => t.direction === args.flags.direction)\n : transactions\n emit(d, args.flags.json, visible, () =>\n visible.length === 0\n ? 'No activity.'\n : table(\n ['DATE', 'DIR', 'AMOUNT', 'TYPE', 'ACCOUNT'],\n visible.map((t) => [\n new Date(t.timestamp * 1000).toISOString().slice(0, 10),\n t.direction === 'in' ? 'in' : 'out',\n `${t.direction === 'in' ? '+' : '-'}${t.valueFormatted} ${t.asset}`,\n t.source ?? 'transfer',\n t.accountName ?? '',\n ]),\n ),\n )\n return EXIT.ok\n}\n\nasync function cmdActivityExport(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n if (args.flags.format === 'sie') return exportSie(args, d)\n const { api } = await authed(args, d)\n const accountId = await resolveAccountId(args, api)\n const params = new URLSearchParams({\n offset: String(args.flags.offset ?? 0),\n limit: String(args.flags.limit ?? 1000),\n })\n if (accountId) params.set('accountId', accountId)\n if (args.flags.agent) params.set('agentId', args.flags.agent)\n const { transactions } = await api.get<{ transactions: Txn[] }>(`/transactions?${params.toString()}`)\n const visible = args.flags.direction\n ? transactions.filter((t) => t.direction === args.flags.direction)\n : transactions\n\n // Same columns as the dashboard export (#411), minus counterparty_name\n // (no contacts join in the CLI yet).\n const headers = [\n 'date', 'type', 'status', 'direction', 'amount', 'token_symbol', 'token_address',\n 'counterparty_address', 'agent_name', 'tx_hash', 'chain_id', 'account_address',\n ]\n const rows = visible.map((t) => [\n new Date(t.timestamp * 1000).toISOString(),\n exportType(t),\n exportStatus(t),\n t.direction,\n t.valueFormatted,\n t.tokenSymbol ?? t.asset ?? '',\n t.tokenAddress ?? '',\n (t.direction === 'in' ? t.from : t.to) ?? '',\n t.agentName ?? '',\n t.hash,\n t.chainId != null ? String(t.chainId) : '',\n t.accountAddress ?? '',\n ])\n d.o.text(toCsv(headers, rows), { format: 'csv', rows: rows.length })\n return EXIT.ok\n}\n\nfunction exportType(t: Txn): string {\n if (t.activityType === 'delegate_sweep') return 'sweep'\n if (t.source === 'x402') return 'x402'\n if (t.source === 'mpp_demo') return 'mpp'\n return t.direction === 'in' ? 'receive' : 'send'\n}\n\nfunction exportStatus(t: Txn): string {\n if (t.isError) return 'failed'\n if (t.paymentFlowStatus === 'confirming_merchant') return 'pending'\n return 'executed'\n}\n\n/** SIE 4I export: the backend builds the verifikat file (book-time SEK + BAS). */\nasync function exportSie(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const params = new URLSearchParams({ format: 'sie' })\n if (args.flags.from) params.set('from', args.flags.from)\n if (args.flags.to) params.set('to', args.flags.to)\n if (args.flags.company) params.set('company', args.flags.company)\n const content = await api.getText(`/accounting/export?${params.toString()}`)\n d.o.text(content, { format: 'sie' })\n return EXIT.ok\n}\n\n// ── Catalog ─────────────────────────────────────────────────────────\n\nasync function cmdCatalogList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const { entries } = await api.get<{ entries: CatalogEntry[] }>('/catalog')\n emit(d, args.flags.json, entries, () =>\n entries.length === 0\n ? 'Catalog is empty.'\n : table(\n ['NAME', 'CATEGORY', 'RAIL', 'PRICE', 'STATUS'],\n entries.map((e) => [e.name, e.category, e.rail, e.price_display ?? '—', e.status]),\n ),\n )\n return EXIT.ok\n}\n\n\n// ── Connect (#2527) ─────────────────────────────────────────────────\n\n/**\n * Resolve the wallet this setup belongs to, and the token's decimals.\n *\n * The decimals are READ from the backend rather than kept in a table here.\n * `GET /balances/:accountAddress` lists every token the chain is configured for —\n * zero balance included — with its address and decimals, which is the same\n * registry the dashboard modal reads. A local table would be a second source\n * of truth for a number that decides a budget's magnitude, and it would drift\n * silently the first time a chain gained a token.\n */\nasync function resolveWalletAndToken(\n args: ParsedArgs,\n api: CliApi,\n symbol: string,\n): Promise<{ accountId: string; token: BalanceToken }> {\n const accounts = accountsEnvelope(await api.get<{ accounts?: Safe[] }>('/user/accounts'))\n if (accounts.length === 0) {\n throw new HavenCliError('No wallet on this account yet — finish onboarding first.', EXIT.refused)\n }\n const safe = args.flags.safe\n ? accounts.find((s) => s.id === args.flags.safe || accountAddressOf(s) === args.flags.safe)\n : (accounts.find((s) => s.is_default) ?? accounts[0])\n if (!safe) throw new UsageError(`No wallet matches --safe ${args.flags.safe}`)\n\n // `chain_id` is REQUIRED here, not decorative. A passkey set derives the same\n // account address on every chain, so one address can own more than one\n // ownership row (an account on each of two chains) — and\n // `GET /balances/:address` answers `400 chain_id required` rather than\n // guessing when it finds more than one (`routes/balances.ts`). `wallets\n // balances` has always passed it; this call omitted it and would have failed\n // for any address with accounts on more than one chain (haven-reviewer,\n // #2527).\n const { balances } = await api.get<{ balances: BalanceToken[] }>(\n `/balances/${accountAddressOf(safe)}?chain_id=${safe.chain_id}`,\n )\n const wanted = symbol.trim().toUpperCase()\n const token = balances.find((b) => b.symbol.toUpperCase() === wanted)\n if (!token) {\n const known = balances.map((b) => b.symbol).join(', ')\n throw new UsageError(`Unknown token ${symbol} on this wallet's chain. Available: ${known || 'none'}`)\n }\n return { accountId: safe.id, token }\n}\n\n/** Poll a setup until it leaves the states that are still in flight. */\nconst SETTLED = new Set(['active', 'expired', 'cancelled', 'failed'])\n\nasync function pollSetup(\n api: CliApi,\n setupId: string,\n d: ResolvedDeps,\n wait: boolean,\n): Promise<SetupStatus> {\n let status = await api.get<SetupStatus>(`/agent-connection-setups/${setupId}`)\n if (!wait) return status\n // Bounded by the setup's own expiry rather than a local guess, so the loop\n // cannot outlive the thing it is watching.\n const deadline = new Date(status.expires_at).getTime()\n while (!SETTLED.has(status.status) && Date.now() < deadline) {\n await d.sleep(5000)\n status = await api.get<SetupStatus>(`/agent-connection-setups/${setupId}`)\n }\n return status\n}\n\n/**\n * `haven agents connect` — the connect flow without the dashboard modal.\n *\n * Three shapes: create a setup, `--status <id>` to read one, and `--run` to\n * additionally execute the connector command the backend printed.\n *\n * The command is PRINTED, never composed. `connector_command` comes back from\n * `POST /agent-connection-setups` and is emitted verbatim, which is what makes\n * it byte-identical to the dashboard's for the same setup — they are the same\n * string from the same builder, not two constructions that have to be kept in\n * agreement.\n */\nasync function cmdAgentsConnect(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n\n if (args.flags.status) {\n const status = await pollSetup(api, args.flags.status, d, args.flags.wait)\n emit(d, args.flags.json, status, () =>\n [\n `setup ${status.setup_id}: ${status.status}`,\n status.agent_id ? `agent: ${status.agent_id}` : null,\n SETTLED.has(status.status) ? null : `approve: ${status.approval_url}`,\n ]\n .filter(Boolean)\n .join('\\n'),\n )\n return EXIT.ok\n }\n\n const name = args.flags.name?.trim()\n if (!name) throw new UsageError('Usage: haven agents connect --name <name> --budget <amount> --token USDC --period <minutes>')\n if (!args.flags.budget || !args.flags.token || args.flags.period === undefined) {\n throw new UsageError('--budget, --token and --period are required (period is whole minutes; 0 means one-time)')\n }\n\n const { accountId, token } = await resolveWalletAndToken(args, api, args.flags.token)\n const amount = parseTokenAmount(args.flags.budget, token.decimals, token.symbol)\n if (!amount.ok) throw new UsageError(amount.message)\n\n const setup = await api.post<CreateSetupResponse>('/agent-connection-setups', {\n name,\n account_id: accountId,\n allowances: [\n {\n token_address: token.address ?? '0x0000000000000000000000000000000000000000',\n token_symbol: token.symbol,\n // ATOMIC on the way in, human on the way back (#2295). Converted here\n // exactly once, from the decimals the backend just told us.\n allowance_amount: amount.atomic,\n reset_period_min: args.flags.period,\n },\n ],\n // How this setup was made, for connect attribution (#2302). The route\n // already accepts any slug, so nothing backend-side had to change.\n source: 'cli',\n // #2522: the hand-off marker, set only when an agent is driving this CLI\n // and says so. Never inferred — a guess here mislabels a human's own run.\n ...(d.env.HAVEN_AGENT_DRIVEN === '1' ? { via: 'agent' } : {}),\n })\n\n if (!args.flags.run) {\n emit(d, args.flags.json, setup, () =>\n [\n 'Run this where the agent runs:',\n '',\n setup.connector_command,\n '',\n `Then approve the budget: ${setup.approval_url}`,\n `Setup ${setup.setup_id} expires ${setup.expires_at}.`,\n ].join('\\n'),\n )\n return EXIT.ok\n }\n\n // `--run`: execute the printed command with `--json` appended and nothing\n // else changed. The connector's stderr is streamed as it arrives — a run can\n // take minutes and that is the only progress anyone sees.\n const run = await runConnector(setup.connector_command, d.spawner, (chunk) => d.err(chunk.trimEnd()))\n const relay = relayLine(run.outcome)\n const merged = {\n setup_id: setup.setup_id,\n approval_url: setup.approval_url,\n connector_command: setup.connector_command,\n connector_exit_code: run.exitCode,\n outcome: run.outcome,\n relay,\n }\n\n if (isRefusal(run.outcome)) {\n // Exit 4 with the refusal carried whole. Recognised by the presence of\n // `error`, never by matching a code — a refusal the connector adds later\n // reaches the user through this same path with no CLI change.\n emitConnectResult(d, args.flags.json, merged, relay)\n return EXIT.refused\n }\n if (!run.outcome) {\n throw new HavenCliError(\n `The connector produced no outcome (exit ${run.exitCode}).${run.stdoutNoise ? ` Output: ${run.stdoutNoise}` : ''}`,\n run.exitCode === 0 ? EXIT.failed : EXIT.failed,\n )\n }\n emitConnectResult(d, args.flags.json, merged, relay)\n return EXIT.ok\n}\n\n/**\n * Print a `--run` result with the relay line FIRST under prose (#2483's\n * one-gate rule): whatever the human has to act on outranks the record of what\n * happened, because a link buried under an outcome dump is a link nobody sees.\n */\nfunction emitConnectResult(\n d: ResolvedDeps,\n json: boolean,\n merged: { relay: string | null; outcome: ConnectorOutcome | null; setup_id: string },\n relay: string | null,\n): void {\n emit(d, json, merged, () =>\n [relay, relay ? '' : null, `setup ${merged.setup_id}: ${merged.outcome?.outcome ?? 'unknown'}`]\n .filter((line) => line !== null)\n .join('\\n'),\n )\n}\n\n// ── Contacts ────────────────────────────────────────────────────────\n\nasync function cmdContactsList(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const { api } = await authed(args, d)\n const { contacts } = await api.get<{ contacts: Contact[] }>('/contacts')\n emit(d, args.flags.json, contacts, () =>\n contacts.length === 0\n ? 'No contacts yet.'\n : table(['ID', 'NAME', 'ADDRESS'], contacts.map((c) => [c.id, c.name, truncateAddress(c.address)])),\n )\n return EXIT.ok\n}\n\nasync function cmdContactsAdd(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const [address, ...nameParts] = [...args.positionals].reverse()\n // positionals are <name...> <address>; address is last, name is the rest.\n const name = nameParts.reverse().join(' ').trim()\n if (!name || !address) throw new UsageError('Usage: haven contacts add <name> <address>')\n const { api } = await authed(args, d)\n const contact = await api.post<Contact>('/contacts', { name, address })\n emit(d, args.flags.json, contact, () => `Added contact \"${contact.name}\" (${truncateAddress(contact.address)}).`)\n return EXIT.ok\n}\n\nasync function cmdContactsRemove(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const id = args.positionals[0]\n if (!id) throw new UsageError('Usage: haven contacts remove <id>')\n const { api } = await authed(args, d)\n await api.del(`/contacts/${id}`)\n emit(d, args.flags.json, { ok: true, contact_id: id, removed: true }, () => `Contact ${id} removed.`)\n return EXIT.ok\n}\n\n// ── Feedback ──────────────────────────────────────────────────────────\n\n/**\n * `haven feedback submit \"<text>\"` (#3597). Several unquoted words are\n * JOINED into one text with a single space between them — the same\n * convention `contacts add <name...> <address>` already uses for its own\n * free-text argument — rather than refused, so a bug report does not have to\n * be hand-quoted.\n *\n * `authed` runs FIRST (a command with no session refuses before anything\n * else, same as every other command), then the secret check runs — and it\n * is the check, not `authed`, that has to run before the one call that would\n * carry the text (`api.post` at the end): a refusal here never reaches the\n * network at all.\n */\nasync function cmdFeedbackSubmit(args: ParsedArgs, d: ResolvedDeps): Promise<number> {\n const text = args.positionals.join(' ').trim()\n if (!text) throw new UsageError('Usage: haven feedback submit \"<text>\"')\n // Code points, not UTF-16 units — `text.length` double-counts anything\n // outside the Basic Multilingual Plane (an emoji in a bug report is not\n // exotic), and the backend's own ceiling (`routes/feedback.ts`'s ajv\n // schema `maxLength`) counts code points too. `[...text]` iterates by\n // code point.\n if ([...text].length > MAX_FEEDBACK_TEXT_LENGTH) {\n throw new UsageError(`Feedback text must be ${MAX_FEEDBACK_TEXT_LENGTH} characters (code points) or fewer.`)\n }\n\n const { session, api } = await authed(args, d)\n\n const refusal = await checkTextForSecrets(text, {\n api,\n localSecrets: { sessionToken: session.token, env: d.env, baseDir: d.credentialsBaseDir },\n })\n if (refusal) {\n throw new HavenCliError(refusal.message, EXIT.refused, `layer ${refusal.layer}: ${refusal.reason}`, {\n layer: refusal.layer,\n reason: refusal.reason,\n })\n }\n\n // The one residual-risk case the check cannot catch by shape at all: a\n // plain password has no recognisable form. stderr only, so `--json`'s\n // stdout contract (one value, nothing else) stays exactly one value.\n d.o.note(\n 'Reminder: never include a password or any other credential in feedback text — this check cannot recognise one by shape.',\n )\n\n const result = await api.post<{ id: string; created_at: string; expires_at: string }>('/feedback', { text })\n emit(d, args.flags.json, { ok: true, ...result }, () => `Feedback submitted (id ${result.id}).`)\n return EXIT.ok\n}\n"]}
|