Skip to content
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,14 +209,14 @@ Run any of these with `npx ethagent`. Commands marked interactive need a termina
| `storage [--set \| --forget] [--json]` | Where snapshots are pinned and whether a credential is set. `--set` saves a Pinata JWT read from stdin; `--forget` removes it after a preview. | Read-only; `--set` and `--forget` write secrets |
| `create --name <text> --network <network> [--description <text>] [--advanced] [--import] [--replace] [--yes] [--json]` | Mint a new agent with its first snapshot. `--advanced` continues into a Vault in the same tab; `--replace` is needed when this machine already has an agent. Previews until `--yes`. | Opens your wallet |
| `restore [<token-id> \| <name>] [--network <network>] [--operator] [--yes] [--json]` | Rebuild an agent on this machine, or with no target pull the newest onchain snapshot into the vault. Previews until `--yes`. | Opens your wallet, or none with `--operator` |
| `restore --owner <address\|name> [--json]` | List the agents a wallet holds or operates. | Goes online |
| `restore --owner <address\|name> [--json]` | List the agents a wallet holds or operates, including ones it deposited into a Vault. When the RPC can't serve the log history to check, it says so and exits 1 instead of listing nothing; point `ETHAGENT_RPC_URL` at a fuller RPC and pass `--network`. | Goes online |
| `profile [--name <text>] [--description <text>] [--image <path\|url\|none>] [--operator] [--yes] [--json]` | Show the public profile, or change it and publish in one save. Previews until `--yes`. | Opens your wallet, or none with `--operator` |
| `custody [--json]` | Custody mode, the Vault and its build, whether it holds the token, the Vault-level owner, and the approved operators. | Goes online |
| `custody --verify [--json]` | Also simulates, sending nothing: the owner withdrawing and changing an operator, the operator rotating the agent URI, and the operator and a stranger being refused. Exits 4 on a mismatch. | Goes online |
| `ens [--json]` | The linked name, its records, the two-way check, the resolver, who controls the name, and whether the operator key could sign for it. | Goes online |
| `ens <name> [--operator] [--yes] [--json]` | Point the agent at a name: create it under a parent the signer controls, write the agent records, clear them on the old name, then publish the name. Previews until `--yes`. | Opens your wallet |
| `ens --unlink [--operator] [--yes] [--json]` | Clear the agent records on the linked name, then publish it unlinked. Previews until `--yes`. | Opens your wallet |
| `ens --delete [--yes] [--json]` | Unlink as above, then remove the subname from its parent. Signed by the wallet that manages the parent. Previews until `--yes`. | Opens your wallet |
| `ens --delete [--operator] [--yes] [--json]` | Unlink as above, then remove the subname from its parent. Signed by the wallet that manages the parent, which may be the operator key. Previews until `--yes`. | Opens your wallet |
| `ens --set <key>=<value> --clear <key> [--operator] [--yes] [--json]` | Write every record change in one transaction. No save needed. Previews until `--yes`. | Opens your wallet, or none with `--operator` |
| `custody --advanced [--yes] [--json]` | Deploy a Vault (or reuse one), deposit the token, and save. Previews until `--yes`. | Opens your wallet |
| `custody --simple [--yes] [--json]` | Revoke the Vault's operators, withdraw the token, and save. Previews until `--yes`. | Opens your wallet |
Expand All @@ -231,13 +231,13 @@ Run any of these with `npx ethagent`. Commands marked interactive need a termina
1. It pulls in any edits from your tools.
2. If nothing changed since the last snapshot, it stops there.
3. Otherwise it prints a link and opens your wallet in the browser. You sign one message and approve one transaction.
4. ethagent encrypts everything, pins it to IPFS, points your token at it, and checks that the pointer landed.
4. ethagent encrypts everything, pins it to IPFS, points your token at it, and checks that the pointer landed (`verification` in the JSON: `verified`, `mismatch`, or `unknown`).

| Flag | Effect |
| --- | --- |
| `--json` | Print the result as JSON. |
| `--no-open` | Print the wallet link without opening the browser. |
| `--operator` | Save with no popup, signed by an approved operator key (Advanced custody), read from `ETHAGENT_OPERATOR_KEY`. |
| `--operator` | Save with no popup, signed by an approved operator key (Advanced custody), read from `ETHAGENT_OPERATOR_KEY`. It skips when nothing changed and checks the pointer the same way. |

| Exit code | Meaning |
| --- | --- |
Expand All @@ -253,8 +253,8 @@ Run any of these with `npx ethagent`. Commands marked interactive need a termina

- **Previews.** ENS changes preview by default. They list every transaction, simulate the ones that can run now from the signer, and send nothing. Rerun with `--yes` to send.
- **Signers.** ENS transactions are signed in your browser wallet, in one tab for the whole change. With `--operator`, the operator key signs them with no popup instead. Run it as `keychain exec ethagent -- ethagent ens <args> --operator`.
- **What the operator key may do.** It only writes text records and creates subnames under a parent it controls. It never sets `addr` on an existing name and never changes ownership.
- **Deleting.** `ens --delete` clears the records, removes the subname from its parent, then publishes the agent unlinked. Only the wallet that manages the parent can sign it, never the operator key. Whoever manages the parent can create the name again, unless its fuses forbid that. A run stopped after the removal finishes when run again.
- **What the operator key may do.** It only writes text records, and creates or deletes subnames under a parent it controls. It never sets `addr` on an existing name and never changes ownership.
- **Deleting.** `ens --delete` clears the records, removes the subname from its parent, then publishes the agent unlinked. Only the wallet that manages the parent can sign it; that is the operator key when the key manages the parent, which could already remove the name at the ENS contracts. Whoever manages the parent can create the name again, unless its fuses forbid that. A run stopped after the removal finishes when run again.
- **Publishing.** Changing, unlinking, or deleting the name always ends with one owner-signed save. A stolen operator key therefore can't point your agent at a name it registered. Local state takes the new name only after that save lands.
- **Control check.** Before anything is sent, the command refuses unless the signer controls the name: as its owner, its NameWrapper owner, or a delegate approved on its resolver.

Expand Down
6 changes: 3 additions & 3 deletions commands/ethagent.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,13 @@ Both commands take `--json` (same `schema: 1` envelope) and `--help`.
- `custody` (read-only, safe anytime) shows the custody mode, the Vault address and its build, whether it holds the agent token, the Vault-level owner, and the approved operators. `custody --verify` also simulates with `eth_call`, sending nothing: the owner withdrawing, the owner changing an operator, the operator rotating the agent URI, and the operator and a stranger being refused. It exits 4 when a result differs from what the Vault should do.
- `custody --advanced`, `custody --simple`, `custody --add-operator [<address>]`, `--remove-operator <address>`, and `--activate-operator <address>` change custody. They are planned from chain state, so running one again after it stopped part way (exit 4, or 3 if a prompt was cancelled) finishes it. `custody --add-operator --operator` lets the injected operator key sign its own proof.
- `ens` (read-only, safe anytime) shows the linked name, its live records, the two-way check, the resolver, who controls the name, and whether the operator key could sign for it.
- `ens <name>`, `ens --unlink`, `ens --delete` (also removes the subname from its parent; never the operator key), and `ens --set <key>=<value> --clear <key>` change ENS. Without `--yes` they only preview: they list every transaction, simulate the ones that can run now, and send nothing (JSON `applied: false`). You may run previews yourself. Anything with `--yes` sends transactions and costs gas, so it stays the user's to run; show them the preview and the command.
- ENS transactions are signed in the browser wallet by default, or by the operator key with `--operator` (run through `keychain exec ethagent -- ethagent ens <args> --operator`; exit 3 without a key, 2 for an invalid one). The operator key only writes text records and creates subnames under a parent it controls. Publishing a name change (`ens <name>`, `ens --unlink`) always ends with one owner-signed save in the browser.
- `ens <name>`, `ens --unlink`, `ens --delete` (also removes the subname from its parent; the operator key may sign it only when it manages the parent), and `ens --set <key>=<value> --clear <key>` change ENS. Without `--yes` they only preview: they list every transaction, simulate the ones that can run now, and send nothing (JSON `applied: false`). You may run previews yourself. Anything with `--yes` sends transactions and costs gas, so it stays the user's to run; show them the preview and the command.
- ENS transactions are signed in the browser wallet by default, or by the operator key with `--operator` (run through `keychain exec ethagent -- ethagent ens <args> --operator`; exit 3 without a key, 2 for an invalid one). The operator key only writes text records, and creates or deletes subnames under a parent it controls. Publishing a name change (`ens <name>`, `ens --unlink`) always ends with one owner-signed save in the browser.

Setting up and moving an agent (all take `--json` and `--help`; anything that signs or sends previews until `--yes`, and the `--yes` run is the user's):

- `profile` (read-only) shows the public name, description, and image; `profile --name <text> --description <text> --image <path|url|none>` changes them in one save. With `--operator` the operator key signs, when advanced custody with a linked ENS name allows it.
- `restore --owner <address|name>` (read-only) lists the agents a wallet holds. `restore <token-id> --network <network>` or `restore <name>` rebuilds an agent on this machine; `restore` with no target pulls the newest onchain snapshot into the vault. `restore --operator --yes` decrypts with the operator key and opens no browser, so you may run it yourself when the user asks you to restore or refresh the agent (through `keychain exec ethagent -- ...`). It checkpoints the vault first; `rollback --undo --yes` reverses it.
- `restore --owner <address|name>` (read-only) lists the agents a wallet holds, including ones in its Vault. If it exits 1 because the RPC couldn't scan the history, pass the `<token-id>` directly or point `ETHAGENT_RPC_URL` at a fuller RPC. `restore <token-id> --network <network>` or `restore <name>` rebuilds an agent on this machine; `restore` with no target pulls the newest onchain snapshot into the vault. `restore --operator --yes` decrypts with the operator key and opens no browser, so you may run it yourself when the user asks you to restore or refresh the agent (through `keychain exec ethagent -- ...`). It checkpoints the vault first; `rollback --undo --yes` reverses it.
- `create --name <text> --network <network>` mints a new agent; `--advanced` continues into a Vault. It costs gas: preview it, then leave `--yes` to the user.
- `transfer <address|name>` re-encrypts the agent for a new owner; both wallets sign in the user's browser, and the user sends the token afterwards.
- `storage` (read-only) says whether IPFS storage is set up; `storage --set` reads a Pinata JWT from stdin. Never put the JWT in a command line.
Expand Down
40 changes: 36 additions & 4 deletions src/cli/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,40 @@ export function isPidAlive(pid: number): boolean {
}
}

export function daemonStatus(): { running: boolean; pid: number | null } {
// The daemon touches its pid file every DAEMON_HEARTBEAT_MS. A pid file left quiet for
// longer than DAEMON_STALE_MS belongs to a daemon that is gone, even when the operating
// system has since handed its pid to some other process.
export const DAEMON_HEARTBEAT_MS = 30_000
export const DAEMON_STALE_MS = 120_000

function heartbeatFresh(): boolean {
try {
return Date.now() - fs.statSync(daemonPidPath()).mtimeMs < DAEMON_STALE_MS
} catch {
return false
}
}

// The pid of a daemon that is alive and still beating, or null.
function liveDaemonPid(): number | null {
const pid = readDaemonPid()
return pid && isPidAlive(pid) ? { running: true, pid } : { running: false, pid: null }
return pid && isPidAlive(pid) && heartbeatFresh() ? pid : null
}

export function touchDaemonPid(): void {
if (readDaemonPid() !== process.pid) return
try {
const now = new Date()
fs.utimesSync(daemonPidPath(), now, now)
} catch {}
}

export function daemonStatus(): { running: boolean; pid: number | null } {
const pid = liveDaemonPid()
if (pid) return { running: true, pid }
// A leftover file would otherwise read as running the moment its pid is reused.
if (readDaemonPid() !== null) clearDaemonPid()
return { running: false, pid: null }
}

export function writeDaemonPid(): void {
Expand Down Expand Up @@ -129,9 +160,10 @@ export function ensureDaemon(): boolean {
}

export function stopDaemon(): boolean {
const pid = readDaemonPid()
// Only a pid that is still beating is ours to signal; a stale one may be anything now.
const pid = liveDaemonPid()
let stopped = false
if (pid && isPidAlive(pid)) {
if (pid) {
try {
process.kill(pid, 'SIGTERM')
stopped = true
Expand Down
35 changes: 25 additions & 10 deletions src/cli/onchain/ens.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getAddress, type Address, type PublicClient } from 'viem'
import type { EthagentConfig, EthagentIdentity } from '../../storage/config.js'
import { saveConfig } from '../../storage/config.js'
import { createMainnetClient, validateAgentEnsLink } from '../../identity/ens/ensLookup.js'
import { createMainnetClient, normalizeEthDomain, splitSubdomainName, validateAgentEnsLink } from '../../identity/ens/ensLookup.js'
import { readAddressRecord, readTextRecords } from '../../identity/ens/ensAutomation/read.js'
import { resolveRegistryForIdentity } from '../../identity/registry/registryConfig.js'
import { DEFAULT_ETHEREUM_RPC_URL, type Erc8004RegistryConfig } from '../../identity/registry/erc8004.js'
Expand Down Expand Up @@ -59,17 +59,18 @@ const HELP = [
' ethagent ens --unlink clear the agent records on the linked name, then publish',
' the unlinked state in one owner-signed save.',
' ethagent ens --delete unlink as above, then remove the subname from its parent.',
' Signed by the wallet that manages the parent, never the',
' operator key. The parent can recreate it, unless its fuses',
' forbid that.',
' Signed by the wallet that manages the parent: the browser',
' wallet, or with --operator the operator key when it is the',
' parent\'s manager. The parent can recreate it, unless its',
' fuses forbid that.',
' ethagent ens --set <key>=<value> --clear <key>',
' write every record change on the linked name in one',
' resolver multicall. No save is needed.',
'',
'Writes preview first and send nothing without --yes. ENS transactions are signed by the',
'browser wallet, or with --operator by the operator key (run through `keychain exec ethagent',
'-- ethagent ens <args> --operator`, which injects ' + OPERATOR_KEY_ENV + '). The operator key only',
'writes text records and creates subnames under a parent it controls. Publishing a name',
'writes text records, and creates or deletes subnames under a parent it controls. Publishing a name',
'change always needs the owner wallet.',
'',
].join('\n')
Expand Down Expand Up @@ -175,6 +176,13 @@ async function readView(identity: EthagentIdentity, registry: Erc8004RegistryCon
operator = { address: getAddress(key.address), canSign: Boolean(how), via: how }
} else if (key && !key.ok && key.reason === 'invalid') {
operator = { error: INVALID_OPERATOR_KEY_MESSAGE }
} else {
// No key in this shell: still say whether the agent's active operator could sign.
const active = readIdentityStateString(state, 'activeOperatorAddress')
if (active) {
const how = await signerControlOf(client, control, getAddress(active))
operator = { address: getAddress(active), canSign: Boolean(how), via: how, keyAvailable: false }
}
}
return {
name: control.name,
Expand Down Expand Up @@ -203,9 +211,9 @@ function printView(view: Record<string, unknown>): string {
for (const [key, value] of entries) lines.push(` ${key} = ${value}`)
lines.push(` resolver: ${String(view.resolver ?? 'none')}`)
lines.push(` controlled by: ${control.owner ?? 'nobody'}${control.wrapped ? ' (wrapped)' : ''}`)
const operator = view.operator as { address?: string; canSign?: boolean; via?: string; error?: string } | null
const operator = view.operator as { address?: string; canSign?: boolean; via?: string; error?: string; keyAvailable?: boolean } | null
if (operator?.error) lines.push(` operator key: ${operator.error}`)
else if (operator) lines.push(` operator key ${operator.address}: ${operator.canSign ? `can sign (${operator.via})` : 'cannot sign for this name'}`)
else if (operator) lines.push(` operator key ${operator.address}: ${operator.canSign ? `can sign (${operator.via})` : 'cannot sign for this name'}${operator.keyAvailable === false ? ' · key not in this shell' : ''}`)
else lines.push(' operator key: not available in this shell')
return `${lines.join('\n')}\n`
}
Expand Down Expand Up @@ -240,9 +248,6 @@ export async function runEnsCommand(args: string[], deps: HistoryDeps, seams: En

if (!identity.agentId) throw new HistoryError(1, 'This identity has no agent token ID yet.', 'Mint one with `ethagent create`, or bring one back with `ethagent restore <token-id>`.')
const owner = getAddress(humanOwnerAddress(identity))
if (mode.kind === 'delete' && values.operator) {
throw new HistoryError(2, '--delete is signed by the wallet that manages the parent name, never the operator key.', 'Drop --operator; `ethagent ens --unlink --operator` clears the records instead.')
}
const signer = chooseSigner(deps, Boolean(values.operator), owner)
const client = seams.readClient()
const currentName = readIdentityStateString(identity.state as Record<string, unknown> | undefined, 'ensName')
Expand Down Expand Up @@ -280,13 +285,23 @@ export async function runEnsCommand(args: string[], deps: HistoryDeps, seams: En
summary = { action: 'unlink', name: plan.name, records: plan.current }
} else if (mode.kind === 'delete') {
if (!currentName) throw new HistoryError(1, 'No ENS name is linked, so there is nothing to delete.')
// Only the parent's manager can remove a subname. When that is the agent's operator
// key, it may sign: it could already remove the name at the ENS contracts directly.
const plan = await planEnsDelete({
client,
name: currentName,
signer: signer.address,
signerRole: signer.role,
identityRegistryAddress: registry.identityRegistryAddress,
agentId: identity.agentId,
}).catch(async (err: unknown) => {
if (!(err instanceof EnsPlanRefusal) || signer.kind === 'operator') throw err
const operator = readIdentityStateString(identity.state as Record<string, unknown> | undefined, 'activeOperatorAddress')
const parent = splitSubdomainName(normalizeEthDomain(currentName))?.parent
if (!operator || !parent) throw err
const control = await readNameControl(client, parent).catch(() => null)
if (!control?.owner || control.owner.toLowerCase() !== operator.toLowerCase()) throw err
throw new EnsPlanRefusal(err.message, `The operator key ${getAddress(operator)} manages ${parent}: run it through \`keychain exec ethagent -- ethagent ens --delete --operator\`.`)
})
transactions = plan.transactions
publishName = ''
Expand Down
Loading
Loading